polling.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { Transport } from "../transport.js";
  2. import debugModule from "debug"; // debug()
  3. import { yeast } from "../contrib/yeast.js";
  4. import { encodePayload, decodePayload } from "engine.io-parser";
  5. import { createCookieJar, XHR as XMLHttpRequest, } from "./xmlhttprequest.js";
  6. import { Emitter } from "@socket.io/component-emitter";
  7. import { installTimerFunctions, pick } from "../util.js";
  8. import { globalThisShim as globalThis } from "../globalThis.js";
  9. const debug = debugModule("engine.io-client:polling"); // debug()
  10. function empty() { }
  11. const hasXHR2 = (function () {
  12. const xhr = new XMLHttpRequest({
  13. xdomain: false,
  14. });
  15. return null != xhr.responseType;
  16. })();
  17. export class Polling extends Transport {
  18. /**
  19. * XHR Polling constructor.
  20. *
  21. * @param {Object} opts
  22. * @package
  23. */
  24. constructor(opts) {
  25. super(opts);
  26. this.polling = false;
  27. if (typeof location !== "undefined") {
  28. const isSSL = "https:" === location.protocol;
  29. let port = location.port;
  30. // some user agents have empty `location.port`
  31. if (!port) {
  32. port = isSSL ? "443" : "80";
  33. }
  34. this.xd =
  35. (typeof location !== "undefined" &&
  36. opts.hostname !== location.hostname) ||
  37. port !== opts.port;
  38. }
  39. /**
  40. * XHR supports binary
  41. */
  42. const forceBase64 = opts && opts.forceBase64;
  43. this.supportsBinary = hasXHR2 && !forceBase64;
  44. if (this.opts.withCredentials) {
  45. this.cookieJar = createCookieJar();
  46. }
  47. }
  48. get name() {
  49. return "polling";
  50. }
  51. /**
  52. * Opens the socket (triggers polling). We write a PING message to determine
  53. * when the transport is open.
  54. *
  55. * @protected
  56. */
  57. doOpen() {
  58. this.poll();
  59. }
  60. /**
  61. * Pauses polling.
  62. *
  63. * @param {Function} onPause - callback upon buffers are flushed and transport is paused
  64. * @package
  65. */
  66. pause(onPause) {
  67. this.readyState = "pausing";
  68. const pause = () => {
  69. debug("paused");
  70. this.readyState = "paused";
  71. onPause();
  72. };
  73. if (this.polling || !this.writable) {
  74. let total = 0;
  75. if (this.polling) {
  76. debug("we are currently polling - waiting to pause");
  77. total++;
  78. this.once("pollComplete", function () {
  79. debug("pre-pause polling complete");
  80. --total || pause();
  81. });
  82. }
  83. if (!this.writable) {
  84. debug("we are currently writing - waiting to pause");
  85. total++;
  86. this.once("drain", function () {
  87. debug("pre-pause writing complete");
  88. --total || pause();
  89. });
  90. }
  91. }
  92. else {
  93. pause();
  94. }
  95. }
  96. /**
  97. * Starts polling cycle.
  98. *
  99. * @private
  100. */
  101. poll() {
  102. debug("polling");
  103. this.polling = true;
  104. this.doPoll();
  105. this.emitReserved("poll");
  106. }
  107. /**
  108. * Overloads onData to detect payloads.
  109. *
  110. * @protected
  111. */
  112. onData(data) {
  113. debug("polling got data %s", data);
  114. const callback = (packet) => {
  115. // if its the first message we consider the transport open
  116. if ("opening" === this.readyState && packet.type === "open") {
  117. this.onOpen();
  118. }
  119. // if its a close packet, we close the ongoing requests
  120. if ("close" === packet.type) {
  121. this.onClose({ description: "transport closed by the server" });
  122. return false;
  123. }
  124. // otherwise bypass onData and handle the message
  125. this.onPacket(packet);
  126. };
  127. // decode payload
  128. decodePayload(data, this.socket.binaryType).forEach(callback);
  129. // if an event did not trigger closing
  130. if ("closed" !== this.readyState) {
  131. // if we got data we're not polling
  132. this.polling = false;
  133. this.emitReserved("pollComplete");
  134. if ("open" === this.readyState) {
  135. this.poll();
  136. }
  137. else {
  138. debug('ignoring poll - transport state "%s"', this.readyState);
  139. }
  140. }
  141. }
  142. /**
  143. * For polling, send a close packet.
  144. *
  145. * @protected
  146. */
  147. doClose() {
  148. const close = () => {
  149. debug("writing close packet");
  150. this.write([{ type: "close" }]);
  151. };
  152. if ("open" === this.readyState) {
  153. debug("transport open - closing");
  154. close();
  155. }
  156. else {
  157. // in case we're trying to close while
  158. // handshaking is in progress (GH-164)
  159. debug("transport not open - deferring close");
  160. this.once("open", close);
  161. }
  162. }
  163. /**
  164. * Writes a packets payload.
  165. *
  166. * @param {Array} packets - data packets
  167. * @protected
  168. */
  169. write(packets) {
  170. this.writable = false;
  171. encodePayload(packets, (data) => {
  172. this.doWrite(data, () => {
  173. this.writable = true;
  174. this.emitReserved("drain");
  175. });
  176. });
  177. }
  178. /**
  179. * Generates uri for connection.
  180. *
  181. * @private
  182. */
  183. uri() {
  184. const schema = this.opts.secure ? "https" : "http";
  185. const query = this.query || {};
  186. // cache busting is forced
  187. if (false !== this.opts.timestampRequests) {
  188. query[this.opts.timestampParam] = yeast();
  189. }
  190. if (!this.supportsBinary && !query.sid) {
  191. query.b64 = 1;
  192. }
  193. return this.createUri(schema, query);
  194. }
  195. /**
  196. * Creates a request.
  197. *
  198. * @param {String} method
  199. * @private
  200. */
  201. request(opts = {}) {
  202. Object.assign(opts, { xd: this.xd, cookieJar: this.cookieJar }, this.opts);
  203. return new Request(this.uri(), opts);
  204. }
  205. /**
  206. * Sends data.
  207. *
  208. * @param {String} data to send.
  209. * @param {Function} called upon flush.
  210. * @private
  211. */
  212. doWrite(data, fn) {
  213. const req = this.request({
  214. method: "POST",
  215. data: data,
  216. });
  217. req.on("success", fn);
  218. req.on("error", (xhrStatus, context) => {
  219. this.onError("xhr post error", xhrStatus, context);
  220. });
  221. }
  222. /**
  223. * Starts a poll cycle.
  224. *
  225. * @private
  226. */
  227. doPoll() {
  228. debug("xhr poll");
  229. const req = this.request();
  230. req.on("data", this.onData.bind(this));
  231. req.on("error", (xhrStatus, context) => {
  232. this.onError("xhr poll error", xhrStatus, context);
  233. });
  234. this.pollXhr = req;
  235. }
  236. }
  237. export class Request extends Emitter {
  238. /**
  239. * Request constructor
  240. *
  241. * @param {Object} options
  242. * @package
  243. */
  244. constructor(uri, opts) {
  245. super();
  246. installTimerFunctions(this, opts);
  247. this.opts = opts;
  248. this.method = opts.method || "GET";
  249. this.uri = uri;
  250. this.data = undefined !== opts.data ? opts.data : null;
  251. this.create();
  252. }
  253. /**
  254. * Creates the XHR object and sends the request.
  255. *
  256. * @private
  257. */
  258. create() {
  259. var _a;
  260. const opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  261. opts.xdomain = !!this.opts.xd;
  262. const xhr = (this.xhr = new XMLHttpRequest(opts));
  263. try {
  264. debug("xhr open %s: %s", this.method, this.uri);
  265. xhr.open(this.method, this.uri, true);
  266. try {
  267. if (this.opts.extraHeaders) {
  268. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  269. for (let i in this.opts.extraHeaders) {
  270. if (this.opts.extraHeaders.hasOwnProperty(i)) {
  271. xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
  272. }
  273. }
  274. }
  275. }
  276. catch (e) { }
  277. if ("POST" === this.method) {
  278. try {
  279. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  280. }
  281. catch (e) { }
  282. }
  283. try {
  284. xhr.setRequestHeader("Accept", "*/*");
  285. }
  286. catch (e) { }
  287. (_a = this.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
  288. // ie6 check
  289. if ("withCredentials" in xhr) {
  290. xhr.withCredentials = this.opts.withCredentials;
  291. }
  292. if (this.opts.requestTimeout) {
  293. xhr.timeout = this.opts.requestTimeout;
  294. }
  295. xhr.onreadystatechange = () => {
  296. var _a;
  297. if (xhr.readyState === 3) {
  298. (_a = this.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(xhr);
  299. }
  300. if (4 !== xhr.readyState)
  301. return;
  302. if (200 === xhr.status || 1223 === xhr.status) {
  303. this.onLoad();
  304. }
  305. else {
  306. // make sure the `error` event handler that's user-set
  307. // does not throw in the same tick and gets caught here
  308. this.setTimeoutFn(() => {
  309. this.onError(typeof xhr.status === "number" ? xhr.status : 0);
  310. }, 0);
  311. }
  312. };
  313. debug("xhr data %s", this.data);
  314. xhr.send(this.data);
  315. }
  316. catch (e) {
  317. // Need to defer since .create() is called directly from the constructor
  318. // and thus the 'error' event can only be only bound *after* this exception
  319. // occurs. Therefore, also, we cannot throw here at all.
  320. this.setTimeoutFn(() => {
  321. this.onError(e);
  322. }, 0);
  323. return;
  324. }
  325. if (typeof document !== "undefined") {
  326. this.index = Request.requestsCount++;
  327. Request.requests[this.index] = this;
  328. }
  329. }
  330. /**
  331. * Called upon error.
  332. *
  333. * @private
  334. */
  335. onError(err) {
  336. this.emitReserved("error", err, this.xhr);
  337. this.cleanup(true);
  338. }
  339. /**
  340. * Cleans up house.
  341. *
  342. * @private
  343. */
  344. cleanup(fromError) {
  345. if ("undefined" === typeof this.xhr || null === this.xhr) {
  346. return;
  347. }
  348. this.xhr.onreadystatechange = empty;
  349. if (fromError) {
  350. try {
  351. this.xhr.abort();
  352. }
  353. catch (e) { }
  354. }
  355. if (typeof document !== "undefined") {
  356. delete Request.requests[this.index];
  357. }
  358. this.xhr = null;
  359. }
  360. /**
  361. * Called upon load.
  362. *
  363. * @private
  364. */
  365. onLoad() {
  366. const data = this.xhr.responseText;
  367. if (data !== null) {
  368. this.emitReserved("data", data);
  369. this.emitReserved("success");
  370. this.cleanup();
  371. }
  372. }
  373. /**
  374. * Aborts the request.
  375. *
  376. * @package
  377. */
  378. abort() {
  379. this.cleanup();
  380. }
  381. }
  382. Request.requestsCount = 0;
  383. Request.requests = {};
  384. /**
  385. * Aborts pending requests when unloading the window. This is needed to prevent
  386. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  387. * emitted.
  388. */
  389. if (typeof document !== "undefined") {
  390. // @ts-ignore
  391. if (typeof attachEvent === "function") {
  392. // @ts-ignore
  393. attachEvent("onunload", unloadHandler);
  394. }
  395. else if (typeof addEventListener === "function") {
  396. const terminationEvent = "onpagehide" in globalThis ? "pagehide" : "unload";
  397. addEventListener(terminationEvent, unloadHandler, false);
  398. }
  399. }
  400. function unloadHandler() {
  401. for (let i in Request.requests) {
  402. if (Request.requests.hasOwnProperty(i)) {
  403. Request.requests[i].abort();
  404. }
  405. }
  406. }