@cosyte/mllp 0.1.14 → 0.1.16

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
@@ -1,9 +1,10 @@
1
- import { W as WarningCode, M as MllpWarning } from './registry-CyGU_l8N.js';
2
- export { c as createWarning } from './registry-CyGU_l8N.js';
3
- import { T as Transport } from './index-CD8V2Mtk.js';
4
- import { EventEmitter } from 'node:events';
1
+ import { W as WarningCode, M as MllpWarning } from './registry-BPOSRmcX.js';
2
+ export { c as createWarning } from './registry-BPOSRmcX.js';
3
+ import { Buffer } from 'node:buffer';
4
+ import { T as Transport } from './transport-2Zo_VBmG.js';
5
5
  import { Socket } from 'node:net';
6
6
  import { TLSSocket } from 'node:tls';
7
+ import { EventEmitter } from 'node:events';
7
8
 
8
9
  /**
9
10
  * Typed framing error class for unrecoverable MLLP wire-format violations.
@@ -109,7 +110,7 @@ interface EncoderOptions {
109
110
  *
110
111
  * Default: `false` (strict, throws on delimiter bytes).
111
112
  */
112
- allowDelimiterBytesInPayload?: boolean;
113
+ readonly allowDelimiterBytesInPayload?: boolean;
113
114
  /**
114
115
  * Called for each offending delimiter byte when `allowDelimiterBytesInPayload` is `true`.
115
116
  * Invocation is wrapped in try/catch, a throwing handler does not interrupt encoding.
@@ -122,7 +123,7 @@ interface EncoderOptions {
122
123
  * });
123
124
  * ```
124
125
  */
125
- onWarning?: (w: MllpWarning) => void;
126
+ readonly onWarning?: (w: MllpWarning) => void;
126
127
  }
127
128
  /**
128
129
  * Encode `payload` in canonical MLLP framing: `VT (0x0B) + payload + FS (0x1C) + CR (0x0D)`.
@@ -154,7 +155,7 @@ interface EncoderOptions {
154
155
  * });
155
156
  * ```
156
157
  */
157
- declare function encodeFrame(payload: Buffer, opts?: EncoderOptions): Buffer;
158
+ declare function encodeFrame(payload: Buffer, options?: EncoderOptions): Buffer;
158
159
 
159
160
  /**
160
161
  * MLLP frame decoder, stateful 3-state FSM for chunked byte-stream parsing.
@@ -166,6 +167,11 @@ declare function encodeFrame(payload: Buffer, opts?: EncoderOptions): Buffer;
166
167
  * unless the matching tolerance option is explicitly enabled (Postel's Law, liberal receiver
167
168
  * means explicit tolerance, not silent acceptance).
168
169
  *
170
+ * A frame whose end cannot be told is refused whole whatever the tolerances: a `VT` inside it
171
+ * throws `MLLP_PAYLOAD_CONTAINS_VT`, and an `FS` followed by anything but `CR`, `LF` or the next
172
+ * frame's `VT` throws `MLLP_PAYLOAD_CONTAINS_FS`. Nothing of that frame is delivered, the reader
173
+ * is left scanning for the next `VT`, and the error names only the framing byte and its offset.
174
+ *
169
175
  * @example
170
176
  * ```typescript
171
177
  * import { FrameReader } from '@cosyte/mllp';
@@ -209,25 +215,29 @@ interface FrameReaderOptions {
209
215
  * @param warnings - Framing warnings emitted during decoding of this specific frame.
210
216
  * Empty array when no tolerance deviations were detected.
211
217
  */
212
- onFrame: (payload: Buffer, byteOffset: number, warnings: readonly MllpWarning[]) => void;
218
+ readonly onFrame: (payload: Buffer, byteOffset: number, warnings: readonly MllpWarning[]) => void;
213
219
  /**
214
220
  * Called for each tolerated framing deviation. Wrapped in try/catch.
215
221
  * A throwing handler will not corrupt FSM state.
216
222
  */
217
- onWarning?: (w: MllpWarning) => void;
223
+ readonly onWarning?: (w: MllpWarning) => void;
218
224
  /**
219
225
  * Maximum accumulated payload bytes before `MllpFramingError('MLLP_FRAME_TOO_LARGE')`.
220
226
  * Default: 16 MiB (DoS prevention).
221
227
  */
222
- maxFrameSizeBytes?: number;
223
- /** Tolerate FS without trailing CR; emits `MLLP_FS_WITHOUT_CR`. */
224
- allowFsOnly?: boolean;
228
+ readonly maxFrameSizeBytes?: number;
229
+ /**
230
+ * Tolerate FS without trailing CR when the next frame's VT follows it; emits
231
+ * `MLLP_FS_WITHOUT_CR`. Any other byte after the FS means the FS sat inside the frame, and the
232
+ * frame is refused whole with `MLLP_PAYLOAD_CONTAINS_FS`.
233
+ */
234
+ readonly allowFsOnly?: boolean;
225
235
  /** Tolerate FS+LF instead of FS+CR; emits `MLLP_LF_AFTER_FS`. */
226
- allowLfAfterFs?: boolean;
236
+ readonly allowLfAfterFs?: boolean;
227
237
  /** Tolerate missing leading VT; emits `MLLP_MISSING_LEADING_VT`. */
228
- allowMissingLeadingVt?: boolean;
238
+ readonly allowMissingLeadingVt?: boolean;
229
239
  /** Tolerate SP/TAB/LF/CR before VT; emits `MLLP_LEADING_WHITESPACE`. */
230
- allowLeadingWhitespace?: boolean;
240
+ readonly allowLeadingWhitespace?: boolean;
231
241
  /**
232
242
  * When `true`, escalates the following tolerances to thrown `MllpFramingError`
233
243
  * even if individual opt-ins (`allowFsOnly`, `allowLfAfterFs`, `allowMissingLeadingVt`,
@@ -237,7 +247,7 @@ interface FrameReaderOptions {
237
247
  * - `MLLP_LF_AFTER_FS`
238
248
  * - `MLLP_LEADING_WHITESPACE` (leading whitespace escalates as `MLLP_MISSING_LEADING_VT`)
239
249
  *
240
- * `MLLP_EMPTY_PAYLOAD` and `MLLP_TRAILING_BYTES` remain warnings even in strict mode.
250
+ * `MLLP_EMPTY_PAYLOAD` remains a warning even in strict mode.
241
251
  *
242
252
  * @example
243
253
  * ```typescript
@@ -245,7 +255,7 @@ interface FrameReaderOptions {
245
255
  * const reader = new FrameReader({ onFrame: fn, strict: true });
246
256
  * ```
247
257
  */
248
- strict?: boolean;
258
+ readonly strict?: boolean;
249
259
  }
250
260
  /**
251
261
  * Stateful MLLP frame decoder. Feed raw TCP byte chunks via `push(chunk)`.
@@ -360,6 +370,12 @@ declare class FrameReader {
360
370
  * bytes forgotten first.
361
371
  */
362
372
  private _deliver;
373
+ /**
374
+ * Refuse the current frame whole: forget its bytes and its warnings, go back to scanning for a
375
+ * VT, and throw. The error names the framing byte (`delimiter`) and its offset, never a byte of
376
+ * the frame's content, and nothing of the frame is delivered.
377
+ */
378
+ private _refuse;
363
379
  /** Emit a warning via the `onWarning` callback, swallowing any handler exceptions. */
364
380
  private _emitWarning;
365
381
  }
@@ -600,6 +616,7 @@ interface SecurityWarning {
600
616
  *
601
617
  * @packageDocumentation
602
618
  */
619
+
603
620
  /**
604
621
  * A PEM-encoded credential (certificate, key, or CA), matching Node's
605
622
  * `tls.connect`/`tls.createServer` input shape, a single PEM string/Buffer,
@@ -1148,9 +1165,9 @@ declare class MllpTlsConfigurationError extends Error {
1148
1165
  * Construct a TLS configuration error.
1149
1166
  *
1150
1167
  * @param code - The stable configuration-error code; also selects the message.
1151
- * @param opts - Optional underlying `cause` from the TLS library.
1168
+ * @param options - Optional underlying `cause` from the TLS library.
1152
1169
  */
1153
- constructor(code: TlsConfigurationErrorCode, opts?: {
1170
+ constructor(code: TlsConfigurationErrorCode, options?: {
1154
1171
  cause?: Error;
1155
1172
  });
1156
1173
  }
@@ -1184,6 +1201,7 @@ declare class MllpTlsConfigurationError extends Error {
1184
1201
  *
1185
1202
  * @packageDocumentation
1186
1203
  */
1204
+
1187
1205
  /**
1188
1206
  * The four TLS 1.2 cipher suites ITI TF-2 §3.19.6.2.3 names, in the OpenSSL
1189
1207
  * spelling a cipher-list string is written in. Their IANA spellings, which are
@@ -1520,15 +1538,15 @@ interface ConnectionStats {
1520
1538
  */
1521
1539
  interface ConnectionOptions {
1522
1540
  /** The transport this Connection will drive. */
1523
- transport: Transport;
1541
+ readonly transport: Transport;
1524
1542
  /** Called for each decoded MLLP frame (raw payload bytes, framing stripped). */
1525
- onMessage?: (payload: Buffer) => void;
1543
+ readonly onMessage?: (payload: Buffer) => void;
1526
1544
  /** Per-connection warning subscriber. Replaces previous subscription. */
1527
- onWarning?: (w: MllpWarning) => void;
1545
+ readonly onWarning?: (w: MllpWarning) => void;
1528
1546
  /** Drain timeout used by close() (default: 30_000 ms). */
1529
- drainTimeoutMs?: number;
1547
+ readonly drainTimeoutMs?: number;
1530
1548
  /** FrameReader options (tolerance, maxFrameSizeBytes). onFrame/onWarning are managed internally. */
1531
- framing?: Omit<FrameReaderOptions, "onFrame" | "onWarning">;
1549
+ readonly framing?: Omit<FrameReaderOptions, "onFrame" | "onWarning">;
1532
1550
  }
1533
1551
  /**
1534
1552
  * A single MLLP connection wrapping a {@link Transport} with a 6-state FSM,
@@ -1582,6 +1600,20 @@ declare class Connection extends EventEmitter {
1582
1600
  * drain it waits on.
1583
1601
  */
1584
1602
  private readonly _leftDraining;
1603
+ /**
1604
+ * Work answering a frame this connection delivered, still running, with what it owes the peer.
1605
+ * See {@link Connection.holdOpenFor}.
1606
+ */
1607
+ private readonly _answering;
1608
+ /**
1609
+ * Set once a fatal framing error has been met, or {@link Connection.stopReading} called: from
1610
+ * then on no byte the peer sends is read.
1611
+ */
1612
+ private _refusing;
1613
+ /** When the `close()` drain began (`Date.now()`), or `undefined` when no `close()` is draining. */
1614
+ private _closeBegan;
1615
+ /** Ends the wait after a fatal framing error: destroys the transport once the bound passes. */
1616
+ private _refusalBound;
1585
1617
  /**
1586
1618
  * beforeClose hook, no-op default that resolves immediately.
1587
1619
  *
@@ -1653,9 +1685,13 @@ declare class Connection extends EventEmitter {
1653
1685
  *
1654
1686
  * - If `CONNECTING` or `RECONNECTING`: cancels the pending attempt, transitions
1655
1687
  * 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.
1688
+ * - If `CONNECTED`: transitions to `DRAINING`, calls `beforeClose(drainTimeoutMs)` and
1689
+ * waits for it and for every piece of work passed to {@link Connection.holdOpenFor} that is
1690
+ * still running, then `DRAINING → DISCONNECTED` and ends the transport gracefully, so what
1691
+ * that work wrote reaches the peer. If the drain timeout elapses first: `DRAINING → CLOSED`
1692
+ * and the transport is destroyed. Work still running when the drain ends that way (the
1693
+ * timeout or a `destroy()`) is abandoned, and an `MllpConnectionError` with `phase: 'close'`
1694
+ * on `'error'` says how many were left and that what they would write is not sent.
1659
1695
  * - If `DRAINING`: waits for the existing drain to complete (idempotent).
1660
1696
  *
1661
1697
  * Every pending `close()` resolves as soon as the connection leaves `DRAINING`, by whatever
@@ -1663,18 +1699,18 @@ declare class Connection extends EventEmitter {
1663
1699
  * `destroy()` during a long drain therefore ends the wait at once, not at the drain timeout.
1664
1700
  * - If `CLOSED` or `DISCONNECTED`: no-op.
1665
1701
  *
1666
- * @param opts.drainTimeoutMs - Override drain timeout (default: `opts.drainTimeoutMs ?? 30_000`).
1702
+ * @param options.drainTimeoutMs - Override drain timeout (default: `options.drainTimeoutMs ?? 30_000`).
1667
1703
  *
1668
1704
  * @example
1669
1705
  * ```typescript
1670
1706
  * await conn.close({ drainTimeoutMs: 5_000 });
1671
1707
  * ```
1672
1708
  */
1673
- close(opts?: {
1709
+ close(options?: {
1674
1710
  drainTimeoutMs?: number;
1675
1711
  }): Promise<void>;
1676
1712
  /**
1677
- * Race `beforeClose()` against the drain timeout.
1713
+ * Race `beforeClose()` and the held work against the drain timeout.
1678
1714
  *
1679
1715
  * On normal completion: `DRAINING → DISCONNECTED` + `transport.close()`.
1680
1716
  * On timeout: `DRAINING → CLOSED` + `transport.destroy()`.
@@ -1695,6 +1731,63 @@ declare class Connection extends EventEmitter {
1695
1731
  * ```
1696
1732
  */
1697
1733
  destroy(reason?: Error): void;
1734
+ /**
1735
+ * Hold the connection open, on `close()` or a fatal framing error, until `work` settles.
1736
+ *
1737
+ * Pass the work that answers a frame this connection delivered: the handler and the write of
1738
+ * its acknowledgement. A `close()` waits for every piece of work passed here to settle before
1739
+ * it ends the transport, so an acknowledgement written by that work still goes out. When a
1740
+ * later frame on the same connection has a fatal framing error, the connection reads nothing
1741
+ * more, waits the same way, and only then closes, so the acknowledgement of a frame delivered
1742
+ * before the refused one still goes out. Either wait is bounded by `drainTimeoutMs` (default 30
1743
+ * seconds): work that has not settled by then is abandoned and the connection is destroyed.
1744
+ * `MllpServer` passes every message's work here itself; a caller driving a bare `Connection`
1745
+ * may do the same.
1746
+ *
1747
+ * `options.kind` says what the work owes the peer, which decides whether `close()` waits for it
1748
+ * and how an abandoned piece is reported:
1749
+ *
1750
+ * - `'ack'` (the default): the work writes the frame's acknowledgement as its last step, so
1751
+ * while it runs the acknowledgement has not been sent. `close()` waits for it; abandoned, it is
1752
+ * counted as a message delivered whose acknowledgement was not sent.
1753
+ * - `'manual'`: the work writes the acknowledgement itself at a point of its own choosing (a
1754
+ * manual-mode handler). `close()` waits for it until it settles; abandoned, it is counted as a
1755
+ * handler whose acknowledgement may not have been sent.
1756
+ * - `'observer'`: the work writes no acknowledgement (an `onMessage` observer in custom-ACK
1757
+ * mode). `close()` does not wait for it; still running when a `close()` is abandoned, it is
1758
+ * named separately as an observer still running. A fatal framing error still waits for it.
1759
+ *
1760
+ * A rejection of `work` is not reported here; it only ends the wait for it.
1761
+ *
1762
+ * @param work - The work answering one delivered frame.
1763
+ * @param options - `kind`: what the work owes the peer (default `'ack'`).
1764
+ *
1765
+ * @example
1766
+ * ```typescript
1767
+ * conn.on('message', ({ payload }) => {
1768
+ * conn.holdOpenFor(commit(payload).then(() => conn.send(encodeFrame(ackFor(payload)))));
1769
+ * });
1770
+ * ```
1771
+ */
1772
+ holdOpenFor(work: PromiseLike<unknown>, options?: {
1773
+ readonly kind?: "ack" | "manual" | "observer";
1774
+ }): void;
1775
+ /**
1776
+ * Read nothing more from the peer: every byte that arrives from now on is dropped unread, and
1777
+ * no further frame is delivered. It cannot be undone.
1778
+ *
1779
+ * `MllpServer.close()` calls this on each connection before closing it, so no new message
1780
+ * reaches a handler while the ones already running finish and their acknowledgements are
1781
+ * written. A client must not call it before a `close()` that waits for acknowledgements, since
1782
+ * it would then never read them.
1783
+ *
1784
+ * @example
1785
+ * ```typescript
1786
+ * conn.stopReading();
1787
+ * await conn.close();
1788
+ * ```
1789
+ */
1790
+ stopReading(): void;
1698
1791
  /**
1699
1792
  * Return a JSON-serializable observability snapshot.
1700
1793
  *
@@ -1711,6 +1804,25 @@ declare class Connection extends EventEmitter {
1711
1804
  * ```
1712
1805
  */
1713
1806
  getStats(): ConnectionStats;
1807
+ /**
1808
+ * Settle once no work passed to {@link Connection.holdOpenFor} that owes an acknowledgement is
1809
+ * running; an `'observer'` is not waited for. Work registered while waiting (a frame decoded
1810
+ * from bytes already read) is waited for too.
1811
+ */
1812
+ private _heldWorkSettled;
1813
+ /**
1814
+ * Report, on `'error'`, the held work a `close()` drain abandons because the drain ended before
1815
+ * that work settled. It counts per delivered message: work that would have written an
1816
+ * acknowledgement (not sent), a manual-mode handler (its acknowledgement may not have been
1817
+ * sent), and, separately, observers that owe none. Nothing is reported when no `close()` is
1818
+ * draining or nothing is still running.
1819
+ *
1820
+ * @param how - How the drain ended, as it reads after "close() ended ".
1821
+ * @param reason - What ended it, the message of the report's `cause`.
1822
+ */
1823
+ private _reportAbandonedWork;
1824
+ /** Report the work a `close()` drain abandons at the bound or on a `destroy()`. */
1825
+ private _reportAbandonedAfter;
1714
1826
  private _transition;
1715
1827
  private _onTransportClose;
1716
1828
  /**
@@ -1730,7 +1842,7 @@ declare class Connection extends EventEmitter {
1730
1842
  */
1731
1843
  private _emitErrorIfListened;
1732
1844
  /**
1733
- * Handle a fatal framing error thrown out of `FrameReader.push` (FRAME-FATAL).
1845
+ * Handle a fatal framing error thrown out of `FrameReader.push`.
1734
1846
  *
1735
1847
  * Contract: surface it as a connection `'error'` (frozen payload, `phase: 'receive'`,
1736
1848
  * `connectionCause: 'framing-fatal'`, the original `MllpFramingError` preserved as `cause` so
@@ -1748,8 +1860,21 @@ declare class Connection extends EventEmitter {
1748
1860
  * forever, and the backoff would become an unbounded reconnect storm against an interface
1749
1861
  * engine that is already unwell. A compatibility failure is not a network blip.
1750
1862
  *
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.
1863
+ * Frames delivered before the refused one are still answered. Their handlers may still be
1864
+ * running (an acknowledgement is written after its handler settles, so even a synchronous
1865
+ * handler's is not out yet), and closing at once dropped every one of those acknowledgements:
1866
+ * the sender resent a message already committed, and it was processed twice. So when work
1867
+ * passed to {@link Connection.holdOpenFor} is still running, the connection reads nothing
1868
+ * more, moves to `DRAINING`, waits for that work to settle, then closes gracefully (`CLOSED`,
1869
+ * the transport ended so the acknowledgements written are flushed). The wait is bounded by
1870
+ * `drainTimeoutMs`: past it the connection is destroyed, settled or not, so a handler that never
1871
+ * settles cannot hold the socket open. With nothing running it is destroyed at once.
1872
+ *
1873
+ * If a peer's quirk is *expected*, the decoder's tolerance opt-ins are the supported answer:
1874
+ * `allowLeadingWhitespace` (padding or keepalive bytes before a frame), `allowMissingLeadingVt`,
1875
+ * `allowFsOnly` (a bare FS that the next frame's VT follows) and `allowLfAfterFs` turn their
1876
+ * throw into a warning. No opt-in accepts other bytes between frames, or a stray FS or VT inside
1877
+ * one: those are always refused.
1753
1878
  */
1754
1879
  private _onFatalFramingError;
1755
1880
  /**
@@ -1994,10 +2119,10 @@ interface MessageMeta {
1994
2119
  * (no readable `MSH`, an empty MSH-10, or a batch/concatenated-message shape). A positive
1995
2120
  * `AA` here names a control ID the sender cannot match → timeout → resend → **duplicate
1996
2121
  * 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.
2122
+ * - `'discarded-bytes'`, no longer sent. It named a frame the decoder delivered as the fragment
2123
+ * after a mid-payload `VT`. The decoder now refuses such a frame whole
2124
+ * (`MLLP_PAYLOAD_CONTAINS_VT`) and closes the connection, so no fragment reaches the
2125
+ * acknowledgement path. The value stays in the type so code that names it still compiles.
2001
2126
  */
2002
2127
  type NackReason = "handler-rejected" | "uncorrelatable-inbound" | "discarded-bytes";
2003
2128
  /**
@@ -2015,7 +2140,7 @@ type NackReason = "handler-rejected" | "uncorrelatable-inbound" | "discarded-byt
2015
2140
  * @example
2016
2141
  * ```typescript
2017
2142
  * server.on('nack', ({ connectionId, ackCode, reason }) => {
2018
- * metrics.increment('mllp.nack', { code: ackCode, reason }); // e.g. reason='discarded-bytes'
2143
+ * metrics.increment('mllp.nack', { code: ackCode, reason }); // e.g. reason='handler-rejected'
2019
2144
  * });
2020
2145
  * ```
2021
2146
  */
@@ -2198,17 +2323,17 @@ interface ServerOptions {
2198
2323
  *
2199
2324
  * May be sync or async; an async handler is awaited in commit-gated mode.
2200
2325
  */
2201
- onMessage?: (payload: Buffer, meta: MessageMeta, conn: Connection) => void | Promise<void>;
2326
+ readonly onMessage?: (payload: Buffer, meta: MessageMeta, conn: Connection) => void | Promise<void>;
2202
2327
  /**
2203
2328
  * FrameReader tolerance options applied to every accepted connection.
2204
2329
  * Merged with SERVER_DEFAULT_FRAMING, caller-supplied values override defaults.
2205
2330
  * `onFrame` and `onWarning` are managed internally and must not be supplied here.
2206
2331
  */
2207
- framing?: Omit<FrameReaderOptions, "onFrame" | "onWarning">;
2332
+ readonly framing?: Omit<FrameReaderOptions, "onFrame" | "onWarning">;
2208
2333
  /**
2209
2334
  * Per-connection warning subscriber. Called for every framing warning on every connection.
2210
2335
  */
2211
- onWarning?: (w: MllpWarning) => void;
2336
+ readonly onWarning?: (w: MllpWarning) => void;
2212
2337
  /**
2213
2338
  * Auto-ACK mode. When set, the server builds and sends the ACK for each message.
2214
2339
  *
@@ -2228,14 +2353,14 @@ interface ServerOptions {
2228
2353
  * The `'message'` event always fires BEFORE the ACK is sent. Do NOT call
2229
2354
  * `conn.send()` in `onMessage` when `autoAck` is set, this results in two ACKs.
2230
2355
  */
2231
- autoAck?: "AA" | ((payload: Buffer, meta: MessageMeta, conn: Connection) => Buffer | Promise<Buffer>);
2356
+ readonly autoAck?: "AA" | ((payload: Buffer, meta: MessageMeta, conn: Connection) => Buffer | Promise<Buffer>);
2232
2357
  /**
2233
2358
  * TCP keepalive probe interval in ms.
2234
2359
  * Calls `socket.setKeepAlive(true, ms)` on each accepted socket.
2235
2360
  * Uses OS TCP stack to detect dead peers (half-open, network partitions).
2236
2361
  * Distinct from `deadPeerTimeoutMs` (application-level idle close).
2237
2362
  */
2238
- keepaliveIntervalMs?: number;
2363
+ readonly keepaliveIntervalMs?: number;
2239
2364
  /**
2240
2365
  * Whether to turn off Nagle's algorithm (`socket.setNoDelay(noDelay)`) on each accepted
2241
2366
  * socket. With it on (`false` here), an ACK written while an earlier one is still
@@ -2244,19 +2369,27 @@ interface ServerOptions {
2244
2369
  *
2245
2370
  * @default true
2246
2371
  */
2247
- noDelay?: boolean;
2372
+ readonly noDelay?: boolean;
2248
2373
  /**
2249
2374
  * Application-level idle close timeout in ms.
2250
2375
  * If no HL7 messages are received on a connection for this interval, the connection
2251
2376
  * is destroyed via `conn.destroy(new Error('idle timeout'))`.
2252
2377
  * Resets on every `'message'` event. Distinct from `keepaliveIntervalMs` (OS TCP probe).
2253
2378
  */
2254
- deadPeerTimeoutMs?: number;
2379
+ readonly deadPeerTimeoutMs?: number;
2255
2380
  /**
2256
- * Graceful drain timeout passed to `conn.close()` during `server.close()`.
2257
- * Default: 30 000 ms.
2381
+ * Graceful drain timeout passed to `conn.close()` during `server.close()`: the longest
2382
+ * `close()` waits for the handlers still running and their acknowledgements. A handler still
2383
+ * running then is abandoned, and an `MllpConnectionError` with `phase: 'close'` on `'error'`
2384
+ * says how many messages were delivered without their acknowledgement being sent (in manual
2385
+ * mode, how many handlers may not have sent theirs). In custom-ACK mode the `onMessage`
2386
+ * observer is not waited for, since it writes no acknowledgement. Default: 30 000 ms.
2387
+ *
2388
+ * It also bounds the wait after a fatal framing error: frames delivered before the refused one
2389
+ * are still answered, and a connection waits at most this long for their handlers before it is
2390
+ * destroyed.
2258
2391
  */
2259
- drainTimeoutMs?: number;
2392
+ readonly drainTimeoutMs?: number;
2260
2393
  /**
2261
2394
  * Enable TLS (MLLPS) for this server. When set, the server binds a
2262
2395
  * `tls.Server` instead of a plain `net.Server`, consumes `'secureConnection'`
@@ -2275,7 +2408,7 @@ interface ServerOptions {
2275
2408
  *
2276
2409
  * @default undefined (plaintext TCP)
2277
2410
  */
2278
- tls?: ServerTlsOptions;
2411
+ readonly tls?: ServerTlsOptions;
2279
2412
  /**
2280
2413
  * Opt-in required to bind a wildcard host, a bind-safety guardrail.
2281
2414
  * Without this flag, `listen()` rejects a wildcard host in
@@ -2292,7 +2425,7 @@ interface ServerOptions {
2292
2425
  *
2293
2426
  * @default false
2294
2427
  */
2295
- allowWildcardBind?: boolean;
2428
+ readonly allowWildcardBind?: boolean;
2296
2429
  /**
2297
2430
  * The most connections this server holds at once. A connection that arrives while the server
2298
2431
  * already holds this many is closed at accept: it never reaches `onMessage` or the
@@ -2313,7 +2446,7 @@ interface ServerOptions {
2313
2446
  *
2314
2447
  * @default undefined (no cap)
2315
2448
  */
2316
- maxConnections?: number;
2449
+ readonly maxConnections?: number;
2317
2450
  }
2318
2451
  /**
2319
2452
  * Options for `createStarterServer()`, the "three lines of code" factory.
@@ -2337,13 +2470,13 @@ interface ServerOptions {
2337
2470
  */
2338
2471
  interface StarterServerOptions extends ServerOptions {
2339
2472
  /** Port to listen on. */
2340
- port: number;
2473
+ readonly port: number;
2341
2474
  /**
2342
2475
  * Host to bind to. Default `'127.0.0.1'` (bind-safety hardening,
2343
2476
  * was `'0.0.0.0'`; binding all interfaces now requires
2344
2477
  * `ServerOptions.allowWildcardBind: true`).
2345
2478
  */
2346
- host?: string;
2479
+ readonly host?: string;
2347
2480
  /**
2348
2481
  * Register `process.once('SIGTERM')` and `process.once('SIGINT')` handlers that
2349
2482
  * call `server.close()` then `process.exit(0)`. Default: `false`.
@@ -2352,7 +2485,7 @@ interface StarterServerOptions extends ServerOptions {
2352
2485
  * `process.listenerCount('SIGTERM') === 0` after close() completes, preventing
2353
2486
  * handler accumulation across test instances or multiple server restarts.
2354
2487
  */
2355
- handleSignals?: boolean;
2488
+ readonly handleSignals?: boolean;
2356
2489
  }
2357
2490
  /**
2358
2491
  * MLLP TCP server, wraps `net.Server` without extending it.
@@ -2365,7 +2498,7 @@ interface StarterServerOptions extends ServerOptions {
2365
2498
  * The `'nack'` event ({@link NackEvent}) fires whenever the server returns a negative ACK
2366
2499
  * instead of `AA` on the auto-ACK path, a commit-gated `autoAck: 'AA'` handler failing, or
2367
2500
  * 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
2501
+ * unreadable or uncorrelatable message). The
2369
2502
  * {@link NackReason} distinguishes the causes.
2370
2503
  *
2371
2504
  * **`'error'` contract:** underlying `net.Server`/`tls.Server` errors are forwarded to the
@@ -2413,6 +2546,11 @@ declare class MllpServer extends EventEmitter {
2413
2546
  /** `true` when `ServerOptions.tls` is set, `_netServer` is actually a `tls.Server`. */
2414
2547
  private readonly _isTls;
2415
2548
  private _listening;
2549
+ /**
2550
+ * `true` from a `close()` until the next `listen()`: a socket accepted meanwhile (a TLS
2551
+ * handshake that began before the close and finished during it) is closed at once, never served.
2552
+ */
2553
+ private _closing;
2416
2554
  /** Single-flight guard: `true` while a `listen()` call is settling. */
2417
2555
  private _listenInFlight;
2418
2556
  /**
@@ -2533,10 +2671,23 @@ declare class MllpServer extends EventEmitter {
2533
2671
  * Stop accepting new connections and gracefully close all active connections.
2534
2672
  *
2535
2673
  * Sequence:
2536
- * 1. `net.Server.close()`, stops accepting new connections immediately
2674
+ * 1. `net.Server.close()`, stops accepting new connections immediately. A socket the listener
2675
+ * still hands over (a TLS handshake that began before `close()` and ends during it) is
2676
+ * destroyed at once, before any byte of it is read.
2537
2677
  * 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
2678
+ * 3. Every connection stops reading: bytes the peer sends from now on are dropped unread, so no
2679
+ * new message reaches a handler.
2680
+ * 4. Every connection waits for its handlers still running and the acknowledgements they write
2681
+ * (`AA`, a negative ACK for a handler that rejects, a custom builder's bytes), then ends its
2682
+ * socket gracefully so those acknowledgements reach the sender. In manual mode the wait lasts
2683
+ * until the handler's promise settles: a `conn.send()` made after that is not waited for. In
2684
+ * custom-ACK mode the `onMessage` observer is not waited for: it writes no acknowledgement.
2685
+ * 5. The wait is bounded by `drainTimeoutMs`. A connection still waiting then is destroyed, and
2686
+ * the server's `'error'` event carries an `MllpConnectionError` with `phase: 'close'` saying
2687
+ * how many messages were delivered without their acknowledgement being sent, how many
2688
+ * manual-mode handlers may not have sent theirs, and how many observers were still running.
2689
+ * The same report is made when the sender closes the connection, or half-closes it (the
2690
+ * server's sockets are not half-open, so our side ends with it), before that work settles.
2540
2691
  *
2541
2692
  * Calling `close()` while a `listen()` is still in flight proactively
2542
2693
  * settles that `listen()` with a typed `MllpConnectionError` rejection
@@ -2548,8 +2699,8 @@ declare class MllpServer extends EventEmitter {
2548
2699
  * the server and does NOT settle the in-flight `listen()`, which simply
2549
2700
  * continues and settles on its own bind outcome.
2550
2701
  *
2551
- * @param opts.drainTimeoutMs - Override drain timeout (default: `opts.drainTimeoutMs ?? 30_000`).
2552
- * @param opts.signal - AbortSignal to cancel the close operation. On abort, all
2702
+ * @param options.drainTimeoutMs - Override drain timeout (default: `options.drainTimeoutMs ?? 30_000`).
2703
+ * @param options.signal - AbortSignal to cancel the close operation. On abort, all
2553
2704
  * active connections are destroyed and the promise rejects with AbortError.
2554
2705
  *
2555
2706
  * @example
@@ -2557,7 +2708,7 @@ declare class MllpServer extends EventEmitter {
2557
2708
  * await server.close({ drainTimeoutMs: 5_000 });
2558
2709
  * ```
2559
2710
  */
2560
- close(opts?: {
2711
+ close(options?: {
2561
2712
  drainTimeoutMs?: number;
2562
2713
  signal?: AbortSignal;
2563
2714
  }): Promise<void>;
@@ -2648,22 +2799,11 @@ declare class MllpServer extends EventEmitter {
2648
2799
  * cannot carry a correlatable positive ACK, so `AA` never names a control ID the sender
2649
2800
  * cannot match (→ timeout → resend → **duplicate clinical message**).
2650
2801
  *
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.
2802
+ * The disqualifier is **`rawAckUncorrelatable(payload)`**: no readable `MSH`, an empty
2803
+ * MSH-10, or a batch/concatenated-message shape. This is the SAME predicate `buildRawAck`
2804
+ * enforces on the wire; it is re-checked here so the downgrade is **observable** (a `'nack'`
2805
+ * event) rather than a silent code change inside the builder. A frame with a `VT` or a stray
2806
+ * `FS` inside it never gets here: the decoder refuses it whole and the connection closes.
2667
2807
  *
2668
2808
  * `selectCode` puts the resolved disposition in the half of HL7 Table 0008 the inbound
2669
2809
  * asked for; it is the identity for a message that asked for nothing.
@@ -2721,10 +2861,12 @@ declare class MllpServer extends EventEmitter {
2721
2861
  */
2722
2862
  private _sendCustomAck;
2723
2863
  /**
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.
2864
+ * Frame an ACK payload and write it to the connection. When the connection has already
2865
+ * closed (a handler that settled after `server.close()` gave up on it, or after the peer
2866
+ * left), the ACK is not sent and a `MllpConnectionError({ phase: 'send' })` saying so is
2867
+ * emitted on the connection. `Connection.send()` returns `false` under backpressure (socket
2868
+ * write buffer full); that is reported the same way, as backpressure. Either way the peer
2869
+ * will time out waiting and may retry. The server never crashes.
2728
2870
  */
2729
2871
  private _dispatchAck;
2730
2872
  }
@@ -2853,10 +2995,10 @@ declare class MllpAckError extends Error {
2853
2995
  readonly ackCode: NegativeAckCode;
2854
2996
  /**
2855
2997
  * @param message - Diagnostic text for the thrower. Never placed on the wire (may carry PHI).
2856
- * @param opts.ackCode - Negative code to return. Default `'AE'`.
2857
- * @param opts.cause - Underlying error, preserved on `.cause`.
2998
+ * @param options.ackCode - Negative code to return. Default `'AE'`.
2999
+ * @param options.cause - Underlying error, preserved on `.cause`.
2858
3000
  */
2859
- constructor(message: string, opts?: {
3001
+ constructor(message: string, options?: {
2860
3002
  ackCode?: NegativeAckCode;
2861
3003
  cause?: unknown;
2862
3004
  });
@@ -2889,8 +3031,8 @@ declare function resolveNackCode(err: unknown): NegativeAckCode;
2889
3031
  * uncorrelatable, all peer-reachable off the wire:
2890
3032
  *
2891
3033
  * 1. **No readable `MSH`.** `readMshSegment` returns `null`, e.g. a `SP`/`TAB` before
2892
- * `MSH` (which shares the `MSH`'s segment line, so `MSH` heads no segment), or a bare
2893
- * fragment delivered after a mid-payload `VT` discard (`MLLP_TRAILING_BYTES`). A UTF-8
3034
+ * `MSH` (which shares the `MSH`'s segment line, so `MSH` heads no segment), or a frame
3035
+ * that holds only part of a message. A UTF-8
2894
3036
  * byte order mark at byte 0 is not one of these: the scan skips it and reads the `MSH`.
2895
3037
  * MSA-2 would be empty: an ACK that correlates to nothing.
2896
3038
  * 2. **Empty MSH-10.** The `MSH` is readable but carries no message control ID, so there
@@ -2966,7 +3108,7 @@ declare function rawAckUncorrelatable(payload: Buffer): boolean;
2966
3108
  * degrading the side that had been **right**: `buildRawAck` began emitting a positive `AA`
2967
3109
  * with an empty MSA-2, silently, for a message whose MSH-10 was plainly present. Agreement
2968
3110
  * is not the goal; agreeing on the *correct*, *tolerant* answer is. A lenient reader may
2969
- * never drop data that is there (Postel's Law, CLAUDE.md).
3111
+ * never drop data that is there (Postel's Law).
2970
3112
  *
2971
3113
  * **The fail-safe downgrade: never a positive `AA`/`CA` it cannot correlate**
2972
3114
  *
@@ -3607,8 +3749,9 @@ interface ClientOptions {
3607
3749
  * friendly.
3608
3750
  *
3609
3751
  * `warningsByCode` keys are constrained to the public {@link WarningCode}
3610
- * union, adding/removing a code is a breaking change (CLAUDE.md
3611
- * stable-codes guardrail enforced at the type boundary).
3752
+ * union, held at the type boundary. The set may grow in any release, so
3753
+ * keep a default branch; removing or renaming a code is a change a caller
3754
+ * must act on.
3612
3755
  *
3613
3756
  * @example
3614
3757
  * ```typescript
@@ -3883,7 +4026,7 @@ declare class MllpClient extends EventEmitter {
3883
4026
  * await client.connect({ signal: ac.signal });
3884
4027
  * ```
3885
4028
  */
3886
- connect(opts?: {
4029
+ connect(options?: {
3887
4030
  signal?: AbortSignal;
3888
4031
  }): Promise<void>;
3889
4032
  /**
@@ -4137,20 +4280,21 @@ declare class MllpClient extends EventEmitter {
4137
4280
  * @example
4138
4281
  * ```typescript
4139
4282
  * const ack = await client.send(payloadBuffer);
4140
- * logger.info({ ack: ack.toString('utf8') });
4283
+ * // Log the acknowledgement's size, never its bytes: they echo your MSH-10.
4284
+ * logger.info({ ackBytes: ack.length });
4141
4285
  * ```
4142
4286
  *
4143
4287
  * @param payload Raw bytes; MLLP framing is added internally via `encodeFrame`.
4144
- * @param opts.signal AbortSignal, aborting cancels the ACK wait.
4145
- * @param opts.ackTimeoutMs This send's bound on the wait for its acknowledgement, from the
4288
+ * @param options.signal AbortSignal, aborting cancels the ACK wait.
4289
+ * @param options.ackTimeoutMs This send's bound on the wait for its acknowledgement, from the
4146
4290
  * moment its bytes are flushed, in place of the client's `ackTimeoutMs`. Under
4147
4291
  * `onBackpressure: "wait"` it also bounds the wait for queue room, and the
4148
4292
  * acknowledgement wait then starts afresh once the send is written.
4149
- * @param opts.applicationAckTimeoutMs Per-send override of the second wait's bound.
4150
- * @param opts.onCommitAck Called with the commit disposition when the peer commits the
4293
+ * @param options.applicationAckTimeoutMs Per-send override of the second wait's bound.
4294
+ * @param options.onCommitAck Called with the commit disposition when the peer commits the
4151
4295
  * message ahead of its application acknowledgement. See {@link CommitAckReport}.
4152
4296
  */
4153
- send(payload: Buffer, opts?: {
4297
+ send(payload: Buffer, options?: {
4154
4298
  signal?: AbortSignal;
4155
4299
  ackTimeoutMs?: number;
4156
4300
  applicationAckTimeoutMs?: number;
@@ -4343,7 +4487,7 @@ declare class MllpClient extends EventEmitter {
4343
4487
  * await client.close({ drainTimeoutMs: 5_000 });
4344
4488
  * ```
4345
4489
  */
4346
- close(opts?: {
4490
+ close(options?: {
4347
4491
  drainTimeoutMs?: number;
4348
4492
  signal?: AbortSignal;
4349
4493
  }): Promise<void>;
@@ -5038,6 +5182,7 @@ declare class MllpBackpressureError extends Error {
5038
5182
  *
5039
5183
  * @packageDocumentation
5040
5184
  */
5185
+
5041
5186
  /**
5042
5187
  * One send-and-await-response pair the harness runs against a peer.
5043
5188
  *
@@ -5572,8 +5717,8 @@ declare function runDifferential(options?: DifferentialRunOptions): Promise<Diff
5572
5717
  /**
5573
5718
  * Package version marker exported from the `@cosyte/mllp` root.
5574
5719
  *
5575
- * Kept in lockstep with `package.json` by `scripts/sync-version.mjs`, which the `version` script
5576
- * runs immediately after `changeset version`. The `: string` annotation is deliberate, without it
5720
+ * Kept in lockstep with `package.json` by `cosyte-process sync-version`, which the `version`
5721
+ * script runs immediately after `changeset version`. The `: string` annotation is deliberate, without it
5577
5722
  * TypeScript infers the *literal* type (`declare const VERSION = "0.0.0"`), which leaks the current
5578
5723
  * release into consumers' types and makes an equality check against any other version a compile
5579
5724
  * error.