@bymax-one/nest-realtime 1.2.23 → 1.2.25

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.25] - 2026-11-21
11
+
12
+ ### Fixed
13
+
14
+ - **A `tenantResolver` is given the authenticator's own result again, and the library keeps its own record.** From 1.2.22 to 1.2.24 the resolver received a copy of the result, and every shape of host object turned out to lose something in a copy: a hidden or symbol-keyed field, a field a class default or `Object.create` supplies from the prototype, an accessor that shadows one, a getter over a private field that throws on the copy. The resolver is now handed the object the authenticator returned, so none of that applies. The record the library keeps is built by name (`userId`, `tenantId`, `roles`, `rooms`, `metadata`), each field read once, before the resolver runs; what a resolver writes to the result does not change it, and `roles`, `rooms` and `metadata` stay shared. What the resolver returns is what routes, so the tenant that was tested and the tenant that is used stay one value.
15
+ - **The entries of `extraProviders` are read under the guard, and a value whose type cannot be read says so.** An entry that throws when its type or its `provide` is read raised the host's own error or a refusal without it; it is now refused with the library's code and the error as the `cause`. A refusal of the options, a group or an entry whose type could not be read says `received an object that could not be read`, where it said `a built-in object` or `an object` according to a second read of the value.
16
+ - **A log field named `service` or `version` can no longer reach a log line.** A logger that stamps those on every line would have been given two answers; `logEvent` drops them with the other names it reserves.
17
+
18
+ #### Apply to a derived backend
19
+
20
+ A `tenantResolver` now receives the authenticator's original result, not a copy: it sees a `null` or absent `tenantId` as the authenticator returned it, and a resolver that wrote to the copy it was given from 1.2.22 to 1.2.24 now writes to the authenticator's object. The record the library keeps is built by name from `userId`, `tenantId`, `roles`, `rooms` and `metadata`, and is read the way JavaScript reads a property: a field supplied by a class default, `Object.create` or an accessor on the prototype is now honoured, where 1.2.22 to 1.2.24 dropped it, so a result whose `userId` exists only on its prototype is admitted, and a blank one is still refused. Properties of the result beyond those five were never exposed to hooks and are not kept.
21
+
22
+ ## [1.2.24] - 2026-11-20
23
+
24
+ ### Fixed
25
+
26
+ - **A `tenantResolver` that writes to the result it receives no longer changes the connection.** With an absent or `null` tenant, the copy handed to the resolver was the object the library kept, so a resolver that assigned to it (for example to `userId`) changed the connection record. The resolver is given its own copy in every case; the copy is shallow, so nested objects are still shared and a write inside them still changes what is kept.
27
+ - **A log field named like what a structured logger writes itself no longer reaches the line.** `logEvent` already dropped `err`, `msg` and `level`; it now also drops `time`, `pid`, `hostname`, `name`, `v`, `req` and `res`, which a logger writes on every line.
28
+ - **Every read of an object the host hands over fails with the library's error and the host's error as its cause.** The keys of a `forRootAsync` registration were read without a guard, so a getter or a proxy on the registration raised the host's own error; they are read once, under the guard. An object that throws when its type is read, as the options, a group or the registration, was refused without the error it threw; the error is now the `cause`. What a synchronous factory returns is read for `then` once and its answer is boxed, so a trap that throws on a later read cannot escape.
29
+
30
+ ### Documentation
31
+
32
+ - **The `tenantResolver` documentation says exactly what the copy holds.** The result's own enumerable properties, and the `tenantId` as the library read it, which counts when an accessor on the prototype supplies it. This replaces "own enumerable properties only", which was true of the rest of the copy and not of the tenant.
33
+
10
34
  ## [1.2.23] - 2026-11-20
11
35
 
12
36
  ### Fixed
@@ -1262,7 +1286,9 @@ First published release.
1262
1286
  rather than by the manual sweep that raised the NestJS floors — that sweep
1263
1287
  asked about NestJS and never put the same question to the other ten peers.
1264
1288
 
1265
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.23...HEAD
1289
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.25...HEAD
1290
+ [1.2.25]: https://github.com/bymaxone/nest-realtime/compare/v1.2.24...v1.2.25
1291
+ [1.2.24]: https://github.com/bymaxone/nest-realtime/compare/v1.2.23...v1.2.24
1266
1292
  [1.2.23]: https://github.com/bymaxone/nest-realtime/compare/v1.2.22...v1.2.23
1267
1293
  [1.2.22]: https://github.com/bymaxone/nest-realtime/compare/v1.2.21...v1.2.22
1268
1294
  [1.2.21]: https://github.com/bymaxone/nest-realtime/compare/v1.2.20...v1.2.21
package/README.md CHANGED
@@ -342,23 +342,23 @@ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls
342
342
 
343
343
  All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `authenticator` are required.
344
344
 
345
- | Group | Key Options | Default |
346
- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- |
347
- | **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
348
- | **authenticator** | `IConnectionAuthenticator` | — (**required**) |
349
- | **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result (it receives a plain copy of that result, which has no `tenantId` when the tenant is absent or `null`), on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
350
- | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
351
- | **hookTimeoutMs** | How long the library waits for a hook it awaits (`onDisconnect` on both transports, WebSocket `onConnect`) before giving up on it; integer from 1 to 2147483647 | `5000` |
352
- | **onConnectFailure** | What a failing `onConnect` does to its connection: `'ignore'` logs it and keeps the connection, `'close'` logs it and closes the connection on both transports, after the hook has run; anything else is refused at start-up | `'ignore'` |
353
- | **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647 | `10000` |
354
- | **maxPendingHandshakes** | How many calls to `authenticate` may be waiting at once, across both transports; over it a handshake is refused at once without calling it; integer >= 1 | `1000` |
355
- | **maxConnections** | How many connections one instance holds, both transports together; a handshake past it is refused before `authenticate` is called (SSE `503`, WebSocket the generic error); integer >= 1, no way to switch it off | `10000` |
356
- | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
357
- | **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
358
- | **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
359
- | **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats` | `/realtime/sse`, `30000`, `100`, `300000`, `1000`, `5`, `true`, `2097152`, `1000`, `3` |
360
- | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults), `5` for `maxConnectionsPerUser` |
361
- | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency` | `300`, `'disconnect'`, `60000`, `10000`, `8` |
345
+ | Group | Key Options | Default |
346
+ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
347
+ | **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
348
+ | **authenticator** | `IConnectionAuthenticator` | — (**required**) |
349
+ | **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result (it receives the authenticator's own result, not a copy), on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
350
+ | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
351
+ | **hookTimeoutMs** | How long the library waits for a hook it awaits (`onDisconnect` on both transports, WebSocket `onConnect`) before giving up on it; integer from 1 to 2147483647 | `5000` |
352
+ | **onConnectFailure** | What a failing `onConnect` does to its connection: `'ignore'` logs it and keeps the connection, `'close'` logs it and closes the connection on both transports, after the hook has run; anything else is refused at start-up | `'ignore'` |
353
+ | **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647 | `10000` |
354
+ | **maxPendingHandshakes** | How many calls to `authenticate` may be waiting at once, across both transports; over it a handshake is refused at once without calling it; integer >= 1 | `1000` |
355
+ | **maxConnections** | How many connections one instance holds, both transports together; a handshake past it is refused before `authenticate` is called (SSE `503`, WebSocket the generic error); integer >= 1, no way to switch it off | `10000` |
356
+ | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
357
+ | **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
358
+ | **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
359
+ | **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats` | `/realtime/sse`, `30000`, `100`, `300000`, `1000`, `5`, `true`, `2097152`, `1000`, `3` |
360
+ | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults), `5` for `maxConnectionsPerUser` |
361
+ | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency` | `300`, `'disconnect'`, `60000`, `10000`, `8` |
362
362
 
363
363
  `sse.heartbeatMs` must be between 5,000 and 90,000 ms. Any other value, including `NaN` and a non-number, stops the application at start-up with `REALTIME_INVALID_OPTIONS`. `websocket.pingIntervalMs` and `websocket.pingTimeoutMs` must be integers from 1 to 2147483647 (Socket.IO runs both as timers, and Node runs a longer one as 1 ms). `sse.replayTtlMs` must be an integer from 1 to 2147483647 and `sse.replayMaxIdleUsers` an integer of 1 or more. `sse.maxQueuedBytes`, `sse.maxQueuedEvents` and `sse.stallHeartbeats` must be integers of 0 or more, and `0` switches that bound off.
364
364
 
@@ -412,7 +412,7 @@ An option that holds `undefined` or `null` is read as unset: it takes its defaul
412
412
 
413
413
  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. An endpoint holds no whitespace, because no request can reach it, and the `sseEndpoint` of `forRootAsync` gets the same check. The options argument must be an object, and so must what a `forRootAsync` factory returns; an array, a `Date` or a `Map` is refused there and where a group is expected, while an instance of your own class is read by its keys. `new RedisOfflineQueue(options)` refuses options that are not an object and a `client` that is not one.
414
414
 
415
- 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`. A `useClass` or `useExisting` provider implements `createRealtimeOptions()`, which returns the options or a promise of them; a provider that does not is refused with `REALTIME_INVALID_OPTIONS`, as is an `extraProviders` that is not an array of providers (a class, or an object with `provide`). An options object, a group, a pluggable piece or a provider whose read throws, such as a getter or a proxy, is refused the same way, with the error it threw as the `cause`. The exception is an object that throws when its type is read, such as a proxy whose every read throws: it is refused as a built-in object and its error is not kept. A factory that returns the object itself is covered, including a proxy that throws on `then` or was revoked; one written as an `async` function rejects its own promise with the object's error, which reaches the application as that factory's failure. A refusal is recognised by its stable code, so an error of your own that carries a `REALTIME_` code is not wrapped.
415
+ 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`. A `useClass` or `useExisting` provider implements `createRealtimeOptions()`, which returns the options or a promise of them; a provider that does not is refused with `REALTIME_INVALID_OPTIONS`, as is an `extraProviders` that is not an array of providers (a class, or an object with `provide`). An options object, a group, a pluggable piece or a provider whose read throws, such as a getter or a proxy, is refused the same way, with the error it threw as the `cause`. The same holds for the keys of a `forRootAsync` registration and for an object that throws when its type is read, such as a proxy whose every read throws: it is refused as an object that could not be read, with the error it threw as the `cause`. A factory that returns the object itself is covered, including a proxy that throws on `then` or was revoked; one written as an `async` function rejects its own promise with the object's error, which reaches the application as that factory's failure. A refusal is recognised by its stable code, so an error of your own that carries a `REALTIME_` code is not wrapped.
416
416
 
417
417
  > [!IMPORTANT]
418
418
  > **`forRootAsync` takes the SSE route on the registration, not from the factory.** NestJS
@@ -777,7 +777,7 @@ Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePub
777
777
 
778
778
  To place a connection in no tenant, **omit `tenantId`**. The runtime also accepts `undefined` or `null`, but whether those type-check depends on the consumer's `tsconfig` (`exactOptionalPropertyTypes` rejects `undefined`, `strictNullChecks` rejects `null`), so omission is the only form that compiles everywhere.
779
779
 
780
- `tenantResolver` cannot clear a tenant. It receives a plain copy of the authentication result, with its own enumerable properties only and no `tenantId` when the tenant is absent or `null`, not the authenticator's original object. Resolution is `tenantResolver?.(auth) ?? auth.tenantId`, so a resolver returning `undefined` or `null` means "no opinion" and the authenticator's tenant stays. Decide the absent case in the authenticator.
780
+ `tenantResolver` cannot clear a tenant. It receives the authenticator's own result, the object it returned and not a copy, so everything on it works as it does for the authenticator's code. The library keeps its own record of `userId`, `tenantId`, `roles`, `rooms` and `metadata`, built by name before the resolver runs and read the way JavaScript reads a property, so a field that a class default, `Object.create` or an accessor on the prototype supplies counts. What a resolver writes to the result does not change that record, which is another object; `roles`, `rooms` and `metadata` are shared, so a write inside them changes what the library keeps. Resolution is `tenantResolver?.(auth) ?? tenantId`, where `tenantId` is what the result held before the resolver ran, so a resolver returning `undefined` or `null` means "no opinion" and the authenticator's tenant stays. Decide the absent case in the authenticator.
781
781
 
782
782
  #### Carrying handshake context into the hooks
783
783
 
@@ -45,11 +45,14 @@ var REALTIME_ERROR_CODES = {
45
45
 
46
46
  // src/server/utils/is-plain-object.ts
47
47
  function isPlainObject(value) {
48
- if (typeof value !== "object") return false;
48
+ return readPlainObject(value).plain;
49
+ }
50
+ function readPlainObject(value) {
51
+ if (typeof value !== "object") return { plain: false, threw: false };
49
52
  try {
50
- return Object.prototype.toString.call(value) === "[object Object]";
51
- } catch {
52
- return false;
53
+ return { plain: Object.prototype.toString.call(value) === "[object Object]", threw: false };
54
+ } catch (error) {
55
+ return { plain: false, threw: true, error };
53
56
  }
54
57
  }
55
58
 
@@ -166,9 +169,12 @@ function guardHostReads(what, read) {
166
169
  );
167
170
  }
168
171
  }
169
- async function awaitHostResult(returned, what = "the options") {
170
- guardHostReads(what, () => returned?.then);
171
- return returned;
172
+ function awaitHostResult(returned, what = "the options") {
173
+ const then = guardHostReads(what, () => returned?.then);
174
+ if (typeof then !== "function") return Promise.resolve({ value: returned });
175
+ return new Promise((resolve, reject) => {
176
+ then.call(returned, (value) => resolve({ value }), reject);
177
+ });
172
178
  }
173
179
 
174
180
  // src/server/constants/injection-tokens.constants.ts
@@ -212,11 +218,11 @@ function describeReceived(value) {
212
218
  }
213
219
 
214
220
  // src/server/utils/refuse-object.ts
215
- function refuseObject(who, path, value) {
221
+ function refuseObject(who, path, value, cause) {
216
222
  throw realtimeError(
217
223
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
218
- `${path} must be an object, received ${describeReceived(value)}`,
219
- { who }
224
+ `${path} must be an object, received ${cause === void 0 ? describeReceived(value) : "an object that could not be read"}`,
225
+ cause === void 0 ? { who } : { who, cause: cause.error }
220
226
  );
221
227
  }
222
228
 
@@ -234,15 +240,18 @@ var HOOK_NAMES = [
234
240
  "onDeliveryFailure"
235
241
  ];
236
242
  var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
237
- function refuse(path, expected, received) {
243
+ var UNREADABLE = "an object that could not be read";
244
+ function refuse(path, expected, received, cause) {
238
245
  throw realtimeError(
239
246
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
240
- `options.${path} must be ${expected}, received ${describeReceived(received)}`,
241
- { who: "BymaxRealtimeModule" }
247
+ `options.${path} must be ${expected}, received ${cause === void 0 ? describeReceived(received) : UNREADABLE}`,
248
+ cause === void 0 ? { who: "BymaxRealtimeModule" } : { who: "BymaxRealtimeModule", cause: cause.error }
242
249
  );
243
250
  }
244
251
  function assertObject(path, value) {
245
- if (value !== void 0 && !isPlainObject(value)) refuse(path, "an object", value);
252
+ if (value === void 0) return;
253
+ const read = readPlainObject(value);
254
+ if (!read.plain) refuse(path, "an object", value, read.threw ? { error: read.error } : void 0);
246
255
  }
247
256
  function assertFunction(path, value) {
248
257
  if (typeof value !== "function") refuse(path, "a function", value);
@@ -261,7 +270,9 @@ function assertSseEndpoint(path, value) {
261
270
  if (/\s/.test(value)) refuse(path, "a string without whitespace", value);
262
271
  }
263
272
  function assertOptionsObject(value, who = "BymaxRealtimeModule") {
264
- if (!isPlainObject(value)) refuseObject(who, "options", value);
273
+ const read = readPlainObject(value);
274
+ if (!read.plain)
275
+ refuseObject(who, "options", value, read.threw ? { error: read.error } : void 0);
265
276
  }
266
277
  function validatePieces(options) {
267
278
  for (const [name, functions] of Object.entries(REQUIRED_FUNCTIONS)) {
@@ -298,14 +309,14 @@ function assertExtraProviders(value) {
298
309
  );
299
310
  }
300
311
  value.forEach((entry, index) => {
301
- const isClass = typeof entry === "function";
302
- const hasProvide = isPlainObject(entry) && "provide" in entry;
303
- if (isClass || hasProvide) return;
304
- const received = isPlainObject(entry) && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
312
+ if (typeof entry === "function") return;
313
+ const read = readPlainObject(entry);
314
+ if (read.plain && "provide" in entry) return;
315
+ const received = read.threw ? UNREADABLE : read.plain && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
305
316
  throw realtimeError(
306
317
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
307
318
  `extraProviders[${index}] must be a provider (a class or an object with provide), received ${received}`,
308
- { who: "BymaxRealtimeModule" }
319
+ read.threw ? { who: "BymaxRealtimeModule", cause: read.error } : { who: "BymaxRealtimeModule" }
309
320
  );
310
321
  });
311
322
  }
@@ -567,7 +578,20 @@ var REALTIME_LOG_EVENTS = [
567
578
  "REALTIME_COMPOSITE_PARTIAL_FAILURE",
568
579
  "REALTIME_SERVER_NOT_ATTACHED"
569
580
  ];
570
- var RESERVED_KEYS = ["err", "msg", "level"];
581
+ var RESERVED_KEYS = [
582
+ "err",
583
+ "msg",
584
+ "level",
585
+ "time",
586
+ "pid",
587
+ "hostname",
588
+ "name",
589
+ "v",
590
+ "req",
591
+ "res",
592
+ "service",
593
+ "version"
594
+ ];
571
595
  function logEvent(logger, level, event, message, fields = {}, error) {
572
596
  try {
573
597
  const line = { ...fields, event, message };
@@ -861,12 +885,25 @@ function isBlank(value) {
861
885
  return typeof value !== "string" || value.trim().length === 0;
862
886
  }
863
887
  function resolveAuthTenant(options, auth) {
864
- const { tenantId: own, ...rest } = auth;
865
- const resolved = options.tenantResolver?.(
866
- own === void 0 || own === null ? rest : { ...rest, tenantId: own }
867
- ) ?? own;
868
- if (resolved === void 0 || resolved === null) return rest;
869
- return { ...rest, tenantId: resolved };
888
+ const own = auth.tenantId;
889
+ const kept = keepByName(auth);
890
+ const resolved = options.tenantResolver?.(auth) ?? own;
891
+ if (resolved === void 0 || resolved === null) return kept;
892
+ return { ...kept, tenantId: resolved };
893
+ }
894
+ function keepByName(auth) {
895
+ const kept = {};
896
+ for (const key of ["userId", "roles", "rooms", "metadata"]) {
897
+ const value = auth[key];
898
+ if (value === void 0) continue;
899
+ Object.defineProperty(kept, key, {
900
+ value,
901
+ enumerable: true,
902
+ writable: true,
903
+ configurable: true
904
+ });
905
+ }
906
+ return kept;
870
907
  }
871
908
  function assertIdentityIsNotBlank(auth) {
872
909
  if (isBlank(auth.userId)) {
@@ -2684,7 +2721,7 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2684
2721
  if (isSet(asyncOptions.useFactory)) {
2685
2722
  return {
2686
2723
  provide: REALTIME_OPTIONS_TOKEN,
2687
- useFactory: async (...args) => resolve(await awaitHostResult(asyncOptions.useFactory(...args)), "useFactory"),
2724
+ useFactory: async (...args) => resolve((await awaitHostResult(asyncOptions.useFactory(...args))).value, "useFactory"),
2688
2725
  inject: [...asyncOptions.inject ?? []]
2689
2726
  };
2690
2727
  }
@@ -2702,7 +2739,7 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2702
2739
  );
2703
2740
  }
2704
2741
  return resolve(
2705
- await awaitHostResult(create.call(factory)),
2742
+ (await awaitHostResult(create.call(factory))).value,
2706
2743
  "createRealtimeOptions"
2707
2744
  );
2708
2745
  },
@@ -2739,34 +2776,48 @@ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, modul
2739
2776
  return bindSseEndpoint(resolved, declaredEndpoint, boundSseEndpoint, moduleName);
2740
2777
  };
2741
2778
  }
2779
+ var copied = (value) => Array.isArray(value) ? [...value] : value;
2780
+ function readRegistration(registration) {
2781
+ return guardHostReads("the registration", () => ({
2782
+ transport: registration.transport,
2783
+ sseEndpoint: registration.sseEndpoint,
2784
+ useFactory: registration.useFactory,
2785
+ useClass: registration.useClass,
2786
+ useExisting: registration.useExisting,
2787
+ inject: copied(registration.inject),
2788
+ imports: copied(registration.imports),
2789
+ extraProviders: copied(registration.extraProviders)
2790
+ }));
2791
+ }
2742
2792
  function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2743
2793
  const moduleName = moduleClass.name;
2744
2794
  assertOptionsObject(asyncOptions, moduleName);
2745
- assertOneFactoryPattern(asyncOptions, moduleName);
2746
- assertModeSupported(wiring, asyncOptions.transport, moduleName);
2747
- assertSseEndpoint("sseEndpoint", asyncOptions.sseEndpoint);
2748
- assertSseEndpointApplies(asyncOptions, moduleName);
2749
- assertExtraProviders(asyncOptions.extraProviders);
2795
+ const registration = readRegistration(asyncOptions);
2796
+ assertOneFactoryPattern(registration, moduleName);
2797
+ assertModeSupported(wiring, registration.transport, moduleName);
2798
+ assertSseEndpoint("sseEndpoint", registration.sseEndpoint);
2799
+ assertSseEndpointApplies(registration, moduleName);
2800
+ guardHostReads("the registration", () => assertExtraProviders(registration.extraProviders));
2750
2801
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2751
2802
  const instanceId = crypto.randomUUID();
2752
- const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2753
- const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
2754
- const factoryClassProvider = isSet(asyncOptions.useClass) ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
2803
+ const boundSseEndpoint = registration.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2804
+ const resolve = buildResolver(registration, instanceId, boundSseEndpoint, logger, moduleName);
2805
+ const factoryClassProvider = isSet(registration.useClass) ? [{ provide: FACTORY_TOKEN, useClass: registration.useClass }] : [];
2755
2806
  const { providers: transportProviders, controllers } = wiring.buildAsync({
2756
- mode: asyncOptions.transport,
2807
+ mode: registration.transport,
2757
2808
  sseEndpoint: boundSseEndpoint
2758
2809
  });
2759
2810
  return {
2760
2811
  module: moduleClass,
2761
- imports: asyncOptions.imports ?? [],
2812
+ imports: registration.imports ?? [],
2762
2813
  controllers,
2763
2814
  providers: [
2764
2815
  ...factoryClassProvider,
2765
- buildOptionsProvider(asyncOptions, resolve, FACTORY_TOKEN),
2816
+ buildOptionsProvider(registration, resolve, FACTORY_TOKEN),
2766
2817
  ...buildOptionDerivedProviders(logger, instanceId),
2767
2818
  ...SHARED_SERVICES,
2768
2819
  ...transportProviders,
2769
- ...asyncOptions.extraProviders ?? []
2820
+ ...registration.extraProviders ?? []
2770
2821
  ],
2771
2822
  exports: EXPORTED_TOKENS
2772
2823
  };
@@ -479,9 +479,15 @@ interface BymaxRealtimeModuleOptions {
479
479
  /**
480
480
  * Derive the tenant a connection routes on from the authenticated result.
481
481
  *
482
- * Applied on **both** transports. It receives a plain copy of the authentication
483
- * result, with its own enumerable properties only and no `tenantId` when the tenant
484
- * is absent or `null`, not the authenticator's original object. `undefined` and
482
+ * Applied on **both** transports. It receives the authenticator's own result, the
483
+ * object it returned and not a copy, so everything on it works as it does for the
484
+ * authenticator's code. The library keeps its own record of `userId`, `tenantId`,
485
+ * `roles`, `rooms` and `metadata`, built by name before the resolver runs and read the
486
+ * way JavaScript reads a property, so a field that a class default, `Object.create` or
487
+ * an accessor on the prototype supplies counts. What a resolver writes to the result
488
+ * does not change that record, which is another object; `roles`, `rooms` and
489
+ * `metadata` are shared, so a write inside them changes what the library keeps.
490
+ * `undefined` and
485
491
  * `null` both mean "no opinion"
486
492
  * and fall back to `auth.tenantId` rather than clearing it; to place a connection
487
493
  * in no tenant, return a result without one from the authenticator. `null` is in
@@ -2309,7 +2315,7 @@ type LogFields = Readonly<Record<string, string | number | boolean>>;
2309
2315
  * @param event - The stable code of the condition.
2310
2316
  * @param message - Human text; the library's own wording, with no host-supplied value in it.
2311
2317
  * @param fields - Closed or numeric fields, built by the library. A key named `event` or `message` is replaced by the
2312
- * library's own value, and one named `err`, `msg` or `level` is dropped, and a field whose read throws, such as a getter, loses the line like any other
2318
+ * library's own value, and one named `err`, `msg`, `level`, `time`, `pid`, `hostname`, `name`, `v`, `req`, `res`, `service` or `version` is dropped, and a field whose read throws, such as a getter, loses the line like any other
2313
2319
  * throw while writing.
2314
2320
  * @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
2315
2321
  * as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
@@ -479,9 +479,15 @@ interface BymaxRealtimeModuleOptions {
479
479
  /**
480
480
  * Derive the tenant a connection routes on from the authenticated result.
481
481
  *
482
- * Applied on **both** transports. It receives a plain copy of the authentication
483
- * result, with its own enumerable properties only and no `tenantId` when the tenant
484
- * is absent or `null`, not the authenticator's original object. `undefined` and
482
+ * Applied on **both** transports. It receives the authenticator's own result, the
483
+ * object it returned and not a copy, so everything on it works as it does for the
484
+ * authenticator's code. The library keeps its own record of `userId`, `tenantId`,
485
+ * `roles`, `rooms` and `metadata`, built by name before the resolver runs and read the
486
+ * way JavaScript reads a property, so a field that a class default, `Object.create` or
487
+ * an accessor on the prototype supplies counts. What a resolver writes to the result
488
+ * does not change that record, which is another object; `roles`, `rooms` and
489
+ * `metadata` are shared, so a write inside them changes what the library keeps.
490
+ * `undefined` and
485
491
  * `null` both mean "no opinion"
486
492
  * and fall back to `auth.tenantId` rather than clearing it; to place a connection
487
493
  * in no tenant, return a result without one from the authenticator. `null` is in
@@ -2309,7 +2315,7 @@ type LogFields = Readonly<Record<string, string | number | boolean>>;
2309
2315
  * @param event - The stable code of the condition.
2310
2316
  * @param message - Human text; the library's own wording, with no host-supplied value in it.
2311
2317
  * @param fields - Closed or numeric fields, built by the library. A key named `event` or `message` is replaced by the
2312
- * library's own value, and one named `err`, `msg` or `level` is dropped, and a field whose read throws, such as a getter, loses the line like any other
2318
+ * library's own value, and one named `err`, `msg`, `level`, `time`, `pid`, `hostname`, `name`, `v`, `req`, `res`, `service` or `version` is dropped, and a field whose read throws, such as a getter, loses the line like any other
2313
2319
  * throw while writing.
2314
2320
  * @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
2315
2321
  * as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
@@ -43,11 +43,14 @@ var REALTIME_ERROR_CODES = {
43
43
 
44
44
  // src/server/utils/is-plain-object.ts
45
45
  function isPlainObject(value) {
46
- if (typeof value !== "object") return false;
46
+ return readPlainObject(value).plain;
47
+ }
48
+ function readPlainObject(value) {
49
+ if (typeof value !== "object") return { plain: false, threw: false };
47
50
  try {
48
- return Object.prototype.toString.call(value) === "[object Object]";
49
- } catch {
50
- return false;
51
+ return { plain: Object.prototype.toString.call(value) === "[object Object]", threw: false };
52
+ } catch (error) {
53
+ return { plain: false, threw: true, error };
51
54
  }
52
55
  }
53
56
 
@@ -164,9 +167,12 @@ function guardHostReads(what, read) {
164
167
  );
165
168
  }
166
169
  }
167
- async function awaitHostResult(returned, what = "the options") {
168
- guardHostReads(what, () => returned?.then);
169
- return returned;
170
+ function awaitHostResult(returned, what = "the options") {
171
+ const then = guardHostReads(what, () => returned?.then);
172
+ if (typeof then !== "function") return Promise.resolve({ value: returned });
173
+ return new Promise((resolve, reject) => {
174
+ then.call(returned, (value) => resolve({ value }), reject);
175
+ });
170
176
  }
171
177
 
172
178
  // src/server/constants/injection-tokens.constants.ts
@@ -210,11 +216,11 @@ function describeReceived(value) {
210
216
  }
211
217
 
212
218
  // src/server/utils/refuse-object.ts
213
- function refuseObject(who, path, value) {
219
+ function refuseObject(who, path, value, cause) {
214
220
  throw realtimeError(
215
221
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
216
- `${path} must be an object, received ${describeReceived(value)}`,
217
- { who }
222
+ `${path} must be an object, received ${cause === void 0 ? describeReceived(value) : "an object that could not be read"}`,
223
+ cause === void 0 ? { who } : { who, cause: cause.error }
218
224
  );
219
225
  }
220
226
 
@@ -232,15 +238,18 @@ var HOOK_NAMES = [
232
238
  "onDeliveryFailure"
233
239
  ];
234
240
  var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
235
- function refuse(path, expected, received) {
241
+ var UNREADABLE = "an object that could not be read";
242
+ function refuse(path, expected, received, cause) {
236
243
  throw realtimeError(
237
244
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
238
- `options.${path} must be ${expected}, received ${describeReceived(received)}`,
239
- { who: "BymaxRealtimeModule" }
245
+ `options.${path} must be ${expected}, received ${cause === void 0 ? describeReceived(received) : UNREADABLE}`,
246
+ cause === void 0 ? { who: "BymaxRealtimeModule" } : { who: "BymaxRealtimeModule", cause: cause.error }
240
247
  );
241
248
  }
242
249
  function assertObject(path, value) {
243
- if (value !== void 0 && !isPlainObject(value)) refuse(path, "an object", value);
250
+ if (value === void 0) return;
251
+ const read = readPlainObject(value);
252
+ if (!read.plain) refuse(path, "an object", value, read.threw ? { error: read.error } : void 0);
244
253
  }
245
254
  function assertFunction(path, value) {
246
255
  if (typeof value !== "function") refuse(path, "a function", value);
@@ -259,7 +268,9 @@ function assertSseEndpoint(path, value) {
259
268
  if (/\s/.test(value)) refuse(path, "a string without whitespace", value);
260
269
  }
261
270
  function assertOptionsObject(value, who = "BymaxRealtimeModule") {
262
- if (!isPlainObject(value)) refuseObject(who, "options", value);
271
+ const read = readPlainObject(value);
272
+ if (!read.plain)
273
+ refuseObject(who, "options", value, read.threw ? { error: read.error } : void 0);
263
274
  }
264
275
  function validatePieces(options) {
265
276
  for (const [name, functions] of Object.entries(REQUIRED_FUNCTIONS)) {
@@ -296,14 +307,14 @@ function assertExtraProviders(value) {
296
307
  );
297
308
  }
298
309
  value.forEach((entry, index) => {
299
- const isClass = typeof entry === "function";
300
- const hasProvide = isPlainObject(entry) && "provide" in entry;
301
- if (isClass || hasProvide) return;
302
- const received = isPlainObject(entry) && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
310
+ if (typeof entry === "function") return;
311
+ const read = readPlainObject(entry);
312
+ if (read.plain && "provide" in entry) return;
313
+ const received = read.threw ? UNREADABLE : read.plain && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
303
314
  throw realtimeError(
304
315
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
305
316
  `extraProviders[${index}] must be a provider (a class or an object with provide), received ${received}`,
306
- { who: "BymaxRealtimeModule" }
317
+ read.threw ? { who: "BymaxRealtimeModule", cause: read.error } : { who: "BymaxRealtimeModule" }
307
318
  );
308
319
  });
309
320
  }
@@ -565,7 +576,20 @@ var REALTIME_LOG_EVENTS = [
565
576
  "REALTIME_COMPOSITE_PARTIAL_FAILURE",
566
577
  "REALTIME_SERVER_NOT_ATTACHED"
567
578
  ];
568
- var RESERVED_KEYS = ["err", "msg", "level"];
579
+ var RESERVED_KEYS = [
580
+ "err",
581
+ "msg",
582
+ "level",
583
+ "time",
584
+ "pid",
585
+ "hostname",
586
+ "name",
587
+ "v",
588
+ "req",
589
+ "res",
590
+ "service",
591
+ "version"
592
+ ];
569
593
  function logEvent(logger, level, event, message, fields = {}, error) {
570
594
  try {
571
595
  const line = { ...fields, event, message };
@@ -859,12 +883,25 @@ function isBlank(value) {
859
883
  return typeof value !== "string" || value.trim().length === 0;
860
884
  }
861
885
  function resolveAuthTenant(options, auth) {
862
- const { tenantId: own, ...rest } = auth;
863
- const resolved = options.tenantResolver?.(
864
- own === void 0 || own === null ? rest : { ...rest, tenantId: own }
865
- ) ?? own;
866
- if (resolved === void 0 || resolved === null) return rest;
867
- return { ...rest, tenantId: resolved };
886
+ const own = auth.tenantId;
887
+ const kept = keepByName(auth);
888
+ const resolved = options.tenantResolver?.(auth) ?? own;
889
+ if (resolved === void 0 || resolved === null) return kept;
890
+ return { ...kept, tenantId: resolved };
891
+ }
892
+ function keepByName(auth) {
893
+ const kept = {};
894
+ for (const key of ["userId", "roles", "rooms", "metadata"]) {
895
+ const value = auth[key];
896
+ if (value === void 0) continue;
897
+ Object.defineProperty(kept, key, {
898
+ value,
899
+ enumerable: true,
900
+ writable: true,
901
+ configurable: true
902
+ });
903
+ }
904
+ return kept;
868
905
  }
869
906
  function assertIdentityIsNotBlank(auth) {
870
907
  if (isBlank(auth.userId)) {
@@ -2682,7 +2719,7 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2682
2719
  if (isSet(asyncOptions.useFactory)) {
2683
2720
  return {
2684
2721
  provide: REALTIME_OPTIONS_TOKEN,
2685
- useFactory: async (...args) => resolve(await awaitHostResult(asyncOptions.useFactory(...args)), "useFactory"),
2722
+ useFactory: async (...args) => resolve((await awaitHostResult(asyncOptions.useFactory(...args))).value, "useFactory"),
2686
2723
  inject: [...asyncOptions.inject ?? []]
2687
2724
  };
2688
2725
  }
@@ -2700,7 +2737,7 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2700
2737
  );
2701
2738
  }
2702
2739
  return resolve(
2703
- await awaitHostResult(create.call(factory)),
2740
+ (await awaitHostResult(create.call(factory))).value,
2704
2741
  "createRealtimeOptions"
2705
2742
  );
2706
2743
  },
@@ -2737,34 +2774,48 @@ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, modul
2737
2774
  return bindSseEndpoint(resolved, declaredEndpoint, boundSseEndpoint, moduleName);
2738
2775
  };
2739
2776
  }
2777
+ var copied = (value) => Array.isArray(value) ? [...value] : value;
2778
+ function readRegistration(registration) {
2779
+ return guardHostReads("the registration", () => ({
2780
+ transport: registration.transport,
2781
+ sseEndpoint: registration.sseEndpoint,
2782
+ useFactory: registration.useFactory,
2783
+ useClass: registration.useClass,
2784
+ useExisting: registration.useExisting,
2785
+ inject: copied(registration.inject),
2786
+ imports: copied(registration.imports),
2787
+ extraProviders: copied(registration.extraProviders)
2788
+ }));
2789
+ }
2740
2790
  function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2741
2791
  const moduleName = moduleClass.name;
2742
2792
  assertOptionsObject(asyncOptions, moduleName);
2743
- assertOneFactoryPattern(asyncOptions, moduleName);
2744
- assertModeSupported(wiring, asyncOptions.transport, moduleName);
2745
- assertSseEndpoint("sseEndpoint", asyncOptions.sseEndpoint);
2746
- assertSseEndpointApplies(asyncOptions, moduleName);
2747
- assertExtraProviders(asyncOptions.extraProviders);
2793
+ const registration = readRegistration(asyncOptions);
2794
+ assertOneFactoryPattern(registration, moduleName);
2795
+ assertModeSupported(wiring, registration.transport, moduleName);
2796
+ assertSseEndpoint("sseEndpoint", registration.sseEndpoint);
2797
+ assertSseEndpointApplies(registration, moduleName);
2798
+ guardHostReads("the registration", () => assertExtraProviders(registration.extraProviders));
2748
2799
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2749
2800
  const instanceId = randomUUID();
2750
- const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2751
- const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
2752
- const factoryClassProvider = isSet(asyncOptions.useClass) ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
2801
+ const boundSseEndpoint = registration.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2802
+ const resolve = buildResolver(registration, instanceId, boundSseEndpoint, logger, moduleName);
2803
+ const factoryClassProvider = isSet(registration.useClass) ? [{ provide: FACTORY_TOKEN, useClass: registration.useClass }] : [];
2753
2804
  const { providers: transportProviders, controllers } = wiring.buildAsync({
2754
- mode: asyncOptions.transport,
2805
+ mode: registration.transport,
2755
2806
  sseEndpoint: boundSseEndpoint
2756
2807
  });
2757
2808
  return {
2758
2809
  module: moduleClass,
2759
- imports: asyncOptions.imports ?? [],
2810
+ imports: registration.imports ?? [],
2760
2811
  controllers,
2761
2812
  providers: [
2762
2813
  ...factoryClassProvider,
2763
- buildOptionsProvider(asyncOptions, resolve, FACTORY_TOKEN),
2814
+ buildOptionsProvider(registration, resolve, FACTORY_TOKEN),
2764
2815
  ...buildOptionDerivedProviders(logger, instanceId),
2765
2816
  ...SHARED_SERVICES,
2766
2817
  ...transportProviders,
2767
- ...asyncOptions.extraProviders ?? []
2818
+ ...registration.extraProviders ?? []
2768
2819
  ],
2769
2820
  exports: EXPORTED_TOKENS
2770
2821
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.23",
3
+ "version": "1.2.25",
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",