@bymax-one/nest-realtime 1.2.16 → 1.2.18
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 +63 -3
- package/README.md +31 -22
- package/dist/internal/index.cjs +349 -88
- package/dist/internal/index.d.cts +53 -11
- package/dist/internal/index.d.ts +53 -11
- package/dist/internal/index.mjs +348 -89
- package/dist/react/index.cjs +163 -101
- package/dist/react/index.mjs +164 -102
- package/dist/websocket/index.cjs +18 -3
- package/dist/websocket/index.d.cts +4 -0
- package/dist/websocket/index.d.ts +4 -0
- package/dist/websocket/index.mjs +19 -4
- package/package.json +4 -3
package/dist/internal/index.mjs
CHANGED
|
@@ -41,6 +41,76 @@ var REALTIME_ERROR_CODES = {
|
|
|
41
41
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
|
42
42
|
};
|
|
43
43
|
|
|
44
|
+
// src/server/config/drop-unset.ts
|
|
45
|
+
var SSE_KEYS = {
|
|
46
|
+
endpoint: true,
|
|
47
|
+
heartbeatMs: true,
|
|
48
|
+
replayBufferSize: true,
|
|
49
|
+
replayTtlMs: true,
|
|
50
|
+
replayMaxIdleUsers: true,
|
|
51
|
+
maxConnectionsPerUser: true,
|
|
52
|
+
emitConnectionEvent: true,
|
|
53
|
+
maxQueuedBytes: true,
|
|
54
|
+
maxQueuedEvents: true,
|
|
55
|
+
stallHeartbeats: true
|
|
56
|
+
};
|
|
57
|
+
var WEBSOCKET_KEYS = {
|
|
58
|
+
namespace: true,
|
|
59
|
+
cors: true,
|
|
60
|
+
maxHttpBufferSize: true,
|
|
61
|
+
pingIntervalMs: true,
|
|
62
|
+
pingTimeoutMs: true,
|
|
63
|
+
maxConnectionsPerUser: true,
|
|
64
|
+
emitConnectionEvent: true,
|
|
65
|
+
redisAdapter: true
|
|
66
|
+
};
|
|
67
|
+
var REAUTHENTICATION_KEYS = {
|
|
68
|
+
intervalSeconds: true,
|
|
69
|
+
onFailure: true,
|
|
70
|
+
cacheTtlMs: true,
|
|
71
|
+
revalidateTimeoutMs: true,
|
|
72
|
+
concurrency: true
|
|
73
|
+
};
|
|
74
|
+
var TOP_LEVEL_KEYS = {
|
|
75
|
+
transport: true,
|
|
76
|
+
authenticator: true,
|
|
77
|
+
tenantResolver: true,
|
|
78
|
+
hooks: true,
|
|
79
|
+
hookTimeoutMs: true,
|
|
80
|
+
onConnectFailure: true,
|
|
81
|
+
authenticateTimeoutMs: true,
|
|
82
|
+
maxPendingHandshakes: true,
|
|
83
|
+
maxConnections: true,
|
|
84
|
+
pubsub: true,
|
|
85
|
+
offlineQueue: true,
|
|
86
|
+
presence: true,
|
|
87
|
+
sse: true,
|
|
88
|
+
websocket: true,
|
|
89
|
+
reauthenticationPolicy: true
|
|
90
|
+
};
|
|
91
|
+
var GROUPS = {
|
|
92
|
+
sse: SSE_KEYS,
|
|
93
|
+
websocket: WEBSOCKET_KEYS,
|
|
94
|
+
reauthenticationPolicy: REAUTHENTICATION_KEYS
|
|
95
|
+
};
|
|
96
|
+
function readSet(source, known) {
|
|
97
|
+
const kept = {};
|
|
98
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(source), ...Object.keys(known)])) {
|
|
99
|
+
const value = source[key];
|
|
100
|
+
if (value !== void 0 && value !== null) kept[key] = value;
|
|
101
|
+
}
|
|
102
|
+
return kept;
|
|
103
|
+
}
|
|
104
|
+
function dropUnset(options) {
|
|
105
|
+
const kept = readSet(options, TOP_LEVEL_KEYS);
|
|
106
|
+
for (const [group, keys] of Object.entries(GROUPS)) {
|
|
107
|
+
const value = kept[group];
|
|
108
|
+
if (typeof value === "object" && !Array.isArray(value))
|
|
109
|
+
kept[group] = readSet(value, keys);
|
|
110
|
+
}
|
|
111
|
+
return kept;
|
|
112
|
+
}
|
|
113
|
+
|
|
44
114
|
// src/server/config/default-options.ts
|
|
45
115
|
var DEFAULT_SSE = {
|
|
46
116
|
endpoint: "/realtime/sse",
|
|
@@ -54,7 +124,8 @@ var DEFAULT_SSE = {
|
|
|
54
124
|
maxQueuedEvents: 1e3,
|
|
55
125
|
stallHeartbeats: 3
|
|
56
126
|
};
|
|
57
|
-
function applyDefaults(
|
|
127
|
+
function applyDefaults(raw) {
|
|
128
|
+
const options = dropUnset(raw);
|
|
58
129
|
return Object.freeze({
|
|
59
130
|
...options,
|
|
60
131
|
sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
|
|
@@ -75,6 +146,23 @@ var DEFAULT_HOOK_TIMEOUT_MS = 5e3;
|
|
|
75
146
|
var HEARTBEAT_MIN_MS = 5e3;
|
|
76
147
|
var HEARTBEAT_MAX_MS = 9e4;
|
|
77
148
|
|
|
149
|
+
// src/server/utils/describe-received.ts
|
|
150
|
+
var KIND_OF_TYPE = {
|
|
151
|
+
string: "a string",
|
|
152
|
+
boolean: "a boolean",
|
|
153
|
+
bigint: "a bigint",
|
|
154
|
+
symbol: "a symbol",
|
|
155
|
+
function: "a function",
|
|
156
|
+
undefined: "undefined"
|
|
157
|
+
};
|
|
158
|
+
function describeReceived(value) {
|
|
159
|
+
if (typeof value === "number") {
|
|
160
|
+
return Number.isFinite(value) ? String(value) : "a number that is not finite";
|
|
161
|
+
}
|
|
162
|
+
if (value === null) return "null";
|
|
163
|
+
return Array.isArray(value) ? "an array" : KIND_OF_TYPE[typeof value] ?? "an object";
|
|
164
|
+
}
|
|
165
|
+
|
|
78
166
|
// src/server/utils/realtime-error.ts
|
|
79
167
|
function realtimeError(code, detail, options = {}) {
|
|
80
168
|
const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
|
|
@@ -83,13 +171,81 @@ function realtimeError(code, detail, options = {}) {
|
|
|
83
171
|
return Object.assign(error, { code });
|
|
84
172
|
}
|
|
85
173
|
|
|
174
|
+
// src/server/config/validate-shapes.ts
|
|
175
|
+
var REQUIRED_FUNCTIONS = {
|
|
176
|
+
pubsub: ["publish", "subscribe"],
|
|
177
|
+
offlineQueue: ["append", "retrieveSince", "acknowledge"],
|
|
178
|
+
presence: ["setOnline", "setOffline", "isOnline", "listOnlineByTenant", "countOnline"]
|
|
179
|
+
};
|
|
180
|
+
var HOOK_NAMES = [
|
|
181
|
+
"onConnect",
|
|
182
|
+
"onDisconnect",
|
|
183
|
+
"onError",
|
|
184
|
+
"onReauthenticationFailed",
|
|
185
|
+
"onDeliveryFailure"
|
|
186
|
+
];
|
|
187
|
+
var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
|
|
188
|
+
function refuse(path, expected, received) {
|
|
189
|
+
throw realtimeError(
|
|
190
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
191
|
+
`options.${path} must be ${expected}, received ${describeReceived(received)}`,
|
|
192
|
+
{ who: "BymaxRealtimeModule" }
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
function isObject(value) {
|
|
196
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
197
|
+
}
|
|
198
|
+
function assertObject(path, value) {
|
|
199
|
+
if (value !== void 0 && !isObject(value)) refuse(path, "an object", value);
|
|
200
|
+
}
|
|
201
|
+
function assertFunction(path, value) {
|
|
202
|
+
if (typeof value !== "function") refuse(path, "a function", value);
|
|
203
|
+
}
|
|
204
|
+
function assertOptionalFunction(path, value) {
|
|
205
|
+
if (value !== void 0 && value !== null) assertFunction(path, value);
|
|
206
|
+
}
|
|
207
|
+
function assertBoolean(path, value) {
|
|
208
|
+
if (value !== void 0 && typeof value !== "boolean") refuse(path, "a boolean", value);
|
|
209
|
+
}
|
|
210
|
+
function assertEndpoint(path, value) {
|
|
211
|
+
if (value !== void 0 && !(typeof value === "string" && value.trim().length > 0)) {
|
|
212
|
+
refuse(path, "a non-blank string", value);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function validatePieces(options) {
|
|
216
|
+
for (const [name, functions] of Object.entries(REQUIRED_FUNCTIONS)) {
|
|
217
|
+
const piece = options[name];
|
|
218
|
+
assertObject(name, piece);
|
|
219
|
+
if (piece === void 0) continue;
|
|
220
|
+
for (const fn of functions)
|
|
221
|
+
assertFunction(`${name}.${fn}`, piece[fn]);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
function validateHooks(options) {
|
|
225
|
+
const hooks = options.hooks;
|
|
226
|
+
assertObject("hooks", hooks);
|
|
227
|
+
if (hooks === void 0) return;
|
|
228
|
+
for (const hook of HOOK_NAMES)
|
|
229
|
+
assertOptionalFunction(`hooks.${hook}`, hooks[hook]);
|
|
230
|
+
}
|
|
231
|
+
function validateShapes(options) {
|
|
232
|
+
for (const group of GROUP_NAMES) assertObject(group, options[group]);
|
|
233
|
+
validatePieces(options);
|
|
234
|
+
validateHooks(options);
|
|
235
|
+
assertOptionalFunction("tenantResolver", options.tenantResolver);
|
|
236
|
+
assertBoolean("sse.emitConnectionEvent", options.sse?.emitConnectionEvent);
|
|
237
|
+
assertBoolean("websocket.emitConnectionEvent", options.websocket?.emitConnectionEvent);
|
|
238
|
+
assertEndpoint("sse.endpoint", options.sse?.endpoint);
|
|
239
|
+
}
|
|
240
|
+
|
|
86
241
|
// src/server/config/validate-options.ts
|
|
87
242
|
var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
|
|
88
|
-
function validateOptions(
|
|
243
|
+
function validateOptions(raw) {
|
|
244
|
+
const options = dropUnset(raw);
|
|
89
245
|
if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
|
|
90
246
|
throw realtimeError(
|
|
91
247
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
92
|
-
`options.transport must be one of 'sse' | 'websocket' | 'both'
|
|
248
|
+
`options.transport must be one of 'sse' | 'websocket' | 'both', received ${describeReceived(options.transport)}`,
|
|
93
249
|
{ who: "BymaxRealtimeModule" }
|
|
94
250
|
);
|
|
95
251
|
}
|
|
@@ -107,18 +263,32 @@ function validateOptions(options) {
|
|
|
107
263
|
{ who: "BymaxRealtimeModule" }
|
|
108
264
|
);
|
|
109
265
|
}
|
|
266
|
+
validateShapes(options);
|
|
110
267
|
validateHookTimeout(options);
|
|
268
|
+
validateOnConnectFailure(options);
|
|
111
269
|
validateSseOptions(options);
|
|
112
270
|
validateReauthPolicy(options);
|
|
113
271
|
}
|
|
114
272
|
var MAX_TIMER_MS = 2147483647;
|
|
273
|
+
var MAX_PER_USER_CONNECTIONS = 1e5;
|
|
274
|
+
var MAX_REPLAY_EVENTS = 1e5;
|
|
275
|
+
var MAX_HTTP_BUFFER_BYTES = 100 * 1024 * 1024;
|
|
115
276
|
function assertInteger(path, value, least, most) {
|
|
116
277
|
if (value === void 0) return;
|
|
117
|
-
const valid = typeof value === "number" && Number.
|
|
278
|
+
const valid = typeof value === "number" && Number.isSafeInteger(value) && value >= least && (most === void 0 || value <= most);
|
|
118
279
|
if (valid) return;
|
|
119
280
|
throw realtimeError(
|
|
120
281
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
121
|
-
`options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`},
|
|
282
|
+
`options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, received ${describeReceived(value)}${most === void 0 && Number.isInteger(value) && !Number.isSafeInteger(value) ? ` (the most is ${Number.MAX_SAFE_INTEGER})` : ""}`,
|
|
283
|
+
{ who: "BymaxRealtimeModule" }
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
function validateOnConnectFailure(options) {
|
|
287
|
+
const value = options.onConnectFailure;
|
|
288
|
+
if (value === void 0 || value === "ignore" || value === "close") return;
|
|
289
|
+
throw realtimeError(
|
|
290
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
291
|
+
`options.onConnectFailure must be 'ignore' or 'close', received ${describeReceived(value)}`,
|
|
122
292
|
{ who: "BymaxRealtimeModule" }
|
|
123
293
|
);
|
|
124
294
|
}
|
|
@@ -127,6 +297,18 @@ function validateHookTimeout(options) {
|
|
|
127
297
|
assertInteger("authenticateTimeoutMs", options.authenticateTimeoutMs, 1, MAX_TIMER_MS);
|
|
128
298
|
assertInteger("maxPendingHandshakes", options.maxPendingHandshakes, 1);
|
|
129
299
|
assertInteger("maxConnections", options.maxConnections, 1);
|
|
300
|
+
assertInteger(
|
|
301
|
+
"websocket.maxConnectionsPerUser",
|
|
302
|
+
options.websocket?.maxConnectionsPerUser,
|
|
303
|
+
0,
|
|
304
|
+
MAX_PER_USER_CONNECTIONS
|
|
305
|
+
);
|
|
306
|
+
assertInteger(
|
|
307
|
+
"websocket.maxHttpBufferSize",
|
|
308
|
+
options.websocket?.maxHttpBufferSize,
|
|
309
|
+
1,
|
|
310
|
+
MAX_HTTP_BUFFER_BYTES
|
|
311
|
+
);
|
|
130
312
|
assertInteger("websocket.pingIntervalMs", options.websocket?.pingIntervalMs, 1, MAX_TIMER_MS);
|
|
131
313
|
assertInteger("websocket.pingTimeoutMs", options.websocket?.pingTimeoutMs, 1, MAX_TIMER_MS);
|
|
132
314
|
}
|
|
@@ -145,7 +327,7 @@ function validateReauthPolicy(options) {
|
|
|
145
327
|
if (onFailure !== void 0 && onFailure !== "disconnect" && onFailure !== "event") {
|
|
146
328
|
throw realtimeError(
|
|
147
329
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
148
|
-
`options.reauthenticationPolicy.onFailure must be 'disconnect' or 'event',
|
|
330
|
+
`options.reauthenticationPolicy.onFailure must be 'disconnect' or 'event', received ${describeReceived(onFailure)}`,
|
|
149
331
|
{ who: "BymaxRealtimeModule" }
|
|
150
332
|
);
|
|
151
333
|
}
|
|
@@ -162,36 +344,29 @@ function validateSseOptions(options) {
|
|
|
162
344
|
if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
|
|
163
345
|
throw realtimeError(
|
|
164
346
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
165
|
-
`options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms
|
|
166
|
-
{ who: "BymaxRealtimeModule" }
|
|
167
|
-
);
|
|
168
|
-
}
|
|
169
|
-
if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
|
|
170
|
-
throw realtimeError(
|
|
171
|
-
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
172
|
-
`options.sse.replayBufferSize must be >= 0`,
|
|
347
|
+
`options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms, received ${describeReceived(heartbeatMs)}`,
|
|
173
348
|
{ who: "BymaxRealtimeModule" }
|
|
174
349
|
);
|
|
175
350
|
}
|
|
351
|
+
assertInteger("sse.replayBufferSize", sse?.replayBufferSize, 0, MAX_REPLAY_EVENTS);
|
|
176
352
|
assertInteger("sse.replayTtlMs", sse?.replayTtlMs, 1, MAX_TIMER_MS);
|
|
177
353
|
assertInteger("sse.replayMaxIdleUsers", sse?.replayMaxIdleUsers, 1);
|
|
178
354
|
for (const name of ["maxQueuedBytes", "maxQueuedEvents", "stallHeartbeats"]) {
|
|
179
355
|
const value = sse?.[name];
|
|
180
|
-
if (value !== void 0 && !(typeof value === "number" && Number.
|
|
356
|
+
if (value !== void 0 && !(typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
|
|
181
357
|
throw realtimeError(
|
|
182
358
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
183
|
-
`options.sse.${name} must be an integer >= 0 (0 switches the bound off),
|
|
359
|
+
`options.sse.${name} must be an integer >= 0 (0 switches the bound off), received ${describeReceived(value)}`,
|
|
184
360
|
{ who: "BymaxRealtimeModule" }
|
|
185
361
|
);
|
|
186
362
|
}
|
|
187
363
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
}
|
|
364
|
+
assertInteger(
|
|
365
|
+
"sse.maxConnectionsPerUser",
|
|
366
|
+
sse?.maxConnectionsPerUser,
|
|
367
|
+
0,
|
|
368
|
+
MAX_PER_USER_CONNECTIONS
|
|
369
|
+
);
|
|
195
370
|
}
|
|
196
371
|
|
|
197
372
|
// src/server/utils/describe-error.ts
|
|
@@ -373,13 +548,40 @@ var ROOM_PREFIXES = {
|
|
|
373
548
|
RESOURCE: "resource"
|
|
374
549
|
};
|
|
375
550
|
|
|
376
|
-
// src/server/utils/
|
|
551
|
+
// src/server/utils/reserved-room.ts
|
|
377
552
|
var RESERVED_ROOM_PREFIXES = [
|
|
378
553
|
`${ROOM_PREFIXES.USER}:`,
|
|
379
554
|
`${ROOM_PREFIXES.TENANT}:`,
|
|
380
555
|
"connection:"
|
|
381
556
|
];
|
|
382
|
-
function
|
|
557
|
+
function reservedRoomPrefix(room) {
|
|
558
|
+
return RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
|
|
559
|
+
}
|
|
560
|
+
function describeShape(value) {
|
|
561
|
+
if (value === null) return "null";
|
|
562
|
+
return Array.isArray(value) ? "an array" : typeof value;
|
|
563
|
+
}
|
|
564
|
+
function requireRoomName(operation, roomId) {
|
|
565
|
+
if (typeof roomId === "string" && roomId.length > 0) return;
|
|
566
|
+
throw realtimeError(
|
|
567
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
568
|
+
`${operation}: \`roomId\` must be a non-empty string, got ${describeShape(roomId)}`,
|
|
569
|
+
{ who: "RealtimeService" }
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
function refuseReservedRoom(operation, roomId) {
|
|
573
|
+
requireRoomName(operation, roomId);
|
|
574
|
+
const prefix = reservedRoomPrefix(roomId);
|
|
575
|
+
if (prefix === void 0) return;
|
|
576
|
+
throw realtimeError(
|
|
577
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
578
|
+
`${operation}: \`roomId\` starts with the reserved prefix "${prefix}", which the library composes itself`,
|
|
579
|
+
{ who: "RealtimeService" }
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// src/server/utils/admit-rooms.ts
|
|
584
|
+
function refuse2(detail) {
|
|
383
585
|
throw realtimeError(
|
|
384
586
|
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
385
587
|
`the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
|
|
@@ -388,11 +590,11 @@ function refuse(detail) {
|
|
|
388
590
|
function admitRooms(auth) {
|
|
389
591
|
const { rooms } = auth;
|
|
390
592
|
if (rooms === void 0) return auth;
|
|
391
|
-
if (!Array.isArray(rooms))
|
|
593
|
+
if (!Array.isArray(rooms)) refuse2("`rooms` is not an array");
|
|
392
594
|
const admitted = [];
|
|
393
595
|
for (const room of rooms) {
|
|
394
596
|
if (admitted.length === ADMISSION_ROOM_LIMITS.MAX_ROOMS) {
|
|
395
|
-
|
|
597
|
+
refuse2(
|
|
396
598
|
`more than ${ADMISSION_ROOM_LIMITS.MAX_ROOMS} rooms: the limit is ${ADMISSION_ROOM_LIMITS.MAX_ROOMS}`
|
|
397
599
|
);
|
|
398
600
|
}
|
|
@@ -400,13 +602,13 @@ function admitRooms(auth) {
|
|
|
400
602
|
}
|
|
401
603
|
for (const room of admitted) {
|
|
402
604
|
if (typeof room !== "string" || room.trim().length === 0) {
|
|
403
|
-
|
|
605
|
+
refuse2("every room must be a non-blank string");
|
|
404
606
|
}
|
|
405
607
|
if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
|
|
406
|
-
|
|
608
|
+
refuse2(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
|
|
407
609
|
}
|
|
408
|
-
const reserved =
|
|
409
|
-
if (reserved !== void 0)
|
|
610
|
+
const reserved = reservedRoomPrefix(room);
|
|
611
|
+
if (reserved !== void 0) refuse2(`a room name starts with the reserved prefix "${reserved}"`);
|
|
410
612
|
}
|
|
411
613
|
return { ...auth, rooms: Object.freeze(admitted) };
|
|
412
614
|
}
|
|
@@ -774,7 +976,12 @@ function composeRoomId(prefix, ...parts) {
|
|
|
774
976
|
}
|
|
775
977
|
function unavailableError(code, who, what, cause) {
|
|
776
978
|
const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
|
|
777
|
-
|
|
979
|
+
const error = Object.assign(new ServiceUnavailableException(), { code });
|
|
980
|
+
Object.defineProperties(error, {
|
|
981
|
+
message: { value: message, enumerable: false, writable: true, configurable: true },
|
|
982
|
+
cause: { value: cause, enumerable: false, writable: true, configurable: true }
|
|
983
|
+
});
|
|
984
|
+
return error;
|
|
778
985
|
}
|
|
779
986
|
var InMemoryPubSub = class {
|
|
780
987
|
handlers = /* @__PURE__ */ new Set();
|
|
@@ -874,7 +1081,7 @@ var HeartbeatService = class {
|
|
|
874
1081
|
if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
|
|
875
1082
|
throw realtimeError(
|
|
876
1083
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
877
|
-
`heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms
|
|
1084
|
+
`heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms, received ${describeReceived(intervalMs)}`
|
|
878
1085
|
);
|
|
879
1086
|
}
|
|
880
1087
|
this.stop(connectionId);
|
|
@@ -1184,6 +1391,7 @@ var SseTransport = class {
|
|
|
1184
1391
|
await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
|
|
1185
1392
|
}
|
|
1186
1393
|
async emitToRoom(roomId, event, data) {
|
|
1394
|
+
requireRoomName("emitToRoom", roomId);
|
|
1187
1395
|
const id = this.idGen.next();
|
|
1188
1396
|
this.emitToRoomLocal(roomId, event, data, id);
|
|
1189
1397
|
await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
|
|
@@ -1194,10 +1402,12 @@ var SseTransport = class {
|
|
|
1194
1402
|
await this.publish({ op: "broadcast", args: { event, data, id } });
|
|
1195
1403
|
}
|
|
1196
1404
|
async joinRoom(connectionId, roomId) {
|
|
1405
|
+
refuseReservedRoom("joinRoom", roomId);
|
|
1197
1406
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
1198
1407
|
this.rooms.join(connectionId, roomId);
|
|
1199
1408
|
}
|
|
1200
1409
|
async leaveRoom(connectionId, roomId) {
|
|
1410
|
+
refuseReservedRoom("leaveRoom", roomId);
|
|
1201
1411
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
1202
1412
|
this.rooms.leave(connectionId, roomId);
|
|
1203
1413
|
}
|
|
@@ -1640,7 +1850,10 @@ var SseSubscriptionHandler = class {
|
|
|
1640
1850
|
}
|
|
1641
1851
|
const record = this.transport.getConnection(connectionId);
|
|
1642
1852
|
if (record) {
|
|
1643
|
-
this.fireHook(
|
|
1853
|
+
this.fireHook(
|
|
1854
|
+
() => this.hooks?.onConnect?.(buildMeta(record)),
|
|
1855
|
+
this.options.onConnectFailure === "close" ? () => subscriber.complete() : void 0
|
|
1856
|
+
);
|
|
1644
1857
|
}
|
|
1645
1858
|
const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
1646
1859
|
this.heartbeat.start(
|
|
@@ -1650,9 +1863,11 @@ var SseSubscriptionHandler = class {
|
|
|
1650
1863
|
() => this.transport.checkStall(connectionId)
|
|
1651
1864
|
);
|
|
1652
1865
|
}
|
|
1653
|
-
fireHook(invoke) {
|
|
1866
|
+
fireHook(invoke, onFailure) {
|
|
1654
1867
|
void runHook(invoke).then((failed) => {
|
|
1655
|
-
if (failed)
|
|
1868
|
+
if (!failed) return;
|
|
1869
|
+
this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
|
|
1870
|
+
onFailure?.();
|
|
1656
1871
|
});
|
|
1657
1872
|
}
|
|
1658
1873
|
};
|
|
@@ -1731,16 +1946,19 @@ var RealtimeService = class {
|
|
|
1731
1946
|
emitToTenant(tenantId, event, data) {
|
|
1732
1947
|
return this.transport.emitToTenant(tenantId, event, data);
|
|
1733
1948
|
}
|
|
1734
|
-
emitToRoom(roomId, event, data) {
|
|
1949
|
+
async emitToRoom(roomId, event, data) {
|
|
1950
|
+
requireRoomName("emitToRoom", roomId);
|
|
1735
1951
|
return this.transport.emitToRoom(roomId, event, data);
|
|
1736
1952
|
}
|
|
1737
1953
|
broadcast(event, data) {
|
|
1738
1954
|
return this.transport.broadcast(event, data);
|
|
1739
1955
|
}
|
|
1740
|
-
joinRoom(connectionId, roomId) {
|
|
1956
|
+
async joinRoom(connectionId, roomId) {
|
|
1957
|
+
refuseReservedRoom("joinRoom", roomId);
|
|
1741
1958
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1742
1959
|
}
|
|
1743
|
-
leaveRoom(connectionId, roomId) {
|
|
1960
|
+
async leaveRoom(connectionId, roomId) {
|
|
1961
|
+
refuseReservedRoom("leaveRoom", roomId);
|
|
1744
1962
|
return this.transport.leaveRoom(connectionId, roomId);
|
|
1745
1963
|
}
|
|
1746
1964
|
disconnect(connectionId, reason) {
|
|
@@ -1995,7 +2213,8 @@ function buildCommonProviders(resolved, instanceId) {
|
|
|
1995
2213
|
...SHARED_SERVICES
|
|
1996
2214
|
];
|
|
1997
2215
|
}
|
|
1998
|
-
function composeForRoot(moduleClass, wiring, logger,
|
|
2216
|
+
function composeForRoot(moduleClass, wiring, logger, raw) {
|
|
2217
|
+
const options = dropUnset(raw);
|
|
1999
2218
|
validateOptions(options);
|
|
2000
2219
|
assertModeSupported(wiring, options.transport, moduleClass.name);
|
|
2001
2220
|
const resolved = applyDefaults(options);
|
|
@@ -2014,7 +2233,7 @@ function assertSseEndpointApplies(asyncOptions, moduleName) {
|
|
|
2014
2233
|
if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
|
|
2015
2234
|
throw realtimeError(
|
|
2016
2235
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2017
|
-
`sseEndpoint
|
|
2236
|
+
`sseEndpoint was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
|
|
2018
2237
|
{ who: moduleName }
|
|
2019
2238
|
);
|
|
2020
2239
|
}
|
|
@@ -2022,7 +2241,7 @@ function bindSseEndpoint(resolved, declared, bound, moduleName) {
|
|
|
2022
2241
|
if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
|
|
2023
2242
|
throw realtimeError(
|
|
2024
2243
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2025
|
-
`the factory resolved sse.endpoint
|
|
2244
|
+
`the factory resolved an sse.endpoint that differs from the SSE route forRootAsync bound \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`,
|
|
2026
2245
|
{ who: moduleName }
|
|
2027
2246
|
);
|
|
2028
2247
|
}
|
|
@@ -2032,39 +2251,68 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
|
|
|
2032
2251
|
if (!raw) {
|
|
2033
2252
|
throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
|
|
2034
2253
|
}
|
|
2035
|
-
|
|
2036
|
-
|
|
2254
|
+
const options = dropUnset(raw);
|
|
2255
|
+
validateOptions(options);
|
|
2256
|
+
if (options.transport !== declaredMode) {
|
|
2037
2257
|
throw realtimeError(
|
|
2038
2258
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2039
|
-
`forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${
|
|
2259
|
+
`forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${options.transport}'`,
|
|
2040
2260
|
{ who: moduleName }
|
|
2041
2261
|
);
|
|
2042
2262
|
}
|
|
2043
|
-
const resolved = applyDefaults(
|
|
2263
|
+
const resolved = applyDefaults(options);
|
|
2044
2264
|
logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
|
|
2045
|
-
return resolved;
|
|
2265
|
+
return { resolved, declaredEndpoint: options.sse?.endpoint };
|
|
2046
2266
|
}
|
|
2047
|
-
function
|
|
2048
|
-
const moduleName = moduleClass.name;
|
|
2267
|
+
function assertOneFactoryPattern(asyncOptions, moduleName) {
|
|
2049
2268
|
const patterns = [
|
|
2050
2269
|
asyncOptions.useFactory,
|
|
2051
2270
|
asyncOptions.useClass,
|
|
2052
2271
|
asyncOptions.useExisting
|
|
2053
2272
|
].filter((pattern) => pattern !== void 0);
|
|
2054
|
-
if (patterns.length
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2273
|
+
if (patterns.length === 1) return;
|
|
2274
|
+
throw realtimeError(
|
|
2275
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2276
|
+
`forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
|
|
2277
|
+
{ who: moduleName }
|
|
2278
|
+
);
|
|
2279
|
+
}
|
|
2280
|
+
function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
|
|
2281
|
+
if (asyncOptions.useFactory) {
|
|
2282
|
+
return {
|
|
2283
|
+
provide: REALTIME_OPTIONS_TOKEN,
|
|
2284
|
+
useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
|
|
2285
|
+
inject: [...asyncOptions.inject ?? []]
|
|
2286
|
+
};
|
|
2060
2287
|
}
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2288
|
+
return {
|
|
2289
|
+
provide: REALTIME_OPTIONS_TOKEN,
|
|
2290
|
+
useFactory: async (factory) => resolve(
|
|
2291
|
+
await factory.createRealtimeOptions(),
|
|
2292
|
+
"createRealtimeOptions"
|
|
2293
|
+
),
|
|
2294
|
+
inject: [asyncOptions.useExisting ?? factoryToken]
|
|
2295
|
+
};
|
|
2296
|
+
}
|
|
2297
|
+
function fromOptions(token, read) {
|
|
2298
|
+
return { provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] };
|
|
2299
|
+
}
|
|
2300
|
+
function buildOptionDerivedProviders(logger, instanceId) {
|
|
2301
|
+
return [
|
|
2302
|
+
fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
|
|
2303
|
+
fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
|
|
2304
|
+
warnIfSingleInstance(opts.pubsub, opts.transport, logger);
|
|
2305
|
+
return opts.pubsub ?? new InMemoryPubSub();
|
|
2306
|
+
}),
|
|
2307
|
+
fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
|
|
2308
|
+
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
2309
|
+
fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
|
|
2310
|
+
fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence)
|
|
2311
|
+
];
|
|
2312
|
+
}
|
|
2313
|
+
function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName) {
|
|
2314
|
+
return (raw, source) => {
|
|
2315
|
+
const { resolved, declaredEndpoint } = resolveAsyncOptions(
|
|
2068
2316
|
raw,
|
|
2069
2317
|
asyncOptions.transport,
|
|
2070
2318
|
instanceId,
|
|
@@ -2073,22 +2321,19 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
2073
2321
|
moduleName
|
|
2074
2322
|
);
|
|
2075
2323
|
if (asyncOptions.transport === "websocket") return resolved;
|
|
2076
|
-
return bindSseEndpoint(resolved,
|
|
2077
|
-
};
|
|
2078
|
-
const resolvedOptionsProvider = asyncOptions.useFactory ? {
|
|
2079
|
-
provide: REALTIME_OPTIONS_TOKEN,
|
|
2080
|
-
useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
|
|
2081
|
-
inject: [...asyncOptions.inject ?? []]
|
|
2082
|
-
} : {
|
|
2083
|
-
provide: REALTIME_OPTIONS_TOKEN,
|
|
2084
|
-
useFactory: async (factory) => resolve(
|
|
2085
|
-
await factory.createRealtimeOptions(),
|
|
2086
|
-
"createRealtimeOptions"
|
|
2087
|
-
),
|
|
2088
|
-
inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
|
|
2324
|
+
return bindSseEndpoint(resolved, declaredEndpoint, boundSseEndpoint, moduleName);
|
|
2089
2325
|
};
|
|
2326
|
+
}
|
|
2327
|
+
function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
2328
|
+
const moduleName = moduleClass.name;
|
|
2329
|
+
assertOneFactoryPattern(asyncOptions, moduleName);
|
|
2330
|
+
assertModeSupported(wiring, asyncOptions.transport, moduleName);
|
|
2331
|
+
assertSseEndpointApplies(asyncOptions, moduleName);
|
|
2332
|
+
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
2333
|
+
const instanceId = randomUUID();
|
|
2334
|
+
const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
|
|
2335
|
+
const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
|
|
2090
2336
|
const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
|
|
2091
|
-
const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
|
|
2092
2337
|
const { providers: transportProviders, controllers } = wiring.buildAsync({
|
|
2093
2338
|
mode: asyncOptions.transport,
|
|
2094
2339
|
sseEndpoint: boundSseEndpoint
|
|
@@ -2099,16 +2344,8 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
2099
2344
|
controllers,
|
|
2100
2345
|
providers: [
|
|
2101
2346
|
...factoryClassProvider,
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
|
|
2105
|
-
warnIfSingleInstance(opts.pubsub, opts.transport, logger);
|
|
2106
|
-
return opts.pubsub ?? new InMemoryPubSub();
|
|
2107
|
-
}),
|
|
2108
|
-
fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
|
|
2109
|
-
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
2110
|
-
fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
|
|
2111
|
-
fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
|
|
2347
|
+
buildOptionsProvider(asyncOptions, resolve, FACTORY_TOKEN),
|
|
2348
|
+
...buildOptionDerivedProviders(logger, instanceId),
|
|
2112
2349
|
...SHARED_SERVICES,
|
|
2113
2350
|
...transportProviders,
|
|
2114
2351
|
...asyncOptions.extraProviders ?? []
|
|
@@ -2507,6 +2744,18 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
2507
2744
|
};
|
|
2508
2745
|
|
|
2509
2746
|
// src/server/offline-queue/redis-offline-queue.ts
|
|
2747
|
+
var MAX_PER_USER_CEILING = 1e5;
|
|
2748
|
+
var TTL_SECONDS_CEILING = 2147483647;
|
|
2749
|
+
function requireInteger(name, value, least, most) {
|
|
2750
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= least && value <= most) {
|
|
2751
|
+
return value;
|
|
2752
|
+
}
|
|
2753
|
+
throw realtimeError(
|
|
2754
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2755
|
+
`options.${name} must be an integer >= ${least} and <= ${most}, received ${describeReceived(value)}`,
|
|
2756
|
+
{ who: "RedisOfflineQueue" }
|
|
2757
|
+
);
|
|
2758
|
+
}
|
|
2510
2759
|
var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
2511
2760
|
#client;
|
|
2512
2761
|
maxPerUser;
|
|
@@ -2515,8 +2764,18 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2515
2764
|
static COUNTER_PAD = 6;
|
|
2516
2765
|
constructor(options) {
|
|
2517
2766
|
this.#client = options.client;
|
|
2518
|
-
this.maxPerUser =
|
|
2519
|
-
|
|
2767
|
+
this.maxPerUser = requireInteger(
|
|
2768
|
+
"maxPerUser",
|
|
2769
|
+
options.maxPerUser ?? 500,
|
|
2770
|
+
1,
|
|
2771
|
+
MAX_PER_USER_CEILING
|
|
2772
|
+
);
|
|
2773
|
+
this.ttlSeconds = requireInteger(
|
|
2774
|
+
"ttlSeconds",
|
|
2775
|
+
options.ttlSeconds ?? 3600,
|
|
2776
|
+
1,
|
|
2777
|
+
TTL_SECONDS_CEILING
|
|
2778
|
+
);
|
|
2520
2779
|
}
|
|
2521
2780
|
key(userId) {
|
|
2522
2781
|
return `bymax:oq:${userId}`;
|
|
@@ -2569,4 +2828,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2569
2828
|
}
|
|
2570
2829
|
};
|
|
2571
2830
|
|
|
2572
|
-
export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
|
|
2831
|
+
export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };
|