socket.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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.Socket = exports.RESERVED_EVENTS = void 0;
  7. const socket_io_parser_1 = require("socket.io-parser");
  8. const debug_1 = __importDefault(require("debug"));
  9. const typed_events_1 = require("./typed-events");
  10. const base64id_1 = __importDefault(require("base64id"));
  11. const broadcast_operator_1 = require("./broadcast-operator");
  12. const debug = (0, debug_1.default)("socket.io:socket");
  13. exports.RESERVED_EVENTS = new Set([
  14. "connect",
  15. "connect_error",
  16. "disconnect",
  17. "disconnecting",
  18. "newListener",
  19. "removeListener",
  20. ]);
  21. class Socket extends typed_events_1.StrictEventEmitter {
  22. /**
  23. * Interface to a `Client` for a given `Namespace`.
  24. *
  25. * @param {Namespace} nsp
  26. * @param {Client} client
  27. * @param {Object} auth
  28. * @package
  29. */
  30. constructor(nsp, client, auth) {
  31. super();
  32. this.nsp = nsp;
  33. this.client = client;
  34. /**
  35. * Additional information that can be attached to the Socket instance and which will be used in the fetchSockets method
  36. */
  37. this.data = {};
  38. this.connected = false;
  39. this.acks = new Map();
  40. this.fns = [];
  41. this.flags = {};
  42. this.server = nsp.server;
  43. this.adapter = this.nsp.adapter;
  44. if (client.conn.protocol === 3) {
  45. // @ts-ignore
  46. this.id = nsp.name !== "/" ? nsp.name + "#" + client.id : client.id;
  47. }
  48. else {
  49. this.id = base64id_1.default.generateId(); // don't reuse the Engine.IO id because it's sensitive information
  50. }
  51. this.handshake = this.buildHandshake(auth);
  52. }
  53. /**
  54. * Builds the `handshake` BC object
  55. *
  56. * @private
  57. */
  58. buildHandshake(auth) {
  59. return {
  60. headers: this.request.headers,
  61. time: new Date() + "",
  62. address: this.conn.remoteAddress,
  63. xdomain: !!this.request.headers.origin,
  64. // @ts-ignore
  65. secure: !!this.request.connection.encrypted,
  66. issued: +new Date(),
  67. url: this.request.url,
  68. // @ts-ignore
  69. query: this.request._query,
  70. auth,
  71. };
  72. }
  73. /**
  74. * Emits to this client.
  75. *
  76. * @return Always returns `true`.
  77. * @public
  78. */
  79. emit(ev, ...args) {
  80. if (exports.RESERVED_EVENTS.has(ev)) {
  81. throw new Error(`"${ev}" is a reserved event name`);
  82. }
  83. const data = [ev, ...args];
  84. const packet = {
  85. type: socket_io_parser_1.PacketType.EVENT,
  86. data: data,
  87. };
  88. // access last argument to see if it's an ACK callback
  89. if (typeof data[data.length - 1] === "function") {
  90. const id = this.nsp._ids++;
  91. debug("emitting packet with ack id %d", id);
  92. this.registerAckCallback(id, data.pop());
  93. packet.id = id;
  94. }
  95. const flags = Object.assign({}, this.flags);
  96. this.flags = {};
  97. this.notifyOutgoingListeners(packet);
  98. this.packet(packet, flags);
  99. return true;
  100. }
  101. /**
  102. * @private
  103. */
  104. registerAckCallback(id, ack) {
  105. const timeout = this.flags.timeout;
  106. if (timeout === undefined) {
  107. this.acks.set(id, ack);
  108. return;
  109. }
  110. const timer = setTimeout(() => {
  111. debug("event with ack id %d has timed out after %d ms", id, timeout);
  112. this.acks.delete(id);
  113. ack.call(this, new Error("operation has timed out"));
  114. }, timeout);
  115. this.acks.set(id, (...args) => {
  116. clearTimeout(timer);
  117. ack.apply(this, [null, ...args]);
  118. });
  119. }
  120. /**
  121. * Targets a room when broadcasting.
  122. *
  123. * @param room
  124. * @return self
  125. * @public
  126. */
  127. to(room) {
  128. return this.newBroadcastOperator().to(room);
  129. }
  130. /**
  131. * Targets a room when broadcasting.
  132. *
  133. * @param room
  134. * @return self
  135. * @public
  136. */
  137. in(room) {
  138. return this.newBroadcastOperator().in(room);
  139. }
  140. /**
  141. * Excludes a room when broadcasting.
  142. *
  143. * @param room
  144. * @return self
  145. * @public
  146. */
  147. except(room) {
  148. return this.newBroadcastOperator().except(room);
  149. }
  150. /**
  151. * Sends a `message` event.
  152. *
  153. * @return self
  154. * @public
  155. */
  156. send(...args) {
  157. this.emit("message", ...args);
  158. return this;
  159. }
  160. /**
  161. * Sends a `message` event.
  162. *
  163. * @return self
  164. * @public
  165. */
  166. write(...args) {
  167. this.emit("message", ...args);
  168. return this;
  169. }
  170. /**
  171. * Writes a packet.
  172. *
  173. * @param {Object} packet - packet object
  174. * @param {Object} opts - options
  175. * @private
  176. */
  177. packet(packet, opts = {}) {
  178. packet.nsp = this.nsp.name;
  179. opts.compress = false !== opts.compress;
  180. this.client._packet(packet, opts);
  181. }
  182. /**
  183. * Joins a room.
  184. *
  185. * @param {String|Array} rooms - room or array of rooms
  186. * @return a Promise or nothing, depending on the adapter
  187. * @public
  188. */
  189. join(rooms) {
  190. debug("join room %s", rooms);
  191. return this.adapter.addAll(this.id, new Set(Array.isArray(rooms) ? rooms : [rooms]));
  192. }
  193. /**
  194. * Leaves a room.
  195. *
  196. * @param {String} room
  197. * @return a Promise or nothing, depending on the adapter
  198. * @public
  199. */
  200. leave(room) {
  201. debug("leave room %s", room);
  202. return this.adapter.del(this.id, room);
  203. }
  204. /**
  205. * Leave all rooms.
  206. *
  207. * @private
  208. */
  209. leaveAll() {
  210. this.adapter.delAll(this.id);
  211. }
  212. /**
  213. * Called by `Namespace` upon successful
  214. * middleware execution (ie: authorization).
  215. * Socket is added to namespace array before
  216. * call to join, so adapters can access it.
  217. *
  218. * @private
  219. */
  220. _onconnect() {
  221. debug("socket connected - writing packet");
  222. this.connected = true;
  223. this.join(this.id);
  224. if (this.conn.protocol === 3) {
  225. this.packet({ type: socket_io_parser_1.PacketType.CONNECT });
  226. }
  227. else {
  228. this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: { sid: this.id } });
  229. }
  230. }
  231. /**
  232. * Called with each packet. Called by `Client`.
  233. *
  234. * @param {Object} packet
  235. * @private
  236. */
  237. _onpacket(packet) {
  238. debug("got packet %j", packet);
  239. switch (packet.type) {
  240. case socket_io_parser_1.PacketType.EVENT:
  241. this.onevent(packet);
  242. break;
  243. case socket_io_parser_1.PacketType.BINARY_EVENT:
  244. this.onevent(packet);
  245. break;
  246. case socket_io_parser_1.PacketType.ACK:
  247. this.onack(packet);
  248. break;
  249. case socket_io_parser_1.PacketType.BINARY_ACK:
  250. this.onack(packet);
  251. break;
  252. case socket_io_parser_1.PacketType.DISCONNECT:
  253. this.ondisconnect();
  254. break;
  255. }
  256. }
  257. /**
  258. * Called upon event packet.
  259. *
  260. * @param {Packet} packet - packet object
  261. * @private
  262. */
  263. onevent(packet) {
  264. const args = packet.data || [];
  265. debug("emitting event %j", args);
  266. if (null != packet.id) {
  267. debug("attaching ack callback to event");
  268. args.push(this.ack(packet.id));
  269. }
  270. if (this._anyListeners && this._anyListeners.length) {
  271. const listeners = this._anyListeners.slice();
  272. for (const listener of listeners) {
  273. listener.apply(this, args);
  274. }
  275. }
  276. this.dispatch(args);
  277. }
  278. /**
  279. * Produces an ack callback to emit with an event.
  280. *
  281. * @param {Number} id - packet id
  282. * @private
  283. */
  284. ack(id) {
  285. const self = this;
  286. let sent = false;
  287. return function () {
  288. // prevent double callbacks
  289. if (sent)
  290. return;
  291. const args = Array.prototype.slice.call(arguments);
  292. debug("sending ack %j", args);
  293. self.packet({
  294. id: id,
  295. type: socket_io_parser_1.PacketType.ACK,
  296. data: args,
  297. });
  298. sent = true;
  299. };
  300. }
  301. /**
  302. * Called upon ack packet.
  303. *
  304. * @private
  305. */
  306. onack(packet) {
  307. const ack = this.acks.get(packet.id);
  308. if ("function" == typeof ack) {
  309. debug("calling ack %s with %j", packet.id, packet.data);
  310. ack.apply(this, packet.data);
  311. this.acks.delete(packet.id);
  312. }
  313. else {
  314. debug("bad ack %s", packet.id);
  315. }
  316. }
  317. /**
  318. * Called upon client disconnect packet.
  319. *
  320. * @private
  321. */
  322. ondisconnect() {
  323. debug("got disconnect packet");
  324. this._onclose("client namespace disconnect");
  325. }
  326. /**
  327. * Handles a client error.
  328. *
  329. * @private
  330. */
  331. _onerror(err) {
  332. if (this.listeners("error").length) {
  333. this.emitReserved("error", err);
  334. }
  335. else {
  336. console.error("Missing error handler on `socket`.");
  337. console.error(err.stack);
  338. }
  339. }
  340. /**
  341. * Called upon closing. Called by `Client`.
  342. *
  343. * @param {String} reason
  344. * @throw {Error} optional error object
  345. *
  346. * @private
  347. */
  348. _onclose(reason) {
  349. if (!this.connected)
  350. return this;
  351. debug("closing socket - reason %s", reason);
  352. this.emitReserved("disconnecting", reason);
  353. this.leaveAll();
  354. this.nsp._remove(this);
  355. this.client._remove(this);
  356. this.connected = false;
  357. this.emitReserved("disconnect", reason);
  358. return;
  359. }
  360. /**
  361. * Produces an `error` packet.
  362. *
  363. * @param {Object} err - error object
  364. *
  365. * @private
  366. */
  367. _error(err) {
  368. this.packet({ type: socket_io_parser_1.PacketType.CONNECT_ERROR, data: err });
  369. }
  370. /**
  371. * Disconnects this client.
  372. *
  373. * @param {Boolean} close - if `true`, closes the underlying connection
  374. * @return {Socket} self
  375. *
  376. * @public
  377. */
  378. disconnect(close = false) {
  379. if (!this.connected)
  380. return this;
  381. if (close) {
  382. this.client._disconnect();
  383. }
  384. else {
  385. this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT });
  386. this._onclose("server namespace disconnect");
  387. }
  388. return this;
  389. }
  390. /**
  391. * Sets the compress flag.
  392. *
  393. * @param {Boolean} compress - if `true`, compresses the sending data
  394. * @return {Socket} self
  395. * @public
  396. */
  397. compress(compress) {
  398. this.flags.compress = compress;
  399. return this;
  400. }
  401. /**
  402. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  403. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  404. * and is in the middle of a request-response cycle).
  405. *
  406. * @return {Socket} self
  407. * @public
  408. */
  409. get volatile() {
  410. this.flags.volatile = true;
  411. return this;
  412. }
  413. /**
  414. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the
  415. * sender.
  416. *
  417. * @return {Socket} self
  418. * @public
  419. */
  420. get broadcast() {
  421. return this.newBroadcastOperator();
  422. }
  423. /**
  424. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  425. *
  426. * @return {Socket} self
  427. * @public
  428. */
  429. get local() {
  430. return this.newBroadcastOperator().local;
  431. }
  432. /**
  433. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  434. * given number of milliseconds have elapsed without an acknowledgement from the client:
  435. *
  436. * ```
  437. * socket.timeout(5000).emit("my-event", (err) => {
  438. * if (err) {
  439. * // the client did not acknowledge the event in the given delay
  440. * }
  441. * });
  442. * ```
  443. *
  444. * @returns self
  445. * @public
  446. */
  447. timeout(timeout) {
  448. this.flags.timeout = timeout;
  449. return this;
  450. }
  451. /**
  452. * Dispatch incoming event to socket listeners.
  453. *
  454. * @param {Array} event - event that will get emitted
  455. * @private
  456. */
  457. dispatch(event) {
  458. debug("dispatching an event %j", event);
  459. this.run(event, (err) => {
  460. process.nextTick(() => {
  461. if (err) {
  462. return this._onerror(err);
  463. }
  464. if (this.connected) {
  465. super.emitUntyped.apply(this, event);
  466. }
  467. else {
  468. debug("ignore packet received after disconnection");
  469. }
  470. });
  471. });
  472. }
  473. /**
  474. * Sets up socket middleware.
  475. *
  476. * @param {Function} fn - middleware function (event, next)
  477. * @return {Socket} self
  478. * @public
  479. */
  480. use(fn) {
  481. this.fns.push(fn);
  482. return this;
  483. }
  484. /**
  485. * Executes the middleware for an incoming event.
  486. *
  487. * @param {Array} event - event that will get emitted
  488. * @param {Function} fn - last fn call in the middleware
  489. * @private
  490. */
  491. run(event, fn) {
  492. const fns = this.fns.slice(0);
  493. if (!fns.length)
  494. return fn(null);
  495. function run(i) {
  496. fns[i](event, function (err) {
  497. // upon error, short-circuit
  498. if (err)
  499. return fn(err);
  500. // if no middleware left, summon callback
  501. if (!fns[i + 1])
  502. return fn(null);
  503. // go on to next
  504. run(i + 1);
  505. });
  506. }
  507. run(0);
  508. }
  509. /**
  510. * Whether the socket is currently disconnected
  511. */
  512. get disconnected() {
  513. return !this.connected;
  514. }
  515. /**
  516. * A reference to the request that originated the underlying Engine.IO Socket.
  517. *
  518. * @public
  519. */
  520. get request() {
  521. return this.client.request;
  522. }
  523. /**
  524. * A reference to the underlying Client transport connection (Engine.IO Socket object).
  525. *
  526. * @public
  527. */
  528. get conn() {
  529. return this.client.conn;
  530. }
  531. /**
  532. * @public
  533. */
  534. get rooms() {
  535. return this.adapter.socketRooms(this.id) || new Set();
  536. }
  537. /**
  538. * Adds a listener that will be fired when any event is received. The event name is passed as the first argument to
  539. * the callback.
  540. *
  541. * @param listener
  542. * @public
  543. */
  544. onAny(listener) {
  545. this._anyListeners = this._anyListeners || [];
  546. this._anyListeners.push(listener);
  547. return this;
  548. }
  549. /**
  550. * Adds a listener that will be fired when any event is received. The event name is passed as the first argument to
  551. * the callback. The listener is added to the beginning of the listeners array.
  552. *
  553. * @param listener
  554. * @public
  555. */
  556. prependAny(listener) {
  557. this._anyListeners = this._anyListeners || [];
  558. this._anyListeners.unshift(listener);
  559. return this;
  560. }
  561. /**
  562. * Removes the listener that will be fired when any event is received.
  563. *
  564. * @param listener
  565. * @public
  566. */
  567. offAny(listener) {
  568. if (!this._anyListeners) {
  569. return this;
  570. }
  571. if (listener) {
  572. const listeners = this._anyListeners;
  573. for (let i = 0; i < listeners.length; i++) {
  574. if (listener === listeners[i]) {
  575. listeners.splice(i, 1);
  576. return this;
  577. }
  578. }
  579. }
  580. else {
  581. this._anyListeners = [];
  582. }
  583. return this;
  584. }
  585. /**
  586. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  587. * e.g. to remove listeners.
  588. *
  589. * @public
  590. */
  591. listenersAny() {
  592. return this._anyListeners || [];
  593. }
  594. /**
  595. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  596. * callback.
  597. *
  598. * @param listener
  599. *
  600. * <pre><code>
  601. *
  602. * socket.onAnyOutgoing((event, ...args) => {
  603. * console.log(event);
  604. * });
  605. *
  606. * </pre></code>
  607. *
  608. * @public
  609. */
  610. onAnyOutgoing(listener) {
  611. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  612. this._anyOutgoingListeners.push(listener);
  613. return this;
  614. }
  615. /**
  616. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  617. * callback. The listener is added to the beginning of the listeners array.
  618. *
  619. * @param listener
  620. *
  621. * <pre><code>
  622. *
  623. * socket.prependAnyOutgoing((event, ...args) => {
  624. * console.log(event);
  625. * });
  626. *
  627. * </pre></code>
  628. *
  629. * @public
  630. */
  631. prependAnyOutgoing(listener) {
  632. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  633. this._anyOutgoingListeners.unshift(listener);
  634. return this;
  635. }
  636. /**
  637. * Removes the listener that will be fired when any event is emitted.
  638. *
  639. * @param listener
  640. *
  641. * <pre><code>
  642. *
  643. * const handler = (event, ...args) => {
  644. * console.log(event);
  645. * }
  646. *
  647. * socket.onAnyOutgoing(handler);
  648. *
  649. * // then later
  650. * socket.offAnyOutgoing(handler);
  651. *
  652. * </pre></code>
  653. *
  654. * @public
  655. */
  656. offAnyOutgoing(listener) {
  657. if (!this._anyOutgoingListeners) {
  658. return this;
  659. }
  660. if (listener) {
  661. const listeners = this._anyOutgoingListeners;
  662. for (let i = 0; i < listeners.length; i++) {
  663. if (listener === listeners[i]) {
  664. listeners.splice(i, 1);
  665. return this;
  666. }
  667. }
  668. }
  669. else {
  670. this._anyOutgoingListeners = [];
  671. }
  672. return this;
  673. }
  674. /**
  675. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  676. * e.g. to remove listeners.
  677. *
  678. * @public
  679. */
  680. listenersAnyOutgoing() {
  681. return this._anyOutgoingListeners || [];
  682. }
  683. /**
  684. * Notify the listeners for each packet sent (emit or broadcast)
  685. *
  686. * @param packet
  687. *
  688. * @private
  689. */
  690. notifyOutgoingListeners(packet) {
  691. if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
  692. const listeners = this._anyOutgoingListeners.slice();
  693. for (const listener of listeners) {
  694. listener.apply(this, packet.data);
  695. }
  696. }
  697. }
  698. newBroadcastOperator() {
  699. const flags = Object.assign({}, this.flags);
  700. this.flags = {};
  701. return new broadcast_operator_1.BroadcastOperator(this.adapter, new Set(), new Set([this.id]), flags);
  702. }
  703. }
  704. exports.Socket = Socket;