@bymax-one/nest-realtime 1.1.2 → 1.2.1
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 +148 -1
- package/README.md +125 -14
- package/dist/internal/index.cjs +139 -18
- package/dist/internal/index.d.cts +196 -24
- package/dist/internal/index.d.ts +196 -24
- package/dist/internal/index.mjs +139 -20
- package/dist/websocket/index.cjs +59 -29
- package/dist/websocket/index.d.cts +21 -4
- package/dist/websocket/index.d.ts +21 -4
- package/dist/websocket/index.mjs +60 -30
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,151 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [1.2.1] - 2026-10-30
|
|
11
|
+
|
|
12
|
+
**This version carries two behavioural breaks, both under Security below.** An authenticator that
|
|
13
|
+
returns a blank identity is now refused, and `tenantResolver` now runs on WebSocket connections.
|
|
14
|
+
Neither is a compile error: both change what a running backend does, so read "⚠️ Apply to a consumer"
|
|
15
|
+
before upgrading. Each closes a defect in which connections shared one delivery bucket or
|
|
16
|
+
were routed to a tenant that differed by transport.
|
|
17
|
+
|
|
18
|
+
### Security
|
|
19
|
+
|
|
20
|
+
- **BREAKING (bootstrap-time): a blank identity is refused on both transports.** An authenticator
|
|
21
|
+
that returns `''` or a whitespace-only `userId`, or a present-but-blank `tenantId`, now fails the
|
|
22
|
+
connection. Such a value used to be indexed under an empty key and
|
|
23
|
+
joined to the room `user:` or `tenant:`, so every such connection shared one bucket and received
|
|
24
|
+
every emit addressed to it for the life of the subscription. An absent `tenantId` stays valid and
|
|
25
|
+
means no tenant.
|
|
26
|
+
- **BREAKING (behavioural): `tenantResolver` now runs on WebSocket connections**, as it already
|
|
27
|
+
did on SSE. It was read on the SSE path and ignored on the WebSocket path, so one user opening
|
|
28
|
+
both transports could be routed to two different tenants by the same configuration. Resolution
|
|
29
|
+
goes through one shared function, so a connection carries the same tenant on either transport,
|
|
30
|
+
and `null` is treated as absent. An application that relied on the resolver not running on
|
|
31
|
+
WebSocket was relying on that defect.
|
|
32
|
+
- Reauthentication now covers WebSocket connections, which previously kept delivering after their
|
|
33
|
+
credentials were revoked. Its failure meta reports the real `conn.transport` instead of a fixed
|
|
34
|
+
`'sse'`.
|
|
35
|
+
|
|
36
|
+
### Changed
|
|
37
|
+
|
|
38
|
+
- `tenantResolver` may return `string | undefined | null`. Not breaking: a resolver typed
|
|
39
|
+
`() => string | undefined` still satisfies the wider signature.
|
|
40
|
+
|
|
41
|
+
### Fixed
|
|
42
|
+
|
|
43
|
+
- `RealtimeIoAdapter` renamed its private logger field from `logger` to `adapterLogger`, so it cannot
|
|
44
|
+
collide with a member of the same name on the `IoAdapter` base class; behaviour is unchanged.
|
|
45
|
+
|
|
46
|
+
### ⚠️ Apply to a consumer
|
|
47
|
+
|
|
48
|
+
- **Blank identity.** Make `authenticate()` return a non-empty `userId`, or `null` to reject the
|
|
49
|
+
connection. Omit `tenantId` for a connection that belongs to no tenant; do not return `''`. A
|
|
50
|
+
blank identity answers HTTP 500 with a generic body on SSE, and is disconnected on WebSocket;
|
|
51
|
+
both log the reason server-side, so a claim that can be blank (an unset `sub` or `tid`) shows up
|
|
52
|
+
as a failed connection rather than a shared room.
|
|
53
|
+
- **`tenantResolver` is honoured on WebSocket.** It now also receives WebSocket connections, and
|
|
54
|
+
it gets the `AuthenticationResult`, not the transport. A resolver that was only correct for SSE must be made
|
|
55
|
+
correct for both; returning `undefined` or `null` keeps `auth.tenantId`.
|
|
56
|
+
- **Reauthentication disconnects WebSocket connections.** They are now checked as well. If
|
|
57
|
+
`revalidate()` can return `false` for a credential that is still acceptable, those sockets are
|
|
58
|
+
now disconnected on the next cycle.
|
|
59
|
+
|
|
60
|
+
### Documentation
|
|
61
|
+
|
|
62
|
+
- The README separates the authenticator path from the `tenantResolver` path for an absent tenant,
|
|
63
|
+
and lists which reserved events the library emits and which it only reserves.
|
|
64
|
+
- `IPresenceStorage` is documented as a contract the application drives; the library does not
|
|
65
|
+
emit `presence:*` events.
|
|
66
|
+
- `SECURITY.md` states that only the latest minor line (1.2.x) receives security fixes; its table listed
|
|
67
|
+
`0.1.x`.
|
|
68
|
+
- The architecture notes, the auth patterns and the nest-auth bridge example match the code: `authorization`
|
|
69
|
+
is dropped on SSE, `auth.token` and `auth.ticket` reach the authenticator through the header and
|
|
70
|
+
`ctx.query.ticket`, `RealtimeIoAdapter` is imported from `/websocket`, and `cacheTtlMs` only matters when it
|
|
71
|
+
exceeds `intervalSeconds`.
|
|
72
|
+
|
|
73
|
+
## [1.2.0] - 2026-08-29
|
|
74
|
+
|
|
75
|
+
**Shipped as a minor, and two entries below are strictly speaking breaking.** Both are called
|
|
76
|
+
out as such rather than hidden: removing the `service` option is a compile error for anyone who
|
|
77
|
+
passed it, and the new required key on `ConnectionEventMeta` is a compile error for anyone who
|
|
78
|
+
*constructs* one. Neither changes runtime behaviour for any working configuration — `service`
|
|
79
|
+
was never read by anything, and reading the meta (what a hook does) is unaffected. The precedent
|
|
80
|
+
is 1.1.1, which added a required `roles` key to the same type and shipped as a patch. The third
|
|
81
|
+
item, the new bootstrap throw on a disagreeing SSE endpoint, replaces a silent misconfiguration
|
|
82
|
+
with a loud one: an application it stops was already serving a route other than the one it
|
|
83
|
+
configured.
|
|
84
|
+
|
|
85
|
+
### Changed
|
|
86
|
+
|
|
87
|
+
- **BREAKING: `forRootAsync` binds the SSE route from the registration, and no longer ignores
|
|
88
|
+
the endpoint it was given.** `sse.endpoint` coming back from the factory could never move the
|
|
89
|
+
route — controllers are registered at decoration time, long before a factory runs — so the
|
|
90
|
+
async path bound a hardcoded `/events` and discarded the configured value in silence. The
|
|
91
|
+
README said the endpoint was "configurable via `sse.endpoint`" with no caveat, so a consumer
|
|
92
|
+
reading it would document, monitor and point a client at a path that did not exist. Found
|
|
93
|
+
while answering a consumer's question about documenting the SSE endpoint in OpenAPI, not by a
|
|
94
|
+
test: every gate was green, because nothing asserted the two agreed.
|
|
95
|
+
|
|
96
|
+
The route is now declared as `sseEndpoint` on the `forRootAsync` options, next to `transport`
|
|
97
|
+
and for the same reason. **The default is unchanged (`/events`)**, so an application that
|
|
98
|
+
never set an endpoint keeps the route it has. Two behaviours change:
|
|
99
|
+
|
|
100
|
+
- A factory that resolves an `sse.endpoint` disagreeing with the bound route now **throws at
|
|
101
|
+
bootstrap** instead of serving a different path than the one configured. Comparison is on
|
|
102
|
+
the normalized path, since `@Sse()` resolves `events` and `/events` identically.
|
|
103
|
+
- `REALTIME_OPTIONS_TOKEN` now reports the endpoint that was actually bound. It previously
|
|
104
|
+
carried the `forRoot` default (`/realtime/sse`) while the route was `/events`, so anything
|
|
105
|
+
reading the configuration back — a health check, an OpenAPI document — was told the wrong
|
|
106
|
+
path.
|
|
107
|
+
|
|
108
|
+
`sseEndpoint` on a `transport: 'websocket'` registration is rejected outright: that mode
|
|
109
|
+
registers no SSE controller, so the option could only be decorative, which is the failure
|
|
110
|
+
this option exists to remove.
|
|
111
|
+
|
|
112
|
+
- **BREAKING: the `service` module option is removed.** It was accepted by the type and read
|
|
113
|
+
nowhere — no reference in `src/` outside its own declaration, and none in the built bundle.
|
|
114
|
+
The README claimed it "identifies the emitting service in event metadata", but `RealtimeEvent`
|
|
115
|
+
carries `id`, `type` and `data` and nothing else, so passing it was inert. Removed rather than
|
|
116
|
+
implemented: putting a service name on every event changes the wire shape for every client to
|
|
117
|
+
serve a need nobody has stated. Consumers passing it should delete the key; nothing else
|
|
118
|
+
changes, because nothing ever read it.
|
|
119
|
+
|
|
120
|
+
### Fixed
|
|
121
|
+
|
|
122
|
+
- **`AuthenticationResult.metadata` now reaches the lifecycle hooks.** The field was documented
|
|
123
|
+
as "free-form extras for downstream code" and was dropped at the boundary: `ConnectionRecord`
|
|
124
|
+
narrowed `originalAuth` to `userId`/`tenantId`/`roles`, and `ConnectionEventMeta` carried no
|
|
125
|
+
bag at all. It is now threaded through all five meta construction sites — SSE and WebSocket
|
|
126
|
+
`onConnect`/`onDisconnect` plus `onReauthenticationFailed` — and handed back to `revalidate`
|
|
127
|
+
as part of the original result.
|
|
128
|
+
|
|
129
|
+
This closes a real gap rather than a cosmetic one. `authenticate` sees the request headers but
|
|
130
|
+
has no `connectionId` yet (the connection does not exist), and the hooks have the
|
|
131
|
+
`connectionId` but never see the headers, so there was no way to correlate a connection with
|
|
132
|
+
anything read off the handshake — a `traceparent`, an `x-request-id`. `metadata` is that
|
|
133
|
+
channel, and it is the reason the field was declared in the first place.
|
|
134
|
+
|
|
135
|
+
**This adds a required key** to `ConnectionEventMeta`, exactly as `roles` did in 1.1.1.
|
|
136
|
+
Reading the meta is unaffected, which is what a hook does; code that *constructs* one
|
|
137
|
+
(typically a test fixture) must now supply `metadata`. `undefined` stays meaningful — an
|
|
138
|
+
authenticator that returns no bag is not one that returns an empty object. Like `roles`, it is
|
|
139
|
+
a connect-time snapshot that `revalidate` does not refresh, and the library never reads a key.
|
|
140
|
+
|
|
141
|
+
### Documentation
|
|
142
|
+
|
|
143
|
+
- The configuration table dropped the `service` row, and the `forRootAsync` endpoint rule is
|
|
144
|
+
documented where the endpoint is configured rather than left to be discovered at runtime.
|
|
145
|
+
- The Contracts section gains a subsection on carrying handshake context into the hooks through
|
|
146
|
+
`metadata`, with the tracing example that motivated it.
|
|
147
|
+
|
|
148
|
+
### Internal
|
|
149
|
+
|
|
150
|
+
- `normalizeEndpointPath` extracted from `createSseController`, which is now one of two callers:
|
|
151
|
+
binding an endpoint and comparing two endpoints have to agree on what a path means.
|
|
152
|
+
|
|
8
153
|
## [1.1.2] - 2026-08-21
|
|
9
154
|
|
|
10
155
|
**Documentation-only.** `dist/` is byte-identical to `1.1.1` — verified by diffing the
|
|
@@ -323,7 +468,9 @@ First published release.
|
|
|
323
468
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
324
469
|
asked about NestJS and never put the same question to the other ten peers.
|
|
325
470
|
|
|
326
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.1
|
|
471
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.1...HEAD
|
|
472
|
+
[1.2.1]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...v1.2.1
|
|
473
|
+
[1.2.0]: https://github.com/bymaxone/nest-realtime/compare/v1.1.2...v1.2.0
|
|
327
474
|
[1.1.2]: https://github.com/bymaxone/nest-realtime/compare/v1.1.1...v1.1.2
|
|
328
475
|
[1.1.1]: https://github.com/bymaxone/nest-realtime/compare/v1.1.0...v1.1.1
|
|
329
476
|
[1.1.0]: https://github.com/bymaxone/nest-realtime/compare/v1.0.6...v1.1.0
|
package/README.md
CHANGED
|
@@ -74,13 +74,13 @@ pnpm add @bymax-one/nest-realtime
|
|
|
74
74
|
- ✅ **Offline queue** — `IOfflineQueueStorage` holds events for absent users and flushes them on reconnect
|
|
75
75
|
- ✅ **Replay buffer** — per-user ring buffer answers `Last-Event-ID` after a dropped SSE stream
|
|
76
76
|
- ✅ **FIFO connection limits** — the oldest connection is evicted, so a new tab never gets a 429
|
|
77
|
-
- ✅ **Presence** — optional `IPresenceStorage`
|
|
77
|
+
- ✅ **Presence contract** — optional `IPresenceStorage` seam and `usePresence()` hook; the library never calls the storage or emits `presence:*` itself, so your application does both
|
|
78
78
|
|
|
79
79
|
### 🧩 Developer Experience
|
|
80
80
|
|
|
81
81
|
- ✅ **4 subpath exports** — server, WebSocket, shared types, and React; tree-shakeable, ESM + CJS dual output
|
|
82
82
|
- ✅ **Dynamic module** — `forRoot()` and `forRootAsync()` with `useFactory` / `useClass` / `useExisting`
|
|
83
|
-
- ✅ **Strict TypeScript, zero `any`** — `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes`
|
|
83
|
+
- ✅ **Strict TypeScript, zero `any`** — `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` enabled
|
|
84
84
|
- ✅ **Horizontal scaling** — `IRealtimePubSub` for SSE fan-out, `@socket.io/redis-adapter` for WebSocket
|
|
85
85
|
- ✅ **Bundle gate in CI** — the SSE-only React bundle is measured on every build and fails over budget
|
|
86
86
|
|
|
@@ -305,12 +305,11 @@ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `
|
|
|
305
305
|
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
|
|
306
306
|
| **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
|
|
307
307
|
| **authenticator** | `IConnectionAuthenticator` | — (**required**) |
|
|
308
|
-
| **
|
|
309
|
-
| **tenantResolver** | `(auth) => string \| undefined` — derives `tenantId` from the auth result | `auth.tenantId` |
|
|
308
|
+
| **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
|
|
310
309
|
| **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed` (fire-and-forget) | — |
|
|
311
310
|
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
|
|
312
311
|
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
|
|
313
|
-
| **presence** | `IPresenceStorage` —
|
|
312
|
+
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
|
|
314
313
|
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `maxConnectionsPerUser`, `emitConnectionEvent` | `/realtime/sse`, `30000`, `100`, `5`, `true` |
|
|
315
314
|
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults) |
|
|
316
315
|
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs` | `300`, `'disconnect'`, `60000` |
|
|
@@ -318,6 +317,25 @@ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `
|
|
|
318
317
|
> [!NOTE]
|
|
319
318
|
> `websocket.maxConnectionsPerUser` is **opt-in** and unlimited unless set to a positive number, while `sse.maxConnectionsPerUser` defaults to `5`. The two transports differ here on purpose: an SSE stream holds an HTTP connection open, a Socket.IO client multiplexes.
|
|
320
319
|
|
|
320
|
+
> [!IMPORTANT]
|
|
321
|
+
> **`forRootAsync` takes the SSE route on the registration, not from the factory.** NestJS
|
|
322
|
+
> registers controllers at decoration time, before any factory has run, so `sse.endpoint`
|
|
323
|
+
> cannot move the route there. Declare it as `sseEndpoint` alongside `transport`:
|
|
324
|
+
>
|
|
325
|
+
> ```typescript
|
|
326
|
+
> BymaxRealtimeModule.forRootAsync({
|
|
327
|
+
> transport: 'sse',
|
|
328
|
+
> sseEndpoint: '/realtime/sse', // defaults to '/events'
|
|
329
|
+
> inject: [ConfigService],
|
|
330
|
+
> useFactory: (cfg: ConfigService) => ({ transport: 'sse', authenticator: ... }),
|
|
331
|
+
> })
|
|
332
|
+
> ```
|
|
333
|
+
>
|
|
334
|
+
> The async default is `'/events'`, not the `forRoot` default of `'/realtime/sse'`. A factory
|
|
335
|
+
> that returns a different `sse.endpoint` is **rejected at bootstrap** rather than ignored, and
|
|
336
|
+
> `REALTIME_OPTIONS_TOKEN` reports the route that was actually bound — so a health check or an
|
|
337
|
+
> OpenAPI document built from the options names the path that exists.
|
|
338
|
+
|
|
321
339
|
The full reference, including `forRootAsync` with `useFactory` / `useClass` / `useExisting`, is in [docs/technical_specification.md](./docs/technical_specification.md) §4.
|
|
322
340
|
|
|
323
341
|
---
|
|
@@ -528,6 +546,77 @@ Read-side view of live connections — useful for admin endpoints and metrics.
|
|
|
528
546
|
|
|
529
547
|
Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
|
|
530
548
|
|
|
549
|
+
#### Identity must be present or absent, never blank
|
|
550
|
+
|
|
551
|
+
`userId` must be a non-empty string, and `tenantId` must be either absent or a non-empty
|
|
552
|
+
string. A connection whose authenticator — or whose `tenantResolver` — yields a blank one is
|
|
553
|
+
**refused at bootstrap** rather than registered.
|
|
554
|
+
|
|
555
|
+
The reason is that blank is not missing. `userId` and `tenantId` key the connection registry
|
|
556
|
+
and compose the `user:` and `tenant:` rooms, so every connection carrying `''` lands under the
|
|
557
|
+
same key and joins the same room; a later emit to that key reaches all of them. On a long-lived
|
|
558
|
+
subscription that is not one wrong response but a stream that keeps delivering.
|
|
559
|
+
|
|
560
|
+
To place a connection in no tenant, the **authenticator omits `tenantId`** — that is indexed
|
|
561
|
+
under none and joins no tenant room, which an empty string is not. Whitespace counts as blank:
|
|
562
|
+
`' '` composes `user: ` just as `''` does.
|
|
563
|
+
|
|
564
|
+
Omission is the form to write, because it is the only one that compiles everywhere.
|
|
565
|
+
`AuthenticationResult` declares `tenantId?: string`; the runtime accepts an explicit `undefined`
|
|
566
|
+
or `null` too — an untyped claim spread into the result produces them routinely — but whether
|
|
567
|
+
either *type-checks* depends on the consuming project's `tsconfig`, which the published
|
|
568
|
+
declarations do not control:
|
|
569
|
+
|
|
570
|
+
| consumer's `tsconfig` | `tenantId: undefined` | `tenantId: null` |
|
|
571
|
+
| ----------------------------------------- | --------------------- | ---------------- |
|
|
572
|
+
| `strict` + `exactOptionalPropertyTypes` | `TS2375` | `TS2322` |
|
|
573
|
+
| `strict`, no `exactOptionalPropertyTypes` | compiles | `TS2322` |
|
|
574
|
+
| no `strictNullChecks` | compiles | compiles |
|
|
575
|
+
|
|
576
|
+
Omitting the key is correct in all three.
|
|
577
|
+
|
|
578
|
+
`tenantResolver` cannot clear a tenant, and this is the one asymmetry worth reading twice.
|
|
579
|
+
Resolution is `tenantResolver?.(auth) ?? auth.tenantId`, so a resolver returning `undefined` or
|
|
580
|
+
`null` means *no opinion* and falls back to the tenant the authenticator supplied. A resolver
|
|
581
|
+
written to place a connection in no tenant by returning `null` leaves it in `auth.tenantId`'s
|
|
582
|
+
room instead, still receiving that tenant's events. Decide the absent case in the
|
|
583
|
+
authenticator, where absence is what it looks like.
|
|
584
|
+
|
|
585
|
+
A blank identity surfaces as a server fault rather than a `401`, because the client's
|
|
586
|
+
credentials were accepted and the fault is in the authenticator. Return `null` to reject a
|
|
587
|
+
client.
|
|
588
|
+
|
|
589
|
+
#### Carrying handshake context into the hooks
|
|
590
|
+
|
|
591
|
+
`AuthenticationResult.metadata` is a free-form bag the library carries verbatim: it reaches
|
|
592
|
+
`ConnectionEventMeta.metadata` in the three hooks that receive that type — `onConnect`,
|
|
593
|
+
`onDisconnect` and `onReauthenticationFailed` — and is handed back to `revalidate` as part of
|
|
594
|
+
the original result. It is the only channel that crosses that boundary — `authenticate` sees
|
|
595
|
+
the request headers but no `connectionId` yet, and those hooks see the `connectionId` but not
|
|
596
|
+
the headers.
|
|
597
|
+
|
|
598
|
+
`onError` is the exception and takes a narrower payload (`connectionId?`, `error`, `transport`):
|
|
599
|
+
it can fire before authentication resolves, so there may be no connection to describe, which is
|
|
600
|
+
also why its `connectionId` is optional. It carries neither `roles` nor `metadata`.
|
|
601
|
+
|
|
602
|
+
```typescript
|
|
603
|
+
class TracingAuthenticator implements IConnectionAuthenticator {
|
|
604
|
+
async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
|
|
605
|
+
const claims = await verify(ctx.cookies['access_token'])
|
|
606
|
+
if (!claims) return null
|
|
607
|
+
// ctx.headers keys are lowercased; this is the only place the headers are visible.
|
|
608
|
+
return { userId: claims.sub, metadata: { traceparent: ctx.headers['traceparent'] } }
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const hooks: IConnectionLifecycleHooks = {
|
|
613
|
+
onConnect: (meta) => tracer.recordConnection(meta.connectionId, meta.metadata?.['traceparent']),
|
|
614
|
+
}
|
|
615
|
+
```
|
|
616
|
+
|
|
617
|
+
Like `roles`, it is a **connect-time snapshot**: a `revalidate` that keeps the connection alive
|
|
618
|
+
does not refresh it. The library never reads a key.
|
|
619
|
+
|
|
531
620
|
### Rooms
|
|
532
621
|
|
|
533
622
|
| Room ID | Used for | Auto-joined |
|
|
@@ -544,6 +633,21 @@ composeRoomId('TENANT', tenantId) // → "tenant:t_acme"
|
|
|
544
633
|
composeRoomId('RESOURCE', 'invoice', invoiceId) // → "resource:invoice:42"
|
|
545
634
|
```
|
|
546
635
|
|
|
636
|
+
`composeRoomId` joins its parts with `:` and escapes nothing, so a part must not contain `:`. The `encodeURIComponent` advice below holds for that `:` separator only, because it escapes `:` and leaves characters such as `-`, `.`, `_` and `~` alone.
|
|
637
|
+
`('a:b', 'c')` and `('a', 'b:c')` both give `resource:a:b:c` and land in the same room. When a
|
|
638
|
+
part comes from outside your code, encode it first:
|
|
639
|
+
`composeRoomId('RESOURCE', encodeURIComponent(type), encodeURIComponent(id))`.
|
|
640
|
+
|
|
641
|
+
A `resource:` room is not tenant-scoped: two tenants using the same type and id share it. When ids
|
|
642
|
+
are only unique within a tenant, pass the tenant as its own encoded part —
|
|
643
|
+
`composeRoomId('RESOURCE', 'invoice', encodeURIComponent(tenantId), encodeURIComponent(id))` —
|
|
644
|
+
because gluing them into one part with a separator that ids may contain, such as `-`, lets two
|
|
645
|
+
different pairs compose the same room.
|
|
646
|
+
|
|
647
|
+
Never pass client-supplied input to `joinRoom` or `emitToRoom` as a room id without checking that
|
|
648
|
+
it cannot start with the reserved `user:` or `tenant:` prefixes. The library does not guard them,
|
|
649
|
+
and joining `tenant:<other>` receives that tenant's events.
|
|
650
|
+
|
|
547
651
|
#### Role-scoped delivery
|
|
548
652
|
|
|
549
653
|
There is no `emitToRole`. Roles are the consumer's authorization vocabulary, not
|
|
@@ -643,16 +747,23 @@ const onConnect = joinRoleRoom({ get: () => ({ joinRoom }) }, 'admin', 'role:adm
|
|
|
643
747
|
|
|
644
748
|
### Reserved Events
|
|
645
749
|
|
|
646
|
-
|
|
750
|
+
These names belong to the library. Do not reuse them for application events.
|
|
751
|
+
|
|
752
|
+
**Emitted today**
|
|
753
|
+
|
|
754
|
+
| Event | Meaning |
|
|
755
|
+
| ------------------------------------ | ------------------------------------------------------- |
|
|
756
|
+
| `connection:established` | Handshake accepted (suppress via `emitConnectionEvent`) |
|
|
757
|
+
| `connection:reauthentication-failed` | Credentials no longer valid |
|
|
758
|
+
|
|
759
|
+
**Reserved, not emitted by the library.** An application may emit them itself; the library never does. The default SSE client subscribes to all of them except `error`. The browser dispatches a server-sent `error` event to the same handler as its own connection failures, so do not emit `error` over SSE: the client treats it as a dropped connection.
|
|
647
760
|
|
|
648
|
-
| Event | Meaning
|
|
649
|
-
| -------------------------------------- |
|
|
650
|
-
| `connection:
|
|
651
|
-
| `
|
|
652
|
-
| `
|
|
653
|
-
| `
|
|
654
|
-
| `error` | Transport-level error |
|
|
655
|
-
| `presence:online` / `presence:offline` | Presence changed (requires `IPresenceStorage`) |
|
|
761
|
+
| Event | Meaning |
|
|
762
|
+
| -------------------------------------- | -------------------------------------------------------------------- |
|
|
763
|
+
| `connection:credential-expiring` | Credential nearing expiry |
|
|
764
|
+
| `room:joined` / `room:left` | Room membership changed |
|
|
765
|
+
| `error` | Transport-level error |
|
|
766
|
+
| `presence:online` / `presence:offline` | Presence changed; emitted by your code, `IPresenceStorage` is a seam |
|
|
656
767
|
|
|
657
768
|
> [!NOTE]
|
|
658
769
|
> The SSE heartbeat is a `: keepalive` **comment line**, not a named event. It never appears in the `Last-Event-ID` id-space and never reaches a client listener.
|