index.d.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /// <reference types="node" />
  2. /// <reference types="node" />
  3. /// <reference types="node" />
  4. import http = require("http");
  5. import type { Server as HTTPSServer } from "https";
  6. import type { Http2SecureServer } from "http2";
  7. import type { ServerOptions as EngineOptions, AttachOptions, BaseServer } from "engine.io";
  8. import { ExtendedError, Namespace, ServerReservedEventsMap } from "./namespace";
  9. import { Adapter, Room, SocketId } from "socket.io-adapter";
  10. import * as parser from "socket.io-parser";
  11. import type { Encoder } from "socket.io-parser";
  12. import { Socket, DisconnectReason } from "./socket";
  13. import type { BroadcastOperator, RemoteSocket } from "./broadcast-operator";
  14. import { EventsMap, DefaultEventsMap, EventParams, StrictEventEmitter, EventNames, DecorateAcknowledgementsWithTimeoutAndMultipleResponses, AllButLast, Last, FirstArg, SecondArg } from "./typed-events";
  15. declare type ParentNspNameMatchFn = (name: string, auth: {
  16. [key: string]: any;
  17. }, fn: (err: Error | null, success: boolean) => void) => void;
  18. declare type AdapterConstructor = typeof Adapter | ((nsp: Namespace) => Adapter);
  19. interface ServerOptions extends EngineOptions, AttachOptions {
  20. /**
  21. * name of the path to capture
  22. * @default "/socket.io"
  23. */
  24. path: string;
  25. /**
  26. * whether to serve the client files
  27. * @default true
  28. */
  29. serveClient: boolean;
  30. /**
  31. * the adapter to use
  32. * @default the in-memory adapter (https://github.com/socketio/socket.io-adapter)
  33. */
  34. adapter: AdapterConstructor;
  35. /**
  36. * the parser to use
  37. * @default the default parser (https://github.com/socketio/socket.io-parser)
  38. */
  39. parser: any;
  40. /**
  41. * how many ms before a client without namespace is closed
  42. * @default 45000
  43. */
  44. connectTimeout: number;
  45. /**
  46. * Whether to enable the recovery of connection state when a client temporarily disconnects.
  47. *
  48. * The connection state includes the missed packets, the rooms the socket was in and the `data` attribute.
  49. */
  50. connectionStateRecovery: {
  51. /**
  52. * The backup duration of the sessions and the packets.
  53. *
  54. * @default 120000 (2 minutes)
  55. */
  56. maxDisconnectionDuration?: number;
  57. /**
  58. * Whether to skip middlewares upon successful connection state recovery.
  59. *
  60. * @default true
  61. */
  62. skipMiddlewares?: boolean;
  63. };
  64. /**
  65. * Whether to remove child namespaces that have no sockets connected to them
  66. * @default false
  67. */
  68. cleanupEmptyChildNamespaces: boolean;
  69. }
  70. /**
  71. * Represents a Socket.IO server.
  72. *
  73. * @example
  74. * import { Server } from "socket.io";
  75. *
  76. * const io = new Server();
  77. *
  78. * io.on("connection", (socket) => {
  79. * console.log(`socket ${socket.id} connected`);
  80. *
  81. * // send an event to the client
  82. * socket.emit("foo", "bar");
  83. *
  84. * socket.on("foobar", () => {
  85. * // an event was received from the client
  86. * });
  87. *
  88. * // upon disconnection
  89. * socket.on("disconnect", (reason) => {
  90. * console.log(`socket ${socket.id} disconnected due to ${reason}`);
  91. * });
  92. * });
  93. *
  94. * io.listen(3000);
  95. */
  96. export declare class Server<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents, ServerSideEvents extends EventsMap = DefaultEventsMap, SocketData = any> extends StrictEventEmitter<ServerSideEvents, EmitEvents, ServerReservedEventsMap<ListenEvents, EmitEvents, ServerSideEvents, SocketData>> {
  97. readonly sockets: Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData>;
  98. /**
  99. * A reference to the underlying Engine.IO server.
  100. *
  101. * @example
  102. * const clientsCount = io.engine.clientsCount;
  103. *
  104. */
  105. engine: BaseServer;
  106. /** @private */
  107. readonly _parser: typeof parser;
  108. /** @private */
  109. readonly encoder: Encoder;
  110. /**
  111. * @private
  112. */
  113. _nsps: Map<string, Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData>>;
  114. private parentNsps;
  115. /**
  116. * A subset of the {@link parentNsps} map, only containing {@link ParentNamespace} which are based on a regular
  117. * expression.
  118. *
  119. * @private
  120. */
  121. private parentNamespacesFromRegExp;
  122. private _adapter?;
  123. private _serveClient;
  124. private readonly opts;
  125. private eio;
  126. private _path;
  127. private clientPathRegex;
  128. /**
  129. * @private
  130. */
  131. _connectTimeout: number;
  132. private httpServer;
  133. private _corsMiddleware;
  134. /**
  135. * Server constructor.
  136. *
  137. * @param srv http server, port, or options
  138. * @param [opts]
  139. */
  140. constructor(opts?: Partial<ServerOptions>);
  141. constructor(srv?: http.Server | HTTPSServer | Http2SecureServer | number, opts?: Partial<ServerOptions>);
  142. constructor(srv: undefined | Partial<ServerOptions> | http.Server | HTTPSServer | Http2SecureServer | number, opts?: Partial<ServerOptions>);
  143. get _opts(): Partial<ServerOptions>;
  144. /**
  145. * Sets/gets whether client code is being served.
  146. *
  147. * @param v - whether to serve client code
  148. * @return self when setting or value when getting
  149. */
  150. serveClient(v: boolean): this;
  151. serveClient(): boolean;
  152. serveClient(v?: boolean): this | boolean;
  153. /**
  154. * Executes the middleware for an incoming namespace not already created on the server.
  155. *
  156. * @param name - name of incoming namespace
  157. * @param auth - the auth parameters
  158. * @param fn - callback
  159. *
  160. * @private
  161. */
  162. _checkNamespace(name: string, auth: {
  163. [key: string]: any;
  164. }, fn: (nsp: Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData> | false) => void): void;
  165. /**
  166. * Sets the client serving path.
  167. *
  168. * @param {String} v pathname
  169. * @return {Server|String} self when setting or value when getting
  170. */
  171. path(v: string): this;
  172. path(): string;
  173. path(v?: string): this | string;
  174. /**
  175. * Set the delay after which a client without namespace is closed
  176. * @param v
  177. */
  178. connectTimeout(v: number): this;
  179. connectTimeout(): number;
  180. connectTimeout(v?: number): this | number;
  181. /**
  182. * Sets the adapter for rooms.
  183. *
  184. * @param v pathname
  185. * @return self when setting or value when getting
  186. */
  187. adapter(): AdapterConstructor | undefined;
  188. adapter(v: AdapterConstructor): this;
  189. /**
  190. * Attaches socket.io to a server or port.
  191. *
  192. * @param srv - server or port
  193. * @param opts - options passed to engine.io
  194. * @return self
  195. */
  196. listen(srv: http.Server | HTTPSServer | Http2SecureServer | number, opts?: Partial<ServerOptions>): this;
  197. /**
  198. * Attaches socket.io to a server or port.
  199. *
  200. * @param srv - server or port
  201. * @param opts - options passed to engine.io
  202. * @return self
  203. */
  204. attach(srv: http.Server | HTTPSServer | Http2SecureServer | number, opts?: Partial<ServerOptions>): this;
  205. attachApp(app: any, opts?: Partial<ServerOptions>): void;
  206. /**
  207. * Initialize engine
  208. *
  209. * @param srv - the server to attach to
  210. * @param opts - options passed to engine.io
  211. * @private
  212. */
  213. private initEngine;
  214. /**
  215. * Attaches the static file serving.
  216. *
  217. * @param srv http server
  218. * @private
  219. */
  220. private attachServe;
  221. /**
  222. * Handles a request serving of client source and map
  223. *
  224. * @param req
  225. * @param res
  226. * @private
  227. */
  228. private serve;
  229. /**
  230. * @param filename
  231. * @param req
  232. * @param res
  233. * @private
  234. */
  235. private static sendFile;
  236. /**
  237. * Binds socket.io to an engine.io instance.
  238. *
  239. * @param engine engine.io (or compatible) server
  240. * @return self
  241. */
  242. bind(engine: BaseServer): this;
  243. /**
  244. * Called with each incoming transport connection.
  245. *
  246. * @param {engine.Socket} conn
  247. * @return self
  248. * @private
  249. */
  250. private onconnection;
  251. /**
  252. * Looks up a namespace.
  253. *
  254. * @example
  255. * // with a simple string
  256. * const myNamespace = io.of("/my-namespace");
  257. *
  258. * // with a regex
  259. * const dynamicNsp = io.of(/^\/dynamic-\d+$/).on("connection", (socket) => {
  260. * const namespace = socket.nsp; // newNamespace.name === "/dynamic-101"
  261. *
  262. * // broadcast to all clients in the given sub-namespace
  263. * namespace.emit("hello");
  264. * });
  265. *
  266. * @param name - nsp name
  267. * @param fn optional, nsp `connection` ev handler
  268. */
  269. of(name: string | RegExp | ParentNspNameMatchFn, fn?: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>) => void): Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData>;
  270. /**
  271. * Closes server connection
  272. *
  273. * @param [fn] optional, called as `fn([err])` on error OR all conns closed
  274. */
  275. close(fn?: (err?: Error) => void): void;
  276. /**
  277. * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}.
  278. *
  279. * @example
  280. * io.use((socket, next) => {
  281. * // ...
  282. * next();
  283. * });
  284. *
  285. * @param fn - the middleware function
  286. */
  287. use(fn: (socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, next: (err?: ExtendedError) => void) => void): this;
  288. /**
  289. * Targets a room when emitting.
  290. *
  291. * @example
  292. * // the “foo” event will be broadcast to all connected clients in the “room-101” room
  293. * io.to("room-101").emit("foo", "bar");
  294. *
  295. * // with an array of rooms (a client will be notified at most once)
  296. * io.to(["room-101", "room-102"]).emit("foo", "bar");
  297. *
  298. * // with multiple chained calls
  299. * io.to("room-101").to("room-102").emit("foo", "bar");
  300. *
  301. * @param room - a room, or an array of rooms
  302. * @return a new {@link BroadcastOperator} instance for chaining
  303. */
  304. to(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  305. /**
  306. * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases:
  307. *
  308. * @example
  309. * // disconnect all clients in the "room-101" room
  310. * io.in("room-101").disconnectSockets();
  311. *
  312. * @param room - a room, or an array of rooms
  313. * @return a new {@link BroadcastOperator} instance for chaining
  314. */
  315. in(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  316. /**
  317. * Excludes a room when emitting.
  318. *
  319. * @example
  320. * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
  321. * io.except("room-101").emit("foo", "bar");
  322. *
  323. * // with an array of rooms
  324. * io.except(["room-101", "room-102"]).emit("foo", "bar");
  325. *
  326. * // with multiple chained calls
  327. * io.except("room-101").except("room-102").emit("foo", "bar");
  328. *
  329. * @param room - a room, or an array of rooms
  330. * @return a new {@link BroadcastOperator} instance for chaining
  331. */
  332. except(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  333. /**
  334. * Emits an event and waits for an acknowledgement from all clients.
  335. *
  336. * @example
  337. * try {
  338. * const responses = await io.timeout(1000).emitWithAck("some-event");
  339. * console.log(responses); // one response per client
  340. * } catch (e) {
  341. * // some clients did not acknowledge the event in the given delay
  342. * }
  343. *
  344. * @return a Promise that will be fulfilled when all clients have acknowledged the event
  345. */
  346. emitWithAck<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>): Promise<SecondArg<Last<EventParams<EmitEvents, Ev>>>>;
  347. /**
  348. * Sends a `message` event to all clients.
  349. *
  350. * This method mimics the WebSocket.send() method.
  351. *
  352. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  353. *
  354. * @example
  355. * io.send("hello");
  356. *
  357. * // this is equivalent to
  358. * io.emit("message", "hello");
  359. *
  360. * @return self
  361. */
  362. send(...args: EventParams<EmitEvents, "message">): this;
  363. /**
  364. * Sends a `message` event to all clients. Alias of {@link send}.
  365. *
  366. * @return self
  367. */
  368. write(...args: EventParams<EmitEvents, "message">): this;
  369. /**
  370. * Sends a message to the other Socket.IO servers of the cluster.
  371. *
  372. * @example
  373. * io.serverSideEmit("hello", "world");
  374. *
  375. * io.on("hello", (arg1) => {
  376. * console.log(arg1); // prints "world"
  377. * });
  378. *
  379. * // acknowledgements (without binary content) are supported too:
  380. * io.serverSideEmit("ping", (err, responses) => {
  381. * if (err) {
  382. * // some servers did not acknowledge the event in the given delay
  383. * } else {
  384. * console.log(responses); // one response per server (except the current one)
  385. * }
  386. * });
  387. *
  388. * io.on("ping", (cb) => {
  389. * cb("pong");
  390. * });
  391. *
  392. * @param ev - the event name
  393. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  394. */
  395. serverSideEmit<Ev extends EventNames<ServerSideEvents>>(ev: Ev, ...args: EventParams<DecorateAcknowledgementsWithTimeoutAndMultipleResponses<ServerSideEvents>, Ev>): boolean;
  396. /**
  397. * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
  398. *
  399. * @example
  400. * try {
  401. * const responses = await io.serverSideEmitWithAck("ping");
  402. * console.log(responses); // one response per server (except the current one)
  403. * } catch (e) {
  404. * // some servers did not acknowledge the event in the given delay
  405. * }
  406. *
  407. * @param ev - the event name
  408. * @param args - an array of arguments
  409. *
  410. * @return a Promise that will be fulfilled when all servers have acknowledged the event
  411. */
  412. serverSideEmitWithAck<Ev extends EventNames<ServerSideEvents>>(ev: Ev, ...args: AllButLast<EventParams<ServerSideEvents, Ev>>): Promise<FirstArg<Last<EventParams<ServerSideEvents, Ev>>>[]>;
  413. /**
  414. * Gets a list of socket ids.
  415. *
  416. * @deprecated this method will be removed in the next major release, please use {@link Server#serverSideEmit} or
  417. * {@link Server#fetchSockets} instead.
  418. */
  419. allSockets(): Promise<Set<SocketId>>;
  420. /**
  421. * Sets the compress flag.
  422. *
  423. * @example
  424. * io.compress(false).emit("hello");
  425. *
  426. * @param compress - if `true`, compresses the sending data
  427. * @return a new {@link BroadcastOperator} instance for chaining
  428. */
  429. compress(compress: boolean): BroadcastOperator<EmitEvents, SocketData>;
  430. /**
  431. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  432. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  433. * and is in the middle of a request-response cycle).
  434. *
  435. * @example
  436. * io.volatile.emit("hello"); // the clients may or may not receive it
  437. *
  438. * @return a new {@link BroadcastOperator} instance for chaining
  439. */
  440. get volatile(): BroadcastOperator<EmitEvents, SocketData>;
  441. /**
  442. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  443. *
  444. * @example
  445. * // the “foo” event will be broadcast to all connected clients on this node
  446. * io.local.emit("foo", "bar");
  447. *
  448. * @return a new {@link BroadcastOperator} instance for chaining
  449. */
  450. get local(): BroadcastOperator<EmitEvents, SocketData>;
  451. /**
  452. * Adds a timeout in milliseconds for the next operation.
  453. *
  454. * @example
  455. * io.timeout(1000).emit("some-event", (err, responses) => {
  456. * if (err) {
  457. * // some clients did not acknowledge the event in the given delay
  458. * } else {
  459. * console.log(responses); // one response per client
  460. * }
  461. * });
  462. *
  463. * @param timeout
  464. */
  465. timeout(timeout: number): BroadcastOperator<DecorateAcknowledgementsWithTimeoutAndMultipleResponses<EmitEvents>, SocketData>;
  466. /**
  467. * Returns the matching socket instances.
  468. *
  469. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  470. *
  471. * @example
  472. * // return all Socket instances
  473. * const sockets = await io.fetchSockets();
  474. *
  475. * // return all Socket instances in the "room1" room
  476. * const sockets = await io.in("room1").fetchSockets();
  477. *
  478. * for (const socket of sockets) {
  479. * console.log(socket.id);
  480. * console.log(socket.handshake);
  481. * console.log(socket.rooms);
  482. * console.log(socket.data);
  483. *
  484. * socket.emit("hello");
  485. * socket.join("room1");
  486. * socket.leave("room2");
  487. * socket.disconnect();
  488. * }
  489. */
  490. fetchSockets(): Promise<RemoteSocket<EmitEvents, SocketData>[]>;
  491. /**
  492. * Makes the matching socket instances join the specified rooms.
  493. *
  494. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  495. *
  496. * @example
  497. *
  498. * // make all socket instances join the "room1" room
  499. * io.socketsJoin("room1");
  500. *
  501. * // make all socket instances in the "room1" room join the "room2" and "room3" rooms
  502. * io.in("room1").socketsJoin(["room2", "room3"]);
  503. *
  504. * @param room - a room, or an array of rooms
  505. */
  506. socketsJoin(room: Room | Room[]): void;
  507. /**
  508. * Makes the matching socket instances leave the specified rooms.
  509. *
  510. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  511. *
  512. * @example
  513. * // make all socket instances leave the "room1" room
  514. * io.socketsLeave("room1");
  515. *
  516. * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
  517. * io.in("room1").socketsLeave(["room2", "room3"]);
  518. *
  519. * @param room - a room, or an array of rooms
  520. */
  521. socketsLeave(room: Room | Room[]): void;
  522. /**
  523. * Makes the matching socket instances disconnect.
  524. *
  525. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  526. *
  527. * @example
  528. * // make all socket instances disconnect (the connections might be kept alive for other namespaces)
  529. * io.disconnectSockets();
  530. *
  531. * // make all socket instances in the "room1" room disconnect and close the underlying connections
  532. * io.in("room1").disconnectSockets(true);
  533. *
  534. * @param close - whether to close the underlying connection
  535. */
  536. disconnectSockets(close?: boolean): void;
  537. }
  538. export { Socket, DisconnectReason, ServerOptions, Namespace, BroadcastOperator, RemoteSocket, };
  539. export { Event } from "./socket";