socket.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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.packet(packet, flags);
  98. return true;
  99. }
  100. /**
  101. * @private
  102. */
  103. registerAckCallback(id, ack) {
  104. const timeout = this.flags.timeout;
  105. if (timeout === undefined) {
  106. this.acks.set(id, ack);
  107. return;
  108. }
  109. const timer = setTimeout(() => {
  110. debug("event with ack id %d has timed out after %d ms", id, timeout);
  111. this.acks.delete(id);
  112. ack.call(this, new Error("operation has timed out"));
  113. }, timeout);
  114. this.acks.set(id, (...args) => {
  115. clearTimeout(timer);
  116. ack.apply(this, [null, ...args]);
  117. });
  118. }
  119. /**
  120. * Targets a room when broadcasting.
  121. *
  122. * @param room
  123. * @return self
  124. * @public
  125. */
  126. to(room) {
  127. return this.newBroadcastOperator().to(room);
  128. }
  129. /**
  130. * Targets a room when broadcasting.
  131. *
  132. * @param room
  133. * @return self
  134. * @public
  135. */
  136. in(room) {
  137. return this.newBroadcastOperator().in(room);
  138. }
  139. /**
  140. * Excludes a room when broadcasting.
  141. *
  142. * @param room
  143. * @return self
  144. * @public
  145. */
  146. except(room) {
  147. return this.newBroadcastOperator().except(room);
  148. }
  149. /**
  150. * Sends a `message` event.
  151. *
  152. * @return self
  153. * @public
  154. */
  155. send(...args) {
  156. this.emit("message", ...args);
  157. return this;
  158. }
  159. /**
  160. * Sends a `message` event.
  161. *
  162. * @return self
  163. * @public
  164. */
  165. write(...args) {
  166. this.emit("message", ...args);
  167. return this;
  168. }
  169. /**
  170. * Writes a packet.
  171. *
  172. * @param {Object} packet - packet object
  173. * @param {Object} opts - options
  174. * @private
  175. */
  176. packet(packet, opts = {}) {
  177. packet.nsp = this.nsp.name;
  178. opts.compress = false !== opts.compress;
  179. this.client._packet(packet, opts);
  180. }
  181. /**
  182. * Joins a room.
  183. *
  184. * @param {String|Array} rooms - room or array of rooms
  185. * @return a Promise or nothing, depending on the adapter
  186. * @public
  187. */
  188. join(rooms) {
  189. debug("join room %s", rooms);
  190. return this.adapter.addAll(this.id, new Set(Array.isArray(rooms) ? rooms : [rooms]));
  191. }
  192. /**
  193. * Leaves a room.
  194. *
  195. * @param {String} room
  196. * @return a Promise or nothing, depending on the adapter
  197. * @public
  198. */
  199. leave(room) {
  200. debug("leave room %s", room);
  201. return this.adapter.del(this.id, room);
  202. }
  203. /**
  204. * Leave all rooms.
  205. *
  206. * @private
  207. */
  208. leaveAll() {
  209. this.adapter.delAll(this.id);
  210. }
  211. /**
  212. * Called by `Namespace` upon successful
  213. * middleware execution (ie: authorization).
  214. * Socket is added to namespace array before
  215. * call to join, so adapters can access it.
  216. *
  217. * @private
  218. */
  219. _onconnect() {
  220. debug("socket connected - writing packet");
  221. this.connected = true;
  222. this.join(this.id);
  223. if (this.conn.protocol === 3) {
  224. this.packet({ type: socket_io_parser_1.PacketType.CONNECT });
  225. }
  226. else {
  227. this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: { sid: this.id } });
  228. }
  229. }
  230. /**
  231. * Called with each packet. Called by `Client`.
  232. *
  233. * @param {Object} packet
  234. * @private
  235. */
  236. _onpacket(packet) {
  237. debug("got packet %j", packet);
  238. switch (packet.type) {
  239. case socket_io_parser_1.PacketType.EVENT:
  240. this.onevent(packet);
  241. break;
  242. case socket_io_parser_1.PacketType.BINARY_EVENT:
  243. this.onevent(packet);
  244. break;
  245. case socket_io_parser_1.PacketType.ACK:
  246. this.onack(packet);
  247. break;
  248. case socket_io_parser_1.PacketType.BINARY_ACK:
  249. this.onack(packet);
  250. break;
  251. case socket_io_parser_1.PacketType.DISCONNECT:
  252. this.ondisconnect();
  253. break;
  254. case socket_io_parser_1.PacketType.CONNECT_ERROR:
  255. this._onerror(new Error(packet.data));
  256. }
  257. }
  258. /**
  259. * Called upon event packet.
  260. *
  261. * @param {Packet} packet - packet object
  262. * @private
  263. */
  264. onevent(packet) {
  265. const args = packet.data || [];
  266. debug("emitting event %j", args);
  267. if (null != packet.id) {
  268. debug("attaching ack callback to event");
  269. args.push(this.ack(packet.id));
  270. }
  271. if (this._anyListeners && this._anyListeners.length) {
  272. const listeners = this._anyListeners.slice();
  273. for (const listener of listeners) {
  274. listener.apply(this, args);
  275. }
  276. }
  277. this.dispatch(args);
  278. }
  279. /**
  280. * Produces an ack callback to emit with an event.
  281. *
  282. * @param {Number} id - packet id
  283. * @private
  284. */
  285. ack(id) {
  286. const self = this;
  287. let sent = false;
  288. return function () {
  289. // prevent double callbacks
  290. if (sent)
  291. return;
  292. const args = Array.prototype.slice.call(arguments);
  293. debug("sending ack %j", args);
  294. self.packet({
  295. id: id,
  296. type: socket_io_parser_1.PacketType.ACK,
  297. data: args,
  298. });
  299. sent = true;
  300. };
  301. }
  302. /**
  303. * Called upon ack packet.
  304. *
  305. * @private
  306. */
  307. onack(packet) {
  308. const ack = this.acks.get(packet.id);
  309. if ("function" == typeof ack) {
  310. debug("calling ack %s with %j", packet.id, packet.data);
  311. ack.apply(this, packet.data);
  312. this.acks.delete(packet.id);
  313. }
  314. else {
  315. debug("bad ack %s", packet.id);
  316. }
  317. }
  318. /**
  319. * Called upon client disconnect packet.
  320. *
  321. * @private
  322. */
  323. ondisconnect() {
  324. debug("got disconnect packet");
  325. this._onclose("client namespace disconnect");
  326. }
  327. /**
  328. * Handles a client error.
  329. *
  330. * @private
  331. */
  332. _onerror(err) {
  333. if (this.listeners("error").length) {
  334. this.emitReserved("error", err);
  335. }
  336. else {
  337. console.error("Missing error handler on `socket`.");
  338. console.error(err.stack);
  339. }
  340. }
  341. /**
  342. * Called upon closing. Called by `Client`.
  343. *
  344. * @param {String} reason
  345. * @throw {Error} optional error object
  346. *
  347. * @private
  348. */
  349. _onclose(reason) {
  350. if (!this.connected)
  351. return this;
  352. debug("closing socket - reason %s", reason);
  353. this.emitReserved("disconnecting", reason);
  354. this.leaveAll();
  355. this.nsp._remove(this);
  356. this.client._remove(this);
  357. this.connected = false;
  358. this.emitReserved("disconnect", reason);
  359. return;
  360. }
  361. /**
  362. * Produces an `error` packet.
  363. *
  364. * @param {Object} err - error object
  365. *
  366. * @private
  367. */
  368. _error(err) {
  369. this.packet({ type: socket_io_parser_1.PacketType.CONNECT_ERROR, data: err });
  370. }
  371. /**
  372. * Disconnects this client.
  373. *
  374. * @param {Boolean} close - if `true`, closes the underlying connection
  375. * @return {Socket} self
  376. *
  377. * @public
  378. */
  379. disconnect(close = false) {
  380. if (!this.connected)
  381. return this;
  382. if (close) {
  383. this.client._disconnect();
  384. }
  385. else {
  386. this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT });
  387. this._onclose("server namespace disconnect");
  388. }
  389. return this;
  390. }
  391. /**
  392. * Sets the compress flag.
  393. *
  394. * @param {Boolean} compress - if `true`, compresses the sending data
  395. * @return {Socket} self
  396. * @public
  397. */
  398. compress(compress) {
  399. this.flags.compress = compress;
  400. return this;
  401. }
  402. /**
  403. * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
  404. * receive messages (because of network slowness or other issues, or because they’re connected through long polling
  405. * and is in the middle of a request-response cycle).
  406. *
  407. * @return {Socket} self
  408. * @public
  409. */
  410. get volatile() {
  411. this.flags.volatile = true;
  412. return this;
  413. }
  414. /**
  415. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the
  416. * sender.
  417. *
  418. * @return {Socket} self
  419. * @public
  420. */
  421. get broadcast() {
  422. return this.newBroadcastOperator();
  423. }
  424. /**
  425. * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
  426. *
  427. * @return {Socket} self
  428. * @public
  429. */
  430. get local() {
  431. return this.newBroadcastOperator().local;
  432. }
  433. /**
  434. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  435. * given number of milliseconds have elapsed without an acknowledgement from the client:
  436. *
  437. * ```
  438. * socket.timeout(5000).emit("my-event", (err) => {
  439. * if (err) {
  440. * // the client did not acknowledge the event in the given delay
  441. * }
  442. * });
  443. * ```
  444. *
  445. * @returns self
  446. * @public
  447. */
  448. timeout(timeout) {
  449. this.flags.timeout = timeout;
  450. return this;
  451. }
  452. /**
  453. * Dispatch incoming event to socket listeners.
  454. *
  455. * @param {Array} event - event that will get emitted
  456. * @private
  457. */
  458. dispatch(event) {
  459. debug("dispatching an event %j", event);
  460. this.run(event, (err) => {
  461. process.nextTick(() => {
  462. if (err) {
  463. return this._onerror(err);
  464. }
  465. if (this.connected) {
  466. super.emitUntyped.apply(this, event);
  467. }
  468. else {
  469. debug("ignore packet received after disconnection");
  470. }
  471. });
  472. });
  473. }
  474. /**
  475. * Sets up socket middleware.
  476. *
  477. * @param {Function} fn - middleware function (event, next)
  478. * @return {Socket} self
  479. * @public
  480. */
  481. use(fn) {
  482. this.fns.push(fn);
  483. return this;
  484. }
  485. /**
  486. * Executes the middleware for an incoming event.
  487. *
  488. * @param {Array} event - event that will get emitted
  489. * @param {Function} fn - last fn call in the middleware
  490. * @private
  491. */
  492. run(event, fn) {
  493. const fns = this.fns.slice(0);
  494. if (!fns.length)
  495. return fn(null);
  496. function run(i) {
  497. fns[i](event, function (err) {
  498. // upon error, short-circuit
  499. if (err)
  500. return fn(err);
  501. // if no middleware left, summon callback
  502. if (!fns[i + 1])
  503. return fn(null);
  504. // go on to next
  505. run(i + 1);
  506. });
  507. }
  508. run(0);
  509. }
  510. /**
  511. * Whether the socket is currently disconnected
  512. */
  513. get disconnected() {
  514. return !this.connected;
  515. }
  516. /**
  517. * A reference to the request that originated the underlying Engine.IO Socket.
  518. *
  519. * @public
  520. */
  521. get request() {
  522. return this.client.request;
  523. }
  524. /**
  525. * A reference to the underlying Client transport connection (Engine.IO Socket object).
  526. *
  527. * @public
  528. */
  529. get conn() {
  530. return this.client.conn;
  531. }
  532. /**
  533. * @public
  534. */
  535. get rooms() {
  536. return this.adapter.socketRooms(this.id) || new Set();
  537. }
  538. /**
  539. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  540. * callback.
  541. *
  542. * @param listener
  543. * @public
  544. */
  545. onAny(listener) {
  546. this._anyListeners = this._anyListeners || [];
  547. this._anyListeners.push(listener);
  548. return this;
  549. }
  550. /**
  551. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  552. * callback. The listener is added to the beginning of the listeners array.
  553. *
  554. * @param listener
  555. * @public
  556. */
  557. prependAny(listener) {
  558. this._anyListeners = this._anyListeners || [];
  559. this._anyListeners.unshift(listener);
  560. return this;
  561. }
  562. /**
  563. * Removes the listener that will be fired when any event is emitted.
  564. *
  565. * @param listener
  566. * @public
  567. */
  568. offAny(listener) {
  569. if (!this._anyListeners) {
  570. return this;
  571. }
  572. if (listener) {
  573. const listeners = this._anyListeners;
  574. for (let i = 0; i < listeners.length; i++) {
  575. if (listener === listeners[i]) {
  576. listeners.splice(i, 1);
  577. return this;
  578. }
  579. }
  580. }
  581. else {
  582. this._anyListeners = [];
  583. }
  584. return this;
  585. }
  586. /**
  587. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  588. * e.g. to remove listeners.
  589. *
  590. * @public
  591. */
  592. listenersAny() {
  593. return this._anyListeners || [];
  594. }
  595. newBroadcastOperator() {
  596. const flags = Object.assign({}, this.flags);
  597. this.flags = {};
  598. return new broadcast_operator_1.BroadcastOperator(this.adapter, new Set(), new Set([this.id]), flags);
  599. }
  600. }
  601. exports.Socket = Socket;