@bymax-one/nest-realtime 1.2.7 → 1.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +150 -1
- package/README.md +5 -3
- package/dist/internal/index.cjs +194 -499
- package/dist/internal/index.d.cts +83 -6
- package/dist/internal/index.d.ts +83 -6
- package/dist/internal/index.mjs +195 -501
- 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/shared/index.d.cts +2 -1
- package/dist/shared/index.d.ts +2 -1
- package/dist/websocket/index.cjs +17 -288
- package/dist/websocket/index.d.cts +6 -3
- package/dist/websocket/index.d.ts +6 -3
- package/dist/websocket/index.mjs +18 -289
- package/package.json +5 -4
package/dist/websocket/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
|
|
3
|
-
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
|
|
3
|
+
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, unavailableError, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, describeError, parseCookieHeader, RESERVED_EVENT_NAMES, realtimeError } from '@bymax-one/nest-realtime/internal';
|
|
4
4
|
import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
|
|
5
5
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
6
6
|
|
|
@@ -40,25 +40,12 @@ var WebSocketTransport = class {
|
|
|
40
40
|
options;
|
|
41
41
|
kind = "websocket";
|
|
42
42
|
logger = new Logger(WebSocketTransport.name);
|
|
43
|
-
/** Nullable until the gateway's afterInit wires the instance. */
|
|
44
43
|
server = null;
|
|
45
44
|
warnedUnattached = false;
|
|
46
|
-
/**
|
|
47
|
-
* Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
|
|
48
|
-
*
|
|
49
|
-
* Until this is called an emit delivers nothing and still resolves, with one warning for
|
|
50
|
-
* the first, so the transport is safe to construct before the HTTP server is ready.
|
|
51
|
-
*
|
|
52
|
-
* @param server - The live Socket.IO `Server` instance from the NestJS gateway.
|
|
53
|
-
*/
|
|
54
45
|
setServer(server) {
|
|
55
46
|
this.server = server;
|
|
56
47
|
this.logger.log("Socket.IO server wired to WebSocketTransport");
|
|
57
48
|
}
|
|
58
|
-
/**
|
|
59
|
-
* The attached server, or `null` before the gateway attaches one. An emit made before
|
|
60
|
-
* then delivers nothing and still resolves; that is logged once, not once per emit.
|
|
61
|
-
*/
|
|
62
49
|
attached(op) {
|
|
63
50
|
if (!this.server && !this.warnedUnattached) {
|
|
64
51
|
this.warnedUnattached = true;
|
|
@@ -68,46 +55,15 @@ var WebSocketTransport = class {
|
|
|
68
55
|
}
|
|
69
56
|
return this.server;
|
|
70
57
|
}
|
|
71
|
-
/**
|
|
72
|
-
* Resolve the map of locally-connected sockets, tolerating both server shapes.
|
|
73
|
-
*
|
|
74
|
-
* A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
|
|
75
|
-
* `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
|
|
76
|
-
* `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
|
|
77
|
-
* `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
|
|
78
|
-
* this indirection so they work under either shape.
|
|
79
|
-
*/
|
|
80
58
|
localSockets() {
|
|
81
59
|
const server = this.server;
|
|
82
60
|
if (!server) return void 0;
|
|
83
61
|
const sockets = server.sockets;
|
|
84
62
|
return sockets instanceof Map ? sockets : sockets.sockets;
|
|
85
63
|
}
|
|
86
|
-
/**
|
|
87
|
-
* Expose the configured authenticator to the gateway.
|
|
88
|
-
*
|
|
89
|
-
* The gateway uses this to avoid a circular injection: `RealtimeGateway` →
|
|
90
|
-
* `WebSocketTransport` → authenticator, rather than injecting the token
|
|
91
|
-
* directly in the gateway.
|
|
92
|
-
*
|
|
93
|
-
* @returns The consumer-provided `IConnectionAuthenticator` instance.
|
|
94
|
-
*/
|
|
95
64
|
authenticator() {
|
|
96
65
|
return this.auth;
|
|
97
66
|
}
|
|
98
|
-
/**
|
|
99
|
-
* Register a freshly-authenticated WebSocket connection.
|
|
100
|
-
*
|
|
101
|
-
* Stores the connection record in `ConnectionRegistry` (with `subject: null` —
|
|
102
|
-
* WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
|
|
103
|
-
* membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
|
|
104
|
-
*
|
|
105
|
-
* Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
|
|
106
|
-
* does not publish to `IRealtimePubSub`.
|
|
107
|
-
*
|
|
108
|
-
* @param socket - The authenticated Socket.IO socket instance.
|
|
109
|
-
* @param auth - The resolved authentication result containing userId, tenantId, and roles.
|
|
110
|
-
*/
|
|
111
67
|
async registerSocket(socket, auth) {
|
|
112
68
|
const connectedAt = /* @__PURE__ */ new Date();
|
|
113
69
|
this.connections.register({
|
|
@@ -145,16 +101,6 @@ var WebSocketTransport = class {
|
|
|
145
101
|
connectedAt
|
|
146
102
|
});
|
|
147
103
|
}
|
|
148
|
-
/**
|
|
149
|
-
* Unregister a disconnected WebSocket connection.
|
|
150
|
-
*
|
|
151
|
-
* Removes the record from `ConnectionRegistry`, clears all room membership
|
|
152
|
-
* from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
|
|
153
|
-
* computed `durationMs`.
|
|
154
|
-
*
|
|
155
|
-
* @param connectionId - The Socket.IO socket `id` of the disconnected connection.
|
|
156
|
-
* @param reason - Optional reason string forwarded to the `onDisconnect` hook.
|
|
157
|
-
*/
|
|
158
104
|
async unregisterSocket(connectionId, reason) {
|
|
159
105
|
const record = this.connections.unregister(connectionId);
|
|
160
106
|
if (!record) return;
|
|
@@ -174,51 +120,18 @@ var WebSocketTransport = class {
|
|
|
174
120
|
};
|
|
175
121
|
await this.hooks.onDisconnect?.(disconnectMeta);
|
|
176
122
|
}
|
|
177
|
-
/**
|
|
178
|
-
* Send an event to every connection of a user (uses `user:{userId}` room).
|
|
179
|
-
*
|
|
180
|
-
* @param userId - Target user identifier.
|
|
181
|
-
* @param event - Event name to emit.
|
|
182
|
-
* @param data - Payload forwarded to all matching connections.
|
|
183
|
-
*/
|
|
184
123
|
async emitToUser(userId, event, data) {
|
|
185
124
|
this.attached("emitToUser")?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
|
|
186
125
|
}
|
|
187
|
-
/**
|
|
188
|
-
* Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
|
|
189
|
-
*
|
|
190
|
-
* @param tenantId - Target tenant identifier.
|
|
191
|
-
* @param event - Event name to emit.
|
|
192
|
-
* @param data - Payload forwarded to all matching connections.
|
|
193
|
-
*/
|
|
194
126
|
async emitToTenant(tenantId, event, data) {
|
|
195
127
|
this.attached("emitToTenant")?.to(`${ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
|
|
196
128
|
}
|
|
197
|
-
/**
|
|
198
|
-
* Send an event to every connection in an arbitrary room.
|
|
199
|
-
*
|
|
200
|
-
* @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
|
|
201
|
-
* @param event - Event name to emit.
|
|
202
|
-
* @param data - Payload forwarded to all connections in the room.
|
|
203
|
-
*/
|
|
204
129
|
async emitToRoom(roomId, event, data) {
|
|
205
130
|
this.attached("emitToRoom")?.to(roomId).emit(event, data);
|
|
206
131
|
}
|
|
207
|
-
/**
|
|
208
|
-
* Broadcast an event to all connected clients.
|
|
209
|
-
*
|
|
210
|
-
* @param event - Event name to emit.
|
|
211
|
-
* @param data - Payload forwarded to every connected socket.
|
|
212
|
-
*/
|
|
213
132
|
async broadcast(event, data) {
|
|
214
133
|
this.attached("broadcast")?.emit(event, data);
|
|
215
134
|
}
|
|
216
|
-
/**
|
|
217
|
-
* Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
|
|
218
|
-
*
|
|
219
|
-
* @param connectionId - The socket `id` of the connection to join.
|
|
220
|
-
* @param roomId - The room to join.
|
|
221
|
-
*/
|
|
222
135
|
async joinRoom(connectionId, roomId) {
|
|
223
136
|
const socket = this.localSockets()?.get(connectionId);
|
|
224
137
|
if (socket) {
|
|
@@ -226,12 +139,6 @@ var WebSocketTransport = class {
|
|
|
226
139
|
this.rooms.join(connectionId, roomId);
|
|
227
140
|
}
|
|
228
141
|
}
|
|
229
|
-
/**
|
|
230
|
-
* Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
|
|
231
|
-
*
|
|
232
|
-
* @param connectionId - The socket `id` of the connection to remove.
|
|
233
|
-
* @param roomId - The room to leave.
|
|
234
|
-
*/
|
|
235
142
|
async leaveRoom(connectionId, roomId) {
|
|
236
143
|
const socket = this.localSockets()?.get(connectionId);
|
|
237
144
|
if (socket) {
|
|
@@ -239,21 +146,6 @@ var WebSocketTransport = class {
|
|
|
239
146
|
this.rooms.leave(connectionId, roomId);
|
|
240
147
|
}
|
|
241
148
|
}
|
|
242
|
-
/**
|
|
243
|
-
* Force-disconnect a specific connection — adapter-aware, so revocation works
|
|
244
|
-
* across nodes.
|
|
245
|
-
*
|
|
246
|
-
* A socket local to this node is closed directly as a fast path. Regardless,
|
|
247
|
-
* `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
|
|
248
|
-
* under `@socket.io/redis-adapter` this fans out to remote nodes, so a
|
|
249
|
-
* connection pinned to another instance is still force-closed. The local socket
|
|
250
|
-
* has already left the room by then, so the broadcast does not double-close it.
|
|
251
|
-
*
|
|
252
|
-
* @param connectionId - The socket `id` of the connection to disconnect.
|
|
253
|
-
* @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
|
|
254
|
-
* @throws {Error} `REALTIME_TRANSPORT_UNAVAILABLE` when no server is attached or the
|
|
255
|
-
* fan-out throws: the revocation did not leave this node.
|
|
256
|
-
*/
|
|
257
149
|
async disconnect(connectionId, _reason) {
|
|
258
150
|
const server = this.server;
|
|
259
151
|
if (!server) {
|
|
@@ -277,11 +169,6 @@ var WebSocketTransport = class {
|
|
|
277
169
|
);
|
|
278
170
|
}
|
|
279
171
|
}
|
|
280
|
-
/**
|
|
281
|
-
* Evict the user's oldest WebSocket connections (FIFO) when over
|
|
282
|
-
* `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
|
|
283
|
-
* as the disconnect reason — never rejects the new connection with HTTP 429.
|
|
284
|
-
*/
|
|
285
172
|
async evictBeyondLimit(userId) {
|
|
286
173
|
const max = this.options.websocket?.maxConnectionsPerUser;
|
|
287
174
|
if (max === void 0 || max <= 0) return;
|
|
@@ -313,13 +200,6 @@ var CompositeTransport = class {
|
|
|
313
200
|
ws;
|
|
314
201
|
kind = "sse";
|
|
315
202
|
logger = new Logger(CompositeTransport.name);
|
|
316
|
-
/**
|
|
317
|
-
* Emit to all connections of a user across both transports.
|
|
318
|
-
*
|
|
319
|
-
* @param userId - Target user identifier.
|
|
320
|
-
* @param event - Event name to emit.
|
|
321
|
-
* @param data - Payload forwarded to all matching connections.
|
|
322
|
-
*/
|
|
323
203
|
async emitToUser(userId, event, data) {
|
|
324
204
|
await this.fanOut(
|
|
325
205
|
"emitToUser",
|
|
@@ -327,13 +207,6 @@ var CompositeTransport = class {
|
|
|
327
207
|
() => this.ws.emitToUser(userId, event, data)
|
|
328
208
|
);
|
|
329
209
|
}
|
|
330
|
-
/**
|
|
331
|
-
* Emit to all connections within a tenant across both transports.
|
|
332
|
-
*
|
|
333
|
-
* @param tenantId - Target tenant identifier.
|
|
334
|
-
* @param event - Event name to emit.
|
|
335
|
-
* @param data - Payload forwarded to all matching connections.
|
|
336
|
-
*/
|
|
337
210
|
async emitToTenant(tenantId, event, data) {
|
|
338
211
|
await this.fanOut(
|
|
339
212
|
"emitToTenant",
|
|
@@ -341,13 +214,6 @@ var CompositeTransport = class {
|
|
|
341
214
|
() => this.ws.emitToTenant(tenantId, event, data)
|
|
342
215
|
);
|
|
343
216
|
}
|
|
344
|
-
/**
|
|
345
|
-
* Emit to all connections in a room across both transports.
|
|
346
|
-
*
|
|
347
|
-
* @param roomId - The fully-qualified room identifier.
|
|
348
|
-
* @param event - Event name to emit.
|
|
349
|
-
* @param data - Payload forwarded to all connections in the room.
|
|
350
|
-
*/
|
|
351
217
|
async emitToRoom(roomId, event, data) {
|
|
352
218
|
await this.fanOut(
|
|
353
219
|
"emitToRoom",
|
|
@@ -355,12 +221,6 @@ var CompositeTransport = class {
|
|
|
355
221
|
() => this.ws.emitToRoom(roomId, event, data)
|
|
356
222
|
);
|
|
357
223
|
}
|
|
358
|
-
/**
|
|
359
|
-
* Broadcast to all connected clients across both transports.
|
|
360
|
-
*
|
|
361
|
-
* @param event - Event name to emit.
|
|
362
|
-
* @param data - Payload forwarded to every connected client.
|
|
363
|
-
*/
|
|
364
224
|
async broadcast(event, data) {
|
|
365
225
|
await this.fanOut(
|
|
366
226
|
"broadcast",
|
|
@@ -368,75 +228,47 @@ var CompositeTransport = class {
|
|
|
368
228
|
() => this.ws.broadcast(event, data)
|
|
369
229
|
);
|
|
370
230
|
}
|
|
371
|
-
/**
|
|
372
|
-
* Join a connection to a room.
|
|
373
|
-
*
|
|
374
|
-
* Both transports are asked; the one that holds the connection acts. Rejects with the
|
|
375
|
-
* failure of whichever transport failed.
|
|
376
|
-
*/
|
|
377
231
|
async joinRoom(connectionId, roomId) {
|
|
378
232
|
await this.settleBoth("joinRoom", connectionId, [
|
|
379
233
|
() => this.sse.joinRoom(connectionId, roomId),
|
|
380
234
|
() => this.ws.joinRoom(connectionId, roomId)
|
|
381
235
|
]);
|
|
382
236
|
}
|
|
383
|
-
/**
|
|
384
|
-
* Remove a connection from a room.
|
|
385
|
-
*
|
|
386
|
-
* Both transports are asked; the one that holds the connection acts. Rejects with the
|
|
387
|
-
* failure of whichever transport failed: a client left in a room it was removed from keeps
|
|
388
|
-
* receiving that room's events.
|
|
389
|
-
*/
|
|
390
237
|
async leaveRoom(connectionId, roomId) {
|
|
391
238
|
await this.settleBoth("leaveRoom", connectionId, [
|
|
392
239
|
() => this.sse.leaveRoom(connectionId, roomId),
|
|
393
240
|
() => this.ws.leaveRoom(connectionId, roomId)
|
|
394
241
|
]);
|
|
395
242
|
}
|
|
396
|
-
/**
|
|
397
|
-
* Disconnect a specific connection.
|
|
398
|
-
*
|
|
399
|
-
* Both transports are asked; the one that holds the connection disconnects it. Rejects when
|
|
400
|
-
* either one could not: the revocation has not reached the connection.
|
|
401
|
-
*/
|
|
402
243
|
async disconnect(connectionId, reason) {
|
|
403
244
|
await this.settleBoth("disconnect", connectionId, [
|
|
404
245
|
() => this.sse.disconnect(connectionId, reason),
|
|
405
246
|
() => this.ws.disconnect(connectionId, reason)
|
|
406
247
|
]);
|
|
407
248
|
}
|
|
408
|
-
/**
|
|
409
|
-
* Run a per-connection operation on both transports and reject if either failed.
|
|
410
|
-
*
|
|
411
|
-
* One failure is rethrown as it is; both are reported together under
|
|
412
|
-
* `REALTIME_TRANSPORT_UNAVAILABLE`, with every reason in `cause`.
|
|
413
|
-
*/
|
|
414
249
|
async settleBoth(op, connectionId, tasks) {
|
|
415
250
|
const results = await Promise.allSettled(tasks.map((t) => t()));
|
|
416
251
|
const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
417
252
|
if (reasons.length === 0) return;
|
|
418
253
|
if (reasons.length === 1) throw reasons[0];
|
|
419
|
-
throw
|
|
420
|
-
REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
|
|
421
|
-
CompositeTransport.name,
|
|
422
|
-
`${op} of ${connectionId} failed on both transports`,
|
|
423
|
-
new AggregateError(reasons, reasons.map(describeError).join("; "))
|
|
424
|
-
);
|
|
254
|
+
throw this.allFailed(`${op} of ${connectionId}`, reasons);
|
|
425
255
|
}
|
|
426
|
-
/**
|
|
427
|
-
* Run two transport tasks in parallel via `Promise.allSettled`.
|
|
428
|
-
*
|
|
429
|
-
* A rejection in either task is logged as a warning and does not propagate,
|
|
430
|
-
* ensuring one failing transport never blocks delivery on the other.
|
|
431
|
-
*/
|
|
432
256
|
async fanOut(op, ...tasks) {
|
|
433
257
|
const results = await Promise.allSettled(tasks.map((t) => t()));
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
}
|
|
258
|
+
const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
259
|
+
if (reasons.length === tasks.length) throw this.allFailed(op, reasons);
|
|
260
|
+
for (const reason of reasons) {
|
|
261
|
+
this.logger.warn(`Composite ${op} partially failed: ${describeError(reason)}`);
|
|
438
262
|
}
|
|
439
263
|
}
|
|
264
|
+
allFailed(what, reasons) {
|
|
265
|
+
return unavailableError(
|
|
266
|
+
REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
|
|
267
|
+
CompositeTransport.name,
|
|
268
|
+
`${what} failed on both transports`,
|
|
269
|
+
new AggregateError(reasons, reasons.map(describeError).join("; "))
|
|
270
|
+
);
|
|
271
|
+
}
|
|
440
272
|
};
|
|
441
273
|
CompositeTransport = __decorateClass([
|
|
442
274
|
Injectable(),
|
|
@@ -454,17 +286,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
|
454
286
|
super(app);
|
|
455
287
|
this.options = app.get(REALTIME_OPTIONS_TOKEN);
|
|
456
288
|
}
|
|
457
|
-
/**
|
|
458
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
459
|
-
*
|
|
460
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
461
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
462
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
463
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
464
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
465
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
466
|
-
* namespace leaves the root server untouched.
|
|
467
|
-
*/
|
|
468
289
|
create(port, options) {
|
|
469
290
|
const server = super.create(port, options);
|
|
470
291
|
const ns = this.options.websocket?.namespace;
|
|
@@ -475,12 +296,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
|
475
296
|
}
|
|
476
297
|
return server;
|
|
477
298
|
}
|
|
478
|
-
/**
|
|
479
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
480
|
-
*
|
|
481
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
482
|
-
* `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
|
|
483
|
-
*/
|
|
484
299
|
createIOServer(port, opts) {
|
|
485
300
|
const wsOpts = this.options.websocket ?? {};
|
|
486
301
|
const mergedOpts = {
|
|
@@ -502,11 +317,6 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
|
502
317
|
realtimeServers.add(server);
|
|
503
318
|
return server;
|
|
504
319
|
}
|
|
505
|
-
/**
|
|
506
|
-
* Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
|
|
507
|
-
* silent single-instance server drops cross-node messages. An unreachable Redis
|
|
508
|
-
* is not one; reconnecting stays with the client.
|
|
509
|
-
*/
|
|
510
320
|
installRedisAdapter(server, pubClient) {
|
|
511
321
|
try {
|
|
512
322
|
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
@@ -515,9 +325,10 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
|
515
325
|
server.adapter(createAdapter(pub, sub));
|
|
516
326
|
} catch (err) {
|
|
517
327
|
const reason = describeError(err);
|
|
518
|
-
throw
|
|
519
|
-
|
|
520
|
-
{
|
|
328
|
+
throw realtimeError(
|
|
329
|
+
REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
|
|
330
|
+
`websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed (${reason}). Install @socket.io/redis-adapter and pass an ioredis client as pubClient.`,
|
|
331
|
+
{ who: _RealtimeIoAdapter.name, cause: err }
|
|
521
332
|
);
|
|
522
333
|
}
|
|
523
334
|
this.adapterLogger.log(
|
|
@@ -539,9 +350,7 @@ var RealtimeGateway = class {
|
|
|
539
350
|
options;
|
|
540
351
|
logger = new Logger(RealtimeGateway.name);
|
|
541
352
|
server;
|
|
542
|
-
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
543
353
|
authenticated = /* @__PURE__ */ new WeakMap();
|
|
544
|
-
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
545
354
|
authenticateHandshake = async (socket, next) => {
|
|
546
355
|
try {
|
|
547
356
|
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
@@ -560,52 +369,18 @@ var RealtimeGateway = class {
|
|
|
560
369
|
next(new Error("Internal Server Error"));
|
|
561
370
|
}
|
|
562
371
|
};
|
|
563
|
-
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
564
372
|
afterInit(server) {
|
|
565
373
|
server.use(this.authenticateHandshake);
|
|
566
374
|
this.transport.setServer(server);
|
|
567
375
|
if (!isRealtimeIoServer(server)) this.reportMissingAdapter();
|
|
568
376
|
this.logger.log("RealtimeGateway initialized");
|
|
569
377
|
}
|
|
570
|
-
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
571
378
|
reportMissingAdapter() {
|
|
572
379
|
const configured = Object.keys(this.options.websocket ?? {});
|
|
573
380
|
this.logger.error(
|
|
574
381
|
"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'."
|
|
575
382
|
);
|
|
576
383
|
}
|
|
577
|
-
/**
|
|
578
|
-
* Handle a new WebSocket connection.
|
|
579
|
-
*
|
|
580
|
-
* Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
|
|
581
|
-
* three supported auth patterns (spec §8.1):
|
|
582
|
-
* - Cookie HttpOnly — extracted via `parseCookieHeader`.
|
|
583
|
-
* - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
|
|
584
|
-
* - Bearer header — available in `headers.authorization` or via `auth.token`.
|
|
585
|
-
*
|
|
586
|
-
* `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
|
|
587
|
-
* (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
|
|
588
|
-
* context so the authenticator sees a single unified shape regardless of client.
|
|
589
|
-
*
|
|
590
|
-
* Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
|
|
591
|
-
* undefined`); the single-value `ticket` parameter is collapsed to its first
|
|
592
|
-
* element so the authenticator receives a well-defined string.
|
|
593
|
-
*
|
|
594
|
-
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
595
|
-
* linger in an unregistered state and receive broadcast events.
|
|
596
|
-
*/
|
|
597
|
-
/**
|
|
598
|
-
* Map a Socket.IO handshake onto the transport-agnostic auth context.
|
|
599
|
-
*
|
|
600
|
-
* Socket.IO carries credentials in three places and the authenticator sees one
|
|
601
|
-
* shape: `handshake.auth` is merged into the headers and query it stands in for,
|
|
602
|
-
* and a repeated `ticket` parameter is collapsed to its first value, because the
|
|
603
|
-
* ticket pattern is single-valued and an array reaching an authenticator that
|
|
604
|
-
* expects a string is a bug at the far end.
|
|
605
|
-
*
|
|
606
|
-
* @param socket - The connecting Socket.IO socket.
|
|
607
|
-
* @returns The context handed to `IConnectionAuthenticator.authenticate`.
|
|
608
|
-
*/
|
|
609
384
|
buildAuthContext(socket) {
|
|
610
385
|
const { handshake } = socket;
|
|
611
386
|
const headers = this.normalizeHeaders(handshake.headers);
|
|
@@ -656,16 +431,9 @@ var RealtimeGateway = class {
|
|
|
656
431
|
socket.disconnect(true);
|
|
657
432
|
}
|
|
658
433
|
}
|
|
659
|
-
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
660
434
|
async handleDisconnect(socket) {
|
|
661
435
|
await this.transport.unregisterSocket(socket.id, "CLIENT_DISCONNECT");
|
|
662
436
|
}
|
|
663
|
-
/**
|
|
664
|
-
* Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
|
|
665
|
-
*
|
|
666
|
-
* Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
|
|
667
|
-
* single string, matching the shape expected by `ConnectionAuthContext.headers`.
|
|
668
|
-
*/
|
|
669
437
|
normalizeHeaders(input) {
|
|
670
438
|
const out = {};
|
|
671
439
|
for (const [k, v] of Object.entries(input)) {
|
|
@@ -740,18 +508,6 @@ var webSocketWiring = {
|
|
|
740
508
|
|
|
741
509
|
// src/websocket/realtime-websocket.module.ts
|
|
742
510
|
var BymaxRealtimeWebSocketModule = class {
|
|
743
|
-
/**
|
|
744
|
-
* Configure the module synchronously.
|
|
745
|
-
*
|
|
746
|
-
* @throws when the options are invalid.
|
|
747
|
-
* @example
|
|
748
|
-
* ```ts
|
|
749
|
-
* BymaxRealtimeWebSocketModule.forRoot({
|
|
750
|
-
* transport: 'websocket',
|
|
751
|
-
* authenticator: new MyAuthenticator(),
|
|
752
|
-
* })
|
|
753
|
-
* ```
|
|
754
|
-
*/
|
|
755
511
|
static forRoot(options) {
|
|
756
512
|
return composeForRoot(
|
|
757
513
|
BymaxRealtimeWebSocketModule,
|
|
@@ -760,33 +516,6 @@ var BymaxRealtimeWebSocketModule = class {
|
|
|
760
516
|
options
|
|
761
517
|
);
|
|
762
518
|
}
|
|
763
|
-
/**
|
|
764
|
-
* Configure the module asynchronously so options — and the authenticator —
|
|
765
|
-
* can be resolved through DI.
|
|
766
|
-
*
|
|
767
|
-
* Controllers are registered at decoration time, so under `'both'` the SSE
|
|
768
|
-
* route comes from `sseEndpoint` on the registration rather than from the
|
|
769
|
-
* `sse.endpoint` the factory resolves — the factory has not run yet when the
|
|
770
|
-
* controller is built. It defaults to `/events`, and a factory that resolves
|
|
771
|
-
* a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
|
|
772
|
-
* registers no SSE controller, so `sseEndpoint` is rejected there outright.
|
|
773
|
-
*
|
|
774
|
-
* @throws when no factory pattern is given, more than one is, or the factory
|
|
775
|
-
* resolves a transport other than the one declared.
|
|
776
|
-
* @example
|
|
777
|
-
* ```ts
|
|
778
|
-
* BymaxRealtimeWebSocketModule.forRootAsync({
|
|
779
|
-
* transport: 'both',
|
|
780
|
-
* sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
|
|
781
|
-
* imports: [ConfigModule],
|
|
782
|
-
* inject: [ConfigService],
|
|
783
|
-
* useFactory: (cfg: ConfigService) => ({
|
|
784
|
-
* transport: 'both' as const,
|
|
785
|
-
* authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
|
|
786
|
-
* }),
|
|
787
|
-
* })
|
|
788
|
-
* ```
|
|
789
|
-
*/
|
|
790
519
|
static forRootAsync(asyncOptions) {
|
|
791
520
|
return composeForRootAsync(
|
|
792
521
|
BymaxRealtimeWebSocketModule,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bymax-one/nest-realtime",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.9",
|
|
4
4
|
"description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
|
|
5
5
|
"author": "Bymax One <support@bymax.one>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -93,9 +93,10 @@
|
|
|
93
93
|
}
|
|
94
94
|
},
|
|
95
95
|
"scripts": {
|
|
96
|
-
"build": "pnpm clean && tsup",
|
|
96
|
+
"build": "pnpm clean && tsup && node scripts/strip-bundle-comments.mjs",
|
|
97
97
|
"check:exports": "attw --pack . --profile strict",
|
|
98
98
|
"check:mutants": "node scripts/check-mutation-directives.mjs",
|
|
99
|
+
"check:file-size": "node scripts/check-file-size.mjs",
|
|
99
100
|
"check:api": "node scripts/check-api-surface.mjs",
|
|
100
101
|
"check:published": "node scripts/check-published-surface.mjs",
|
|
101
102
|
"check:runtime": "node scripts/check-consumer-runtime.mjs",
|
|
@@ -107,7 +108,7 @@
|
|
|
107
108
|
"mutation": "stryker run",
|
|
108
109
|
"mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
|
|
109
110
|
"mutation:dry-run": "stryker run --dryRunOnly",
|
|
110
|
-
"prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm check:runtime",
|
|
111
|
+
"prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm check:file-size && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm check:runtime",
|
|
111
112
|
"release": "npm publish --provenance --access public",
|
|
112
113
|
"size": "node scripts/check-size.mjs",
|
|
113
114
|
"test": "jest",
|
|
@@ -206,7 +207,7 @@
|
|
|
206
207
|
"ts-jest": "^29.4.12",
|
|
207
208
|
"ts-node": "^10.9.0",
|
|
208
209
|
"tslib": "^2.6.0",
|
|
209
|
-
"tsup": "^
|
|
210
|
+
"tsup": "^9.0.0",
|
|
210
211
|
"typescript": "^5.6.0"
|
|
211
212
|
},
|
|
212
213
|
"packageManager": "pnpm@11.20.0",
|