@bymax-one/nest-realtime 1.0.0 → 1.0.2

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.
@@ -1,9 +1,6 @@
1
- import { ModuleMetadata, Type, Provider, DynamicModule, MessageEvent, INestApplicationContext } from '@nestjs/common';
1
+ import { ModuleMetadata, Type, Provider, DynamicModule, MessageEvent } from '@nestjs/common';
2
2
  import { Subject } from 'rxjs';
3
3
  import { Redis } from 'ioredis';
4
- import { Server, Socket, ServerOptions } from 'socket.io';
5
- import { OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
6
- import { IoAdapter } from '@nestjs/platform-socket.io';
7
4
 
8
5
  /**
9
6
  * @fileoverview Config-level transport mode selection.
@@ -297,6 +294,16 @@ interface BymaxRealtimeModuleOptions {
297
294
  websocket?: WebSocketOptions;
298
295
  reauthenticationPolicy?: ReauthenticationPolicy;
299
296
  }
297
+ /**
298
+ * Synchronous configuration for `BymaxRealtimeModule`, which serves SSE only.
299
+ *
300
+ * `transport` is narrowed rather than validated at runtime: WebSocket lives
301
+ * behind `@bymax-one/nest-realtime/websocket`, so asking this module for it is
302
+ * a mistake the compiler can catch.
303
+ */
304
+ type SseRealtimeModuleOptions = Omit<BymaxRealtimeModuleOptions, 'transport'> & {
305
+ transport: 'sse';
306
+ };
300
307
  /** A factory that builds module options (async dynamic-module pattern). */
301
308
  interface BymaxRealtimeModuleOptionsFactory {
302
309
  createRealtimeOptions(): BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
@@ -304,18 +311,12 @@ interface BymaxRealtimeModuleOptionsFactory {
304
311
  /** Asynchronous module configuration — the standard NestJS dynamic-module pattern. */
305
312
  interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
306
313
  /**
307
- * Optional synchronous transport mode. When provided, it gates WebSocket
308
- * provider registration at module-definition time — exactly as `forRoot` does —
309
- * so an SSE-only application never registers the gateway, never boots a
310
- * Socket.IO server, and never requires the optional WebSocket peer dependencies.
311
- *
312
- * It MUST equal the `transport` returned by the async factory; a mismatch fails
313
- * fast at bootstrap. When omitted, every transport provider is registered and
314
- * the active transport is resolved at runtime from the factory result (which
315
- * boots Socket.IO and requires the WS peer deps regardless of the configured
316
- * mode).
314
+ * The transport this registration wires. Required, not a hint: providers and
315
+ * controllers are fixed at decoration time, long before a factory runs, so the
316
+ * module cannot discover its own transport later. It MUST equal the
317
+ * `transport` the factory resolves; a mismatch fails fast at bootstrap.
317
318
  */
318
- transport?: TransportMode;
319
+ transport: TransportMode;
319
320
  useFactory?: (...args: unknown[]) => BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
320
321
  inject?: readonly (string | symbol | Type<unknown>)[];
321
322
  useExisting?: Type<BymaxRealtimeModuleOptionsFactory>;
@@ -326,25 +327,27 @@ interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'
326
327
  */
327
328
  extraProviders?: Provider[];
328
329
  }
330
+ /** Asynchronous configuration for `BymaxRealtimeModule` (SSE only). */
331
+ type SseRealtimeModuleAsyncOptions = Omit<BymaxRealtimeModuleAsyncOptions, 'transport'> & {
332
+ transport: 'sse';
333
+ };
329
334
 
330
335
  /**
331
- * Realtime module — supports SSE, WebSocket, or both transports. Registered
332
- * globally so a single configuration serves the whole application.
336
+ * Realtime module for Server-Sent Events. Registered globally so a single
337
+ * configuration serves the whole application.
338
+ *
339
+ * WebSocket lives behind `@bymax-one/nest-realtime/websocket`, and that split is
340
+ * what this module buys: nothing reachable from here imports
341
+ * `@nestjs/websockets` or `socket.io`, so an SSE application never installs the
342
+ * Socket.IO stack. Reach for `BymaxRealtimeWebSocketModule` when the transport
343
+ * is `'websocket'` or `'both'`.
333
344
  */
334
345
  declare class BymaxRealtimeModule {
335
346
  private static readonly logger;
336
- /**
337
- * Validate a raw async factory result, enforce the optional synchronous
338
- * `transport` hint, apply defaults, and log the bootstrap line.
339
- *
340
- * @throws when the factory returned nothing, the options are invalid, or the
341
- * resolved transport disagrees with the synchronous hint used to gate
342
- * provider registration.
343
- */
344
- private static resolveAsyncOptions;
345
347
  /**
346
348
  * Configure the module synchronously.
347
349
  *
350
+ * @throws when the options are invalid.
348
351
  * @example
349
352
  * ```ts
350
353
  * BymaxRealtimeModule.forRoot({
@@ -353,41 +356,35 @@ declare class BymaxRealtimeModule {
353
356
  * })
354
357
  * ```
355
358
  */
356
- static forRoot(options: BymaxRealtimeModuleOptions): DynamicModule;
359
+ static forRoot(options: SseRealtimeModuleOptions): DynamicModule;
357
360
  /**
358
- * Configure the module asynchronously so consumers can resolve options (and
359
- * the authenticator) through DI — `ConfigService`, `JwtService`, a Redis
360
- * client, etc.
361
+ * Configure the module asynchronously so options — and the authenticator —
362
+ * can be resolved through DI: `ConfigService`, a Redis client, and so on.
361
363
  *
362
- * Options are validated and defaulted **inside** the resolving factory, so a
363
- * malformed configuration rejects via the Promise at bootstrap time and the
364
- * application fails to start with a clear error.
364
+ * Options are validated inside the resolving factory, so a malformed
365
+ * configuration rejects at bootstrap and the application fails to start with
366
+ * a clear error.
365
367
  *
366
- * Controllers are registered at decoration time, so the async path binds the
367
- * SSE controller to the fixed default endpoint `/events`. Consumers that need
368
- * a non-default endpoint with async configuration should use `forRoot` and
369
- * pre-resolve the options before passing them.
370
- *
371
- * Pass a synchronous `transport` hint to gate WebSocket wiring exactly as
372
- * `forRoot` does — an SSE-only application then never registers the gateway,
373
- * never boots Socket.IO, and never requires the optional WS peer deps. Without
374
- * the hint, every transport provider is registered and the active one is
375
- * resolved at runtime from the factory result.
368
+ * Controllers are registered at decoration time, so this path binds the SSE
369
+ * controller to the default endpoint `/events`. A non-default endpoint needs
370
+ * `forRoot` with pre-resolved options.
376
371
  *
372
+ * @throws when no factory pattern is given, more than one is, or the factory
373
+ * resolves a transport other than `'sse'`.
377
374
  * @example
378
375
  * ```ts
379
376
  * BymaxRealtimeModule.forRootAsync({
380
377
  * transport: 'sse',
381
378
  * imports: [ConfigModule],
382
379
  * inject: [ConfigService],
383
- * useFactory: async (cfg: ConfigService) => ({
384
- * transport: 'sse',
385
- * authenticator: new CookieJwtAuthenticator(cfg.get('JWT_SECRET')!),
380
+ * useFactory: (cfg: ConfigService) => ({
381
+ * transport: 'sse' as const,
382
+ * authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
386
383
  * }),
387
384
  * })
388
385
  * ```
389
386
  */
390
- static forRootAsync(asyncOptions: BymaxRealtimeModuleAsyncOptions): DynamicModule;
387
+ static forRootAsync(asyncOptions: SseRealtimeModuleAsyncOptions): DynamicModule;
391
388
  }
392
389
 
393
390
  /**
@@ -703,594 +700,6 @@ declare const REALTIME_PRESENCE_TOKEN: unique symbol;
703
700
  declare const REALTIME_HOOKS_TOKEN: unique symbol;
704
701
  declare const REALTIME_INSTANCE_ID_TOKEN: unique symbol;
705
702
 
706
- /**
707
- * Indexed registry of room membership.
708
- *
709
- * Maintains two maps — `rooms` (roomId → Set<connectionId>) and `connectionRooms`
710
- * (connectionId → Set<roomId>). The reverse index makes `leaveAll()` on disconnect
711
- * O(rooms-per-connection) instead of O(total rooms).
712
- */
713
- declare class RoomRegistry {
714
- private readonly rooms;
715
- private readonly connectionRooms;
716
- /** Join a connection to a room (idempotent). */
717
- join(connectionId: string, roomId: string): void;
718
- /** Remove a connection from a room (idempotent); prunes empty entries. */
719
- leave(connectionId: string, roomId: string): void;
720
- /** Snapshot of a room's members — safe to iterate while membership mutates. */
721
- members(roomId: string): readonly string[];
722
- /** Snapshot of the rooms a connection currently belongs to. */
723
- roomsOf(connectionId: string): readonly string[];
724
- /** Remove a connection from every room (called on disconnect). */
725
- leaveAll(connectionId: string): void;
726
- /** Total number of distinct rooms. */
727
- countRooms(): number;
728
- }
729
-
730
- /**
731
- * WebSocket transport implementing `ITransport` over a Socket.IO `Server`.
732
- *
733
- * Emit methods call `server.to(room).emit(event, data)`. Cross-instance fan-out
734
- * is handled exclusively by `@socket.io/redis-adapter` (spec §11.4) — this class
735
- * never calls `IRealtimePubSub.publish` for WS messages.
736
- *
737
- * The Socket.IO `Server` instance is injected lazily via `setServer` (called by
738
- * `RealtimeGateway.afterInit`) because the server only exists after NestJS boots
739
- * the gateway. All emit methods are safe no-ops while the server is unset.
740
- */
741
- declare class WebSocketTransport implements ITransport {
742
- private readonly connections;
743
- private readonly rooms;
744
- private readonly auth;
745
- private readonly hooks;
746
- private readonly options;
747
- readonly kind: "websocket";
748
- private readonly logger;
749
- /** Nullable until the gateway's afterInit wires the instance. */
750
- private server;
751
- constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
752
- /**
753
- * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
754
- *
755
- * All emit methods silently no-op until this is called, so the transport is
756
- * safe to construct before the HTTP server is ready.
757
- *
758
- * @param server - The live Socket.IO `Server` instance from the NestJS gateway.
759
- */
760
- setServer(server: Server): void;
761
- /**
762
- * Resolve the map of locally-connected sockets, tolerating both server shapes.
763
- *
764
- * A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
765
- * `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
766
- * `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
767
- * `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
768
- * this indirection so they work under either shape.
769
- */
770
- private localSockets;
771
- /**
772
- * Expose the configured authenticator to the gateway.
773
- *
774
- * The gateway uses this to avoid a circular injection: `RealtimeGateway` →
775
- * `WebSocketTransport` → authenticator, rather than injecting the token
776
- * directly in the gateway.
777
- *
778
- * @returns The consumer-provided `IConnectionAuthenticator` instance.
779
- */
780
- authenticator(): IConnectionAuthenticator;
781
- /**
782
- * Register a freshly-authenticated WebSocket connection.
783
- *
784
- * Stores the connection record in `ConnectionRegistry` (with `subject: null` —
785
- * WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
786
- * membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
787
- *
788
- * Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
789
- * does not publish to `IRealtimePubSub`.
790
- *
791
- * @param socket - The authenticated Socket.IO socket instance.
792
- * @param auth - The resolved authentication result containing userId, tenantId, and roles.
793
- */
794
- registerSocket(socket: Socket, auth: AuthenticationResult): Promise<void>;
795
- /**
796
- * Unregister a disconnected WebSocket connection.
797
- *
798
- * Removes the record from `ConnectionRegistry`, clears all room membership
799
- * from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
800
- * computed `durationMs`.
801
- *
802
- * @param connectionId - The Socket.IO socket `id` of the disconnected connection.
803
- * @param reason - Optional reason string forwarded to the `onDisconnect` hook.
804
- */
805
- unregisterSocket(connectionId: string, reason?: string): Promise<void>;
806
- /**
807
- * Send an event to every connection of a user (uses `user:{userId}` room).
808
- *
809
- * @param userId - Target user identifier.
810
- * @param event - Event name to emit.
811
- * @param data - Payload forwarded to all matching connections.
812
- */
813
- emitToUser(userId: string, event: string, data: unknown): Promise<void>;
814
- /**
815
- * Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
816
- *
817
- * @param tenantId - Target tenant identifier.
818
- * @param event - Event name to emit.
819
- * @param data - Payload forwarded to all matching connections.
820
- */
821
- emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
822
- /**
823
- * Send an event to every connection in an arbitrary room.
824
- *
825
- * @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
826
- * @param event - Event name to emit.
827
- * @param data - Payload forwarded to all connections in the room.
828
- */
829
- emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
830
- /**
831
- * Broadcast an event to all connected clients.
832
- *
833
- * @param event - Event name to emit.
834
- * @param data - Payload forwarded to every connected socket.
835
- */
836
- broadcast(event: string, data: unknown): Promise<void>;
837
- /**
838
- * Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
839
- *
840
- * @param connectionId - The socket `id` of the connection to join.
841
- * @param roomId - The room to join.
842
- */
843
- joinRoom(connectionId: string, roomId: string): Promise<void>;
844
- /**
845
- * Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
846
- *
847
- * @param connectionId - The socket `id` of the connection to remove.
848
- * @param roomId - The room to leave.
849
- */
850
- leaveRoom(connectionId: string, roomId: string): Promise<void>;
851
- /**
852
- * Force-disconnect a specific connection — adapter-aware, so revocation works
853
- * across nodes.
854
- *
855
- * A socket local to this node is closed directly as a fast path. Regardless,
856
- * `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
857
- * under `@socket.io/redis-adapter` this fans out to remote nodes, so a
858
- * connection pinned to another instance is still force-closed. The local socket
859
- * has already left the room by then, so the broadcast does not double-close it.
860
- *
861
- * @param connectionId - The socket `id` of the connection to disconnect.
862
- * @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
863
- */
864
- disconnect(connectionId: string, _reason?: string): Promise<void>;
865
- /**
866
- * Evict the user's oldest WebSocket connections (FIFO) when over
867
- * `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
868
- * as the disconnect reason — never rejects the new connection with HTTP 429.
869
- */
870
- private evictBeyondLimit;
871
- }
872
-
873
- /**
874
- * NestJS WebSocket gateway wiring the Socket.IO lifecycle to `WebSocketTransport`.
875
- *
876
- * Authentication flows exclusively through the consumer-provided
877
- * `IConnectionAuthenticator` (auth inversion — spec §1.6). The gateway never
878
- * imports a concrete auth library; it only shapes the `ConnectionAuthContext`
879
- * from the Socket.IO handshake and delegates to the authenticator.
880
- *
881
- * Namespace, CORS, ping options, and the Redis adapter are applied by
882
- * `RealtimeIoAdapter` (not here), because `@WebSocketGateway()` args are
883
- * evaluated at class-decoration time — before the module options are resolved.
884
- *
885
- * CORS is intentionally disabled in the decorator (`origin: false`). The real
886
- * policy is applied by `RealtimeIoAdapter.createIOServer` from the consumer's
887
- * `websocket.cors` option. Leaving it open-by-default here would allow any
888
- * origin to make credentialed connections before the adapter overrides the policy.
889
- */
890
- declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
891
- private readonly transport;
892
- private readonly options;
893
- private readonly logger;
894
- server: Server;
895
- constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
896
- /** Wire the resolved Socket.IO server to the transport after gateway init. */
897
- afterInit(server: Server): void;
898
- /**
899
- * Handle a new WebSocket connection.
900
- *
901
- * Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
902
- * three supported auth patterns (spec §8.1):
903
- * - Cookie HttpOnly — extracted via `parseCookieHeader`.
904
- * - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
905
- * - Bearer header — available in `headers.authorization` or via `auth.token`.
906
- *
907
- * `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
908
- * (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
909
- * context so the authenticator sees a single unified shape regardless of client.
910
- *
911
- * Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
912
- * undefined`); the single-value `ticket` parameter is collapsed to its first
913
- * element so the authenticator receives a well-defined string.
914
- *
915
- * Fail-closed: any thrown error disconnects the socket immediately so it cannot
916
- * linger in an unregistered state and receive broadcast events.
917
- */
918
- handleConnection(socket: Socket): Promise<void>;
919
- /** Handle a WebSocket disconnection — unregister the connection. */
920
- handleDisconnect(socket: Socket): Promise<void>;
921
- /**
922
- * Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
923
- *
924
- * Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
925
- * single string, matching the shape expected by `ConnectionAuthContext.headers`.
926
- */
927
- private normalizeHeaders;
928
- }
929
-
930
- /**
931
- * Custom NestJS `IoAdapter` that:
932
- *
933
- * 1. Applies `websocket.cors`, `pingIntervalMs`, `pingTimeoutMs`, and
934
- * `maxHttpBufferSize` from `BymaxRealtimeModuleOptions`.
935
- * 2. Lazily installs `@socket.io/redis-adapter` when
936
- * `websocket.redisAdapter.pubClient` is provided, enabling transparent
937
- * cross-instance WebSocket fan-out (spec §11.4).
938
- *
939
- * Register this adapter in `main.ts` **before** `app.listen()`:
940
- *
941
- * ```ts
942
- * import { RealtimeIoAdapter } from '@bymax-one/nest-realtime'
943
- *
944
- * const app = await NestFactory.create(AppModule)
945
- * app.useWebSocketAdapter(new RealtimeIoAdapter(app))
946
- * await app.listen(3000)
947
- * ```
948
- *
949
- * Sticky sessions are MANDATORY when the polling fallback is enabled in a
950
- * horizontally scaled deployment. The adapter synchronizes messages across
951
- * nodes but does NOT remove the load-balancer's session-affinity requirement
952
- * (spec §11.5).
953
- */
954
- declare class RealtimeIoAdapter extends IoAdapter {
955
- private readonly logger;
956
- private readonly options;
957
- constructor(app: INestApplicationContext);
958
- /**
959
- * Bind the gateway to `websocket.namespace` when configured.
960
- *
961
- * `@WebSocketGateway()` args are evaluated at class-decoration time — before
962
- * the module options resolve — so the namespace cannot be declared there.
963
- * Instead we build the root server via `super.create` (which routes through the
964
- * overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
965
- * the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
966
- * and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
967
- * namespace leaves the root server untouched.
968
- */
969
- create(port: number, options?: ServerOptions & {
970
- namespace?: string;
971
- server?: unknown;
972
- }): Server;
973
- /**
974
- * Create the Socket.IO server with merged WebSocket options.
975
- *
976
- * When `websocket.redisAdapter.pubClient` is set, installs the
977
- * `@socket.io/redis-adapter` lazily (so the package stays an optional peer
978
- * dep — its absence does not crash the lib).
979
- */
980
- createIOServer(port: number, opts?: ServerOptions): unknown;
981
- /**
982
- * Lazily load and install `@socket.io/redis-adapter`.
983
- *
984
- * Uses a dynamic `require` so the package stays optional — absent peers do
985
- * not crash the lib. A load or install failure is logged and tolerated;
986
- * the lib degrades gracefully to single-instance mode.
987
- */
988
- private installRedisAdapter;
989
- }
990
-
991
- /**
992
- * Generates monotonically increasing event ids of the form
993
- * `{epochMillis}-{counter}`, where the counter resets every millisecond.
994
- *
995
- * Guarantees:
996
- * - Lexicographically sortable (the counter is zero-padded to a fixed width), so
997
- * `Last-Event-ID` replay can string-compare ids.
998
- * - Monotonic within a single instance even when called repeatedly at the same
999
- * epoch millisecond.
1000
- *
1001
- * @example
1002
- * ```ts
1003
- * gen.next() // → '1717000000000-000001'
1004
- * gen.next() // → '1717000000000-000002'
1005
- * ```
1006
- */
1007
- declare class EventIdGenerator {
1008
- private lastMs;
1009
- private counter;
1010
- /** Produce the next monotonic event id. */
1011
- next(): string;
1012
- }
1013
-
1014
- /**
1015
- * Per-user ring buffer of recent events for `Last-Event-ID` replay.
1016
- *
1017
- * In-memory by design — it survives only as long as the process. Per-user buffers
1018
- * prevent one user from poisoning another's replay state. For durable replay
1019
- * (instance restart, or a gap larger than the buffer), a consumer can plug
1020
- * `IOfflineQueueStorage` as a fallback.
1021
- *
1022
- * @example
1023
- * ```ts
1024
- * // On reconnect with `Last-Event-ID: <id>`, replay what was missed:
1025
- * const missed = replayBuffer.since(userId, lastEventId)
1026
- * ```
1027
- */
1028
- declare class EventReplayBuffer {
1029
- private readonly opts;
1030
- private readonly buffers;
1031
- constructor(opts: BymaxRealtimeModuleOptions);
1032
- /** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
1033
- append(userId: string, event: MessageEvent): void;
1034
- /**
1035
- * Return the events emitted after `lastEventId`.
1036
- *
1037
- * Returns an empty array when the user has no buffer, or when `lastEventId` is
1038
- * not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
1039
- */
1040
- since(userId: string, lastEventId: string): MessageEvent[];
1041
- /** Number of events currently buffered for a user (diagnostics). */
1042
- size(userId: string): number;
1043
- }
1044
-
1045
- /** Minimal response surface the heartbeat needs — a writable text stream. */
1046
- interface HeartbeatWritable {
1047
- write(chunk: string): unknown;
1048
- }
1049
- /**
1050
- * Emits the SSE keepalive on an interval, per connection.
1051
- *
1052
- * The keepalive is a raw `: keepalive\n\n` comment written DIRECTLY to the response
1053
- * stream — not a `MessageEvent`, not a named event, and outside the `Last-Event-ID`
1054
- * id-space — so it never corrupts replay. Comments keep proxies and load balancers
1055
- * from idling out the connection. Timers are tracked per connection and cleared on
1056
- * `stop`.
1057
- *
1058
- * The configured interval must be within `[5_000, 90_000]` ms; values outside this
1059
- * range throw a `REALTIME_INVALID_OPTIONS` error.
1060
- *
1061
- * See `docs/proxies-cheat-sheet.md` for nginx, Cloudflare, and AWS ALB configuration.
1062
- */
1063
- declare class HeartbeatService {
1064
- private readonly timers;
1065
- /**
1066
- * Start writing keepalives for a connection every `intervalMs`.
1067
- *
1068
- * @param connectionId - Unique connection identifier used to track the timer.
1069
- * @param res - The writable response stream (or any object with a `write` method).
1070
- * @param intervalMs - Keepalive interval in milliseconds; must be within
1071
- * `[5_000, 90_000]`.
1072
- * @throws {Error} When `intervalMs` is outside the valid range.
1073
- */
1074
- start(connectionId: string, res: HeartbeatWritable, intervalMs: number): void;
1075
- /** Stop and clear the keepalive timer for a connection (idempotent). */
1076
- stop(connectionId: string): void;
1077
- /** Stop every keepalive timer (used on shutdown). */
1078
- stopAll(): void;
1079
- }
1080
-
1081
- /** Parameters required to register a freshly authenticated SSE connection. */
1082
- interface RegisterSseConnectionParams {
1083
- connectionId: string;
1084
- auth: AuthenticationResult;
1085
- subject: Subject<MessageEvent>;
1086
- close$: Subject<void>;
1087
- ip: string;
1088
- userAgent: string | undefined;
1089
- }
1090
- /**
1091
- * SSE transport implementation.
1092
- *
1093
- * Each public `emitTo*`/`broadcast` performs local delivery via the matching
1094
- * `*Local` method and then publishes exactly once to `IRealtimePubSub`. Remote
1095
- * messages received from the bus are dispatched by `RealtimePubSubSubscriber`
1096
- * (not this class) to the `*Local` methods only (never re-published), and
1097
- * self-originated messages are filtered there — so a single instance never
1098
- * double-delivers and multiple instances never ping-pong.
1099
- *
1100
- * Teardown of an SSE stream is driven by the per-connection `close$` subject:
1101
- * `disconnectLocal` completes it (which ends the `@Sse` Observable via
1102
- * `takeUntil`) before unregistering. See `docs/technical_specification.md` §6.1.
1103
- */
1104
- declare class SseTransport implements ITransport {
1105
- private readonly connections;
1106
- private readonly rooms;
1107
- private readonly replayBuffer;
1108
- private readonly idGen;
1109
- private readonly heartbeat;
1110
- private readonly auth;
1111
- private readonly pubsub;
1112
- private readonly hooks;
1113
- private readonly options;
1114
- private readonly instanceId;
1115
- private readonly offlineQueue?;
1116
- readonly kind: "sse";
1117
- private readonly logger;
1118
- constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
1119
- /** Tear down every SSE connection and stop heartbeat on process shutdown. */
1120
- onApplicationShutdown(): Promise<void>;
1121
- /** The resolved heartbeat interval for this transport. */
1122
- get heartbeatMs(): number;
1123
- /** Whether the `connection:established` event should be emitted on connect. */
1124
- get emitConnectionEvent(): boolean;
1125
- /** Authenticate a connection through the consumer-provided authenticator. */
1126
- authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
1127
- /**
1128
- * Register an authenticated SSE connection and auto-join its user/tenant rooms.
1129
- *
1130
- * Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
1131
- * lifecycle hook is fired by the subscription handler after this returns, so that the
1132
- * handler can carry a consistent connection record reference.
1133
- */
1134
- registerConnection(params: RegisterSseConnectionParams): Promise<void>;
1135
- /** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
1136
- unregisterConnection(connectionId: string, reason?: string): Promise<void>;
1137
- /** Replay the events a user missed after `lastEventId`. */
1138
- getReplayEvents(userId: string, lastEventId: string): MessageEvent[];
1139
- /**
1140
- * All SSE connections for a user — public accessor so external callers can
1141
- * inspect or iterate without reaching into a private registry field.
1142
- *
1143
- * @param userId - The user whose active connections are returned.
1144
- * @returns A snapshot of the user's current SSE `ConnectionRecord` list.
1145
- */
1146
- connectionsForUser(userId: string): ConnectionRecord[];
1147
- /**
1148
- * Look up a single connection by id.
1149
- *
1150
- * @param connectionId - The unique connection identifier.
1151
- * @returns The `ConnectionRecord`, or `undefined` when not found.
1152
- */
1153
- getConnection(connectionId: string): ConnectionRecord | undefined;
1154
- emitToUser(userId: string, event: string, data: unknown): Promise<void>;
1155
- emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
1156
- emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
1157
- broadcast(event: string, data: unknown): Promise<void>;
1158
- joinRoom(connectionId: string, roomId: string): Promise<void>;
1159
- leaveRoom(connectionId: string, roomId: string): Promise<void>;
1160
- /** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
1161
- disconnect(connectionId: string, reason?: string): Promise<void>;
1162
- /**
1163
- * Deliver an event to a user's local SSE connections and update the replay buffer.
1164
- *
1165
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
1166
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
1167
- */
1168
- emitToUserLocal(userId: string, event: string, data: unknown, id: string): void;
1169
- /**
1170
- * Deliver an event to all local SSE connections for a tenant.
1171
- *
1172
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
1173
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
1174
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
1175
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
1176
- */
1177
- emitToTenantLocal(tenantId: string, event: string, data: unknown, id: string): void;
1178
- /**
1179
- * Deliver an event to all local SSE connections that joined the given room.
1180
- *
1181
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
1182
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
1183
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
1184
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
1185
- */
1186
- emitToRoomLocal(roomId: string, event: string, data: unknown, id: string): void;
1187
- /**
1188
- * Deliver an event to all local SSE connections.
1189
- *
1190
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
1191
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
1192
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
1193
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
1194
- */
1195
- broadcastLocal(event: string, data: unknown, id: string): void;
1196
- /**
1197
- * Tear down a locally-owned SSE stream, then clean up (no re-publish).
1198
- *
1199
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
1200
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
1201
- */
1202
- disconnectLocal(connectionId: string, reason?: string): Promise<void>;
1203
- private buildMessage;
1204
- /** Deliver to one connection, isolating failures so others still receive the event. */
1205
- private deliver;
1206
- /** Publish once to the bus; pub/sub failures never affect the live emit path. */
1207
- private publish;
1208
- /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
1209
- private evictBeyondLimit;
1210
- }
1211
-
1212
- /**
1213
- * Fan-out transport activated when `transport: 'both'`.
1214
- *
1215
- * Every `emitTo*` and `broadcast` invokes both SSE and WebSocket transports in
1216
- * parallel via `Promise.allSettled` so a failure in one never aborts the other.
1217
- * Failures are logged as warnings without rethrowing.
1218
- *
1219
- * `joinRoom`, `leaveRoom`, and `disconnect` attempt both transports tolerantly:
1220
- * only the transport that owns the connection will succeed; the other's rejection
1221
- * is swallowed. There is no double-delivery because each connection lives on
1222
- * exactly one transport.
1223
- *
1224
- * `kind` reports `'sse'` (the dominant transport); `ITransport.kind` is
1225
- * `'sse' | 'websocket'` — `'both'` is a module-level `TransportMode`, not a
1226
- * valid per-transport kind (spec §6.3).
1227
- */
1228
- declare class CompositeTransport implements ITransport {
1229
- private readonly sse;
1230
- private readonly ws;
1231
- readonly kind: "sse";
1232
- private readonly logger;
1233
- constructor(sse: SseTransport, ws: WebSocketTransport);
1234
- /**
1235
- * Emit to all connections of a user across both transports.
1236
- *
1237
- * @param userId - Target user identifier.
1238
- * @param event - Event name to emit.
1239
- * @param data - Payload forwarded to all matching connections.
1240
- */
1241
- emitToUser(userId: string, event: string, data: unknown): Promise<void>;
1242
- /**
1243
- * Emit to all connections within a tenant across both transports.
1244
- *
1245
- * @param tenantId - Target tenant identifier.
1246
- * @param event - Event name to emit.
1247
- * @param data - Payload forwarded to all matching connections.
1248
- */
1249
- emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
1250
- /**
1251
- * Emit to all connections in a room across both transports.
1252
- *
1253
- * @param roomId - The fully-qualified room identifier.
1254
- * @param event - Event name to emit.
1255
- * @param data - Payload forwarded to all connections in the room.
1256
- */
1257
- emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
1258
- /**
1259
- * Broadcast to all connected clients across both transports.
1260
- *
1261
- * @param event - Event name to emit.
1262
- * @param data - Payload forwarded to every connected client.
1263
- */
1264
- broadcast(event: string, data: unknown): Promise<void>;
1265
- /**
1266
- * Join a connection to a room.
1267
- *
1268
- * Both transports are attempted; only the one that owns the connection
1269
- * succeeds. The other's failure is expected and swallowed.
1270
- */
1271
- joinRoom(connectionId: string, roomId: string): Promise<void>;
1272
- /**
1273
- * Remove a connection from a room.
1274
- *
1275
- * Both transports are attempted tolerantly — one will succeed, the other
1276
- * may fail silently.
1277
- */
1278
- leaveRoom(connectionId: string, roomId: string): Promise<void>;
1279
- /**
1280
- * Disconnect a specific connection.
1281
- *
1282
- * Both transports are attempted; the one owning the connection disconnects it.
1283
- */
1284
- disconnect(connectionId: string, reason?: string): Promise<void>;
1285
- /**
1286
- * Run two transport tasks in parallel via `Promise.allSettled`.
1287
- *
1288
- * A rejection in either task is logged as a warning and does not propagate,
1289
- * ensuring one failing transport never blocks delivery on the other.
1290
- */
1291
- private fanOut;
1292
- }
1293
-
1294
703
  /**
1295
704
  * @fileoverview Canonical room id prefixes for scoping emits and auto-join.
1296
705
  * @layer shared
@@ -1434,4 +843,4 @@ declare const REALTIME_ERROR_CODES: {
1434
843
  /** Union of canonical error code values. */
1435
844
  type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
1436
845
 
1437
- export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, CompositeTransport, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, RealtimeGateway, RealtimeIoAdapter, type RealtimePubSubMessage, RealtimeService, type ReauthenticationPolicy, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, type SseOptions, type TransportMode, type WebSocketOptions, WebSocketTransport, composeRoomId };
846
+ export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimeService, type ReauthenticationPolicy, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, type SseOptions, type TransportMode, type WebSocketOptions, composeRoomId };