@hadoku/rooms-server 0.45.61 → 0.45.62

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.
@@ -5,4 +5,5 @@
5
5
  * `node:fs`, and the main entry stays usable from a browser-safe context.
6
6
  */
7
7
  export * from './history.js';
8
+ export * from './room-chat.js';
8
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/chat/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/chat/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,cAAc,CAAC;AAC7B,cAAc,gBAAgB,CAAC"}
@@ -5,3 +5,4 @@
5
5
  * `node:fs`, and the main entry stays usable from a browser-safe context.
6
6
  */
7
7
  export * from './history.js';
8
+ export * from './room-chat.js';
@@ -0,0 +1,212 @@
1
+ /**
2
+ * A room's chat, served: validate a send, store it, broadcast it, and read
3
+ * history back — for any app whose rooms have chat, so each app serves its own
4
+ * rooms' chat (platform plan phase 4, step 5) instead of watchparty serving
5
+ * every app's.
6
+ *
7
+ * Two layers, both used by watchparty itself:
8
+ *
9
+ * - `createRoomChat` is the pipeline (parse → rate limit → append → broadcast
10
+ * payload) with no transport. Watchparty's own room socket calls it from its
11
+ * `chat_send` handler, beside its playback events.
12
+ * - `serveRoomChat` puts that pipeline on a socket.io NAMESPACE of the app's
13
+ * own server (default `/chat`), with the app's admission rule. That is what
14
+ * `RoomChrome`'s `chatOrigin` connects to. A namespace rather than the app's
15
+ * default one because the chat wire's `join` would otherwise collide with
16
+ * the app's own events.
17
+ *
18
+ * THE WIRE IS WATCHPARTY'S, UNCHANGED: the client emits `join` (watchparty's
19
+ * join payload; only `room_key` is read here) and `chat_send` (`{ text,
20
+ * style?, images? }`), and receives `chat_history` (`{ messages }`),
21
+ * `chat_broadcast` and `error` (`{ code, message }`). Same event names and
22
+ * payloads as watchparty's room socket, so the chat client is one piece of
23
+ * code whichever server it talks to.
24
+ *
25
+ * NOTHING ABOUT A PERSON IS STORED (watchparty R12): a stored message keeps
26
+ * who wrote it (`author`, `authorId`, `clientId`), never what they were
27
+ * called. Names and characters are filled in when a message is SENT, from the
28
+ * live member list, or by the app's `present` hook.
29
+ */
30
+ import type { Namespace, Server as SocketIOServer, Socket } from 'socket.io';
31
+ import type { ChatHistoryRecord, ChatHistoryStore } from './history.js';
32
+ /** CDN image key: a SHA-256 plus a raster extension. The trust boundary for
33
+ * anything that will reach an `<img src>` (watchparty `chatImages.ts`). */
34
+ export declare const CHAT_IMAGE_KEY_RE: RegExp;
35
+ /** Stands for the subject's name in a stored system message. */
36
+ export declare const CHAT_NAME_TOKEN = "{name}";
37
+ export declare const CHAT_MAX_LENGTH = 500;
38
+ export declare const CHAT_MAX_IMAGES = 4;
39
+ export declare const CHAT_MAX_STYLE_LENGTH = 64;
40
+ export declare const CHAT_MAX_IMAGE_DIMENSION = 20000;
41
+ export declare const CHAT_MAX_IMAGE_TITLE_LENGTH = 300;
42
+ export declare const CHAT_HISTORY_JOIN_LIMIT = 100;
43
+ export interface ChatImageInput {
44
+ key: string;
45
+ w: number;
46
+ h: number;
47
+ title?: string;
48
+ }
49
+ /** What a `chat_send` carries once validated. */
50
+ export interface ChatSendInput {
51
+ text: string;
52
+ style?: string;
53
+ images?: ChatImageInput[];
54
+ }
55
+ /** The stored message. Hosts may extend it (the history store is generic). */
56
+ export interface RoomChatMessage extends ChatHistoryRecord {
57
+ clientId: string;
58
+ author?: string;
59
+ authorId?: string;
60
+ text: string;
61
+ style?: string;
62
+ images?: ChatImageInput[];
63
+ isSystem?: boolean;
64
+ systemType?: string;
65
+ }
66
+ /** Who is sending, as the room shows them right now. */
67
+ export interface ChatSender {
68
+ /** The connection (socket id). */
69
+ clientId: string;
70
+ /** A stable participant handle, so a reload still reads as the same author. */
71
+ author?: string;
72
+ /** The account userId, if any. */
73
+ authorId?: string;
74
+ name: string;
75
+ sprite: string | null;
76
+ }
77
+ /** `chat_broadcast` / one `chat_history` entry, as watchparty's client reads it. */
78
+ export interface ChatBroadcastPayload {
79
+ id: string;
80
+ client_id: string;
81
+ author?: string;
82
+ name: string;
83
+ sprite: string | null;
84
+ text: string;
85
+ ts: number;
86
+ style?: string;
87
+ images?: ChatImageInput[];
88
+ isSystem: boolean;
89
+ systemType?: string;
90
+ template?: string;
91
+ }
92
+ /**
93
+ * Validate a `chat_send` payload, or null. Kept identical to watchparty's Zod
94
+ * `ChatSend` (`@watchparty/shared` protocol.ts), which this package cannot
95
+ * import (it is never published) — `room-chat.test.ts` runs both over one
96
+ * table of cases, so a change to either that the other lacks fails there.
97
+ * Unknown fields are dropped, as Zod's object parse drops them.
98
+ */
99
+ export declare function parseChatSend(payload: unknown): ChatSendInput | null;
100
+ /** Fill the `{name}` token of a stored system line. */
101
+ export declare function fillChatName(text: string, name: string | null | undefined): string;
102
+ /** The wire shape of a stored message, named by `who` (live or as presented). */
103
+ export declare function toChatBroadcast(msg: RoomChatMessage, who: {
104
+ name: string;
105
+ sprite: string | null;
106
+ }): ChatBroadcastPayload;
107
+ export type ChatSendOutcome<M> = {
108
+ ok: true;
109
+ message: M;
110
+ broadcast: ChatBroadcastPayload;
111
+ } | {
112
+ ok: false;
113
+ reason: 'rate_limited' | 'invalid' | 'append_failed';
114
+ };
115
+ export interface RoomChatOptions<M extends RoomChatMessage> {
116
+ store: ChatHistoryStore<M>;
117
+ /** Validate a send. Default `parseChatSend`. */
118
+ parse?: (payload: unknown) => ChatSendInput | null;
119
+ /** Per-connection rate limit; false refuses the send. Default: no limit. */
120
+ allow?: (clientId: string) => boolean;
121
+ newId?: () => string;
122
+ now?: () => number;
123
+ }
124
+ export interface RoomChat<M extends RoomChatMessage> {
125
+ /** Parse, rate-limit and store one `chat_send`; returns the payload to
126
+ * broadcast. Never throws. The caller broadcasts (it owns the transport). */
127
+ send(roomId: string, sender: ChatSender, payload: unknown): Promise<ChatSendOutcome<M>>;
128
+ store: ChatHistoryStore<M>;
129
+ }
130
+ export declare function createRoomChat<M extends RoomChatMessage>(opts: RoomChatOptions<M>): RoomChat<M>;
131
+ export interface ChatHistoryHttpQuery {
132
+ limit?: unknown;
133
+ before?: unknown;
134
+ }
135
+ export interface ChatHistoryHttpResult {
136
+ status: number;
137
+ body: unknown;
138
+ }
139
+ /**
140
+ * The body of `GET <prefix>/api/rooms/:id/chat?key=&limit=&before=`, with no
141
+ * HTTP framework attached. The caller resolves the room and decides whether
142
+ * `key` proves membership (that is the app's rule); this does the rest, with
143
+ * watchparty's status codes and error strings.
144
+ */
145
+ export declare function chatHistoryResponse<M extends RoomChatMessage>(store: ChatHistoryStore<M>, args: {
146
+ roomId: string | null;
147
+ member: boolean;
148
+ query: ChatHistoryHttpQuery;
149
+ present?: (messages: M[]) => Promise<Array<{
150
+ name: string;
151
+ sprite: string | null;
152
+ }>> | Array<{
153
+ name: string;
154
+ sprite: string | null;
155
+ }>;
156
+ }): Promise<ChatHistoryHttpResult>;
157
+ /** A socket admitted to one room's chat. */
158
+ export interface ChatAdmission {
159
+ roomId: string;
160
+ /** Who this connection is right now — re-read on every send, so a rename
161
+ * shows on the next line. */
162
+ sender: () => ChatSender;
163
+ }
164
+ export interface ServeRoomChatOptions<M extends RoomChatMessage> extends RoomChatOptions<M> {
165
+ /** Default `/chat`. */
166
+ namespace?: string;
167
+ /**
168
+ * The app's membership rule: may this socket read and write this room's
169
+ * chat? `join` is the client's join payload (`room_key` is the room key the
170
+ * client holds). Return null to refuse; the socket then gets
171
+ * `error { code: 'auth/forbidden' }` and nothing of the room. Authenticate
172
+ * from the socket's handshake (the edge's `X-User-Key`), never from the
173
+ * payload alone.
174
+ */
175
+ admit: (socket: Socket, join: {
176
+ room_key: string;
177
+ } & Record<string, unknown>) => Promise<ChatAdmission | null> | ChatAdmission | null;
178
+ /** How many stored lines a joiner gets. Default 100. */
179
+ historyJoinLimit?: number;
180
+ /**
181
+ * Name stored messages for a reader in `roomId`. Default: a live member
182
+ * matched by `author` then `clientId`, else "Someone" with no character.
183
+ */
184
+ present?: (roomId: string, messages: M[], members: ChatSender[]) => Promise<Array<{
185
+ name: string;
186
+ sprite: string | null;
187
+ }>> | Array<{
188
+ name: string;
189
+ sprite: string | null;
190
+ }>;
191
+ onEvent?: (level: 'info' | 'warn', event: string, fields: Record<string, unknown>) => void;
192
+ }
193
+ export interface ServedRoomChat<M extends RoomChatMessage> extends RoomChat<M> {
194
+ namespace: Namespace;
195
+ /** Live senders admitted to `roomId` through this namespace. */
196
+ members(roomId: string): ChatSender[];
197
+ /** Name stored messages the way `chat_history` does. */
198
+ present(roomId: string, messages: M[]): Promise<Array<{
199
+ name: string;
200
+ sprite: string | null;
201
+ }>>;
202
+ /** Broadcast a message the app composed (a system line) to the room. */
203
+ broadcast(roomId: string, payload: ChatBroadcastPayload): void;
204
+ }
205
+ /** The socket.io room a chat room's members are in. */
206
+ export declare function chatChannel(roomId: string): string;
207
+ export declare function defaultPresent<M extends RoomChatMessage>(messages: M[], members: ChatSender[]): Array<{
208
+ name: string;
209
+ sprite: string | null;
210
+ }>;
211
+ export declare function serveRoomChat<M extends RoomChatMessage>(io: SocketIOServer, opts: ServeRoomChatOptions<M>): ServedRoomChat<M>;
212
+ //# sourceMappingURL=room-chat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"room-chat.d.ts","sourceRoot":"","sources":["../../src/chat/room-chat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,cAAc,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAExE;4EAC4E;AAC5E,eAAO,MAAM,iBAAiB,QAAgD,CAAC;AAC/E,gEAAgE;AAChE,eAAO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AAE,SAAS,CAAC;IACrB,gEAAgE;IAChE,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,EAAE,CAAC;IACtC,wDAAwD;IACxD,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAAC,CAAC;IAChG,wEAAwE;IACxE,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC;CAChE;AAED,uDAAuD;AACvD,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,cAAc,CAAC,CAAC,SAAS,eAAe,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,CAW9I;AAED,wBAAgB,aAAa,CAAC,CAAC,SAAS,eAAe,EAAE,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,oBAAoB,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC,CAAC,CAAC,CAkE7H"}
@@ -0,0 +1,244 @@
1
+ /** CDN image key: a SHA-256 plus a raster extension. The trust boundary for
2
+ * anything that will reach an `<img src>` (watchparty `chatImages.ts`). */
3
+ export const CHAT_IMAGE_KEY_RE = /^[0-9a-f]{64}\.(?:png|jpe?g|gif|webp|avif)$/;
4
+ /** Stands for the subject's name in a stored system message. */
5
+ export const CHAT_NAME_TOKEN = '{name}';
6
+ export const CHAT_MAX_LENGTH = 500;
7
+ export const CHAT_MAX_IMAGES = 4;
8
+ export const CHAT_MAX_STYLE_LENGTH = 64;
9
+ export const CHAT_MAX_IMAGE_DIMENSION = 20_000;
10
+ export const CHAT_MAX_IMAGE_TITLE_LENGTH = 300;
11
+ export const CHAT_HISTORY_JOIN_LIMIT = 100;
12
+ function isInt(n, max) {
13
+ return typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= max;
14
+ }
15
+ /**
16
+ * Validate a `chat_send` payload, or null. Kept identical to watchparty's Zod
17
+ * `ChatSend` (`@watchparty/shared` protocol.ts), which this package cannot
18
+ * import (it is never published) — `room-chat.test.ts` runs both over one
19
+ * table of cases, so a change to either that the other lacks fails there.
20
+ * Unknown fields are dropped, as Zod's object parse drops them.
21
+ */
22
+ export function parseChatSend(payload) {
23
+ if (!payload || typeof payload !== 'object')
24
+ return null;
25
+ const p = payload;
26
+ if (typeof p.text !== 'string' || p.text.length > CHAT_MAX_LENGTH)
27
+ return null;
28
+ const out = { text: p.text };
29
+ if (p.style !== undefined) {
30
+ if (typeof p.style !== 'string' || p.style.length > CHAT_MAX_STYLE_LENGTH)
31
+ return null;
32
+ out.style = p.style;
33
+ }
34
+ if (p.images !== undefined) {
35
+ if (!Array.isArray(p.images) || p.images.length > CHAT_MAX_IMAGES)
36
+ return null;
37
+ const images = [];
38
+ for (const raw of p.images) {
39
+ if (!raw || typeof raw !== 'object')
40
+ return null;
41
+ const im = raw;
42
+ if (typeof im.key !== 'string' || !CHAT_IMAGE_KEY_RE.test(im.key))
43
+ return null;
44
+ if (!isInt(im.w, CHAT_MAX_IMAGE_DIMENSION) || !isInt(im.h, CHAT_MAX_IMAGE_DIMENSION))
45
+ return null;
46
+ const image = { key: im.key, w: im.w, h: im.h };
47
+ if (im.title !== undefined) {
48
+ if (typeof im.title !== 'string' || im.title.length > CHAT_MAX_IMAGE_TITLE_LENGTH)
49
+ return null;
50
+ image.title = im.title;
51
+ }
52
+ images.push(image);
53
+ }
54
+ out.images = images;
55
+ }
56
+ if (out.text.length === 0 && (out.images?.length ?? 0) === 0)
57
+ return null;
58
+ return out;
59
+ }
60
+ /** Fill the `{name}` token of a stored system line. */
61
+ export function fillChatName(text, name) {
62
+ return text.split(CHAT_NAME_TOKEN).join(name || 'Someone');
63
+ }
64
+ /** The wire shape of a stored message, named by `who` (live or as presented). */
65
+ export function toChatBroadcast(msg, who) {
66
+ const templated = !!msg.isSystem && msg.text.includes(CHAT_NAME_TOKEN);
67
+ return {
68
+ id: msg.id,
69
+ client_id: msg.clientId,
70
+ author: msg.author,
71
+ name: who.name,
72
+ sprite: who.sprite,
73
+ text: msg.isSystem ? fillChatName(msg.text, who.name) : msg.text,
74
+ ts: msg.ts,
75
+ style: msg.style,
76
+ images: msg.images,
77
+ isSystem: !!msg.isSystem,
78
+ systemType: msg.systemType,
79
+ ...(templated ? { template: msg.text } : {}),
80
+ };
81
+ }
82
+ export function createRoomChat(opts) {
83
+ const parse = opts.parse ?? parseChatSend;
84
+ const newId = opts.newId ?? (() => globalThis.crypto.randomUUID());
85
+ const now = opts.now ?? Date.now;
86
+ async function send(roomId, sender, payload) {
87
+ if (opts.allow && !opts.allow(sender.clientId))
88
+ return { ok: false, reason: 'rate_limited' };
89
+ const data = parse(payload);
90
+ if (!data)
91
+ return { ok: false, reason: 'invalid' };
92
+ const message = {
93
+ id: newId(),
94
+ clientId: sender.clientId,
95
+ author: sender.author,
96
+ authorId: sender.authorId,
97
+ ts: now(),
98
+ text: data.text,
99
+ style: data.style,
100
+ // Undefined rather than [] when there are none, so an image-less message
101
+ // is byte-identical to one sent before attachments existed.
102
+ images: data.images?.length ? data.images : undefined,
103
+ isSystem: false,
104
+ };
105
+ try {
106
+ await opts.store.appendMessage(roomId, message);
107
+ }
108
+ catch {
109
+ return { ok: false, reason: 'append_failed' };
110
+ }
111
+ return { ok: true, message, broadcast: toChatBroadcast(message, sender) };
112
+ }
113
+ return { send, store: opts.store };
114
+ }
115
+ /**
116
+ * The body of `GET <prefix>/api/rooms/:id/chat?key=&limit=&before=`, with no
117
+ * HTTP framework attached. The caller resolves the room and decides whether
118
+ * `key` proves membership (that is the app's rule); this does the rest, with
119
+ * watchparty's status codes and error strings.
120
+ */
121
+ export async function chatHistoryResponse(store, args) {
122
+ if (!args.roomId)
123
+ return { status: 404, body: { error: 'room/not_found' } };
124
+ if (!args.member)
125
+ return { status: 403, body: { error: 'auth/invalid_key' } };
126
+ let limit;
127
+ let before;
128
+ if (args.query.limit !== undefined) {
129
+ const n = Number(args.query.limit);
130
+ if (!Number.isFinite(n) || n <= 0)
131
+ return { status: 400, body: { error: 'chat/invalid_limit' } };
132
+ limit = n;
133
+ }
134
+ if (args.query.before !== undefined) {
135
+ const b = Number(args.query.before);
136
+ if (!Number.isFinite(b) || b <= 0)
137
+ return { status: 400, body: { error: 'chat/invalid_before' } };
138
+ before = b;
139
+ }
140
+ try {
141
+ const paged = await store.pagedMessages(args.roomId, { beforeTs: before, limit });
142
+ const who = args.present ? await args.present(paged.messages) : paged.messages.map(() => ({ name: 'Someone', sprite: null }));
143
+ const messages = paged.messages.map((m, i) => ({
144
+ id: m.id,
145
+ client_id: m.clientId,
146
+ text: m.isSystem ? fillChatName(m.text, who[i]?.name) : m.text,
147
+ ts: m.ts,
148
+ }));
149
+ return {
150
+ status: 200,
151
+ body: {
152
+ messages,
153
+ has_more: paged.hasMore,
154
+ next_before: paged.hasMore && messages.length ? messages[0].ts : null,
155
+ },
156
+ };
157
+ }
158
+ catch {
159
+ return { status: 500, body: { error: 'server/error' } };
160
+ }
161
+ }
162
+ /** The socket.io room a chat room's members are in. */
163
+ export function chatChannel(roomId) {
164
+ return `chat:${roomId}`;
165
+ }
166
+ export function defaultPresent(messages, members) {
167
+ const byAuthor = new Map();
168
+ const byClient = new Map();
169
+ for (const s of members) {
170
+ if (s.author)
171
+ byAuthor.set(s.author, s);
172
+ byClient.set(s.clientId, s);
173
+ }
174
+ return messages.map((m) => {
175
+ const s = (m.author && byAuthor.get(m.author)) || byClient.get(m.clientId);
176
+ return s ? { name: s.name, sprite: s.sprite } : { name: 'Someone', sprite: null };
177
+ });
178
+ }
179
+ export function serveRoomChat(io, opts) {
180
+ const nsp = io.of(opts.namespace ?? '/chat');
181
+ const chat = createRoomChat(opts);
182
+ const admitted = new Map(); // socket id → admission
183
+ const emit = opts.onEvent ?? (() => { });
184
+ function members(roomId) {
185
+ const out = [];
186
+ for (const a of admitted.values())
187
+ if (a.roomId === roomId)
188
+ out.push(a.sender());
189
+ return out;
190
+ }
191
+ async function present(roomId, messages) {
192
+ const live = members(roomId);
193
+ return opts.present ? opts.present(roomId, messages, live) : defaultPresent(messages, live);
194
+ }
195
+ function broadcast(roomId, payload) {
196
+ nsp.to(chatChannel(roomId)).emit('chat_broadcast', payload);
197
+ }
198
+ nsp.on('connection', (socket) => {
199
+ const refuse = (code, message) => socket.emit('error', { code, message });
200
+ socket.on('join', async (payload) => {
201
+ const roomKey = payload && typeof payload === 'object' ? payload.room_key : undefined;
202
+ if (typeof roomKey !== 'string' || !roomKey)
203
+ return refuse('chat/invalid_join', 'join needs a room_key');
204
+ let admission;
205
+ try {
206
+ admission = await opts.admit(socket, payload);
207
+ }
208
+ catch (err) {
209
+ emit('warn', 'chat.admit_failed', { sid: socket.id, err_message: String(err) });
210
+ admission = null;
211
+ }
212
+ if (!socket.connected)
213
+ return;
214
+ if (!admission) {
215
+ emit('warn', 'chat.join_refused', { sid: socket.id });
216
+ return refuse('auth/forbidden', 'not a member of this room');
217
+ }
218
+ const previous = admitted.get(socket.id);
219
+ if (previous && previous.roomId !== admission.roomId)
220
+ await socket.leave(chatChannel(previous.roomId));
221
+ admitted.set(socket.id, admission);
222
+ await socket.join(chatChannel(admission.roomId));
223
+ const stored = await chat.store.recentMessages(admission.roomId, opts.historyJoinLimit ?? CHAT_HISTORY_JOIN_LIMIT);
224
+ const who = await present(admission.roomId, stored);
225
+ socket.emit('chat_history', { messages: stored.map((m, i) => toChatBroadcast(m, who[i] ?? { name: 'Someone', sprite: null })) });
226
+ emit('info', 'chat.joined', { sid: socket.id, room_id: admission.roomId });
227
+ });
228
+ socket.on('chat_send', async (payload) => {
229
+ const admission = admitted.get(socket.id);
230
+ if (!admission)
231
+ return refuse('auth/forbidden', 'join the room before chatting');
232
+ const outcome = await chat.send(admission.roomId, admission.sender(), payload);
233
+ if (!outcome.ok) {
234
+ emit('warn', 'chat.send_refused', { sid: socket.id, room_id: admission.roomId, reason: outcome.reason });
235
+ return refuse(outcome.reason === 'rate_limited' ? 'rate/limited' : 'server/error', `chat ${outcome.reason}`);
236
+ }
237
+ broadcast(admission.roomId, outcome.broadcast);
238
+ });
239
+ socket.on('disconnect', () => {
240
+ admitted.delete(socket.id);
241
+ });
242
+ });
243
+ return { ...chat, namespace: nsp, members, present, broadcast };
244
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/rooms-server",
3
- "version": "0.45.61",
4
- "gitHead": "0e98044983dd1855d944daa8dcafc17e5c0b450b",
3
+ "version": "0.45.62",
4
+ "gitHead": "2e965af2d4374dfa5345cfeca2f6e57932034ffb",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "Room lifecycle, membership, seating, identity, presence, backpressure-aware emit and durable room storage for a socket.io server.",
@@ -31,7 +31,7 @@
31
31
  "directory": "packages/rooms-server"
32
32
  },
33
33
  "dependencies": {
34
- "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.61"
34
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.62"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "socket.io": "^4.8.3"