@gleamkit/socket.io 4.8.6

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.
@@ -0,0 +1,432 @@
1
+ import { Socket } from "./socket";
2
+ import type { Server } from "./index";
3
+ import { EventParams, EventNames, EventsMap, StrictEventEmitter, DefaultEventsMap, DecorateAcknowledgementsWithTimeoutAndMultipleResponses, AllButLast, Last, DecorateAcknowledgementsWithMultipleResponses, RemoveAcknowledgements, EventNamesWithAck, FirstNonErrorArg, EventNamesWithoutAck } from "./typed-events";
4
+ import type { Client } from "./client";
5
+ import type { Adapter, Room, SocketId } from "socket.io-adapter";
6
+ import { BroadcastOperator } from "./broadcast-operator";
7
+ export interface ExtendedError extends Error {
8
+ data?: any;
9
+ }
10
+ export interface NamespaceReservedEventsMap<ListenEvents extends EventsMap, EmitEvents extends EventsMap, ServerSideEvents extends EventsMap, SocketData> {
11
+ connect: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void;
12
+ connection: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void;
13
+ }
14
+ export interface ServerReservedEventsMap<ListenEvents extends EventsMap, EmitEvents extends EventsMap, ServerSideEvents extends EventsMap, SocketData> extends NamespaceReservedEventsMap<ListenEvents, EmitEvents, ServerSideEvents, SocketData> {
15
+ new_namespace: (namespace: Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void;
16
+ }
17
+ export declare const RESERVED_EVENTS: ReadonlySet<string | Symbol>;
18
+ /**
19
+ * A Namespace is a communication channel that allows you to split the logic of your application over a single shared
20
+ * connection.
21
+ *
22
+ * Each namespace has its own:
23
+ *
24
+ * - event handlers
25
+ *
26
+ * ```
27
+ * io.of("/orders").on("connection", (socket) => {
28
+ * socket.on("order:list", () => {});
29
+ * socket.on("order:create", () => {});
30
+ * });
31
+ *
32
+ * io.of("/users").on("connection", (socket) => {
33
+ * socket.on("user:list", () => {});
34
+ * });
35
+ * ```
36
+ *
37
+ * - rooms
38
+ *
39
+ * ```
40
+ * const orderNamespace = io.of("/orders");
41
+ *
42
+ * orderNamespace.on("connection", (socket) => {
43
+ * socket.join("room1");
44
+ * orderNamespace.to("room1").emit("hello");
45
+ * });
46
+ *
47
+ * const userNamespace = io.of("/users");
48
+ *
49
+ * userNamespace.on("connection", (socket) => {
50
+ * socket.join("room1"); // distinct from the room in the "orders" namespace
51
+ * userNamespace.to("room1").emit("holà");
52
+ * });
53
+ * ```
54
+ *
55
+ * - middlewares
56
+ *
57
+ * ```
58
+ * const orderNamespace = io.of("/orders");
59
+ *
60
+ * orderNamespace.use((socket, next) => {
61
+ * // ensure the socket has access to the "orders" namespace
62
+ * });
63
+ *
64
+ * const userNamespace = io.of("/users");
65
+ *
66
+ * userNamespace.use((socket, next) => {
67
+ * // ensure the socket has access to the "users" namespace
68
+ * });
69
+ * ```
70
+ */
71
+ export declare class Namespace<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents, ServerSideEvents extends EventsMap = DefaultEventsMap, SocketData = any> extends StrictEventEmitter<ServerSideEvents, RemoveAcknowledgements<EmitEvents>, NamespaceReservedEventsMap<ListenEvents, EmitEvents, ServerSideEvents, SocketData>> {
72
+ readonly name: string;
73
+ /**
74
+ * A map of currently connected sockets.
75
+ */
76
+ readonly sockets: Map<SocketId, Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>>;
77
+ /**
78
+ * A map of currently connecting sockets.
79
+ */
80
+ private _preConnectSockets;
81
+ adapter: Adapter;
82
+ /** @private */
83
+ readonly server: Server<ListenEvents, EmitEvents, ServerSideEvents, SocketData>;
84
+ private _fns;
85
+ /** @private */
86
+ _ids: number;
87
+ /**
88
+ * Namespace constructor.
89
+ *
90
+ * @param server instance
91
+ * @param name
92
+ */
93
+ constructor(server: Server<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, name: string);
94
+ /**
95
+ * Initializes the `Adapter` for this nsp.
96
+ * Run upon changing adapter by `Server#adapter`
97
+ * in addition to the constructor.
98
+ *
99
+ * @private
100
+ */
101
+ _initAdapter(): void;
102
+ /**
103
+ * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}.
104
+ *
105
+ * @example
106
+ * const myNamespace = io.of("/my-namespace");
107
+ *
108
+ * myNamespace.use((socket, next) => {
109
+ * // ...
110
+ * next();
111
+ * });
112
+ *
113
+ * @param fn - the middleware function
114
+ */
115
+ use(fn: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, next: (err?: ExtendedError) => void) => void): this;
116
+ /**
117
+ * Executes the middleware for an incoming client.
118
+ *
119
+ * @param socket - the socket that will get added
120
+ * @param fn - last fn call in the middleware
121
+ * @private
122
+ */
123
+ private run;
124
+ /**
125
+ * Targets a room when emitting.
126
+ *
127
+ * @example
128
+ * const myNamespace = io.of("/my-namespace");
129
+ *
130
+ * // the “foo” event will be broadcast to all connected clients in the “room-101” room
131
+ * myNamespace.to("room-101").emit("foo", "bar");
132
+ *
133
+ * // with an array of rooms (a client will be notified at most once)
134
+ * myNamespace.to(["room-101", "room-102"]).emit("foo", "bar");
135
+ *
136
+ * // with multiple chained calls
137
+ * myNamespace.to("room-101").to("room-102").emit("foo", "bar");
138
+ *
139
+ * @param room - a room, or an array of rooms
140
+ * @return a new {@link BroadcastOperator} instance for chaining
141
+ */
142
+ to(room: Room | Room[]): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
143
+ /**
144
+ * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases:
145
+ *
146
+ * @example
147
+ * const myNamespace = io.of("/my-namespace");
148
+ *
149
+ * // disconnect all clients in the "room-101" room
150
+ * myNamespace.in("room-101").disconnectSockets();
151
+ *
152
+ * @param room - a room, or an array of rooms
153
+ * @return a new {@link BroadcastOperator} instance for chaining
154
+ */
155
+ in(room: Room | Room[]): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
156
+ /**
157
+ * Excludes a room when emitting.
158
+ *
159
+ * @example
160
+ * const myNamespace = io.of("/my-namespace");
161
+ *
162
+ * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
163
+ * myNamespace.except("room-101").emit("foo", "bar");
164
+ *
165
+ * // with an array of rooms
166
+ * myNamespace.except(["room-101", "room-102"]).emit("foo", "bar");
167
+ *
168
+ * // with multiple chained calls
169
+ * myNamespace.except("room-101").except("room-102").emit("foo", "bar");
170
+ *
171
+ * @param room - a room, or an array of rooms
172
+ * @return a new {@link BroadcastOperator} instance for chaining
173
+ */
174
+ except(room: Room | Room[]): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
175
+ /**
176
+ * Adds a new client.
177
+ *
178
+ * @return {Socket}
179
+ * @private
180
+ */
181
+ _add(client: Client<ListenEvents, EmitEvents, ServerSideEvents>, auth: Record<string, unknown>, fn: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void): Promise<void>;
182
+ private _createSocket;
183
+ private _doConnect;
184
+ /**
185
+ * Removes a client. Called by each `Socket`.
186
+ *
187
+ * @private
188
+ */
189
+ _remove(socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>): void;
190
+ /**
191
+ * Emits to all connected clients.
192
+ *
193
+ * @example
194
+ * const myNamespace = io.of("/my-namespace");
195
+ *
196
+ * myNamespace.emit("hello", "world");
197
+ *
198
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
199
+ * myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
200
+ *
201
+ * // with an acknowledgement from the clients
202
+ * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
203
+ * if (err) {
204
+ * // some clients did not acknowledge the event in the given delay
205
+ * } else {
206
+ * console.log(responses); // one response per client
207
+ * }
208
+ * });
209
+ *
210
+ * @return Always true
211
+ */
212
+ emit<Ev extends EventNamesWithoutAck<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): boolean;
213
+ /**
214
+ * Sends a `message` event to all clients.
215
+ *
216
+ * This method mimics the WebSocket.send() method.
217
+ *
218
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
219
+ *
220
+ * @example
221
+ * const myNamespace = io.of("/my-namespace");
222
+ *
223
+ * myNamespace.send("hello");
224
+ *
225
+ * // this is equivalent to
226
+ * myNamespace.emit("message", "hello");
227
+ *
228
+ * @return self
229
+ */
230
+ send(...args: EventParams<EmitEvents, "message">): this;
231
+ /**
232
+ * Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}.
233
+ *
234
+ * @return self
235
+ */
236
+ write(...args: EventParams<EmitEvents, "message">): this;
237
+ /**
238
+ * Sends a message to the other Socket.IO servers of the cluster.
239
+ *
240
+ * @example
241
+ * const myNamespace = io.of("/my-namespace");
242
+ *
243
+ * myNamespace.serverSideEmit("hello", "world");
244
+ *
245
+ * myNamespace.on("hello", (arg1) => {
246
+ * console.log(arg1); // prints "world"
247
+ * });
248
+ *
249
+ * // acknowledgements (without binary content) are supported too:
250
+ * myNamespace.serverSideEmit("ping", (err, responses) => {
251
+ * if (err) {
252
+ * // some servers did not acknowledge the event in the given delay
253
+ * } else {
254
+ * console.log(responses); // one response per server (except the current one)
255
+ * }
256
+ * });
257
+ *
258
+ * myNamespace.on("ping", (cb) => {
259
+ * cb("pong");
260
+ * });
261
+ *
262
+ * @param ev - the event name
263
+ * @param args - an array of arguments, which may include an acknowledgement callback at the end
264
+ */
265
+ serverSideEmit<Ev extends EventNames<ServerSideEvents>>(ev: Ev, ...args: EventParams<DecorateAcknowledgementsWithTimeoutAndMultipleResponses<ServerSideEvents>, Ev>): boolean;
266
+ /**
267
+ * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
268
+ *
269
+ * @example
270
+ * const myNamespace = io.of("/my-namespace");
271
+ *
272
+ * try {
273
+ * const responses = await myNamespace.serverSideEmitWithAck("ping");
274
+ * console.log(responses); // one response per server (except the current one)
275
+ * } catch (e) {
276
+ * // some servers did not acknowledge the event in the given delay
277
+ * }
278
+ *
279
+ * @param ev - the event name
280
+ * @param args - an array of arguments
281
+ *
282
+ * @return a Promise that will be fulfilled when all servers have acknowledged the event
283
+ */
284
+ serverSideEmitWithAck<Ev extends EventNamesWithAck<ServerSideEvents>>(ev: Ev, ...args: AllButLast<EventParams<ServerSideEvents, Ev>>): Promise<FirstNonErrorArg<Last<EventParams<ServerSideEvents, Ev>>>[]>;
285
+ /**
286
+ * Called when a packet is received from another Socket.IO server
287
+ *
288
+ * @param args - an array of arguments, which may include an acknowledgement callback at the end
289
+ *
290
+ * @private
291
+ */
292
+ _onServerSideEmit(args: [string, ...any[]]): void;
293
+ /**
294
+ * Gets a list of clients.
295
+ *
296
+ * @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or
297
+ * {@link Namespace#fetchSockets} instead.
298
+ */
299
+ allSockets(): Promise<Set<SocketId>>;
300
+ /**
301
+ * Sets the compress flag.
302
+ *
303
+ * @example
304
+ * const myNamespace = io.of("/my-namespace");
305
+ *
306
+ * myNamespace.compress(false).emit("hello");
307
+ *
308
+ * @param compress - if `true`, compresses the sending data
309
+ * @return self
310
+ */
311
+ compress(compress: boolean): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
312
+ /**
313
+ * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
314
+ * receive messages (because of network slowness or other issues, or because they’re connected through long polling
315
+ * and is in the middle of a request-response cycle).
316
+ *
317
+ * @example
318
+ * const myNamespace = io.of("/my-namespace");
319
+ *
320
+ * myNamespace.volatile.emit("hello"); // the clients may or may not receive it
321
+ *
322
+ * @return self
323
+ */
324
+ get volatile(): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
325
+ /**
326
+ * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
327
+ *
328
+ * @example
329
+ * const myNamespace = io.of("/my-namespace");
330
+ *
331
+ * // the “foo” event will be broadcast to all connected clients on this node
332
+ * myNamespace.local.emit("foo", "bar");
333
+ *
334
+ * @return a new {@link BroadcastOperator} instance for chaining
335
+ */
336
+ get local(): BroadcastOperator<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
337
+ /**
338
+ * Adds a timeout in milliseconds for the next operation.
339
+ *
340
+ * @example
341
+ * const myNamespace = io.of("/my-namespace");
342
+ *
343
+ * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
344
+ * if (err) {
345
+ * // some clients did not acknowledge the event in the given delay
346
+ * } else {
347
+ * console.log(responses); // one response per client
348
+ * }
349
+ * });
350
+ *
351
+ * @param timeout
352
+ */
353
+ timeout(timeout: number): BroadcastOperator<import("./typed-events").DecorateAcknowledgements<DecorateAcknowledgementsWithMultipleResponses<EmitEvents>>, SocketData>;
354
+ /**
355
+ * Returns the matching socket instances.
356
+ *
357
+ * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
358
+ *
359
+ * @example
360
+ * const myNamespace = io.of("/my-namespace");
361
+ *
362
+ * // return all Socket instances
363
+ * const sockets = await myNamespace.fetchSockets();
364
+ *
365
+ * // return all Socket instances in the "room1" room
366
+ * const sockets = await myNamespace.in("room1").fetchSockets();
367
+ *
368
+ * for (const socket of sockets) {
369
+ * console.log(socket.id);
370
+ * console.log(socket.handshake);
371
+ * console.log(socket.rooms);
372
+ * console.log(socket.data);
373
+ *
374
+ * socket.emit("hello");
375
+ * socket.join("room1");
376
+ * socket.leave("room2");
377
+ * socket.disconnect();
378
+ * }
379
+ */
380
+ fetchSockets(): Promise<import("./broadcast-operator").RemoteSocket<EmitEvents, SocketData>[]>;
381
+ /**
382
+ * Makes the matching socket instances join the specified rooms.
383
+ *
384
+ * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
385
+ *
386
+ * @example
387
+ * const myNamespace = io.of("/my-namespace");
388
+ *
389
+ * // make all socket instances join the "room1" room
390
+ * myNamespace.socketsJoin("room1");
391
+ *
392
+ * // make all socket instances in the "room1" room join the "room2" and "room3" rooms
393
+ * myNamespace.in("room1").socketsJoin(["room2", "room3"]);
394
+ *
395
+ * @param room - a room, or an array of rooms
396
+ */
397
+ socketsJoin(room: Room | Room[]): void;
398
+ /**
399
+ * Makes the matching socket instances leave the specified rooms.
400
+ *
401
+ * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
402
+ *
403
+ * @example
404
+ * const myNamespace = io.of("/my-namespace");
405
+ *
406
+ * // make all socket instances leave the "room1" room
407
+ * myNamespace.socketsLeave("room1");
408
+ *
409
+ * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
410
+ * myNamespace.in("room1").socketsLeave(["room2", "room3"]);
411
+ *
412
+ * @param room - a room, or an array of rooms
413
+ */
414
+ socketsLeave(room: Room | Room[]): void;
415
+ /**
416
+ * Makes the matching socket instances disconnect.
417
+ *
418
+ * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
419
+ *
420
+ * @example
421
+ * const myNamespace = io.of("/my-namespace");
422
+ *
423
+ * // make all socket instances disconnect (the connections might be kept alive for other namespaces)
424
+ * myNamespace.disconnectSockets();
425
+ *
426
+ * // make all socket instances in the "room1" room disconnect and close the underlying connections
427
+ * myNamespace.in("room1").disconnectSockets(true);
428
+ *
429
+ * @param close - whether to close the underlying connection
430
+ */
431
+ disconnectSockets(close?: boolean): void;
432
+ }