@bymax-one/nest-realtime 1.0.0 → 1.0.2

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,21 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
3
  var common = require('@nestjs/common');
4
+ var crypto = require('crypto');
5
5
  var rxjs = require('rxjs');
6
6
  var operators = require('rxjs/operators');
7
- var websockets = require('@nestjs/websockets');
8
- var platformSocket_io = require('@nestjs/platform-socket.io');
9
7
 
10
8
  var __defProp = Object.defineProperty;
11
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
10
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
14
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
15
- }) : x)(function(x) {
16
- if (typeof require !== "undefined") return require.apply(this, arguments);
17
- throw Error('Dynamic require of "' + x + '" is not supported');
18
- });
19
11
  var __decorateClass = (decorators, target, key, kind) => {
20
12
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
13
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -996,81 +988,6 @@ exports.InMemoryPubSub = class InMemoryPubSub {
996
988
  exports.InMemoryPubSub = __decorateClass([
997
989
  common.Injectable()
998
990
  ], exports.InMemoryPubSub);
999
- var RealtimePubSubSubscriber = class {
1000
- constructor(pubsub, instanceId, sse) {
1001
- this.pubsub = pubsub;
1002
- this.instanceId = instanceId;
1003
- this.sse = sse;
1004
- }
1005
- pubsub;
1006
- instanceId;
1007
- sse;
1008
- logger = new common.Logger(RealtimePubSubSubscriber.name);
1009
- unsubscribe = null;
1010
- async onModuleInit() {
1011
- try {
1012
- this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1013
- } catch (err) {
1014
- this.logger.warn(
1015
- `Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1016
- );
1017
- }
1018
- }
1019
- async onApplicationShutdown() {
1020
- if (this.unsubscribe) {
1021
- try {
1022
- await this.unsubscribe();
1023
- } catch (err) {
1024
- this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
1025
- }
1026
- this.unsubscribe = null;
1027
- }
1028
- }
1029
- handle(msg) {
1030
- if (msg.origin === this.instanceId) return;
1031
- try {
1032
- switch (msg.op) {
1033
- case "emitToUser": {
1034
- const a = msg.args;
1035
- this.sse.emitToUserLocal(a.userId, a.event, a.data, a.id);
1036
- break;
1037
- }
1038
- case "emitToTenant": {
1039
- const a = msg.args;
1040
- this.sse.emitToTenantLocal(a.tenantId, a.event, a.data, a.id);
1041
- break;
1042
- }
1043
- case "emitToRoom": {
1044
- const a = msg.args;
1045
- this.sse.emitToRoomLocal(a.roomId, a.event, a.data, a.id);
1046
- break;
1047
- }
1048
- case "broadcast": {
1049
- const a = msg.args;
1050
- this.sse.broadcastLocal(a.event, a.data, a.id);
1051
- break;
1052
- }
1053
- case "disconnect": {
1054
- const a = msg.args;
1055
- void this.sse.disconnectLocal(a.connectionId, a.reason);
1056
- break;
1057
- }
1058
- default: {
1059
- const exhaustive = msg.op;
1060
- this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
1061
- }
1062
- }
1063
- } catch (err) {
1064
- this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
1065
- }
1066
- }
1067
- };
1068
- RealtimePubSubSubscriber = __decorateClass([
1069
- common.Injectable(),
1070
- __decorateParam(0, common.Inject(REALTIME_PUBSUB_TOKEN)),
1071
- __decorateParam(1, common.Inject(REALTIME_INSTANCE_ID_TOKEN)),
1072
- __decorateParam(2, common.Inject(SseTransport))
1073
- ], RealtimePubSubSubscriber);
1074
991
  exports.RealtimeService = class RealtimeService {
1075
992
  constructor(transport) {
1076
993
  this.transport = transport;
@@ -1238,475 +1155,42 @@ ReauthenticationService = __decorateClass([
1238
1155
  __decorateParam(4, common.Optional()),
1239
1156
  __decorateParam(4, common.Inject(REALTIME_HOOKS_TOKEN))
1240
1157
  ], ReauthenticationService);
1241
- var CONNECTION_ROOM_PREFIX = "connection";
1242
- exports.WebSocketTransport = class WebSocketTransport {
1243
- constructor(connections, rooms, auth, hooks, options) {
1244
- this.connections = connections;
1245
- this.rooms = rooms;
1246
- this.auth = auth;
1247
- this.hooks = hooks;
1248
- this.options = options;
1249
- }
1250
- connections;
1251
- rooms;
1252
- auth;
1253
- hooks;
1254
- options;
1255
- kind = "websocket";
1256
- logger = new common.Logger(exports.WebSocketTransport.name);
1257
- /** Nullable until the gateway's afterInit wires the instance. */
1258
- server = null;
1259
- /**
1260
- * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
1261
- *
1262
- * All emit methods silently no-op until this is called, so the transport is
1263
- * safe to construct before the HTTP server is ready.
1264
- *
1265
- * @param server - The live Socket.IO `Server` instance from the NestJS gateway.
1266
- */
1267
- setServer(server) {
1268
- this.server = server;
1269
- this.logger.log("Socket.IO server wired to WebSocketTransport");
1270
- }
1271
- /**
1272
- * Resolve the map of locally-connected sockets, tolerating both server shapes.
1273
- *
1274
- * A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
1275
- * `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
1276
- * `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
1277
- * `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
1278
- * this indirection so they work under either shape.
1279
- */
1280
- localSockets() {
1281
- const server = this.server;
1282
- if (!server) return void 0;
1283
- const sockets = server.sockets;
1284
- return sockets instanceof Map ? sockets : sockets.sockets;
1285
- }
1286
- /**
1287
- * Expose the configured authenticator to the gateway.
1288
- *
1289
- * The gateway uses this to avoid a circular injection: `RealtimeGateway` →
1290
- * `WebSocketTransport` → authenticator, rather than injecting the token
1291
- * directly in the gateway.
1292
- *
1293
- * @returns The consumer-provided `IConnectionAuthenticator` instance.
1294
- */
1295
- authenticator() {
1296
- return this.auth;
1297
- }
1298
- /**
1299
- * Register a freshly-authenticated WebSocket connection.
1300
- *
1301
- * Stores the connection record in `ConnectionRegistry` (with `subject: null` —
1302
- * WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
1303
- * membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
1304
- *
1305
- * Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
1306
- * does not publish to `IRealtimePubSub`.
1307
- *
1308
- * @param socket - The authenticated Socket.IO socket instance.
1309
- * @param auth - The resolved authentication result containing userId, tenantId, and roles.
1310
- */
1311
- async registerSocket(socket, auth) {
1312
- const connectedAt = /* @__PURE__ */ new Date();
1313
- this.connections.register({
1314
- connectionId: socket.id,
1315
- userId: auth.userId,
1316
- tenantId: auth.tenantId,
1317
- transport: "websocket",
1318
- ip: socket.handshake.address,
1319
- userAgent: socket.handshake.headers["user-agent"],
1320
- connectedAt,
1321
- subject: null,
1322
- close$: null,
1323
- originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
1324
- });
1325
- await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
1326
- if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
1327
- await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
1328
- this.rooms.join(socket.id, `${ROOM_PREFIXES.USER}:${auth.userId}`);
1329
- if (auth.tenantId) this.rooms.join(socket.id, `${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
1330
- await this.evictBeyondLimit(auth.userId);
1331
- await this.hooks.onConnect?.({
1332
- connectionId: socket.id,
1333
- userId: auth.userId,
1334
- tenantId: auth.tenantId,
1335
- transport: "websocket",
1336
- ip: socket.handshake.address,
1337
- userAgent: socket.handshake.headers["user-agent"],
1338
- connectedAt
1339
- });
1340
- }
1341
- /**
1342
- * Unregister a disconnected WebSocket connection.
1343
- *
1344
- * Removes the record from `ConnectionRegistry`, clears all room membership
1345
- * from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
1346
- * computed `durationMs`.
1347
- *
1348
- * @param connectionId - The Socket.IO socket `id` of the disconnected connection.
1349
- * @param reason - Optional reason string forwarded to the `onDisconnect` hook.
1350
- */
1351
- async unregisterSocket(connectionId, reason) {
1352
- const record = this.connections.unregister(connectionId);
1353
- if (!record) return;
1354
- this.rooms.leaveAll(connectionId);
1355
- const disconnectMeta = {
1356
- connectionId,
1357
- userId: record.userId,
1358
- tenantId: record.tenantId,
1359
- transport: "websocket",
1360
- ip: record.ip,
1361
- userAgent: record.userAgent,
1362
- connectedAt: record.connectedAt,
1363
- durationMs: Date.now() - record.connectedAt.getTime(),
1364
- ...reason !== void 0 ? { reason } : {}
1365
- };
1366
- await this.hooks.onDisconnect?.(disconnectMeta);
1367
- }
1368
- /**
1369
- * Send an event to every connection of a user (uses `user:{userId}` room).
1370
- *
1371
- * @param userId - Target user identifier.
1372
- * @param event - Event name to emit.
1373
- * @param data - Payload forwarded to all matching connections.
1374
- */
1375
- async emitToUser(userId, event, data) {
1376
- this.server?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
1377
- }
1378
- /**
1379
- * Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
1380
- *
1381
- * @param tenantId - Target tenant identifier.
1382
- * @param event - Event name to emit.
1383
- * @param data - Payload forwarded to all matching connections.
1384
- */
1385
- async emitToTenant(tenantId, event, data) {
1386
- this.server?.to(`${ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
1387
- }
1388
- /**
1389
- * Send an event to every connection in an arbitrary room.
1390
- *
1391
- * @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
1392
- * @param event - Event name to emit.
1393
- * @param data - Payload forwarded to all connections in the room.
1394
- */
1395
- async emitToRoom(roomId, event, data) {
1396
- this.server?.to(roomId).emit(event, data);
1397
- }
1398
- /**
1399
- * Broadcast an event to all connected clients.
1400
- *
1401
- * @param event - Event name to emit.
1402
- * @param data - Payload forwarded to every connected socket.
1403
- */
1404
- async broadcast(event, data) {
1405
- this.server?.emit(event, data);
1406
- }
1407
- /**
1408
- * Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
1409
- *
1410
- * @param connectionId - The socket `id` of the connection to join.
1411
- * @param roomId - The room to join.
1412
- */
1413
- async joinRoom(connectionId, roomId) {
1414
- const socket = this.localSockets()?.get(connectionId);
1415
- if (socket) {
1416
- await socket.join(roomId);
1417
- this.rooms.join(connectionId, roomId);
1418
- }
1419
- }
1420
- /**
1421
- * Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
1422
- *
1423
- * @param connectionId - The socket `id` of the connection to remove.
1424
- * @param roomId - The room to leave.
1425
- */
1426
- async leaveRoom(connectionId, roomId) {
1427
- const socket = this.localSockets()?.get(connectionId);
1428
- if (socket) {
1429
- await socket.leave(roomId);
1430
- this.rooms.leave(connectionId, roomId);
1431
- }
1432
- }
1433
- /**
1434
- * Force-disconnect a specific connection — adapter-aware, so revocation works
1435
- * across nodes.
1436
- *
1437
- * A socket local to this node is closed directly as a fast path. Regardless,
1438
- * `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
1439
- * under `@socket.io/redis-adapter` this fans out to remote nodes, so a
1440
- * connection pinned to another instance is still force-closed. The local socket
1441
- * has already left the room by then, so the broadcast does not double-close it.
1442
- *
1443
- * @param connectionId - The socket `id` of the connection to disconnect.
1444
- * @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
1445
- */
1446
- async disconnect(connectionId, _reason) {
1447
- const server = this.server;
1448
- if (!server) return;
1449
- const local = this.localSockets()?.get(connectionId);
1450
- if (local) local.disconnect(true);
1451
- server.in(`${CONNECTION_ROOM_PREFIX}:${connectionId}`).disconnectSockets(true);
1452
- }
1453
- /**
1454
- * Evict the user's oldest WebSocket connections (FIFO) when over
1455
- * `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
1456
- * as the disconnect reason — never rejects the new connection with HTTP 429.
1457
- */
1458
- async evictBeyondLimit(userId) {
1459
- const max = this.options.websocket?.maxConnectionsPerUser;
1460
- if (max === void 0 || max <= 0) return;
1461
- let userConnections = this.connections.byUser(userId, "websocket");
1462
- while (userConnections.length > max) {
1463
- const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
1464
- await this.disconnect(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
1465
- await this.unregisterSocket(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
1466
- userConnections = this.connections.byUser(userId, "websocket");
1467
- }
1468
- }
1469
- };
1470
- exports.WebSocketTransport = __decorateClass([
1471
- common.Injectable(),
1472
- __decorateParam(0, common.Inject(exports.ConnectionRegistry)),
1473
- __decorateParam(1, common.Inject(RoomRegistry)),
1474
- __decorateParam(2, common.Inject(REALTIME_AUTHENTICATOR_TOKEN)),
1475
- __decorateParam(3, common.Inject(REALTIME_HOOKS_TOKEN)),
1476
- __decorateParam(4, common.Inject(REALTIME_OPTIONS_TOKEN))
1477
- ], exports.WebSocketTransport);
1478
- function firstQueryValue(value) {
1479
- return Array.isArray(value) ? value[0] : value;
1480
- }
1481
- exports.RealtimeGateway = class RealtimeGateway {
1482
- constructor(transport, options) {
1483
- this.transport = transport;
1484
- this.options = options;
1485
- }
1486
- transport;
1487
- options;
1488
- logger = new common.Logger(exports.RealtimeGateway.name);
1489
- server;
1490
- /** Wire the resolved Socket.IO server to the transport after gateway init. */
1491
- afterInit(server) {
1492
- this.transport.setServer(server);
1493
- this.logger.log("RealtimeGateway initialized");
1494
- }
1495
- /**
1496
- * Handle a new WebSocket connection.
1497
- *
1498
- * Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
1499
- * three supported auth patterns (spec §8.1):
1500
- * - Cookie HttpOnly — extracted via `parseCookieHeader`.
1501
- * - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
1502
- * - Bearer header — available in `headers.authorization` or via `auth.token`.
1503
- *
1504
- * `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
1505
- * (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
1506
- * context so the authenticator sees a single unified shape regardless of client.
1507
- *
1508
- * Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
1509
- * undefined`); the single-value `ticket` parameter is collapsed to its first
1510
- * element so the authenticator receives a well-defined string.
1511
- *
1512
- * Fail-closed: any thrown error disconnects the socket immediately so it cannot
1513
- * linger in an unregistered state and receive broadcast events.
1514
- */
1515
- async handleConnection(socket) {
1516
- try {
1517
- const { handshake } = socket;
1518
- const headers = this.normalizeHeaders(handshake.headers);
1519
- const query = { ...handshake.query };
1520
- const handshakeAuth = handshake.auth;
1521
- if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
1522
- if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
1523
- const ticket = firstQueryValue(query["ticket"]);
1524
- if (ticket !== void 0) query["ticket"] = ticket;
1525
- const ctx = {
1526
- cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
1527
- headers,
1528
- query,
1529
- ip: handshake.address,
1530
- userAgent: handshake.headers["user-agent"],
1531
- transport: "websocket"
1532
- };
1533
- const auth = await this.transport.authenticator().authenticate(ctx);
1534
- if (!auth) {
1535
- socket.disconnect(true);
1536
- return;
1537
- }
1538
- await this.transport.registerSocket(socket, auth);
1539
- if (this.options.websocket?.emitConnectionEvent !== false) {
1540
- socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
1541
- connectionId: socket.id,
1542
- traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
1543
- });
1544
- }
1545
- } catch (err) {
1546
- this.logger.error(
1547
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err.message}`
1548
- );
1549
- socket.disconnect(true);
1550
- }
1551
- }
1552
- /** Handle a WebSocket disconnection — unregister the connection. */
1553
- async handleDisconnect(socket) {
1554
- await this.transport.unregisterSocket(socket.id, "CLIENT_DISCONNECT");
1555
- }
1556
- /**
1557
- * Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
1558
- *
1559
- * Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
1560
- * single string, matching the shape expected by `ConnectionAuthContext.headers`.
1561
- */
1562
- normalizeHeaders(input) {
1563
- const out = {};
1564
- for (const [k, v] of Object.entries(input)) {
1565
- out[k.toLowerCase()] = Array.isArray(v) ? v.join(",") : v;
1566
- }
1567
- return out;
1568
- }
1569
- };
1570
- __decorateClass([
1571
- websockets.WebSocketServer()
1572
- ], exports.RealtimeGateway.prototype, "server", 2);
1573
- exports.RealtimeGateway = __decorateClass([
1574
- websockets.WebSocketGateway({
1575
- cors: { origin: false }
1576
- }),
1577
- __decorateParam(0, common.Inject(exports.WebSocketTransport)),
1578
- __decorateParam(1, common.Inject(REALTIME_OPTIONS_TOKEN))
1579
- ], exports.RealtimeGateway);
1580
- exports.CompositeTransport = class CompositeTransport {
1581
- constructor(sse, ws) {
1582
- this.sse = sse;
1583
- this.ws = ws;
1584
- }
1585
- sse;
1586
- ws;
1587
- kind = "sse";
1588
- logger = new common.Logger(exports.CompositeTransport.name);
1589
- /**
1590
- * Emit to all connections of a user across both transports.
1591
- *
1592
- * @param userId - Target user identifier.
1593
- * @param event - Event name to emit.
1594
- * @param data - Payload forwarded to all matching connections.
1595
- */
1596
- async emitToUser(userId, event, data) {
1597
- await this.fanOut(
1598
- "emitToUser",
1599
- () => this.sse.emitToUser(userId, event, data),
1600
- () => this.ws.emitToUser(userId, event, data)
1601
- );
1602
- }
1603
- /**
1604
- * Emit to all connections within a tenant across both transports.
1605
- *
1606
- * @param tenantId - Target tenant identifier.
1607
- * @param event - Event name to emit.
1608
- * @param data - Payload forwarded to all matching connections.
1609
- */
1610
- async emitToTenant(tenantId, event, data) {
1611
- await this.fanOut(
1612
- "emitToTenant",
1613
- () => this.sse.emitToTenant(tenantId, event, data),
1614
- () => this.ws.emitToTenant(tenantId, event, data)
1615
- );
1616
- }
1617
- /**
1618
- * Emit to all connections in a room across both transports.
1619
- *
1620
- * @param roomId - The fully-qualified room identifier.
1621
- * @param event - Event name to emit.
1622
- * @param data - Payload forwarded to all connections in the room.
1623
- */
1624
- async emitToRoom(roomId, event, data) {
1625
- await this.fanOut(
1626
- "emitToRoom",
1627
- () => this.sse.emitToRoom(roomId, event, data),
1628
- () => this.ws.emitToRoom(roomId, event, data)
1629
- );
1630
- }
1631
- /**
1632
- * Broadcast to all connected clients across both transports.
1633
- *
1634
- * @param event - Event name to emit.
1635
- * @param data - Payload forwarded to every connected client.
1636
- */
1637
- async broadcast(event, data) {
1638
- await this.fanOut(
1639
- "broadcast",
1640
- () => this.sse.broadcast(event, data),
1641
- () => this.ws.broadcast(event, data)
1642
- );
1643
- }
1644
- /**
1645
- * Join a connection to a room.
1646
- *
1647
- * Both transports are attempted; only the one that owns the connection
1648
- * succeeds. The other's failure is expected and swallowed.
1649
- */
1650
- async joinRoom(connectionId, roomId) {
1651
- await Promise.all([
1652
- this.sse.joinRoom(connectionId, roomId).catch(() => void 0),
1653
- this.ws.joinRoom(connectionId, roomId).catch(() => void 0)
1654
- ]);
1655
- }
1656
- /**
1657
- * Remove a connection from a room.
1658
- *
1659
- * Both transports are attempted tolerantly — one will succeed, the other
1660
- * may fail silently.
1661
- */
1662
- async leaveRoom(connectionId, roomId) {
1663
- await Promise.all([
1664
- this.sse.leaveRoom(connectionId, roomId).catch(() => void 0),
1665
- this.ws.leaveRoom(connectionId, roomId).catch(() => void 0)
1666
- ]);
1667
- }
1668
- /**
1669
- * Disconnect a specific connection.
1670
- *
1671
- * Both transports are attempted; the one owning the connection disconnects it.
1672
- */
1673
- async disconnect(connectionId, reason) {
1674
- await Promise.all([
1675
- this.sse.disconnect(connectionId, reason).catch(() => void 0),
1676
- this.ws.disconnect(connectionId, reason).catch(() => void 0)
1677
- ]);
1678
- }
1679
- /**
1680
- * Run two transport tasks in parallel via `Promise.allSettled`.
1681
- *
1682
- * A rejection in either task is logged as a warning and does not propagate,
1683
- * ensuring one failing transport never blocks delivery on the other.
1684
- */
1685
- async fanOut(op, ...tasks) {
1686
- const results = await Promise.allSettled(tasks.map((t) => t()));
1687
- for (const result of results) {
1688
- if (result.status === "rejected") {
1689
- this.logger.warn(
1690
- `Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
1691
- );
1692
- }
1693
- }
1694
- }
1695
- };
1696
- exports.CompositeTransport = __decorateClass([
1697
- common.Injectable(),
1698
- __decorateParam(0, common.Inject(SseTransport)),
1699
- __decorateParam(1, common.Inject(exports.WebSocketTransport))
1700
- ], exports.CompositeTransport);
1701
1158
 
1702
- // src/server/realtime.module.ts
1703
- function assertWsPeerDeps(resolver = __require.resolve) {
1704
- try {
1705
- resolver("@nestjs/websockets");
1706
- resolver("socket.io");
1707
- } catch {
1708
- throw new Error(
1709
- "[BymaxRealtimeModule] transport 'websocket'|'both' requires '@nestjs/websockets' and 'socket.io' \u2014 install them, or switch to transport: 'sse'."
1159
+ // src/server/composition/realtime-module.factory.ts
1160
+ var EXPORTED_TOKENS = [
1161
+ exports.RealtimeService,
1162
+ exports.ConnectionRegistry,
1163
+ REALTIME_OPTIONS_TOKEN,
1164
+ REALTIME_INSTANCE_ID_TOKEN,
1165
+ REALTIME_AUTHENTICATOR_TOKEN,
1166
+ REALTIME_PUBSUB_TOKEN,
1167
+ REALTIME_HOOKS_TOKEN,
1168
+ REALTIME_OFFLINE_QUEUE_TOKEN,
1169
+ REALTIME_PRESENCE_TOKEN,
1170
+ REALTIME_TRANSPORT_TOKEN
1171
+ ];
1172
+ var SHARED_SERVICES = [
1173
+ exports.ConnectionRegistry,
1174
+ RoomRegistry,
1175
+ EventIdGenerator,
1176
+ EventReplayBuffer,
1177
+ HeartbeatService,
1178
+ exports.RealtimeService,
1179
+ ReauthenticationService,
1180
+ OfflineQueueDeliveryService
1181
+ ];
1182
+ function assertModeSupported(wiring, mode, moduleName) {
1183
+ if (wiring.modes.includes(mode)) return;
1184
+ const alternative = mode === "sse" ? "'BymaxRealtimeModule' from '@bymax-one/nest-realtime'" : "'BymaxRealtimeWebSocketModule' from '@bymax-one/nest-realtime/websocket'";
1185
+ throw new Error(
1186
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`
1187
+ );
1188
+ }
1189
+ function warnIfSingleInstance(pubsub, transport, logger) {
1190
+ if (transport === "websocket") return;
1191
+ if (!pubsub && process.env["NODE_ENV"] === "production") {
1192
+ logger.warn(
1193
+ "No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
1710
1194
  );
1711
1195
  }
1712
1196
  }
@@ -1719,66 +1203,173 @@ function buildCommonProviders(resolved, instanceId) {
1719
1203
  { provide: REALTIME_HOOKS_TOKEN, useValue: resolved.hooks ?? {} },
1720
1204
  { provide: REALTIME_OFFLINE_QUEUE_TOKEN, useValue: resolved.offlineQueue },
1721
1205
  { provide: REALTIME_PRESENCE_TOKEN, useValue: resolved.presence },
1722
- exports.ConnectionRegistry,
1723
- RoomRegistry,
1724
- EventIdGenerator,
1725
- EventReplayBuffer,
1726
- HeartbeatService,
1727
- exports.RealtimeService,
1728
- ReauthenticationService,
1729
- OfflineQueueDeliveryService
1206
+ ...SHARED_SERVICES
1730
1207
  ];
1731
1208
  }
1732
- function buildTransportProviders(resolved) {
1733
- const transport = resolved.transport;
1734
- const providers = [];
1735
- const controllers = [];
1736
- const gateways = [];
1737
- if (transport === "sse") {
1738
- providers.push(SseTransport, SseSubscriptionHandler, RealtimePubSubSubscriber);
1739
- providers.push({ provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport });
1740
- controllers.push(resolved.sse.endpoint);
1741
- } else if (transport === "websocket") {
1742
- assertWsPeerDeps();
1743
- providers.push(exports.WebSocketTransport);
1744
- providers.push({ provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport });
1745
- gateways.push(exports.RealtimeGateway);
1746
- } else {
1747
- assertWsPeerDeps();
1748
- providers.push(
1749
- SseTransport,
1750
- exports.WebSocketTransport,
1751
- exports.CompositeTransport,
1752
- SseSubscriptionHandler,
1753
- RealtimePubSubSubscriber
1209
+ function composeForRoot(moduleClass, wiring, logger, options) {
1210
+ validateOptions(options);
1211
+ assertModeSupported(wiring, options.transport, moduleClass.name);
1212
+ const resolved = applyDefaults(options);
1213
+ const instanceId = crypto.randomUUID();
1214
+ warnIfSingleInstance(resolved.pubsub, resolved.transport, logger);
1215
+ const { providers, endpoints, gateways } = wiring.build(resolved);
1216
+ logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
1217
+ return {
1218
+ module: moduleClass,
1219
+ controllers: endpoints.map((endpoint) => createSseController(endpoint)),
1220
+ providers: [...buildCommonProviders(resolved, instanceId), ...providers, ...gateways],
1221
+ exports: EXPORTED_TOKENS
1222
+ };
1223
+ }
1224
+ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
1225
+ if (!raw) {
1226
+ throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
1227
+ }
1228
+ validateOptions(raw);
1229
+ if (raw.transport !== declaredMode) {
1230
+ throw new Error(
1231
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`
1754
1232
  );
1755
- providers.push({ provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport });
1756
- controllers.push(resolved.sse.endpoint);
1757
- gateways.push(exports.RealtimeGateway);
1758
1233
  }
1759
- return { providers, controllers, gateways };
1234
+ const resolved = applyDefaults(raw);
1235
+ logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
1236
+ return resolved;
1760
1237
  }
1761
- function buildLegacyAsyncTransportProviders() {
1762
- return [
1763
- SseTransport,
1764
- SseSubscriptionHandler,
1765
- exports.WebSocketTransport,
1766
- exports.CompositeTransport,
1767
- exports.RealtimeGateway,
1768
- RealtimePubSubSubscriber,
1769
- {
1770
- provide: REALTIME_TRANSPORT_TOKEN,
1771
- useFactory: (opts, sse, ws, composite) => {
1772
- if (opts.transport === "sse") return sse;
1773
- if (opts.transport === "websocket") return ws;
1774
- return composite;
1775
- },
1776
- inject: [REALTIME_OPTIONS_TOKEN, SseTransport, exports.WebSocketTransport, exports.CompositeTransport]
1777
- }
1778
- ];
1238
+ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1239
+ const moduleName = moduleClass.name;
1240
+ const patterns = [
1241
+ asyncOptions.useFactory,
1242
+ asyncOptions.useClass,
1243
+ asyncOptions.useExisting
1244
+ ].filter((pattern) => pattern !== void 0);
1245
+ if (patterns.length !== 1) {
1246
+ throw new Error(
1247
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
1248
+ );
1249
+ }
1250
+ assertModeSupported(wiring, asyncOptions.transport, moduleName);
1251
+ const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
1252
+ const instanceId = crypto.randomUUID();
1253
+ const resolve = (raw, source) => resolveAsyncOptions(raw, asyncOptions.transport, instanceId, source, logger, moduleName);
1254
+ const resolvedOptionsProvider = asyncOptions.useFactory ? {
1255
+ provide: REALTIME_OPTIONS_TOKEN,
1256
+ useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
1257
+ inject: [...asyncOptions.inject ?? []]
1258
+ } : {
1259
+ provide: REALTIME_OPTIONS_TOKEN,
1260
+ useFactory: async (factory) => resolve(
1261
+ await factory.createRealtimeOptions(),
1262
+ "createRealtimeOptions"
1263
+ ),
1264
+ inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
1265
+ };
1266
+ const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
1267
+ const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
1268
+ const { providers: transportProviders, controllers } = wiring.buildAsync(asyncOptions.transport);
1269
+ return {
1270
+ module: moduleClass,
1271
+ imports: asyncOptions.imports ?? [],
1272
+ controllers,
1273
+ providers: [
1274
+ ...factoryClassProvider,
1275
+ resolvedOptionsProvider,
1276
+ fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
1277
+ fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
1278
+ warnIfSingleInstance(opts.pubsub, opts.transport, logger);
1279
+ return opts.pubsub ?? new exports.InMemoryPubSub();
1280
+ }),
1281
+ fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
1282
+ { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
1283
+ fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
1284
+ fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
1285
+ ...SHARED_SERVICES,
1286
+ ...transportProviders,
1287
+ ...asyncOptions.extraProviders ?? []
1288
+ ],
1289
+ exports: EXPORTED_TOKENS
1290
+ };
1779
1291
  }
1780
- function buildAsyncTransportProviders(mode) {
1781
- if (mode === "sse") {
1292
+ var RealtimePubSubSubscriber = class {
1293
+ constructor(pubsub, instanceId, sse) {
1294
+ this.pubsub = pubsub;
1295
+ this.instanceId = instanceId;
1296
+ this.sse = sse;
1297
+ }
1298
+ pubsub;
1299
+ instanceId;
1300
+ sse;
1301
+ logger = new common.Logger(RealtimePubSubSubscriber.name);
1302
+ unsubscribe = null;
1303
+ async onModuleInit() {
1304
+ try {
1305
+ this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1306
+ } catch (err) {
1307
+ this.logger.warn(
1308
+ `Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1309
+ );
1310
+ }
1311
+ }
1312
+ async onApplicationShutdown() {
1313
+ if (this.unsubscribe) {
1314
+ try {
1315
+ await this.unsubscribe();
1316
+ } catch (err) {
1317
+ this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
1318
+ }
1319
+ this.unsubscribe = null;
1320
+ }
1321
+ }
1322
+ handle(msg) {
1323
+ if (msg.origin === this.instanceId) return;
1324
+ try {
1325
+ switch (msg.op) {
1326
+ case "emitToUser": {
1327
+ const a = msg.args;
1328
+ this.sse.emitToUserLocal(a.userId, a.event, a.data, a.id);
1329
+ break;
1330
+ }
1331
+ case "emitToTenant": {
1332
+ const a = msg.args;
1333
+ this.sse.emitToTenantLocal(a.tenantId, a.event, a.data, a.id);
1334
+ break;
1335
+ }
1336
+ case "emitToRoom": {
1337
+ const a = msg.args;
1338
+ this.sse.emitToRoomLocal(a.roomId, a.event, a.data, a.id);
1339
+ break;
1340
+ }
1341
+ case "broadcast": {
1342
+ const a = msg.args;
1343
+ this.sse.broadcastLocal(a.event, a.data, a.id);
1344
+ break;
1345
+ }
1346
+ case "disconnect": {
1347
+ const a = msg.args;
1348
+ void this.sse.disconnectLocal(a.connectionId, a.reason);
1349
+ break;
1350
+ }
1351
+ default: {
1352
+ const exhaustive = msg.op;
1353
+ this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
1354
+ }
1355
+ }
1356
+ } catch (err) {
1357
+ this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
1358
+ }
1359
+ }
1360
+ };
1361
+ RealtimePubSubSubscriber = __decorateClass([
1362
+ common.Injectable(),
1363
+ __decorateParam(0, common.Inject(REALTIME_PUBSUB_TOKEN)),
1364
+ __decorateParam(1, common.Inject(REALTIME_INSTANCE_ID_TOKEN)),
1365
+ __decorateParam(2, common.Inject(SseTransport))
1366
+ ], RealtimePubSubSubscriber);
1367
+
1368
+ // src/server/composition/sse-wiring.ts
1369
+ var DEFAULT_ASYNC_ENDPOINT = "/events";
1370
+ var sseWiring = {
1371
+ modes: ["sse"],
1372
+ build(resolved) {
1782
1373
  return {
1783
1374
  providers: [
1784
1375
  SseTransport,
@@ -1786,68 +1377,29 @@ function buildAsyncTransportProviders(mode) {
1786
1377
  RealtimePubSubSubscriber,
1787
1378
  { provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport }
1788
1379
  ],
1789
- controllers: [createSseController("/events")]
1790
- };
1791
- }
1792
- if (mode === "websocket") {
1793
- assertWsPeerDeps();
1794
- return {
1795
- providers: [
1796
- exports.WebSocketTransport,
1797
- exports.RealtimeGateway,
1798
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.WebSocketTransport }
1799
- ],
1800
- controllers: []
1380
+ endpoints: [resolved.sse.endpoint],
1381
+ gateways: []
1801
1382
  };
1802
- }
1803
- if (mode === "both") {
1804
- assertWsPeerDeps();
1383
+ },
1384
+ buildAsync() {
1805
1385
  return {
1806
1386
  providers: [
1807
1387
  SseTransport,
1808
1388
  SseSubscriptionHandler,
1809
- exports.WebSocketTransport,
1810
- exports.CompositeTransport,
1811
- exports.RealtimeGateway,
1812
1389
  RealtimePubSubSubscriber,
1813
- { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
1390
+ { provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport }
1814
1391
  ],
1815
- controllers: [createSseController("/events")]
1392
+ controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
1816
1393
  };
1817
1394
  }
1818
- return {
1819
- providers: buildLegacyAsyncTransportProviders(),
1820
- controllers: [createSseController("/events")]
1821
- };
1822
- }
1395
+ };
1396
+
1397
+ // src/server/realtime.module.ts
1823
1398
  exports.BymaxRealtimeModule = class BymaxRealtimeModule {
1824
- /**
1825
- * Validate a raw async factory result, enforce the optional synchronous
1826
- * `transport` hint, apply defaults, and log the bootstrap line.
1827
- *
1828
- * @throws when the factory returned nothing, the options are invalid, or the
1829
- * resolved transport disagrees with the synchronous hint used to gate
1830
- * provider registration.
1831
- */
1832
- static resolveAsyncOptions(raw, transportHint, instanceId, source) {
1833
- if (!raw) {
1834
- throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
1835
- }
1836
- validateOptions(raw);
1837
- if (transportHint !== void 0 && raw.transport !== transportHint) {
1838
- throw new Error(
1839
- `${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync transport hint '${transportHint}' does not match the resolved transport '${raw.transport}'`
1840
- );
1841
- }
1842
- const resolved = applyDefaults(raw);
1843
- exports.BymaxRealtimeModule.logger.log(
1844
- `Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`
1845
- );
1846
- return resolved;
1847
- }
1848
1399
  /**
1849
1400
  * Configure the module synchronously.
1850
1401
  *
1402
+ * @throws when the options are invalid.
1851
1403
  * @example
1852
1404
  * ```ts
1853
1405
  * BymaxRealtimeModule.forRoot({
@@ -1857,180 +1409,42 @@ exports.BymaxRealtimeModule = class BymaxRealtimeModule {
1857
1409
  * ```
1858
1410
  */
1859
1411
  static forRoot(options) {
1860
- validateOptions(options);
1861
- const resolved = applyDefaults(options);
1862
- const instanceId = crypto.randomUUID();
1863
- if (!resolved.pubsub && process.env["NODE_ENV"] === "production") {
1864
- exports.BymaxRealtimeModule.logger.warn(
1865
- "No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
1866
- );
1867
- }
1868
- const common = buildCommonProviders(resolved, instanceId);
1869
- const {
1870
- providers: transportProviders,
1871
- controllers,
1872
- gateways
1873
- } = buildTransportProviders(resolved);
1874
- exports.BymaxRealtimeModule.logger.log(
1875
- `Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`
1876
- );
1877
- return {
1878
- module: exports.BymaxRealtimeModule,
1879
- controllers: controllers.map((ep) => createSseController(ep)),
1880
- providers: [...common, ...transportProviders, ...gateways],
1881
- exports: [
1882
- exports.RealtimeService,
1883
- exports.ConnectionRegistry,
1884
- REALTIME_OPTIONS_TOKEN,
1885
- REALTIME_INSTANCE_ID_TOKEN,
1886
- REALTIME_AUTHENTICATOR_TOKEN,
1887
- REALTIME_PUBSUB_TOKEN,
1888
- REALTIME_HOOKS_TOKEN,
1889
- REALTIME_OFFLINE_QUEUE_TOKEN,
1890
- REALTIME_PRESENCE_TOKEN,
1891
- REALTIME_TRANSPORT_TOKEN
1892
- ]
1893
- };
1412
+ return composeForRoot(exports.BymaxRealtimeModule, sseWiring, exports.BymaxRealtimeModule.logger, options);
1894
1413
  }
1895
1414
  /**
1896
- * Configure the module asynchronously so consumers can resolve options (and
1897
- * the authenticator) through DI — `ConfigService`, `JwtService`, a Redis
1898
- * client, etc.
1415
+ * Configure the module asynchronously so options — and the authenticator —
1416
+ * can be resolved through DI: `ConfigService`, a Redis client, and so on.
1899
1417
  *
1900
- * Options are validated and defaulted **inside** the resolving factory, so a
1901
- * malformed configuration rejects via the Promise at bootstrap time and the
1902
- * application fails to start with a clear error.
1418
+ * Options are validated inside the resolving factory, so a malformed
1419
+ * configuration rejects at bootstrap and the application fails to start with
1420
+ * a clear error.
1903
1421
  *
1904
- * Controllers are registered at decoration time, so the async path binds the
1905
- * SSE controller to the fixed default endpoint `/events`. Consumers that need
1906
- * a non-default endpoint with async configuration should use `forRoot` and
1907
- * pre-resolve the options before passing them.
1908
- *
1909
- * Pass a synchronous `transport` hint to gate WebSocket wiring exactly as
1910
- * `forRoot` does — an SSE-only application then never registers the gateway,
1911
- * never boots Socket.IO, and never requires the optional WS peer deps. Without
1912
- * the hint, every transport provider is registered and the active one is
1913
- * resolved at runtime from the factory result.
1422
+ * Controllers are registered at decoration time, so this path binds the SSE
1423
+ * controller to the default endpoint `/events`. A non-default endpoint needs
1424
+ * `forRoot` with pre-resolved options.
1914
1425
  *
1426
+ * @throws when no factory pattern is given, more than one is, or the factory
1427
+ * resolves a transport other than `'sse'`.
1915
1428
  * @example
1916
1429
  * ```ts
1917
1430
  * BymaxRealtimeModule.forRootAsync({
1918
1431
  * transport: 'sse',
1919
1432
  * imports: [ConfigModule],
1920
1433
  * inject: [ConfigService],
1921
- * useFactory: async (cfg: ConfigService) => ({
1922
- * transport: 'sse',
1923
- * authenticator: new CookieJwtAuthenticator(cfg.get('JWT_SECRET')!),
1434
+ * useFactory: (cfg: ConfigService) => ({
1435
+ * transport: 'sse' as const,
1436
+ * authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
1924
1437
  * }),
1925
1438
  * })
1926
1439
  * ```
1927
1440
  */
1928
1441
  static forRootAsync(asyncOptions) {
1929
- const patterns = [
1930
- asyncOptions.useFactory,
1931
- asyncOptions.useClass,
1932
- asyncOptions.useExisting
1933
- ].filter((pattern) => pattern !== void 0);
1934
- if (patterns.length !== 1) {
1935
- throw new Error(
1936
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
1937
- );
1938
- }
1939
- const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
1940
- const instanceId = crypto.randomUUID();
1941
- const resolvedOptionsProvider = asyncOptions.useFactory ? {
1942
- provide: REALTIME_OPTIONS_TOKEN,
1943
- useFactory: async (...args) => exports.BymaxRealtimeModule.resolveAsyncOptions(
1944
- await asyncOptions.useFactory(...args),
1945
- asyncOptions.transport,
1946
- instanceId,
1947
- "useFactory"
1948
- ),
1949
- inject: [...asyncOptions.inject ?? []]
1950
- } : {
1951
- provide: REALTIME_OPTIONS_TOKEN,
1952
- useFactory: async (factory) => exports.BymaxRealtimeModule.resolveAsyncOptions(
1953
- await factory.createRealtimeOptions(),
1954
- asyncOptions.transport,
1955
- instanceId,
1956
- "options factory"
1957
- ),
1958
- inject: [asyncOptions.useClass ? FACTORY_TOKEN : asyncOptions.useExisting]
1959
- };
1960
- const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
1961
- const authenticatorProvider = {
1962
- provide: REALTIME_AUTHENTICATOR_TOKEN,
1963
- useFactory: (opts) => opts.authenticator,
1964
- inject: [REALTIME_OPTIONS_TOKEN]
1965
- };
1966
- const pubsubProvider = {
1967
- provide: REALTIME_PUBSUB_TOKEN,
1968
- useFactory: (opts) => {
1969
- if (!opts.pubsub && process.env["NODE_ENV"] === "production") {
1970
- exports.BymaxRealtimeModule.logger.warn(
1971
- "No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
1972
- );
1973
- }
1974
- return opts.pubsub ?? new exports.InMemoryPubSub();
1975
- },
1976
- inject: [REALTIME_OPTIONS_TOKEN]
1977
- };
1978
- const hooksProvider = {
1979
- provide: REALTIME_HOOKS_TOKEN,
1980
- useFactory: (opts) => opts.hooks ?? {},
1981
- inject: [REALTIME_OPTIONS_TOKEN]
1982
- };
1983
- const offlineQueueProvider = {
1984
- provide: REALTIME_OFFLINE_QUEUE_TOKEN,
1985
- useFactory: (opts) => opts.offlineQueue,
1986
- inject: [REALTIME_OPTIONS_TOKEN]
1987
- };
1988
- const presenceProvider = {
1989
- provide: REALTIME_PRESENCE_TOKEN,
1990
- useFactory: (opts) => opts.presence,
1991
- inject: [REALTIME_OPTIONS_TOKEN]
1992
- };
1993
- const { providers: transportProviders, controllers } = buildAsyncTransportProviders(
1994
- asyncOptions.transport
1442
+ return composeForRootAsync(
1443
+ exports.BymaxRealtimeModule,
1444
+ sseWiring,
1445
+ exports.BymaxRealtimeModule.logger,
1446
+ asyncOptions
1995
1447
  );
1996
- const providers = [
1997
- ...factoryClassProvider,
1998
- resolvedOptionsProvider,
1999
- authenticatorProvider,
2000
- pubsubProvider,
2001
- hooksProvider,
2002
- { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
2003
- offlineQueueProvider,
2004
- presenceProvider,
2005
- exports.ConnectionRegistry,
2006
- RoomRegistry,
2007
- EventIdGenerator,
2008
- EventReplayBuffer,
2009
- HeartbeatService,
2010
- exports.RealtimeService,
2011
- ReauthenticationService,
2012
- OfflineQueueDeliveryService,
2013
- ...transportProviders,
2014
- ...asyncOptions.extraProviders ?? []
2015
- ];
2016
- return {
2017
- module: exports.BymaxRealtimeModule,
2018
- imports: asyncOptions.imports ?? [],
2019
- providers,
2020
- controllers,
2021
- exports: [
2022
- exports.RealtimeService,
2023
- exports.ConnectionRegistry,
2024
- REALTIME_OPTIONS_TOKEN,
2025
- REALTIME_INSTANCE_ID_TOKEN,
2026
- REALTIME_AUTHENTICATOR_TOKEN,
2027
- REALTIME_PUBSUB_TOKEN,
2028
- REALTIME_HOOKS_TOKEN,
2029
- REALTIME_OFFLINE_QUEUE_TOKEN,
2030
- REALTIME_PRESENCE_TOKEN,
2031
- REALTIME_TRANSPORT_TOKEN
2032
- ]
2033
- };
2034
1448
  }
2035
1449
  };
2036
1450
  __publicField(exports.BymaxRealtimeModule, "logger", new common.Logger(exports.BymaxRealtimeModule.name));
@@ -2187,77 +1601,6 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2187
1601
  }
2188
1602
  }
2189
1603
  };
2190
- var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
2191
- logger = new common.Logger(_RealtimeIoAdapter.name);
2192
- options;
2193
- constructor(app) {
2194
- super(app);
2195
- this.options = app.get(REALTIME_OPTIONS_TOKEN);
2196
- }
2197
- /**
2198
- * Bind the gateway to `websocket.namespace` when configured.
2199
- *
2200
- * `@WebSocketGateway()` args are evaluated at class-decoration time — before
2201
- * the module options resolve — so the namespace cannot be declared there.
2202
- * Instead we build the root server via `super.create` (which routes through the
2203
- * overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
2204
- * the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
2205
- * and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
2206
- * namespace leaves the root server untouched.
2207
- */
2208
- create(port, options) {
2209
- const server = super.create(port, options);
2210
- const ns = this.options.websocket?.namespace;
2211
- if (ns && ns !== "/" && typeof server.of === "function") {
2212
- return server.of(ns);
2213
- }
2214
- return server;
2215
- }
2216
- /**
2217
- * Create the Socket.IO server with merged WebSocket options.
2218
- *
2219
- * When `websocket.redisAdapter.pubClient` is set, installs the
2220
- * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
2221
- * dep — its absence does not crash the lib).
2222
- */
2223
- createIOServer(port, opts) {
2224
- const wsOpts = this.options.websocket ?? {};
2225
- const mergedOpts = {
2226
- ...opts,
2227
- cors: wsOpts.cors ?? opts?.cors,
2228
- pingInterval: wsOpts.pingIntervalMs ?? 25e3,
2229
- pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
2230
- maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
2231
- };
2232
- const server = super.createIOServer(port, mergedOpts);
2233
- if (wsOpts.redisAdapter?.pubClient) {
2234
- this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
2235
- }
2236
- return server;
2237
- }
2238
- /**
2239
- * Lazily load and install `@socket.io/redis-adapter`.
2240
- *
2241
- * Uses a dynamic `require` so the package stays optional — absent peers do
2242
- * not crash the lib. A load or install failure is logged and tolerated;
2243
- * the lib degrades gracefully to single-instance mode.
2244
- */
2245
- installRedisAdapter(server, pubClient) {
2246
- try {
2247
- const { createAdapter } = __require("@socket.io/redis-adapter");
2248
- const pub = pubClient;
2249
- const sub = pub.duplicate();
2250
- server.adapter(createAdapter(pub, sub));
2251
- this.logger.log(
2252
- "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
2253
- );
2254
- } catch (err) {
2255
- this.logger.error(
2256
- `Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
2257
- );
2258
- }
2259
- }
2260
- };
2261
1604
 
2262
1605
  exports.REALTIME_AUTHENTICATOR_TOKEN = REALTIME_AUTHENTICATOR_TOKEN;
2263
1606
  exports.REALTIME_ERROR_CODES = REALTIME_ERROR_CODES;
@@ -2270,7 +1613,6 @@ exports.REALTIME_PUBSUB_TOKEN = REALTIME_PUBSUB_TOKEN;
2270
1613
  exports.REALTIME_TRANSPORT_TOKEN = REALTIME_TRANSPORT_TOKEN;
2271
1614
  exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
2272
1615
  exports.ROOM_PREFIXES = ROOM_PREFIXES;
2273
- exports.RealtimeIoAdapter = RealtimeIoAdapter;
2274
1616
  exports.RedisOfflineQueue = RedisOfflineQueue;
2275
1617
  exports.RedisRealtimePubSub = RedisRealtimePubSub;
2276
1618
  exports.composeRoomId = composeRoomId;