@my-nestjs-kit/sse 0.0.0-stage → 0.1.0-dev.20261129020438

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sabationok
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @my-nestjs-kit/sse
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server-sent events for NestJS. Depends on `@my-nestjs-kit/core` (`RedisService`, `AppHttpException`).
4
+
5
+ ```sh
6
+ npm i @my-nestjs-kit/sse
7
+ ```
8
+
9
+ Peers: `@nestjs/common`, `rxjs`, plus core's peers. Optional: `@types/express`.
10
+
11
+ - **`SseServer`:** clients and in-memory rooms (`connect` / `subscribe` / `disconnect` / `to` / `broadcast`),
12
+ `SseRoutesModule.forRoot({ path })`, `SseHeaderMiddleware`. The client id comes from `getTracker(req)` (server
13
+ side, wins) or the fallbacks (cookie, `?deviceId`, random), so authenticate the route. `channel` is any
14
+ `{ message(type, data) }` publisher for cross-instance fan-out.
15
+ - **`SseRoomStream`:** one connection per client of a room, numbered events, `Last-Event-ID` replay, per-client
16
+ ack, heartbeat, per-client filter, `emitVolatile`. The log is a port: `InMemorySseEventLog` or
17
+ `RedisSseEventLog` on the app's client (`ttlSec` required), `historySize` bounds a room.
18
+
19
+ ## License
20
+
21
+ MIT
@@ -0,0 +1,5 @@
1
+ export * from './sse-server.types';
2
+ export * from './sse-server';
3
+ export * from './sse-event-log';
4
+ export * from './redis-sse-event-log';
5
+ export * from './sse-room-stream';
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./sse-server.types"), exports);
18
+ __exportStar(require("./sse-server"), exports);
19
+ __exportStar(require("./sse-event-log"), exports);
20
+ __exportStar(require("./redis-sse-event-log"), exports);
21
+ __exportStar(require("./sse-room-stream"), exports);
@@ -0,0 +1,31 @@
1
+ import { SseEventLog, SseLoggedEvent } from './sse-event-log';
2
+ import type { SseClientId, SseRoomId } from './sse-server.types';
3
+ /** The subset of an ioredis client the log uses. `eval` only runs the constant scripts below; values go as ARGV. */
4
+ export interface SseEventLogRedisClient {
5
+ eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
6
+ zrangebyscore(key: string, min: string | number, max: string | number, ...args: any[]): Promise<string[]>;
7
+ del(...keys: string[]): Promise<number>;
8
+ }
9
+ export interface RedisSseEventLogOptions {
10
+ /** Key prefix: `{prefix}:{{room}}:…`. Default `sse`. */
11
+ prefix?: string;
12
+ /** The most events a room keeps; the oldest go first. Default 300. */
13
+ historySize?: number;
14
+ /** Keys expire this long after the room's last activity, so an abandoned room cleans itself up. */
15
+ ttlSec: number;
16
+ }
17
+ /** A room's log in Redis on the app's own client: the kit doesn't open connections. */
18
+ export declare class RedisSseEventLog implements SseEventLog {
19
+ private readonly redis;
20
+ private readonly prefix;
21
+ private readonly historySize;
22
+ private readonly ttlSec;
23
+ constructor(redis: SseEventLogRedisClient, options: RedisSseEventLogOptions);
24
+ private key;
25
+ append<Type extends string, Data extends object>(room: SseRoomId, type: Type, data: Data): Promise<SseLoggedEvent<Type, Data>>;
26
+ read(room: SseRoomId, afterId: number, limit: number): Promise<SseLoggedEvent[]>;
27
+ join(room: SseRoomId, clientId: SseClientId, lastId: number): Promise<void>;
28
+ ack(room: SseRoomId, clientId: SseClientId, lastId: number): Promise<void>;
29
+ leave(room: SseRoomId, clientId: SseClientId): Promise<void>;
30
+ drop(room: SseRoomId): Promise<void>;
31
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedisSseEventLog = void 0;
4
+ const sse_event_log_1 = require("./sse-event-log");
5
+ // Numbering and storing are one step: otherwise a reader could pass a number written a moment later.
6
+ const APPEND = `
7
+ local id = redis.call('INCR', KEYS[1])
8
+ redis.call('ZADD', KEYS[2], id, id .. '|' .. ARGV[1])
9
+ redis.call('ZREMRANGEBYRANK', KEYS[2], 0, -(tonumber(ARGV[2]) + 1))
10
+ redis.call('EXPIRE', KEYS[1], ARGV[3])
11
+ redis.call('EXPIRE', KEYS[2], ARGV[3])
12
+ redis.call('EXPIRE', KEYS[3], ARGV[3])
13
+ return id`;
14
+ const JOIN = `
15
+ redis.call('HSETNX', KEYS[1], ARGV[1], ARGV[2])
16
+ redis.call('EXPIRE', KEYS[1], ARGV[3])`;
17
+ const TRIM = `
18
+ local lowest
19
+ for _, cursor in ipairs(redis.call('HVALS', KEYS[1])) do
20
+ local value = tonumber(cursor)
21
+ if not lowest or value < lowest then lowest = value end
22
+ end
23
+ if lowest then redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', lowest) end`;
24
+ const ACK = `
25
+ local current = tonumber(redis.call('HGET', KEYS[1], ARGV[1]) or '0')
26
+ if tonumber(ARGV[2]) > current then redis.call('HSET', KEYS[1], ARGV[1], ARGV[2]) end
27
+ redis.call('EXPIRE', KEYS[1], ARGV[3])
28
+ ${TRIM}`;
29
+ const LEAVE = `
30
+ redis.call('HDEL', KEYS[1], ARGV[1])
31
+ ${TRIM}`;
32
+ /** A room's log in Redis on the app's own client: the kit doesn't open connections. */
33
+ class RedisSseEventLog {
34
+ constructor(redis, options) {
35
+ this.redis = redis;
36
+ this.prefix = options.prefix ?? 'sse';
37
+ this.historySize = options.historySize ?? sse_event_log_1.SSE_DEFAULT_HISTORY_SIZE;
38
+ this.ttlSec = options.ttlSec;
39
+ }
40
+ // The hash tag keeps a room's keys on one Redis Cluster slot, which the scripts need.
41
+ key(room, part) {
42
+ return `${this.prefix}:{${room}}:${part}`;
43
+ }
44
+ async append(room, type, data) {
45
+ const id = await this.redis.eval(APPEND, 3, this.key(room, 'seq'), this.key(room, 'events'), this.key(room, 'cursors'), JSON.stringify({ type, data }), this.historySize, this.ttlSec);
46
+ return { id: Number(id), type, data };
47
+ }
48
+ async read(room, afterId, limit) {
49
+ const members = await this.redis.zrangebyscore(this.key(room, 'events'), `(${afterId}`, '+inf', 'LIMIT', 0, limit);
50
+ return members.map((member) => {
51
+ const separator = member.indexOf('|');
52
+ return {
53
+ id: Number(member.slice(0, separator)),
54
+ ...JSON.parse(member.slice(separator + 1)),
55
+ };
56
+ });
57
+ }
58
+ async join(room, clientId, lastId) {
59
+ await this.redis.eval(JOIN, 1, this.key(room, 'cursors'), clientId, lastId, this.ttlSec);
60
+ }
61
+ async ack(room, clientId, lastId) {
62
+ await this.redis.eval(ACK, 2, this.key(room, 'cursors'), this.key(room, 'events'), clientId, lastId, this.ttlSec);
63
+ }
64
+ async leave(room, clientId) {
65
+ await this.redis.eval(LEAVE, 2, this.key(room, 'cursors'), this.key(room, 'events'), clientId);
66
+ }
67
+ async drop(room) {
68
+ await this.redis.del(this.key(room, 'seq'), this.key(room, 'events'), this.key(room, 'cursors'));
69
+ }
70
+ }
71
+ exports.RedisSseEventLog = RedisSseEventLog;
@@ -0,0 +1,45 @@
1
+ import type { SseClientId, SseRoomId } from './sse-server.types';
2
+ export interface SseLoggedEvent<Type extends string = string, Data extends object = object> {
3
+ /** The event's number in its room, starting from 1. Goes out as the SSE `id:` field. */
4
+ id: number;
5
+ type: Type;
6
+ data: Data;
7
+ }
8
+ /**
9
+ * Where a room's events wait until every client of the room has acked them. An event stays until
10
+ * the lowest cursor among the room's clients passes it, so one client's ack never takes an event
11
+ * from another. `historySize` bounds a room whose client never acks.
12
+ */
13
+ export interface SseEventLog {
14
+ /** Numbers the event and keeps it. Numbers grow by one per room and are never reused. */
15
+ append<Type extends string, Data extends object>(room: SseRoomId, type: Type, data: Data): Promise<SseLoggedEvent<Type, Data>>;
16
+ /** The events with `id > afterId`, oldest first. */
17
+ read(room: SseRoomId, afterId: number, limit: number): Promise<SseLoggedEvent[]>;
18
+ /** Starts holding events for the client, from `lastId`. A known client keeps its cursor. */
19
+ join(room: SseRoomId, clientId: SseClientId, lastId: number): Promise<void>;
20
+ /** Cumulative: everything up to `lastId` is delivered. A cursor only moves forward. */
21
+ ack(room: SseRoomId, clientId: SseClientId, lastId: number): Promise<void>;
22
+ /** The client is gone for good: its cursor stops holding events. */
23
+ leave(room: SseRoomId, clientId: SseClientId): Promise<void>;
24
+ /** Forgets the room: its events, cursors and numbering. */
25
+ drop(room: SseRoomId): Promise<void>;
26
+ }
27
+ export declare const SSE_DEFAULT_HISTORY_SIZE = 300;
28
+ export interface InMemorySseEventLogOptions {
29
+ /** The most events a room keeps; the oldest go first. Default 300. */
30
+ historySize?: number;
31
+ }
32
+ /** For tests and one-instance setups: everything is lost on restart. */
33
+ export declare class InMemorySseEventLog implements SseEventLog {
34
+ private readonly options;
35
+ private readonly rooms;
36
+ constructor(options?: InMemorySseEventLogOptions);
37
+ private room;
38
+ private trim;
39
+ append<Type extends string, Data extends object>(roomId: SseRoomId, type: Type, data: Data): Promise<SseLoggedEvent<Type, Data>>;
40
+ read(roomId: SseRoomId, afterId: number, limit: number): Promise<SseLoggedEvent<string, object>[]>;
41
+ join(roomId: SseRoomId, clientId: SseClientId, lastId: number): Promise<void>;
42
+ ack(roomId: SseRoomId, clientId: SseClientId, lastId: number): Promise<void>;
43
+ leave(roomId: SseRoomId, clientId: SseClientId): Promise<void>;
44
+ drop(roomId: SseRoomId): Promise<void>;
45
+ }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InMemorySseEventLog = exports.SSE_DEFAULT_HISTORY_SIZE = void 0;
4
+ exports.SSE_DEFAULT_HISTORY_SIZE = 300;
5
+ /** For tests and one-instance setups: everything is lost on restart. */
6
+ class InMemorySseEventLog {
7
+ constructor(options = {}) {
8
+ this.options = options;
9
+ this.rooms = new Map();
10
+ }
11
+ room(id) {
12
+ let room = this.rooms.get(id);
13
+ if (!room) {
14
+ room = { seq: 0, events: [], cursors: new Map() };
15
+ this.rooms.set(id, room);
16
+ }
17
+ return room;
18
+ }
19
+ trim(room) {
20
+ if (!room.cursors.size)
21
+ return;
22
+ const lowest = Math.min(...room.cursors.values());
23
+ room.events = room.events.filter(({ id }) => id > lowest);
24
+ }
25
+ async append(roomId, type, data) {
26
+ const room = this.room(roomId);
27
+ const event = { id: ++room.seq, type, data };
28
+ room.events.push(event);
29
+ const excess = room.events.length -
30
+ (this.options.historySize ?? exports.SSE_DEFAULT_HISTORY_SIZE);
31
+ if (excess > 0)
32
+ room.events.splice(0, excess);
33
+ return event;
34
+ }
35
+ async read(roomId, afterId, limit) {
36
+ return this.room(roomId)
37
+ .events.filter(({ id }) => id > afterId)
38
+ .slice(0, limit);
39
+ }
40
+ async join(roomId, clientId, lastId) {
41
+ const { cursors } = this.room(roomId);
42
+ if (!cursors.has(clientId))
43
+ cursors.set(clientId, lastId);
44
+ }
45
+ async ack(roomId, clientId, lastId) {
46
+ const room = this.room(roomId);
47
+ room.cursors.set(clientId, Math.max(room.cursors.get(clientId) ?? 0, lastId));
48
+ this.trim(room);
49
+ }
50
+ async leave(roomId, clientId) {
51
+ const room = this.room(roomId);
52
+ room.cursors.delete(clientId);
53
+ this.trim(room);
54
+ }
55
+ async drop(roomId) {
56
+ this.rooms.delete(roomId);
57
+ }
58
+ }
59
+ exports.InMemorySseEventLog = InMemorySseEventLog;
@@ -0,0 +1,63 @@
1
+ import { MessageEvent, OnModuleDestroy } from '@nestjs/common';
2
+ import { Observable } from 'rxjs';
3
+ import type { SseEventLog, SseLoggedEvent } from './sse-event-log';
4
+ import { SseClientId, SseRoomId } from './sse-server.types';
5
+ export interface SseRoomStreamOptions {
6
+ /** Where events wait until acked: `InMemorySseEventLog`, `RedisSseEventLog` or the app's own. */
7
+ log: SseEventLog;
8
+ /** How often an open connection hears `connection:heartbeat`. `0` turns it off. Default 25 s. */
9
+ heartbeatMs?: number;
10
+ /** Events a client gets whatever its filter says. */
11
+ requiredEvents?: readonly string[];
12
+ }
13
+ export interface SseRoomConnectOptions {
14
+ /** The events this client wants; none: all of them. `requiredEvents` are always added. */
15
+ events?: readonly string[];
16
+ /** The last event the client saw: the `Last-Event-ID` header, or a query value on first connect. */
17
+ lastEventId?: number;
18
+ }
19
+ /**
20
+ * One connection per client of a room, with what it missed replayed on reconnect. Works alongside
21
+ * `SseServer` and does not replace it: `SseServer` keeps one stream per client over any number of
22
+ * rooms, which leaves no single numbering for `Last-Event-ID`.
23
+ *
24
+ * On the wire `MessageEvent.type` is `message` or `connection`, `data.type` is the event's name, and
25
+ * `MessageEvent.id` is the event's number. A second connection of one client replaces the first, so
26
+ * derive `clientId` on the server or authenticate it, or any caller can close someone's stream.
27
+ * Delivery stays within this process.
28
+ *
29
+ * ```ts
30
+ * @Sse('events')
31
+ * events(@Query() q: EventsQuery, @Headers('last-event-id') lastId?: string) {
32
+ * return this.stream.connect(q.room, q.clientId, { lastEventId: Number(lastId) });
33
+ * }
34
+ * ```
35
+ */
36
+ export declare class SseRoomStream<M extends object = Record<string, object>> implements OnModuleDestroy {
37
+ private readonly options;
38
+ private readonly rooms;
39
+ constructor(options: SseRoomStreamOptions);
40
+ /** Numbers the event, keeps it until acked and delivers it to the room's connected clients. */
41
+ emit<Type extends keyof M & string>(room: SseRoomId, type: Type, data: M[Type]): Promise<number>;
42
+ /** Only for the clients connected now: no number of its own, nothing kept. */
43
+ emitVolatile<Type extends keyof M & string>(room: SseRoomId, type: Type, data: M[Type]): void;
44
+ /** Cumulative: everything up to `lastId` is delivered to this client. */
45
+ ack(room: SseRoomId, clientId: SseClientId, lastId: number): Promise<void>;
46
+ /** What is kept after `afterId`. */
47
+ replay(room: SseRoomId, afterId: number): AsyncIterable<SseLoggedEvent>;
48
+ /** A live client's new filter, no reconnect needed. */
49
+ setSubscription(room: SseRoomId, clientId: SseClientId, events?: readonly string[]): void;
50
+ /** What was not acked first, then the live events. */
51
+ connect(room: SseRoomId, clientId: SseClientId, { events, lastEventId }?: SseRoomConnectOptions): Observable<MessageEvent>;
52
+ /** The client is gone for good: closes its connection and stops holding events for it. */
53
+ leave(room: SseRoomId, clientId: SseClientId): Promise<void>;
54
+ /** Closes the room's connections and forgets its events. */
55
+ dropRoom(room: SseRoomId): Promise<void>;
56
+ onModuleDestroy(): void;
57
+ private catchUp;
58
+ private deliver;
59
+ private close;
60
+ private wants;
61
+ private toFilter;
62
+ private send;
63
+ }
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SseRoomStream = void 0;
4
+ const rxjs_1 = require("rxjs");
5
+ const sse_server_types_1 = require("./sse-server.types");
6
+ const REPLAY_PAGE = 500;
7
+ const DEFAULT_HEARTBEAT_MS = 25_000;
8
+ /**
9
+ * One connection per client of a room, with what it missed replayed on reconnect. Works alongside
10
+ * `SseServer` and does not replace it: `SseServer` keeps one stream per client over any number of
11
+ * rooms, which leaves no single numbering for `Last-Event-ID`.
12
+ *
13
+ * On the wire `MessageEvent.type` is `message` or `connection`, `data.type` is the event's name, and
14
+ * `MessageEvent.id` is the event's number. A second connection of one client replaces the first, so
15
+ * derive `clientId` on the server or authenticate it, or any caller can close someone's stream.
16
+ * Delivery stays within this process.
17
+ *
18
+ * ```ts
19
+ * @Sse('events')
20
+ * events(@Query() q: EventsQuery, @Headers('last-event-id') lastId?: string) {
21
+ * return this.stream.connect(q.room, q.clientId, { lastEventId: Number(lastId) });
22
+ * }
23
+ * ```
24
+ */
25
+ class SseRoomStream {
26
+ constructor(options) {
27
+ this.options = options;
28
+ this.rooms = new Map();
29
+ }
30
+ /** Numbers the event, keeps it until acked and delivers it to the room's connected clients. */
31
+ async emit(room, type, data) {
32
+ const event = await this.options.log.append(room, type, data);
33
+ for (const client of this.rooms.get(room)?.values() ?? []) {
34
+ if (client.replaying)
35
+ client.replaying.push(event);
36
+ else
37
+ this.deliver(client, event);
38
+ }
39
+ return event.id;
40
+ }
41
+ /** Only for the clients connected now: no number of its own, nothing kept. */
42
+ emitVolatile(room, type, data) {
43
+ for (const client of this.rooms.get(room)?.values() ?? []) {
44
+ if (this.wants(client, type)) {
45
+ this.send(client, 'message', type, data);
46
+ }
47
+ }
48
+ }
49
+ /** Cumulative: everything up to `lastId` is delivered to this client. */
50
+ ack(room, clientId, lastId) {
51
+ return this.options.log.ack(room, clientId, lastId);
52
+ }
53
+ /** What is kept after `afterId`. */
54
+ async *replay(room, afterId) {
55
+ let after = afterId;
56
+ for (;;) {
57
+ const page = await this.options.log.read(room, after, REPLAY_PAGE);
58
+ for (const event of page) {
59
+ after = event.id;
60
+ yield event;
61
+ }
62
+ if (page.length < REPLAY_PAGE)
63
+ return;
64
+ }
65
+ }
66
+ /** A live client's new filter, no reconnect needed. */
67
+ setSubscription(room, clientId, events) {
68
+ const client = this.rooms.get(room)?.get(clientId);
69
+ if (client)
70
+ client.events = this.toFilter(events);
71
+ }
72
+ /** What was not acked first, then the live events. */
73
+ connect(room, clientId, { events, lastEventId } = {}) {
74
+ const lastId = Number.isSafeInteger(lastEventId) && lastEventId > 0 ? lastEventId : 0;
75
+ return new rxjs_1.Observable((subscriber) => {
76
+ // The old connection first: its teardown may remove the room.
77
+ this.rooms.get(room)?.get(clientId)?.subscriber.complete();
78
+ let clients = this.rooms.get(room);
79
+ if (!clients)
80
+ this.rooms.set(room, (clients = new Map()));
81
+ const client = {
82
+ events: this.toFilter(events),
83
+ subscriber,
84
+ lastId,
85
+ replaying: [],
86
+ };
87
+ const heartbeatMs = this.options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
88
+ if (heartbeatMs > 0) {
89
+ client.heartbeat = setInterval(() => this.send(client, 'connection', sse_server_types_1.SseReservedEventEnum.connection_heartbeat, { at: new Date().toISOString() }), heartbeatMs);
90
+ client.heartbeat.unref();
91
+ }
92
+ clients.set(clientId, client);
93
+ this.send(client, 'connection', sse_server_types_1.SseReservedEventEnum.connection_open, {
94
+ clientId,
95
+ events: client.events && [...client.events],
96
+ });
97
+ void this.catchUp(room, clientId, client);
98
+ return () => {
99
+ clearInterval(client.heartbeat);
100
+ if (clients.get(clientId) === client)
101
+ clients.delete(clientId);
102
+ if (!clients.size && this.rooms.get(room) === clients) {
103
+ this.rooms.delete(room);
104
+ }
105
+ };
106
+ });
107
+ }
108
+ /** The client is gone for good: closes its connection and stops holding events for it. */
109
+ async leave(room, clientId) {
110
+ const client = this.rooms.get(room)?.get(clientId);
111
+ if (client)
112
+ this.close(client);
113
+ await this.options.log.leave(room, clientId);
114
+ }
115
+ /** Closes the room's connections and forgets its events. */
116
+ async dropRoom(room) {
117
+ for (const client of [...(this.rooms.get(room)?.values() ?? [])]) {
118
+ this.close(client);
119
+ }
120
+ await this.options.log.drop(room);
121
+ }
122
+ onModuleDestroy() {
123
+ for (const clients of [...this.rooms.values()]) {
124
+ for (const client of [...clients.values()])
125
+ this.close(client);
126
+ }
127
+ }
128
+ async catchUp(room, clientId, client) {
129
+ try {
130
+ await this.options.log.join(room, clientId, client.lastId);
131
+ for await (const event of this.replay(room, client.lastId)) {
132
+ if (client.subscriber.closed)
133
+ return;
134
+ this.deliver(client, event);
135
+ }
136
+ }
137
+ catch (e) {
138
+ this.send(client, 'connection', sse_server_types_1.SseReservedEventEnum.connection_error, {
139
+ message: e instanceof Error ? e.message : String(e),
140
+ });
141
+ }
142
+ for (const event of client.replaying ?? [])
143
+ this.deliver(client, event);
144
+ client.replaying = null;
145
+ }
146
+ deliver(client, event) {
147
+ if (event.id <= client.lastId)
148
+ return;
149
+ client.lastId = event.id;
150
+ if (this.wants(client, event.type)) {
151
+ this.send(client, 'message', event.type, event.data);
152
+ }
153
+ }
154
+ close(client) {
155
+ this.send(client, 'connection', sse_server_types_1.SseReservedEventEnum.connection_closed, {});
156
+ client.subscriber.complete();
157
+ }
158
+ wants(client, type) {
159
+ return !client.events || client.events.has(type);
160
+ }
161
+ toFilter(events) {
162
+ return events
163
+ ? new Set([...events, ...(this.options.requiredEvents ?? [])])
164
+ : null;
165
+ }
166
+ // Nest numbers an event with no id by itself, which would overwrite the client's Last-Event-ID:
167
+ // whatever has no number of its own repeats the last real one.
168
+ send(client, wireType, type, data) {
169
+ client.subscriber.next({
170
+ id: String(client.lastId),
171
+ type: wireType,
172
+ data: { ...data, type },
173
+ });
174
+ }
175
+ }
176
+ exports.SseRoomStream = SseRoomStream;
@@ -0,0 +1,127 @@
1
+ import { DynamicModule, Logger, MessageEvent as NestMessageEvent, MiddlewareConsumer, NestMiddleware, NestModule, OnModuleDestroy } from '@nestjs/common';
2
+ import { Observable, Subject } from 'rxjs';
3
+ import { RedisService } from '@my-nestjs-kit/core';
4
+ import { SseClientId, SseEvent, SseEventsMapBase, SseHeaderEnum, SseHttpRequest, SseHttpResponse, SseNextFn, SseRoom, SseRoomId, SseServerChannel, SseServerMessage } from './sse-server.types';
5
+ export declare const sseClientIdHeader = SseHeaderEnum.sseClientId;
6
+ export interface SseServerOptions<ServerEventsMap extends SseEventsMapBase> {
7
+ /** Resolves the client id before the defaults (cookie → `?deviceId` → random), e.g. from the auth session. */
8
+ getTracker?: (req: SseHttpRequest) => string | undefined;
9
+ retryTimeout?: number;
10
+ /** @deprecated Has no effect: `SseServer` keeps no history. For replay use `SseRoomStream`. */
11
+ historySize?: number;
12
+ /** How often, in ms, every client hears `connection:heartbeat`. Off unless set. */
13
+ pingInterval?: number;
14
+ jsonEncode?: boolean;
15
+ onInit?: () => void;
16
+ handleConnection?: (client: SseClient<ServerEventsMap>) => void;
17
+ handleDisconnect?: (client: SseClient<ServerEventsMap>) => void;
18
+ adapter?: SseServerAdapterBase<ServerEventsMap>;
19
+ }
20
+ export declare abstract class SseServerStoreBase {
21
+ constructor();
22
+ abstract set(key: string, value: any): Promise<boolean>;
23
+ abstract get<V>(key: string): Promise<V>;
24
+ abstract del(key: string): Promise<boolean>;
25
+ }
26
+ export declare abstract class SseServerAdapterBase<ServerEventsMap extends SseEventsMapBase = SseEventsMapBase> implements Pick<SseServer, 'join' | 'leave'> {
27
+ readonly server: SseServer;
28
+ readonly store?: SseServerStoreBase;
29
+ constructor(server: SseServer, store?: SseServerStoreBase);
30
+ abstract join(client: SseClient<ServerEventsMap>, ...roomIds: SseRoomId[]): Promise<void>;
31
+ abstract leave(clientId: SseClientId, ...roomIds: SseRoomId[]): Promise<void>;
32
+ }
33
+ export declare class SseTestAdapter extends SseServerAdapterBase {
34
+ readonly server: SseServer;
35
+ readonly redis: RedisService;
36
+ private readonly _rooms;
37
+ constructor(server: SseServer, redis: RedisService);
38
+ private readonly normalizeKey;
39
+ join(client: SseClient<SseEventsMapBase>, roomId: SseRoomId): Promise<void>;
40
+ leave(clientId: SseClientId, ...roomIds: string[]): Promise<void>;
41
+ }
42
+ export declare class SseServer<ServerEventsMap extends SseEventsMapBase = SseEventsMapBase> implements OnModuleDestroy {
43
+ protected readonly channel?: SseServerChannel;
44
+ _clients: Map<SseClientId, SseClient<ServerEventsMap>>;
45
+ _rooms: Map<SseRoomId | SseClientId, SseRoom>;
46
+ private _toRoomKey;
47
+ private pingIntervalId?;
48
+ private options;
49
+ private readonly _logger;
50
+ constructor(channel?: SseServerChannel, options?: SseServerOptions<ServerEventsMap>);
51
+ /** Default client id: `Sse-Client-Id` cookie → `?deviceId` → random. */
52
+ static getTracker(req: SseHttpRequest): string;
53
+ /**
54
+ * Client id: the app's `options.getTracker` (server-side, e.g. auth session) wins;
55
+ * the client-supplied cookie / `?deviceId` are only fallbacks and never override it.
56
+ */
57
+ getTracker(req: SseHttpRequest): string;
58
+ static setTracker(res: SseHttpResponse, clientId: string): void;
59
+ static setHeaders(): void;
60
+ onModuleDestroy(): void;
61
+ kill(): void;
62
+ deleteRoom(roomId: SseRoomId): Promise<boolean>;
63
+ createRoom(roomId: SseRoomId): SseRoom;
64
+ leave(clientId: SseClientId, ...roomIds: SseRoomId[]): void;
65
+ leaveAll(tracker: SseClientId): void;
66
+ isClientInRoom(clientId: SseClientId, roomId: SseRoomId): boolean;
67
+ getRoom(roomId: SseRoomId): SseRoom;
68
+ join(client: SseClient<ServerEventsMap>, ...roomIds: SseRoomId[]): void;
69
+ to<EventName extends keyof ServerEventsMap & string>(roomId: SseRoomId, event: SseEvent<ServerEventsMap, EventName>): void;
70
+ broadcast<EventName extends keyof ServerEventsMap & string>(clientId: SseClientId, event: ServerEventsMap[EventName], ...roomIds: SseRoomId[]): void;
71
+ getClient(id: SseClientId): SseClient<ServerEventsMap>;
72
+ subscribe(req: SseHttpRequest, res: SseHttpResponse): Promise<Observable<NestMessageEvent>>;
73
+ connect: (req: SseHttpRequest, res: SseHttpResponse) => Promise<SseClient<ServerEventsMap> | undefined>;
74
+ disconnect: (clientId: SseClientId, cb?: SseNextFn) => Promise<void>;
75
+ isConnected: (req: SseHttpRequest, res: SseHttpResponse) => string;
76
+ private _removeClientFromRoom;
77
+ }
78
+ export declare class SseClient<SEventsDict extends SseEventsMapBase = SseEventsMapBase> {
79
+ readonly req: SseHttpRequest;
80
+ readonly res: SseHttpResponse;
81
+ userId?: string;
82
+ deviceId?: string;
83
+ id: string;
84
+ private readonly _logger;
85
+ private readonly _connection;
86
+ private readonly _subject;
87
+ private readonly _server;
88
+ private _retry;
89
+ constructor(req: SseHttpRequest, res: SseHttpResponse, server: SseServer<SEventsDict>);
90
+ get conn(): SseHttpResponse;
91
+ get sbj(): Subject<NestMessageEvent>;
92
+ get logger(): Logger;
93
+ join(...roomId: SseRoomId[]): void;
94
+ leave(...roomId: SseRoomId[]): void;
95
+ getRoom(roomId: SseRoomId): SseRoom;
96
+ isInRoom(roomId: SseRoomId): boolean;
97
+ leaveAll(): void;
98
+ send: (message: SseServerMessage) => {
99
+ result: boolean;
100
+ idRes: boolean;
101
+ eventRes: boolean;
102
+ dataRes: boolean;
103
+ error?: undefined;
104
+ } | {
105
+ result: boolean;
106
+ error: any;
107
+ idRes?: undefined;
108
+ eventRes?: undefined;
109
+ dataRes?: undefined;
110
+ };
111
+ emit<EType extends keyof SEventsDict = keyof SEventsDict>(type: EType, data: SEventsDict[EType]): void;
112
+ disconnect: (cb?: () => void) => Promise<void>;
113
+ }
114
+ export declare class SseHeaderMiddleware implements NestMiddleware {
115
+ private readonly _logger;
116
+ use(req: SseHttpRequest, res: SseHttpResponse, next: SseNextFn): void;
117
+ }
118
+ export type SseModuleOptions = {
119
+ /** Routes the `Sse-Client-Id` cookie middleware applies to. */
120
+ path: string;
121
+ };
122
+ export declare class SseRoutesModule implements NestModule {
123
+ private readonly options;
124
+ constructor(options: SseModuleOptions);
125
+ static forRoot(options: SseModuleOptions): DynamicModule;
126
+ configure(consumer: MiddlewareConsumer): void;
127
+ }
@@ -0,0 +1,377 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var SseHeaderMiddleware_1, SseRoutesModule_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.SseRoutesModule = exports.SseHeaderMiddleware = exports.SseClient = exports.SseServer = exports.SseTestAdapter = exports.SseServerAdapterBase = exports.SseServerStoreBase = exports.sseClientIdHeader = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const core_1 = require("@my-nestjs-kit/core");
19
+ const rxjs_1 = require("rxjs");
20
+ const core_2 = require("@my-nestjs-kit/core");
21
+ const sse_server_types_1 = require("./sse-server.types");
22
+ const { randomUUID } = crypto;
23
+ const { connection_open, connection_heartbeat, connection_error, connection_closed, } = sse_server_types_1.SseReservedEventEnum;
24
+ exports.sseClientIdHeader = sse_server_types_1.SseHeaderEnum.sseClientId;
25
+ class SseServerStoreBase {
26
+ constructor() { }
27
+ }
28
+ exports.SseServerStoreBase = SseServerStoreBase;
29
+ class SseServerAdapterBase {
30
+ constructor(server, store) {
31
+ this.server = server;
32
+ this.store = store;
33
+ }
34
+ }
35
+ exports.SseServerAdapterBase = SseServerAdapterBase;
36
+ class SseTestAdapter extends SseServerAdapterBase {
37
+ constructor(server, redis) {
38
+ super(server);
39
+ this.server = server;
40
+ this.redis = redis;
41
+ this.normalizeKey = (key) => key.startsWith('room') ? key : `room:${key}`;
42
+ this._rooms = new core_2.SetStorageAsync(redis.redis, { name: 'room' });
43
+ }
44
+ async join(client, roomId) {
45
+ await this._rooms.add(roomId, client.id);
46
+ }
47
+ async leave(clientId, ...roomIds) {
48
+ await Promise.all(roomIds.map((rId) => this._rooms.remove(this.normalizeKey(rId), clientId)));
49
+ }
50
+ }
51
+ exports.SseTestAdapter = SseTestAdapter;
52
+ class SseServer {
53
+ constructor(channel, options = {}) {
54
+ this.channel = channel;
55
+ this._toRoomKey = (roomId) => roomId.startsWith('room') ? roomId : `room:${roomId}`;
56
+ this._logger = new common_1.Logger(this.constructor.name);
57
+ this.connect = async (req, res) => {
58
+ const existId = this.isConnected(req, res);
59
+ if (existId) {
60
+ return this.getClient(existId);
61
+ }
62
+ const client = new SseClient(req, res, this);
63
+ // ! Connect client
64
+ this._clients.set(client.id, client);
65
+ // add to personal room
66
+ this.join(client, client.id);
67
+ client.emit(sse_server_types_1.SseReservedEventEnum.connection_open, {
68
+ message: 'Connected',
69
+ });
70
+ return client;
71
+ };
72
+ this.disconnect = async (clientId, cb) => {
73
+ const client = this.getClient(clientId);
74
+ if (!client) {
75
+ if (cb)
76
+ cb(new core_1.AppHttpException({
77
+ message: 'Client not found',
78
+ meta: { clientId: client.id },
79
+ }));
80
+ return;
81
+ }
82
+ this._logger.debug('Client will be disconnected');
83
+ client?.sbj.complete();
84
+ this.leaveAll(clientId);
85
+ this._clients.delete(clientId);
86
+ this._logger.debug('Client was disconnected');
87
+ };
88
+ this.isConnected = (req, res) => {
89
+ const tracker = this.getTracker(req);
90
+ return this._clients.has(tracker) ? tracker : '';
91
+ };
92
+ this._rooms = new Map();
93
+ this._clients = new Map();
94
+ this.options = {
95
+ retryTimeout: 250,
96
+ jsonEncode: true,
97
+ ...options,
98
+ };
99
+ if (this.options.pingInterval) {
100
+ this.pingIntervalId = setInterval(() => {
101
+ this._clients.forEach((client) => client.emit(connection_heartbeat, {
102
+ message: 'Heartbeat',
103
+ }));
104
+ }, this.options.pingInterval);
105
+ this.pingIntervalId.unref();
106
+ }
107
+ if (this.options.onInit) {
108
+ this.options.onInit();
109
+ }
110
+ }
111
+ /** Default client id: `Sse-Client-Id` cookie → `?deviceId` → random. */
112
+ static getTracker(req) {
113
+ return (req.cookies?.[exports.sseClientIdHeader] ||
114
+ req.query?.deviceId ||
115
+ `undefined_${randomUUID()}`);
116
+ }
117
+ /**
118
+ * Client id: the app's `options.getTracker` (server-side, e.g. auth session) wins;
119
+ * the client-supplied cookie / `?deviceId` are only fallbacks and never override it.
120
+ */
121
+ getTracker(req) {
122
+ return this.options.getTracker?.(req) || SseServer.getTracker(req);
123
+ }
124
+ static setTracker(res, clientId) {
125
+ res.cookie(exports.sseClientIdHeader, clientId);
126
+ res.setHeader(sse_server_types_1.SseHeaderEnum.accessAllowOrigin, '*');
127
+ }
128
+ static setHeaders() { }
129
+ onModuleDestroy() {
130
+ this.kill();
131
+ }
132
+ kill() {
133
+ clearInterval(this.pingIntervalId);
134
+ this._clients.forEach((client) => {
135
+ client.emit(connection_closed, { message: 'Closed' });
136
+ client.sbj.complete(); // Завершити всі Subject
137
+ });
138
+ this._clients.clear(); // Очистити карту
139
+ }
140
+ async deleteRoom(roomId) {
141
+ if (this.options.adapter) {
142
+ return;
143
+ }
144
+ const roomKey = this._toRoomKey(roomId);
145
+ if (this._rooms.has(roomKey)) {
146
+ const room = await this.getRoom(roomId);
147
+ if (room) {
148
+ room.forEach((clientId) => {
149
+ this._removeClientFromRoom(clientId, roomId);
150
+ });
151
+ }
152
+ return this._rooms.delete(roomKey);
153
+ }
154
+ return false;
155
+ }
156
+ createRoom(roomId) {
157
+ const roomKey = this._toRoomKey(roomId);
158
+ if (!this._rooms.has(roomKey)) {
159
+ this._rooms.set(roomKey, new Set()); // TODO redis set
160
+ }
161
+ return this._rooms.get(roomKey);
162
+ }
163
+ leave(clientId, ...roomIds) {
164
+ roomIds.forEach((id) => this._removeClientFromRoom(clientId, id));
165
+ }
166
+ leaveAll(tracker) {
167
+ for (const [roomId, room] of Array.from(this._rooms.entries())) {
168
+ room.delete(tracker);
169
+ if (room.size === 0)
170
+ this._rooms.delete(roomId);
171
+ }
172
+ }
173
+ isClientInRoom(clientId, roomId) {
174
+ const roomKey = this._toRoomKey(roomId);
175
+ const room = this._rooms.get(roomKey);
176
+ return room ? room.has(clientId) : false;
177
+ }
178
+ getRoom(roomId) {
179
+ const roomKey = this._toRoomKey(roomId);
180
+ return this._rooms.get(roomKey);
181
+ }
182
+ join(client, ...roomIds) {
183
+ for (const roomId of roomIds) {
184
+ const room = this.createRoom(roomId);
185
+ room?.add(client.id);
186
+ }
187
+ }
188
+ to(roomId, event) {
189
+ const clientsInRoom = this._rooms.get(roomId);
190
+ if (clientsInRoom) {
191
+ clientsInRoom.forEach((clientId) => {
192
+ const client = this.getClient(clientId);
193
+ if (clientId === client.id)
194
+ return;
195
+ client?.emit(event.type, event.data);
196
+ });
197
+ }
198
+ }
199
+ broadcast(clientId, event, ...roomIds) {
200
+ const clientRoom = this.getRoom(clientId);
201
+ clientRoom.forEach((currentId) => {
202
+ if (clientId === currentId)
203
+ return;
204
+ const current = this.getClient(currentId);
205
+ current.emit(event.type, event.data);
206
+ });
207
+ for (const roomId of roomIds) {
208
+ this.getRoom(roomId).forEach((currentId) => {
209
+ if (clientId === currentId)
210
+ return;
211
+ const current = this.getClient(currentId);
212
+ current.emit(event.type, event.data);
213
+ });
214
+ }
215
+ }
216
+ getClient(id) {
217
+ return this._clients.get(id);
218
+ }
219
+ async subscribe(req, res) {
220
+ const tracker = this.getTracker(req);
221
+ if (!this._clients.has(tracker)) {
222
+ const client = new SseClient(req, res, this);
223
+ this._clients.set(client.id, client);
224
+ client.emit(connection_open, {
225
+ data: { connectionId: client.id },
226
+ });
227
+ res.on('close', async () => {
228
+ try {
229
+ await this.disconnect(client.id);
230
+ }
231
+ catch (err) {
232
+ console.log(`Error to disconnect user on close SSE connection, ClientId ${client.id}`);
233
+ }
234
+ });
235
+ // todo fix types or delete
236
+ await this.channel?.message(connection_open, {
237
+ message: 'Test channel message',
238
+ type: 'message',
239
+ data: {},
240
+ });
241
+ return client.sbj?.asObservable();
242
+ }
243
+ return this._clients.get(tracker).sbj.asObservable();
244
+ }
245
+ _removeClientFromRoom(clientId, roomId) {
246
+ const room = this.getRoom(roomId);
247
+ if (!room)
248
+ return;
249
+ room.delete(clientId);
250
+ if (room.size === 0) {
251
+ this._rooms.delete(roomId);
252
+ }
253
+ }
254
+ }
255
+ exports.SseServer = SseServer;
256
+ class SseClient {
257
+ // Метод для додавання кімнати
258
+ constructor(req, res, server) {
259
+ this.req = req;
260
+ this.res = res;
261
+ this._retry = 1500;
262
+ this.send = (message) => {
263
+ // todo deprecated
264
+ try {
265
+ const idRes = this._connection.write(`id: ${this.id}\n`);
266
+ const eventRes = this._connection.write(`retry: ${this._retry}\n`);
267
+ const dataRes = this._connection.write(`data: ${JSON.stringify(message)}\n\n`);
268
+ return { result: true, idRes, eventRes, dataRes };
269
+ }
270
+ catch (e) {
271
+ this._logger.error('Send message error');
272
+ console.log({ id: this.id, error: e });
273
+ return { result: false, error: e };
274
+ }
275
+ };
276
+ this.disconnect = async (cb) => {
277
+ await this._server.disconnect(this.id, cb);
278
+ };
279
+ this.id = server.getTracker(req);
280
+ this._connection = res;
281
+ this._subject = new rxjs_1.Subject();
282
+ this._server = server;
283
+ this._logger = new common_1.Logger(`[ Client: ${this.id}]`);
284
+ }
285
+ get conn() {
286
+ return this._connection;
287
+ }
288
+ get sbj() {
289
+ return this._subject;
290
+ }
291
+ get logger() {
292
+ return this._logger;
293
+ }
294
+ join(...roomId) {
295
+ this._server.join(this, ...roomId);
296
+ }
297
+ // Видалення клієнта з певної кімнати
298
+ leave(...roomId) {
299
+ roomId.forEach((id) => {
300
+ this._server.leave(this.id, id);
301
+ });
302
+ }
303
+ // Метод для отримання кімнати
304
+ getRoom(roomId) {
305
+ return this._server._rooms.get(roomId);
306
+ }
307
+ isInRoom(roomId) {
308
+ return this._server.isClientInRoom(this.id, roomId);
309
+ }
310
+ // Видалення клієнта з усіх кімнат
311
+ leaveAll() {
312
+ this._server.leaveAll(this.id);
313
+ }
314
+ // TODO(sse-event-id): give every event its own `id` — a per-room / per-client sequence number, sent
315
+ // as the SSE `id:` field (MessageEvent.id). Needed for delivery acks and `Last-Event-ID` replay
316
+ // after a reconnect (keep unacked events in Redis, a ZSET by id). Today `id:` is only written by
317
+ // the deprecated `send`, and it is the client id, not the event's.
318
+ emit(type, data) {
319
+ return this._subject.next(new MessageEvent(type, { data: { ...data, type } }));
320
+ }
321
+ }
322
+ exports.SseClient = SseClient;
323
+ let SseHeaderMiddleware = SseHeaderMiddleware_1 = class SseHeaderMiddleware {
324
+ constructor() {
325
+ this._logger = new common_1.Logger('SSE' + ' ' + SseHeaderMiddleware_1.name);
326
+ }
327
+ use(req, res, next) {
328
+ if (!req.url.includes('/sse')) {
329
+ return next();
330
+ }
331
+ const connectionId = SseServer.getTracker(req);
332
+ res.cookie(exports.sseClientIdHeader, connectionId);
333
+ res.setHeader(sse_server_types_1.SseHeaderEnum.accessAllowOrigin, '*');
334
+ this._logger.debug(exports.sseClientIdHeader, { connectionId });
335
+ next();
336
+ }
337
+ };
338
+ exports.SseHeaderMiddleware = SseHeaderMiddleware;
339
+ exports.SseHeaderMiddleware = SseHeaderMiddleware = SseHeaderMiddleware_1 = __decorate([
340
+ (0, common_1.Injectable)()
341
+ ], SseHeaderMiddleware);
342
+ const SSE_MODULE_OPTIONS = 'SSE_MODULE_OPTIONS';
343
+ let SseRoutesModule = SseRoutesModule_1 = class SseRoutesModule {
344
+ constructor(options) {
345
+ this.options = options;
346
+ }
347
+ static forRoot(options) {
348
+ return {
349
+ module: SseRoutesModule_1,
350
+ providers: [
351
+ {
352
+ provide: SSE_MODULE_OPTIONS,
353
+ useValue: options,
354
+ },
355
+ ],
356
+ exports: [SSE_MODULE_OPTIONS],
357
+ };
358
+ }
359
+ configure(consumer) {
360
+ consumer
361
+ .apply(SseHeaderMiddleware)
362
+ .forRoutes(this.options.path);
363
+ }
364
+ };
365
+ exports.SseRoutesModule = SseRoutesModule;
366
+ exports.SseRoutesModule = SseRoutesModule = SseRoutesModule_1 = __decorate([
367
+ (0, common_1.Module)({
368
+ providers: [
369
+ {
370
+ provide: SSE_MODULE_OPTIONS,
371
+ useValue: {},
372
+ },
373
+ ],
374
+ }),
375
+ __param(0, (0, common_1.Inject)(SSE_MODULE_OPTIONS)),
376
+ __metadata("design:paramtypes", [Object])
377
+ ], SseRoutesModule);
@@ -0,0 +1,48 @@
1
+ import type { NextFunction, Request, Response } from 'express';
2
+ export type SseClientId = string;
3
+ export type SseRoomId = string;
4
+ export type SseRoom = Set<SseClientId>;
5
+ export declare enum SseHeaderEnum {
6
+ contentType = "Content-Type",
7
+ cacheControl = "Cache-Control",
8
+ connection = "Connection",
9
+ sseClientId = "Sse-Client-Id",
10
+ accessAllowOrigin = "Access-Allow-Origin"
11
+ }
12
+ /** Reserved SSE event names sent to clients — wire names, do not rename. */
13
+ export declare enum SseReservedEventEnum {
14
+ connection_ping = "connection:ping",
15
+ connection_heartbeat = "connection:heartbeat",
16
+ connection_open = "connection:open",
17
+ connection_error = "connection:error",
18
+ connection_closed = "connection:closed"
19
+ }
20
+ /** The app's own request type satisfies it structurally. */
21
+ export type SseHttpRequest = Request;
22
+ export type SseHttpResponse = Response;
23
+ export type SseNextFn = NextFunction;
24
+ /** Optional cross-instance channel the server notifies (e.g. a Redis pub/sub publisher). */
25
+ export interface SseServerChannel {
26
+ message(type: string, data: any): unknown;
27
+ }
28
+ export declare class SseServerMessage<Data = any> {
29
+ message: string;
30
+ data?: Data;
31
+ constructor(payload: SseServerMessage<Data>);
32
+ }
33
+ export interface SseReservedEventsMap {
34
+ [SseReservedEventEnum.connection_ping]: SseServerMessage;
35
+ [SseReservedEventEnum.connection_heartbeat]: SseServerMessage;
36
+ [SseReservedEventEnum.connection_error]: SseServerMessage;
37
+ [SseReservedEventEnum.connection_closed]: SseServerMessage;
38
+ [SseReservedEventEnum.connection_open]: SseServerMessage;
39
+ }
40
+ /** Base of every SSE output map: wire event name → `data` payload. Apps extend it. */
41
+ export interface SseEventsMapBase extends SseReservedEventsMap {
42
+ [key: string]: Record<string, any>;
43
+ }
44
+ export declare class SseEvent<M extends SseEventsMapBase = SseEventsMapBase, Type extends keyof M = keyof M> {
45
+ type?: Type;
46
+ data: M[Type];
47
+ constructor(payload: SseEvent<M, Type>);
48
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SseEvent = exports.SseServerMessage = exports.SseReservedEventEnum = exports.SseHeaderEnum = void 0;
4
+ var SseHeaderEnum;
5
+ (function (SseHeaderEnum) {
6
+ SseHeaderEnum["contentType"] = "Content-Type";
7
+ SseHeaderEnum["cacheControl"] = "Cache-Control";
8
+ SseHeaderEnum["connection"] = "Connection";
9
+ SseHeaderEnum["sseClientId"] = "Sse-Client-Id";
10
+ SseHeaderEnum["accessAllowOrigin"] = "Access-Allow-Origin";
11
+ })(SseHeaderEnum || (exports.SseHeaderEnum = SseHeaderEnum = {}));
12
+ /** Reserved SSE event names sent to clients — wire names, do not rename. */
13
+ var SseReservedEventEnum;
14
+ (function (SseReservedEventEnum) {
15
+ SseReservedEventEnum["connection_ping"] = "connection:ping";
16
+ SseReservedEventEnum["connection_heartbeat"] = "connection:heartbeat";
17
+ SseReservedEventEnum["connection_open"] = "connection:open";
18
+ SseReservedEventEnum["connection_error"] = "connection:error";
19
+ SseReservedEventEnum["connection_closed"] = "connection:closed";
20
+ })(SseReservedEventEnum || (exports.SseReservedEventEnum = SseReservedEventEnum = {}));
21
+ class SseServerMessage {
22
+ constructor(payload) {
23
+ Object.assign(this, payload);
24
+ }
25
+ }
26
+ exports.SseServerMessage = SseServerMessage;
27
+ class SseEvent {
28
+ constructor(payload) {
29
+ Object.assign(this, payload);
30
+ }
31
+ }
32
+ exports.SseEvent = SseEvent;
package/package.json CHANGED
@@ -1,6 +1,80 @@
1
1
  {
2
2
  "name": "@my-nestjs-kit/sse",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-dev.20261129020438",
4
+ "description": "Server-sent events for NestJS: SseServer with rooms, SseRoomStream with numbered events, Last-Event-ID replay and acks, in-memory or Redis event log.",
5
+ "keywords": [
6
+ "nestjs",
7
+ "nest",
8
+ "sse",
9
+ "server-sent-events",
10
+ "eventsource"
11
+ ],
12
+ "license": "MIT",
13
+ "homepage": "https://github.com/sabationok/my-nestjs-kit/tree/main/packages/sse#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/sabationok/my-nestjs-kit/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/sabationok/my-nestjs-kit.git",
20
+ "directory": "packages/sse"
21
+ },
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "main": "dist/index.js",
29
+ "types": "dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "require": "./dist/index.js",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "!dist/**/*.spec.*",
41
+ "!dist/**/*.tsbuildinfo",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "dependencies": {
46
+ "@my-nestjs-kit/core": "^0.1.0-dev.20261129020438"
47
+ },
48
+ "peerDependencies": {
49
+ "@nestjs/common": "^10.4.1",
50
+ "@types/express": "^4.17.0 || ^5.0.0",
51
+ "rxjs": "^7.8.1"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "@types/express": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "devDependencies": {
59
+ "@nestjs/common": "10.4.20",
60
+ "@nestjs/core": "10.4.1",
61
+ "@nestjs/swagger": "7.4.0",
62
+ "@nestjs/websockets": "10.4.1",
63
+ "@types/express": "4.17.21",
64
+ "@types/node": "20.11.28",
65
+ "class-transformer": "0.5.1",
66
+ "class-validator": "0.14.1",
67
+ "decimal.js": "10.4.3",
68
+ "ioredis": "5.8.2",
69
+ "lodash": "4.17.21",
70
+ "reflect-metadata": "0.2.2",
71
+ "rxjs": "7.8.1",
72
+ "typeorm": "0.3.28",
73
+ "typescript": "5.4.2"
74
+ },
75
+ "scripts": {
76
+ "build": "rm -rf dist && tsc -p tsconfig.json",
77
+ "build:watch": "tsc -p tsconfig.json --watch",
78
+ "typecheck": "tsc -p tsconfig.json --noEmit"
79
+ }
6
80
  }