@bymax-one/nest-realtime 1.2.6 → 1.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +145 -1
- package/README.md +84 -52
- package/dist/internal/index.cjs +296 -436
- package/dist/internal/index.d.cts +215 -45
- package/dist/internal/index.d.ts +215 -45
- package/dist/internal/index.mjs +295 -437
- package/dist/react/index.cjs +0 -2
- package/dist/react/index.d.cts +2 -1
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.mjs +0 -2
- package/dist/server/index.d.cts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/shared/index.cjs +1 -0
- package/dist/shared/index.d.cts +3 -1
- package/dist/shared/index.d.ts +3 -1
- package/dist/shared/index.mjs +1 -0
- package/dist/websocket/index.cjs +60 -283
- package/dist/websocket/index.d.cts +30 -11
- package/dist/websocket/index.d.ts +30 -11
- package/dist/websocket/index.mjs +61 -284
- package/package.json +3 -3
package/dist/react/index.cjs
CHANGED
|
@@ -216,7 +216,6 @@ function useRealtime(opts) {
|
|
|
216
216
|
return {
|
|
217
217
|
transport: "sse",
|
|
218
218
|
...sseResult,
|
|
219
|
-
// `emit` is WebSocket-exclusive; typed as `never` to prevent accidental use on SSE.
|
|
220
219
|
emit: void 0
|
|
221
220
|
};
|
|
222
221
|
}
|
|
@@ -260,7 +259,6 @@ function usePresence() {
|
|
|
260
259
|
}
|
|
261
260
|
}, [events]);
|
|
262
261
|
return {
|
|
263
|
-
// Sorted for stable, deterministic rendering (matches UsePresenceReturn docs).
|
|
264
262
|
onlineUserIds: Array.from(online).sort(),
|
|
265
263
|
isOnline: (userId) => online.has(userId),
|
|
266
264
|
count: online.size
|
package/dist/react/index.d.cts
CHANGED
|
@@ -242,4 +242,5 @@ interface RealtimeEvent<TData = unknown> {
|
|
|
242
242
|
readonly data: TData;
|
|
243
243
|
}
|
|
244
244
|
|
|
245
|
-
export {
|
|
245
|
+
export { RealtimeProvider, usePresence, useRealtime, useRealtimeConnection, useRealtimeContext };
|
|
246
|
+
export type { RealtimeEvent, TransportMode, UsePresenceReturn, UseRealtimeOptions };
|
package/dist/react/index.d.ts
CHANGED
|
@@ -242,4 +242,5 @@ interface RealtimeEvent<TData = unknown> {
|
|
|
242
242
|
readonly data: TData;
|
|
243
243
|
}
|
|
244
244
|
|
|
245
|
-
export {
|
|
245
|
+
export { RealtimeProvider, usePresence, useRealtime, useRealtimeConnection, useRealtimeContext };
|
|
246
|
+
export type { RealtimeEvent, TransportMode, UsePresenceReturn, UseRealtimeOptions };
|
package/dist/react/index.mjs
CHANGED
|
@@ -214,7 +214,6 @@ function useRealtime(opts) {
|
|
|
214
214
|
return {
|
|
215
215
|
transport: "sse",
|
|
216
216
|
...sseResult,
|
|
217
|
-
// `emit` is WebSocket-exclusive; typed as `never` to prevent accidental use on SSE.
|
|
218
217
|
emit: void 0
|
|
219
218
|
};
|
|
220
219
|
}
|
|
@@ -258,7 +257,6 @@ function usePresence() {
|
|
|
258
257
|
}
|
|
259
258
|
}, [events]);
|
|
260
259
|
return {
|
|
261
|
-
// Sorted for stable, deterministic rendering (matches UsePresenceReturn docs).
|
|
262
260
|
onlineUserIds: Array.from(online).sort(),
|
|
263
261
|
isOnline: (userId) => online.has(userId),
|
|
264
262
|
count: online.size
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
|
1
|
+
export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
|
1
|
+
export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
|
package/dist/shared/index.cjs
CHANGED
|
@@ -30,6 +30,7 @@ var REALTIME_ERROR_CODES = {
|
|
|
30
30
|
TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
|
|
31
31
|
INVALID_TICKET: "REALTIME_INVALID_TICKET",
|
|
32
32
|
PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
|
|
33
|
+
TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE",
|
|
33
34
|
REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
|
|
34
35
|
PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
|
|
35
36
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
package/dist/shared/index.d.cts
CHANGED
|
@@ -153,6 +153,7 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
153
153
|
readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
|
|
154
154
|
readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
|
|
155
155
|
readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
|
|
156
|
+
readonly TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE";
|
|
156
157
|
readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
|
|
157
158
|
readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
|
|
158
159
|
readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
|
|
@@ -160,4 +161,5 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
160
161
|
/** Union of canonical error code values. */
|
|
161
162
|
type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
|
|
162
163
|
|
|
163
|
-
export { PRESENCE_EVENT_NAMES,
|
|
164
|
+
export { PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
|
|
165
|
+
export type { PresenceEventName, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, ReservedEventName, RoomPrefix, TransportMode };
|
package/dist/shared/index.d.ts
CHANGED
|
@@ -153,6 +153,7 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
153
153
|
readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
|
|
154
154
|
readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
|
|
155
155
|
readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
|
|
156
|
+
readonly TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE";
|
|
156
157
|
readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
|
|
157
158
|
readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
|
|
158
159
|
readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
|
|
@@ -160,4 +161,5 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
160
161
|
/** Union of canonical error code values. */
|
|
161
162
|
type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
|
|
162
163
|
|
|
163
|
-
export { PRESENCE_EVENT_NAMES,
|
|
164
|
+
export { PRESENCE_EVENT_NAMES, REALTIME_ERROR_CODES, RESERVED_EVENT_NAMES, ROOM_PREFIXES };
|
|
165
|
+
export type { PresenceEventName, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, ReservedEventName, RoomPrefix, TransportMode };
|
package/dist/shared/index.mjs
CHANGED
|
@@ -28,6 +28,7 @@ var REALTIME_ERROR_CODES = {
|
|
|
28
28
|
TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
|
|
29
29
|
INVALID_TICKET: "REALTIME_INVALID_TICKET",
|
|
30
30
|
PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
|
|
31
|
+
TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE",
|
|
31
32
|
REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
|
|
32
33
|
PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
|
|
33
34
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
package/dist/websocket/index.cjs
CHANGED
|
@@ -40,60 +40,30 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
40
40
|
options;
|
|
41
41
|
kind = "websocket";
|
|
42
42
|
logger = new common.Logger(exports.WebSocketTransport.name);
|
|
43
|
-
/** Nullable until the gateway's afterInit wires the instance. */
|
|
44
43
|
server = null;
|
|
45
|
-
|
|
46
|
-
* Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
|
|
47
|
-
*
|
|
48
|
-
* All emit methods silently no-op until this is called, so the transport is
|
|
49
|
-
* safe to construct before the HTTP server is ready.
|
|
50
|
-
*
|
|
51
|
-
* @param server - The live Socket.IO `Server` instance from the NestJS gateway.
|
|
52
|
-
*/
|
|
44
|
+
warnedUnattached = false;
|
|
53
45
|
setServer(server) {
|
|
54
46
|
this.server = server;
|
|
55
47
|
this.logger.log("Socket.IO server wired to WebSocketTransport");
|
|
56
48
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
49
|
+
attached(op) {
|
|
50
|
+
if (!this.server && !this.warnedUnattached) {
|
|
51
|
+
this.warnedUnattached = true;
|
|
52
|
+
this.logger.warn(
|
|
53
|
+
`${internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE} op=${op}: no WebSocket server is attached yet, so emits are dropped until the gateway initialises`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return this.server;
|
|
57
|
+
}
|
|
66
58
|
localSockets() {
|
|
67
59
|
const server = this.server;
|
|
68
60
|
if (!server) return void 0;
|
|
69
61
|
const sockets = server.sockets;
|
|
70
62
|
return sockets instanceof Map ? sockets : sockets.sockets;
|
|
71
63
|
}
|
|
72
|
-
/**
|
|
73
|
-
* Expose the configured authenticator to the gateway.
|
|
74
|
-
*
|
|
75
|
-
* The gateway uses this to avoid a circular injection: `RealtimeGateway` →
|
|
76
|
-
* `WebSocketTransport` → authenticator, rather than injecting the token
|
|
77
|
-
* directly in the gateway.
|
|
78
|
-
*
|
|
79
|
-
* @returns The consumer-provided `IConnectionAuthenticator` instance.
|
|
80
|
-
*/
|
|
81
64
|
authenticator() {
|
|
82
65
|
return this.auth;
|
|
83
66
|
}
|
|
84
|
-
/**
|
|
85
|
-
* Register a freshly-authenticated WebSocket connection.
|
|
86
|
-
*
|
|
87
|
-
* Stores the connection record in `ConnectionRegistry` (with `subject: null` —
|
|
88
|
-
* WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
|
|
89
|
-
* membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
|
|
90
|
-
*
|
|
91
|
-
* Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
|
|
92
|
-
* does not publish to `IRealtimePubSub`.
|
|
93
|
-
*
|
|
94
|
-
* @param socket - The authenticated Socket.IO socket instance.
|
|
95
|
-
* @param auth - The resolved authentication result containing userId, tenantId, and roles.
|
|
96
|
-
*/
|
|
97
67
|
async registerSocket(socket, auth) {
|
|
98
68
|
const connectedAt = /* @__PURE__ */ new Date();
|
|
99
69
|
this.connections.register({
|
|
@@ -131,16 +101,6 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
131
101
|
connectedAt
|
|
132
102
|
});
|
|
133
103
|
}
|
|
134
|
-
/**
|
|
135
|
-
* Unregister a disconnected WebSocket connection.
|
|
136
|
-
*
|
|
137
|
-
* Removes the record from `ConnectionRegistry`, clears all room membership
|
|
138
|
-
* from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
|
|
139
|
-
* computed `durationMs`.
|
|
140
|
-
*
|
|
141
|
-
* @param connectionId - The Socket.IO socket `id` of the disconnected connection.
|
|
142
|
-
* @param reason - Optional reason string forwarded to the `onDisconnect` hook.
|
|
143
|
-
*/
|
|
144
104
|
async unregisterSocket(connectionId, reason) {
|
|
145
105
|
const record = this.connections.unregister(connectionId);
|
|
146
106
|
if (!record) return;
|
|
@@ -160,51 +120,18 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
160
120
|
};
|
|
161
121
|
await this.hooks.onDisconnect?.(disconnectMeta);
|
|
162
122
|
}
|
|
163
|
-
/**
|
|
164
|
-
* Send an event to every connection of a user (uses `user:{userId}` room).
|
|
165
|
-
*
|
|
166
|
-
* @param userId - Target user identifier.
|
|
167
|
-
* @param event - Event name to emit.
|
|
168
|
-
* @param data - Payload forwarded to all matching connections.
|
|
169
|
-
*/
|
|
170
123
|
async emitToUser(userId, event, data) {
|
|
171
|
-
this.
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
|
|
175
|
-
*
|
|
176
|
-
* @param tenantId - Target tenant identifier.
|
|
177
|
-
* @param event - Event name to emit.
|
|
178
|
-
* @param data - Payload forwarded to all matching connections.
|
|
179
|
-
*/
|
|
124
|
+
this.attached("emitToUser")?.to(`${internal.ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
|
|
125
|
+
}
|
|
180
126
|
async emitToTenant(tenantId, event, data) {
|
|
181
|
-
this.
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Send an event to every connection in an arbitrary room.
|
|
185
|
-
*
|
|
186
|
-
* @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
|
|
187
|
-
* @param event - Event name to emit.
|
|
188
|
-
* @param data - Payload forwarded to all connections in the room.
|
|
189
|
-
*/
|
|
127
|
+
this.attached("emitToTenant")?.to(`${internal.ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
|
|
128
|
+
}
|
|
190
129
|
async emitToRoom(roomId, event, data) {
|
|
191
|
-
this.
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Broadcast an event to all connected clients.
|
|
195
|
-
*
|
|
196
|
-
* @param event - Event name to emit.
|
|
197
|
-
* @param data - Payload forwarded to every connected socket.
|
|
198
|
-
*/
|
|
130
|
+
this.attached("emitToRoom")?.to(roomId).emit(event, data);
|
|
131
|
+
}
|
|
199
132
|
async broadcast(event, data) {
|
|
200
|
-
this.
|
|
201
|
-
}
|
|
202
|
-
/**
|
|
203
|
-
* Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
|
|
204
|
-
*
|
|
205
|
-
* @param connectionId - The socket `id` of the connection to join.
|
|
206
|
-
* @param roomId - The room to join.
|
|
207
|
-
*/
|
|
133
|
+
this.attached("broadcast")?.emit(event, data);
|
|
134
|
+
}
|
|
208
135
|
async joinRoom(connectionId, roomId) {
|
|
209
136
|
const socket = this.localSockets()?.get(connectionId);
|
|
210
137
|
if (socket) {
|
|
@@ -212,12 +139,6 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
212
139
|
this.rooms.join(connectionId, roomId);
|
|
213
140
|
}
|
|
214
141
|
}
|
|
215
|
-
/**
|
|
216
|
-
* Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
|
|
217
|
-
*
|
|
218
|
-
* @param connectionId - The socket `id` of the connection to remove.
|
|
219
|
-
* @param roomId - The room to leave.
|
|
220
|
-
*/
|
|
221
142
|
async leaveRoom(connectionId, roomId) {
|
|
222
143
|
const socket = this.localSockets()?.get(connectionId);
|
|
223
144
|
if (socket) {
|
|
@@ -225,31 +146,29 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
225
146
|
this.rooms.leave(connectionId, roomId);
|
|
226
147
|
}
|
|
227
148
|
}
|
|
228
|
-
/**
|
|
229
|
-
* Force-disconnect a specific connection — adapter-aware, so revocation works
|
|
230
|
-
* across nodes.
|
|
231
|
-
*
|
|
232
|
-
* A socket local to this node is closed directly as a fast path. Regardless,
|
|
233
|
-
* `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
|
|
234
|
-
* under `@socket.io/redis-adapter` this fans out to remote nodes, so a
|
|
235
|
-
* connection pinned to another instance is still force-closed. The local socket
|
|
236
|
-
* has already left the room by then, so the broadcast does not double-close it.
|
|
237
|
-
*
|
|
238
|
-
* @param connectionId - The socket `id` of the connection to disconnect.
|
|
239
|
-
* @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
|
|
240
|
-
*/
|
|
241
149
|
async disconnect(connectionId, _reason) {
|
|
242
150
|
const server = this.server;
|
|
243
|
-
if (!server)
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
151
|
+
if (!server) {
|
|
152
|
+
throw internal.unavailableError(
|
|
153
|
+
internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
|
|
154
|
+
exports.WebSocketTransport.name,
|
|
155
|
+
`the WebSocket server is not attached, so ${connectionId} cannot be revoked`,
|
|
156
|
+
new Error("server not attached")
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
const local = this.localSockets()?.get(connectionId);
|
|
161
|
+
if (local) local.disconnect(true);
|
|
162
|
+
server.in(`${CONNECTION_ROOM_PREFIX}:${connectionId}`).disconnectSockets(true);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
throw internal.unavailableError(
|
|
165
|
+
internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
|
|
166
|
+
exports.WebSocketTransport.name,
|
|
167
|
+
`the revocation of ${connectionId} could not be sent`,
|
|
168
|
+
error
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
253
172
|
async evictBeyondLimit(userId) {
|
|
254
173
|
const max = this.options.websocket?.maxConnectionsPerUser;
|
|
255
174
|
if (max === void 0 || max <= 0) return;
|
|
@@ -281,13 +200,6 @@ exports.CompositeTransport = class CompositeTransport {
|
|
|
281
200
|
ws;
|
|
282
201
|
kind = "sse";
|
|
283
202
|
logger = new common.Logger(exports.CompositeTransport.name);
|
|
284
|
-
/**
|
|
285
|
-
* Emit to all connections of a user across both transports.
|
|
286
|
-
*
|
|
287
|
-
* @param userId - Target user identifier.
|
|
288
|
-
* @param event - Event name to emit.
|
|
289
|
-
* @param data - Payload forwarded to all matching connections.
|
|
290
|
-
*/
|
|
291
203
|
async emitToUser(userId, event, data) {
|
|
292
204
|
await this.fanOut(
|
|
293
205
|
"emitToUser",
|
|
@@ -295,13 +207,6 @@ exports.CompositeTransport = class CompositeTransport {
|
|
|
295
207
|
() => this.ws.emitToUser(userId, event, data)
|
|
296
208
|
);
|
|
297
209
|
}
|
|
298
|
-
/**
|
|
299
|
-
* Emit to all connections within a tenant across both transports.
|
|
300
|
-
*
|
|
301
|
-
* @param tenantId - Target tenant identifier.
|
|
302
|
-
* @param event - Event name to emit.
|
|
303
|
-
* @param data - Payload forwarded to all matching connections.
|
|
304
|
-
*/
|
|
305
210
|
async emitToTenant(tenantId, event, data) {
|
|
306
211
|
await this.fanOut(
|
|
307
212
|
"emitToTenant",
|
|
@@ -309,13 +214,6 @@ exports.CompositeTransport = class CompositeTransport {
|
|
|
309
214
|
() => this.ws.emitToTenant(tenantId, event, data)
|
|
310
215
|
);
|
|
311
216
|
}
|
|
312
|
-
/**
|
|
313
|
-
* Emit to all connections in a room across both transports.
|
|
314
|
-
*
|
|
315
|
-
* @param roomId - The fully-qualified room identifier.
|
|
316
|
-
* @param event - Event name to emit.
|
|
317
|
-
* @param data - Payload forwarded to all connections in the room.
|
|
318
|
-
*/
|
|
319
217
|
async emitToRoom(roomId, event, data) {
|
|
320
218
|
await this.fanOut(
|
|
321
219
|
"emitToRoom",
|
|
@@ -323,12 +221,6 @@ exports.CompositeTransport = class CompositeTransport {
|
|
|
323
221
|
() => this.ws.emitToRoom(roomId, event, data)
|
|
324
222
|
);
|
|
325
223
|
}
|
|
326
|
-
/**
|
|
327
|
-
* Broadcast to all connected clients across both transports.
|
|
328
|
-
*
|
|
329
|
-
* @param event - Event name to emit.
|
|
330
|
-
* @param data - Payload forwarded to every connected client.
|
|
331
|
-
*/
|
|
332
224
|
async broadcast(event, data) {
|
|
333
225
|
await this.fanOut(
|
|
334
226
|
"broadcast",
|
|
@@ -336,47 +228,36 @@ exports.CompositeTransport = class CompositeTransport {
|
|
|
336
228
|
() => this.ws.broadcast(event, data)
|
|
337
229
|
);
|
|
338
230
|
}
|
|
339
|
-
/**
|
|
340
|
-
* Join a connection to a room.
|
|
341
|
-
*
|
|
342
|
-
* Both transports are attempted; only the one that owns the connection
|
|
343
|
-
* succeeds. The other's failure is expected and swallowed.
|
|
344
|
-
*/
|
|
345
231
|
async joinRoom(connectionId, roomId) {
|
|
346
|
-
await
|
|
347
|
-
this.sse.joinRoom(connectionId, roomId)
|
|
348
|
-
this.ws.joinRoom(connectionId, roomId)
|
|
232
|
+
await this.settleBoth("joinRoom", connectionId, [
|
|
233
|
+
() => this.sse.joinRoom(connectionId, roomId),
|
|
234
|
+
() => this.ws.joinRoom(connectionId, roomId)
|
|
349
235
|
]);
|
|
350
236
|
}
|
|
351
|
-
/**
|
|
352
|
-
* Remove a connection from a room.
|
|
353
|
-
*
|
|
354
|
-
* Both transports are attempted tolerantly — one will succeed, the other
|
|
355
|
-
* may fail silently.
|
|
356
|
-
*/
|
|
357
237
|
async leaveRoom(connectionId, roomId) {
|
|
358
|
-
await
|
|
359
|
-
this.sse.leaveRoom(connectionId, roomId)
|
|
360
|
-
this.ws.leaveRoom(connectionId, roomId)
|
|
238
|
+
await this.settleBoth("leaveRoom", connectionId, [
|
|
239
|
+
() => this.sse.leaveRoom(connectionId, roomId),
|
|
240
|
+
() => this.ws.leaveRoom(connectionId, roomId)
|
|
361
241
|
]);
|
|
362
242
|
}
|
|
363
|
-
/**
|
|
364
|
-
* Disconnect a specific connection.
|
|
365
|
-
*
|
|
366
|
-
* Both transports are attempted; the one owning the connection disconnects it.
|
|
367
|
-
*/
|
|
368
243
|
async disconnect(connectionId, reason) {
|
|
369
|
-
await
|
|
370
|
-
this.sse.disconnect(connectionId, reason)
|
|
371
|
-
this.ws.disconnect(connectionId, reason)
|
|
244
|
+
await this.settleBoth("disconnect", connectionId, [
|
|
245
|
+
() => this.sse.disconnect(connectionId, reason),
|
|
246
|
+
() => this.ws.disconnect(connectionId, reason)
|
|
372
247
|
]);
|
|
373
248
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
249
|
+
async settleBoth(op, connectionId, tasks) {
|
|
250
|
+
const results = await Promise.allSettled(tasks.map((t) => t()));
|
|
251
|
+
const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
252
|
+
if (reasons.length === 0) return;
|
|
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
|
+
);
|
|
260
|
+
}
|
|
380
261
|
async fanOut(op, ...tasks) {
|
|
381
262
|
const results = await Promise.allSettled(tasks.map((t) => t()));
|
|
382
263
|
for (const result of results) {
|
|
@@ -402,17 +283,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
|
|
|
402
283
|
super(app);
|
|
403
284
|
this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
|
|
404
285
|
}
|
|
405
|
-
/**
|
|
406
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
407
|
-
*
|
|
408
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
409
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
410
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
411
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
412
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
413
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
414
|
-
* namespace leaves the root server untouched.
|
|
415
|
-
*/
|
|
416
286
|
create(port, options) {
|
|
417
287
|
const server = super.create(port, options);
|
|
418
288
|
const ns = this.options.websocket?.namespace;
|
|
@@ -423,12 +293,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
|
|
|
423
293
|
}
|
|
424
294
|
return server;
|
|
425
295
|
}
|
|
426
|
-
/**
|
|
427
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
428
|
-
*
|
|
429
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
430
|
-
* `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
|
|
431
|
-
*/
|
|
432
296
|
createIOServer(port, opts) {
|
|
433
297
|
const wsOpts = this.options.websocket ?? {};
|
|
434
298
|
const mergedOpts = {
|
|
@@ -450,11 +314,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
|
|
|
450
314
|
realtimeServers.add(server);
|
|
451
315
|
return server;
|
|
452
316
|
}
|
|
453
|
-
/**
|
|
454
|
-
* Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
|
|
455
|
-
* silent single-instance server drops cross-node messages. An unreachable Redis
|
|
456
|
-
* is not one; reconnecting stays with the client.
|
|
457
|
-
*/
|
|
458
317
|
installRedisAdapter(server, pubClient) {
|
|
459
318
|
try {
|
|
460
319
|
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
@@ -487,9 +346,7 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
487
346
|
options;
|
|
488
347
|
logger = new common.Logger(exports.RealtimeGateway.name);
|
|
489
348
|
server;
|
|
490
|
-
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
491
349
|
authenticated = /* @__PURE__ */ new WeakMap();
|
|
492
|
-
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
493
350
|
authenticateHandshake = async (socket, next) => {
|
|
494
351
|
try {
|
|
495
352
|
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
@@ -508,52 +365,18 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
508
365
|
next(new Error("Internal Server Error"));
|
|
509
366
|
}
|
|
510
367
|
};
|
|
511
|
-
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
512
368
|
afterInit(server) {
|
|
513
369
|
server.use(this.authenticateHandshake);
|
|
514
370
|
this.transport.setServer(server);
|
|
515
371
|
if (!isRealtimeIoServer(server)) this.reportMissingAdapter();
|
|
516
372
|
this.logger.log("RealtimeGateway initialized");
|
|
517
373
|
}
|
|
518
|
-
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
519
374
|
reportMissingAdapter() {
|
|
520
375
|
const configured = Object.keys(this.options.websocket ?? {});
|
|
521
376
|
this.logger.error(
|
|
522
377
|
"RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options" + (configured.length > 0 ? ` (${configured.join(", ")})` : "") + " are ignored and the gateway CORS stays closed (origin: false): browsers on another origin cannot connect. Add app.useWebSocketAdapter(new RealtimeIoAdapter(app)) in main.ts, importing it from '@bymax-one/nest-realtime/websocket'."
|
|
523
378
|
);
|
|
524
379
|
}
|
|
525
|
-
/**
|
|
526
|
-
* Handle a new WebSocket connection.
|
|
527
|
-
*
|
|
528
|
-
* Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
|
|
529
|
-
* three supported auth patterns (spec §8.1):
|
|
530
|
-
* - Cookie HttpOnly — extracted via `parseCookieHeader`.
|
|
531
|
-
* - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
|
|
532
|
-
* - Bearer header — available in `headers.authorization` or via `auth.token`.
|
|
533
|
-
*
|
|
534
|
-
* `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
|
|
535
|
-
* (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
|
|
536
|
-
* context so the authenticator sees a single unified shape regardless of client.
|
|
537
|
-
*
|
|
538
|
-
* Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
|
|
539
|
-
* undefined`); the single-value `ticket` parameter is collapsed to its first
|
|
540
|
-
* element so the authenticator receives a well-defined string.
|
|
541
|
-
*
|
|
542
|
-
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
543
|
-
* linger in an unregistered state and receive broadcast events.
|
|
544
|
-
*/
|
|
545
|
-
/**
|
|
546
|
-
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
547
|
-
*
|
|
548
|
-
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
549
|
-
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
550
|
-
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
551
|
-
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
552
|
-
* expects a string is a bug at the far end.
|
|
553
|
-
*
|
|
554
|
-
* @param socket - The connecting Socket.IO socket.
|
|
555
|
-
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
556
|
-
*/
|
|
557
380
|
buildAuthContext(socket) {
|
|
558
381
|
const { handshake } = socket;
|
|
559
382
|
const headers = this.normalizeHeaders(handshake.headers);
|
|
@@ -604,16 +427,9 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
604
427
|
socket.disconnect(true);
|
|
605
428
|
}
|
|
606
429
|
}
|
|
607
|
-
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
608
430
|
async handleDisconnect(socket) {
|
|
609
431
|
await this.transport.unregisterSocket(socket.id, "CLIENT_DISCONNECT");
|
|
610
432
|
}
|
|
611
|
-
/**
|
|
612
|
-
* Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
|
|
613
|
-
*
|
|
614
|
-
* Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
|
|
615
|
-
* single string, matching the shape expected by `ConnectionAuthContext.headers`.
|
|
616
|
-
*/
|
|
617
433
|
normalizeHeaders(input) {
|
|
618
434
|
const out = {};
|
|
619
435
|
for (const [k, v] of Object.entries(input)) {
|
|
@@ -688,18 +504,6 @@ var webSocketWiring = {
|
|
|
688
504
|
|
|
689
505
|
// src/websocket/realtime-websocket.module.ts
|
|
690
506
|
exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
|
|
691
|
-
/**
|
|
692
|
-
* Configure the module synchronously.
|
|
693
|
-
*
|
|
694
|
-
* @throws when the options are invalid.
|
|
695
|
-
* @example
|
|
696
|
-
* ```ts
|
|
697
|
-
* BymaxRealtimeWebSocketModule.forRoot({
|
|
698
|
-
* transport: 'websocket',
|
|
699
|
-
* authenticator: new MyAuthenticator(),
|
|
700
|
-
* })
|
|
701
|
-
* ```
|
|
702
|
-
*/
|
|
703
507
|
static forRoot(options) {
|
|
704
508
|
return internal.composeForRoot(
|
|
705
509
|
exports.BymaxRealtimeWebSocketModule,
|
|
@@ -708,33 +512,6 @@ exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
|
|
|
708
512
|
options
|
|
709
513
|
);
|
|
710
514
|
}
|
|
711
|
-
/**
|
|
712
|
-
* Configure the module asynchronously so options — and the authenticator —
|
|
713
|
-
* can be resolved through DI.
|
|
714
|
-
*
|
|
715
|
-
* Controllers are registered at decoration time, so under `'both'` the SSE
|
|
716
|
-
* route comes from `sseEndpoint` on the registration rather than from the
|
|
717
|
-
* `sse.endpoint` the factory resolves — the factory has not run yet when the
|
|
718
|
-
* controller is built. It defaults to `/events`, and a factory that resolves
|
|
719
|
-
* a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
|
|
720
|
-
* registers no SSE controller, so `sseEndpoint` is rejected there outright.
|
|
721
|
-
*
|
|
722
|
-
* @throws when no factory pattern is given, more than one is, or the factory
|
|
723
|
-
* resolves a transport other than the one declared.
|
|
724
|
-
* @example
|
|
725
|
-
* ```ts
|
|
726
|
-
* BymaxRealtimeWebSocketModule.forRootAsync({
|
|
727
|
-
* transport: 'both',
|
|
728
|
-
* sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
|
|
729
|
-
* imports: [ConfigModule],
|
|
730
|
-
* inject: [ConfigService],
|
|
731
|
-
* useFactory: (cfg: ConfigService) => ({
|
|
732
|
-
* transport: 'both' as const,
|
|
733
|
-
* authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
|
|
734
|
-
* }),
|
|
735
|
-
* })
|
|
736
|
-
* ```
|
|
737
|
-
*/
|
|
738
515
|
static forRootAsync(asyncOptions) {
|
|
739
516
|
return internal.composeForRootAsync(
|
|
740
517
|
exports.BymaxRealtimeWebSocketModule,
|