Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.d.ts 16KB

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