@bymax-one/nest-realtime 1.2.2 → 1.2.4

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/CHANGELOG.md CHANGED
@@ -7,6 +7,54 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.4] - 2026-11-01
11
+
12
+ ### Fixed
13
+
14
+ - **A rejection that is not an `Error` no longer makes the handler reporting it fail.** Handlers
15
+ that log a failure read `.message` from whatever was thrown, so a promise that rejected with
16
+ `null` or `undefined`, or with an object that has no prototype, made the `catch` itself throw. In
17
+ a fire-and-forget `.catch` that surfaced as an unhandled rejection. They now describe the reason
18
+ through one function that never throws, and a test fails if a source file goes back to the old
19
+ patterns. The text logged for an `Error` or a string reason is unchanged; a plain object with a
20
+ string `message` now logs that message instead of `[object Object]`.
21
+
22
+ ### Documentation
23
+
24
+ - A local benchmark (`pnpm benchmark`, in `scripts/benchmark/`, not a CI gate) measures connect
25
+ latency, fan-out latency for 1, 100 and 1000 clients, cross-instance latency through Redis, memory
26
+ per idle connection and Redis connections per instance, and writes its tables as Markdown. The
27
+ first results, with the machine, versions and run-to-run noise, are in
28
+ `docs/benchmark_results_2026-10-31.md`.
29
+
30
+ ## [1.2.3] - 2026-10-31
31
+
32
+ **Apply before upgrading, if you set `websocket.redisAdapter`:** make sure `@socket.io/redis-adapter`
33
+ is installed and that `pubClient` is an ioredis client. 1.2.2 and earlier logged one error and served a single
34
+ instance when the adapter could not be installed, and every ESM consumer was in that state, so
35
+ WebSocket events did not cross instances. The boot now fails with `REALTIME_REDIS_ADAPTER_FAILED`
36
+ instead. A Redis that is merely unreachable does not fail the boot.
37
+
38
+ ### Fixed
39
+
40
+ - **The WebSocket Redis adapter now installs in the ES module build.** The adapter loaded
41
+ `@socket.io/redis-adapter` with a bare `require`, which an ES module does not have, so for every
42
+ consumer importing the package as ESM the load threw, one error line was logged, and the server
43
+ stayed single-instance: an emit on one instance never reached a client on another. Measured on the
44
+ published bundle with two instances and a real Redis, 0 of 5000 messages crossed; with the adapter
45
+ installed, 5000 of 5000 did. CommonJS consumers were not affected. The ESM bundle now declares a
46
+ `require` that resolves from the package, and still loads when a consumer's bundler re-bundles it
47
+ into CommonJS, where `import.meta.url` is undefined. `pnpm size` fails when an ESM bundle calls a
48
+ `require` it does not declare, and `pnpm check:runtime` boots the packed tarball in ESM, in
49
+ CommonJS and re-bundled into CommonJS, and asserts the adapter registers in each.
50
+
51
+ - **A WebSocket authenticator that rejects with a value that is not an `Error` no longer leaves the
52
+ socket connected.** The catch in `handleConnection` read `.message` from whatever was thrown, so a
53
+ rejection with `null` or `undefined` made the catch itself throw before `socket.disconnect(true)`
54
+ ran. The reason is now logged as `String(reason)` when it is not an `Error`, and the socket is
55
+ always closed. The handshake middleware already logged it this way; this is the path that runs when
56
+ the gateway is used without it.
57
+
10
58
  ## [1.2.2] - 2026-10-31
11
59
 
12
60
  ### Fixed
@@ -177,7 +225,7 @@ were routed to a tenant that differed by transport.
177
225
  **Shipped as a minor, and two entries below are strictly speaking breaking.** Both are called
178
226
  out as such rather than hidden: removing the `service` option is a compile error for anyone who
179
227
  passed it, and the new required key on `ConnectionEventMeta` is a compile error for anyone who
180
- *constructs* one. Neither changes runtime behaviour for any working configuration — `service`
228
+ _constructs_ one. Neither changes runtime behaviour for any working configuration — `service`
181
229
  was never read by anything, and reading the meta (what a hook does) is unaffected. The precedent
182
230
  is 1.1.1, which added a required `roles` key to the same type and shipped as a patch. The third
183
231
  item, the new bootstrap throw on a disagreeing SSE endpoint, replaces a silent misconfiguration
@@ -235,7 +283,7 @@ configured.
235
283
  channel, and it is the reason the field was declared in the first place.
236
284
 
237
285
  **This adds a required key** to `ConnectionEventMeta`, exactly as `roles` did in 1.1.1.
238
- Reading the meta is unaffected, which is what a hook does; code that *constructs* one
286
+ Reading the meta is unaffected, which is what a hook does; code that _constructs_ one
239
287
  (typically a test fixture) must now supply `metadata`. `undefined` stays meaningful — an
240
288
  authenticator that returns no bag is not one that returns an empty object. Like `roles`, it is
241
289
  a connect-time snapshot that `revalidate` does not refresh, and the library never reads a key.
@@ -570,7 +618,9 @@ First published release.
570
618
  rather than by the manual sweep that raised the NestJS floors — that sweep
571
619
  asked about NestJS and never put the same question to the other ten peers.
572
620
 
573
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.2...HEAD
621
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.4...HEAD
622
+ [1.2.4]: https://github.com/bymaxone/nest-realtime/compare/v1.2.3...v1.2.4
623
+ [1.2.3]: https://github.com/bymaxone/nest-realtime/compare/v1.2.2...v1.2.3
574
624
  [1.2.2]: https://github.com/bymaxone/nest-realtime/compare/v1.2.1...v1.2.2
575
625
  [1.2.1]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...v1.2.1
576
626
  [1.2.0]: https://github.com/bymaxone/nest-realtime/compare/v1.1.2...v1.2.0
package/README.md CHANGED
@@ -342,7 +342,7 @@ bootstrap()
342
342
  > [!IMPORTANT]
343
343
  > The `main.ts` line is not optional. `RealtimeIoAdapter` is what applies `websocket.cors`, `namespace`, `pingIntervalMs`, `pingTimeoutMs`, `maxHttpBufferSize` and `redisAdapter`. Without it those options are ignored, the gateway's own CORS stays closed (`origin: false`) so a browser on another origin cannot connect, and the module logs an error at start-up that names this fix.
344
344
 
345
- With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls `pubClient.duplicate()` for the subscriber; the library never opens its own Redis connection. Socket.IO's polling fallback needs sticky sessions even then — see [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md). On the frontend, a `ws://` or `wss://` `url` selects WebSocket in `RealtimeProvider`. Replay through `Last-Event-ID` and the offline queue are SSE features: a WebSocket connection has neither.
345
+ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls `pubClient.duplicate()` for the subscriber; the library never opens its own Redis connection. If it cannot be installed (the package is missing, the client has no `duplicate()`), the boot fails with `REALTIME_REDIS_ADAPTER_FAILED` instead of serving a single instance; a Redis that is merely unreachable does not fail the boot. Socket.IO's polling fallback needs sticky sessions even then — see [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md). On the frontend, a `ws://` or `wss://` `url` selects WebSocket in `RealtimeProvider`. Replay through `Last-Event-ID` and the offline queue are SSE features: a WebSocket connection has neither.
346
346
 
347
347
  ---
348
348
 
@@ -830,6 +830,7 @@ These names belong to the library. Do not reuse them for application events. The
830
830
  | `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
831
831
  | `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
832
832
  | `REALTIME_PUBSUB_UNAVAILABLE` | Reserved, never raised today: a pub/sub failure is logged |
833
+ | `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
833
834
  | `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
834
835
  | `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
835
836
 
@@ -28,6 +28,7 @@ var REALTIME_ERROR_CODES = {
28
28
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
29
29
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
30
30
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
31
+ REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
31
32
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
32
33
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
33
34
  };
@@ -104,6 +105,18 @@ var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
104
105
  var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
105
106
  var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
106
107
  var DEFAULT_HEARTBEAT_MS = 3e4;
108
+
109
+ // src/server/utils/describe-error.ts
110
+ function describeError(reason) {
111
+ try {
112
+ const message = reason?.message;
113
+ return typeof message === "string" ? message : String(reason);
114
+ } catch {
115
+ return "unprintable error";
116
+ }
117
+ }
118
+
119
+ // src/server/offline-queue/offline-queue-delivery.service.ts
107
120
  var RETRIEVE_LIMIT = 200;
108
121
  exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
109
122
  constructor(storage) {
@@ -130,7 +143,7 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
130
143
  try {
131
144
  events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
132
145
  } catch (err) {
133
- this.logger.warn(`Offline queue retrieve failed: ${err.message}`);
146
+ this.logger.warn(`Offline queue retrieve failed: ${describeError(err)}`);
134
147
  return [];
135
148
  }
136
149
  if (events.length === RETRIEVE_LIMIT) {
@@ -157,7 +170,7 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
157
170
  try {
158
171
  await this.storage.acknowledge(userId, lastId);
159
172
  } catch (err) {
160
- this.logger.warn(`Offline queue acknowledge failed: ${err.message}`);
173
+ this.logger.warn(`Offline queue acknowledge failed: ${describeError(err)}`);
161
174
  }
162
175
  }
163
176
  };
@@ -569,7 +582,7 @@ exports.SseTransport = class SseTransport {
569
582
  ...reason !== void 0 ? { reason } : {}
570
583
  });
571
584
  } catch (error) {
572
- this.logger.error(`onDisconnect hook failed: ${error.message}`);
585
+ this.logger.error(`onDisconnect hook failed: ${describeError(error)}`);
573
586
  }
574
587
  }
575
588
  /** Replay the events a user missed after `lastEventId`. */
@@ -600,7 +613,7 @@ exports.SseTransport = class SseTransport {
600
613
  this.emitToUserLocal(userId, event, data, id);
601
614
  if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
602
615
  void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
603
- (error) => this.logger.warn(`Offline queue append failed: ${error.message}`)
616
+ (error) => this.logger.warn(`Offline queue append failed: ${describeError(error)}`)
604
617
  );
605
618
  }
606
619
  await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
@@ -706,7 +719,7 @@ exports.SseTransport = class SseTransport {
706
719
  try {
707
720
  conn.subject?.next(message);
708
721
  } catch (error) {
709
- this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${error.message}`);
722
+ this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
710
723
  }
711
724
  }
712
725
  /** Publish once to the bus; pub/sub failures never affect the live emit path. */
@@ -714,7 +727,7 @@ exports.SseTransport = class SseTransport {
714
727
  try {
715
728
  await this.pubsub.publish({ ...message, origin: this.instanceId });
716
729
  } catch (error) {
717
- this.logger.warn(`pubsub.publish failed: ${error.message}`);
730
+ this.logger.warn(`pubsub.publish failed: ${describeError(error)}`);
718
731
  }
719
732
  }
720
733
  /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
@@ -848,7 +861,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
848
861
  try {
849
862
  assertIdentityIsNotBlank(resolvedAuth);
850
863
  } catch (err) {
851
- this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
864
+ this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
852
865
  throw new common.InternalServerErrorException();
853
866
  }
854
867
  return resolvedAuth;
@@ -931,9 +944,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
931
944
  return err instanceof common.HttpException ? err : this.serverError(err, what);
932
945
  }
933
946
  serverError(err, what) {
934
- this.logger.error(
935
- `${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
936
- );
947
+ this.logger.error(`${what} \u2014 responding 500: ${describeError(err)}`);
937
948
  return new common.InternalServerErrorException();
938
949
  }
939
950
  async authenticateRequest(req) {
@@ -1030,7 +1041,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
1030
1041
  */
1031
1042
  fireHook(invoke) {
1032
1043
  void Promise.resolve(invoke()).catch((err) => {
1033
- this.logger.warn(`Lifecycle hook failed: ${err.message}`);
1044
+ this.logger.warn(`Lifecycle hook failed: ${describeError(err)}`);
1034
1045
  });
1035
1046
  }
1036
1047
  };
@@ -1264,9 +1275,7 @@ exports.ReauthenticationService = class ReauthenticationService {
1264
1275
  }
1265
1276
  await this.handleFailure(conn);
1266
1277
  } catch (err) {
1267
- this.logger.warn(
1268
- `Reauthentication errored for ${conn.connectionId}: ${err.message}`
1269
- );
1278
+ this.logger.warn(`Reauthentication errored for ${conn.connectionId}: ${describeError(err)}`);
1270
1279
  await this.handleFailure(conn);
1271
1280
  }
1272
1281
  }
@@ -1292,7 +1301,7 @@ exports.ReauthenticationService = class ReauthenticationService {
1292
1301
  connectedAt: conn.connectedAt
1293
1302
  })
1294
1303
  ).catch((err) => {
1295
- this.logger.warn(`onReauthenticationFailed hook failed: ${err.message}`);
1304
+ this.logger.warn(`onReauthenticationFailed hook failed: ${describeError(err)}`);
1296
1305
  });
1297
1306
  await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1298
1307
  }
@@ -1487,7 +1496,7 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
1487
1496
  this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1488
1497
  } catch (err) {
1489
1498
  this.logger.warn(
1490
- `Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1499
+ `Failed to subscribe to pub/sub: ${describeError(err)}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1491
1500
  );
1492
1501
  }
1493
1502
  }
@@ -1496,7 +1505,7 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
1496
1505
  try {
1497
1506
  await this.unsubscribe();
1498
1507
  } catch (err) {
1499
- this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
1508
+ this.logger.warn(`Pub/sub unsubscribe failed: ${describeError(err)}`);
1500
1509
  }
1501
1510
  this.unsubscribe = null;
1502
1511
  }
@@ -1536,7 +1545,7 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
1536
1545
  }
1537
1546
  }
1538
1547
  } catch (err) {
1539
- this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
1548
+ this.logger.warn(`Pub/sub message handling failed: ${describeError(err)}`);
1540
1549
  }
1541
1550
  }
1542
1551
  };
@@ -1821,6 +1830,7 @@ exports.composeForRoot = composeForRoot;
1821
1830
  exports.composeForRootAsync = composeForRootAsync;
1822
1831
  exports.composeRoomId = composeRoomId;
1823
1832
  exports.createSseController = createSseController;
1833
+ exports.describeError = describeError;
1824
1834
  exports.parseCookieHeader = parseCookieHeader;
1825
1835
  exports.resolveAuthTenant = resolveAuthTenant;
1826
1836
  exports.sseWiring = sseWiring;
@@ -1549,6 +1549,13 @@ type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
1549
1549
  */
1550
1550
  declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: string[]): string;
1551
1551
 
1552
+ /**
1553
+ * @fileoverview Printable text for whatever a `catch` or a rejected promise delivered.
1554
+ * @layer utils
1555
+ */
1556
+ /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
1557
+ declare function describeError(reason: unknown): string;
1558
+
1552
1559
  /**
1553
1560
  * @fileoverview Parser turning a raw HTTP `Cookie` header into a plain object.
1554
1561
  * @layer utils
@@ -1663,10 +1670,11 @@ declare const REALTIME_ERROR_CODES: {
1663
1670
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
1664
1671
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
1665
1672
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
1673
+ readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
1666
1674
  readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
1667
1675
  readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
1668
1676
  };
1669
1677
  /** Union of canonical error code values. */
1670
1678
  type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
1671
1679
 
1672
- export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
1680
+ export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, resolveAuthTenant, sseWiring };
@@ -1549,6 +1549,13 @@ type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
1549
1549
  */
1550
1550
  declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: string[]): string;
1551
1551
 
1552
+ /**
1553
+ * @fileoverview Printable text for whatever a `catch` or a rejected promise delivered.
1554
+ * @layer utils
1555
+ */
1556
+ /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
1557
+ declare function describeError(reason: unknown): string;
1558
+
1552
1559
  /**
1553
1560
  * @fileoverview Parser turning a raw HTTP `Cookie` header into a plain object.
1554
1561
  * @layer utils
@@ -1663,10 +1670,11 @@ declare const REALTIME_ERROR_CODES: {
1663
1670
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
1664
1671
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
1665
1672
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
1673
+ readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
1666
1674
  readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
1667
1675
  readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
1668
1676
  };
1669
1677
  /** Union of canonical error code values. */
1670
1678
  type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
1671
1679
 
1672
- export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
1680
+ export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, resolveAuthTenant, sseWiring };
@@ -26,6 +26,7 @@ var REALTIME_ERROR_CODES = {
26
26
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
27
27
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
28
28
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
29
+ REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
29
30
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
30
31
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
31
32
  };
@@ -102,6 +103,18 @@ var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
102
103
  var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
103
104
  var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
104
105
  var DEFAULT_HEARTBEAT_MS = 3e4;
106
+
107
+ // src/server/utils/describe-error.ts
108
+ function describeError(reason) {
109
+ try {
110
+ const message = reason?.message;
111
+ return typeof message === "string" ? message : String(reason);
112
+ } catch {
113
+ return "unprintable error";
114
+ }
115
+ }
116
+
117
+ // src/server/offline-queue/offline-queue-delivery.service.ts
105
118
  var RETRIEVE_LIMIT = 200;
106
119
  var OfflineQueueDeliveryService = class {
107
120
  constructor(storage) {
@@ -128,7 +141,7 @@ var OfflineQueueDeliveryService = class {
128
141
  try {
129
142
  events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
130
143
  } catch (err) {
131
- this.logger.warn(`Offline queue retrieve failed: ${err.message}`);
144
+ this.logger.warn(`Offline queue retrieve failed: ${describeError(err)}`);
132
145
  return [];
133
146
  }
134
147
  if (events.length === RETRIEVE_LIMIT) {
@@ -155,7 +168,7 @@ var OfflineQueueDeliveryService = class {
155
168
  try {
156
169
  await this.storage.acknowledge(userId, lastId);
157
170
  } catch (err) {
158
- this.logger.warn(`Offline queue acknowledge failed: ${err.message}`);
171
+ this.logger.warn(`Offline queue acknowledge failed: ${describeError(err)}`);
159
172
  }
160
173
  }
161
174
  };
@@ -567,7 +580,7 @@ var SseTransport = class {
567
580
  ...reason !== void 0 ? { reason } : {}
568
581
  });
569
582
  } catch (error) {
570
- this.logger.error(`onDisconnect hook failed: ${error.message}`);
583
+ this.logger.error(`onDisconnect hook failed: ${describeError(error)}`);
571
584
  }
572
585
  }
573
586
  /** Replay the events a user missed after `lastEventId`. */
@@ -598,7 +611,7 @@ var SseTransport = class {
598
611
  this.emitToUserLocal(userId, event, data, id);
599
612
  if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
600
613
  void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
601
- (error) => this.logger.warn(`Offline queue append failed: ${error.message}`)
614
+ (error) => this.logger.warn(`Offline queue append failed: ${describeError(error)}`)
602
615
  );
603
616
  }
604
617
  await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
@@ -704,7 +717,7 @@ var SseTransport = class {
704
717
  try {
705
718
  conn.subject?.next(message);
706
719
  } catch (error) {
707
- this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${error.message}`);
720
+ this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
708
721
  }
709
722
  }
710
723
  /** Publish once to the bus; pub/sub failures never affect the live emit path. */
@@ -712,7 +725,7 @@ var SseTransport = class {
712
725
  try {
713
726
  await this.pubsub.publish({ ...message, origin: this.instanceId });
714
727
  } catch (error) {
715
- this.logger.warn(`pubsub.publish failed: ${error.message}`);
728
+ this.logger.warn(`pubsub.publish failed: ${describeError(error)}`);
716
729
  }
717
730
  }
718
731
  /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
@@ -846,7 +859,7 @@ var SseSubscriptionHandler = class {
846
859
  try {
847
860
  assertIdentityIsNotBlank(resolvedAuth);
848
861
  } catch (err) {
849
- this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
862
+ this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
850
863
  throw new InternalServerErrorException();
851
864
  }
852
865
  return resolvedAuth;
@@ -929,9 +942,7 @@ var SseSubscriptionHandler = class {
929
942
  return err instanceof HttpException ? err : this.serverError(err, what);
930
943
  }
931
944
  serverError(err, what) {
932
- this.logger.error(
933
- `${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
934
- );
945
+ this.logger.error(`${what} \u2014 responding 500: ${describeError(err)}`);
935
946
  return new InternalServerErrorException();
936
947
  }
937
948
  async authenticateRequest(req) {
@@ -1028,7 +1039,7 @@ var SseSubscriptionHandler = class {
1028
1039
  */
1029
1040
  fireHook(invoke) {
1030
1041
  void Promise.resolve(invoke()).catch((err) => {
1031
- this.logger.warn(`Lifecycle hook failed: ${err.message}`);
1042
+ this.logger.warn(`Lifecycle hook failed: ${describeError(err)}`);
1032
1043
  });
1033
1044
  }
1034
1045
  };
@@ -1262,9 +1273,7 @@ var ReauthenticationService = class {
1262
1273
  }
1263
1274
  await this.handleFailure(conn);
1264
1275
  } catch (err) {
1265
- this.logger.warn(
1266
- `Reauthentication errored for ${conn.connectionId}: ${err.message}`
1267
- );
1276
+ this.logger.warn(`Reauthentication errored for ${conn.connectionId}: ${describeError(err)}`);
1268
1277
  await this.handleFailure(conn);
1269
1278
  }
1270
1279
  }
@@ -1290,7 +1299,7 @@ var ReauthenticationService = class {
1290
1299
  connectedAt: conn.connectedAt
1291
1300
  })
1292
1301
  ).catch((err) => {
1293
- this.logger.warn(`onReauthenticationFailed hook failed: ${err.message}`);
1302
+ this.logger.warn(`onReauthenticationFailed hook failed: ${describeError(err)}`);
1294
1303
  });
1295
1304
  await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1296
1305
  }
@@ -1485,7 +1494,7 @@ var RealtimePubSubSubscriber = class {
1485
1494
  this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1486
1495
  } catch (err) {
1487
1496
  this.logger.warn(
1488
- `Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1497
+ `Failed to subscribe to pub/sub: ${describeError(err)}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1489
1498
  );
1490
1499
  }
1491
1500
  }
@@ -1494,7 +1503,7 @@ var RealtimePubSubSubscriber = class {
1494
1503
  try {
1495
1504
  await this.unsubscribe();
1496
1505
  } catch (err) {
1497
- this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
1506
+ this.logger.warn(`Pub/sub unsubscribe failed: ${describeError(err)}`);
1498
1507
  }
1499
1508
  this.unsubscribe = null;
1500
1509
  }
@@ -1534,7 +1543,7 @@ var RealtimePubSubSubscriber = class {
1534
1543
  }
1535
1544
  }
1536
1545
  } catch (err) {
1537
- this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
1546
+ this.logger.warn(`Pub/sub message handling failed: ${describeError(err)}`);
1538
1547
  }
1539
1548
  }
1540
1549
  };
@@ -1801,4 +1810,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1801
1810
  }
1802
1811
  };
1803
1812
 
1804
- export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
1813
+ export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, resolveAuthTenant, sseWiring };
@@ -30,6 +30,7 @@ var REALTIME_ERROR_CODES = {
30
30
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
31
31
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
32
32
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
33
+ REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
33
34
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
34
35
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
35
36
  };
@@ -153,6 +153,7 @@ declare const REALTIME_ERROR_CODES: {
153
153
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
154
154
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
155
155
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
156
+ readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
156
157
  readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
157
158
  readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
158
159
  };
@@ -153,6 +153,7 @@ declare const REALTIME_ERROR_CODES: {
153
153
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
154
154
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
155
155
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
156
+ readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
156
157
  readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
157
158
  readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
158
159
  };
@@ -28,6 +28,7 @@ var REALTIME_ERROR_CODES = {
28
28
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
29
29
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
30
30
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
31
+ REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
31
32
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
32
33
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
33
34
  };
@@ -381,9 +381,7 @@ exports.CompositeTransport = class CompositeTransport {
381
381
  const results = await Promise.allSettled(tasks.map((t) => t()));
382
382
  for (const result of results) {
383
383
  if (result.status === "rejected") {
384
- this.logger.warn(
385
- `Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
386
- );
384
+ this.logger.warn(`Composite ${op} partially failed: ${internal.describeError(result.reason)}`);
387
385
  }
388
386
  }
389
387
  }
@@ -429,8 +427,7 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
429
427
  * Create the Socket.IO server with merged WebSocket options.
430
428
  *
431
429
  * When `websocket.redisAdapter.pubClient` is set, installs the
432
- * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
433
- * dep — its absence does not crash the lib).
430
+ * `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
434
431
  */
435
432
  createIOServer(port, opts) {
436
433
  const wsOpts = this.options.websocket ?? {};
@@ -443,17 +440,20 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
443
440
  };
444
441
  const server = super.createIOServer(port, mergedOpts);
445
442
  if (wsOpts.redisAdapter?.pubClient) {
446
- this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
443
+ try {
444
+ this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
445
+ } catch (err) {
446
+ server.close().catch(() => void 0);
447
+ throw err;
448
+ }
447
449
  }
448
450
  realtimeServers.add(server);
449
451
  return server;
450
452
  }
451
453
  /**
452
- * Lazily load and install `@socket.io/redis-adapter`.
453
- *
454
- * Uses a dynamic `require` so the package stays optional — absent peers do
455
- * not crash the lib. A load or install failure is logged and tolerated;
456
- * the lib degrades gracefully to single-instance mode.
454
+ * Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
455
+ * silent single-instance server drops cross-node messages. An unreachable Redis
456
+ * is not one; reconnecting stays with the client.
457
457
  */
458
458
  installRedisAdapter(server, pubClient) {
459
459
  try {
@@ -461,14 +461,16 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
461
461
  const pub = pubClient;
462
462
  const sub = pub.duplicate();
463
463
  server.adapter(createAdapter(pub, sub));
464
- this.adapterLogger.log(
465
- "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
466
- );
467
464
  } catch (err) {
468
- this.adapterLogger.error(
469
- `Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
465
+ const reason = internal.describeError(err);
466
+ throw new Error(
467
+ `[${_RealtimeIoAdapter.name}] ${internal.REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED}: websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed (${reason}). Install @socket.io/redis-adapter and pass an ioredis client as pubClient.`,
468
+ { cause: err }
470
469
  );
471
470
  }
471
+ this.adapterLogger.log(
472
+ "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
473
+ );
472
474
  }
473
475
  };
474
476
 
@@ -502,9 +504,7 @@ exports.RealtimeGateway = class RealtimeGateway {
502
504
  this.authenticated.set(socket, resolvedAuth);
503
505
  next();
504
506
  } catch (err) {
505
- this.logger.error(
506
- `handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
507
- );
507
+ this.logger.error(`handshake refused for socket ${socket.id}: ${internal.describeError(err)}`);
508
508
  next(new Error("Internal Server Error"));
509
509
  }
510
510
  };
@@ -598,7 +598,7 @@ exports.RealtimeGateway = class RealtimeGateway {
598
598
  }
599
599
  } catch (err) {
600
600
  this.logger.error(
601
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err.message}`
601
+ `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${internal.describeError(err)}`
602
602
  );
603
603
  socket.disconnect(true);
604
604
  }
@@ -326,16 +326,13 @@ declare class RealtimeIoAdapter extends IoAdapter {
326
326
  * Create the Socket.IO server with merged WebSocket options.
327
327
  *
328
328
  * When `websocket.redisAdapter.pubClient` is set, installs the
329
- * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
330
- * dep — its absence does not crash the lib).
329
+ * `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
331
330
  */
332
331
  createIOServer(port: number, opts?: ServerOptions): unknown;
333
332
  /**
334
- * Lazily load and install `@socket.io/redis-adapter`.
335
- *
336
- * Uses a dynamic `require` so the package stays optional — absent peers do
337
- * not crash the lib. A load or install failure is logged and tolerated;
338
- * the lib degrades gracefully to single-instance mode.
333
+ * Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
334
+ * silent single-instance server drops cross-node messages. An unreachable Redis
335
+ * is not one; reconnecting stays with the client.
339
336
  */
340
337
  private installRedisAdapter;
341
338
  }
@@ -326,16 +326,13 @@ declare class RealtimeIoAdapter extends IoAdapter {
326
326
  * Create the Socket.IO server with merged WebSocket options.
327
327
  *
328
328
  * When `websocket.redisAdapter.pubClient` is set, installs the
329
- * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
330
- * dep — its absence does not crash the lib).
329
+ * `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
331
330
  */
332
331
  createIOServer(port: number, opts?: ServerOptions): unknown;
333
332
  /**
334
- * Lazily load and install `@socket.io/redis-adapter`.
335
- *
336
- * Uses a dynamic `require` so the package stays optional — absent peers do
337
- * not crash the lib. A load or install failure is logged and tolerated;
338
- * the lib degrades gracefully to single-instance mode.
333
+ * Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
334
+ * silent single-instance server drops cross-node messages. An unreachable Redis
335
+ * is not one; reconnecting stays with the client.
339
336
  */
340
337
  private installRedisAdapter;
341
338
  }
@@ -1,15 +1,17 @@
1
+ import { createRequire } from 'node:module';
1
2
  import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
2
- import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
3
+ import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
3
4
  import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
4
5
  import { IoAdapter } from '@nestjs/platform-socket.io';
5
6
 
7
+ const require$1 = createRequire(import.meta.url || __filename);
6
8
  var __defProp = Object.defineProperty;
7
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
10
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ var __require = /* @__PURE__ */ ((x) => typeof require$1 !== "undefined" ? require$1 : typeof Proxy !== "undefined" ? new Proxy(x, {
12
+ get: (a, b) => (typeof require$1 !== "undefined" ? require$1 : a)[b]
11
13
  }) : x)(function(x) {
12
- if (typeof require !== "undefined") return require.apply(this, arguments);
14
+ if (typeof require$1 !== "undefined") return require$1.apply(this, arguments);
13
15
  throw Error('Dynamic require of "' + x + '" is not supported');
14
16
  });
15
17
  var __decorateClass = (decorators, target, key, kind) => {
@@ -379,9 +381,7 @@ var CompositeTransport = class {
379
381
  const results = await Promise.allSettled(tasks.map((t) => t()));
380
382
  for (const result of results) {
381
383
  if (result.status === "rejected") {
382
- this.logger.warn(
383
- `Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
384
- );
384
+ this.logger.warn(`Composite ${op} partially failed: ${describeError(result.reason)}`);
385
385
  }
386
386
  }
387
387
  }
@@ -427,8 +427,7 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
427
427
  * Create the Socket.IO server with merged WebSocket options.
428
428
  *
429
429
  * When `websocket.redisAdapter.pubClient` is set, installs the
430
- * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
431
- * dep — its absence does not crash the lib).
430
+ * `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
432
431
  */
433
432
  createIOServer(port, opts) {
434
433
  const wsOpts = this.options.websocket ?? {};
@@ -441,17 +440,20 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
441
440
  };
442
441
  const server = super.createIOServer(port, mergedOpts);
443
442
  if (wsOpts.redisAdapter?.pubClient) {
444
- this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
443
+ try {
444
+ this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
445
+ } catch (err) {
446
+ server.close().catch(() => void 0);
447
+ throw err;
448
+ }
445
449
  }
446
450
  realtimeServers.add(server);
447
451
  return server;
448
452
  }
449
453
  /**
450
- * Lazily load and install `@socket.io/redis-adapter`.
451
- *
452
- * Uses a dynamic `require` so the package stays optional — absent peers do
453
- * not crash the lib. A load or install failure is logged and tolerated;
454
- * the lib degrades gracefully to single-instance mode.
454
+ * Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
455
+ * silent single-instance server drops cross-node messages. An unreachable Redis
456
+ * is not one; reconnecting stays with the client.
455
457
  */
456
458
  installRedisAdapter(server, pubClient) {
457
459
  try {
@@ -459,14 +461,16 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
459
461
  const pub = pubClient;
460
462
  const sub = pub.duplicate();
461
463
  server.adapter(createAdapter(pub, sub));
462
- this.adapterLogger.log(
463
- "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
464
- );
465
464
  } catch (err) {
466
- this.adapterLogger.error(
467
- `Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
465
+ const reason = describeError(err);
466
+ throw new Error(
467
+ `[${_RealtimeIoAdapter.name}] ${REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED}: websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed (${reason}). Install @socket.io/redis-adapter and pass an ioredis client as pubClient.`,
468
+ { cause: err }
468
469
  );
469
470
  }
471
+ this.adapterLogger.log(
472
+ "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
473
+ );
470
474
  }
471
475
  };
472
476
 
@@ -500,9 +504,7 @@ var RealtimeGateway = class {
500
504
  this.authenticated.set(socket, resolvedAuth);
501
505
  next();
502
506
  } catch (err) {
503
- this.logger.error(
504
- `handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
505
- );
507
+ this.logger.error(`handshake refused for socket ${socket.id}: ${describeError(err)}`);
506
508
  next(new Error("Internal Server Error"));
507
509
  }
508
510
  };
@@ -596,7 +598,7 @@ var RealtimeGateway = class {
596
598
  }
597
599
  } catch (err) {
598
600
  this.logger.error(
599
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err.message}`
601
+ `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${describeError(err)}`
600
602
  );
601
603
  socket.disconnect(true);
602
604
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
4
4
  "description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -98,6 +98,7 @@
98
98
  "check:mutants": "node scripts/check-mutation-directives.mjs",
99
99
  "check:published": "node scripts/check-published-surface.mjs",
100
100
  "check:runtime": "node scripts/check-consumer-runtime.mjs",
101
+ "benchmark": "node scripts/benchmark/run.mjs",
101
102
  "check:surface": "node scripts/check-public-surface.mjs",
102
103
  "clean": "rm -rf dist coverage",
103
104
  "lint": "eslint src",