@bymax-one/nest-realtime 1.1.1 → 1.2.0

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
@@ -5,6 +5,116 @@ 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
+ ## [1.2.0] - 2026-08-29
9
+
10
+ **Shipped as a minor, and two entries below are strictly speaking breaking.** Both are called
11
+ out as such rather than hidden: removing the `service` option is a compile error for anyone who
12
+ passed it, and the new required key on `ConnectionEventMeta` is a compile error for anyone who
13
+ *constructs* one. Neither changes runtime behaviour for any working configuration — `service`
14
+ was never read by anything, and reading the meta (what a hook does) is unaffected. The precedent
15
+ is 1.1.1, which added a required `roles` key to the same type and shipped as a patch. The third
16
+ item, the new bootstrap throw on a disagreeing SSE endpoint, replaces a silent misconfiguration
17
+ with a loud one: an application it stops was already serving a route other than the one it
18
+ configured.
19
+
20
+ ### Changed
21
+
22
+ - **BREAKING: `forRootAsync` binds the SSE route from the registration, and no longer ignores
23
+ the endpoint it was given.** `sse.endpoint` coming back from the factory could never move the
24
+ route — controllers are registered at decoration time, long before a factory runs — so the
25
+ async path bound a hardcoded `/events` and discarded the configured value in silence. The
26
+ README said the endpoint was "configurable via `sse.endpoint`" with no caveat, so a consumer
27
+ reading it would document, monitor and point a client at a path that did not exist. Found
28
+ while answering a consumer's question about documenting the SSE endpoint in OpenAPI, not by a
29
+ test: every gate was green, because nothing asserted the two agreed.
30
+
31
+ The route is now declared as `sseEndpoint` on the `forRootAsync` options, next to `transport`
32
+ and for the same reason. **The default is unchanged (`/events`)**, so an application that
33
+ never set an endpoint keeps the route it has. Two behaviours change:
34
+
35
+ - A factory that resolves an `sse.endpoint` disagreeing with the bound route now **throws at
36
+ bootstrap** instead of serving a different path than the one configured. Comparison is on
37
+ the normalized path, since `@Sse()` resolves `events` and `/events` identically.
38
+ - `REALTIME_OPTIONS_TOKEN` now reports the endpoint that was actually bound. It previously
39
+ carried the `forRoot` default (`/realtime/sse`) while the route was `/events`, so anything
40
+ reading the configuration back — a health check, an OpenAPI document — was told the wrong
41
+ path.
42
+
43
+ `sseEndpoint` on a `transport: 'websocket'` registration is rejected outright: that mode
44
+ registers no SSE controller, so the option could only be decorative, which is the failure
45
+ this option exists to remove.
46
+
47
+ - **BREAKING: the `service` module option is removed.** It was accepted by the type and read
48
+ nowhere — no reference in `src/` outside its own declaration, and none in the built bundle.
49
+ The README claimed it "identifies the emitting service in event metadata", but `RealtimeEvent`
50
+ carries `id`, `type` and `data` and nothing else, so passing it was inert. Removed rather than
51
+ implemented: putting a service name on every event changes the wire shape for every client to
52
+ serve a need nobody has stated. Consumers passing it should delete the key; nothing else
53
+ changes, because nothing ever read it.
54
+
55
+ ### Fixed
56
+
57
+ - **`AuthenticationResult.metadata` now reaches the lifecycle hooks.** The field was documented
58
+ as "free-form extras for downstream code" and was dropped at the boundary: `ConnectionRecord`
59
+ narrowed `originalAuth` to `userId`/`tenantId`/`roles`, and `ConnectionEventMeta` carried no
60
+ bag at all. It is now threaded through all five meta construction sites — SSE and WebSocket
61
+ `onConnect`/`onDisconnect` plus `onReauthenticationFailed` — and handed back to `revalidate`
62
+ as part of the original result.
63
+
64
+ This closes a real gap rather than a cosmetic one. `authenticate` sees the request headers but
65
+ has no `connectionId` yet (the connection does not exist), and the hooks have the
66
+ `connectionId` but never see the headers, so there was no way to correlate a connection with
67
+ anything read off the handshake — a `traceparent`, an `x-request-id`. `metadata` is that
68
+ channel, and it is the reason the field was declared in the first place.
69
+
70
+ **This adds a required key** to `ConnectionEventMeta`, exactly as `roles` did in 1.1.1.
71
+ Reading the meta is unaffected, which is what a hook does; code that *constructs* one
72
+ (typically a test fixture) must now supply `metadata`. `undefined` stays meaningful — an
73
+ authenticator that returns no bag is not one that returns an empty object. Like `roles`, it is
74
+ a connect-time snapshot that `revalidate` does not refresh, and the library never reads a key.
75
+
76
+ ### Documentation
77
+
78
+ - The configuration table dropped the `service` row, and the `forRootAsync` endpoint rule is
79
+ documented where the endpoint is configured rather than left to be discovered at runtime.
80
+ - The Contracts section gains a subsection on carrying handshake context into the hooks through
81
+ `metadata`, with the tracing example that motivated it.
82
+
83
+ ### Internal
84
+
85
+ - `normalizeEndpointPath` extracted from `createSseController`, which is now one of two callers:
86
+ binding an endpoint and comparing two endpoints have to agree on what a path means.
87
+
88
+ ## [1.1.2] - 2026-08-21
89
+
90
+ **Documentation-only.** `dist/` is byte-identical to `1.1.1` — verified by diffing the
91
+ build against the published tarball, not asserted. No runtime path, exported type or
92
+ public surface changed. The release exists because `README.md` ships inside the package
93
+ and renders on npm, so a documentation defect there reaches consumers exactly as a code
94
+ one does.
95
+
96
+ ### Documentation
97
+
98
+ - **The role-scoped room snippet led a careful consumer into a wall.** It called
99
+ `moduleRef.get()` inside the `onConnect` hook, which is correct and runs — and which
100
+ means unit-testing that hook requires faking `ModuleRef`, in practice
101
+ `as unknown as ModuleRef`. That is a suppression many codebases block outright, so the
102
+ documented pattern was unusable for anyone whose policy forbids the cast. Found by a
103
+ consumer adopting `1.1.1`, not by us; "it works" was true and was the reason it
104
+ survived review.
105
+
106
+ The README now also documents the testable shape: give the hook the two capabilities
107
+ it uses, `RoomJoiner` and `ServiceResolver`. `ModuleRef` and `RealtimeService` satisfy
108
+ them structurally, so production passes the real objects and a test passes plain ones,
109
+ with no cast at either end. Both snippets are compiled and executed by
110
+ `realtime.module.documented-patterns.spec.ts` rather than left as prose.
111
+
112
+ - **Role matching is exact membership.** `roles?.includes('admin')` on a
113
+ `readonly string[]` compares whole elements. Reaching for
114
+ `roles?.some((r) => r.includes('admin'))` — for case-insensitivity, say — admits
115
+ `administrator`, `admin-readonly` and `superadmin`. That failure is an authorization
116
+ leak, it fails open, and it appears only for role names nobody declared.
117
+
8
118
  ## [1.1.1] - 2026-08-21
9
119
 
10
120
  ### Added
@@ -20,7 +130,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
20
130
  and absent at disconnect would be a field that lies by omission exactly when a host cleans up.
21
131
 
22
132
  **This adds a required key.** Reading the meta is unaffected, which is what a hook does; code
23
- that *constructs* a `ConnectionEventMeta` (typically a test fixture) must now supply `roles`.
133
+ that _constructs_ a `ConnectionEventMeta` (typically a test fixture) must now supply `roles`.
24
134
  `undefined` stays meaningful for an authenticator that returns none.
25
135
 
26
136
  Roles are carried, never interpreted: there is deliberately no `emitToRole`. Indexing a
@@ -293,7 +403,9 @@ First published release.
293
403
  rather than by the manual sweep that raised the NestJS floors — that sweep
294
404
  asked about NestJS and never put the same question to the other ten peers.
295
405
 
296
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.1.1...HEAD
406
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.0...HEAD
407
+ [1.2.0]: https://github.com/bymaxone/nest-realtime/compare/v1.1.2...v1.2.0
408
+ [1.1.2]: https://github.com/bymaxone/nest-realtime/compare/v1.1.1...v1.1.2
297
409
  [1.1.1]: https://github.com/bymaxone/nest-realtime/compare/v1.1.0...v1.1.1
298
410
  [1.1.0]: https://github.com/bymaxone/nest-realtime/compare/v1.0.6...v1.1.0
299
411
  [1.0.6]: https://github.com/bymaxone/nest-realtime/compare/v1.0.5...v1.0.6
package/README.md CHANGED
@@ -305,7 +305,6 @@ 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
- | **service** | `name`, `version` — identifies the emitting service in event metadata | — |
309
308
  | **tenantResolver** | `(auth) => string \| undefined` — derives `tenantId` from the auth result | `auth.tenantId` |
310
309
  | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed` (fire-and-forget) | — |
311
310
  | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
@@ -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,37 @@ 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
+ #### Carrying handshake context into the hooks
550
+
551
+ `AuthenticationResult.metadata` is a free-form bag the library carries verbatim: it reaches
552
+ `ConnectionEventMeta.metadata` in the three hooks that receive that type — `onConnect`,
553
+ `onDisconnect` and `onReauthenticationFailed` — and is handed back to `revalidate` as part of
554
+ the original result. It is the only channel that crosses that boundary — `authenticate` sees
555
+ the request headers but no `connectionId` yet, and those hooks see the `connectionId` but not
556
+ the headers.
557
+
558
+ `onError` is the exception and takes a narrower payload (`connectionId?`, `error`, `transport`):
559
+ it can fire before authentication resolves, so there may be no connection to describe, which is
560
+ also why its `connectionId` is optional. It carries neither `roles` nor `metadata`.
561
+
562
+ ```typescript
563
+ class TracingAuthenticator implements IConnectionAuthenticator {
564
+ async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
565
+ const claims = await verify(ctx.cookies['access_token'])
566
+ if (!claims) return null
567
+ // ctx.headers keys are lowercased; this is the only place the headers are visible.
568
+ return { userId: claims.sub, metadata: { traceparent: ctx.headers['traceparent'] } }
569
+ }
570
+ }
571
+
572
+ const hooks: IConnectionLifecycleHooks = {
573
+ onConnect: (meta) => tracer.recordConnection(meta.connectionId, meta.metadata?.['traceparent']),
574
+ }
575
+ ```
576
+
577
+ Like `roles`, it is a **connect-time snapshot**: a `revalidate` that keeps the connection alive
578
+ does not refresh it. The library never reads a key.
579
+
531
580
  ### Rooms
532
581
 
533
582
  | Room ID | Used for | Auto-joined |
@@ -588,6 +637,59 @@ the connection alive does not refresh it. When a role can be revoked mid-session
588
637
  make `revalidate` return `false` so the connection is torn down and re-established
589
638
  with the new roles.
590
639
 
640
+ ##### Make the hook testable: depend on the capability, not the injector
641
+
642
+ The snippet above works, and it still walks a careful consumer into a wall: a
643
+ `moduleRef.get()` call inside the hook means unit-testing that hook requires
644
+ faking `ModuleRef`, which in practice means `as unknown as ModuleRef` — a
645
+ suppression many codebases block outright.
646
+
647
+ Give the hook the two capabilities it actually uses instead. `ModuleRef` and
648
+ `RealtimeService` satisfy these shapes **structurally**, so the module passes the
649
+ real objects and a test passes plain ones, with no cast at either end:
650
+
651
+ ```typescript
652
+ interface RoomJoiner {
653
+ joinRoom(connectionId: string, roomId: string): Promise<void>
654
+ }
655
+
656
+ interface ServiceResolver {
657
+ get(token: typeof RealtimeService): RoomJoiner
658
+ }
659
+
660
+ function joinRoleRoom(resolver: ServiceResolver, role: string, roomId: string) {
661
+ return async (meta: ConnectionEventMeta): Promise<void> => {
662
+ if (!meta.roles?.includes(role)) return
663
+ await resolver.get(RealtimeService).joinRoom(meta.connectionId, roomId)
664
+ }
665
+ }
666
+ ```
667
+
668
+ Wire it with the real injector:
669
+
670
+ ```typescript
671
+ inject: [ModuleRef],
672
+ useFactory: (moduleRef: ModuleRef) => ({
673
+ transport: 'sse' as const,
674
+ authenticator: new CookieAuthenticator(),
675
+ hooks: { onConnect: joinRoleRoom(moduleRef, 'admin', 'role:admin') },
676
+ }),
677
+ ```
678
+
679
+ and test it without booting NestJS:
680
+
681
+ ```typescript
682
+ const joinRoom = jest.fn()
683
+ const onConnect = joinRoleRoom({ get: () => ({ joinRoom }) }, 'admin', 'role:admin')
684
+ ```
685
+
686
+ > [!NOTE]
687
+ > Match roles by exact membership. `roles?.includes('admin')` on a `readonly string[]`
688
+ > compares whole elements; reaching for `roles?.some((r) => r.includes('admin'))` —
689
+ > for case-insensitivity, say — admits `administrator`, `admin-readonly` and
690
+ > `superadmin`. That failure is an authorization leak, it fails open, and it only
691
+ > shows up for role names nobody declared.
692
+
591
693
  ### Reserved Events
592
694
 
593
695
  Emitted by the library. Do not reuse these names for application events.
@@ -504,7 +504,8 @@ exports.SseTransport = class SseTransport {
504
504
  originalAuth: {
505
505
  userId: params.auth.userId,
506
506
  tenantId: params.auth.tenantId,
507
- roles: params.auth.roles
507
+ roles: params.auth.roles,
508
+ metadata: params.auth.metadata
508
509
  }
509
510
  };
510
511
  this.connections.register(record);
@@ -526,6 +527,7 @@ exports.SseTransport = class SseTransport {
526
527
  userId: record.userId,
527
528
  tenantId: record.tenantId,
528
529
  roles: record.originalAuth.roles,
530
+ metadata: record.originalAuth.metadata,
529
531
  transport: "sse",
530
532
  ip: record.ip,
531
533
  userAgent: record.userAgent,
@@ -763,6 +765,7 @@ function buildMeta(record) {
763
765
  userId: record.userId,
764
766
  tenantId: record.tenantId,
765
767
  roles: record.originalAuth.roles,
768
+ metadata: record.originalAuth.metadata,
766
769
  transport: "sse",
767
770
  ip: record.ip,
768
771
  userAgent: record.userAgent,
@@ -929,9 +932,14 @@ exports.SseSubscriptionHandler = __decorateClass([
929
932
  __decorateParam(4, common.Inject(exports.OfflineQueueDeliveryService))
930
933
  ], exports.SseSubscriptionHandler);
931
934
 
935
+ // src/server/utils/normalize-endpoint-path.ts
936
+ function normalizeEndpointPath(endpoint) {
937
+ return endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
938
+ }
939
+
932
940
  // src/server/factories/sse-controller.factory.ts
933
941
  function createSseController(endpoint) {
934
- const ssePath = endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
942
+ const ssePath = normalizeEndpointPath(endpoint);
935
943
  let DynamicSseController = class {
936
944
  // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
937
945
  // not emit `design:paramtypes` decorator metadata, so constructor params must
@@ -1108,7 +1116,8 @@ exports.ReauthenticationService = class ReauthenticationService {
1108
1116
  const originalAuth = {
1109
1117
  userId: conn.originalAuth.userId,
1110
1118
  ...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
1111
- ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {}
1119
+ ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {},
1120
+ ...conn.originalAuth.metadata !== void 0 ? { metadata: conn.originalAuth.metadata } : {}
1112
1121
  };
1113
1122
  const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
1114
1123
  if (rawResult === true) {
@@ -1138,6 +1147,7 @@ exports.ReauthenticationService = class ReauthenticationService {
1138
1147
  userId: conn.userId,
1139
1148
  tenantId: conn.tenantId,
1140
1149
  roles: conn.originalAuth.roles,
1150
+ metadata: conn.originalAuth.metadata,
1141
1151
  transport: "sse",
1142
1152
  ip: conn.ip,
1143
1153
  userAgent: conn.userAgent,
@@ -1160,6 +1170,7 @@ exports.ReauthenticationService = __decorateClass([
1160
1170
  ], exports.ReauthenticationService);
1161
1171
 
1162
1172
  // src/server/composition/realtime-module.factory.ts
1173
+ var DEFAULT_ASYNC_SSE_ENDPOINT = "/events";
1163
1174
  var EXPORTED_TOKENS = [
1164
1175
  exports.RealtimeService,
1165
1176
  exports.ConnectionRegistry,
@@ -1224,6 +1235,20 @@ function composeForRoot(moduleClass, wiring, logger, options) {
1224
1235
  exports: EXPORTED_TOKENS
1225
1236
  };
1226
1237
  }
1238
+ function assertSseEndpointApplies(asyncOptions, moduleName) {
1239
+ if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
1240
+ throw new Error(
1241
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`
1242
+ );
1243
+ }
1244
+ function bindSseEndpoint(resolved, declared, bound, moduleName) {
1245
+ if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
1246
+ throw new Error(
1247
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`
1248
+ );
1249
+ }
1250
+ return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
1251
+ }
1227
1252
  function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
1228
1253
  if (!raw) {
1229
1254
  throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
@@ -1251,9 +1276,22 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1251
1276
  );
1252
1277
  }
1253
1278
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
1279
+ assertSseEndpointApplies(asyncOptions, moduleName);
1254
1280
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
1255
1281
  const instanceId = crypto.randomUUID();
1256
- const resolve = (raw, source) => resolveAsyncOptions(raw, asyncOptions.transport, instanceId, source, logger, moduleName);
1282
+ const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
1283
+ const resolve = (raw, source) => {
1284
+ const resolved = resolveAsyncOptions(
1285
+ raw,
1286
+ asyncOptions.transport,
1287
+ instanceId,
1288
+ source,
1289
+ logger,
1290
+ moduleName
1291
+ );
1292
+ if (asyncOptions.transport === "websocket") return resolved;
1293
+ return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
1294
+ };
1257
1295
  const resolvedOptionsProvider = asyncOptions.useFactory ? {
1258
1296
  provide: REALTIME_OPTIONS_TOKEN,
1259
1297
  useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
@@ -1268,7 +1306,10 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1268
1306
  };
1269
1307
  const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
1270
1308
  const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
1271
- const { providers: transportProviders, controllers } = wiring.buildAsync(asyncOptions.transport);
1309
+ const { providers: transportProviders, controllers } = wiring.buildAsync({
1310
+ mode: asyncOptions.transport,
1311
+ sseEndpoint: boundSseEndpoint
1312
+ });
1272
1313
  return {
1273
1314
  module: moduleClass,
1274
1315
  imports: asyncOptions.imports ?? [],
@@ -1369,7 +1410,6 @@ exports.RealtimePubSubSubscriber = __decorateClass([
1369
1410
  ], exports.RealtimePubSubSubscriber);
1370
1411
 
1371
1412
  // src/server/composition/sse-wiring.ts
1372
- var DEFAULT_ASYNC_ENDPOINT = "/events";
1373
1413
  var sseWiring = {
1374
1414
  modes: ["sse"],
1375
1415
  build(resolved) {
@@ -1384,7 +1424,7 @@ var sseWiring = {
1384
1424
  gateways: []
1385
1425
  };
1386
1426
  },
1387
- buildAsync() {
1427
+ buildAsync({ sseEndpoint }) {
1388
1428
  return {
1389
1429
  providers: [
1390
1430
  exports.SseTransport,
@@ -1392,7 +1432,7 @@ var sseWiring = {
1392
1432
  exports.RealtimePubSubSubscriber,
1393
1433
  { provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.SseTransport }
1394
1434
  ],
1395
- controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
1435
+ controllers: [createSseController(sseEndpoint)]
1396
1436
  };
1397
1437
  }
1398
1438
  };
@@ -1420,9 +1460,12 @@ exports.BymaxRealtimeModule = class BymaxRealtimeModule {
1420
1460
  * configuration rejects at bootstrap and the application fails to start with
1421
1461
  * a clear error.
1422
1462
  *
1423
- * Controllers are registered at decoration time, so this path binds the SSE
1424
- * controller to the default endpoint `/events`. A non-default endpoint needs
1425
- * `forRoot` with pre-resolved options.
1463
+ * Controllers are registered at decoration time, so the SSE route comes from
1464
+ * `sseEndpoint` on the registration rather than from the `sse.endpoint` the
1465
+ * factory resolves — the factory has not run yet when the controller is
1466
+ * built. It defaults to `/events`, and a factory that resolves a disagreeing
1467
+ * `sse.endpoint` is rejected at bootstrap rather than silently served on
1468
+ * another path.
1426
1469
  *
1427
1470
  * @throws when no factory pattern is given, more than one is, or the factory
1428
1471
  * resolves a transport other than `'sse'`.
@@ -1430,6 +1473,7 @@ exports.BymaxRealtimeModule = class BymaxRealtimeModule {
1430
1473
  * ```ts
1431
1474
  * BymaxRealtimeModule.forRootAsync({
1432
1475
  * transport: 'sse',
1476
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
1433
1477
  * imports: [ConfigModule],
1434
1478
  * inject: [ConfigService],
1435
1479
  * useFactory: (cfg: ConfigService) => ({
@@ -72,7 +72,16 @@ interface AuthenticationResult {
72
72
  readonly userId: string;
73
73
  readonly tenantId?: string;
74
74
  readonly roles?: readonly string[];
75
- /** Free-form extras for downstream code (e.g. feature flags, plan tier). */
75
+ /**
76
+ * Free-form extras for downstream code (e.g. feature flags, plan tier, a
77
+ * correlation id read off the handshake headers).
78
+ *
79
+ * Carried verbatim — the library never reads a key. It reaches
80
+ * `ConnectionEventMeta.metadata` in the three hooks that receive that type —
81
+ * `onConnect`, `onDisconnect` and `onReauthenticationFailed` — and is handed
82
+ * back to `revalidate` as part of the original result. `onError` takes a
83
+ * narrower payload and carries no `metadata`.
84
+ */
76
85
  readonly metadata?: Record<string, unknown>;
77
86
  }
78
87
  /**
@@ -131,6 +140,26 @@ interface ConnectionEventMeta {
131
140
  * keeps the connection alive does not refresh this snapshot.
132
141
  */
133
142
  readonly roles: readonly string[] | undefined;
143
+ /**
144
+ * The free-form `metadata` bag the authenticator returned, as a snapshot taken
145
+ * at connect time — `undefined` when the authenticator returned none.
146
+ *
147
+ * This is the only channel that carries a value from the handshake into the
148
+ * hooks that receive this type — `onConnect`, `onDisconnect` and
149
+ * `onReauthenticationFailed`. `authenticate` sees the request headers but not
150
+ * yet a `connectionId`, and those hooks see the `connectionId` but not the
151
+ * headers, so anything read off the request — a `traceparent`, an
152
+ * `x-request-id`, a plan tier — has to travel through here to be correlated
153
+ * with a connection.
154
+ *
155
+ * `onError` does NOT receive this type and therefore carries no `metadata`:
156
+ * it can fire before authentication has resolved, which is why even its
157
+ * `connectionId` is optional.
158
+ *
159
+ * The library never inspects a key. Like `roles`, it is a snapshot: a later
160
+ * `revalidate` that keeps the connection alive does not refresh it.
161
+ */
162
+ readonly metadata: Record<string, unknown> | undefined;
134
163
  readonly transport: 'sse' | 'websocket';
135
164
  readonly ip: string;
136
165
  readonly userAgent: string | undefined;
@@ -149,7 +178,15 @@ interface IConnectionLifecycleHooks {
149
178
  reason?: string;
150
179
  durationMs: number;
151
180
  }): void | Promise<void>;
152
- /** Called on a transport error. */
181
+ /**
182
+ * Called on a transport error.
183
+ *
184
+ * Deliberately NOT `ConnectionEventMeta`: this hook can fire before
185
+ * authentication resolves, so there may be no connection to describe. It
186
+ * carries no `roles` and no `metadata` — `connectionId` is optional for the
187
+ * same reason. Pinned by a test, so widening this shape means updating the
188
+ * documented guarantee with it.
189
+ */
153
190
  onError?(meta: {
154
191
  connectionId?: string;
155
192
  error: Error;
@@ -290,10 +327,6 @@ interface ReauthenticationPolicy {
290
327
  /** Synchronous module configuration. */
291
328
  interface BymaxRealtimeModuleOptions {
292
329
  transport: TransportMode;
293
- service?: {
294
- name: string;
295
- version: string;
296
- };
297
330
  authenticator: IConnectionAuthenticator;
298
331
  tenantResolver?: (auth: AuthenticationResult) => string | undefined;
299
332
  hooks?: IConnectionLifecycleHooks;
@@ -334,6 +367,20 @@ interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'
334
367
  * `transport` the factory resolves; a mismatch fails fast at bootstrap.
335
368
  */
336
369
  transport: TransportMode;
370
+ /**
371
+ * Path to bind the SSE controller to. Defaults to `'/events'`.
372
+ *
373
+ * Declared here rather than read from `sse.endpoint` for the same reason
374
+ * `transport` is: controllers are registered at decoration time, and the
375
+ * factory has not run yet. An `sse.endpoint` coming back from the factory
376
+ * cannot move the route, so a registration that sets it to anything other
377
+ * than this value is rejected at bootstrap instead of silently serving a
378
+ * different path than the one configured.
379
+ *
380
+ * Rejected outright when `transport` is `'websocket'`, which registers no SSE
381
+ * controller for it to name.
382
+ */
383
+ sseEndpoint?: string;
337
384
  /**
338
385
  * Factory producing the options, receiving whatever `inject` resolves.
339
386
  *
@@ -409,14 +456,21 @@ interface TransportWiring {
409
456
  build(resolved: ResolvedRealtimeOptions): TransportRegistration;
410
457
  /**
411
458
  * Wire the transports for the asynchronous path, where options are not known
412
- * at decoration time. Controllers must be registered then, so the endpoint is
413
- * fixed rather than read from the resolved options.
459
+ * at decoration time. Controllers must be registered then, so the endpoint
460
+ * comes from the registration itself rather than from the resolved options.
414
461
  */
415
- buildAsync(mode: BymaxRealtimeModuleOptions['transport']): {
462
+ buildAsync(params: AsyncWiringParams): {
416
463
  readonly providers: Provider[];
417
464
  readonly controllers: Type<unknown>[];
418
465
  };
419
466
  }
467
+ /** What the async path can know before any factory has run. */
468
+ interface AsyncWiringParams {
469
+ /** The transport declared on the registration. */
470
+ readonly mode: BymaxRealtimeModuleOptions['transport'];
471
+ /** The path to bind the SSE controller to, already defaulted by the caller. */
472
+ readonly sseEndpoint: string;
473
+ }
420
474
 
421
475
  /**
422
476
  * Compose the synchronous dynamic module for an entry point.
@@ -478,9 +532,12 @@ declare class BymaxRealtimeModule {
478
532
  * configuration rejects at bootstrap and the application fails to start with
479
533
  * a clear error.
480
534
  *
481
- * Controllers are registered at decoration time, so this path binds the SSE
482
- * controller to the default endpoint `/events`. A non-default endpoint needs
483
- * `forRoot` with pre-resolved options.
535
+ * Controllers are registered at decoration time, so the SSE route comes from
536
+ * `sseEndpoint` on the registration rather than from the `sse.endpoint` the
537
+ * factory resolves — the factory has not run yet when the controller is
538
+ * built. It defaults to `/events`, and a factory that resolves a disagreeing
539
+ * `sse.endpoint` is rejected at bootstrap rather than silently served on
540
+ * another path.
484
541
  *
485
542
  * @throws when no factory pattern is given, more than one is, or the factory
486
543
  * resolves a transport other than `'sse'`.
@@ -488,6 +545,7 @@ declare class BymaxRealtimeModule {
488
545
  * ```ts
489
546
  * BymaxRealtimeModule.forRootAsync({
490
547
  * transport: 'sse',
548
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
491
549
  * imports: [ConfigModule],
492
550
  * inject: [ConfigService],
493
551
  * useFactory: (cfg: ConfigService) => ({
@@ -545,6 +603,8 @@ interface ConnectionRecord {
545
603
  userId: string;
546
604
  tenantId: string | undefined;
547
605
  roles: readonly string[] | undefined;
606
+ /** The authenticator's free-form bag, carried through verbatim and never read. */
607
+ metadata: Record<string, unknown> | undefined;
548
608
  };
549
609
  }
550
610
  /**
@@ -72,7 +72,16 @@ interface AuthenticationResult {
72
72
  readonly userId: string;
73
73
  readonly tenantId?: string;
74
74
  readonly roles?: readonly string[];
75
- /** Free-form extras for downstream code (e.g. feature flags, plan tier). */
75
+ /**
76
+ * Free-form extras for downstream code (e.g. feature flags, plan tier, a
77
+ * correlation id read off the handshake headers).
78
+ *
79
+ * Carried verbatim — the library never reads a key. It reaches
80
+ * `ConnectionEventMeta.metadata` in the three hooks that receive that type —
81
+ * `onConnect`, `onDisconnect` and `onReauthenticationFailed` — and is handed
82
+ * back to `revalidate` as part of the original result. `onError` takes a
83
+ * narrower payload and carries no `metadata`.
84
+ */
76
85
  readonly metadata?: Record<string, unknown>;
77
86
  }
78
87
  /**
@@ -131,6 +140,26 @@ interface ConnectionEventMeta {
131
140
  * keeps the connection alive does not refresh this snapshot.
132
141
  */
133
142
  readonly roles: readonly string[] | undefined;
143
+ /**
144
+ * The free-form `metadata` bag the authenticator returned, as a snapshot taken
145
+ * at connect time — `undefined` when the authenticator returned none.
146
+ *
147
+ * This is the only channel that carries a value from the handshake into the
148
+ * hooks that receive this type — `onConnect`, `onDisconnect` and
149
+ * `onReauthenticationFailed`. `authenticate` sees the request headers but not
150
+ * yet a `connectionId`, and those hooks see the `connectionId` but not the
151
+ * headers, so anything read off the request — a `traceparent`, an
152
+ * `x-request-id`, a plan tier — has to travel through here to be correlated
153
+ * with a connection.
154
+ *
155
+ * `onError` does NOT receive this type and therefore carries no `metadata`:
156
+ * it can fire before authentication has resolved, which is why even its
157
+ * `connectionId` is optional.
158
+ *
159
+ * The library never inspects a key. Like `roles`, it is a snapshot: a later
160
+ * `revalidate` that keeps the connection alive does not refresh it.
161
+ */
162
+ readonly metadata: Record<string, unknown> | undefined;
134
163
  readonly transport: 'sse' | 'websocket';
135
164
  readonly ip: string;
136
165
  readonly userAgent: string | undefined;
@@ -149,7 +178,15 @@ interface IConnectionLifecycleHooks {
149
178
  reason?: string;
150
179
  durationMs: number;
151
180
  }): void | Promise<void>;
152
- /** Called on a transport error. */
181
+ /**
182
+ * Called on a transport error.
183
+ *
184
+ * Deliberately NOT `ConnectionEventMeta`: this hook can fire before
185
+ * authentication resolves, so there may be no connection to describe. It
186
+ * carries no `roles` and no `metadata` — `connectionId` is optional for the
187
+ * same reason. Pinned by a test, so widening this shape means updating the
188
+ * documented guarantee with it.
189
+ */
153
190
  onError?(meta: {
154
191
  connectionId?: string;
155
192
  error: Error;
@@ -290,10 +327,6 @@ interface ReauthenticationPolicy {
290
327
  /** Synchronous module configuration. */
291
328
  interface BymaxRealtimeModuleOptions {
292
329
  transport: TransportMode;
293
- service?: {
294
- name: string;
295
- version: string;
296
- };
297
330
  authenticator: IConnectionAuthenticator;
298
331
  tenantResolver?: (auth: AuthenticationResult) => string | undefined;
299
332
  hooks?: IConnectionLifecycleHooks;
@@ -334,6 +367,20 @@ interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'
334
367
  * `transport` the factory resolves; a mismatch fails fast at bootstrap.
335
368
  */
336
369
  transport: TransportMode;
370
+ /**
371
+ * Path to bind the SSE controller to. Defaults to `'/events'`.
372
+ *
373
+ * Declared here rather than read from `sse.endpoint` for the same reason
374
+ * `transport` is: controllers are registered at decoration time, and the
375
+ * factory has not run yet. An `sse.endpoint` coming back from the factory
376
+ * cannot move the route, so a registration that sets it to anything other
377
+ * than this value is rejected at bootstrap instead of silently serving a
378
+ * different path than the one configured.
379
+ *
380
+ * Rejected outright when `transport` is `'websocket'`, which registers no SSE
381
+ * controller for it to name.
382
+ */
383
+ sseEndpoint?: string;
337
384
  /**
338
385
  * Factory producing the options, receiving whatever `inject` resolves.
339
386
  *
@@ -409,14 +456,21 @@ interface TransportWiring {
409
456
  build(resolved: ResolvedRealtimeOptions): TransportRegistration;
410
457
  /**
411
458
  * Wire the transports for the asynchronous path, where options are not known
412
- * at decoration time. Controllers must be registered then, so the endpoint is
413
- * fixed rather than read from the resolved options.
459
+ * at decoration time. Controllers must be registered then, so the endpoint
460
+ * comes from the registration itself rather than from the resolved options.
414
461
  */
415
- buildAsync(mode: BymaxRealtimeModuleOptions['transport']): {
462
+ buildAsync(params: AsyncWiringParams): {
416
463
  readonly providers: Provider[];
417
464
  readonly controllers: Type<unknown>[];
418
465
  };
419
466
  }
467
+ /** What the async path can know before any factory has run. */
468
+ interface AsyncWiringParams {
469
+ /** The transport declared on the registration. */
470
+ readonly mode: BymaxRealtimeModuleOptions['transport'];
471
+ /** The path to bind the SSE controller to, already defaulted by the caller. */
472
+ readonly sseEndpoint: string;
473
+ }
420
474
 
421
475
  /**
422
476
  * Compose the synchronous dynamic module for an entry point.
@@ -478,9 +532,12 @@ declare class BymaxRealtimeModule {
478
532
  * configuration rejects at bootstrap and the application fails to start with
479
533
  * a clear error.
480
534
  *
481
- * Controllers are registered at decoration time, so this path binds the SSE
482
- * controller to the default endpoint `/events`. A non-default endpoint needs
483
- * `forRoot` with pre-resolved options.
535
+ * Controllers are registered at decoration time, so the SSE route comes from
536
+ * `sseEndpoint` on the registration rather than from the `sse.endpoint` the
537
+ * factory resolves — the factory has not run yet when the controller is
538
+ * built. It defaults to `/events`, and a factory that resolves a disagreeing
539
+ * `sse.endpoint` is rejected at bootstrap rather than silently served on
540
+ * another path.
484
541
  *
485
542
  * @throws when no factory pattern is given, more than one is, or the factory
486
543
  * resolves a transport other than `'sse'`.
@@ -488,6 +545,7 @@ declare class BymaxRealtimeModule {
488
545
  * ```ts
489
546
  * BymaxRealtimeModule.forRootAsync({
490
547
  * transport: 'sse',
548
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
491
549
  * imports: [ConfigModule],
492
550
  * inject: [ConfigService],
493
551
  * useFactory: (cfg: ConfigService) => ({
@@ -545,6 +603,8 @@ interface ConnectionRecord {
545
603
  userId: string;
546
604
  tenantId: string | undefined;
547
605
  roles: readonly string[] | undefined;
606
+ /** The authenticator's free-form bag, carried through verbatim and never read. */
607
+ metadata: Record<string, unknown> | undefined;
548
608
  };
549
609
  }
550
610
  /**
@@ -502,7 +502,8 @@ var SseTransport = class {
502
502
  originalAuth: {
503
503
  userId: params.auth.userId,
504
504
  tenantId: params.auth.tenantId,
505
- roles: params.auth.roles
505
+ roles: params.auth.roles,
506
+ metadata: params.auth.metadata
506
507
  }
507
508
  };
508
509
  this.connections.register(record);
@@ -524,6 +525,7 @@ var SseTransport = class {
524
525
  userId: record.userId,
525
526
  tenantId: record.tenantId,
526
527
  roles: record.originalAuth.roles,
528
+ metadata: record.originalAuth.metadata,
527
529
  transport: "sse",
528
530
  ip: record.ip,
529
531
  userAgent: record.userAgent,
@@ -761,6 +763,7 @@ function buildMeta(record) {
761
763
  userId: record.userId,
762
764
  tenantId: record.tenantId,
763
765
  roles: record.originalAuth.roles,
766
+ metadata: record.originalAuth.metadata,
764
767
  transport: "sse",
765
768
  ip: record.ip,
766
769
  userAgent: record.userAgent,
@@ -927,9 +930,14 @@ SseSubscriptionHandler = __decorateClass([
927
930
  __decorateParam(4, Inject(OfflineQueueDeliveryService))
928
931
  ], SseSubscriptionHandler);
929
932
 
933
+ // src/server/utils/normalize-endpoint-path.ts
934
+ function normalizeEndpointPath(endpoint) {
935
+ return endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
936
+ }
937
+
930
938
  // src/server/factories/sse-controller.factory.ts
931
939
  function createSseController(endpoint) {
932
- const ssePath = endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
940
+ const ssePath = normalizeEndpointPath(endpoint);
933
941
  let DynamicSseController = class {
934
942
  // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
935
943
  // not emit `design:paramtypes` decorator metadata, so constructor params must
@@ -1106,7 +1114,8 @@ var ReauthenticationService = class {
1106
1114
  const originalAuth = {
1107
1115
  userId: conn.originalAuth.userId,
1108
1116
  ...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
1109
- ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {}
1117
+ ...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {},
1118
+ ...conn.originalAuth.metadata !== void 0 ? { metadata: conn.originalAuth.metadata } : {}
1110
1119
  };
1111
1120
  const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
1112
1121
  if (rawResult === true) {
@@ -1136,6 +1145,7 @@ var ReauthenticationService = class {
1136
1145
  userId: conn.userId,
1137
1146
  tenantId: conn.tenantId,
1138
1147
  roles: conn.originalAuth.roles,
1148
+ metadata: conn.originalAuth.metadata,
1139
1149
  transport: "sse",
1140
1150
  ip: conn.ip,
1141
1151
  userAgent: conn.userAgent,
@@ -1158,6 +1168,7 @@ ReauthenticationService = __decorateClass([
1158
1168
  ], ReauthenticationService);
1159
1169
 
1160
1170
  // src/server/composition/realtime-module.factory.ts
1171
+ var DEFAULT_ASYNC_SSE_ENDPOINT = "/events";
1161
1172
  var EXPORTED_TOKENS = [
1162
1173
  RealtimeService,
1163
1174
  ConnectionRegistry,
@@ -1222,6 +1233,20 @@ function composeForRoot(moduleClass, wiring, logger, options) {
1222
1233
  exports: EXPORTED_TOKENS
1223
1234
  };
1224
1235
  }
1236
+ function assertSseEndpointApplies(asyncOptions, moduleName) {
1237
+ if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
1238
+ throw new Error(
1239
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`
1240
+ );
1241
+ }
1242
+ function bindSseEndpoint(resolved, declared, bound, moduleName) {
1243
+ if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
1244
+ throw new Error(
1245
+ `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`
1246
+ );
1247
+ }
1248
+ return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
1249
+ }
1225
1250
  function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
1226
1251
  if (!raw) {
1227
1252
  throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
@@ -1249,9 +1274,22 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1249
1274
  );
1250
1275
  }
1251
1276
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
1277
+ assertSseEndpointApplies(asyncOptions, moduleName);
1252
1278
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
1253
1279
  const instanceId = randomUUID();
1254
- const resolve = (raw, source) => resolveAsyncOptions(raw, asyncOptions.transport, instanceId, source, logger, moduleName);
1280
+ const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
1281
+ const resolve = (raw, source) => {
1282
+ const resolved = resolveAsyncOptions(
1283
+ raw,
1284
+ asyncOptions.transport,
1285
+ instanceId,
1286
+ source,
1287
+ logger,
1288
+ moduleName
1289
+ );
1290
+ if (asyncOptions.transport === "websocket") return resolved;
1291
+ return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
1292
+ };
1255
1293
  const resolvedOptionsProvider = asyncOptions.useFactory ? {
1256
1294
  provide: REALTIME_OPTIONS_TOKEN,
1257
1295
  useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
@@ -1266,7 +1304,10 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1266
1304
  };
1267
1305
  const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
1268
1306
  const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
1269
- const { providers: transportProviders, controllers } = wiring.buildAsync(asyncOptions.transport);
1307
+ const { providers: transportProviders, controllers } = wiring.buildAsync({
1308
+ mode: asyncOptions.transport,
1309
+ sseEndpoint: boundSseEndpoint
1310
+ });
1270
1311
  return {
1271
1312
  module: moduleClass,
1272
1313
  imports: asyncOptions.imports ?? [],
@@ -1367,7 +1408,6 @@ RealtimePubSubSubscriber = __decorateClass([
1367
1408
  ], RealtimePubSubSubscriber);
1368
1409
 
1369
1410
  // src/server/composition/sse-wiring.ts
1370
- var DEFAULT_ASYNC_ENDPOINT = "/events";
1371
1411
  var sseWiring = {
1372
1412
  modes: ["sse"],
1373
1413
  build(resolved) {
@@ -1382,7 +1422,7 @@ var sseWiring = {
1382
1422
  gateways: []
1383
1423
  };
1384
1424
  },
1385
- buildAsync() {
1425
+ buildAsync({ sseEndpoint }) {
1386
1426
  return {
1387
1427
  providers: [
1388
1428
  SseTransport,
@@ -1390,7 +1430,7 @@ var sseWiring = {
1390
1430
  RealtimePubSubSubscriber,
1391
1431
  { provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport }
1392
1432
  ],
1393
- controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
1433
+ controllers: [createSseController(sseEndpoint)]
1394
1434
  };
1395
1435
  }
1396
1436
  };
@@ -1418,9 +1458,12 @@ var BymaxRealtimeModule = class {
1418
1458
  * configuration rejects at bootstrap and the application fails to start with
1419
1459
  * a clear error.
1420
1460
  *
1421
- * Controllers are registered at decoration time, so this path binds the SSE
1422
- * controller to the default endpoint `/events`. A non-default endpoint needs
1423
- * `forRoot` with pre-resolved options.
1461
+ * Controllers are registered at decoration time, so the SSE route comes from
1462
+ * `sseEndpoint` on the registration rather than from the `sse.endpoint` the
1463
+ * factory resolves — the factory has not run yet when the controller is
1464
+ * built. It defaults to `/events`, and a factory that resolves a disagreeing
1465
+ * `sse.endpoint` is rejected at bootstrap rather than silently served on
1466
+ * another path.
1424
1467
  *
1425
1468
  * @throws when no factory pattern is given, more than one is, or the factory
1426
1469
  * resolves a transport other than `'sse'`.
@@ -1428,6 +1471,7 @@ var BymaxRealtimeModule = class {
1428
1471
  * ```ts
1429
1472
  * BymaxRealtimeModule.forRootAsync({
1430
1473
  * transport: 'sse',
1474
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
1431
1475
  * imports: [ConfigModule],
1432
1476
  * inject: [ConfigService],
1433
1477
  * useFactory: (cfg: ConfigService) => ({
@@ -106,7 +106,12 @@ exports.WebSocketTransport = class WebSocketTransport {
106
106
  connectedAt,
107
107
  subject: null,
108
108
  close$: null,
109
- originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
109
+ originalAuth: {
110
+ userId: auth.userId,
111
+ tenantId: auth.tenantId,
112
+ roles: auth.roles,
113
+ metadata: auth.metadata
114
+ }
110
115
  });
111
116
  await socket.join(`${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
112
117
  if (auth.tenantId) await socket.join(`${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
@@ -119,6 +124,7 @@ exports.WebSocketTransport = class WebSocketTransport {
119
124
  userId: auth.userId,
120
125
  tenantId: auth.tenantId,
121
126
  roles: auth.roles,
127
+ metadata: auth.metadata,
122
128
  transport: "websocket",
123
129
  ip: socket.handshake.address,
124
130
  userAgent: socket.handshake.headers["user-agent"],
@@ -144,6 +150,7 @@ exports.WebSocketTransport = class WebSocketTransport {
144
150
  userId: record.userId,
145
151
  tenantId: record.tenantId,
146
152
  roles: record.originalAuth.roles,
153
+ metadata: record.originalAuth.metadata,
147
154
  transport: "websocket",
148
155
  ip: record.ip,
149
156
  userAgent: record.userAgent,
@@ -490,7 +497,6 @@ exports.RealtimeGateway = __decorateClass([
490
497
  ], exports.RealtimeGateway);
491
498
 
492
499
  // src/websocket/websocket-wiring.ts
493
- var DEFAULT_ASYNC_ENDPOINT = "/events";
494
500
  var webSocketWiring = {
495
501
  modes: ["websocket", "both"],
496
502
  build(resolved) {
@@ -517,7 +523,7 @@ var webSocketWiring = {
517
523
  gateways: [exports.RealtimeGateway]
518
524
  };
519
525
  },
520
- buildAsync(mode) {
526
+ buildAsync({ mode, sseEndpoint }) {
521
527
  if (mode === "websocket") {
522
528
  return {
523
529
  providers: [
@@ -538,7 +544,7 @@ var webSocketWiring = {
538
544
  internal.RealtimePubSubSubscriber,
539
545
  { provide: internal.REALTIME_TRANSPORT_TOKEN, useExisting: exports.CompositeTransport }
540
546
  ],
541
- controllers: [internal.createSseController(DEFAULT_ASYNC_ENDPOINT)]
547
+ controllers: [internal.createSseController(sseEndpoint)]
542
548
  };
543
549
  }
544
550
  };
@@ -569,9 +575,12 @@ exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
569
575
  * Configure the module asynchronously so options — and the authenticator —
570
576
  * can be resolved through DI.
571
577
  *
572
- * Controllers are registered at decoration time, so `'both'` binds the SSE
573
- * controller to the default endpoint `/events`. A non-default endpoint needs
574
- * `forRoot` with pre-resolved options.
578
+ * Controllers are registered at decoration time, so under `'both'` the SSE
579
+ * route comes from `sseEndpoint` on the registration rather than from the
580
+ * `sse.endpoint` the factory resolves — the factory has not run yet when the
581
+ * controller is built. It defaults to `/events`, and a factory that resolves
582
+ * a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
583
+ * registers no SSE controller, so `sseEndpoint` is rejected there outright.
575
584
  *
576
585
  * @throws when no factory pattern is given, more than one is, or the factory
577
586
  * resolves a transport other than the one declared.
@@ -579,6 +588,7 @@ exports.BymaxRealtimeWebSocketModule = class BymaxRealtimeWebSocketModule {
579
588
  * ```ts
580
589
  * BymaxRealtimeWebSocketModule.forRootAsync({
581
590
  * transport: 'both',
591
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
582
592
  * imports: [ConfigModule],
583
593
  * inject: [ConfigService],
584
594
  * useFactory: (cfg: ConfigService) => ({
@@ -34,9 +34,12 @@ declare class BymaxRealtimeWebSocketModule {
34
34
  * Configure the module asynchronously so options — and the authenticator —
35
35
  * can be resolved through DI.
36
36
  *
37
- * Controllers are registered at decoration time, so `'both'` binds the SSE
38
- * controller to the default endpoint `/events`. A non-default endpoint needs
39
- * `forRoot` with pre-resolved options.
37
+ * Controllers are registered at decoration time, so under `'both'` the SSE
38
+ * route comes from `sseEndpoint` on the registration rather than from the
39
+ * `sse.endpoint` the factory resolves — the factory has not run yet when the
40
+ * controller is built. It defaults to `/events`, and a factory that resolves
41
+ * a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
42
+ * registers no SSE controller, so `sseEndpoint` is rejected there outright.
40
43
  *
41
44
  * @throws when no factory pattern is given, more than one is, or the factory
42
45
  * resolves a transport other than the one declared.
@@ -44,6 +47,7 @@ declare class BymaxRealtimeWebSocketModule {
44
47
  * ```ts
45
48
  * BymaxRealtimeWebSocketModule.forRootAsync({
46
49
  * transport: 'both',
50
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
47
51
  * imports: [ConfigModule],
48
52
  * inject: [ConfigService],
49
53
  * useFactory: (cfg: ConfigService) => ({
@@ -34,9 +34,12 @@ declare class BymaxRealtimeWebSocketModule {
34
34
  * Configure the module asynchronously so options — and the authenticator —
35
35
  * can be resolved through DI.
36
36
  *
37
- * Controllers are registered at decoration time, so `'both'` binds the SSE
38
- * controller to the default endpoint `/events`. A non-default endpoint needs
39
- * `forRoot` with pre-resolved options.
37
+ * Controllers are registered at decoration time, so under `'both'` the SSE
38
+ * route comes from `sseEndpoint` on the registration rather than from the
39
+ * `sse.endpoint` the factory resolves — the factory has not run yet when the
40
+ * controller is built. It defaults to `/events`, and a factory that resolves
41
+ * a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
42
+ * registers no SSE controller, so `sseEndpoint` is rejected there outright.
40
43
  *
41
44
  * @throws when no factory pattern is given, more than one is, or the factory
42
45
  * resolves a transport other than the one declared.
@@ -44,6 +47,7 @@ declare class BymaxRealtimeWebSocketModule {
44
47
  * ```ts
45
48
  * BymaxRealtimeWebSocketModule.forRootAsync({
46
49
  * transport: 'both',
50
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
47
51
  * imports: [ConfigModule],
48
52
  * inject: [ConfigService],
49
53
  * useFactory: (cfg: ConfigService) => ({
@@ -104,7 +104,12 @@ var WebSocketTransport = class {
104
104
  connectedAt,
105
105
  subject: null,
106
106
  close$: null,
107
- originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
107
+ originalAuth: {
108
+ userId: auth.userId,
109
+ tenantId: auth.tenantId,
110
+ roles: auth.roles,
111
+ metadata: auth.metadata
112
+ }
108
113
  });
109
114
  await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
110
115
  if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
@@ -117,6 +122,7 @@ var WebSocketTransport = class {
117
122
  userId: auth.userId,
118
123
  tenantId: auth.tenantId,
119
124
  roles: auth.roles,
125
+ metadata: auth.metadata,
120
126
  transport: "websocket",
121
127
  ip: socket.handshake.address,
122
128
  userAgent: socket.handshake.headers["user-agent"],
@@ -142,6 +148,7 @@ var WebSocketTransport = class {
142
148
  userId: record.userId,
143
149
  tenantId: record.tenantId,
144
150
  roles: record.originalAuth.roles,
151
+ metadata: record.originalAuth.metadata,
145
152
  transport: "websocket",
146
153
  ip: record.ip,
147
154
  userAgent: record.userAgent,
@@ -488,7 +495,6 @@ RealtimeGateway = __decorateClass([
488
495
  ], RealtimeGateway);
489
496
 
490
497
  // src/websocket/websocket-wiring.ts
491
- var DEFAULT_ASYNC_ENDPOINT = "/events";
492
498
  var webSocketWiring = {
493
499
  modes: ["websocket", "both"],
494
500
  build(resolved) {
@@ -515,7 +521,7 @@ var webSocketWiring = {
515
521
  gateways: [RealtimeGateway]
516
522
  };
517
523
  },
518
- buildAsync(mode) {
524
+ buildAsync({ mode, sseEndpoint }) {
519
525
  if (mode === "websocket") {
520
526
  return {
521
527
  providers: [
@@ -536,7 +542,7 @@ var webSocketWiring = {
536
542
  RealtimePubSubSubscriber,
537
543
  { provide: REALTIME_TRANSPORT_TOKEN, useExisting: CompositeTransport }
538
544
  ],
539
- controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
545
+ controllers: [createSseController(sseEndpoint)]
540
546
  };
541
547
  }
542
548
  };
@@ -567,9 +573,12 @@ var BymaxRealtimeWebSocketModule = class {
567
573
  * Configure the module asynchronously so options — and the authenticator —
568
574
  * can be resolved through DI.
569
575
  *
570
- * Controllers are registered at decoration time, so `'both'` binds the SSE
571
- * controller to the default endpoint `/events`. A non-default endpoint needs
572
- * `forRoot` with pre-resolved options.
576
+ * Controllers are registered at decoration time, so under `'both'` the SSE
577
+ * route comes from `sseEndpoint` on the registration rather than from the
578
+ * `sse.endpoint` the factory resolves — the factory has not run yet when the
579
+ * controller is built. It defaults to `/events`, and a factory that resolves
580
+ * a disagreeing `sse.endpoint` is rejected at bootstrap. `'websocket'`
581
+ * registers no SSE controller, so `sseEndpoint` is rejected there outright.
573
582
  *
574
583
  * @throws when no factory pattern is given, more than one is, or the factory
575
584
  * resolves a transport other than the one declared.
@@ -577,6 +586,7 @@ var BymaxRealtimeWebSocketModule = class {
577
586
  * ```ts
578
587
  * BymaxRealtimeWebSocketModule.forRootAsync({
579
588
  * transport: 'both',
589
+ * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
580
590
  * imports: [ConfigModule],
581
591
  * inject: [ConfigService],
582
592
  * useFactory: (cfg: ConfigService) => ({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
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",