socket.d.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. /// <reference types="node" />
  2. import { Packet } from "socket.io-parser";
  3. import { EventParams, EventNames, EventsMap, StrictEventEmitter, DefaultEventsMap } from "./typed-events";
  4. import type { Client } from "./client";
  5. import type { Namespace } from "./namespace";
  6. import type { IncomingMessage, IncomingHttpHeaders } from "http";
  7. import type { Room, SocketId } from "socket.io-adapter";
  8. import type { ParsedUrlQuery } from "querystring";
  9. import { BroadcastOperator } from "./broadcast-operator";
  10. export interface SocketReservedEventsMap {
  11. disconnect: (reason: string) => void;
  12. disconnecting: (reason: string) => void;
  13. error: (err: Error) => void;
  14. }
  15. export interface EventEmitterReservedEventsMap {
  16. newListener: (eventName: string | Symbol, listener: (...args: any[]) => void) => void;
  17. removeListener: (eventName: string | Symbol, listener: (...args: any[]) => void) => void;
  18. }
  19. export declare const RESERVED_EVENTS: ReadonlySet<string | Symbol>;
  20. /**
  21. * The handshake details
  22. */
  23. export interface Handshake {
  24. /**
  25. * The headers sent as part of the handshake
  26. */
  27. headers: IncomingHttpHeaders;
  28. /**
  29. * The date of creation (as string)
  30. */
  31. time: string;
  32. /**
  33. * The ip of the client
  34. */
  35. address: string;
  36. /**
  37. * Whether the connection is cross-domain
  38. */
  39. xdomain: boolean;
  40. /**
  41. * Whether the connection is secure
  42. */
  43. secure: boolean;
  44. /**
  45. * The date of creation (as unix timestamp)
  46. */
  47. issued: number;
  48. /**
  49. * The request URL string
  50. */
  51. url: string;
  52. /**
  53. * The query object
  54. */
  55. query: ParsedUrlQuery;
  56. /**
  57. * The auth object
  58. */
  59. auth: {
  60. [key: string]: any;
  61. };
  62. }
  63. /**
  64. * `[eventName, ...args]`
  65. */
  66. export declare type Event = [string, ...any[]];
  67. export declare class Socket<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents, ServerSideEvents extends EventsMap = DefaultEventsMap, SocketData = any> extends StrictEventEmitter<ListenEvents, EmitEvents, SocketReservedEventsMap> {
  68. readonly nsp: Namespace<ListenEvents, EmitEvents, ServerSideEvents>;
  69. readonly client: Client<ListenEvents, EmitEvents, ServerSideEvents>;
  70. readonly id: SocketId;
  71. readonly handshake: Handshake;
  72. /**
  73. * Additional information that can be attached to the Socket instance and which will be used in the fetchSockets method
  74. */
  75. data: Partial<SocketData>;
  76. connected: boolean;
  77. private readonly server;
  78. private readonly adapter;
  79. private acks;
  80. private fns;
  81. private flags;
  82. private _anyListeners?;
  83. private _anyOutgoingListeners?;
  84. /**
  85. * Interface to a `Client` for a given `Namespace`.
  86. *
  87. * @param {Namespace} nsp
  88. * @param {Client} client
  89. * @param {Object} auth
  90. * @package
  91. */
  92. constructor(nsp: Namespace<ListenEvents, EmitEvents, ServerSideEvents>, client: Client<ListenEvents, EmitEvents, ServerSideEvents>, auth: object);
  93. /**
  94. * Builds the `handshake` BC object
  95. *
  96. * @private
  97. */
  98. private buildHandshake;
  99. /**
  100. * Emits to this client.
  101. *
  102. * @return Always returns `true`.
  103. * @public
  104. */
  105. emit<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): boolean;
  106. /**
  107. * @private
  108. */
  109. private registerAckCallback;
  110. /**
  111. * Targets a room when broadcasting.
  112. *
  113. * @param room
  114. * @return self
  115. * @public
  116. */
  117. to(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  118. /**
  119. * Targets a room when broadcasting.
  120. *
  121. * @param room
  122. * @return self
  123. * @public
  124. */
  125. in(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  126. /**
  127. * Excludes a room when broadcasting.
  128. *
  129. * @param room
  130. * @return self
  131. * @public
  132. */
  133. except(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData>;
  134. /**
  135. * Sends a `message` event.
  136. *
  137. * @return self
  138. * @public
  139. */
  140. send(...args: EventParams<EmitEvents, "message">): this;
  141. /**
  142. * Sends a `message` event.
  143. *
  144. * @return self
  145. * @public
  146. */
  147. write(...args: EventParams<EmitEvents, "message">): this;
  148. /**
  149. * Writes a packet.
  150. *
  151. * @param {Object} packet - packet object
  152. * @param {Object} opts - options
  153. * @private
  154. */
  155. private packet;
  156. /**
  157. * Joins a room.
  158. *
  159. * @param {String|Array} rooms - room or array of rooms
  160. * @return a Promise or nothing, depending on the adapter
  161. * @public
  162. */
  163. join(rooms: Room | Array<Room>): Promise<void> | void;
  164. /**
  165. * Leaves a room.
  166. *
  167. * @param {String} room
  168. * @return a Promise or nothing, depending on the adapter
  169. * @public
  170. */
  171. leave(room: string): Promise<void> | void;
  172. /**
  173. * Leave all rooms.
  174. *
  175. * @private
  176. */
  177. private leaveAll;
  178. /**
  179. * Called by `Namespace` upon successful
  180. * middleware execution (ie: authorization).
  181. * Socket is added to namespace array before
  182. * call to join, so adapters can access it.
  183. *
  184. * @private
  185. */
  186. _onconnect(): void;
  187. /**
  188. * Called with each packet. Called by `Client`.
  189. *
  190. * @param {Object} packet
  191. * @private
  192. */
  193. _onpacket(packet: Packet): void;
  194. /**
  195. * Called upon event packet.
  196. *
  197. * @param {Packet} packet - packet object
  198. * @private
  199. */
  200. private onevent;
  201. /**
  202. * Produces an ack callback to emit with an event.
  203. *
  204. * @param {Number} id - packet id
  205. * @private
  206. */
  207. private ack;
  208. /**
  209. * Called upon ack packet.
  210. *
  211. * @private
  212. */
  213. private onack;
  214. /**
  215. * Called upon client disconnect packet.
  216. *
  217. * @private
  218. */
  219. private ondisconnect;
  220. /**
  221. * Handles a client error.
  222. *
  223. * @private
  224. */
  225. _onerror(err: Error): void;
  226. /**
  227. * Called upon closing. Called by `Client`.
  228. *
  229. * @param {String} reason
  230. * @throw {Error} optional error object
  231. *
  232. * @private
  233. */
  234. _onclose(reason: string): this | undefined;
  235. /**
  236. * Produces an `error` packet.
  237. *
  238. * @param {Object} err - error object
  239. *
  240. * @private
  241. */
  242. _error(err: any): void;
  243. /**
  244. * Disconnects this client.
  245. *
  246. * @param {Boolean} close - if `true`, closes the underlying connection
  247. * @return {Socket} self
  248. *
  249. * @public
  250. */
  251. disconnect(close?: boolean): this;
  252. /**
  253. * Sets the compress flag.
  254. *
  255. * @param {Boolean} compress - if `true`, compresses the sending data
  256. * @return {Socket} self
  257. * @public
  258. */
  259. compress(compress: boolean): this;
  260. /**
  261. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  262. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  263. * and is in the middle of a request-response cycle).
  264. *
  265. * @return {Socket} self
  266. * @public
  267. */
  268. get volatile(): this;
  269. /**
  270. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the
  271. * sender.
  272. *
  273. * @return {Socket} self
  274. * @public
  275. */
  276. get broadcast(): BroadcastOperator<EmitEvents, SocketData>;
  277. /**
  278. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  279. *
  280. * @return {Socket} self
  281. * @public
  282. */
  283. get local(): BroadcastOperator<EmitEvents, SocketData>;
  284. /**
  285. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  286. * given number of milliseconds have elapsed without an acknowledgement from the client:
  287. *
  288. * ```
  289. * socket.timeout(5000).emit("my-event", (err) => {
  290. * if (err) {
  291. * // the client did not acknowledge the event in the given delay
  292. * }
  293. * });
  294. * ```
  295. *
  296. * @returns self
  297. * @public
  298. */
  299. timeout(timeout: number): this;
  300. /**
  301. * Dispatch incoming event to socket listeners.
  302. *
  303. * @param {Array} event - event that will get emitted
  304. * @private
  305. */
  306. private dispatch;
  307. /**
  308. * Sets up socket middleware.
  309. *
  310. * @param {Function} fn - middleware function (event, next)
  311. * @return {Socket} self
  312. * @public
  313. */
  314. use(fn: (event: Event, next: (err?: Error) => void) => void): this;
  315. /**
  316. * Executes the middleware for an incoming event.
  317. *
  318. * @param {Array} event - event that will get emitted
  319. * @param {Function} fn - last fn call in the middleware
  320. * @private
  321. */
  322. private run;
  323. /**
  324. * Whether the socket is currently disconnected
  325. */
  326. get disconnected(): boolean;
  327. /**
  328. * A reference to the request that originated the underlying Engine.IO Socket.
  329. *
  330. * @public
  331. */
  332. get request(): IncomingMessage;
  333. /**
  334. * A reference to the underlying Client transport connection (Engine.IO Socket object).
  335. *
  336. * @public
  337. */
  338. get conn(): import("engine.io").Socket;
  339. /**
  340. * @public
  341. */
  342. get rooms(): Set<Room>;
  343. /**
  344. * Adds a listener that will be fired when any event is received. The event name is passed as the first argument to
  345. * the callback.
  346. *
  347. * @param listener
  348. * @public
  349. */
  350. onAny(listener: (...args: any[]) => void): this;
  351. /**
  352. * Adds a listener that will be fired when any event is received. The event name is passed as the first argument to
  353. * the callback. The listener is added to the beginning of the listeners array.
  354. *
  355. * @param listener
  356. * @public
  357. */
  358. prependAny(listener: (...args: any[]) => void): this;
  359. /**
  360. * Removes the listener that will be fired when any event is received.
  361. *
  362. * @param listener
  363. * @public
  364. */
  365. offAny(listener?: (...args: any[]) => void): this;
  366. /**
  367. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  368. * e.g. to remove listeners.
  369. *
  370. * @public
  371. */
  372. listenersAny(): ((...args: any[]) => void)[];
  373. /**
  374. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  375. * callback.
  376. *
  377. * @param listener
  378. *
  379. * <pre><code>
  380. *
  381. * socket.onAnyOutgoing((event, ...args) => {
  382. * console.log(event);
  383. * });
  384. *
  385. * </pre></code>
  386. *
  387. * @public
  388. */
  389. onAnyOutgoing(listener: (...args: any[]) => void): this;
  390. /**
  391. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  392. * callback. The listener is added to the beginning of the listeners array.
  393. *
  394. * @param listener
  395. *
  396. * <pre><code>
  397. *
  398. * socket.prependAnyOutgoing((event, ...args) => {
  399. * console.log(event);
  400. * });
  401. *
  402. * </pre></code>
  403. *
  404. * @public
  405. */
  406. prependAnyOutgoing(listener: (...args: any[]) => void): this;
  407. /**
  408. * Removes the listener that will be fired when any event is emitted.
  409. *
  410. * @param listener
  411. *
  412. * <pre><code>
  413. *
  414. * const handler = (event, ...args) => {
  415. * console.log(event);
  416. * }
  417. *
  418. * socket.onAnyOutgoing(handler);
  419. *
  420. * // then later
  421. * socket.offAnyOutgoing(handler);
  422. *
  423. * </pre></code>
  424. *
  425. * @public
  426. */
  427. offAnyOutgoing(listener?: (...args: any[]) => void): this;
  428. /**
  429. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  430. * e.g. to remove listeners.
  431. *
  432. * @public
  433. */
  434. listenersAnyOutgoing(): ((...args: any[]) => void)[];
  435. /**
  436. * Notify the listeners for each packet sent (emit or broadcast)
  437. *
  438. * @param packet
  439. *
  440. * @private
  441. */
  442. private notifyOutgoingListeners;
  443. private newBroadcastOperator;
  444. }