@cosyte/mllp 0.1.11 → 0.1.12

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
@@ -646,13 +646,21 @@ var MLLP_BIND_ALL_INTERFACES = "MLLP_BIND_ALL_INTERFACES";
646
646
  var MLLP_TLS_CIPHER_LIST_REJECTED = "MLLP_TLS_CIPHER_LIST_REJECTED";
647
647
  var MLLP_TLS_CIPHER_OPTION_CONFLICT = "MLLP_TLS_CIPHER_OPTION_CONFLICT";
648
648
  var MLLP_TLS_DH_PARAMETERS_REJECTED = "MLLP_TLS_DH_PARAMETERS_REJECTED";
649
- var TLS_CONFIGURATION_MESSAGES = Object.freeze({
650
- [MLLP_TLS_CIPHER_LIST_REJECTED]: "the TLS library rejected the configured cipher-suite list; no connection was opened and no fallback to the runtime default list was made",
651
- [MLLP_TLS_CIPHER_OPTION_CONFLICT]: "tls.atnaTransportSecurity and tls.ciphers both declare the offered cipher-suite list; set exactly one of them",
652
- [MLLP_TLS_DH_PARAMETERS_REJECTED]: "the configured ephemeral Diffie-Hellman parameters are not usable; nothing was bound and no fallback to a server without Diffie-Hellman parameters was made"
653
- });
649
+ var MLLP_TLS_CIPHER_LIST_UNENFORCEABLE = "MLLP_TLS_CIPHER_LIST_UNENFORCEABLE";
650
+ var MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE = "MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE";
651
+ var MLLP_TLS_PFX_REJECTED = "MLLP_TLS_PFX_REJECTED";
652
+ var MLLP_TLS_CREDENTIAL_CONFLICT = "MLLP_TLS_CREDENTIAL_CONFLICT";
654
653
  function tlsConfigurationMessage(code) {
655
- return TLS_CONFIGURATION_MESSAGES[code];
654
+ const messages = {
655
+ [MLLP_TLS_CIPHER_LIST_REJECTED]: "the TLS library rejected the configured cipher-suite list; no connection was opened and no fallback to the runtime default list was made",
656
+ [MLLP_TLS_CIPHER_OPTION_CONFLICT]: "tls.atnaTransportSecurity and tls.ciphers both declare the offered cipher-suite list; set exactly one of them",
657
+ [MLLP_TLS_DH_PARAMETERS_REJECTED]: "the configured ephemeral Diffie-Hellman parameters are not usable; nothing was bound and no fallback to a server without Diffie-Hellman parameters was made",
658
+ [MLLP_TLS_CIPHER_LIST_UNENFORCEABLE]: "this runtime's TLS library does not enforce a configured cipher-suite list; no connection was opened, rather than one offering a list other than the one configured",
659
+ [MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE]: "this runtime's TLS library does not enforce server Diffie-Hellman parameters; nothing was bound, rather than a server running without the parameters configured",
660
+ [MLLP_TLS_PFX_REJECTED]: "tls.pfx could not be loaded with tls.passphrase: the passphrase is wrong, the file is not PKCS#12, or it uses a legacy encryption (RC2-40, as `openssl pkcs12 -export -legacy` and older exports write it) that OpenSSL 3 does not load, so re-export it with AES-256; no socket was opened",
661
+ [MLLP_TLS_CREDENTIAL_CONFLICT]: "tls.pfx was set together with tls.cert or tls.key; the PKCS#12 file carries its own certificate and key, so set either cert and key or pfx, not both"
662
+ };
663
+ return messages[code];
656
664
  }
657
665
  var MllpTlsConfigurationError = class _MllpTlsConfigurationError extends Error {
658
666
  name = "MllpTlsConfigurationError";
@@ -662,7 +670,8 @@ var MllpTlsConfigurationError = class _MllpTlsConfigurationError extends Error {
662
670
  */
663
671
  code;
664
672
  /**
665
- * The TLS library's own error, when the runtime is what refused the list.
673
+ * The TLS library's own error, when the runtime is what refused the input
674
+ * (or, for an `_UNENFORCEABLE` code, refused one of the probes).
666
675
  * `undefined` when this package refused the configuration itself.
667
676
  */
668
677
  cause;
@@ -826,6 +835,47 @@ var ATNA_CIPHER_LIST = [
826
835
  ...TLS13_DEFAULT_CIPHER_SUITES,
827
836
  ...ATNA_CIPHER_SUITES
828
837
  ].join(":");
838
+ function refusalOf(options) {
839
+ try {
840
+ tls.createSecureContext(options);
841
+ } catch (err) {
842
+ return err instanceof Error ? err : new Error(String(err));
843
+ }
844
+ return null;
845
+ }
846
+ var probeResults = /* @__PURE__ */ new Map();
847
+ function probeRefusal(probe) {
848
+ const key = "ciphers" in probe ? `ciphers=${probe.ciphers}` : `dhparam=${probe.dhparam}`;
849
+ const found = probeResults.get(key);
850
+ if (found !== void 0) return found;
851
+ const refusal = refusalOf(probe);
852
+ probeResults.set(key, refusal);
853
+ return refusal;
854
+ }
855
+ function assertCipherListEnforced(atna) {
856
+ if (probeRefusal({ ciphers: "ECDHE-RSA-AES128-GCM-SHA256:!ECDHE-RSA-AES128-GCM-SHA256" }) === null) {
857
+ throw new MllpTlsConfigurationError(MLLP_TLS_CIPHER_LIST_UNENFORCEABLE);
858
+ }
859
+ if (!atna) return;
860
+ for (const suite of ATNA_CIPHER_SUITES) {
861
+ const refusal = probeRefusal({ ciphers: suite });
862
+ if (refusal !== null) {
863
+ throw new MllpTlsConfigurationError(MLLP_TLS_CIPHER_LIST_UNENFORCEABLE, { cause: refusal });
864
+ }
865
+ }
866
+ }
867
+ function assertDhParametersEnforced() {
868
+ const autoRefusal = probeRefusal({ dhparam: "auto" });
869
+ if (autoRefusal !== null) {
870
+ throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE, {
871
+ cause: autoRefusal
872
+ });
873
+ }
874
+ const undersized = "-----BEGIN DH PARAMETERS-----\nMAYCARcCAQU=\n-----END DH PARAMETERS-----\n";
875
+ if (probeRefusal({ dhparam: undersized }) === null) {
876
+ throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE);
877
+ }
878
+ }
829
879
  function assertUsableDhParameters(dhParameters) {
830
880
  if (!isDhParametersPem(dhParameters)) {
831
881
  throw new MllpTlsConfigurationError(MLLP_TLS_DH_PARAMETERS_REJECTED);
@@ -850,7 +900,9 @@ function resolveTlsCipherPolicy(opts, side) {
850
900
  const supplied = side === "server" ? opts.dhParameters : void 0;
851
901
  if (supplied !== void 0) assertUsableDhParameters(supplied);
852
902
  const dhparam = supplied ?? (atna && side === "server" ? "auto" : void 0);
903
+ if (dhparam !== void 0) assertDhParametersEnforced();
853
904
  if (ciphers !== void 0) {
905
+ assertCipherListEnforced(atna);
854
906
  try {
855
907
  tls.createSecureContext({ ciphers });
856
908
  } catch (err) {
@@ -1373,6 +1425,20 @@ var Connection = class extends events.EventEmitter {
1373
1425
  });
1374
1426
  }
1375
1427
  };
1428
+ function checkCredentialMix(tls) {
1429
+ if (typeof tls !== "object" || tls.pfx === void 0) return;
1430
+ if (tls.cert !== void 0 || tls.key !== void 0) {
1431
+ throw new MllpTlsConfigurationError(MLLP_TLS_CREDENTIAL_CONFLICT);
1432
+ }
1433
+ }
1434
+ function checkPfx(pfx, passphrase) {
1435
+ if (pfx === void 0) return;
1436
+ try {
1437
+ tls.createSecureContext({ pfx, passphrase });
1438
+ } catch (err) {
1439
+ throw new MllpTlsConfigurationError(MLLP_TLS_PFX_REJECTED, { cause: err });
1440
+ }
1441
+ }
1376
1442
 
1377
1443
  // src/internal/control-id.ts
1378
1444
  var ASCII_M = 77;
@@ -1611,6 +1677,9 @@ function trimSpaces(value) {
1611
1677
  while (end > start && value.charAt(end - 1) === SPACE) end--;
1612
1678
  return value.substring(start, end);
1613
1679
  }
1680
+ function readConditionField(raw, delimiters) {
1681
+ return readTableField(raw, delimiters, TABLE_0155);
1682
+ }
1614
1683
  function readTableField(raw, delimiters, table) {
1615
1684
  if (raw === void 0) return { kind: "null", byteLength: 0 };
1616
1685
  const byteLength = raw.length;
@@ -1772,6 +1841,18 @@ var MllpServer = class extends events.EventEmitter {
1772
1841
  _host = null;
1773
1842
  _acceptedTotal = 0;
1774
1843
  _closedTotal = 0;
1844
+ /**
1845
+ * Sockets accepted and not yet closed, counted only when {@link ServerOptions.maxConnections} is
1846
+ * set: the number the cap is compared against.
1847
+ */
1848
+ _openSockets = 0;
1849
+ /** Sockets the connection cap closed at accept, so a runtime's report of them is recognised. */
1850
+ _closedAtAccept = /* @__PURE__ */ new WeakSet();
1851
+ /**
1852
+ * For each socket the connection cap counted, what gives its place back. Released once, however
1853
+ * many times it is called.
1854
+ */
1855
+ _capRelease = /* @__PURE__ */ new WeakMap();
1775
1856
  /** Count of `'tlsClientError'` events since listen(). */
1776
1857
  _tlsClientErrorsTotal = 0;
1777
1858
  /**
@@ -1798,11 +1879,17 @@ var MllpServer = class extends events.EventEmitter {
1798
1879
  "ServerOptions.maxConnections must be a positive integer, or left unset for no cap"
1799
1880
  );
1800
1881
  }
1882
+ const tlsInput = opts.tls;
1883
+ checkCredentialMix(tlsInput);
1884
+ if (tlsInput !== void 0 && tlsInput.pfx === void 0 && (tlsInput.cert === void 0 || tlsInput.key === void 0)) {
1885
+ throw new TypeError("ServerOptions.tls needs cert and key, or pfx");
1886
+ }
1801
1887
  this._opts = opts;
1802
1888
  this._isTls = opts.tls !== void 0;
1803
1889
  let cipherPolicy = null;
1804
1890
  if (opts.tls !== void 0) {
1805
1891
  try {
1892
+ checkPfx(opts.tls.pfx, opts.tls.passphrase);
1806
1893
  cipherPolicy = resolveTlsCipherPolicy(opts.tls, "server");
1807
1894
  } catch (err) {
1808
1895
  if (!(err instanceof MllpTlsConfigurationError)) throw err;
@@ -1817,6 +1904,7 @@ var MllpServer = class extends events.EventEmitter {
1817
1904
  const tlsServer = tls.createServer({
1818
1905
  cert: tlsOpts.cert,
1819
1906
  key: tlsOpts.key,
1907
+ pfx: tlsOpts.pfx,
1820
1908
  ...tlsOpts.ca !== void 0 ? { ca: tlsOpts.ca } : {},
1821
1909
  ...tlsOpts.passphrase !== void 0 ? { passphrase: tlsOpts.passphrase } : {},
1822
1910
  minVersion: tlsOpts.minVersion ?? "TLSv1.2",
@@ -1830,6 +1918,7 @@ var MllpServer = class extends events.EventEmitter {
1830
1918
  this._onSocketAccepted(socket);
1831
1919
  });
1832
1920
  tlsServer.on("tlsClientError", (err, socket) => {
1921
+ if (this._closedAtAccept.has(socket)) return;
1833
1922
  this._tlsClientErrorsTotal += 1;
1834
1923
  const nodeErr = err;
1835
1924
  const event = Object.freeze({
@@ -1854,26 +1943,67 @@ var MllpServer = class extends events.EventEmitter {
1854
1943
  this.emit("error", err);
1855
1944
  }
1856
1945
  });
1857
- if (maxConnections !== void 0) {
1858
- this._netServer.maxConnections = maxConnections;
1859
- this._netServer.on("drop", (data) => {
1860
- this._onConnectionOverCap(maxConnections, data);
1861
- });
1862
- }
1946
+ if (maxConnections !== void 0) this._gateConnections(maxConnections);
1947
+ }
1948
+ /**
1949
+ * Enforce {@link ServerOptions.maxConnections} by counting sockets here, at accept.
1950
+ *
1951
+ * WHY NOT THE LISTENER'S OWN `maxConnections`. Node's `net.Server` enforces a cap of its own and
1952
+ * reports each refusal on `'drop'`, but that report is the runtime's to make, and Deno's
1953
+ * `node:net` closes the socket without emitting `'drop'` (measured: Deno 2.9.8), so the cap held
1954
+ * and `'connectionRejected'` never fired. Counting here makes the cap and its event a property of
1955
+ * this package on every runtime.
1956
+ *
1957
+ * The gate sits IN FRONT of every `'connection'` listener the server already has, and replaces
1958
+ * them: for a plaintext server that is this class's own accept handler, and for a TLS server it
1959
+ * is the runtime's, which wraps the raw socket and starts the handshake. An over-cap socket is
1960
+ * destroyed before either runs, so it never becomes a `Connection`, costs no handshake, and is
1961
+ * not a `'tlsClientError'`. The count is of open sockets, the number that bounds file
1962
+ * descriptors: a socket counts from accept until its `'close'`, handshake in flight included.
1963
+ *
1964
+ * @param maxConnections - The validated cap.
1965
+ */
1966
+ _gateConnections(maxConnections) {
1967
+ const server = this._netServer;
1968
+ const downstream = server.listeners("connection");
1969
+ server.removeAllListeners("connection");
1970
+ server.on("connection", (socket) => {
1971
+ if (this._openSockets >= maxConnections) {
1972
+ const remoteAddress = socket.remoteAddress ?? null;
1973
+ const remotePort = socket.remotePort ?? null;
1974
+ this._closedAtAccept.add(socket);
1975
+ socket.destroy();
1976
+ this._onConnectionOverCap(maxConnections, remoteAddress, remotePort);
1977
+ return;
1978
+ }
1979
+ this._openSockets += 1;
1980
+ let released = false;
1981
+ const release = () => {
1982
+ if (released) return;
1983
+ released = true;
1984
+ this._openSockets -= 1;
1985
+ };
1986
+ this._capRelease.set(socket, release);
1987
+ try {
1988
+ for (const listener of downstream) listener.call(server, socket);
1989
+ } finally {
1990
+ socket.once("close", release);
1991
+ }
1992
+ });
1863
1993
  }
1864
1994
  /**
1865
- * Report a connection the listener closed at accept because the cap was full.
1995
+ * Report a connection closed at accept because the cap was full.
1866
1996
  *
1867
- * Contained: this runs inside the listener's own 'drop' callback, so a throwing subscriber would
1868
- * otherwise unwind into the accept path. The throw is surfaced on 'error' instead.
1997
+ * Contained: this runs inside the listener's own 'connection' callback, so a throwing subscriber
1998
+ * would otherwise unwind into the accept path. The throw is surfaced on 'error' instead.
1869
1999
  */
1870
- _onConnectionOverCap(maxConnections, data) {
2000
+ _onConnectionOverCap(maxConnections, remoteAddress, remotePort) {
1871
2001
  const event = Object.freeze({
1872
2002
  code: MLLP_CONNECTION_LIMIT_REACHED,
1873
2003
  message: CONNECTION_LIMIT_MESSAGE,
1874
2004
  maxConnections,
1875
- remoteAddress: data?.remoteAddress ?? null,
1876
- remotePort: data?.remotePort ?? null,
2005
+ remoteAddress,
2006
+ remotePort,
1877
2007
  timestamp: /* @__PURE__ */ new Date()
1878
2008
  });
1879
2009
  this._emitContained("connectionRejected", event);
@@ -2243,6 +2373,7 @@ var MllpServer = class extends events.EventEmitter {
2243
2373
  if (this._opts.keepaliveIntervalMs !== void 0) {
2244
2374
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
2245
2375
  }
2376
+ socket.setNoDelay(this._opts.noDelay !== false);
2246
2377
  const transport = this._isTls ? new TlsTransport(socket) : new NetTransport(socket);
2247
2378
  const mergedFraming = {
2248
2379
  ...SERVER_DEFAULT_FRAMING,
@@ -2250,6 +2381,8 @@ var MllpServer = class extends events.EventEmitter {
2250
2381
  };
2251
2382
  const connOpts = this._opts.onWarning !== void 0 ? { transport, framing: mergedFraming, onWarning: this._opts.onWarning } : { transport, framing: mergedFraming };
2252
2383
  const conn = new Connection(connOpts);
2384
+ const release = this._capRelease.get(socket);
2385
+ if (release !== void 0) socket.once("close", release);
2253
2386
  conn.beforeClose = () => Promise.resolve();
2254
2387
  conn.on("error", (errEvent) => {
2255
2388
  this._emitErrorIfListened(errEvent);
@@ -2589,6 +2722,24 @@ async function createStarterServer(opts) {
2589
2722
  return server;
2590
2723
  }
2591
2724
 
2725
+ // src/server/ack-code.ts
2726
+ function selectAckCode(input) {
2727
+ const { outcome } = input;
2728
+ if (outcome !== "AA" && outcome !== "AE" && outcome !== "AR") {
2729
+ throw new RangeError("selectAckCode: outcome must be one of AA, AE or AR");
2730
+ }
2731
+ const delimiters = delimitersFrom(input.encodingCharacters ?? "^~\\&");
2732
+ const accept = readConditionField(input.msh15, delimiters);
2733
+ const application = readConditionField(input.msh16, delimiters);
2734
+ return Object.freeze({
2735
+ code: acceptAckRequested(accept, outcome) ? acceptModeCounterpart(outcome) : outcome,
2736
+ mode: accept.kind === "null" && application.kind === "null" ? "original" : "enhanced",
2737
+ applicationAckRequested: application.kind !== "code" || acceptAckRequested(application, outcome),
2738
+ acceptTypeUnrecognised: accept.kind === "unrecognised",
2739
+ applicationTypeUnrecognised: application.kind === "unrecognised"
2740
+ });
2741
+ }
2742
+
2592
2743
  // src/client/correlator.ts
2593
2744
  var Correlator = class {
2594
2745
  _opts;
@@ -2658,8 +2809,11 @@ var Correlator = class {
2658
2809
  * `twoPhase` is the enhanced-mode state for a send being correlated by control ID.
2659
2810
  * Omitting it (or passing `null`) is what every other send does, and such an entry is
2660
2811
  * settled by the first acknowledgement matched to it, exactly as before.
2812
+ *
2813
+ * `ackTimeoutMs` is this send's own bound on the wait for its acknowledgement. Omitting it
2814
+ * gives the entry the correlator-wide `ackTimeoutMs`.
2661
2815
  */
2662
- enqueue(frame, controlIdOrNull, resolve, reject, twoPhase = null) {
2816
+ enqueue(frame, controlIdOrNull, resolve, reject, twoPhase = null, ackTimeoutMs) {
2663
2817
  if (this._pending.size >= this._opts.maxInFlight) return null;
2664
2818
  const key = this._opts.mode === "controlId" ? controlIdOrNull ?? `__seq-${++this._sendSeq}` : ++this._sendSeq;
2665
2819
  const entry = {
@@ -2668,6 +2822,7 @@ var Correlator = class {
2668
2822
  controlId: controlIdOrNull,
2669
2823
  byteCount: frame.length,
2670
2824
  sentAt: null,
2825
+ ackTimeoutMs: ackTimeoutMs ?? this._opts.ackTimeoutMs,
2671
2826
  resolve,
2672
2827
  reject,
2673
2828
  twoPhase
@@ -2844,7 +2999,7 @@ var Correlator = class {
2844
2999
  return null;
2845
3000
  }
2846
3001
  /**
2847
- * Sweep live entries; expire those past `sentAt + ackTimeoutMs`.
3002
+ * Sweep live entries; expire those past `sentAt` plus their own `ackTimeoutMs`.
2848
3003
  * Fires `onTimeout(entry, elapsedMs)`; entries move to graveyard.
2849
3004
  * Driven externally by `MllpClient`'s periodic sweep tick, Correlator
2850
3005
  * itself owns no timers.
@@ -2856,7 +3011,6 @@ var Correlator = class {
2856
3011
  */
2857
3012
  expireDue(now) {
2858
3013
  const t = now ?? this._opts.now();
2859
- const ackTimeoutMs = this._opts.ackTimeoutMs;
2860
3014
  for (const [key, entry] of this._pending) {
2861
3015
  if (entry.sentAt === null) continue;
2862
3016
  const twoPhase = entry.twoPhase;
@@ -2874,7 +3028,7 @@ var Correlator = class {
2874
3028
  }
2875
3029
  continue;
2876
3030
  }
2877
- if (entry.sentAt + ackTimeoutMs <= t) {
3031
+ if (entry.sentAt + entry.ackTimeoutMs <= t) {
2878
3032
  const elapsed = t - entry.sentAt;
2879
3033
  this._removeExpired(key, entry);
2880
3034
  if (twoPhase !== null) {
@@ -3321,6 +3475,15 @@ var MllpClient = class extends events.EventEmitter {
3321
3475
  _connectSignal;
3322
3476
  /** Set when close()/destroy()/abort fires; reconnect handler short-circuits. */
3323
3477
  _userClosed = false;
3478
+ /**
3479
+ * The reason passed to the `destroy(reason)` that closed a connection still connecting, `null`
3480
+ * otherwise. The socket hands it back on `'error'`, and `connect()` compares by identity so the
3481
+ * caller's own reason is carried as the cause and never sorted into a TLS `connectionCause`.
3482
+ * Only the call that reaches the socket records it: a later `destroy()` finds the connection
3483
+ * already CLOSED and leaves it alone. Cleared once matched and at the start of `connect()`, so
3484
+ * the client does not keep the caller's object alive.
3485
+ */
3486
+ _destroyReason = null;
3324
3487
  /**
3325
3488
  * Sends parked inside the client with nothing written for them. See {@link ParkedSend}.
3326
3489
  * Every entry removes itself the moment its own wait ends, however it ends.
@@ -3383,6 +3546,7 @@ var MllpClient = class extends events.EventEmitter {
3383
3546
  "ClientOptions.connectTimeoutMs must be an integer from 1 to 2147483647, or left unset for no bound"
3384
3547
  );
3385
3548
  }
3549
+ checkCredentialMix(opts.tls);
3386
3550
  this._opts = opts;
3387
3551
  this._ackTimeoutMs = opts.ackTimeoutMs ?? 3e4;
3388
3552
  this._applicationAckTimeoutMs = opts.applicationAckTimeoutMs;
@@ -3429,10 +3593,22 @@ var MllpClient = class extends events.EventEmitter {
3429
3593
  * - `MllpConnectionError({ phase: 'connect', connectionCause: 'connect-timeout' })` if
3430
3594
  * {@link ClientOptions.connectTimeoutMs} is set and the TCP connect, or the TLS handshake
3431
3595
  * after it, did not complete in time. The socket is destroyed; nothing was written.
3596
+ * - `MllpConnectionError({ phase: 'connect' })` if {@link MllpClient.destroy} is called while
3597
+ * `connect()` is still connecting, over TCP or TLS, before or during the handshake. Its
3598
+ * `cause` is the reason passed to `destroy(reason)`, as it is, and its message is that
3599
+ * reason's; with no reason the cause is an `Error` whose message is `closed before connect`,
3600
+ * the same as for any socket that closes before connecting with no error. It carries no
3601
+ * `connectionCause` either way: a reason is the caller's own, so one whose message or `code`
3602
+ * reads like a TLS failure (`alert`, `ERR_SSL_*`, `EPROTO`, a certificate code) is never
3603
+ * sorted into `'tls-handshake'` or `'tls-verify'`. The first `destroy()` decides: a second
3604
+ * call before `connect()` settles, with a reason or without one, changes nothing.
3432
3605
  * - `MllpTlsConfigurationError` if the configured cipher-suite list cannot be
3433
- * honoured (the runtime rejects it, or `atnaTransportSecurity` and `ciphers`
3434
- * both declare one). Raised **before** a socket is opened, so nothing is left
3435
- * connected; identify it by `instanceof` plus its stable `code`.
3606
+ * honoured (the runtime rejects it, the runtime does not enforce cipher lists
3607
+ * at all, or `atnaTransportSecurity` and `ciphers` both declare one). Raised
3608
+ * **before** a socket is opened, so nothing is left connected; identify it by
3609
+ * `instanceof` plus its stable `code`.
3610
+ * - `MllpTlsConfigurationError` with `MLLP_TLS_PFX_REJECTED` if `tls.pfx` cannot be loaded
3611
+ * with `tls.passphrase` (see {@link TlsOptions.pfx}), also before a socket is opened.
3436
3612
  *
3437
3613
  * **Dual failure signal on initial connect:** the Connection's transport
3438
3614
  * error handler is attached before this promise's own error listener, so a
@@ -3473,12 +3649,14 @@ var MllpClient = class extends events.EventEmitter {
3473
3649
  if (signal !== void 0) {
3474
3650
  this._captureConnectSignal(signal);
3475
3651
  }
3652
+ this._destroyReason = null;
3476
3653
  return new Promise((resolve, reject) => {
3477
3654
  let aborted = false;
3478
3655
  const { socket, transport } = this._createSocketAndTransport();
3479
3656
  if (this._opts.keepaliveIntervalMs !== void 0) {
3480
3657
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
3481
3658
  }
3659
+ socket.setNoDelay(this._opts.noDelay !== false);
3482
3660
  this._socket = socket;
3483
3661
  const connOpts = this._opts.framing !== void 0 ? { transport, framing: this._opts.framing } : { transport };
3484
3662
  if (this._opts.drainTimeoutMs !== void 0) {
@@ -3494,6 +3672,7 @@ var MllpClient = class extends events.EventEmitter {
3494
3672
  }
3495
3673
  socket.removeListener(connectEventName, onSocketConnect);
3496
3674
  socket.removeListener("error", onSocketError);
3675
+ socket.removeListener("close", onSocketClose);
3497
3676
  };
3498
3677
  const abortHandler = () => {
3499
3678
  aborted = true;
@@ -3518,13 +3697,28 @@ var MllpClient = class extends events.EventEmitter {
3518
3697
  const onSocketError = (err) => {
3519
3698
  if (aborted) return;
3520
3699
  cleanup();
3700
+ if (err === this._destroyReason) {
3701
+ this._destroyReason = null;
3702
+ reject(new MllpConnectionError(err.message, { cause: err, phase: "connect" }));
3703
+ return;
3704
+ }
3521
3705
  reject(this._wrapConnectError(err, "connect"));
3522
3706
  };
3707
+ const onSocketClose = () => {
3708
+ cleanup();
3709
+ reject(
3710
+ new MllpConnectionError("connection closed before it was established", {
3711
+ cause: new Error("closed before connect"),
3712
+ phase: "connect"
3713
+ })
3714
+ );
3715
+ };
3523
3716
  if (signal !== void 0) {
3524
3717
  signal.addEventListener("abort", abortHandler, { once: true });
3525
3718
  }
3526
3719
  socket.once(connectEventName, onSocketConnect);
3527
3720
  socket.once("error", onSocketError);
3721
+ socket.once("close", onSocketClose);
3528
3722
  });
3529
3723
  }
3530
3724
  /**
@@ -3547,6 +3741,7 @@ var MllpClient = class extends events.EventEmitter {
3547
3741
  }
3548
3742
  const tlsOpts = tlsOpt === true ? {} : tlsOpt;
3549
3743
  const cipherPolicy = resolveTlsCipherPolicy(tlsOpts, "client");
3744
+ checkPfx(tlsOpts.pfx, tlsOpts.passphrase);
3550
3745
  const socket = tls.connect({
3551
3746
  host: this._opts.host,
3552
3747
  port: this._opts.port,
@@ -3555,6 +3750,7 @@ var MllpClient = class extends events.EventEmitter {
3555
3750
  ...tlsOpts.cert !== void 0 ? { cert: tlsOpts.cert } : {},
3556
3751
  ...tlsOpts.key !== void 0 ? { key: tlsOpts.key } : {},
3557
3752
  ...tlsOpts.passphrase !== void 0 ? { passphrase: tlsOpts.passphrase } : {},
3753
+ pfx: tlsOpts.pfx,
3558
3754
  minVersion: tlsOpts.minVersion ?? "TLSv1.2",
3559
3755
  ...tlsOpts.maxVersion !== void 0 ? { maxVersion: tlsOpts.maxVersion } : {},
3560
3756
  ...cipherPolicy,
@@ -4086,6 +4282,7 @@ var MllpClient = class extends events.EventEmitter {
4086
4282
  if (this._opts.keepaliveIntervalMs !== void 0) {
4087
4283
  socket.setKeepAlive(true, this._opts.keepaliveIntervalMs);
4088
4284
  }
4285
+ socket.setNoDelay(this._opts.noDelay !== false);
4089
4286
  this._socket = socket;
4090
4287
  const connOpts = this._opts.framing !== void 0 ? { transport, framing: this._opts.framing } : { transport };
4091
4288
  if (this._opts.drainTimeoutMs !== void 0) {
@@ -4274,8 +4471,8 @@ var MllpClient = class extends events.EventEmitter {
4274
4471
  *
4275
4472
  * Resolves with the ACK Buffer (framing stripped). Rejects with:
4276
4473
  * - `DOMException('Aborted', 'AbortError')` if `signal` aborts before the ACK.
4277
- * - `MllpTimeoutError` if no ACK arrives within `ackTimeoutMs`.
4278
- * The clock starts at the underlying `write()` flush callback, NOT at
4474
+ * - `MllpTimeoutError` if no ACK arrives within `ackTimeoutMs` (this send's own, else the
4475
+ * client's). The clock starts at the underlying `write()` flush callback, NOT at
4279
4476
  * the `send()` call.
4280
4477
  * - `MllpConnectionError({ phase: 'send' })` if the client is not connected.
4281
4478
  *
@@ -4304,7 +4501,10 @@ var MllpClient = class extends events.EventEmitter {
4304
4501
  *
4305
4502
  * @param payload Raw bytes; MLLP framing is added internally via `encodeFrame`.
4306
4503
  * @param opts.signal AbortSignal, aborting cancels the ACK wait.
4307
- * @param opts.ackTimeoutMs Per-send override of the backpressure wait budget.
4504
+ * @param opts.ackTimeoutMs This send's bound on the wait for its acknowledgement, from the
4505
+ * moment its bytes are flushed, in place of the client's `ackTimeoutMs`. Under
4506
+ * `onBackpressure: "wait"` it also bounds the wait for queue room, and the
4507
+ * acknowledgement wait then starts afresh once the send is written.
4308
4508
  * @param opts.applicationAckTimeoutMs Per-send override of the second wait's bound.
4309
4509
  * @param opts.onCommitAck Called with the commit disposition when the peer commits the
4310
4510
  * message ahead of its application acknowledgement. See {@link CommitAckReport}.
@@ -4359,21 +4559,34 @@ var MllpClient = class extends events.EventEmitter {
4359
4559
  opts
4360
4560
  );
4361
4561
  }
4562
+ const sendAckTimeoutMs = opts?.ackTimeoutMs;
4362
4563
  return new Promise((resolve, reject) => {
4363
4564
  let abortListener = null;
4364
- const wrappedResolve = (ack) => {
4565
+ let ackDeadline;
4566
+ let settled = false;
4567
+ const settle = () => {
4568
+ settled = true;
4365
4569
  if (signal !== void 0 && abortListener !== null) {
4366
4570
  signal.removeEventListener("abort", abortListener);
4367
4571
  }
4572
+ clearTimeout(ackDeadline);
4573
+ };
4574
+ const wrappedResolve = (ack) => {
4575
+ settle();
4368
4576
  resolve(ack);
4369
4577
  };
4370
4578
  const wrappedReject = (err) => {
4371
- if (signal !== void 0 && abortListener !== null) {
4372
- signal.removeEventListener("abort", abortListener);
4373
- }
4579
+ settle();
4374
4580
  reject(err);
4375
4581
  };
4376
- const key = correlator.enqueue(frame, controlId, wrappedResolve, wrappedReject, twoPhase);
4582
+ const key = correlator.enqueue(
4583
+ frame,
4584
+ controlId,
4585
+ wrappedResolve,
4586
+ wrappedReject,
4587
+ twoPhase,
4588
+ sendAckTimeoutMs
4589
+ );
4377
4590
  if (key === null) {
4378
4591
  const parked = { cancel: () => void 0 };
4379
4592
  const neverDelivered = () => new MllpNeverDeliveredError({
@@ -4415,6 +4628,12 @@ var MllpClient = class extends events.EventEmitter {
4415
4628
  }
4416
4629
  conn.send(frame);
4417
4630
  correlator.markFlushed(key, Date.now());
4631
+ if (sendAckTimeoutMs !== void 0 && !settled) {
4632
+ ackDeadline = setTimeout(() => {
4633
+ correlator.expireDue();
4634
+ }, sendAckTimeoutMs);
4635
+ ackDeadline.unref();
4636
+ }
4418
4637
  this._sentTotal += 1;
4419
4638
  });
4420
4639
  }
@@ -4811,6 +5030,12 @@ var MllpClient = class extends events.EventEmitter {
4811
5030
  * ever written for it; that is a statement about the bytes, not about how the client was
4812
5031
  * shut down, so it holds on this path too.
4813
5032
  *
5033
+ * A {@link MllpClient.connect} still connecting rejects with an `MllpConnectionError` whose
5034
+ * `phase` is `'connect'` and no `connectionCause`. Its `cause` is `reason` when one is given,
5035
+ * never classified as a TLS failure whatever its message or `code`, and otherwise an `Error`
5036
+ * whose message is `closed before connect`. Only the first call reaches the socket, so a
5037
+ * second `destroy()` before `connect()` settles, with or without a reason, changes nothing.
5038
+ *
4814
5039
  * @example
4815
5040
  * ```typescript
4816
5041
  * client.destroy(new Error('shutting down'));
@@ -4831,6 +5056,7 @@ var MllpClient = class extends events.EventEmitter {
4831
5056
  this._teardownCorrelator(teardownReason);
4832
5057
  const conn = this._connection;
4833
5058
  if (conn === null) return;
5059
+ if (conn.state === "CONNECTING") this._destroyReason = reason ?? null;
4834
5060
  conn.destroy(reason);
4835
5061
  }
4836
5062
  /**
@@ -4911,6 +5137,7 @@ async function createStarterClient(opts) {
4911
5137
  ...opts.retryStrategy !== void 0 ? { retryStrategy: opts.retryStrategy } : {},
4912
5138
  ...opts.keepaliveIntervalMs !== void 0 ? { keepaliveIntervalMs: opts.keepaliveIntervalMs } : {},
4913
5139
  ...opts.deadPeerTimeoutMs !== void 0 ? { deadPeerTimeoutMs: opts.deadPeerTimeoutMs } : {},
5140
+ noDelay: opts.noDelay !== false,
4914
5141
  ...opts.connectTimeoutMs !== void 0 ? { connectTimeoutMs: opts.connectTimeoutMs } : {},
4915
5142
  ...opts.tls !== void 0 ? { tls: opts.tls } : {}
4916
5143
  };
@@ -5232,7 +5459,7 @@ async function runDifferential(options = {}) {
5232
5459
  }
5233
5460
 
5234
5461
  // src/index.ts
5235
- var VERSION = "0.1.11";
5462
+ var VERSION = "0.1.12";
5236
5463
 
5237
5464
  exports.ATNA_CIPHER_LIST = ATNA_CIPHER_LIST;
5238
5465
  exports.ATNA_CIPHER_SUITES = ATNA_CIPHER_SUITES;
@@ -5242,8 +5469,12 @@ exports.MLLP_BIND_ALL_INTERFACES = MLLP_BIND_ALL_INTERFACES;
5242
5469
  exports.MLLP_CONNECTION_LIMIT_REACHED = MLLP_CONNECTION_LIMIT_REACHED;
5243
5470
  exports.MLLP_DIFF_PEER_UNPARSEABLE = MLLP_DIFF_PEER_UNPARSEABLE;
5244
5471
  exports.MLLP_TLS_CIPHER_LIST_REJECTED = MLLP_TLS_CIPHER_LIST_REJECTED;
5472
+ exports.MLLP_TLS_CIPHER_LIST_UNENFORCEABLE = MLLP_TLS_CIPHER_LIST_UNENFORCEABLE;
5245
5473
  exports.MLLP_TLS_CIPHER_OPTION_CONFLICT = MLLP_TLS_CIPHER_OPTION_CONFLICT;
5474
+ exports.MLLP_TLS_CREDENTIAL_CONFLICT = MLLP_TLS_CREDENTIAL_CONFLICT;
5246
5475
  exports.MLLP_TLS_DH_PARAMETERS_REJECTED = MLLP_TLS_DH_PARAMETERS_REJECTED;
5476
+ exports.MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE = MLLP_TLS_DH_PARAMETERS_UNENFORCEABLE;
5477
+ exports.MLLP_TLS_PFX_REJECTED = MLLP_TLS_PFX_REJECTED;
5247
5478
  exports.MLLP_TLS_VERIFY_DISABLED = MLLP_TLS_VERIFY_DISABLED;
5248
5479
  exports.MllpAckError = MllpAckError;
5249
5480
  exports.MllpApplicationAckError = MllpApplicationAckError;
@@ -5283,6 +5514,7 @@ exports.resolveDifferentialPeer = resolveDifferentialPeer;
5283
5514
  exports.resolveNackCode = resolveNackCode;
5284
5515
  exports.resolveTlsCipherPolicy = resolveTlsCipherPolicy;
5285
5516
  exports.runDifferential = runDifferential;
5517
+ exports.selectAckCode = selectAckCode;
5286
5518
  exports.tlsConfigurationMessage = tlsConfigurationMessage;
5287
5519
  //# sourceMappingURL=index.cjs.map
5288
5520
  //# sourceMappingURL=index.cjs.map