namespace.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.Namespace = exports.RESERVED_EVENTS = void 0;
  7. const socket_1 = require("./socket");
  8. const typed_events_1 = require("./typed-events");
  9. const debug_1 = __importDefault(require("debug"));
  10. const broadcast_operator_1 = require("./broadcast-operator");
  11. const debug = (0, debug_1.default)("socket.io:namespace");
  12. exports.RESERVED_EVENTS = new Set(["connect", "connection", "new_namespace"]);
  13. /**
  14. * A Namespace is a communication channel that allows you to split the logic of your application over a single shared
  15. * connection.
  16. *
  17. * Each namespace has its own:
  18. *
  19. * - event handlers
  20. *
  21. * ```
  22. * io.of("/orders").on("connection", (socket) => {
  23. * socket.on("order:list", () => {});
  24. * socket.on("order:create", () => {});
  25. * });
  26. *
  27. * io.of("/users").on("connection", (socket) => {
  28. * socket.on("user:list", () => {});
  29. * });
  30. * ```
  31. *
  32. * - rooms
  33. *
  34. * ```
  35. * const orderNamespace = io.of("/orders");
  36. *
  37. * orderNamespace.on("connection", (socket) => {
  38. * socket.join("room1");
  39. * orderNamespace.to("room1").emit("hello");
  40. * });
  41. *
  42. * const userNamespace = io.of("/users");
  43. *
  44. * userNamespace.on("connection", (socket) => {
  45. * socket.join("room1"); // distinct from the room in the "orders" namespace
  46. * userNamespace.to("room1").emit("holà");
  47. * });
  48. * ```
  49. *
  50. * - middlewares
  51. *
  52. * ```
  53. * const orderNamespace = io.of("/orders");
  54. *
  55. * orderNamespace.use((socket, next) => {
  56. * // ensure the socket has access to the "orders" namespace
  57. * });
  58. *
  59. * const userNamespace = io.of("/users");
  60. *
  61. * userNamespace.use((socket, next) => {
  62. * // ensure the socket has access to the "users" namespace
  63. * });
  64. * ```
  65. */
  66. class Namespace extends typed_events_1.StrictEventEmitter {
  67. /**
  68. * Namespace constructor.
  69. *
  70. * @param server instance
  71. * @param name
  72. */
  73. constructor(server, name) {
  74. super();
  75. this.sockets = new Map();
  76. /** @private */
  77. this._fns = [];
  78. /** @private */
  79. this._ids = 0;
  80. this.server = server;
  81. this.name = name;
  82. this._initAdapter();
  83. }
  84. /**
  85. * Initializes the `Adapter` for this nsp.
  86. * Run upon changing adapter by `Server#adapter`
  87. * in addition to the constructor.
  88. *
  89. * @private
  90. */
  91. _initAdapter() {
  92. // @ts-ignore
  93. this.adapter = new (this.server.adapter())(this);
  94. }
  95. /**
  96. * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}.
  97. *
  98. * @example
  99. * const myNamespace = io.of("/my-namespace");
  100. *
  101. * myNamespace.use((socket, next) => {
  102. * // ...
  103. * next();
  104. * });
  105. *
  106. * @param fn - the middleware function
  107. */
  108. use(fn) {
  109. this._fns.push(fn);
  110. return this;
  111. }
  112. /**
  113. * Executes the middleware for an incoming client.
  114. *
  115. * @param socket - the socket that will get added
  116. * @param fn - last fn call in the middleware
  117. * @private
  118. */
  119. run(socket, fn) {
  120. const fns = this._fns.slice(0);
  121. if (!fns.length)
  122. return fn(null);
  123. function run(i) {
  124. fns[i](socket, function (err) {
  125. // upon error, short-circuit
  126. if (err)
  127. return fn(err);
  128. // if no middleware left, summon callback
  129. if (!fns[i + 1])
  130. return fn(null);
  131. // go on to next
  132. run(i + 1);
  133. });
  134. }
  135. run(0);
  136. }
  137. /**
  138. * Targets a room when emitting.
  139. *
  140. * @example
  141. * const myNamespace = io.of("/my-namespace");
  142. *
  143. * // the “foo” event will be broadcast to all connected clients in the “room-101” room
  144. * myNamespace.to("room-101").emit("foo", "bar");
  145. *
  146. * // with an array of rooms (a client will be notified at most once)
  147. * myNamespace.to(["room-101", "room-102"]).emit("foo", "bar");
  148. *
  149. * // with multiple chained calls
  150. * myNamespace.to("room-101").to("room-102").emit("foo", "bar");
  151. *
  152. * @param room - a room, or an array of rooms
  153. * @return a new {@link BroadcastOperator} instance for chaining
  154. */
  155. to(room) {
  156. return new broadcast_operator_1.BroadcastOperator(this.adapter).to(room);
  157. }
  158. /**
  159. * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases:
  160. *
  161. * @example
  162. * const myNamespace = io.of("/my-namespace");
  163. *
  164. * // disconnect all clients in the "room-101" room
  165. * myNamespace.in("room-101").disconnectSockets();
  166. *
  167. * @param room - a room, or an array of rooms
  168. * @return a new {@link BroadcastOperator} instance for chaining
  169. */
  170. in(room) {
  171. return new broadcast_operator_1.BroadcastOperator(this.adapter).in(room);
  172. }
  173. /**
  174. * Excludes a room when emitting.
  175. *
  176. * @example
  177. * const myNamespace = io.of("/my-namespace");
  178. *
  179. * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
  180. * myNamespace.except("room-101").emit("foo", "bar");
  181. *
  182. * // with an array of rooms
  183. * myNamespace.except(["room-101", "room-102"]).emit("foo", "bar");
  184. *
  185. * // with multiple chained calls
  186. * myNamespace.except("room-101").except("room-102").emit("foo", "bar");
  187. *
  188. * @param room - a room, or an array of rooms
  189. * @return a new {@link BroadcastOperator} instance for chaining
  190. */
  191. except(room) {
  192. return new broadcast_operator_1.BroadcastOperator(this.adapter).except(room);
  193. }
  194. /**
  195. * Adds a new client.
  196. *
  197. * @return {Socket}
  198. * @private
  199. */
  200. async _add(client, auth, fn) {
  201. var _a;
  202. debug("adding socket to nsp %s", this.name);
  203. const socket = await this._createSocket(client, auth);
  204. if (
  205. // @ts-ignore
  206. ((_a = this.server.opts.connectionStateRecovery) === null || _a === void 0 ? void 0 : _a.skipMiddlewares) &&
  207. socket.recovered &&
  208. client.conn.readyState === "open") {
  209. return this._doConnect(socket, fn);
  210. }
  211. this.run(socket, (err) => {
  212. process.nextTick(() => {
  213. if ("open" !== client.conn.readyState) {
  214. debug("next called after client was closed - ignoring socket");
  215. socket._cleanup();
  216. return;
  217. }
  218. if (err) {
  219. debug("middleware error, sending CONNECT_ERROR packet to the client");
  220. socket._cleanup();
  221. if (client.conn.protocol === 3) {
  222. return socket._error(err.data || err.message);
  223. }
  224. else {
  225. return socket._error({
  226. message: err.message,
  227. data: err.data,
  228. });
  229. }
  230. }
  231. this._doConnect(socket, fn);
  232. });
  233. });
  234. }
  235. async _createSocket(client, auth) {
  236. const sessionId = auth.pid;
  237. const offset = auth.offset;
  238. if (
  239. // @ts-ignore
  240. this.server.opts.connectionStateRecovery &&
  241. typeof sessionId === "string" &&
  242. typeof offset === "string") {
  243. let session;
  244. try {
  245. session = await this.adapter.restoreSession(sessionId, offset);
  246. }
  247. catch (e) {
  248. debug("error while restoring session: %s", e);
  249. }
  250. if (session) {
  251. debug("connection state recovered for sid %s", session.sid);
  252. return new socket_1.Socket(this, client, auth, session);
  253. }
  254. }
  255. return new socket_1.Socket(this, client, auth);
  256. }
  257. _doConnect(socket, fn) {
  258. // track socket
  259. this.sockets.set(socket.id, socket);
  260. // it's paramount that the internal `onconnect` logic
  261. // fires before user-set events to prevent state order
  262. // violations (such as a disconnection before the connection
  263. // logic is complete)
  264. socket._onconnect();
  265. if (fn)
  266. fn(socket);
  267. // fire user-set events
  268. this.emitReserved("connect", socket);
  269. this.emitReserved("connection", socket);
  270. }
  271. /**
  272. * Removes a client. Called by each `Socket`.
  273. *
  274. * @private
  275. */
  276. _remove(socket) {
  277. if (this.sockets.has(socket.id)) {
  278. this.sockets.delete(socket.id);
  279. }
  280. else {
  281. debug("ignoring remove for %s", socket.id);
  282. }
  283. }
  284. /**
  285. * Emits to all connected clients.
  286. *
  287. * @example
  288. * const myNamespace = io.of("/my-namespace");
  289. *
  290. * myNamespace.emit("hello", "world");
  291. *
  292. * // all serializable datastructures are supported (no need to call JSON.stringify)
  293. * myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  294. *
  295. * // with an acknowledgement from the clients
  296. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  297. * if (err) {
  298. * // some clients did not acknowledge the event in the given delay
  299. * } else {
  300. * console.log(responses); // one response per client
  301. * }
  302. * });
  303. *
  304. * @return Always true
  305. */
  306. emit(ev, ...args) {
  307. return new broadcast_operator_1.BroadcastOperator(this.adapter).emit(ev, ...args);
  308. }
  309. /**
  310. * Emits an event and waits for an acknowledgement from all clients.
  311. *
  312. * @example
  313. * const myNamespace = io.of("/my-namespace");
  314. *
  315. * try {
  316. * const responses = await myNamespace.timeout(1000).emitWithAck("some-event");
  317. * console.log(responses); // one response per client
  318. * } catch (e) {
  319. * // some clients did not acknowledge the event in the given delay
  320. * }
  321. *
  322. * @return a Promise that will be fulfilled when all clients have acknowledged the event
  323. */
  324. emitWithAck(ev, ...args) {
  325. return new broadcast_operator_1.BroadcastOperator(this.adapter).emitWithAck(ev, ...args);
  326. }
  327. /**
  328. * Sends a `message` event to all clients.
  329. *
  330. * This method mimics the WebSocket.send() method.
  331. *
  332. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  333. *
  334. * @example
  335. * const myNamespace = io.of("/my-namespace");
  336. *
  337. * myNamespace.send("hello");
  338. *
  339. * // this is equivalent to
  340. * myNamespace.emit("message", "hello");
  341. *
  342. * @return self
  343. */
  344. send(...args) {
  345. this.emit("message", ...args);
  346. return this;
  347. }
  348. /**
  349. * Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}.
  350. *
  351. * @return self
  352. */
  353. write(...args) {
  354. this.emit("message", ...args);
  355. return this;
  356. }
  357. /**
  358. * Sends a message to the other Socket.IO servers of the cluster.
  359. *
  360. * @example
  361. * const myNamespace = io.of("/my-namespace");
  362. *
  363. * myNamespace.serverSideEmit("hello", "world");
  364. *
  365. * myNamespace.on("hello", (arg1) => {
  366. * console.log(arg1); // prints "world"
  367. * });
  368. *
  369. * // acknowledgements (without binary content) are supported too:
  370. * myNamespace.serverSideEmit("ping", (err, responses) => {
  371. * if (err) {
  372. * // some servers did not acknowledge the event in the given delay
  373. * } else {
  374. * console.log(responses); // one response per server (except the current one)
  375. * }
  376. * });
  377. *
  378. * myNamespace.on("ping", (cb) => {
  379. * cb("pong");
  380. * });
  381. *
  382. * @param ev - the event name
  383. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  384. */
  385. serverSideEmit(ev, ...args) {
  386. if (exports.RESERVED_EVENTS.has(ev)) {
  387. throw new Error(`"${String(ev)}" is a reserved event name`);
  388. }
  389. args.unshift(ev);
  390. this.adapter.serverSideEmit(args);
  391. return true;
  392. }
  393. /**
  394. * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
  395. *
  396. * @example
  397. * const myNamespace = io.of("/my-namespace");
  398. *
  399. * try {
  400. * const responses = await myNamespace.serverSideEmitWithAck("ping");
  401. * console.log(responses); // one response per server (except the current one)
  402. * } catch (e) {
  403. * // some servers did not acknowledge the event in the given delay
  404. * }
  405. *
  406. * @param ev - the event name
  407. * @param args - an array of arguments
  408. *
  409. * @return a Promise that will be fulfilled when all servers have acknowledged the event
  410. */
  411. serverSideEmitWithAck(ev, ...args) {
  412. return new Promise((resolve, reject) => {
  413. args.push((err, responses) => {
  414. if (err) {
  415. err.responses = responses;
  416. return reject(err);
  417. }
  418. else {
  419. return resolve(responses);
  420. }
  421. });
  422. this.serverSideEmit(ev, ...args);
  423. });
  424. }
  425. /**
  426. * Called when a packet is received from another Socket.IO server
  427. *
  428. * @param args - an array of arguments, which may include an acknowledgement callback at the end
  429. *
  430. * @private
  431. */
  432. _onServerSideEmit(args) {
  433. super.emitUntyped.apply(this, args);
  434. }
  435. /**
  436. * Gets a list of clients.
  437. *
  438. * @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or
  439. * {@link Namespace#fetchSockets} instead.
  440. */
  441. allSockets() {
  442. return new broadcast_operator_1.BroadcastOperator(this.adapter).allSockets();
  443. }
  444. /**
  445. * Sets the compress flag.
  446. *
  447. * @example
  448. * const myNamespace = io.of("/my-namespace");
  449. *
  450. * myNamespace.compress(false).emit("hello");
  451. *
  452. * @param compress - if `true`, compresses the sending data
  453. * @return self
  454. */
  455. compress(compress) {
  456. return new broadcast_operator_1.BroadcastOperator(this.adapter).compress(compress);
  457. }
  458. /**
  459. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  460. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  461. * and is in the middle of a request-response cycle).
  462. *
  463. * @example
  464. * const myNamespace = io.of("/my-namespace");
  465. *
  466. * myNamespace.volatile.emit("hello"); // the clients may or may not receive it
  467. *
  468. * @return self
  469. */
  470. get volatile() {
  471. return new broadcast_operator_1.BroadcastOperator(this.adapter).volatile;
  472. }
  473. /**
  474. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  475. *
  476. * @example
  477. * const myNamespace = io.of("/my-namespace");
  478. *
  479. * // the “foo” event will be broadcast to all connected clients on this node
  480. * myNamespace.local.emit("foo", "bar");
  481. *
  482. * @return a new {@link BroadcastOperator} instance for chaining
  483. */
  484. get local() {
  485. return new broadcast_operator_1.BroadcastOperator(this.adapter).local;
  486. }
  487. /**
  488. * Adds a timeout in milliseconds for the next operation.
  489. *
  490. * @example
  491. * const myNamespace = io.of("/my-namespace");
  492. *
  493. * myNamespace.timeout(1000).emit("some-event", (err, responses) => {
  494. * if (err) {
  495. * // some clients did not acknowledge the event in the given delay
  496. * } else {
  497. * console.log(responses); // one response per client
  498. * }
  499. * });
  500. *
  501. * @param timeout
  502. */
  503. timeout(timeout) {
  504. return new broadcast_operator_1.BroadcastOperator(this.adapter).timeout(timeout);
  505. }
  506. /**
  507. * Returns the matching socket instances.
  508. *
  509. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  510. *
  511. * @example
  512. * const myNamespace = io.of("/my-namespace");
  513. *
  514. * // return all Socket instances
  515. * const sockets = await myNamespace.fetchSockets();
  516. *
  517. * // return all Socket instances in the "room1" room
  518. * const sockets = await myNamespace.in("room1").fetchSockets();
  519. *
  520. * for (const socket of sockets) {
  521. * console.log(socket.id);
  522. * console.log(socket.handshake);
  523. * console.log(socket.rooms);
  524. * console.log(socket.data);
  525. *
  526. * socket.emit("hello");
  527. * socket.join("room1");
  528. * socket.leave("room2");
  529. * socket.disconnect();
  530. * }
  531. */
  532. fetchSockets() {
  533. return new broadcast_operator_1.BroadcastOperator(this.adapter).fetchSockets();
  534. }
  535. /**
  536. * Makes the matching socket instances join the specified rooms.
  537. *
  538. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  539. *
  540. * @example
  541. * const myNamespace = io.of("/my-namespace");
  542. *
  543. * // make all socket instances join the "room1" room
  544. * myNamespace.socketsJoin("room1");
  545. *
  546. * // make all socket instances in the "room1" room join the "room2" and "room3" rooms
  547. * myNamespace.in("room1").socketsJoin(["room2", "room3"]);
  548. *
  549. * @param room - a room, or an array of rooms
  550. */
  551. socketsJoin(room) {
  552. return new broadcast_operator_1.BroadcastOperator(this.adapter).socketsJoin(room);
  553. }
  554. /**
  555. * Makes the matching socket instances leave the specified rooms.
  556. *
  557. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  558. *
  559. * @example
  560. * const myNamespace = io.of("/my-namespace");
  561. *
  562. * // make all socket instances leave the "room1" room
  563. * myNamespace.socketsLeave("room1");
  564. *
  565. * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
  566. * myNamespace.in("room1").socketsLeave(["room2", "room3"]);
  567. *
  568. * @param room - a room, or an array of rooms
  569. */
  570. socketsLeave(room) {
  571. return new broadcast_operator_1.BroadcastOperator(this.adapter).socketsLeave(room);
  572. }
  573. /**
  574. * Makes the matching socket instances disconnect.
  575. *
  576. * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
  577. *
  578. * @example
  579. * const myNamespace = io.of("/my-namespace");
  580. *
  581. * // make all socket instances disconnect (the connections might be kept alive for other namespaces)
  582. * myNamespace.disconnectSockets();
  583. *
  584. * // make all socket instances in the "room1" room disconnect and close the underlying connections
  585. * myNamespace.in("room1").disconnectSockets(true);
  586. *
  587. * @param close - whether to close the underlying connection
  588. */
  589. disconnectSockets(close = false) {
  590. return new broadcast_operator_1.BroadcastOperator(this.adapter).disconnectSockets(close);
  591. }
  592. }
  593. exports.Namespace = Namespace;