@cosyte/mllp 0.1.13 → 0.1.15

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.d.ts CHANGED
@@ -166,6 +166,11 @@ declare function encodeFrame(payload: Buffer, opts?: EncoderOptions): Buffer;
166
166
  * unless the matching tolerance option is explicitly enabled (Postel's Law, liberal receiver
167
167
  * means explicit tolerance, not silent acceptance).
168
168
  *
169
+ * A frame whose end cannot be told is refused whole whatever the tolerances: a `VT` inside it
170
+ * throws `MLLP_PAYLOAD_CONTAINS_VT`, and an `FS` followed by anything but `CR`, `LF` or the next
171
+ * frame's `VT` throws `MLLP_PAYLOAD_CONTAINS_FS`. Nothing of that frame is delivered, the reader
172
+ * is left scanning for the next `VT`, and the error names only the framing byte and its offset.
173
+ *
169
174
  * @example
170
175
  * ```typescript
171
176
  * import { FrameReader } from '@cosyte/mllp';
@@ -220,7 +225,11 @@ interface FrameReaderOptions {
220
225
  * Default: 16 MiB (DoS prevention).
221
226
  */
222
227
  maxFrameSizeBytes?: number;
223
- /** Tolerate FS without trailing CR; emits `MLLP_FS_WITHOUT_CR`. */
228
+ /**
229
+ * Tolerate FS without trailing CR when the next frame's VT follows it; emits
230
+ * `MLLP_FS_WITHOUT_CR`. Any other byte after the FS means the FS sat inside the frame, and the
231
+ * frame is refused whole with `MLLP_PAYLOAD_CONTAINS_FS`.
232
+ */
224
233
  allowFsOnly?: boolean;
225
234
  /** Tolerate FS+LF instead of FS+CR; emits `MLLP_LF_AFTER_FS`. */
226
235
  allowLfAfterFs?: boolean;
@@ -237,7 +246,7 @@ interface FrameReaderOptions {
237
246
  * - `MLLP_LF_AFTER_FS`
238
247
  * - `MLLP_LEADING_WHITESPACE` (leading whitespace escalates as `MLLP_MISSING_LEADING_VT`)
239
248
  *
240
- * `MLLP_EMPTY_PAYLOAD` and `MLLP_TRAILING_BYTES` remain warnings even in strict mode.
249
+ * `MLLP_EMPTY_PAYLOAD` remains a warning even in strict mode.
241
250
  *
242
251
  * @example
243
252
  * ```typescript
@@ -360,6 +369,12 @@ declare class FrameReader {
360
369
  * bytes forgotten first.
361
370
  */
362
371
  private _deliver;
372
+ /**
373
+ * Refuse the current frame whole: forget its bytes and its warnings, go back to scanning for a
374
+ * VT, and throw. The error names the framing byte (`delimiter`) and its offset, never a byte of
375
+ * the frame's content, and nothing of the frame is delivered.
376
+ */
377
+ private _refuse;
363
378
  /** Emit a warning via the `onWarning` callback, swallowing any handler exceptions. */
364
379
  private _emitWarning;
365
380
  }
@@ -1582,6 +1597,20 @@ declare class Connection extends EventEmitter {
1582
1597
  * drain it waits on.
1583
1598
  */
1584
1599
  private readonly _leftDraining;
1600
+ /**
1601
+ * Work answering a frame this connection delivered, still running, with what it owes the peer.
1602
+ * See {@link Connection.holdOpenFor}.
1603
+ */
1604
+ private readonly _answering;
1605
+ /**
1606
+ * Set once a fatal framing error has been met, or {@link Connection.stopReading} called: from
1607
+ * then on no byte the peer sends is read.
1608
+ */
1609
+ private _refusing;
1610
+ /** When the `close()` drain began (`Date.now()`), or `undefined` when no `close()` is draining. */
1611
+ private _closeBegan;
1612
+ /** Ends the wait after a fatal framing error: destroys the transport once the bound passes. */
1613
+ private _refusalBound;
1585
1614
  /**
1586
1615
  * beforeClose hook, no-op default that resolves immediately.
1587
1616
  *
@@ -1653,9 +1682,13 @@ declare class Connection extends EventEmitter {
1653
1682
  *
1654
1683
  * - If `CONNECTING` or `RECONNECTING`: cancels the pending attempt, transitions
1655
1684
  * directly to `CLOSED`, and calls `transport.destroy()`.
1656
- * - If `CONNECTED`: transitions to `DRAINING`, calls `beforeClose(drainTimeoutMs)`,
1657
- * then `DRAINING → DISCONNECTED` once the hook resolves, or `DRAINING → CLOSED`
1658
- * if the drain timeout elapses first.
1685
+ * - If `CONNECTED`: transitions to `DRAINING`, calls `beforeClose(drainTimeoutMs)` and
1686
+ * waits for it and for every piece of work passed to {@link Connection.holdOpenFor} that is
1687
+ * still running, then `DRAINING → DISCONNECTED` and ends the transport gracefully, so what
1688
+ * that work wrote reaches the peer. If the drain timeout elapses first: `DRAINING → CLOSED`
1689
+ * and the transport is destroyed. Work still running when the drain ends that way (the
1690
+ * timeout or a `destroy()`) is abandoned, and an `MllpConnectionError` with `phase: 'close'`
1691
+ * on `'error'` says how many were left and that what they would write is not sent.
1659
1692
  * - If `DRAINING`: waits for the existing drain to complete (idempotent).
1660
1693
  *
1661
1694
  * Every pending `close()` resolves as soon as the connection leaves `DRAINING`, by whatever
@@ -1674,7 +1707,7 @@ declare class Connection extends EventEmitter {
1674
1707
  drainTimeoutMs?: number;
1675
1708
  }): Promise<void>;
1676
1709
  /**
1677
- * Race `beforeClose()` against the drain timeout.
1710
+ * Race `beforeClose()` and the held work against the drain timeout.
1678
1711
  *
1679
1712
  * On normal completion: `DRAINING → DISCONNECTED` + `transport.close()`.
1680
1713
  * On timeout: `DRAINING → CLOSED` + `transport.destroy()`.
@@ -1695,6 +1728,63 @@ declare class Connection extends EventEmitter {
1695
1728
  * ```
1696
1729
  */
1697
1730
  destroy(reason?: Error): void;
1731
+ /**
1732
+ * Hold the connection open, on `close()` or a fatal framing error, until `work` settles.
1733
+ *
1734
+ * Pass the work that answers a frame this connection delivered: the handler and the write of
1735
+ * its acknowledgement. A `close()` waits for every piece of work passed here to settle before
1736
+ * it ends the transport, so an acknowledgement written by that work still goes out. When a
1737
+ * later frame on the same connection has a fatal framing error, the connection reads nothing
1738
+ * more, waits the same way, and only then closes, so the acknowledgement of a frame delivered
1739
+ * before the refused one still goes out. Either wait is bounded by `drainTimeoutMs` (default 30
1740
+ * seconds): work that has not settled by then is abandoned and the connection is destroyed.
1741
+ * `MllpServer` passes every message's work here itself; a caller driving a bare `Connection`
1742
+ * may do the same.
1743
+ *
1744
+ * `options.kind` says what the work owes the peer, which decides whether `close()` waits for it
1745
+ * and how an abandoned piece is reported:
1746
+ *
1747
+ * - `'ack'` (the default): the work writes the frame's acknowledgement as its last step, so
1748
+ * while it runs the acknowledgement has not been sent. `close()` waits for it; abandoned, it is
1749
+ * counted as a message delivered whose acknowledgement was not sent.
1750
+ * - `'manual'`: the work writes the acknowledgement itself at a point of its own choosing (a
1751
+ * manual-mode handler). `close()` waits for it until it settles; abandoned, it is counted as a
1752
+ * handler whose acknowledgement may not have been sent.
1753
+ * - `'observer'`: the work writes no acknowledgement (an `onMessage` observer in custom-ACK
1754
+ * mode). `close()` does not wait for it; still running when a `close()` is abandoned, it is
1755
+ * named separately as an observer still running. A fatal framing error still waits for it.
1756
+ *
1757
+ * A rejection of `work` is not reported here; it only ends the wait for it.
1758
+ *
1759
+ * @param work - The work answering one delivered frame.
1760
+ * @param options - `kind`: what the work owes the peer (default `'ack'`).
1761
+ *
1762
+ * @example
1763
+ * ```typescript
1764
+ * conn.on('message', ({ payload }) => {
1765
+ * conn.holdOpenFor(commit(payload).then(() => conn.send(encodeFrame(ackFor(payload)))));
1766
+ * });
1767
+ * ```
1768
+ */
1769
+ holdOpenFor(work: PromiseLike<unknown>, options?: {
1770
+ readonly kind?: "ack" | "manual" | "observer";
1771
+ }): void;
1772
+ /**
1773
+ * Read nothing more from the peer: every byte that arrives from now on is dropped unread, and
1774
+ * no further frame is delivered. It cannot be undone.
1775
+ *
1776
+ * `MllpServer.close()` calls this on each connection before closing it, so no new message
1777
+ * reaches a handler while the ones already running finish and their acknowledgements are
1778
+ * written. A client must not call it before a `close()` that waits for acknowledgements, since
1779
+ * it would then never read them.
1780
+ *
1781
+ * @example
1782
+ * ```typescript
1783
+ * conn.stopReading();
1784
+ * await conn.close();
1785
+ * ```
1786
+ */
1787
+ stopReading(): void;
1698
1788
  /**
1699
1789
  * Return a JSON-serializable observability snapshot.
1700
1790
  *
@@ -1711,6 +1801,25 @@ declare class Connection extends EventEmitter {
1711
1801
  * ```
1712
1802
  */
1713
1803
  getStats(): ConnectionStats;
1804
+ /**
1805
+ * Settle once no work passed to {@link Connection.holdOpenFor} that owes an acknowledgement is
1806
+ * running; an `'observer'` is not waited for. Work registered while waiting (a frame decoded
1807
+ * from bytes already read) is waited for too.
1808
+ */
1809
+ private _heldWorkSettled;
1810
+ /**
1811
+ * Report, on `'error'`, the held work a `close()` drain abandons because the drain ended before
1812
+ * that work settled. It counts per delivered message: work that would have written an
1813
+ * acknowledgement (not sent), a manual-mode handler (its acknowledgement may not have been
1814
+ * sent), and, separately, observers that owe none. Nothing is reported when no `close()` is
1815
+ * draining or nothing is still running.
1816
+ *
1817
+ * @param how - How the drain ended, as it reads after "close() ended ".
1818
+ * @param reason - What ended it, the message of the report's `cause`.
1819
+ */
1820
+ private _reportAbandonedWork;
1821
+ /** Report the work a `close()` drain abandons at the bound or on a `destroy()`. */
1822
+ private _reportAbandonedAfter;
1714
1823
  private _transition;
1715
1824
  private _onTransportClose;
1716
1825
  /**
@@ -1730,7 +1839,7 @@ declare class Connection extends EventEmitter {
1730
1839
  */
1731
1840
  private _emitErrorIfListened;
1732
1841
  /**
1733
- * Handle a fatal framing error thrown out of `FrameReader.push` (FRAME-FATAL).
1842
+ * Handle a fatal framing error thrown out of `FrameReader.push`.
1734
1843
  *
1735
1844
  * Contract: surface it as a connection `'error'` (frozen payload, `phase: 'receive'`,
1736
1845
  * `connectionCause: 'framing-fatal'`, the original `MllpFramingError` preserved as `cause` so
@@ -1748,8 +1857,21 @@ declare class Connection extends EventEmitter {
1748
1857
  * forever, and the backoff would become an unbounded reconnect storm against an interface
1749
1858
  * engine that is already unwell. A compatibility failure is not a network blip.
1750
1859
  *
1751
- * If a peer's quirk is *expected* (trailing junk, keepalive bytes, a missing leading VT), the
1752
- * decoder's tolerance opt-ins are the supported answer, they turn the throw into a warning.
1860
+ * Frames delivered before the refused one are still answered. Their handlers may still be
1861
+ * running (an acknowledgement is written after its handler settles, so even a synchronous
1862
+ * handler's is not out yet), and closing at once dropped every one of those acknowledgements:
1863
+ * the sender resent a message already committed, and it was processed twice. So when work
1864
+ * passed to {@link Connection.holdOpenFor} is still running, the connection reads nothing
1865
+ * more, moves to `DRAINING`, waits for that work to settle, then closes gracefully (`CLOSED`,
1866
+ * the transport ended so the acknowledgements written are flushed). The wait is bounded by
1867
+ * `drainTimeoutMs`: past it the connection is destroyed, settled or not, so a handler that never
1868
+ * settles cannot hold the socket open. With nothing running it is destroyed at once.
1869
+ *
1870
+ * If a peer's quirk is *expected*, the decoder's tolerance opt-ins are the supported answer:
1871
+ * `allowLeadingWhitespace` (padding or keepalive bytes before a frame), `allowMissingLeadingVt`,
1872
+ * `allowFsOnly` (a bare FS that the next frame's VT follows) and `allowLfAfterFs` turn their
1873
+ * throw into a warning. No opt-in accepts other bytes between frames, or a stray FS or VT inside
1874
+ * one: those are always refused.
1753
1875
  */
1754
1876
  private _onFatalFramingError;
1755
1877
  /**
@@ -1925,7 +2047,7 @@ declare class MllpConnectionError extends Error {
1925
2047
  * const code: AckModeCode = 'MLLP_ACK_TWO_PHASE_UNAVAILABLE';
1926
2048
  * ```
1927
2049
  */
1928
- type AckModeCode = "MLLP_ACK_ACCEPT_TYPE_UNRECOGNISED" | "MLLP_ACK_APPLICATION_TYPE_UNRECOGNISED" | "MLLP_ACK_TWO_PHASE_UNAVAILABLE" | "MLLP_ACK_COMMIT_ALREADY_REPORTED" | "MLLP_ACK_MSA1_ABSENT" | "MLLP_ACK_MSA1_UNCLASSIFIABLE" | "MLLP_ACK_SEND_ALREADY_DISPOSED";
2050
+ type AckModeCode = "MLLP_ACK_ACCEPT_TYPE_UNRECOGNISED" | "MLLP_ACK_APPLICATION_TYPE_UNRECOGNISED" | "MLLP_ACK_TWO_PHASE_UNAVAILABLE" | "MLLP_ACK_COMMIT_ALREADY_REPORTED" | "MLLP_ACK_MSA1_ABSENT" | "MLLP_ACK_MSA1_UNCLASSIFIABLE" | "MLLP_ACK_SEND_ALREADY_DISPOSED" | "MLLP_ACK_FIFO_MSA1_UNREADABLE";
1929
2051
  /**
1930
2052
  * Look up the frozen diagnostic text for an acknowledgement-mode code.
1931
2053
  *
@@ -1994,10 +2116,10 @@ interface MessageMeta {
1994
2116
  * (no readable `MSH`, an empty MSH-10, or a batch/concatenated-message shape). A positive
1995
2117
  * `AA` here names a control ID the sender cannot match → timeout → resend → **duplicate
1996
2118
  * clinical message**. See {@link rawAckUncorrelatable}.
1997
- * - `'discarded-bytes'`, the decoder flagged `MLLP_TRAILING_BYTES` for this frame: a
1998
- * mid-payload `VT` made it **discard accumulated bytes** and deliver only the fragment
1999
- * after it. The clinical message was destroyed in transit; a positive `AA` would tell the
2000
- * sender a message we never received was delivered.
2119
+ * - `'discarded-bytes'`, no longer sent. It named a frame the decoder delivered as the fragment
2120
+ * after a mid-payload `VT`. The decoder now refuses such a frame whole
2121
+ * (`MLLP_PAYLOAD_CONTAINS_VT`) and closes the connection, so no fragment reaches the
2122
+ * acknowledgement path. The value stays in the type so code that names it still compiles.
2001
2123
  */
2002
2124
  type NackReason = "handler-rejected" | "uncorrelatable-inbound" | "discarded-bytes";
2003
2125
  /**
@@ -2015,7 +2137,7 @@ type NackReason = "handler-rejected" | "uncorrelatable-inbound" | "discarded-byt
2015
2137
  * @example
2016
2138
  * ```typescript
2017
2139
  * server.on('nack', ({ connectionId, ackCode, reason }) => {
2018
- * metrics.increment('mllp.nack', { code: ackCode, reason }); // e.g. reason='discarded-bytes'
2140
+ * metrics.increment('mllp.nack', { code: ackCode, reason }); // e.g. reason='handler-rejected'
2019
2141
  * });
2020
2142
  * ```
2021
2143
  */
@@ -2253,8 +2375,16 @@ interface ServerOptions {
2253
2375
  */
2254
2376
  deadPeerTimeoutMs?: number;
2255
2377
  /**
2256
- * Graceful drain timeout passed to `conn.close()` during `server.close()`.
2257
- * Default: 30 000 ms.
2378
+ * Graceful drain timeout passed to `conn.close()` during `server.close()`: the longest
2379
+ * `close()` waits for the handlers still running and their acknowledgements. A handler still
2380
+ * running then is abandoned, and an `MllpConnectionError` with `phase: 'close'` on `'error'`
2381
+ * says how many messages were delivered without their acknowledgement being sent (in manual
2382
+ * mode, how many handlers may not have sent theirs). In custom-ACK mode the `onMessage`
2383
+ * observer is not waited for, since it writes no acknowledgement. Default: 30 000 ms.
2384
+ *
2385
+ * It also bounds the wait after a fatal framing error: frames delivered before the refused one
2386
+ * are still answered, and a connection waits at most this long for their handlers before it is
2387
+ * destroyed.
2258
2388
  */
2259
2389
  drainTimeoutMs?: number;
2260
2390
  /**
@@ -2365,7 +2495,7 @@ interface StarterServerOptions extends ServerOptions {
2365
2495
  * The `'nack'` event ({@link NackEvent}) fires whenever the server returns a negative ACK
2366
2496
  * instead of `AA` on the auto-ACK path, a commit-gated `autoAck: 'AA'` handler failing, or
2367
2497
  * a positive auto-ACK **downgraded** because the inbound could not be correlated (an
2368
- * unreadable/uncorrelatable message, or one whose bytes the decoder discarded). The
2498
+ * unreadable or uncorrelatable message). The
2369
2499
  * {@link NackReason} distinguishes the causes.
2370
2500
  *
2371
2501
  * **`'error'` contract:** underlying `net.Server`/`tls.Server` errors are forwarded to the
@@ -2413,6 +2543,11 @@ declare class MllpServer extends EventEmitter {
2413
2543
  /** `true` when `ServerOptions.tls` is set, `_netServer` is actually a `tls.Server`. */
2414
2544
  private readonly _isTls;
2415
2545
  private _listening;
2546
+ /**
2547
+ * `true` from a `close()` until the next `listen()`: a socket accepted meanwhile (a TLS
2548
+ * handshake that began before the close and finished during it) is closed at once, never served.
2549
+ */
2550
+ private _closing;
2416
2551
  /** Single-flight guard: `true` while a `listen()` call is settling. */
2417
2552
  private _listenInFlight;
2418
2553
  /**
@@ -2533,10 +2668,23 @@ declare class MllpServer extends EventEmitter {
2533
2668
  * Stop accepting new connections and gracefully close all active connections.
2534
2669
  *
2535
2670
  * Sequence:
2536
- * 1. `net.Server.close()`, stops accepting new connections immediately
2671
+ * 1. `net.Server.close()`, stops accepting new connections immediately. A socket the listener
2672
+ * still hands over (a TLS handshake that began before `close()` and ends during it) is
2673
+ * destroyed at once, before any byte of it is read.
2537
2674
  * 2. If `_connections` is empty: resolves immediately (no drain needed)
2538
- * 3. Calls `_drainAll(drainTimeoutMs)`, Promise.all + side-effect setTimeout
2539
- * that force-destroys stragglers after the drain window
2675
+ * 3. Every connection stops reading: bytes the peer sends from now on are dropped unread, so no
2676
+ * new message reaches a handler.
2677
+ * 4. Every connection waits for its handlers still running and the acknowledgements they write
2678
+ * (`AA`, a negative ACK for a handler that rejects, a custom builder's bytes), then ends its
2679
+ * socket gracefully so those acknowledgements reach the sender. In manual mode the wait lasts
2680
+ * until the handler's promise settles: a `conn.send()` made after that is not waited for. In
2681
+ * custom-ACK mode the `onMessage` observer is not waited for: it writes no acknowledgement.
2682
+ * 5. The wait is bounded by `drainTimeoutMs`. A connection still waiting then is destroyed, and
2683
+ * the server's `'error'` event carries an `MllpConnectionError` with `phase: 'close'` saying
2684
+ * how many messages were delivered without their acknowledgement being sent, how many
2685
+ * manual-mode handlers may not have sent theirs, and how many observers were still running.
2686
+ * The same report is made when the sender closes the connection, or half-closes it (the
2687
+ * server's sockets are not half-open, so our side ends with it), before that work settles.
2540
2688
  *
2541
2689
  * Calling `close()` while a `listen()` is still in flight proactively
2542
2690
  * settles that `listen()` with a typed `MllpConnectionError` rejection
@@ -2648,22 +2796,11 @@ declare class MllpServer extends EventEmitter {
2648
2796
  * cannot carry a correlatable positive ACK, so `AA` never names a control ID the sender
2649
2797
  * cannot match (→ timeout → resend → **duplicate clinical message**).
2650
2798
  *
2651
- * Two independent disqualifiers, one from the bytes and one from the frame:
2652
- *
2653
- * - **`rawAckUncorrelatable(payload)`**, no readable `MSH`, an empty MSH-10, or a
2654
- * batch/concatenated-message shape. This is the SAME predicate `buildRawAck` enforces
2655
- * on the wire; it is re-checked here so the downgrade is **observable** (a `'nack'`
2656
- * event) rather than a silent code change inside the builder.
2657
- * - **`MLLP_TRAILING_BYTES`** in the frame's warnings, a mid-payload `VT` made the
2658
- * decoder discard accumulated bytes and deliver only the fragment after it. The
2659
- * clinical message was destroyed in transit, so even a fragment that happens to carry
2660
- * a readable MSH must not be positively acknowledged. This condition is invisible to
2661
- * `buildRawAck` (it sees only the fragment), which is why it lives here. The code is
2662
- * **reserved** for that discard (see the decoder's `_readPayload`) and is emitted while
2663
- * accumulating the delivered frame, so it is frame-scoped: it names *this* payload's own
2664
- * discard, never a neighbouring frame's trailing junk.
2665
- *
2666
- * `'discarded-bytes'` takes precedence in the reason when both hold, it is the root cause.
2799
+ * The disqualifier is **`rawAckUncorrelatable(payload)`**: no readable `MSH`, an empty
2800
+ * MSH-10, or a batch/concatenated-message shape. This is the SAME predicate `buildRawAck`
2801
+ * enforces on the wire; it is re-checked here so the downgrade is **observable** (a `'nack'`
2802
+ * event) rather than a silent code change inside the builder. A frame with a `VT` or a stray
2803
+ * `FS` inside it never gets here: the decoder refuses it whole and the connection closes.
2667
2804
  *
2668
2805
  * `selectCode` puts the resolved disposition in the half of HL7 Table 0008 the inbound
2669
2806
  * asked for; it is the identity for a message that asked for nothing.
@@ -2721,10 +2858,12 @@ declare class MllpServer extends EventEmitter {
2721
2858
  */
2722
2859
  private _sendCustomAck;
2723
2860
  /**
2724
- * Frame an ACK payload and write it to the connection. `Connection.send()` returns
2725
- * `false` under backpressure (socket write buffer full); that drops the ACK and emits
2726
- * a `MllpConnectionError({ phase: 'send' })` on the connection, the peer will
2727
- * time out waiting and may retry. The server never crashes.
2861
+ * Frame an ACK payload and write it to the connection. When the connection has already
2862
+ * closed (a handler that settled after `server.close()` gave up on it, or after the peer
2863
+ * left), the ACK is not sent and a `MllpConnectionError({ phase: 'send' })` saying so is
2864
+ * emitted on the connection. `Connection.send()` returns `false` under backpressure (socket
2865
+ * write buffer full); that is reported the same way, as backpressure. Either way the peer
2866
+ * will time out waiting and may retry. The server never crashes.
2728
2867
  */
2729
2868
  private _dispatchAck;
2730
2869
  }
@@ -2888,9 +3027,10 @@ declare function resolveNackCode(err: unknown): NegativeAckCode;
2888
3027
  * destroyed message was delivered). Three payload-shaped reasons make a positive ACK
2889
3028
  * uncorrelatable, all peer-reachable off the wire:
2890
3029
  *
2891
- * 1. **No readable `MSH`.** `readMshSegment` returns `null`, e.g. a `BOM`/`SP`/`TAB`
2892
- * before `MSH` (which shares the `MSH`'s segment line, so `MSH` heads no segment), or
2893
- * a bare fragment delivered after a mid-payload `VT` discard (`MLLP_TRAILING_BYTES`).
3030
+ * 1. **No readable `MSH`.** `readMshSegment` returns `null`, e.g. a `SP`/`TAB` before
3031
+ * `MSH` (which shares the `MSH`'s segment line, so `MSH` heads no segment), or a frame
3032
+ * that holds only part of a message. A UTF-8
3033
+ * byte order mark at byte 0 is not one of these: the scan skips it and reads the `MSH`.
2894
3034
  * MSA-2 would be empty: an ACK that correlates to nothing.
2895
3035
  * 2. **Empty MSH-10.** The `MSH` is readable but carries no message control ID, so there
2896
3036
  * is nothing to echo, again `MSA|AA|` with an empty MSA-2.
@@ -3460,6 +3600,24 @@ interface ClientOptions {
3460
3600
  * @default false
3461
3601
  */
3462
3602
  readonly correlateByControlId?: boolean;
3603
+ /**
3604
+ * What a client correlating in order (FIFO, the default) does when the frame that settles a
3605
+ * send carries no readable MSA-1: no HL7 Table 0008 code can be read from it, as with a lone
3606
+ * `0x06` or `0x15` byte, an `MSH` with no `MSA`, an empty MSA-1, or a value outside the table.
3607
+ * Such a frame is not an HL7 acknowledgement of the message.
3608
+ *
3609
+ * - `'warn'` (default): the send resolves with the frame, as it always has, and the client
3610
+ * emits the `'warning'` `MLLP_ACK_FIFO_MSA1_UNREADABLE` (an {@link AckModeWarning}).
3611
+ * - `'reject'`: the client emits the same warning and the send rejects with
3612
+ * {@link MllpUnreadableAckError}. The frame still takes that send's turn, so the next send
3613
+ * settles on the next frame.
3614
+ *
3615
+ * Has no effect with `correlateByControlId: true`, which matches by MSA-2 and settles nothing
3616
+ * on a frame that has none. Any other value throws a `TypeError` at construction.
3617
+ *
3618
+ * @default 'warn'
3619
+ */
3620
+ readonly fifoUnreadableAck?: "warn" | "reject";
3463
3621
  /**
3464
3622
  * Auto-reconnect on transient disconnect. Default `false`.
3465
3623
  *
@@ -3690,6 +3848,8 @@ declare class MllpClient extends EventEmitter {
3690
3848
  private readonly _applicationAckTimeoutMs;
3691
3849
  /** controlId-mode flag. `false` → FIFO. */
3692
3850
  private readonly _correlateByControlId;
3851
+ /** Whether a FIFO send settled on a frame with no readable MSA-1 rejects rather than resolves. */
3852
+ private readonly _rejectUnreadableAck;
3693
3853
  /** Unified ACK correlator. Built during `_attachConnection`. */
3694
3854
  private _correlator;
3695
3855
  /**
@@ -4089,6 +4249,12 @@ declare class MllpClient extends EventEmitter {
4089
4249
  * client's). The clock starts at the underlying `write()` flush callback, NOT at
4090
4250
  * the `send()` call.
4091
4251
  * - `MllpConnectionError({ phase: 'send' })` if the client is not connected.
4252
+ * - `MllpUnreadableAckError` with `fifoUnreadableAck: 'reject'`, when the frame that settles
4253
+ * this send in order carries no readable MSA-1.
4254
+ *
4255
+ * Resolving is not acceptance: read MSA-1 off the acknowledgement you are handed. In FIFO
4256
+ * mode a frame with no readable MSA-1 still resolves by default, with the warning
4257
+ * `MLLP_ACK_FIFO_MSA1_UNREADABLE`.
4092
4258
  *
4093
4259
  * Emits a frozen `'ack'` event on every successful match.
4094
4260
  *
@@ -4110,7 +4276,8 @@ declare class MllpClient extends EventEmitter {
4110
4276
  * @example
4111
4277
  * ```typescript
4112
4278
  * const ack = await client.send(payloadBuffer);
4113
- * logger.info({ ack: ack.toString('utf8') });
4279
+ * // Log the acknowledgement's size, never its bytes: they echo your MSH-10.
4280
+ * logger.info({ ackBytes: ack.length });
4114
4281
  * ```
4115
4282
  *
4116
4283
  * @param payload Raw bytes; MLLP framing is added internally via `encodeFrame`.
@@ -4418,6 +4585,8 @@ interface StarterClientOptions {
4418
4585
  readonly ackTimeoutMs?: number;
4419
4586
  /** Override default `false` (FIFO mode). */
4420
4587
  readonly correlateByControlId?: boolean;
4588
+ /** Passthrough to `ClientOptions.fifoUnreadableAck`, default `'warn'`. */
4589
+ readonly fifoUnreadableAck?: "warn" | "reject";
4421
4590
  /** Override default `true` (parallel up to highWaterMark). */
4422
4591
  readonly pipeline?: boolean;
4423
4592
  /** Override default `64`. */
@@ -4487,6 +4656,7 @@ declare function createStarterClient(opts: StarterClientOptions): Promise<MllpCl
4487
4656
  * - `MllpBackpressureError`, high-water mark exceeded
4488
4657
  * - `MllpNeverDeliveredError`, a send that never reached the transport
4489
4658
  * - `MllpUnknownFateError`, a send whose bytes went out and drew no answer
4659
+ * - `MllpUnreadableAckError`, a FIFO send settled on a frame with no readable MSA-1
4490
4660
  * - `isTransientConnectionError`, transient/permanent classifier
4491
4661
  *
4492
4662
  * Re-exported from `src/client/index.ts` and `src/index.ts`.
@@ -4617,6 +4787,50 @@ declare class MllpApplicationAckError extends Error {
4617
4787
  commitReceivedAt: number;
4618
4788
  });
4619
4789
  }
4790
+ /**
4791
+ * Rejects a `send()` on a client correlating in order (FIFO, the default) when the frame that
4792
+ * settled it carries no readable MSA-1: no HL7 Table 0008 code could be read from it. A lone
4793
+ * `0x06` or `0x15` byte, an `MSH` with no `MSA`, an empty MSA-1 and a value outside the table
4794
+ * all qualify.
4795
+ *
4796
+ * Only raised with `fifoUnreadableAck: 'reject'`; by default the send resolves with the frame
4797
+ * and the client warns `MLLP_ACK_FIFO_MSA1_UNREADABLE`. The frame was written in reply to this
4798
+ * send's turn, so the peer may hold the message: resending it may deliver it twice, and the
4799
+ * receiver's de-duplication on MSH-10 is what makes a resend safe.
4800
+ *
4801
+ * Every field is a number. The frame itself is on the client's `'message'` event.
4802
+ *
4803
+ * @example
4804
+ * ```typescript
4805
+ * try {
4806
+ * await client.send(payload);
4807
+ * } catch (err) {
4808
+ * if (err instanceof MllpUnreadableAckError) {
4809
+ * logger.warn({ msa1Bytes: err.msa1Bytes, at: err.byteOffset });
4810
+ * }
4811
+ * }
4812
+ * ```
4813
+ */
4814
+ declare class MllpUnreadableAckError extends Error {
4815
+ readonly name: "MllpUnreadableAckError";
4816
+ /** Byte length of the MSA-1 field read, `0` when the frame has no `MSH` or no `MSA`. */
4817
+ readonly msa1Bytes: number;
4818
+ /** Stream byte offset of the frame that settled the send. */
4819
+ readonly byteOffset: number;
4820
+ /** Milliseconds between the send's write-flush and that frame. */
4821
+ readonly elapsedMs: number;
4822
+ /**
4823
+ * Construct an unreadable-acknowledgement error.
4824
+ *
4825
+ * @param message - Human-readable error message. Structural facts only, never field content.
4826
+ * @param opts - Failure context (MSA-1 byte length, stream offset, elapsed time).
4827
+ */
4828
+ constructor(message: string, opts: {
4829
+ msa1Bytes: number;
4830
+ byteOffset: number;
4831
+ elapsedMs: number;
4832
+ });
4833
+ }
4620
4834
  /**
4621
4835
  * Rejects a `send()` whose peer answered with a **negative commit**: HL7 Table 0008 `CE`
4622
4836
  * (commit error) or `CR` (commit reject).
@@ -5512,5 +5726,5 @@ declare function runDifferential(options?: DifferentialRunOptions): Promise<Diff
5512
5726
  */
5513
5727
  declare const VERSION: string;
5514
5728
 
5515
- export { ATNA_CIPHER_LIST, ATNA_CIPHER_SUITES, Connection, FrameReader, MLLP_BIND_ALL_INTERFACES, MLLP_CONNECTION_LIMIT_REACHED, MLLP_DIFF_PEER_UNPARSEABLE, MLLP_TLS_CIPHER_LIST_REJECTED, MLLP_TLS_CIPHER_LIST_UNENFORCEABLE, MLLP_TLS_CIPHER_OPTION_CONFLICT, MLLP_TLS_CREDENTIAL_CONFLICT, MLLP_TLS_DH_PARAMETERS_REJECTED, MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE, MLLP_TLS_OPTIONS_NOT_AN_OBJECT, MLLP_TLS_PFX_REJECTED, MLLP_TLS_VERIFY_DISABLED, MllpAckError, MllpApplicationAckError, MllpBackpressureError, MllpClient, MllpCommitRejectedError, MllpConnectionError, MllpDifferentialConfigurationError, MllpFramingError, MllpNeverDeliveredError, MllpServer, MllpTimeoutError, MllpTlsConfigurationError, MllpUnknownFateError, MllpWarning, NetTransport, TLS13_DEFAULT_CIPHER_SUITES, TlsTransport, Transport, VERSION, WarningCode, ackDiagnosticMessage, ackModeDiagnosticMessage, buildRawAck, canonicalAcknowledgement, canonicalExchanges, createClient, createServer, createStarterClient, createStarterServer, differentialConfigurationMessage, encodeFrame, isTlsProtocolError, isTlsVerificationErrorCode, isTransientConnectionError, rawAckUncorrelatable, readNegotiatedTlsParameters, resolveDifferentialPeer, resolveNackCode, resolveTlsCipherPolicy, runDifferential, selectAckCode, tlsConfigurationMessage };
5729
+ export { ATNA_CIPHER_LIST, ATNA_CIPHER_SUITES, Connection, FrameReader, MLLP_BIND_ALL_INTERFACES, MLLP_CONNECTION_LIMIT_REACHED, MLLP_DIFF_PEER_UNPARSEABLE, MLLP_TLS_CIPHER_LIST_REJECTED, MLLP_TLS_CIPHER_LIST_UNENFORCEABLE, MLLP_TLS_CIPHER_OPTION_CONFLICT, MLLP_TLS_CREDENTIAL_CONFLICT, MLLP_TLS_DH_PARAMETERS_REJECTED, MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE, MLLP_TLS_OPTIONS_NOT_AN_OBJECT, MLLP_TLS_PFX_REJECTED, MLLP_TLS_VERIFY_DISABLED, MllpAckError, MllpApplicationAckError, MllpBackpressureError, MllpClient, MllpCommitRejectedError, MllpConnectionError, MllpDifferentialConfigurationError, MllpFramingError, MllpNeverDeliveredError, MllpServer, MllpTimeoutError, MllpTlsConfigurationError, MllpUnknownFateError, MllpUnreadableAckError, MllpWarning, NetTransport, TLS13_DEFAULT_CIPHER_SUITES, TlsTransport, Transport, VERSION, WarningCode, ackDiagnosticMessage, ackModeDiagnosticMessage, buildRawAck, canonicalAcknowledgement, canonicalExchanges, createClient, createServer, createStarterClient, createStarterServer, differentialConfigurationMessage, encodeFrame, isTlsProtocolError, isTlsVerificationErrorCode, isTransientConnectionError, rawAckUncorrelatable, readNegotiatedTlsParameters, resolveDifferentialPeer, resolveNackCode, resolveTlsCipherPolicy, runDifferential, selectAckCode, tlsConfigurationMessage };
5516
5730
  export type { AckCode, AckCodeSelection, AckCodeSelectionInput, AckCorrelationCode, AckCorrelationWarning, AckModeCode, AckModeWarning, AckModeWarningEvent, ApplicationAckFailure, CanonicalExchange, ClientAuth, ClientOptions, ClientStats, CommitAckReport, ConnectionErrorCause, ConnectionErrorPhase, ConnectionOptions, ConnectionRejectedEvent, ConnectionState, ConnectionStats, DifferentialConfigurationErrorCode, DifferentialConnect, DifferentialCorrelationOutcome, DifferentialDeviation, DifferentialExchangeOutcome, DifferentialExchangeReport, DifferentialParityOutcome, DifferentialPeer, DifferentialReport, DifferentialReportPeer, DifferentialRunOptions, DifferentialRunResult, DifferentialSkipReason, EncoderOptions, FrameReaderOptions, MessageMeta, NackAckCode, NackEvent, NackReason, NegativeAckCode, NegotiatedTlsParameters, PemInput, ReconnectingEvent, ResolvedTlsCipherPolicy, RetryContext, RetryStrategy, SecurityWarning, SecurityWarningCode, ServerOptions, ServerStats, ServerTlsOptions, StarterClientOptions, StarterServerOptions, StateChangeEvent, TlsCipherPolicyInput, TlsConfigurationErrorCode, TlsOptions };