@bymax-one/nest-realtime 1.2.8 → 1.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,14 @@
1
1
  import { randomUUID } from 'crypto';
2
- import { Injectable, Optional, Inject, Logger, Global, Module, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, HttpException, UnauthorizedException } from '@nestjs/common';
2
+ import { Injectable, Optional, Inject, Logger, Global, Module, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, ServiceUnavailableException, HttpException, UnauthorizedException } from '@nestjs/common';
3
3
  import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
4
4
  import { takeUntil, catchError, finalize } from 'rxjs/operators';
5
5
  import { isIP } from 'net';
6
6
 
7
7
  var __defProp = Object.defineProperty;
8
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __typeError = (msg) => {
10
+ throw TypeError(msg);
11
+ };
9
12
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
13
  var __decorateClass = (decorators, target, key, kind) => {
11
14
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
@@ -16,7 +19,11 @@ var __decorateClass = (decorators, target, key, kind) => {
16
19
  return result;
17
20
  };
18
21
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
19
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
22
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
23
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
24
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
25
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
26
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
20
27
 
21
28
  // src/shared/constants/error-codes.constants.ts
22
29
  var REALTIME_ERROR_CODES = {
@@ -61,22 +68,36 @@ var DEFAULT_HEARTBEAT_MS = 3e4;
61
68
  var HEARTBEAT_MIN_MS = 5e3;
62
69
  var HEARTBEAT_MAX_MS = 9e4;
63
70
 
71
+ // src/server/utils/realtime-error.ts
72
+ function realtimeError(code, detail, options = {}) {
73
+ const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
74
+ const message = `${lead}: ${detail}`;
75
+ const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
76
+ return Object.assign(error, { code });
77
+ }
78
+
64
79
  // src/server/config/validate-options.ts
65
80
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
66
81
  function validateOptions(options) {
67
82
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
68
- throw new Error(
69
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`
83
+ throw realtimeError(
84
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
85
+ `options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`,
86
+ { who: "BymaxRealtimeModule" }
70
87
  );
71
88
  }
72
89
  if (!options.authenticator) {
73
- throw new Error(
74
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator is required \u2014 the library never ships a default authenticator`
90
+ throw realtimeError(
91
+ REALTIME_ERROR_CODES.NO_AUTHENTICATOR,
92
+ `options.authenticator is required \u2014 the library never ships a default authenticator`,
93
+ { who: "BymaxRealtimeModule" }
75
94
  );
76
95
  }
77
96
  if (typeof options.authenticator.authenticate !== "function") {
78
- throw new Error(
79
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator must implement IConnectionAuthenticator.authenticate(context)`
97
+ throw realtimeError(
98
+ REALTIME_ERROR_CODES.NO_AUTHENTICATOR,
99
+ `options.authenticator must implement IConnectionAuthenticator.authenticate(context)`,
100
+ { who: "BymaxRealtimeModule" }
80
101
  );
81
102
  }
82
103
  validateSseOptions(options);
@@ -95,18 +116,24 @@ function validateSseOptions(options) {
95
116
  const sse = options.sse;
96
117
  const heartbeatMs = sse?.heartbeatMs;
97
118
  if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
98
- throw new Error(
99
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`
119
+ throw realtimeError(
120
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
121
+ `options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`,
122
+ { who: "BymaxRealtimeModule" }
100
123
  );
101
124
  }
102
125
  if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
103
- throw new Error(
104
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.replayBufferSize must be >= 0`
126
+ throw realtimeError(
127
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
128
+ `options.sse.replayBufferSize must be >= 0`,
129
+ { who: "BymaxRealtimeModule" }
105
130
  );
106
131
  }
107
132
  if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
108
- throw new Error(
109
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`
133
+ throw realtimeError(
134
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
135
+ `options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`,
136
+ { who: "BymaxRealtimeModule" }
110
137
  );
111
138
  }
112
139
  }
@@ -210,13 +237,15 @@ function resolveAuthTenant(options, auth) {
210
237
  }
211
238
  function assertIdentityIsNotBlank(auth) {
212
239
  if (isBlank(auth.userId)) {
213
- throw new Error(
214
- `${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
240
+ throw realtimeError(
241
+ REALTIME_ERROR_CODES.AUTH_FAILED,
242
+ `the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
215
243
  );
216
244
  }
217
245
  if (auth.tenantId !== void 0 && isBlank(auth.tenantId)) {
218
- throw new Error(
219
- `${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
246
+ throw realtimeError(
247
+ REALTIME_ERROR_CODES.AUTH_FAILED,
248
+ `the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
220
249
  );
221
250
  }
222
251
  }
@@ -401,7 +430,7 @@ function composeRoomId(prefix, ...parts) {
401
430
 
402
431
  // src/server/utils/unavailable-error.ts
403
432
  function unavailableError(code, who, what, cause) {
404
- return new Error(`[${who}] ${code}: ${what} (${describeError(cause)})`, { cause });
433
+ return realtimeError(code, `${what} (${describeError(cause)})`, { who, cause });
405
434
  }
406
435
  var InMemoryPubSub = class {
407
436
  handlers = /* @__PURE__ */ new Set();
@@ -458,8 +487,9 @@ var HeartbeatService = class {
458
487
  timers = /* @__PURE__ */ new Map();
459
488
  start(connectionId, res, intervalMs) {
460
489
  if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
461
- throw new Error(
462
- `${REALTIME_ERROR_CODES.INVALID_OPTIONS}: heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
490
+ throw realtimeError(
491
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
492
+ `heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
463
493
  );
464
494
  }
465
495
  this.stop(connectionId);
@@ -490,6 +520,7 @@ HeartbeatService = __decorateClass([
490
520
  ], HeartbeatService);
491
521
 
492
522
  // src/server/transports/sse/sse.transport.ts
523
+ var _shuttingDown;
493
524
  var SseTransport = class {
494
525
  constructor(connections, rooms, replayBuffer, idGen, heartbeat, auth, pubsub, hooks, options, instanceId, offlineQueue) {
495
526
  this.connections = connections;
@@ -503,6 +534,9 @@ var SseTransport = class {
503
534
  this.options = options;
504
535
  this.instanceId = instanceId;
505
536
  this.offlineQueue = offlineQueue;
537
+ __publicField(this, "kind", "sse");
538
+ __publicField(this, "logger", new Logger(SseTransport.name));
539
+ __privateAdd(this, _shuttingDown, false);
506
540
  }
507
541
  connections;
508
542
  rooms;
@@ -515,14 +549,19 @@ var SseTransport = class {
515
549
  options;
516
550
  instanceId;
517
551
  offlineQueue;
518
- kind = "sse";
519
- logger = new Logger(SseTransport.name);
520
- async onApplicationShutdown() {
552
+ async beforeApplicationShutdown() {
553
+ __privateSet(this, _shuttingDown, true);
521
554
  this.heartbeat.stopAll();
522
555
  for (const conn of this.connections.allByTransport("sse")) {
523
556
  await this.disconnectLocal(conn.connectionId);
524
557
  }
525
558
  }
559
+ async onApplicationShutdown() {
560
+ await this.beforeApplicationShutdown();
561
+ }
562
+ get shuttingDown() {
563
+ return __privateGet(this, _shuttingDown);
564
+ }
526
565
  get heartbeatMs() {
527
566
  return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
528
567
  }
@@ -743,6 +782,7 @@ var SseTransport = class {
743
782
  }
744
783
  }
745
784
  };
785
+ _shuttingDown = new WeakMap();
746
786
  SseTransport = __decorateClass([
747
787
  Injectable(),
748
788
  __decorateParam(0, Inject(ConnectionRegistry)),
@@ -843,6 +883,7 @@ var SseSubscriptionHandler = class {
843
883
  async handle(req, res) {
844
884
  res.setHeader("Cache-Control", "no-cache, no-transform");
845
885
  res.setHeader("X-Accel-Buffering", "no");
886
+ this.refuseDuringShutdown();
846
887
  const done = this.authenticated.get(req);
847
888
  this.authenticated.delete(req);
848
889
  let authenticated;
@@ -851,11 +892,19 @@ var SseSubscriptionHandler = class {
851
892
  } catch (err) {
852
893
  throw this.toClientError(err, "SSE authentication failed");
853
894
  }
895
+ let stream;
854
896
  try {
855
- return await this.openStream(req, res, authenticated);
897
+ stream = await this.openStream(req, res, authenticated);
856
898
  } catch (err) {
857
899
  throw this.serverError(err, "SSE handshake failed");
858
900
  }
901
+ this.refuseDuringShutdown();
902
+ return stream;
903
+ }
904
+ refuseDuringShutdown() {
905
+ if (this.transport.shuttingDown) {
906
+ throw new ServiceUnavailableException(REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
907
+ }
859
908
  }
860
909
  async openStream(req, res, authenticated) {
861
910
  const { context, auth: resolvedAuth } = authenticated;
@@ -903,6 +952,10 @@ var SseSubscriptionHandler = class {
903
952
  }
904
953
  buildStream(p) {
905
954
  return new Observable((subscriber) => {
955
+ if (this.transport.shuttingDown) {
956
+ subscriber.complete();
957
+ return void 0;
958
+ }
906
959
  const inner = this.subscribePipeline(p, subscriber);
907
960
  if (!subscriber.closed && p.queueEvents.length > 0) {
908
961
  void this.offlineDelivery?.acknowledge(p.resolvedAuth.userId, p.queueEvents);
@@ -1132,11 +1185,7 @@ var ReauthenticationService = class {
1132
1185
  }
1133
1186
  async handleFailure(conn) {
1134
1187
  this.positiveCache.delete(conn.connectionId);
1135
- if (this.policy.onFailure === "event") {
1136
- await this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
1137
- reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
1138
- });
1139
- }
1188
+ if (this.policy.onFailure === "event") this.notify(conn);
1140
1189
  void Promise.resolve(
1141
1190
  this.hooks?.onReauthenticationFailed?.({
1142
1191
  connectionId: conn.connectionId,
@@ -1154,6 +1203,20 @@ var ReauthenticationService = class {
1154
1203
  });
1155
1204
  await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1156
1205
  }
1206
+ notify(conn) {
1207
+ const failed = (err) => {
1208
+ this.logger.warn(
1209
+ `Reauthentication notification for ${conn.connectionId} failed, disconnecting anyway: ${describeError(err)}`
1210
+ );
1211
+ };
1212
+ try {
1213
+ this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
1214
+ reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
1215
+ }).catch(failed);
1216
+ } catch (err) {
1217
+ failed(err);
1218
+ }
1219
+ }
1157
1220
  };
1158
1221
  ReauthenticationService = __decorateClass([
1159
1222
  Injectable(),
@@ -1192,8 +1255,10 @@ var SHARED_SERVICES = [
1192
1255
  function assertModeSupported(wiring, mode, moduleName) {
1193
1256
  if (wiring.modes.includes(mode)) return;
1194
1257
  const alternative = mode === "sse" ? "'BymaxRealtimeModule' from '@bymax-one/nest-realtime'" : "'BymaxRealtimeWebSocketModule' from '@bymax-one/nest-realtime/websocket'";
1195
- throw new Error(
1196
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`
1258
+ throw realtimeError(
1259
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1260
+ `transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`,
1261
+ { who: moduleName }
1197
1262
  );
1198
1263
  }
1199
1264
  function warnIfSingleInstance(pubsub, transport, logger) {
@@ -1233,26 +1298,32 @@ function composeForRoot(moduleClass, wiring, logger, options) {
1233
1298
  }
1234
1299
  function assertSseEndpointApplies(asyncOptions, moduleName) {
1235
1300
  if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
1236
- throw new Error(
1237
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`
1301
+ throw realtimeError(
1302
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1303
+ `sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
1304
+ { who: moduleName }
1238
1305
  );
1239
1306
  }
1240
1307
  function bindSseEndpoint(resolved, declared, bound, moduleName) {
1241
1308
  if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
1242
- throw new Error(
1243
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`
1309
+ throw realtimeError(
1310
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1311
+ `the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`,
1312
+ { who: moduleName }
1244
1313
  );
1245
1314
  }
1246
1315
  return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
1247
1316
  }
1248
1317
  function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
1249
1318
  if (!raw) {
1250
- throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
1319
+ throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
1251
1320
  }
1252
1321
  validateOptions(raw);
1253
1322
  if (raw.transport !== declaredMode) {
1254
- throw new Error(
1255
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`
1323
+ throw realtimeError(
1324
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1325
+ `forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`,
1326
+ { who: moduleName }
1256
1327
  );
1257
1328
  }
1258
1329
  const resolved = applyDefaults(raw);
@@ -1267,8 +1338,10 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1267
1338
  asyncOptions.useExisting
1268
1339
  ].filter((pattern) => pattern !== void 0);
1269
1340
  if (patterns.length !== 1) {
1270
- throw new Error(
1271
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
1341
+ throw realtimeError(
1342
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1343
+ `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
1344
+ { who: moduleName }
1272
1345
  );
1273
1346
  }
1274
1347
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
@@ -1451,6 +1524,16 @@ BymaxRealtimeModule = __decorateClass([
1451
1524
  Module({})
1452
1525
  ], BymaxRealtimeModule);
1453
1526
  var MALFORMED_REPORT_INTERVAL_MS = 6e4;
1527
+ var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
1528
+ "wait",
1529
+ "connecting",
1530
+ "connect",
1531
+ "reconnecting",
1532
+ "close",
1533
+ "end"
1534
+ ]);
1535
+ var PUBLISHER_WAIT_MS = 2e3;
1536
+ var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
1454
1537
  function connectionReason(err) {
1455
1538
  const code = err?.code;
1456
1539
  const text = describeError(err);
@@ -1467,25 +1550,47 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1467
1550
  #subscribed = false;
1468
1551
  #outageLogged = false;
1469
1552
  #retired = /* @__PURE__ */ new WeakSet();
1553
+ #lastRefusal;
1470
1554
  constructor(options) {
1471
1555
  this.#pub = options.client;
1472
1556
  this.channel = options.channel ?? "bymax:realtime";
1473
1557
  }
1474
1558
  isSubscribed() {
1475
- return this.#subscribed;
1559
+ return this.#subscribed && !CANNOT_PUBLISH.has(this.#pub.status);
1476
1560
  }
1477
1561
  async publish(message) {
1478
1562
  const status = this.#pub.status;
1479
- if (status === "reconnecting" || status === "close" || status === "end") {
1480
- throw unavailableError(
1481
- REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1482
- _RedisRealtimePubSub.name,
1483
- `cannot publish to "${this.channel}"`,
1484
- new Error(`the Redis client is ${status}`)
1485
- );
1563
+ if (CANNOT_PUBLISH.has(status)) {
1564
+ this.connectLazyClient();
1565
+ throw this.cannotPublish(`the Redis client is ${status}`);
1486
1566
  }
1487
1567
  await this.#pub.publish(this.channel, JSON.stringify(message));
1488
1568
  }
1569
+ connectLazyClient() {
1570
+ if (this.#pub.status === "wait") this.#pub.connect().catch(() => void 0);
1571
+ }
1572
+ publisherSettled() {
1573
+ const pub = this.#pub;
1574
+ if (pub.status !== "connecting" && pub.status !== "connect") return Promise.resolve();
1575
+ return new Promise((resolve) => {
1576
+ const settle = () => {
1577
+ clearTimeout(deadline);
1578
+ for (const event of CONNECTION_OVER) pub.off(event, settle);
1579
+ resolve();
1580
+ };
1581
+ const deadline = setTimeout(settle, PUBLISHER_WAIT_MS);
1582
+ deadline.unref();
1583
+ for (const event of CONNECTION_OVER) pub.once(event, settle);
1584
+ });
1585
+ }
1586
+ cannotPublish(reason) {
1587
+ return unavailableError(
1588
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1589
+ _RedisRealtimePubSub.name,
1590
+ `cannot publish to "${this.channel}"`,
1591
+ new Error(reason)
1592
+ );
1593
+ }
1489
1594
  async subscribe(handler) {
1490
1595
  this.handlers.add(handler);
1491
1596
  let sub;
@@ -1496,6 +1601,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1496
1601
  this.#subInit = null;
1497
1602
  throw err;
1498
1603
  }
1604
+ await this.publisherSettled();
1499
1605
  return async () => {
1500
1606
  this.handlers.delete(handler);
1501
1607
  if (this.handlers.size === 0) {
@@ -1517,6 +1623,8 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1517
1623
  }
1518
1624
  async createSubscriber() {
1519
1625
  this.#outageLogged = false;
1626
+ this.#lastRefusal = void 0;
1627
+ this.connectLazyClient();
1520
1628
  const sub = this.#pub.duplicate({ autoResubscribe: false, enableOfflineQueue: true });
1521
1629
  let attached = false;
1522
1630
  sub.on("message", (_ch, payload) => this.dispatch(payload));
@@ -1574,14 +1682,18 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1574
1682
  refused(err) {
1575
1683
  if (err?.name !== "ReplyError") return;
1576
1684
  this.#subscribed = false;
1685
+ const reason = describeError(err);
1686
+ if (reason === this.#lastRefusal) return;
1687
+ this.#lastRefusal = reason;
1577
1688
  this.logger.warn(
1578
- `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${describeError(err)}`
1689
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${reason}`
1579
1690
  );
1580
1691
  }
1581
1692
  markUp() {
1582
1693
  if (this.#subscribed) return;
1583
1694
  this.#subscribed = true;
1584
1695
  this.#outageLogged = false;
1696
+ this.#lastRefusal = void 0;
1585
1697
  this.logger.log(
1586
1698
  `Subscribed to "${this.channel}"; remote events and revocations reach this instance`
1587
1699
  );
@@ -1684,4 +1796,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1684
1796
  }
1685
1797
  };
1686
1798
 
1687
- 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, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
1799
+ 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, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
@@ -251,21 +251,24 @@ exports.CompositeTransport = class CompositeTransport {
251
251
  const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
252
252
  if (reasons.length === 0) return;
253
253
  if (reasons.length === 1) throw reasons[0];
254
- throw internal.unavailableError(
255
- internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
256
- exports.CompositeTransport.name,
257
- `${op} of ${connectionId} failed on both transports`,
258
- new AggregateError(reasons, reasons.map(internal.describeError).join("; "))
259
- );
254
+ throw this.allFailed(`${op} of ${connectionId}`, reasons);
260
255
  }
261
256
  async fanOut(op, ...tasks) {
262
257
  const results = await Promise.allSettled(tasks.map((t) => t()));
263
- for (const result of results) {
264
- if (result.status === "rejected") {
265
- this.logger.warn(`Composite ${op} partially failed: ${internal.describeError(result.reason)}`);
266
- }
258
+ const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
259
+ if (reasons.length === tasks.length) throw this.allFailed(op, reasons);
260
+ for (const reason of reasons) {
261
+ this.logger.warn(`Composite ${op} partially failed: ${internal.describeError(reason)}`);
267
262
  }
268
263
  }
264
+ allFailed(what, reasons) {
265
+ return internal.unavailableError(
266
+ internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
267
+ exports.CompositeTransport.name,
268
+ `${what} failed on both transports`,
269
+ new AggregateError(reasons, reasons.map(internal.describeError).join("; "))
270
+ );
271
+ }
269
272
  };
270
273
  exports.CompositeTransport = __decorateClass([
271
274
  common.Injectable(),
@@ -322,9 +325,10 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
322
325
  server.adapter(createAdapter(pub, sub));
323
326
  } catch (err) {
324
327
  const reason = internal.describeError(err);
325
- throw new Error(
326
- `[${_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.`,
327
- { cause: err }
328
+ throw internal.realtimeError(
329
+ internal.REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
330
+ `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.`,
331
+ { who: _RealtimeIoAdapter.name, cause: err }
328
332
  );
329
333
  }
330
334
  this.adapterLogger.log(
@@ -350,7 +350,8 @@ declare class RealtimeIoAdapter extends IoAdapter {
350
350
  *
351
351
  * Every `emitTo*` and `broadcast` invokes both SSE and WebSocket transports in
352
352
  * parallel via `Promise.allSettled` so a failure in one never aborts the other.
353
- * Failures are logged as warnings without rethrowing.
353
+ * A failure of one is logged as a warning and the call resolves; a failure of both
354
+ * rejects.
354
355
  *
355
356
  * `joinRoom`, `leaveRoom`, and `disconnect` ask both transports and settle both: each
356
357
  * transport acts only on a connection it holds, and a connection neither holds is handed
@@ -432,10 +433,12 @@ declare class CompositeTransport implements ITransport {
432
433
  /**
433
434
  * Run two transport tasks in parallel via `Promise.allSettled`.
434
435
  *
435
- * A rejection in either task is logged as a warning and does not propagate,
436
- * ensuring one failing transport never blocks delivery on the other.
436
+ * One task failing is logged as a warning and the call resolves, so one failing transport
437
+ * never blocks delivery on the other. Every task failing rejects.
437
438
  */
438
439
  private fanOut;
440
+ /** The rejection for an operation that failed on every transport, with every reason in `cause`. */
441
+ private allFailed;
439
442
  }
440
443
 
441
444
  export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, WebSocketTransport };
@@ -350,7 +350,8 @@ declare class RealtimeIoAdapter extends IoAdapter {
350
350
  *
351
351
  * Every `emitTo*` and `broadcast` invokes both SSE and WebSocket transports in
352
352
  * parallel via `Promise.allSettled` so a failure in one never aborts the other.
353
- * Failures are logged as warnings without rethrowing.
353
+ * A failure of one is logged as a warning and the call resolves; a failure of both
354
+ * rejects.
354
355
  *
355
356
  * `joinRoom`, `leaveRoom`, and `disconnect` ask both transports and settle both: each
356
357
  * transport acts only on a connection it holds, and a connection neither holds is handed
@@ -432,10 +433,12 @@ declare class CompositeTransport implements ITransport {
432
433
  /**
433
434
  * Run two transport tasks in parallel via `Promise.allSettled`.
434
435
  *
435
- * A rejection in either task is logged as a warning and does not propagate,
436
- * ensuring one failing transport never blocks delivery on the other.
436
+ * One task failing is logged as a warning and the call resolves, so one failing transport
437
+ * never blocks delivery on the other. Every task failing rejects.
437
438
  */
438
439
  private fanOut;
440
+ /** The rejection for an operation that failed on every transport, with every reason in `cause`. */
441
+ private allFailed;
439
442
  }
440
443
 
441
444
  export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, WebSocketTransport };
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
3
- import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
3
+ import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES, realtimeError } from '@bymax-one/nest-realtime/internal';
4
4
  import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
5
5
  import { IoAdapter } from '@nestjs/platform-socket.io';
6
6
 
@@ -251,21 +251,24 @@ var CompositeTransport = class {
251
251
  const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
252
252
  if (reasons.length === 0) return;
253
253
  if (reasons.length === 1) throw reasons[0];
254
- throw unavailableError(
255
- REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
256
- CompositeTransport.name,
257
- `${op} of ${connectionId} failed on both transports`,
258
- new AggregateError(reasons, reasons.map(describeError).join("; "))
259
- );
254
+ throw this.allFailed(`${op} of ${connectionId}`, reasons);
260
255
  }
261
256
  async fanOut(op, ...tasks) {
262
257
  const results = await Promise.allSettled(tasks.map((t) => t()));
263
- for (const result of results) {
264
- if (result.status === "rejected") {
265
- this.logger.warn(`Composite ${op} partially failed: ${describeError(result.reason)}`);
266
- }
258
+ const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
259
+ if (reasons.length === tasks.length) throw this.allFailed(op, reasons);
260
+ for (const reason of reasons) {
261
+ this.logger.warn(`Composite ${op} partially failed: ${describeError(reason)}`);
267
262
  }
268
263
  }
264
+ allFailed(what, reasons) {
265
+ return unavailableError(
266
+ REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
267
+ CompositeTransport.name,
268
+ `${what} failed on both transports`,
269
+ new AggregateError(reasons, reasons.map(describeError).join("; "))
270
+ );
271
+ }
269
272
  };
270
273
  CompositeTransport = __decorateClass([
271
274
  Injectable(),
@@ -322,9 +325,10 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
322
325
  server.adapter(createAdapter(pub, sub));
323
326
  } catch (err) {
324
327
  const reason = describeError(err);
325
- throw new Error(
326
- `[${_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.`,
327
- { cause: err }
328
+ throw realtimeError(
329
+ REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
330
+ `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.`,
331
+ { who: _RealtimeIoAdapter.name, cause: err }
328
332
  );
329
333
  }
330
334
  this.adapterLogger.log(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.8",
3
+ "version": "1.2.9",
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",
@@ -96,6 +96,7 @@
96
96
  "build": "pnpm clean && tsup && node scripts/strip-bundle-comments.mjs",
97
97
  "check:exports": "attw --pack . --profile strict",
98
98
  "check:mutants": "node scripts/check-mutation-directives.mjs",
99
+ "check:file-size": "node scripts/check-file-size.mjs",
99
100
  "check:api": "node scripts/check-api-surface.mjs",
100
101
  "check:published": "node scripts/check-published-surface.mjs",
101
102
  "check:runtime": "node scripts/check-consumer-runtime.mjs",
@@ -107,7 +108,7 @@
107
108
  "mutation": "stryker run",
108
109
  "mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
109
110
  "mutation:dry-run": "stryker run --dryRunOnly",
110
- "prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm check:runtime",
111
+ "prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm check:file-size && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm check:runtime",
111
112
  "release": "npm publish --provenance --access public",
112
113
  "size": "node scripts/check-size.mjs",
113
114
  "test": "jest",