@bymax-one/nest-realtime 1.2.22 → 1.2.24
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 +25 -1
- package/README.md +26 -26
- package/dist/internal/index.cjs +65 -29
- package/dist/internal/index.d.cts +11 -3
- package/dist/internal/index.d.ts +11 -3
- package/dist/internal/index.mjs +65 -29
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,28 @@ Versioning is **not** strict [SemVer](https://semver.org/spec/v2.0.0.html) while
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.24] - 2026-11-20
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **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.
|
|
15
|
+
- **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.
|
|
16
|
+
- **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.
|
|
17
|
+
|
|
18
|
+
### Documentation
|
|
19
|
+
|
|
20
|
+
- **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.
|
|
21
|
+
|
|
22
|
+
## [1.2.23] - 2026-11-20
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- **A field named `msg` or `level` can no longer reach a log line.** A structured logger reads `msg` as the text of a line and `level` as its severity, so a field of either name could change what a library line says or how it is filed. `logEvent` drops them, as it already did `err`; `event` and `message` stay the library's own.
|
|
27
|
+
|
|
28
|
+
### Documentation
|
|
29
|
+
|
|
30
|
+
- **The README and the `tenantResolver` documentation say that the resolver receives a plain copy.** The options table, the paragraph on identity and the JSDoc state that the copy has its own enumerable properties only and no `tenantId` when the tenant is absent or `null`.
|
|
31
|
+
|
|
10
32
|
## [1.2.22] - 2026-11-20
|
|
11
33
|
|
|
12
34
|
### Fixed
|
|
@@ -1252,7 +1274,9 @@ First published release.
|
|
|
1252
1274
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
1253
1275
|
asked about NestJS and never put the same question to the other ten peers.
|
|
1254
1276
|
|
|
1255
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
1277
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.24...HEAD
|
|
1278
|
+
[1.2.24]: https://github.com/bymaxone/nest-realtime/compare/v1.2.23...v1.2.24
|
|
1279
|
+
[1.2.23]: https://github.com/bymaxone/nest-realtime/compare/v1.2.22...v1.2.23
|
|
1256
1280
|
[1.2.22]: https://github.com/bymaxone/nest-realtime/compare/v1.2.21...v1.2.22
|
|
1257
1281
|
[1.2.21]: https://github.com/bymaxone/nest-realtime/compare/v1.2.20...v1.2.21
|
|
1258
1282
|
[1.2.20]: https://github.com/bymaxone/nest-realtime/compare/v1.2.19...v1.2.20
|
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
|
|
346
|
-
| -------------------------- |
|
|
347
|
-
| **transport** | `'sse'` \| `'websocket'` \| `'both'`
|
|
348
|
-
| **authenticator** | `IConnectionAuthenticator`
|
|
349
|
-
| **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back
|
|
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
|
|
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
|
|
353
|
-
| **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647
|
|
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
|
|
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
|
|
356
|
-
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE
|
|
357
|
-
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away
|
|
358
|
-
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it
|
|
359
|
-
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats`
|
|
360
|
-
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter`
|
|
361
|
-
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency`
|
|
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` |
|
|
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
|
|
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 a built-in object, 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
|
|
@@ -497,13 +497,13 @@ import {
|
|
|
497
497
|
export class ObservabilityModule {}
|
|
498
498
|
```
|
|
499
499
|
|
|
500
|
-
| Metric | Type | Labels | Meaning
|
|
501
|
-
| ------------------------------------------ | ------- | ---------------------------------------------------------- |
|
|
502
|
-
| `bymax_realtime_connections` | gauge | `transport` = `sse`, `websocket` | Connections open on this instance now.
|
|
503
|
-
| `bymax_realtime_connections_refused_total` | counter | `reason` = `limit`, `unauthorized`, `unavailable`, `error` | Handshakes refused since start; `error` is one that failed with an unexpected error (a 500); a connection that `onConnectFailure: 'close'` closes was admitted first, and is not counted.
|
|
504
|
-
| `bymax_realtime_evictions_total` | counter | `reason` = `per_user_cap`, `slow_consumer`, `revoked` | Connections closed by the library or by a revocation.
|
|
505
|
-
| `bymax_realtime_events_emitted_total` | counter | `transport` = `sse`, `websocket` | Emit calls handled on this instance, not deliveries: a call with no recipient counts, and under `'both'` each transport counts it.
|
|
506
|
-
| `bymax_realtime_slow_consumer_drops_total` | counter | none | Connections cut for not reading what they were sent.
|
|
500
|
+
| Metric | Type | Labels | Meaning |
|
|
501
|
+
| ------------------------------------------ | ------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
502
|
+
| `bymax_realtime_connections` | gauge | `transport` = `sse`, `websocket` | Connections open on this instance now. |
|
|
503
|
+
| `bymax_realtime_connections_refused_total` | counter | `reason` = `limit`, `unauthorized`, `unavailable`, `error` | Handshakes refused since start; `error` is one that failed with an unexpected error (a 500); a connection that `onConnectFailure: 'close'` closes was admitted first, and is not counted. |
|
|
504
|
+
| `bymax_realtime_evictions_total` | counter | `reason` = `per_user_cap`, `slow_consumer`, `revoked` | Connections closed by the library or by a revocation. |
|
|
505
|
+
| `bymax_realtime_events_emitted_total` | counter | `transport` = `sse`, `websocket` | Emit calls handled on this instance, not deliveries: a call with no recipient counts, and under `'both'` each transport counts it. |
|
|
506
|
+
| `bymax_realtime_slow_consumer_drops_total` | counter | none | Connections cut for not reading what they were sent. |
|
|
507
507
|
|
|
508
508
|
A label is one of the values listed and never an id, a tenant or a user. A revocation is counted on the instance that was asked to make it, once it has closed the connection or handed the request to the bus.
|
|
509
509
|
|
|
@@ -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. 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 a plain copy of the authentication result, not the authenticator's original object: the result's own enumerable properties, and the `tenantId` as the library read it, which counts when an accessor on the prototype supplies it and is missing when the tenant is absent or `null`. The copy is its own object and is shallow: a resolver that assigns to one of its top-level properties changes nothing the library keeps, while nested objects are shared with the original, so a write inside them changes what the library keeps. 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.
|
|
781
781
|
|
|
782
782
|
#### Carrying handshake context into the hooks
|
|
783
783
|
|
package/dist/internal/index.cjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
224
|
`${path} must be an object, received ${describeReceived(value)}`,
|
|
219
|
-
{ who }
|
|
225
|
+
cause === void 0 ? { who } : { who, cause: cause.error }
|
|
220
226
|
);
|
|
221
227
|
}
|
|
222
228
|
|
|
@@ -234,15 +240,17 @@ var HOOK_NAMES = [
|
|
|
234
240
|
"onDeliveryFailure"
|
|
235
241
|
];
|
|
236
242
|
var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
|
|
237
|
-
function refuse(path, expected, received) {
|
|
243
|
+
function refuse(path, expected, received, cause) {
|
|
238
244
|
throw realtimeError(
|
|
239
245
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
240
246
|
`options.${path} must be ${expected}, received ${describeReceived(received)}`,
|
|
241
|
-
{ who: "BymaxRealtimeModule" }
|
|
247
|
+
cause === void 0 ? { who: "BymaxRealtimeModule" } : { who: "BymaxRealtimeModule", cause: cause.error }
|
|
242
248
|
);
|
|
243
249
|
}
|
|
244
250
|
function assertObject(path, value) {
|
|
245
|
-
if (value
|
|
251
|
+
if (value === void 0) return;
|
|
252
|
+
const read = readPlainObject(value);
|
|
253
|
+
if (!read.plain) refuse(path, "an object", value, read.threw ? { error: read.error } : void 0);
|
|
246
254
|
}
|
|
247
255
|
function assertFunction(path, value) {
|
|
248
256
|
if (typeof value !== "function") refuse(path, "a function", value);
|
|
@@ -261,7 +269,9 @@ function assertSseEndpoint(path, value) {
|
|
|
261
269
|
if (/\s/.test(value)) refuse(path, "a string without whitespace", value);
|
|
262
270
|
}
|
|
263
271
|
function assertOptionsObject(value, who = "BymaxRealtimeModule") {
|
|
264
|
-
|
|
272
|
+
const read = readPlainObject(value);
|
|
273
|
+
if (!read.plain)
|
|
274
|
+
refuseObject(who, "options", value, read.threw ? { error: read.error } : void 0);
|
|
265
275
|
}
|
|
266
276
|
function validatePieces(options) {
|
|
267
277
|
for (const [name, functions] of Object.entries(REQUIRED_FUNCTIONS)) {
|
|
@@ -567,10 +577,22 @@ var REALTIME_LOG_EVENTS = [
|
|
|
567
577
|
"REALTIME_COMPOSITE_PARTIAL_FAILURE",
|
|
568
578
|
"REALTIME_SERVER_NOT_ATTACHED"
|
|
569
579
|
];
|
|
580
|
+
var RESERVED_KEYS = [
|
|
581
|
+
"err",
|
|
582
|
+
"msg",
|
|
583
|
+
"level",
|
|
584
|
+
"time",
|
|
585
|
+
"pid",
|
|
586
|
+
"hostname",
|
|
587
|
+
"name",
|
|
588
|
+
"v",
|
|
589
|
+
"req",
|
|
590
|
+
"res"
|
|
591
|
+
];
|
|
570
592
|
function logEvent(logger, level, event, message, fields = {}, error) {
|
|
571
593
|
try {
|
|
572
594
|
const line = { ...fields, event, message };
|
|
573
|
-
delete line[
|
|
595
|
+
for (const key of RESERVED_KEYS) delete line[key];
|
|
574
596
|
if (error !== void 0) line["err"] = error;
|
|
575
597
|
logger[level](line);
|
|
576
598
|
} catch {
|
|
@@ -862,7 +884,7 @@ function isBlank(value) {
|
|
|
862
884
|
function resolveAuthTenant(options, auth) {
|
|
863
885
|
const { tenantId: own, ...rest } = auth;
|
|
864
886
|
const resolved = options.tenantResolver?.(
|
|
865
|
-
own === void 0 || own === null ? rest : { ...rest, tenantId: own }
|
|
887
|
+
own === void 0 || own === null ? { ...rest } : { ...rest, tenantId: own }
|
|
866
888
|
) ?? own;
|
|
867
889
|
if (resolved === void 0 || resolved === null) return rest;
|
|
868
890
|
return { ...rest, tenantId: resolved };
|
|
@@ -2683,7 +2705,7 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
|
|
|
2683
2705
|
if (isSet(asyncOptions.useFactory)) {
|
|
2684
2706
|
return {
|
|
2685
2707
|
provide: REALTIME_OPTIONS_TOKEN,
|
|
2686
|
-
useFactory: async (...args) => resolve(await awaitHostResult(asyncOptions.useFactory(...args)), "useFactory"),
|
|
2708
|
+
useFactory: async (...args) => resolve((await awaitHostResult(asyncOptions.useFactory(...args))).value, "useFactory"),
|
|
2687
2709
|
inject: [...asyncOptions.inject ?? []]
|
|
2688
2710
|
};
|
|
2689
2711
|
}
|
|
@@ -2701,7 +2723,7 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
|
|
|
2701
2723
|
);
|
|
2702
2724
|
}
|
|
2703
2725
|
return resolve(
|
|
2704
|
-
await awaitHostResult(create.call(factory)),
|
|
2726
|
+
(await awaitHostResult(create.call(factory))).value,
|
|
2705
2727
|
"createRealtimeOptions"
|
|
2706
2728
|
);
|
|
2707
2729
|
},
|
|
@@ -2738,34 +2760,48 @@ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, modul
|
|
|
2738
2760
|
return bindSseEndpoint(resolved, declaredEndpoint, boundSseEndpoint, moduleName);
|
|
2739
2761
|
};
|
|
2740
2762
|
}
|
|
2763
|
+
var copied = (value) => Array.isArray(value) ? [...value] : value;
|
|
2764
|
+
function readRegistration(registration) {
|
|
2765
|
+
return guardHostReads("the registration", () => ({
|
|
2766
|
+
transport: registration.transport,
|
|
2767
|
+
sseEndpoint: registration.sseEndpoint,
|
|
2768
|
+
useFactory: registration.useFactory,
|
|
2769
|
+
useClass: registration.useClass,
|
|
2770
|
+
useExisting: registration.useExisting,
|
|
2771
|
+
inject: copied(registration.inject),
|
|
2772
|
+
imports: copied(registration.imports),
|
|
2773
|
+
extraProviders: copied(registration.extraProviders)
|
|
2774
|
+
}));
|
|
2775
|
+
}
|
|
2741
2776
|
function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
2742
2777
|
const moduleName = moduleClass.name;
|
|
2743
2778
|
assertOptionsObject(asyncOptions, moduleName);
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2779
|
+
const registration = readRegistration(asyncOptions);
|
|
2780
|
+
assertOneFactoryPattern(registration, moduleName);
|
|
2781
|
+
assertModeSupported(wiring, registration.transport, moduleName);
|
|
2782
|
+
assertSseEndpoint("sseEndpoint", registration.sseEndpoint);
|
|
2783
|
+
assertSseEndpointApplies(registration, moduleName);
|
|
2784
|
+
assertExtraProviders(registration.extraProviders);
|
|
2749
2785
|
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
2750
2786
|
const instanceId = crypto.randomUUID();
|
|
2751
|
-
const boundSseEndpoint =
|
|
2752
|
-
const resolve = buildResolver(
|
|
2753
|
-
const factoryClassProvider = isSet(
|
|
2787
|
+
const boundSseEndpoint = registration.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
|
|
2788
|
+
const resolve = buildResolver(registration, instanceId, boundSseEndpoint, logger, moduleName);
|
|
2789
|
+
const factoryClassProvider = isSet(registration.useClass) ? [{ provide: FACTORY_TOKEN, useClass: registration.useClass }] : [];
|
|
2754
2790
|
const { providers: transportProviders, controllers } = wiring.buildAsync({
|
|
2755
|
-
mode:
|
|
2791
|
+
mode: registration.transport,
|
|
2756
2792
|
sseEndpoint: boundSseEndpoint
|
|
2757
2793
|
});
|
|
2758
2794
|
return {
|
|
2759
2795
|
module: moduleClass,
|
|
2760
|
-
imports:
|
|
2796
|
+
imports: registration.imports ?? [],
|
|
2761
2797
|
controllers,
|
|
2762
2798
|
providers: [
|
|
2763
2799
|
...factoryClassProvider,
|
|
2764
|
-
buildOptionsProvider(
|
|
2800
|
+
buildOptionsProvider(registration, resolve, FACTORY_TOKEN),
|
|
2765
2801
|
...buildOptionDerivedProviders(logger, instanceId),
|
|
2766
2802
|
...SHARED_SERVICES,
|
|
2767
2803
|
...transportProviders,
|
|
2768
|
-
...
|
|
2804
|
+
...registration.extraProviders ?? []
|
|
2769
2805
|
],
|
|
2770
2806
|
exports: EXPORTED_TOKENS
|
|
2771
2807
|
};
|
|
@@ -479,7 +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.
|
|
482
|
+
* Applied on **both** transports. It receives a plain copy of the authentication
|
|
483
|
+
* result, not the authenticator's original object: the result's own enumerable
|
|
484
|
+
* properties and the `tenantId` as the library read it, which counts when an accessor
|
|
485
|
+
* on the prototype supplies it and is missing when the tenant is absent or `null`.
|
|
486
|
+
* The copy is its own object and is shallow: a resolver that assigns to one of its
|
|
487
|
+
* top-level properties changes nothing the library keeps, while `roles`, `rooms` and
|
|
488
|
+
* `metadata` are shared with the original, so a write inside them changes what the
|
|
489
|
+
* library keeps. `undefined` and
|
|
490
|
+
* `null` both mean "no opinion"
|
|
483
491
|
* and fall back to `auth.tenantId` rather than clearing it; to place a connection
|
|
484
492
|
* in no tenant, return a result without one from the authenticator. `null` is in
|
|
485
493
|
* the signature because the implementation accepts it and a type narrower than the
|
|
@@ -2305,8 +2313,8 @@ type LogFields = Readonly<Record<string, string | number | boolean>>;
|
|
|
2305
2313
|
* @param level - `warn` for what degrades service, `error` for what fails an operation.
|
|
2306
2314
|
* @param event - The stable code of the condition.
|
|
2307
2315
|
* @param message - Human text; the library's own wording, with no host-supplied value in it.
|
|
2308
|
-
* @param fields - Closed or numeric fields, built by the library. A key named `event
|
|
2309
|
-
* library's own value or dropped, and a field whose read throws, such as a getter, loses the line like any other
|
|
2316
|
+
* @param fields - Closed or numeric fields, built by the library. A key named `event` or `message` is replaced by the
|
|
2317
|
+
* library's own value, and one named `err`, `msg`, `level`, `time`, `pid`, `hostname`, `name`, `v`, `req` or `res` is dropped, and a field whose read throws, such as a getter, loses the line like any other
|
|
2310
2318
|
* throw while writing.
|
|
2311
2319
|
* @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
|
|
2312
2320
|
* as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
|
package/dist/internal/index.d.ts
CHANGED
|
@@ -479,7 +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.
|
|
482
|
+
* Applied on **both** transports. It receives a plain copy of the authentication
|
|
483
|
+
* result, not the authenticator's original object: the result's own enumerable
|
|
484
|
+
* properties and the `tenantId` as the library read it, which counts when an accessor
|
|
485
|
+
* on the prototype supplies it and is missing when the tenant is absent or `null`.
|
|
486
|
+
* The copy is its own object and is shallow: a resolver that assigns to one of its
|
|
487
|
+
* top-level properties changes nothing the library keeps, while `roles`, `rooms` and
|
|
488
|
+
* `metadata` are shared with the original, so a write inside them changes what the
|
|
489
|
+
* library keeps. `undefined` and
|
|
490
|
+
* `null` both mean "no opinion"
|
|
483
491
|
* and fall back to `auth.tenantId` rather than clearing it; to place a connection
|
|
484
492
|
* in no tenant, return a result without one from the authenticator. `null` is in
|
|
485
493
|
* the signature because the implementation accepts it and a type narrower than the
|
|
@@ -2305,8 +2313,8 @@ type LogFields = Readonly<Record<string, string | number | boolean>>;
|
|
|
2305
2313
|
* @param level - `warn` for what degrades service, `error` for what fails an operation.
|
|
2306
2314
|
* @param event - The stable code of the condition.
|
|
2307
2315
|
* @param message - Human text; the library's own wording, with no host-supplied value in it.
|
|
2308
|
-
* @param fields - Closed or numeric fields, built by the library. A key named `event
|
|
2309
|
-
* library's own value or dropped, and a field whose read throws, such as a getter, loses the line like any other
|
|
2316
|
+
* @param fields - Closed or numeric fields, built by the library. A key named `event` or `message` is replaced by the
|
|
2317
|
+
* library's own value, and one named `err`, `msg`, `level`, `time`, `pid`, `hostname`, `name`, `v`, `req` or `res` is dropped, and a field whose read throws, such as a getter, loses the line like any other
|
|
2310
2318
|
* throw while writing.
|
|
2311
2319
|
* @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
|
|
2312
2320
|
* as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
|
package/dist/internal/index.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
222
|
`${path} must be an object, received ${describeReceived(value)}`,
|
|
217
|
-
{ who }
|
|
223
|
+
cause === void 0 ? { who } : { who, cause: cause.error }
|
|
218
224
|
);
|
|
219
225
|
}
|
|
220
226
|
|
|
@@ -232,15 +238,17 @@ var HOOK_NAMES = [
|
|
|
232
238
|
"onDeliveryFailure"
|
|
233
239
|
];
|
|
234
240
|
var GROUP_NAMES = ["sse", "websocket", "reauthenticationPolicy"];
|
|
235
|
-
function refuse(path, expected, received) {
|
|
241
|
+
function refuse(path, expected, received, cause) {
|
|
236
242
|
throw realtimeError(
|
|
237
243
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
238
244
|
`options.${path} must be ${expected}, received ${describeReceived(received)}`,
|
|
239
|
-
{ who: "BymaxRealtimeModule" }
|
|
245
|
+
cause === void 0 ? { who: "BymaxRealtimeModule" } : { who: "BymaxRealtimeModule", cause: cause.error }
|
|
240
246
|
);
|
|
241
247
|
}
|
|
242
248
|
function assertObject(path, value) {
|
|
243
|
-
if (value
|
|
249
|
+
if (value === void 0) return;
|
|
250
|
+
const read = readPlainObject(value);
|
|
251
|
+
if (!read.plain) refuse(path, "an object", value, read.threw ? { error: read.error } : void 0);
|
|
244
252
|
}
|
|
245
253
|
function assertFunction(path, value) {
|
|
246
254
|
if (typeof value !== "function") refuse(path, "a function", value);
|
|
@@ -259,7 +267,9 @@ function assertSseEndpoint(path, value) {
|
|
|
259
267
|
if (/\s/.test(value)) refuse(path, "a string without whitespace", value);
|
|
260
268
|
}
|
|
261
269
|
function assertOptionsObject(value, who = "BymaxRealtimeModule") {
|
|
262
|
-
|
|
270
|
+
const read = readPlainObject(value);
|
|
271
|
+
if (!read.plain)
|
|
272
|
+
refuseObject(who, "options", value, read.threw ? { error: read.error } : void 0);
|
|
263
273
|
}
|
|
264
274
|
function validatePieces(options) {
|
|
265
275
|
for (const [name, functions] of Object.entries(REQUIRED_FUNCTIONS)) {
|
|
@@ -565,10 +575,22 @@ var REALTIME_LOG_EVENTS = [
|
|
|
565
575
|
"REALTIME_COMPOSITE_PARTIAL_FAILURE",
|
|
566
576
|
"REALTIME_SERVER_NOT_ATTACHED"
|
|
567
577
|
];
|
|
578
|
+
var RESERVED_KEYS = [
|
|
579
|
+
"err",
|
|
580
|
+
"msg",
|
|
581
|
+
"level",
|
|
582
|
+
"time",
|
|
583
|
+
"pid",
|
|
584
|
+
"hostname",
|
|
585
|
+
"name",
|
|
586
|
+
"v",
|
|
587
|
+
"req",
|
|
588
|
+
"res"
|
|
589
|
+
];
|
|
568
590
|
function logEvent(logger, level, event, message, fields = {}, error) {
|
|
569
591
|
try {
|
|
570
592
|
const line = { ...fields, event, message };
|
|
571
|
-
delete line[
|
|
593
|
+
for (const key of RESERVED_KEYS) delete line[key];
|
|
572
594
|
if (error !== void 0) line["err"] = error;
|
|
573
595
|
logger[level](line);
|
|
574
596
|
} catch {
|
|
@@ -860,7 +882,7 @@ function isBlank(value) {
|
|
|
860
882
|
function resolveAuthTenant(options, auth) {
|
|
861
883
|
const { tenantId: own, ...rest } = auth;
|
|
862
884
|
const resolved = options.tenantResolver?.(
|
|
863
|
-
own === void 0 || own === null ? rest : { ...rest, tenantId: own }
|
|
885
|
+
own === void 0 || own === null ? { ...rest } : { ...rest, tenantId: own }
|
|
864
886
|
) ?? own;
|
|
865
887
|
if (resolved === void 0 || resolved === null) return rest;
|
|
866
888
|
return { ...rest, tenantId: resolved };
|
|
@@ -2681,7 +2703,7 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
|
|
|
2681
2703
|
if (isSet(asyncOptions.useFactory)) {
|
|
2682
2704
|
return {
|
|
2683
2705
|
provide: REALTIME_OPTIONS_TOKEN,
|
|
2684
|
-
useFactory: async (...args) => resolve(await awaitHostResult(asyncOptions.useFactory(...args)), "useFactory"),
|
|
2706
|
+
useFactory: async (...args) => resolve((await awaitHostResult(asyncOptions.useFactory(...args))).value, "useFactory"),
|
|
2685
2707
|
inject: [...asyncOptions.inject ?? []]
|
|
2686
2708
|
};
|
|
2687
2709
|
}
|
|
@@ -2699,7 +2721,7 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
|
|
|
2699
2721
|
);
|
|
2700
2722
|
}
|
|
2701
2723
|
return resolve(
|
|
2702
|
-
await awaitHostResult(create.call(factory)),
|
|
2724
|
+
(await awaitHostResult(create.call(factory))).value,
|
|
2703
2725
|
"createRealtimeOptions"
|
|
2704
2726
|
);
|
|
2705
2727
|
},
|
|
@@ -2736,34 +2758,48 @@ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, modul
|
|
|
2736
2758
|
return bindSseEndpoint(resolved, declaredEndpoint, boundSseEndpoint, moduleName);
|
|
2737
2759
|
};
|
|
2738
2760
|
}
|
|
2761
|
+
var copied = (value) => Array.isArray(value) ? [...value] : value;
|
|
2762
|
+
function readRegistration(registration) {
|
|
2763
|
+
return guardHostReads("the registration", () => ({
|
|
2764
|
+
transport: registration.transport,
|
|
2765
|
+
sseEndpoint: registration.sseEndpoint,
|
|
2766
|
+
useFactory: registration.useFactory,
|
|
2767
|
+
useClass: registration.useClass,
|
|
2768
|
+
useExisting: registration.useExisting,
|
|
2769
|
+
inject: copied(registration.inject),
|
|
2770
|
+
imports: copied(registration.imports),
|
|
2771
|
+
extraProviders: copied(registration.extraProviders)
|
|
2772
|
+
}));
|
|
2773
|
+
}
|
|
2739
2774
|
function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
2740
2775
|
const moduleName = moduleClass.name;
|
|
2741
2776
|
assertOptionsObject(asyncOptions, moduleName);
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2777
|
+
const registration = readRegistration(asyncOptions);
|
|
2778
|
+
assertOneFactoryPattern(registration, moduleName);
|
|
2779
|
+
assertModeSupported(wiring, registration.transport, moduleName);
|
|
2780
|
+
assertSseEndpoint("sseEndpoint", registration.sseEndpoint);
|
|
2781
|
+
assertSseEndpointApplies(registration, moduleName);
|
|
2782
|
+
assertExtraProviders(registration.extraProviders);
|
|
2747
2783
|
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
2748
2784
|
const instanceId = randomUUID();
|
|
2749
|
-
const boundSseEndpoint =
|
|
2750
|
-
const resolve = buildResolver(
|
|
2751
|
-
const factoryClassProvider = isSet(
|
|
2785
|
+
const boundSseEndpoint = registration.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
|
|
2786
|
+
const resolve = buildResolver(registration, instanceId, boundSseEndpoint, logger, moduleName);
|
|
2787
|
+
const factoryClassProvider = isSet(registration.useClass) ? [{ provide: FACTORY_TOKEN, useClass: registration.useClass }] : [];
|
|
2752
2788
|
const { providers: transportProviders, controllers } = wiring.buildAsync({
|
|
2753
|
-
mode:
|
|
2789
|
+
mode: registration.transport,
|
|
2754
2790
|
sseEndpoint: boundSseEndpoint
|
|
2755
2791
|
});
|
|
2756
2792
|
return {
|
|
2757
2793
|
module: moduleClass,
|
|
2758
|
-
imports:
|
|
2794
|
+
imports: registration.imports ?? [],
|
|
2759
2795
|
controllers,
|
|
2760
2796
|
providers: [
|
|
2761
2797
|
...factoryClassProvider,
|
|
2762
|
-
buildOptionsProvider(
|
|
2798
|
+
buildOptionsProvider(registration, resolve, FACTORY_TOKEN),
|
|
2763
2799
|
...buildOptionDerivedProviders(logger, instanceId),
|
|
2764
2800
|
...SHARED_SERVICES,
|
|
2765
2801
|
...transportProviders,
|
|
2766
|
-
...
|
|
2802
|
+
...registration.extraProviders ?? []
|
|
2767
2803
|
],
|
|
2768
2804
|
exports: EXPORTED_TOKENS
|
|
2769
2805
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bymax-one/nest-realtime",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.24",
|
|
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",
|