@bymax-one/nest-realtime 1.0.1 → 1.0.3

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.
@@ -0,0 +1,673 @@
1
+ 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, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
3
+ import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
4
+ import { IoAdapter } from '@nestjs/platform-socket.io';
5
+
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ 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
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __decorateClass = (decorators, target, key, kind) => {
16
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
17
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
18
+ if (decorator = decorators[i])
19
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
20
+ if (kind && result) __defProp(target, key, result);
21
+ return result;
22
+ };
23
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
24
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
25
+ var CONNECTION_ROOM_PREFIX = "connection";
26
+ var WebSocketTransport = class {
27
+ constructor(connections, rooms, auth, hooks, options) {
28
+ this.connections = connections;
29
+ this.rooms = rooms;
30
+ this.auth = auth;
31
+ this.hooks = hooks;
32
+ this.options = options;
33
+ }
34
+ connections;
35
+ rooms;
36
+ auth;
37
+ hooks;
38
+ options;
39
+ kind = "websocket";
40
+ logger = new Logger(WebSocketTransport.name);
41
+ /** Nullable until the gateway's afterInit wires the instance. */
42
+ server = null;
43
+ /**
44
+ * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
45
+ *
46
+ * All emit methods silently no-op until this is called, so the transport is
47
+ * safe to construct before the HTTP server is ready.
48
+ *
49
+ * @param server - The live Socket.IO `Server` instance from the NestJS gateway.
50
+ */
51
+ setServer(server) {
52
+ this.server = server;
53
+ this.logger.log("Socket.IO server wired to WebSocketTransport");
54
+ }
55
+ /**
56
+ * Resolve the map of locally-connected sockets, tolerating both server shapes.
57
+ *
58
+ * A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
59
+ * `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
60
+ * `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
61
+ * `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
62
+ * this indirection so they work under either shape.
63
+ */
64
+ localSockets() {
65
+ const server = this.server;
66
+ if (!server) return void 0;
67
+ const sockets = server.sockets;
68
+ return sockets instanceof Map ? sockets : sockets.sockets;
69
+ }
70
+ /**
71
+ * Expose the configured authenticator to the gateway.
72
+ *
73
+ * The gateway uses this to avoid a circular injection: `RealtimeGateway` →
74
+ * `WebSocketTransport` → authenticator, rather than injecting the token
75
+ * directly in the gateway.
76
+ *
77
+ * @returns The consumer-provided `IConnectionAuthenticator` instance.
78
+ */
79
+ authenticator() {
80
+ return this.auth;
81
+ }
82
+ /**
83
+ * Register a freshly-authenticated WebSocket connection.
84
+ *
85
+ * Stores the connection record in `ConnectionRegistry` (with `subject: null` —
86
+ * WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
87
+ * membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
88
+ *
89
+ * Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
90
+ * does not publish to `IRealtimePubSub`.
91
+ *
92
+ * @param socket - The authenticated Socket.IO socket instance.
93
+ * @param auth - The resolved authentication result containing userId, tenantId, and roles.
94
+ */
95
+ async registerSocket(socket, auth) {
96
+ const connectedAt = /* @__PURE__ */ new Date();
97
+ this.connections.register({
98
+ connectionId: socket.id,
99
+ userId: auth.userId,
100
+ tenantId: auth.tenantId,
101
+ transport: "websocket",
102
+ ip: socket.handshake.address,
103
+ userAgent: socket.handshake.headers["user-agent"],
104
+ connectedAt,
105
+ subject: null,
106
+ close$: null,
107
+ originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
108
+ });
109
+ await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
110
+ if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
111
+ await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
112
+ this.rooms.join(socket.id, `${ROOM_PREFIXES.USER}:${auth.userId}`);
113
+ if (auth.tenantId) this.rooms.join(socket.id, `${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
114
+ await this.evictBeyondLimit(auth.userId);
115
+ await this.hooks.onConnect?.({
116
+ connectionId: socket.id,
117
+ userId: auth.userId,
118
+ tenantId: auth.tenantId,
119
+ transport: "websocket",
120
+ ip: socket.handshake.address,
121
+ userAgent: socket.handshake.headers["user-agent"],
122
+ connectedAt
123
+ });
124
+ }
125
+ /**
126
+ * Unregister a disconnected WebSocket connection.
127
+ *
128
+ * Removes the record from `ConnectionRegistry`, clears all room membership
129
+ * from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
130
+ * computed `durationMs`.
131
+ *
132
+ * @param connectionId - The Socket.IO socket `id` of the disconnected connection.
133
+ * @param reason - Optional reason string forwarded to the `onDisconnect` hook.
134
+ */
135
+ async unregisterSocket(connectionId, reason) {
136
+ const record = this.connections.unregister(connectionId);
137
+ if (!record) return;
138
+ this.rooms.leaveAll(connectionId);
139
+ const disconnectMeta = {
140
+ connectionId,
141
+ userId: record.userId,
142
+ tenantId: record.tenantId,
143
+ transport: "websocket",
144
+ ip: record.ip,
145
+ userAgent: record.userAgent,
146
+ connectedAt: record.connectedAt,
147
+ durationMs: Date.now() - record.connectedAt.getTime(),
148
+ ...reason !== void 0 ? { reason } : {}
149
+ };
150
+ await this.hooks.onDisconnect?.(disconnectMeta);
151
+ }
152
+ /**
153
+ * Send an event to every connection of a user (uses `user:{userId}` room).
154
+ *
155
+ * @param userId - Target user identifier.
156
+ * @param event - Event name to emit.
157
+ * @param data - Payload forwarded to all matching connections.
158
+ */
159
+ async emitToUser(userId, event, data) {
160
+ this.server?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
161
+ }
162
+ /**
163
+ * Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
164
+ *
165
+ * @param tenantId - Target tenant identifier.
166
+ * @param event - Event name to emit.
167
+ * @param data - Payload forwarded to all matching connections.
168
+ */
169
+ async emitToTenant(tenantId, event, data) {
170
+ this.server?.to(`${ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
171
+ }
172
+ /**
173
+ * Send an event to every connection in an arbitrary room.
174
+ *
175
+ * @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
176
+ * @param event - Event name to emit.
177
+ * @param data - Payload forwarded to all connections in the room.
178
+ */
179
+ async emitToRoom(roomId, event, data) {
180
+ this.server?.to(roomId).emit(event, data);
181
+ }
182
+ /**
183
+ * Broadcast an event to all connected clients.
184
+ *
185
+ * @param event - Event name to emit.
186
+ * @param data - Payload forwarded to every connected socket.
187
+ */
188
+ async broadcast(event, data) {
189
+ this.server?.emit(event, data);
190
+ }
191
+ /**
192
+ * Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
193
+ *
194
+ * @param connectionId - The socket `id` of the connection to join.
195
+ * @param roomId - The room to join.
196
+ */
197
+ async joinRoom(connectionId, roomId) {
198
+ const socket = this.localSockets()?.get(connectionId);
199
+ if (socket) {
200
+ await socket.join(roomId);
201
+ this.rooms.join(connectionId, roomId);
202
+ }
203
+ }
204
+ /**
205
+ * Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
206
+ *
207
+ * @param connectionId - The socket `id` of the connection to remove.
208
+ * @param roomId - The room to leave.
209
+ */
210
+ async leaveRoom(connectionId, roomId) {
211
+ const socket = this.localSockets()?.get(connectionId);
212
+ if (socket) {
213
+ await socket.leave(roomId);
214
+ this.rooms.leave(connectionId, roomId);
215
+ }
216
+ }
217
+ /**
218
+ * Force-disconnect a specific connection — adapter-aware, so revocation works
219
+ * across nodes.
220
+ *
221
+ * A socket local to this node is closed directly as a fast path. Regardless,
222
+ * `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
223
+ * under `@socket.io/redis-adapter` this fans out to remote nodes, so a
224
+ * connection pinned to another instance is still force-closed. The local socket
225
+ * has already left the room by then, so the broadcast does not double-close it.
226
+ *
227
+ * @param connectionId - The socket `id` of the connection to disconnect.
228
+ * @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
229
+ */
230
+ async disconnect(connectionId, _reason) {
231
+ const server = this.server;
232
+ if (!server) return;
233
+ const local = this.localSockets()?.get(connectionId);
234
+ if (local) local.disconnect(true);
235
+ server.in(`${CONNECTION_ROOM_PREFIX}:${connectionId}`).disconnectSockets(true);
236
+ }
237
+ /**
238
+ * Evict the user's oldest WebSocket connections (FIFO) when over
239
+ * `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
240
+ * as the disconnect reason — never rejects the new connection with HTTP 429.
241
+ */
242
+ async evictBeyondLimit(userId) {
243
+ const max = this.options.websocket?.maxConnectionsPerUser;
244
+ if (max === void 0 || max <= 0) return;
245
+ let userConnections = this.connections.byUser(userId, "websocket");
246
+ while (userConnections.length > max) {
247
+ const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
248
+ await this.disconnect(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
249
+ await this.unregisterSocket(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
250
+ userConnections = this.connections.byUser(userId, "websocket");
251
+ }
252
+ }
253
+ };
254
+ WebSocketTransport = __decorateClass([
255
+ Injectable(),
256
+ __decorateParam(0, Inject(ConnectionRegistry)),
257
+ __decorateParam(1, Inject(RoomRegistry)),
258
+ __decorateParam(2, Inject(REALTIME_AUTHENTICATOR_TOKEN)),
259
+ __decorateParam(3, Inject(REALTIME_HOOKS_TOKEN)),
260
+ __decorateParam(4, Inject(REALTIME_OPTIONS_TOKEN))
261
+ ], WebSocketTransport);
262
+
263
+ // src/websocket/transports/composite/composite.transport.ts
264
+ var CompositeTransport = class {
265
+ constructor(sse, ws) {
266
+ this.sse = sse;
267
+ this.ws = ws;
268
+ }
269
+ sse;
270
+ ws;
271
+ kind = "sse";
272
+ logger = new Logger(CompositeTransport.name);
273
+ /**
274
+ * Emit to all connections of a user across both transports.
275
+ *
276
+ * @param userId - Target user identifier.
277
+ * @param event - Event name to emit.
278
+ * @param data - Payload forwarded to all matching connections.
279
+ */
280
+ async emitToUser(userId, event, data) {
281
+ await this.fanOut(
282
+ "emitToUser",
283
+ () => this.sse.emitToUser(userId, event, data),
284
+ () => this.ws.emitToUser(userId, event, data)
285
+ );
286
+ }
287
+ /**
288
+ * Emit to all connections within a tenant across both transports.
289
+ *
290
+ * @param tenantId - Target tenant identifier.
291
+ * @param event - Event name to emit.
292
+ * @param data - Payload forwarded to all matching connections.
293
+ */
294
+ async emitToTenant(tenantId, event, data) {
295
+ await this.fanOut(
296
+ "emitToTenant",
297
+ () => this.sse.emitToTenant(tenantId, event, data),
298
+ () => this.ws.emitToTenant(tenantId, event, data)
299
+ );
300
+ }
301
+ /**
302
+ * Emit to all connections in a room across both transports.
303
+ *
304
+ * @param roomId - The fully-qualified room identifier.
305
+ * @param event - Event name to emit.
306
+ * @param data - Payload forwarded to all connections in the room.
307
+ */
308
+ async emitToRoom(roomId, event, data) {
309
+ await this.fanOut(
310
+ "emitToRoom",
311
+ () => this.sse.emitToRoom(roomId, event, data),
312
+ () => this.ws.emitToRoom(roomId, event, data)
313
+ );
314
+ }
315
+ /**
316
+ * Broadcast to all connected clients across both transports.
317
+ *
318
+ * @param event - Event name to emit.
319
+ * @param data - Payload forwarded to every connected client.
320
+ */
321
+ async broadcast(event, data) {
322
+ await this.fanOut(
323
+ "broadcast",
324
+ () => this.sse.broadcast(event, data),
325
+ () => this.ws.broadcast(event, data)
326
+ );
327
+ }
328
+ /**
329
+ * Join a connection to a room.
330
+ *
331
+ * Both transports are attempted; only the one that owns the connection
332
+ * succeeds. The other's failure is expected and swallowed.
333
+ */
334
+ async joinRoom(connectionId, roomId) {
335
+ await Promise.all([
336
+ this.sse.joinRoom(connectionId, roomId).catch(() => void 0),
337
+ this.ws.joinRoom(connectionId, roomId).catch(() => void 0)
338
+ ]);
339
+ }
340
+ /**
341
+ * Remove a connection from a room.
342
+ *
343
+ * Both transports are attempted tolerantly — one will succeed, the other
344
+ * may fail silently.
345
+ */
346
+ async leaveRoom(connectionId, roomId) {
347
+ await Promise.all([
348
+ this.sse.leaveRoom(connectionId, roomId).catch(() => void 0),
349
+ this.ws.leaveRoom(connectionId, roomId).catch(() => void 0)
350
+ ]);
351
+ }
352
+ /**
353
+ * Disconnect a specific connection.
354
+ *
355
+ * Both transports are attempted; the one owning the connection disconnects it.
356
+ */
357
+ async disconnect(connectionId, reason) {
358
+ await Promise.all([
359
+ this.sse.disconnect(connectionId, reason).catch(() => void 0),
360
+ this.ws.disconnect(connectionId, reason).catch(() => void 0)
361
+ ]);
362
+ }
363
+ /**
364
+ * Run two transport tasks in parallel via `Promise.allSettled`.
365
+ *
366
+ * A rejection in either task is logged as a warning and does not propagate,
367
+ * ensuring one failing transport never blocks delivery on the other.
368
+ */
369
+ async fanOut(op, ...tasks) {
370
+ const results = await Promise.allSettled(tasks.map((t) => t()));
371
+ for (const result of results) {
372
+ if (result.status === "rejected") {
373
+ this.logger.warn(
374
+ `Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
375
+ );
376
+ }
377
+ }
378
+ }
379
+ };
380
+ CompositeTransport = __decorateClass([
381
+ Injectable(),
382
+ __decorateParam(0, Inject(SseTransport)),
383
+ __decorateParam(1, Inject(WebSocketTransport))
384
+ ], CompositeTransport);
385
+ function firstQueryValue(value) {
386
+ return Array.isArray(value) ? value[0] : value;
387
+ }
388
+ var RealtimeGateway = class {
389
+ constructor(transport, options) {
390
+ this.transport = transport;
391
+ this.options = options;
392
+ }
393
+ transport;
394
+ options;
395
+ logger = new Logger(RealtimeGateway.name);
396
+ server;
397
+ /** Wire the resolved Socket.IO server to the transport after gateway init. */
398
+ afterInit(server) {
399
+ this.transport.setServer(server);
400
+ this.logger.log("RealtimeGateway initialized");
401
+ }
402
+ /**
403
+ * Handle a new WebSocket connection.
404
+ *
405
+ * Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
406
+ * three supported auth patterns (spec §8.1):
407
+ * - Cookie HttpOnly — extracted via `parseCookieHeader`.
408
+ * - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
409
+ * - Bearer header — available in `headers.authorization` or via `auth.token`.
410
+ *
411
+ * `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
412
+ * (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
413
+ * context so the authenticator sees a single unified shape regardless of client.
414
+ *
415
+ * Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
416
+ * undefined`); the single-value `ticket` parameter is collapsed to its first
417
+ * element so the authenticator receives a well-defined string.
418
+ *
419
+ * Fail-closed: any thrown error disconnects the socket immediately so it cannot
420
+ * linger in an unregistered state and receive broadcast events.
421
+ */
422
+ async handleConnection(socket) {
423
+ try {
424
+ const { handshake } = socket;
425
+ const headers = this.normalizeHeaders(handshake.headers);
426
+ const query = { ...handshake.query };
427
+ const handshakeAuth = handshake.auth;
428
+ if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
429
+ if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
430
+ const ticket = firstQueryValue(query["ticket"]);
431
+ if (ticket !== void 0) query["ticket"] = ticket;
432
+ const ctx = {
433
+ cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
434
+ headers,
435
+ query,
436
+ ip: handshake.address,
437
+ userAgent: handshake.headers["user-agent"],
438
+ transport: "websocket"
439
+ };
440
+ const auth = await this.transport.authenticator().authenticate(ctx);
441
+ if (!auth) {
442
+ socket.disconnect(true);
443
+ return;
444
+ }
445
+ await this.transport.registerSocket(socket, auth);
446
+ if (this.options.websocket?.emitConnectionEvent !== false) {
447
+ socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
448
+ connectionId: socket.id,
449
+ traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
450
+ });
451
+ }
452
+ } catch (err) {
453
+ this.logger.error(
454
+ `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err.message}`
455
+ );
456
+ socket.disconnect(true);
457
+ }
458
+ }
459
+ /** Handle a WebSocket disconnection — unregister the connection. */
460
+ async handleDisconnect(socket) {
461
+ await this.transport.unregisterSocket(socket.id, "CLIENT_DISCONNECT");
462
+ }
463
+ /**
464
+ * Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
465
+ *
466
+ * Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
467
+ * single string, matching the shape expected by `ConnectionAuthContext.headers`.
468
+ */
469
+ normalizeHeaders(input) {
470
+ const out = {};
471
+ for (const [k, v] of Object.entries(input)) {
472
+ out[k.toLowerCase()] = Array.isArray(v) ? v.join(",") : v;
473
+ }
474
+ return out;
475
+ }
476
+ };
477
+ __decorateClass([
478
+ WebSocketServer()
479
+ ], RealtimeGateway.prototype, "server", 2);
480
+ RealtimeGateway = __decorateClass([
481
+ WebSocketGateway({
482
+ cors: { origin: false }
483
+ }),
484
+ __decorateParam(0, Inject(WebSocketTransport)),
485
+ __decorateParam(1, Inject(REALTIME_OPTIONS_TOKEN))
486
+ ], RealtimeGateway);
487
+
488
+ // src/websocket/websocket-wiring.ts
489
+ var DEFAULT_ASYNC_ENDPOINT = "/events";
490
+ var webSocketWiring = {
491
+ modes: ["websocket", "both"],
492
+ build(resolved) {
493
+ if (resolved.transport === "websocket") {
494
+ return {
495
+ providers: [
496
+ WebSocketTransport,
497
+ { provide: REALTIME_TRANSPORT_TOKEN, useExisting: WebSocketTransport }
498
+ ],
499
+ endpoints: [],
500
+ gateways: [RealtimeGateway]
501
+ };
502
+ }
503
+ return {
504
+ providers: [
505
+ SseTransport,
506
+ WebSocketTransport,
507
+ CompositeTransport,
508
+ SseSubscriptionHandler,
509
+ RealtimePubSubSubscriber,
510
+ { provide: REALTIME_TRANSPORT_TOKEN, useExisting: CompositeTransport }
511
+ ],
512
+ endpoints: [resolved.sse.endpoint],
513
+ gateways: [RealtimeGateway]
514
+ };
515
+ },
516
+ buildAsync(mode) {
517
+ if (mode === "websocket") {
518
+ return {
519
+ providers: [
520
+ WebSocketTransport,
521
+ RealtimeGateway,
522
+ { provide: REALTIME_TRANSPORT_TOKEN, useExisting: WebSocketTransport }
523
+ ],
524
+ controllers: []
525
+ };
526
+ }
527
+ return {
528
+ providers: [
529
+ SseTransport,
530
+ SseSubscriptionHandler,
531
+ WebSocketTransport,
532
+ CompositeTransport,
533
+ RealtimeGateway,
534
+ RealtimePubSubSubscriber,
535
+ { provide: REALTIME_TRANSPORT_TOKEN, useExisting: CompositeTransport }
536
+ ],
537
+ controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
538
+ };
539
+ }
540
+ };
541
+
542
+ // src/websocket/realtime-websocket.module.ts
543
+ var BymaxRealtimeWebSocketModule = class {
544
+ /**
545
+ * Configure the module synchronously.
546
+ *
547
+ * @throws when the options are invalid.
548
+ * @example
549
+ * ```ts
550
+ * BymaxRealtimeWebSocketModule.forRoot({
551
+ * transport: 'websocket',
552
+ * authenticator: new MyAuthenticator(),
553
+ * })
554
+ * ```
555
+ */
556
+ static forRoot(options) {
557
+ return composeForRoot(
558
+ BymaxRealtimeWebSocketModule,
559
+ webSocketWiring,
560
+ BymaxRealtimeWebSocketModule.logger,
561
+ options
562
+ );
563
+ }
564
+ /**
565
+ * Configure the module asynchronously so options — and the authenticator —
566
+ * can be resolved through DI.
567
+ *
568
+ * Controllers are registered at decoration time, so `'both'` binds the SSE
569
+ * controller to the default endpoint `/events`. A non-default endpoint needs
570
+ * `forRoot` with pre-resolved options.
571
+ *
572
+ * @throws when no factory pattern is given, more than one is, or the factory
573
+ * resolves a transport other than the one declared.
574
+ * @example
575
+ * ```ts
576
+ * BymaxRealtimeWebSocketModule.forRootAsync({
577
+ * transport: 'both',
578
+ * imports: [ConfigModule],
579
+ * inject: [ConfigService],
580
+ * useFactory: (cfg: ConfigService) => ({
581
+ * transport: 'both' as const,
582
+ * authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
583
+ * }),
584
+ * })
585
+ * ```
586
+ */
587
+ static forRootAsync(asyncOptions) {
588
+ return composeForRootAsync(
589
+ BymaxRealtimeWebSocketModule,
590
+ webSocketWiring,
591
+ BymaxRealtimeWebSocketModule.logger,
592
+ asyncOptions
593
+ );
594
+ }
595
+ };
596
+ __publicField(BymaxRealtimeWebSocketModule, "logger", new Logger(BymaxRealtimeWebSocketModule.name));
597
+ BymaxRealtimeWebSocketModule = __decorateClass([
598
+ Global(),
599
+ Module({})
600
+ ], BymaxRealtimeWebSocketModule);
601
+ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
602
+ logger = new Logger(_RealtimeIoAdapter.name);
603
+ options;
604
+ constructor(app) {
605
+ super(app);
606
+ this.options = app.get(REALTIME_OPTIONS_TOKEN);
607
+ }
608
+ /**
609
+ * Bind the gateway to `websocket.namespace` when configured.
610
+ *
611
+ * `@WebSocketGateway()` args are evaluated at class-decoration time — before
612
+ * the module options resolve — so the namespace cannot be declared there.
613
+ * Instead we build the root server via `super.create` (which routes through the
614
+ * overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
615
+ * the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
616
+ * and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
617
+ * namespace leaves the root server untouched.
618
+ */
619
+ create(port, options) {
620
+ const server = super.create(port, options);
621
+ const ns = this.options.websocket?.namespace;
622
+ if (ns && ns !== "/" && typeof server.of === "function") {
623
+ return server.of(ns);
624
+ }
625
+ return server;
626
+ }
627
+ /**
628
+ * Create the Socket.IO server with merged WebSocket options.
629
+ *
630
+ * When `websocket.redisAdapter.pubClient` is set, installs the
631
+ * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
632
+ * dep — its absence does not crash the lib).
633
+ */
634
+ createIOServer(port, opts) {
635
+ const wsOpts = this.options.websocket ?? {};
636
+ const mergedOpts = {
637
+ ...opts,
638
+ cors: wsOpts.cors ?? opts?.cors,
639
+ pingInterval: wsOpts.pingIntervalMs ?? 25e3,
640
+ pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
641
+ maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
642
+ };
643
+ const server = super.createIOServer(port, mergedOpts);
644
+ if (wsOpts.redisAdapter?.pubClient) {
645
+ this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
646
+ }
647
+ return server;
648
+ }
649
+ /**
650
+ * Lazily load and install `@socket.io/redis-adapter`.
651
+ *
652
+ * Uses a dynamic `require` so the package stays optional — absent peers do
653
+ * not crash the lib. A load or install failure is logged and tolerated;
654
+ * the lib degrades gracefully to single-instance mode.
655
+ */
656
+ installRedisAdapter(server, pubClient) {
657
+ try {
658
+ const { createAdapter } = __require("@socket.io/redis-adapter");
659
+ const pub = pubClient;
660
+ const sub = pub.duplicate();
661
+ server.adapter(createAdapter(pub, sub));
662
+ this.logger.log(
663
+ "Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
664
+ );
665
+ } catch (err) {
666
+ this.logger.error(
667
+ `Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
668
+ );
669
+ }
670
+ }
671
+ };
672
+
673
+ export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, WebSocketTransport };