@bymax-one/nest-realtime 1.2.17 → 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 CHANGED
@@ -7,6 +7,30 @@ Versioning is **not** strict [SemVer](https://semver.org/spec/v2.0.0.html) while
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.18] - 2026-11-17
11
+
12
+ ### Security
13
+
14
+ - **An option set to `undefined` resolved to "no bound", and a refusal echoed what it was given.** The defaults were merged with `{ ...DEFAULT_SSE, ...options.sse }`, so an own key holding `undefined` overwrote its default. Measured on 1.2.17 with `sse: { maxConnectionsPerUser: undefined, maxQueuedBytes: undefined, maxQueuedEvents: undefined, stallHeartbeats: undefined, replayBufferSize: undefined }`: the options the services receive carried `undefined` for all five, the per-user eviction returns early on `undefined` (no cap), and the three queue bounds are read with `?? 0`, which switches them off. A host that spelled an option as `cond ? value : undefined` therefore ran with the bound off instead of the default. Separately, the refusals of the numeric and enum options ended in `got <value>`, which printed whatever the host had passed: a token pasted into the wrong field, or the source text of a function. Now the keys that hold `undefined` or `null` are dropped, at the top level and in `sse`, `websocket` and `reauthenticationPolicy`, before the defaults are merged and before validation, so such an option resolves to its default and is validated as absent; a group handed over as a class instance is read through its fields and getters, as the services read it, so it is covered too. Every refusal of an option names the option and the type of what it received (`received a string`), prints a finite number, and echoes nothing else; the two `forRootAsync` endpoint refusals no longer print the paths.
15
+
16
+ - **`RedisOfflineQueue` accepted a `maxPerUser` or a `ttlSeconds` that loses or corrupts the queue.** Measured on Redis 7: a `ttlSeconds` of `0` or a negative made `EXPIRE` delete the key, so every append was dropped without an error; a `maxPerUser` of `0` made the trim remove every entry; and `NaN`, a fraction, `Infinity`, `1e300` or a value Redis rejects made the pipeline fail after `ZADD` had already run, which left the entries untrimmed or the key without an expiry, and every append rejected. A numeric string such as `'3'` concatenated in the trim (`'3' + 1` is `'31'`), keeping up to 30 events. The constructor now refuses anything that is not a safe integer from 1 to 100,000 for `maxPerUser` and from 1 to 2,147,483,647 for `ttlSeconds`, with `REALTIME_INVALID_OPTIONS` naming the option and its range and describing what it received by type (a finite number is printed). A `maxPerUser` or `ttlSeconds` of `undefined` or `null` is read as unset and takes its default.
17
+
18
+ - **A malformed pluggable piece, group or flag was accepted at start-up and failed later, or did the opposite of what it said.** Measured on 1.2.17 with `forRoot`: `pubsub: {}` and a `pubsub` without `subscribe` were accepted and the application then failed at init with a raw `this.pubsub.subscribe is not a function`; `sse.endpoint: 5` failed at registration with `endpoint.startsWith is not a function`; `offlineQueue: {}` and `presence: {}` were accepted, and with `offlineQueue: {}` an emit to an offline user rejected at run time with `REALTIME_TRANSPORT_UNAVAILABLE`; `tenantResolver: 'x'` was accepted and every handshake then threw a `TypeError` at `tenantResolver?.(auth)`; `hooks`, `sse`, `websocket` and `reauthenticationPolicy` were accepted as strings; `sse.emitConnectionEvent: 'no'` was accepted and read as true because it is truthy. `forRoot` now refuses each at registration with `REALTIME_INVALID_OPTIONS`, naming the option and describing what it received by type: a group (`sse`, `websocket`, `reauthenticationPolicy`) and `hooks` must be objects; `pubsub`, `offlineQueue` and `presence` must be objects with every function of their interface, which may be on a class prototype; each lifecycle hook that is set and `tenantResolver` must be functions; the two `emitConnectionEvent` flags must be booleans; and `sse.endpoint` must be a non-blank string, with or without a leading slash.
19
+
20
+ #### Apply to a derived backend
21
+
22
+ An option that holds `null` was refused (`got null`) and is now read as unset, like `undefined`: it takes its default. An option you meant to leave unlimited with `undefined` now takes its default instead, so say `0` where `0` switches the bound off. A test that pinned the text of a refusal (`got 1000`, `(got: carrier-pigeon)`) now reads `received 1000` and `received a string`.
23
+
24
+ A queue built with `new RedisOfflineQueue({ client, maxPerUser, ttlSeconds })` now throws at construction for a value outside those ranges, where it used to start and lose events. If you passed `0` to mean unlimited, there is no such mode: pick the count you can afford to hold per user.
25
+
26
+ A test double for the bus, the offline queue or presence that implements only the functions a test calls is now refused at registration: give it every required function, as a no-op where it does nothing. A flag you passed as a string (`'false'`) is refused instead of being read as true; pass a boolean.
27
+
28
+ ### Documentation
29
+
30
+ - **Details the 1.2.17 notes did not state.** A subclass of `WebSocketTransport` that replaces `joinRooms` drops, besides the user, tenant and connection rooms, the rooms an authenticator returns (`AuthenticationResult.rooms`) and the update of the `RoomRegistry`; a `static` member named `joinRooms` or `runOnConnect` compiles, because only the instance members are private; and for `emitToRoom` the change a caller can observe in 1.2.17 is that a `roomId` that is not a non-empty string is refused as a rejected promise, an outcome 1.2.16 did not have. `CONTRIBUTING.md` no longer describes a `commit-msg` hook and a `pre-commit` hook that this repository does not have.
31
+
32
+ - **A shutdown can wait six seconds for a client that stopped reading.** `app.close()` ends every stream at once, but Node's HTTP server then waits for the sockets of clients that no longer read, for `keepAliveTimeout` and a check interval: 6,004 ms measured, against 3 ms with `forceCloseConnections: true`. The README's "Shutdown" section now says so. Apply: pass `{ forceCloseConnections: true }` to `NestFactory.create`, or give the process a termination grace of at least 7 seconds.
33
+
10
34
  ## [1.2.17] - 2026-11-17
11
35
 
12
36
  ### Added
@@ -1139,7 +1163,8 @@ First published release.
1139
1163
  rather than by the manual sweep that raised the NestJS floors — that sweep
1140
1164
  asked about NestJS and never put the same question to the other ten peers.
1141
1165
 
1142
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.17...HEAD
1166
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.18...HEAD
1167
+ [1.2.18]: https://github.com/bymaxone/nest-realtime/compare/v1.2.17...v1.2.18
1143
1168
  [1.2.17]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...v1.2.17
1144
1169
  [1.2.16]: https://github.com/bymaxone/nest-realtime/compare/v1.2.15...v1.2.16
1145
1170
  [1.2.15]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...v1.2.15
package/README.md CHANGED
@@ -405,6 +405,10 @@ An SSE response writes one event at a time and waits for the client to read befo
405
405
  > [!NOTE]
406
406
  > `maxConnectionsPerUser` defaults to `5` on both transports: a user's sixth connection closes their oldest, which is sent a disconnect. The oldest is closed when the new connection is admitted, before `onConnect` runs, so a connection that `onConnectFailure: 'close'` refuses has already displaced it. `0` switches the cap off. The cap, `replayBufferSize` and `websocket.maxHttpBufferSize` must be integers (`0` or more, and `1` or more for the payload bound) and have a most: 100,000 for the cap on either transport, 100,000 events for `replayBufferSize` (memory per user stream is that times the size of a frame), and 104,857,600 bytes (100 MiB) for `websocket.maxHttpBufferSize`, whose Socket.IO default is 1,000,000 bytes. `NaN`, `Infinity`, a fraction, a numeric string, a value past its most and any integer past 9,007,199,254,740,991 (`1e300`, `2 ** 53`) are refused at start-up, since a comparison with `NaN` is never true and a bound that large never trips. The cap is per user and does not bound the connections of an instance: many users, or a token minted per request, are bounded by your proxy or the process's file-descriptor limit, not by this option.
407
407
 
408
+ An option that holds `undefined` or `null` is read as unset: it takes its default, in the module options and in `sse`, `websocket` and `reauthenticationPolicy`, so `maxConnectionsPerUser: cond ? 3 : undefined` means the default cap of `5`, never no cap. Say `0` where `0` switches a bound off. A refusal of an option names the option and the type of what it received (`received a string`), prints a finite number, and echoes nothing else, so a value pasted into the wrong field does not reach a log.
409
+
410
+ The shape of what you pass is checked at start-up too, and refused with `REALTIME_INVALID_OPTIONS`: `sse`, `websocket`, `reauthenticationPolicy` and `hooks` must be objects; `pubsub`, `offlineQueue` and `presence` must have every function of their interface (`IRealtimePubSub`, `IOfflineQueueStorage`, `IPresenceStorage`), on the object or its prototype; each hook that is set and `tenantResolver` must be a function; `sse.emitConnectionEvent` and `websocket.emitConnectionEvent` must be booleans; `sse.endpoint` must be a non-blank string, with or without a leading slash.
411
+
408
412
  The options are typed per entry point: `SseRealtimeModuleOptions` and `SseRealtimeModuleAsyncOptions` fix `transport: 'sse'`, and `WebSocketRealtimeModuleOptions` and `WebSocketRealtimeModuleAsyncOptions` (from `/websocket`) fix `'websocket' | 'both'`. `forRootAsync` takes `useFactory`, `useClass` (a `BymaxRealtimeModuleOptionsFactory`) or `useExisting`.
409
413
 
410
414
  > [!IMPORTANT]
@@ -703,6 +707,8 @@ Read-side view of live connections — useful for admin endpoints and metrics. T
703
707
 
704
708
  Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
705
709
 
710
+ `RedisOfflineQueue` takes `maxPerUser` (default 500) and `ttlSeconds` (default 3600), each an integer: `maxPerUser` from 1 to 100,000 and `ttlSeconds` from 1 to 2,147,483,647. A value outside that is refused when the queue is constructed, with `REALTIME_INVALID_OPTIONS`, because Redis would otherwise turn it into a silent loss: see the changelog entry for what each value did.
711
+
706
712
  #### Identity must be present or absent, never blank
707
713
 
708
714
  `userId` must be a non-empty string, and `tenantId` either absent or a non-empty string. A connection whose authenticator, or whose `tenantResolver`, yields a blank one is **refused at bootstrap** as a server fault, not a `401`: blank is not missing. Every connection carrying `''` lands under the same registry key and joins the same `user:` or `tenant:` room, and a later emit reaches all of them. Whitespace counts as blank.
@@ -923,6 +929,8 @@ Nest's default exception filter does not log an `HttpException`, so a `503` from
923
929
 
924
930
  From the `onModuleDestroy` phase on, which runs ahead of every `beforeApplicationShutdown`, a new SSE stream gets a 503 whose message is `REALTIME_TRANSPORT_UNAVAILABLE` and a new WebSocket handshake gets a `connect_error` whose `data.code` is that code. A slow `onModuleDestroy` in a module nearer the root than the realtime module still runs first, and until it returns a connection is accepted.
925
931
 
932
+ A client that stopped reading holds its socket open after the library has ended its stream, and Node's HTTP server waits for it: `app.close()` took 6,004 ms with such clients and 3 ms with `forceCloseConnections: true`. Create the application with `NestFactory.create(AppModule, { forceCloseConnections: true })`, or give the process a termination grace of at least 7 seconds.
933
+
926
934
  ### DI Tokens
927
935
 
928
936
  `REALTIME_OPTIONS_TOKEN` · `REALTIME_TRANSPORT_TOKEN` · `REALTIME_AUTHENTICATOR_TOKEN` · `REALTIME_PUBSUB_TOKEN` · `REALTIME_OFFLINE_QUEUE_TOKEN` · `REALTIME_PRESENCE_TOKEN` · `REALTIME_HOOKS_TOKEN` · `REALTIME_INSTANCE_ID_TOKEN`
@@ -43,6 +43,76 @@ var REALTIME_ERROR_CODES = {
43
43
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
44
44
  };
45
45
 
46
+ // src/server/config/drop-unset.ts
47
+ var SSE_KEYS = {
48
+ endpoint: true,
49
+ heartbeatMs: true,
50
+ replayBufferSize: true,
51
+ replayTtlMs: true,
52
+ replayMaxIdleUsers: true,
53
+ maxConnectionsPerUser: true,
54
+ emitConnectionEvent: true,
55
+ maxQueuedBytes: true,
56
+ maxQueuedEvents: true,
57
+ stallHeartbeats: true
58
+ };
59
+ var WEBSOCKET_KEYS = {
60
+ namespace: true,
61
+ cors: true,
62
+ maxHttpBufferSize: true,
63
+ pingIntervalMs: true,
64
+ pingTimeoutMs: true,
65
+ maxConnectionsPerUser: true,
66
+ emitConnectionEvent: true,
67
+ redisAdapter: true
68
+ };
69
+ var REAUTHENTICATION_KEYS = {
70
+ intervalSeconds: true,
71
+ onFailure: true,
72
+ cacheTtlMs: true,
73
+ revalidateTimeoutMs: true,
74
+ concurrency: true
75
+ };
76
+ var TOP_LEVEL_KEYS = {
77
+ transport: true,
78
+ authenticator: true,
79
+ tenantResolver: true,
80
+ hooks: true,
81
+ hookTimeoutMs: true,
82
+ onConnectFailure: true,
83
+ authenticateTimeoutMs: true,
84
+ maxPendingHandshakes: true,
85
+ maxConnections: true,
86
+ pubsub: true,
87
+ offlineQueue: true,
88
+ presence: true,
89
+ sse: true,
90
+ websocket: true,
91
+ reauthenticationPolicy: true
92
+ };
93
+ var GROUPS = {
94
+ sse: SSE_KEYS,
95
+ websocket: WEBSOCKET_KEYS,
96
+ reauthenticationPolicy: REAUTHENTICATION_KEYS
97
+ };
98
+ function readSet(source, known) {
99
+ const kept = {};
100
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(source), ...Object.keys(known)])) {
101
+ const value = source[key];
102
+ if (value !== void 0 && value !== null) kept[key] = value;
103
+ }
104
+ return kept;
105
+ }
106
+ function dropUnset(options) {
107
+ const kept = readSet(options, TOP_LEVEL_KEYS);
108
+ for (const [group, keys] of Object.entries(GROUPS)) {
109
+ const value = kept[group];
110
+ if (typeof value === "object" && !Array.isArray(value))
111
+ kept[group] = readSet(value, keys);
112
+ }
113
+ return kept;
114
+ }
115
+
46
116
  // src/server/config/default-options.ts
47
117
  var DEFAULT_SSE = {
48
118
  endpoint: "/realtime/sse",
@@ -56,7 +126,8 @@ var DEFAULT_SSE = {
56
126
  maxQueuedEvents: 1e3,
57
127
  stallHeartbeats: 3
58
128
  };
59
- function applyDefaults(options) {
129
+ function applyDefaults(raw) {
130
+ const options = dropUnset(raw);
60
131
  return Object.freeze({
61
132
  ...options,
62
133
  sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
@@ -77,6 +148,23 @@ var DEFAULT_HOOK_TIMEOUT_MS = 5e3;
77
148
  var HEARTBEAT_MIN_MS = 5e3;
78
149
  var HEARTBEAT_MAX_MS = 9e4;
79
150
 
151
+ // src/server/utils/describe-received.ts
152
+ var KIND_OF_TYPE = {
153
+ string: "a string",
154
+ boolean: "a boolean",
155
+ bigint: "a bigint",
156
+ symbol: "a symbol",
157
+ function: "a function",
158
+ undefined: "undefined"
159
+ };
160
+ function describeReceived(value) {
161
+ if (typeof value === "number") {
162
+ return Number.isFinite(value) ? String(value) : "a number that is not finite";
163
+ }
164
+ if (value === null) return "null";
165
+ return Array.isArray(value) ? "an array" : KIND_OF_TYPE[typeof value] ?? "an object";
166
+ }
167
+
80
168
  // src/server/utils/realtime-error.ts
81
169
  function realtimeError(code, detail, options = {}) {
82
170
  const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
@@ -85,13 +173,81 @@ function realtimeError(code, detail, options = {}) {
85
173
  return Object.assign(error, { code });
86
174
  }
87
175
 
176
+ // src/server/config/validate-shapes.ts
177
+ var REQUIRED_FUNCTIONS = {
178
+ pubsub: ["publish", "subscribe"],
179
+ offlineQueue: ["append", "retrieveSince", "acknowledge"],
180
+ presence: ["setOnline", "setOffline", "isOnline", "listOnlineByTenant", "countOnline"]
181
+ };
182
+ var HOOK_NAMES = [
183
+ "onConnect",
184
+ "onDisconnect",
185
+ "onError",
186
+ "onReauthenticationFailed",
187
+ "onDeliveryFailure"
188
+ ];
189
+ var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
190
+ function refuse(path, expected, received) {
191
+ throw realtimeError(
192
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
193
+ `options.${path} must be ${expected}, received ${describeReceived(received)}`,
194
+ { who: "BymaxRealtimeModule" }
195
+ );
196
+ }
197
+ function isObject(value) {
198
+ return typeof value === "object" && value !== null && !Array.isArray(value);
199
+ }
200
+ function assertObject(path, value) {
201
+ if (value !== void 0 && !isObject(value)) refuse(path, "an object", value);
202
+ }
203
+ function assertFunction(path, value) {
204
+ if (typeof value !== "function") refuse(path, "a function", value);
205
+ }
206
+ function assertOptionalFunction(path, value) {
207
+ if (value !== void 0 && value !== null) assertFunction(path, value);
208
+ }
209
+ function assertBoolean(path, value) {
210
+ if (value !== void 0 && typeof value !== "boolean") refuse(path, "a boolean", value);
211
+ }
212
+ function assertEndpoint(path, value) {
213
+ if (value !== void 0 && !(typeof value === "string" && value.trim().length > 0)) {
214
+ refuse(path, "a non-blank string", value);
215
+ }
216
+ }
217
+ function validatePieces(options) {
218
+ for (const [name, functions] of Object.entries(REQUIRED_FUNCTIONS)) {
219
+ const piece = options[name];
220
+ assertObject(name, piece);
221
+ if (piece === void 0) continue;
222
+ for (const fn of functions)
223
+ assertFunction(`${name}.${fn}`, piece[fn]);
224
+ }
225
+ }
226
+ function validateHooks(options) {
227
+ const hooks = options.hooks;
228
+ assertObject("hooks", hooks);
229
+ if (hooks === void 0) return;
230
+ for (const hook of HOOK_NAMES)
231
+ assertOptionalFunction(`hooks.${hook}`, hooks[hook]);
232
+ }
233
+ function validateShapes(options) {
234
+ for (const group of GROUP_NAMES) assertObject(group, options[group]);
235
+ validatePieces(options);
236
+ validateHooks(options);
237
+ assertOptionalFunction("tenantResolver", options.tenantResolver);
238
+ assertBoolean("sse.emitConnectionEvent", options.sse?.emitConnectionEvent);
239
+ assertBoolean("websocket.emitConnectionEvent", options.websocket?.emitConnectionEvent);
240
+ assertEndpoint("sse.endpoint", options.sse?.endpoint);
241
+ }
242
+
88
243
  // src/server/config/validate-options.ts
89
244
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
90
- function validateOptions(options) {
245
+ function validateOptions(raw) {
246
+ const options = dropUnset(raw);
91
247
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
92
248
  throw realtimeError(
93
249
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
94
- `options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`,
250
+ `options.transport must be one of 'sse' | 'websocket' | 'both', received ${describeReceived(options.transport)}`,
95
251
  { who: "BymaxRealtimeModule" }
96
252
  );
97
253
  }
@@ -109,6 +265,7 @@ function validateOptions(options) {
109
265
  { who: "BymaxRealtimeModule" }
110
266
  );
111
267
  }
268
+ validateShapes(options);
112
269
  validateHookTimeout(options);
113
270
  validateOnConnectFailure(options);
114
271
  validateSseOptions(options);
@@ -124,7 +281,7 @@ function assertInteger(path, value, least, most) {
124
281
  if (valid) return;
125
282
  throw realtimeError(
126
283
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
127
- `options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}${most === void 0 && Number.isInteger(value) && !Number.isSafeInteger(value) ? ` (the most is ${Number.MAX_SAFE_INTEGER})` : ""}`,
284
+ `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})` : ""}`,
128
285
  { who: "BymaxRealtimeModule" }
129
286
  );
130
287
  }
@@ -133,7 +290,7 @@ function validateOnConnectFailure(options) {
133
290
  if (value === void 0 || value === "ignore" || value === "close") return;
134
291
  throw realtimeError(
135
292
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
136
- `options.onConnectFailure must be 'ignore' or 'close', got ${String(value)}`,
293
+ `options.onConnectFailure must be 'ignore' or 'close', received ${describeReceived(value)}`,
137
294
  { who: "BymaxRealtimeModule" }
138
295
  );
139
296
  }
@@ -172,7 +329,7 @@ function validateReauthPolicy(options) {
172
329
  if (onFailure !== void 0 && onFailure !== "disconnect" && onFailure !== "event") {
173
330
  throw realtimeError(
174
331
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
175
- `options.reauthenticationPolicy.onFailure must be 'disconnect' or 'event', got ${String(onFailure)}`,
332
+ `options.reauthenticationPolicy.onFailure must be 'disconnect' or 'event', received ${describeReceived(onFailure)}`,
176
333
  { who: "BymaxRealtimeModule" }
177
334
  );
178
335
  }
@@ -189,7 +346,7 @@ function validateSseOptions(options) {
189
346
  if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
190
347
  throw realtimeError(
191
348
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
192
- `options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`,
349
+ `options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms, received ${describeReceived(heartbeatMs)}`,
193
350
  { who: "BymaxRealtimeModule" }
194
351
  );
195
352
  }
@@ -201,7 +358,7 @@ function validateSseOptions(options) {
201
358
  if (value !== void 0 && !(typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
202
359
  throw realtimeError(
203
360
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
204
- `options.sse.${name} must be an integer >= 0 (0 switches the bound off), got ${String(value)}`,
361
+ `options.sse.${name} must be an integer >= 0 (0 switches the bound off), received ${describeReceived(value)}`,
205
362
  { who: "BymaxRealtimeModule" }
206
363
  );
207
364
  }
@@ -426,7 +583,7 @@ function refuseReservedRoom(operation, roomId) {
426
583
  }
427
584
 
428
585
  // src/server/utils/admit-rooms.ts
429
- function refuse(detail) {
586
+ function refuse2(detail) {
430
587
  throw realtimeError(
431
588
  REALTIME_ERROR_CODES.AUTH_FAILED,
432
589
  `the authenticator returned rooms that are not valid: ${detail}. Fix the authenticator; the limits are bounds against abuse and apply to this field only.`
@@ -435,11 +592,11 @@ function refuse(detail) {
435
592
  function admitRooms(auth) {
436
593
  const { rooms } = auth;
437
594
  if (rooms === void 0) return auth;
438
- if (!Array.isArray(rooms)) refuse("`rooms` is not an array");
595
+ if (!Array.isArray(rooms)) refuse2("`rooms` is not an array");
439
596
  const admitted = [];
440
597
  for (const room of rooms) {
441
598
  if (admitted.length === ADMISSION_ROOM_LIMITS.MAX_ROOMS) {
442
- refuse(
599
+ refuse2(
443
600
  `more than ${ADMISSION_ROOM_LIMITS.MAX_ROOMS} rooms: the limit is ${ADMISSION_ROOM_LIMITS.MAX_ROOMS}`
444
601
  );
445
602
  }
@@ -447,13 +604,13 @@ function admitRooms(auth) {
447
604
  }
448
605
  for (const room of admitted) {
449
606
  if (typeof room !== "string" || room.trim().length === 0) {
450
- refuse("every room must be a non-blank string");
607
+ refuse2("every room must be a non-blank string");
451
608
  }
452
609
  if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
453
- refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
610
+ refuse2(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
454
611
  }
455
612
  const reserved = reservedRoomPrefix(room);
456
- if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
613
+ if (reserved !== void 0) refuse2(`a room name starts with the reserved prefix "${reserved}"`);
457
614
  }
458
615
  return { ...auth, rooms: Object.freeze(admitted) };
459
616
  }
@@ -926,7 +1083,7 @@ exports.HeartbeatService = class HeartbeatService {
926
1083
  if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
927
1084
  throw realtimeError(
928
1085
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
929
- `heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
1086
+ `heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms, received ${describeReceived(intervalMs)}`
930
1087
  );
931
1088
  }
932
1089
  this.stop(connectionId);
@@ -2058,7 +2215,8 @@ function buildCommonProviders(resolved, instanceId) {
2058
2215
  ...SHARED_SERVICES
2059
2216
  ];
2060
2217
  }
2061
- function composeForRoot(moduleClass, wiring, logger, options) {
2218
+ function composeForRoot(moduleClass, wiring, logger, raw) {
2219
+ const options = dropUnset(raw);
2062
2220
  validateOptions(options);
2063
2221
  assertModeSupported(wiring, options.transport, moduleClass.name);
2064
2222
  const resolved = applyDefaults(options);
@@ -2077,7 +2235,7 @@ function assertSseEndpointApplies(asyncOptions, moduleName) {
2077
2235
  if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
2078
2236
  throw realtimeError(
2079
2237
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
2080
- `sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
2238
+ `sseEndpoint was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
2081
2239
  { who: moduleName }
2082
2240
  );
2083
2241
  }
@@ -2085,7 +2243,7 @@ function bindSseEndpoint(resolved, declared, bound, moduleName) {
2085
2243
  if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
2086
2244
  throw realtimeError(
2087
2245
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
2088
- `the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`,
2246
+ `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`,
2089
2247
  { who: moduleName }
2090
2248
  );
2091
2249
  }
@@ -2095,17 +2253,18 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
2095
2253
  if (!raw) {
2096
2254
  throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
2097
2255
  }
2098
- validateOptions(raw);
2099
- if (raw.transport !== declaredMode) {
2256
+ const options = dropUnset(raw);
2257
+ validateOptions(options);
2258
+ if (options.transport !== declaredMode) {
2100
2259
  throw realtimeError(
2101
2260
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
2102
- `forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`,
2261
+ `forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${options.transport}'`,
2103
2262
  { who: moduleName }
2104
2263
  );
2105
2264
  }
2106
- const resolved = applyDefaults(raw);
2265
+ const resolved = applyDefaults(options);
2107
2266
  logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
2108
- return resolved;
2267
+ return { resolved, declaredEndpoint: options.sse?.endpoint };
2109
2268
  }
2110
2269
  function assertOneFactoryPattern(asyncOptions, moduleName) {
2111
2270
  const patterns = [
@@ -2155,7 +2314,7 @@ function buildOptionDerivedProviders(logger, instanceId) {
2155
2314
  }
2156
2315
  function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName) {
2157
2316
  return (raw, source) => {
2158
- const resolved = resolveAsyncOptions(
2317
+ const { resolved, declaredEndpoint } = resolveAsyncOptions(
2159
2318
  raw,
2160
2319
  asyncOptions.transport,
2161
2320
  instanceId,
@@ -2164,7 +2323,7 @@ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, modul
2164
2323
  moduleName
2165
2324
  );
2166
2325
  if (asyncOptions.transport === "websocket") return resolved;
2167
- return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
2326
+ return bindSseEndpoint(resolved, declaredEndpoint, boundSseEndpoint, moduleName);
2168
2327
  };
2169
2328
  }
2170
2329
  function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
@@ -2587,6 +2746,18 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2587
2746
  };
2588
2747
 
2589
2748
  // src/server/offline-queue/redis-offline-queue.ts
2749
+ var MAX_PER_USER_CEILING = 1e5;
2750
+ var TTL_SECONDS_CEILING = 2147483647;
2751
+ function requireInteger(name, value, least, most) {
2752
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= least && value <= most) {
2753
+ return value;
2754
+ }
2755
+ throw realtimeError(
2756
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
2757
+ `options.${name} must be an integer >= ${least} and <= ${most}, received ${describeReceived(value)}`,
2758
+ { who: "RedisOfflineQueue" }
2759
+ );
2760
+ }
2590
2761
  var RedisOfflineQueue = class _RedisOfflineQueue {
2591
2762
  #client;
2592
2763
  maxPerUser;
@@ -2595,8 +2766,18 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2595
2766
  static COUNTER_PAD = 6;
2596
2767
  constructor(options) {
2597
2768
  this.#client = options.client;
2598
- this.maxPerUser = options.maxPerUser ?? 500;
2599
- this.ttlSeconds = options.ttlSeconds ?? 3600;
2769
+ this.maxPerUser = requireInteger(
2770
+ "maxPerUser",
2771
+ options.maxPerUser ?? 500,
2772
+ 1,
2773
+ MAX_PER_USER_CEILING
2774
+ );
2775
+ this.ttlSeconds = requireInteger(
2776
+ "ttlSeconds",
2777
+ options.ttlSeconds ?? 3600,
2778
+ 1,
2779
+ TTL_SECONDS_CEILING
2780
+ );
2600
2781
  }
2601
2782
  key(userId) {
2602
2783
  return `bymax:oq:${userId}`;
@@ -656,7 +656,7 @@ interface AsyncWiringParams {
656
656
  * @throws when the options are invalid or name a transport this entry point
657
657
  * does not serve.
658
658
  */
659
- declare function composeForRoot(moduleClass: Type<unknown>, wiring: TransportWiring, logger: Logger, options: BymaxRealtimeModuleOptions): DynamicModule;
659
+ declare function composeForRoot(moduleClass: Type<unknown>, wiring: TransportWiring, logger: Logger, raw: BymaxRealtimeModuleOptions): DynamicModule;
660
660
  /**
661
661
  * Compose the asynchronous dynamic module for an entry point.
662
662
  *
@@ -2020,9 +2020,9 @@ declare class RedisRealtimePubSub implements IRealtimePubSub {
2020
2020
  interface RedisOfflineQueueOptions {
2021
2021
  /** The Redis client to use for all queue operations. */
2022
2022
  readonly client: Redis;
2023
- /** Maximum events retained per user (oldest are trimmed). Defaults to 500. */
2023
+ /** Maximum events retained per user (oldest are trimmed): an integer from 1 to 100,000. Defaults to 500. */
2024
2024
  readonly maxPerUser?: number;
2025
- /** TTL for each user's key in seconds. Defaults to 3600 (1 hour). */
2025
+ /** TTL for each user's key in seconds: an integer from 1 to 2,147,483,647. Defaults to 3600 (1 hour). */
2026
2026
  readonly ttlSeconds?: number;
2027
2027
  }
2028
2028
  /**
@@ -656,7 +656,7 @@ interface AsyncWiringParams {
656
656
  * @throws when the options are invalid or name a transport this entry point
657
657
  * does not serve.
658
658
  */
659
- declare function composeForRoot(moduleClass: Type<unknown>, wiring: TransportWiring, logger: Logger, options: BymaxRealtimeModuleOptions): DynamicModule;
659
+ declare function composeForRoot(moduleClass: Type<unknown>, wiring: TransportWiring, logger: Logger, raw: BymaxRealtimeModuleOptions): DynamicModule;
660
660
  /**
661
661
  * Compose the asynchronous dynamic module for an entry point.
662
662
  *
@@ -2020,9 +2020,9 @@ declare class RedisRealtimePubSub implements IRealtimePubSub {
2020
2020
  interface RedisOfflineQueueOptions {
2021
2021
  /** The Redis client to use for all queue operations. */
2022
2022
  readonly client: Redis;
2023
- /** Maximum events retained per user (oldest are trimmed). Defaults to 500. */
2023
+ /** Maximum events retained per user (oldest are trimmed): an integer from 1 to 100,000. Defaults to 500. */
2024
2024
  readonly maxPerUser?: number;
2025
- /** TTL for each user's key in seconds. Defaults to 3600 (1 hour). */
2025
+ /** TTL for each user's key in seconds: an integer from 1 to 2,147,483,647. Defaults to 3600 (1 hour). */
2026
2026
  readonly ttlSeconds?: number;
2027
2027
  }
2028
2028
  /**
@@ -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(options) {
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(options) {
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' (got: ${String(options.transport)})`,
248
+ `options.transport must be one of 'sse' | 'websocket' | 'both', received ${describeReceived(options.transport)}`,
93
249
  { who: "BymaxRealtimeModule" }
94
250
  );
95
251
  }
@@ -107,6 +263,7 @@ function validateOptions(options) {
107
263
  { who: "BymaxRealtimeModule" }
108
264
  );
109
265
  }
266
+ validateShapes(options);
110
267
  validateHookTimeout(options);
111
268
  validateOnConnectFailure(options);
112
269
  validateSseOptions(options);
@@ -122,7 +279,7 @@ function assertInteger(path, value, least, most) {
122
279
  if (valid) return;
123
280
  throw realtimeError(
124
281
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
125
- `options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}${most === void 0 && Number.isInteger(value) && !Number.isSafeInteger(value) ? ` (the most is ${Number.MAX_SAFE_INTEGER})` : ""}`,
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})` : ""}`,
126
283
  { who: "BymaxRealtimeModule" }
127
284
  );
128
285
  }
@@ -131,7 +288,7 @@ function validateOnConnectFailure(options) {
131
288
  if (value === void 0 || value === "ignore" || value === "close") return;
132
289
  throw realtimeError(
133
290
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
134
- `options.onConnectFailure must be 'ignore' or 'close', got ${String(value)}`,
291
+ `options.onConnectFailure must be 'ignore' or 'close', received ${describeReceived(value)}`,
135
292
  { who: "BymaxRealtimeModule" }
136
293
  );
137
294
  }
@@ -170,7 +327,7 @@ function validateReauthPolicy(options) {
170
327
  if (onFailure !== void 0 && onFailure !== "disconnect" && onFailure !== "event") {
171
328
  throw realtimeError(
172
329
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
173
- `options.reauthenticationPolicy.onFailure must be 'disconnect' or 'event', got ${String(onFailure)}`,
330
+ `options.reauthenticationPolicy.onFailure must be 'disconnect' or 'event', received ${describeReceived(onFailure)}`,
174
331
  { who: "BymaxRealtimeModule" }
175
332
  );
176
333
  }
@@ -187,7 +344,7 @@ function validateSseOptions(options) {
187
344
  if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
188
345
  throw realtimeError(
189
346
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
190
- `options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`,
347
+ `options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms, received ${describeReceived(heartbeatMs)}`,
191
348
  { who: "BymaxRealtimeModule" }
192
349
  );
193
350
  }
@@ -199,7 +356,7 @@ function validateSseOptions(options) {
199
356
  if (value !== void 0 && !(typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
200
357
  throw realtimeError(
201
358
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
202
- `options.sse.${name} must be an integer >= 0 (0 switches the bound off), got ${String(value)}`,
359
+ `options.sse.${name} must be an integer >= 0 (0 switches the bound off), received ${describeReceived(value)}`,
203
360
  { who: "BymaxRealtimeModule" }
204
361
  );
205
362
  }
@@ -424,7 +581,7 @@ function refuseReservedRoom(operation, roomId) {
424
581
  }
425
582
 
426
583
  // src/server/utils/admit-rooms.ts
427
- function refuse(detail) {
584
+ function refuse2(detail) {
428
585
  throw realtimeError(
429
586
  REALTIME_ERROR_CODES.AUTH_FAILED,
430
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.`
@@ -433,11 +590,11 @@ function refuse(detail) {
433
590
  function admitRooms(auth) {
434
591
  const { rooms } = auth;
435
592
  if (rooms === void 0) return auth;
436
- if (!Array.isArray(rooms)) refuse("`rooms` is not an array");
593
+ if (!Array.isArray(rooms)) refuse2("`rooms` is not an array");
437
594
  const admitted = [];
438
595
  for (const room of rooms) {
439
596
  if (admitted.length === ADMISSION_ROOM_LIMITS.MAX_ROOMS) {
440
- refuse(
597
+ refuse2(
441
598
  `more than ${ADMISSION_ROOM_LIMITS.MAX_ROOMS} rooms: the limit is ${ADMISSION_ROOM_LIMITS.MAX_ROOMS}`
442
599
  );
443
600
  }
@@ -445,13 +602,13 @@ function admitRooms(auth) {
445
602
  }
446
603
  for (const room of admitted) {
447
604
  if (typeof room !== "string" || room.trim().length === 0) {
448
- refuse("every room must be a non-blank string");
605
+ refuse2("every room must be a non-blank string");
449
606
  }
450
607
  if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
451
- refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
608
+ refuse2(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
452
609
  }
453
610
  const reserved = reservedRoomPrefix(room);
454
- if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
611
+ if (reserved !== void 0) refuse2(`a room name starts with the reserved prefix "${reserved}"`);
455
612
  }
456
613
  return { ...auth, rooms: Object.freeze(admitted) };
457
614
  }
@@ -924,7 +1081,7 @@ var HeartbeatService = class {
924
1081
  if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
925
1082
  throw realtimeError(
926
1083
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
927
- `heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
1084
+ `heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms, received ${describeReceived(intervalMs)}`
928
1085
  );
929
1086
  }
930
1087
  this.stop(connectionId);
@@ -2056,7 +2213,8 @@ function buildCommonProviders(resolved, instanceId) {
2056
2213
  ...SHARED_SERVICES
2057
2214
  ];
2058
2215
  }
2059
- function composeForRoot(moduleClass, wiring, logger, options) {
2216
+ function composeForRoot(moduleClass, wiring, logger, raw) {
2217
+ const options = dropUnset(raw);
2060
2218
  validateOptions(options);
2061
2219
  assertModeSupported(wiring, options.transport, moduleClass.name);
2062
2220
  const resolved = applyDefaults(options);
@@ -2075,7 +2233,7 @@ function assertSseEndpointApplies(asyncOptions, moduleName) {
2075
2233
  if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
2076
2234
  throw realtimeError(
2077
2235
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
2078
- `sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
2236
+ `sseEndpoint was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
2079
2237
  { who: moduleName }
2080
2238
  );
2081
2239
  }
@@ -2083,7 +2241,7 @@ function bindSseEndpoint(resolved, declared, bound, moduleName) {
2083
2241
  if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
2084
2242
  throw realtimeError(
2085
2243
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
2086
- `the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`,
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`,
2087
2245
  { who: moduleName }
2088
2246
  );
2089
2247
  }
@@ -2093,17 +2251,18 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
2093
2251
  if (!raw) {
2094
2252
  throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
2095
2253
  }
2096
- validateOptions(raw);
2097
- if (raw.transport !== declaredMode) {
2254
+ const options = dropUnset(raw);
2255
+ validateOptions(options);
2256
+ if (options.transport !== declaredMode) {
2098
2257
  throw realtimeError(
2099
2258
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
2100
- `forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`,
2259
+ `forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${options.transport}'`,
2101
2260
  { who: moduleName }
2102
2261
  );
2103
2262
  }
2104
- const resolved = applyDefaults(raw);
2263
+ const resolved = applyDefaults(options);
2105
2264
  logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
2106
- return resolved;
2265
+ return { resolved, declaredEndpoint: options.sse?.endpoint };
2107
2266
  }
2108
2267
  function assertOneFactoryPattern(asyncOptions, moduleName) {
2109
2268
  const patterns = [
@@ -2153,7 +2312,7 @@ function buildOptionDerivedProviders(logger, instanceId) {
2153
2312
  }
2154
2313
  function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName) {
2155
2314
  return (raw, source) => {
2156
- const resolved = resolveAsyncOptions(
2315
+ const { resolved, declaredEndpoint } = resolveAsyncOptions(
2157
2316
  raw,
2158
2317
  asyncOptions.transport,
2159
2318
  instanceId,
@@ -2162,7 +2321,7 @@ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, modul
2162
2321
  moduleName
2163
2322
  );
2164
2323
  if (asyncOptions.transport === "websocket") return resolved;
2165
- return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
2324
+ return bindSseEndpoint(resolved, declaredEndpoint, boundSseEndpoint, moduleName);
2166
2325
  };
2167
2326
  }
2168
2327
  function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
@@ -2585,6 +2744,18 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2585
2744
  };
2586
2745
 
2587
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
+ }
2588
2759
  var RedisOfflineQueue = class _RedisOfflineQueue {
2589
2760
  #client;
2590
2761
  maxPerUser;
@@ -2593,8 +2764,18 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2593
2764
  static COUNTER_PAD = 6;
2594
2765
  constructor(options) {
2595
2766
  this.#client = options.client;
2596
- this.maxPerUser = options.maxPerUser ?? 500;
2597
- this.ttlSeconds = options.ttlSeconds ?? 3600;
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
+ );
2598
2779
  }
2599
2780
  key(userId) {
2600
2781
  return `bymax:oq:${userId}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.17",
3
+ "version": "1.2.18",
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",