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.

5852 lines
129 KiB

4 years ago
  1. /*!
  2. * Socket.IO v2.3.0
  3. * (c) 2014-2019 Guillermo Rauch
  4. * Released under the MIT License.
  5. */
  6. (function webpackUniversalModuleDefinition(root, factory) {
  7. if(typeof exports === 'object' && typeof module === 'object')
  8. module.exports = factory();
  9. else if(typeof define === 'function' && define.amd)
  10. define([], factory);
  11. else if(typeof exports === 'object')
  12. exports["io"] = factory();
  13. else
  14. root["io"] = factory();
  15. })(this, function() {
  16. return /******/ (function(modules) { // webpackBootstrap
  17. /******/ // The module cache
  18. /******/ var installedModules = {};
  19. /******/
  20. /******/ // The require function
  21. /******/ function __webpack_require__(moduleId) {
  22. /******/
  23. /******/ // Check if module is in cache
  24. /******/ if(installedModules[moduleId])
  25. /******/ return installedModules[moduleId].exports;
  26. /******/
  27. /******/ // Create a new module (and put it into the cache)
  28. /******/ var module = installedModules[moduleId] = {
  29. /******/ exports: {},
  30. /******/ id: moduleId,
  31. /******/ loaded: false
  32. /******/ };
  33. /******/
  34. /******/ // Execute the module function
  35. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  36. /******/
  37. /******/ // Flag the module as loaded
  38. /******/ module.loaded = true;
  39. /******/
  40. /******/ // Return the exports of the module
  41. /******/ return module.exports;
  42. /******/ }
  43. /******/
  44. /******/
  45. /******/ // expose the modules object (__webpack_modules__)
  46. /******/ __webpack_require__.m = modules;
  47. /******/
  48. /******/ // expose the module cache
  49. /******/ __webpack_require__.c = installedModules;
  50. /******/
  51. /******/ // __webpack_public_path__
  52. /******/ __webpack_require__.p = "";
  53. /******/
  54. /******/ // Load entry module and return exports
  55. /******/ return __webpack_require__(0);
  56. /******/ })
  57. /************************************************************************/
  58. /******/ ([
  59. /* 0 */
  60. /***/ (function(module, exports, __webpack_require__) {
  61. 'use strict';
  62. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  63. /**
  64. * Module dependencies.
  65. */
  66. var url = __webpack_require__(1);
  67. var parser = __webpack_require__(4);
  68. var Manager = __webpack_require__(9);
  69. var debug = __webpack_require__(3)('socket.io-client');
  70. /**
  71. * Module exports.
  72. */
  73. module.exports = exports = lookup;
  74. /**
  75. * Managers cache.
  76. */
  77. var cache = exports.managers = {};
  78. /**
  79. * Looks up an existing `Manager` for multiplexing.
  80. * If the user summons:
  81. *
  82. * `io('http://localhost/a');`
  83. * `io('http://localhost/b');`
  84. *
  85. * We reuse the existing instance based on same scheme/port/host,
  86. * and we initialize sockets for each namespace.
  87. *
  88. * @api public
  89. */
  90. function lookup(uri, opts) {
  91. if ((typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) === 'object') {
  92. opts = uri;
  93. uri = undefined;
  94. }
  95. opts = opts || {};
  96. var parsed = url(uri);
  97. var source = parsed.source;
  98. var id = parsed.id;
  99. var path = parsed.path;
  100. var sameNamespace = cache[id] && path in cache[id].nsps;
  101. var newConnection = opts.forceNew || opts['force new connection'] || false === opts.multiplex || sameNamespace;
  102. var io;
  103. if (newConnection) {
  104. io = Manager(source, opts);
  105. } else {
  106. if (!cache[id]) {
  107. cache[id] = Manager(source, opts);
  108. }
  109. io = cache[id];
  110. }
  111. if (parsed.query && !opts.query) {
  112. opts.query = parsed.query;
  113. }
  114. return io.socket(parsed.path, opts);
  115. }
  116. /**
  117. * Protocol version.
  118. *
  119. * @api public
  120. */
  121. exports.protocol = parser.protocol;
  122. /**
  123. * `connect`.
  124. *
  125. * @param {String} uri
  126. * @api public
  127. */
  128. exports.connect = lookup;
  129. /**
  130. * Expose constructors for standalone build.
  131. *
  132. * @api public
  133. */
  134. exports.Manager = __webpack_require__(9);
  135. exports.Socket = __webpack_require__(33);
  136. /***/ }),
  137. /* 1 */
  138. /***/ (function(module, exports, __webpack_require__) {
  139. 'use strict';
  140. /**
  141. * Module dependencies.
  142. */
  143. var parseuri = __webpack_require__(2);
  144. var debug = __webpack_require__(3)('socket.io-client:url');
  145. /**
  146. * Module exports.
  147. */
  148. module.exports = url;
  149. /**
  150. * URL parser.
  151. *
  152. * @param {String} url
  153. * @param {Object} An object meant to mimic window.location.
  154. * Defaults to window.location.
  155. * @api public
  156. */
  157. function url(uri, loc) {
  158. var obj = uri;
  159. // default to window.location
  160. loc = loc || typeof location !== 'undefined' && location;
  161. if (null == uri) uri = loc.protocol + '//' + loc.host;
  162. // relative path support
  163. if ('string' === typeof uri) {
  164. if ('/' === uri.charAt(0)) {
  165. if ('/' === uri.charAt(1)) {
  166. uri = loc.protocol + uri;
  167. } else {
  168. uri = loc.host + uri;
  169. }
  170. }
  171. if (!/^(https?|wss?):\/\//.test(uri)) {
  172. if ('undefined' !== typeof loc) {
  173. uri = loc.protocol + '//' + uri;
  174. } else {
  175. uri = 'https://' + uri;
  176. }
  177. }
  178. // parse
  179. obj = parseuri(uri);
  180. }
  181. // make sure we treat `localhost:80` and `localhost` equally
  182. if (!obj.port) {
  183. if (/^(http|ws)$/.test(obj.protocol)) {
  184. obj.port = '80';
  185. } else if (/^(http|ws)s$/.test(obj.protocol)) {
  186. obj.port = '443';
  187. }
  188. }
  189. obj.path = obj.path || '/';
  190. var ipv6 = obj.host.indexOf(':') !== -1;
  191. var host = ipv6 ? '[' + obj.host + ']' : obj.host;
  192. // define unique id
  193. obj.id = obj.protocol + '://' + host + ':' + obj.port;
  194. // define href
  195. obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : ':' + obj.port);
  196. return obj;
  197. }
  198. /***/ }),
  199. /* 2 */
  200. /***/ (function(module, exports) {
  201. /**
  202. * Parses an URI
  203. *
  204. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  205. * @api private
  206. */
  207. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  208. var parts = [
  209. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  210. ];
  211. module.exports = function parseuri(str) {
  212. var src = str,
  213. b = str.indexOf('['),
  214. e = str.indexOf(']');
  215. if (b != -1 && e != -1) {
  216. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  217. }
  218. var m = re.exec(str || ''),
  219. uri = {},
  220. i = 14;
  221. while (i--) {
  222. uri[parts[i]] = m[i] || '';
  223. }
  224. if (b != -1 && e != -1) {
  225. uri.source = src;
  226. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  227. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  228. uri.ipv6uri = true;
  229. }
  230. return uri;
  231. };
  232. /***/ }),
  233. /* 3 */
  234. /***/ (function(module, exports) {
  235. "use strict";
  236. module.exports = function () {
  237. return function () {};
  238. };
  239. /***/ }),
  240. /* 4 */
  241. /***/ (function(module, exports, __webpack_require__) {
  242. /**
  243. * Module dependencies.
  244. */
  245. var debug = __webpack_require__(3)('socket.io-parser');
  246. var Emitter = __webpack_require__(5);
  247. var binary = __webpack_require__(6);
  248. var isArray = __webpack_require__(7);
  249. var isBuf = __webpack_require__(8);
  250. /**
  251. * Protocol version.
  252. *
  253. * @api public
  254. */
  255. exports.protocol = 4;
  256. /**
  257. * Packet types.
  258. *
  259. * @api public
  260. */
  261. exports.types = [
  262. 'CONNECT',
  263. 'DISCONNECT',
  264. 'EVENT',
  265. 'ACK',
  266. 'ERROR',
  267. 'BINARY_EVENT',
  268. 'BINARY_ACK'
  269. ];
  270. /**
  271. * Packet type `connect`.
  272. *
  273. * @api public
  274. */
  275. exports.CONNECT = 0;
  276. /**
  277. * Packet type `disconnect`.
  278. *
  279. * @api public
  280. */
  281. exports.DISCONNECT = 1;
  282. /**
  283. * Packet type `event`.
  284. *
  285. * @api public
  286. */
  287. exports.EVENT = 2;
  288. /**
  289. * Packet type `ack`.
  290. *
  291. * @api public
  292. */
  293. exports.ACK = 3;
  294. /**
  295. * Packet type `error`.
  296. *
  297. * @api public
  298. */
  299. exports.ERROR = 4;
  300. /**
  301. * Packet type 'binary event'
  302. *
  303. * @api public
  304. */
  305. exports.BINARY_EVENT = 5;
  306. /**
  307. * Packet type `binary ack`. For acks with binary arguments.
  308. *
  309. * @api public
  310. */
  311. exports.BINARY_ACK = 6;
  312. /**
  313. * Encoder constructor.
  314. *
  315. * @api public
  316. */
  317. exports.Encoder = Encoder;
  318. /**
  319. * Decoder constructor.
  320. *
  321. * @api public
  322. */
  323. exports.Decoder = Decoder;
  324. /**
  325. * A socket.io Encoder instance
  326. *
  327. * @api public
  328. */
  329. function Encoder() {}
  330. var ERROR_PACKET = exports.ERROR + '"encode error"';
  331. /**
  332. * Encode a packet as a single string if non-binary, or as a
  333. * buffer sequence, depending on packet type.
  334. *
  335. * @param {Object} obj - packet object
  336. * @param {Function} callback - function to handle encodings (likely engine.write)
  337. * @return Calls callback with Array of encodings
  338. * @api public
  339. */
  340. Encoder.prototype.encode = function(obj, callback){
  341. if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
  342. encodeAsBinary(obj, callback);
  343. } else {
  344. var encoding = encodeAsString(obj);
  345. callback([encoding]);
  346. }
  347. };
  348. /**
  349. * Encode packet as string.
  350. *
  351. * @param {Object} packet
  352. * @return {String} encoded
  353. * @api private
  354. */
  355. function encodeAsString(obj) {
  356. // first is type
  357. var str = '' + obj.type;
  358. // attachments if we have them
  359. if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
  360. str += obj.attachments + '-';
  361. }
  362. // if we have a namespace other than `/`
  363. // we append it followed by a comma `,`
  364. if (obj.nsp && '/' !== obj.nsp) {
  365. str += obj.nsp + ',';
  366. }
  367. // immediately followed by the id
  368. if (null != obj.id) {
  369. str += obj.id;
  370. }
  371. // json data
  372. if (null != obj.data) {
  373. var payload = tryStringify(obj.data);
  374. if (payload !== false) {
  375. str += payload;
  376. } else {
  377. return ERROR_PACKET;
  378. }
  379. }
  380. return str;
  381. }
  382. function tryStringify(str) {
  383. try {
  384. return JSON.stringify(str);
  385. } catch(e){
  386. return false;
  387. }
  388. }
  389. /**
  390. * Encode packet as 'buffer sequence' by removing blobs, and
  391. * deconstructing packet into object with placeholders and
  392. * a list of buffers.
  393. *
  394. * @param {Object} packet
  395. * @return {Buffer} encoded
  396. * @api private
  397. */
  398. function encodeAsBinary(obj, callback) {
  399. function writeEncoding(bloblessData) {
  400. var deconstruction = binary.deconstructPacket(bloblessData);
  401. var pack = encodeAsString(deconstruction.packet);
  402. var buffers = deconstruction.buffers;
  403. buffers.unshift(pack); // add packet info to beginning of data list
  404. callback(buffers); // write all the buffers
  405. }
  406. binary.removeBlobs(obj, writeEncoding);
  407. }
  408. /**
  409. * A socket.io Decoder instance
  410. *
  411. * @return {Object} decoder
  412. * @api public
  413. */
  414. function Decoder() {
  415. this.reconstructor = null;
  416. }
  417. /**
  418. * Mix in `Emitter` with Decoder.
  419. */
  420. Emitter(Decoder.prototype);
  421. /**
  422. * Decodes an encoded packet string into packet JSON.
  423. *
  424. * @param {String} obj - encoded packet
  425. * @return {Object} packet
  426. * @api public
  427. */
  428. Decoder.prototype.add = function(obj) {
  429. var packet;
  430. if (typeof obj === 'string') {
  431. packet = decodeString(obj);
  432. if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json
  433. this.reconstructor = new BinaryReconstructor(packet);
  434. // no attachments, labeled binary but no binary data to follow
  435. if (this.reconstructor.reconPack.attachments === 0) {
  436. this.emit('decoded', packet);
  437. }
  438. } else { // non-binary full packet
  439. this.emit('decoded', packet);
  440. }
  441. } else if (isBuf(obj) || obj.base64) { // raw binary data
  442. if (!this.reconstructor) {
  443. throw new Error('got binary data when not reconstructing a packet');
  444. } else {
  445. packet = this.reconstructor.takeBinaryData(obj);
  446. if (packet) { // received final buffer
  447. this.reconstructor = null;
  448. this.emit('decoded', packet);
  449. }
  450. }
  451. } else {
  452. throw new Error('Unknown type: ' + obj);
  453. }
  454. };
  455. /**
  456. * Decode a packet String (JSON data)
  457. *
  458. * @param {String} str
  459. * @return {Object} packet
  460. * @api private
  461. */
  462. function decodeString(str) {
  463. var i = 0;
  464. // look up type
  465. var p = {
  466. type: Number(str.charAt(0))
  467. };
  468. if (null == exports.types[p.type]) {
  469. return error('unknown packet type ' + p.type);
  470. }
  471. // look up attachments if type binary
  472. if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) {
  473. var buf = '';
  474. while (str.charAt(++i) !== '-') {
  475. buf += str.charAt(i);
  476. if (i == str.length) break;
  477. }
  478. if (buf != Number(buf) || str.charAt(i) !== '-') {
  479. throw new Error('Illegal attachments');
  480. }
  481. p.attachments = Number(buf);
  482. }
  483. // look up namespace (if any)
  484. if ('/' === str.charAt(i + 1)) {
  485. p.nsp = '';
  486. while (++i) {
  487. var c = str.charAt(i);
  488. if (',' === c) break;
  489. p.nsp += c;
  490. if (i === str.length) break;
  491. }
  492. } else {
  493. p.nsp = '/';
  494. }
  495. // look up id
  496. var next = str.charAt(i + 1);
  497. if ('' !== next && Number(next) == next) {
  498. p.id = '';
  499. while (++i) {
  500. var c = str.charAt(i);
  501. if (null == c || Number(c) != c) {
  502. --i;
  503. break;
  504. }
  505. p.id += str.charAt(i);
  506. if (i === str.length) break;
  507. }
  508. p.id = Number(p.id);
  509. }
  510. // look up json data
  511. if (str.charAt(++i)) {
  512. var payload = tryParse(str.substr(i));
  513. var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload));
  514. if (isPayloadValid) {
  515. p.data = payload;
  516. } else {
  517. return error('invalid payload');
  518. }
  519. }
  520. return p;
  521. }
  522. function tryParse(str) {
  523. try {
  524. return JSON.parse(str);
  525. } catch(e){
  526. return false;
  527. }
  528. }
  529. /**
  530. * Deallocates a parser's resources
  531. *
  532. * @api public
  533. */
  534. Decoder.prototype.destroy = function() {
  535. if (this.reconstructor) {
  536. this.reconstructor.finishedReconstruction();
  537. }
  538. };
  539. /**
  540. * A manager of a binary event's 'buffer sequence'. Should
  541. * be constructed whenever a packet of type BINARY_EVENT is
  542. * decoded.
  543. *
  544. * @param {Object} packet
  545. * @return {BinaryReconstructor} initialized reconstructor
  546. * @api private
  547. */
  548. function BinaryReconstructor(packet) {
  549. this.reconPack = packet;
  550. this.buffers = [];
  551. }
  552. /**
  553. * Method to be called when binary data received from connection
  554. * after a BINARY_EVENT packet.
  555. *
  556. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  557. * @return {null | Object} returns null if more binary data is expected or
  558. * a reconstructed packet object if all buffers have been received.
  559. * @api private
  560. */
  561. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  562. this.buffers.push(binData);
  563. if (this.buffers.length === this.reconPack.attachments) { // done with buffer list
  564. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  565. this.finishedReconstruction();
  566. return packet;
  567. }
  568. return null;
  569. };
  570. /**
  571. * Cleans up binary packet reconstruction variables.
  572. *
  573. * @api private
  574. */
  575. BinaryReconstructor.prototype.finishedReconstruction = function() {
  576. this.reconPack = null;
  577. this.buffers = [];
  578. };
  579. function error(msg) {
  580. return {
  581. type: exports.ERROR,
  582. data: 'parser error: ' + msg
  583. };
  584. }
  585. /***/ }),
  586. /* 5 */
  587. /***/ (function(module, exports, __webpack_require__) {
  588. /**
  589. * Expose `Emitter`.
  590. */
  591. if (true) {
  592. module.exports = Emitter;
  593. }
  594. /**
  595. * Initialize a new `Emitter`.
  596. *
  597. * @api public
  598. */
  599. function Emitter(obj) {
  600. if (obj) return mixin(obj);
  601. };
  602. /**
  603. * Mixin the emitter properties.
  604. *
  605. * @param {Object} obj
  606. * @return {Object}
  607. * @api private
  608. */
  609. function mixin(obj) {
  610. for (var key in Emitter.prototype) {
  611. obj[key] = Emitter.prototype[key];
  612. }
  613. return obj;
  614. }
  615. /**
  616. * Listen on the given `event` with `fn`.
  617. *
  618. * @param {String} event
  619. * @param {Function} fn
  620. * @return {Emitter}
  621. * @api public
  622. */
  623. Emitter.prototype.on =
  624. Emitter.prototype.addEventListener = function(event, fn){
  625. this._callbacks = this._callbacks || {};
  626. (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
  627. .push(fn);
  628. return this;
  629. };
  630. /**
  631. * Adds an `event` listener that will be invoked a single
  632. * time then automatically removed.
  633. *
  634. * @param {String} event
  635. * @param {Function} fn
  636. * @return {Emitter}
  637. * @api public
  638. */
  639. Emitter.prototype.once = function(event, fn){
  640. function on() {
  641. this.off(event, on);
  642. fn.apply(this, arguments);
  643. }
  644. on.fn = fn;
  645. this.on(event, on);
  646. return this;
  647. };
  648. /**
  649. * Remove the given callback for `event` or all
  650. * registered callbacks.
  651. *
  652. * @param {String} event
  653. * @param {Function} fn
  654. * @return {Emitter}
  655. * @api public
  656. */
  657. Emitter.prototype.off =
  658. Emitter.prototype.removeListener =
  659. Emitter.prototype.removeAllListeners =
  660. Emitter.prototype.removeEventListener = function(event, fn){
  661. this._callbacks = this._callbacks || {};
  662. // all
  663. if (0 == arguments.length) {
  664. this._callbacks = {};
  665. return this;
  666. }
  667. // specific event
  668. var callbacks = this._callbacks['$' + event];
  669. if (!callbacks) return this;
  670. // remove all handlers
  671. if (1 == arguments.length) {
  672. delete this._callbacks['$' + event];
  673. return this;
  674. }
  675. // remove specific handler
  676. var cb;
  677. for (var i = 0; i < callbacks.length; i++) {
  678. cb = callbacks[i];
  679. if (cb === fn || cb.fn === fn) {
  680. callbacks.splice(i, 1);
  681. break;
  682. }
  683. }
  684. return this;
  685. };
  686. /**
  687. * Emit `event` with the given args.
  688. *
  689. * @param {String} event
  690. * @param {Mixed} ...
  691. * @return {Emitter}
  692. */
  693. Emitter.prototype.emit = function(event){
  694. this._callbacks = this._callbacks || {};
  695. var args = [].slice.call(arguments, 1)
  696. , callbacks = this._callbacks['$' + event];
  697. if (callbacks) {
  698. callbacks = callbacks.slice(0);
  699. for (var i = 0, len = callbacks.length; i < len; ++i) {
  700. callbacks[i].apply(this, args);
  701. }
  702. }
  703. return this;
  704. };
  705. /**
  706. * Return array of callbacks for `event`.
  707. *
  708. * @param {String} event
  709. * @return {Array}
  710. * @api public
  711. */
  712. Emitter.prototype.listeners = function(event){
  713. this._callbacks = this._callbacks || {};
  714. return this._callbacks['$' + event] || [];
  715. };
  716. /**
  717. * Check if this emitter has `event` handlers.
  718. *
  719. * @param {String} event
  720. * @return {Boolean}
  721. * @api public
  722. */
  723. Emitter.prototype.hasListeners = function(event){
  724. return !! this.listeners(event).length;
  725. };
  726. /***/ }),
  727. /* 6 */
  728. /***/ (function(module, exports, __webpack_require__) {
  729. /*global Blob,File*/
  730. /**
  731. * Module requirements
  732. */
  733. var isArray = __webpack_require__(7);
  734. var isBuf = __webpack_require__(8);
  735. var toString = Object.prototype.toString;
  736. var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]');
  737. var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]');
  738. /**
  739. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  740. * Anything with blobs or files should be fed through removeBlobs before coming
  741. * here.
  742. *
  743. * @param {Object} packet - socket.io event packet
  744. * @return {Object} with deconstructed packet and list of buffers
  745. * @api public
  746. */
  747. exports.deconstructPacket = function(packet) {
  748. var buffers = [];
  749. var packetData = packet.data;
  750. var pack = packet;
  751. pack.data = _deconstructPacket(packetData, buffers);
  752. pack.attachments = buffers.length; // number of binary 'attachments'
  753. return {packet: pack, buffers: buffers};
  754. };
  755. function _deconstructPacket(data, buffers) {
  756. if (!data) return data;
  757. if (isBuf(data)) {
  758. var placeholder = { _placeholder: true, num: buffers.length };
  759. buffers.push(data);
  760. return placeholder;
  761. } else if (isArray(data)) {
  762. var newData = new Array(data.length);
  763. for (var i = 0; i < data.length; i++) {
  764. newData[i] = _deconstructPacket(data[i], buffers);
  765. }
  766. return newData;
  767. } else if (typeof data === 'object' && !(data instanceof Date)) {
  768. var newData = {};
  769. for (var key in data) {
  770. newData[key] = _deconstructPacket(data[key], buffers);
  771. }
  772. return newData;
  773. }
  774. return data;
  775. }
  776. /**
  777. * Reconstructs a binary packet from its placeholder packet and buffers
  778. *
  779. * @param {Object} packet - event packet with placeholders
  780. * @param {Array} buffers - binary buffers to put in placeholder positions
  781. * @return {Object} reconstructed packet
  782. * @api public
  783. */
  784. exports.reconstructPacket = function(packet, buffers) {
  785. packet.data = _reconstructPacket(packet.data, buffers);
  786. packet.attachments = undefined; // no longer useful
  787. return packet;
  788. };
  789. function _reconstructPacket(data, buffers) {
  790. if (!data) return data;
  791. if (data && data._placeholder) {
  792. return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  793. } else if (isArray(data)) {
  794. for (var i = 0; i < data.length; i++) {
  795. data[i] = _reconstructPacket(data[i], buffers);
  796. }
  797. } else if (typeof data === 'object') {
  798. for (var key in data) {
  799. data[key] = _reconstructPacket(data[key], buffers);
  800. }
  801. }
  802. return data;
  803. }
  804. /**
  805. * Asynchronously removes Blobs or Files from data via
  806. * FileReader's readAsArrayBuffer method. Used before encoding
  807. * data as msgpack. Calls callback with the blobless data.
  808. *
  809. * @param {Object} data
  810. * @param {Function} callback
  811. * @api private
  812. */
  813. exports.removeBlobs = function(data, callback) {
  814. function _removeBlobs(obj, curKey, containingObject) {
  815. if (!obj) return obj;
  816. // convert any blob
  817. if ((withNativeBlob && obj instanceof Blob) ||
  818. (withNativeFile && obj instanceof File)) {
  819. pendingBlobs++;
  820. // async filereader
  821. var fileReader = new FileReader();
  822. fileReader.onload = function() { // this.result == arraybuffer
  823. if (containingObject) {
  824. containingObject[curKey] = this.result;
  825. }
  826. else {
  827. bloblessData = this.result;
  828. }
  829. // if nothing pending its callback time
  830. if(! --pendingBlobs) {
  831. callback(bloblessData);
  832. }
  833. };
  834. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  835. } else if (isArray(obj)) { // handle array
  836. for (var i = 0; i < obj.length; i++) {
  837. _removeBlobs(obj[i], i, obj);
  838. }
  839. } else if (typeof obj === 'object' && !isBuf(obj)) { // and object
  840. for (var key in obj) {
  841. _removeBlobs(obj[key], key, obj);
  842. }
  843. }
  844. }
  845. var pendingBlobs = 0;
  846. var bloblessData = data;
  847. _removeBlobs(bloblessData);
  848. if (!pendingBlobs) {
  849. callback(bloblessData);
  850. }
  851. };
  852. /***/ }),
  853. /* 7 */
  854. /***/ (function(module, exports) {
  855. var toString = {}.toString;
  856. module.exports = Array.isArray || function (arr) {
  857. return toString.call(arr) == '[object Array]';
  858. };
  859. /***/ }),
  860. /* 8 */
  861. /***/ (function(module, exports) {
  862. module.exports = isBuf;
  863. var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function';
  864. var withNativeArrayBuffer = typeof ArrayBuffer === 'function';
  865. var isView = function (obj) {
  866. return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer);
  867. };
  868. /**
  869. * Returns true if obj is a buffer or an arraybuffer.
  870. *
  871. * @api private
  872. */
  873. function isBuf(obj) {
  874. return (withNativeBuffer && Buffer.isBuffer(obj)) ||
  875. (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)));
  876. }
  877. /***/ }),
  878. /* 9 */
  879. /***/ (function(module, exports, __webpack_require__) {
  880. 'use strict';
  881. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  882. /**
  883. * Module dependencies.
  884. */
  885. var eio = __webpack_require__(10);
  886. var Socket = __webpack_require__(33);
  887. var Emitter = __webpack_require__(5);
  888. var parser = __webpack_require__(4);
  889. var on = __webpack_require__(35);
  890. var bind = __webpack_require__(36);
  891. var debug = __webpack_require__(3)('socket.io-client:manager');
  892. var indexOf = __webpack_require__(32);
  893. var Backoff = __webpack_require__(37);
  894. /**
  895. * IE6+ hasOwnProperty
  896. */
  897. var has = Object.prototype.hasOwnProperty;
  898. /**
  899. * Module exports
  900. */
  901. module.exports = Manager;
  902. /**
  903. * `Manager` constructor.
  904. *
  905. * @param {String} engine instance or engine uri/opts
  906. * @param {Object} options
  907. * @api public
  908. */
  909. function Manager(uri, opts) {
  910. if (!(this instanceof Manager)) return new Manager(uri, opts);
  911. if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) {
  912. opts = uri;
  913. uri = undefined;
  914. }
  915. opts = opts || {};
  916. opts.path = opts.path || '/socket.io';
  917. this.nsps = {};
  918. this.subs = [];
  919. this.opts = opts;
  920. this.reconnection(opts.reconnection !== false);
  921. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  922. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  923. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  924. this.randomizationFactor(opts.randomizationFactor || 0.5);
  925. this.backoff = new Backoff({
  926. min: this.reconnectionDelay(),
  927. max: this.reconnectionDelayMax(),
  928. jitter: this.randomizationFactor()
  929. });
  930. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  931. this.readyState = 'closed';
  932. this.uri = uri;
  933. this.connecting = [];
  934. this.lastPing = null;
  935. this.encoding = false;
  936. this.packetBuffer = [];
  937. var _parser = opts.parser || parser;
  938. this.encoder = new _parser.Encoder();
  939. this.decoder = new _parser.Decoder();
  940. this.autoConnect = opts.autoConnect !== false;
  941. if (this.autoConnect) this.open();
  942. }
  943. /**
  944. * Propagate given event to sockets and emit on `this`
  945. *
  946. * @api private
  947. */
  948. Manager.prototype.emitAll = function () {
  949. this.emit.apply(this, arguments);
  950. for (var nsp in this.nsps) {
  951. if (has.call(this.nsps, nsp)) {
  952. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  953. }
  954. }
  955. };
  956. /**
  957. * Update `socket.id` of all sockets
  958. *
  959. * @api private
  960. */
  961. Manager.prototype.updateSocketIds = function () {
  962. for (var nsp in this.nsps) {
  963. if (has.call(this.nsps, nsp)) {
  964. this.nsps[nsp].id = this.generateId(nsp);
  965. }
  966. }
  967. };
  968. /**
  969. * generate `socket.id` for the given `nsp`
  970. *
  971. * @param {String} nsp
  972. * @return {String}
  973. * @api private
  974. */
  975. Manager.prototype.generateId = function (nsp) {
  976. return (nsp === '/' ? '' : nsp + '#') + this.engine.id;
  977. };
  978. /**
  979. * Mix in `Emitter`.
  980. */
  981. Emitter(Manager.prototype);
  982. /**
  983. * Sets the `reconnection` config.
  984. *
  985. * @param {Boolean} true/false if it should automatically reconnect
  986. * @return {Manager} self or value
  987. * @api public
  988. */
  989. Manager.prototype.reconnection = function (v) {
  990. if (!arguments.length) return this._reconnection;
  991. this._reconnection = !!v;
  992. return this;
  993. };
  994. /**
  995. * Sets the reconnection attempts config.
  996. *
  997. * @param {Number} max reconnection attempts before giving up
  998. * @return {Manager} self or value
  999. * @api public
  1000. */
  1001. Manager.prototype.reconnectionAttempts = function (v) {
  1002. if (!arguments.length) return this._reconnectionAttempts;
  1003. this._reconnectionAttempts = v;
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets the delay between reconnections.
  1008. *
  1009. * @param {Number} delay
  1010. * @return {Manager} self or value
  1011. * @api public
  1012. */
  1013. Manager.prototype.reconnectionDelay = function (v) {
  1014. if (!arguments.length) return this._reconnectionDelay;
  1015. this._reconnectionDelay = v;
  1016. this.backoff && this.backoff.setMin(v);
  1017. return this;
  1018. };
  1019. Manager.prototype.randomizationFactor = function (v) {
  1020. if (!arguments.length) return this._randomizationFactor;
  1021. this._randomizationFactor = v;
  1022. this.backoff && this.backoff.setJitter(v);
  1023. return this;
  1024. };
  1025. /**
  1026. * Sets the maximum delay between reconnections.
  1027. *
  1028. * @param {Number} delay
  1029. * @return {Manager} self or value
  1030. * @api public
  1031. */
  1032. Manager.prototype.reconnectionDelayMax = function (v) {
  1033. if (!arguments.length) return this._reconnectionDelayMax;
  1034. this._reconnectionDelayMax = v;
  1035. this.backoff && this.backoff.setMax(v);
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets the connection timeout. `false` to disable
  1040. *
  1041. * @return {Manager} self or value
  1042. * @api public
  1043. */
  1044. Manager.prototype.timeout = function (v) {
  1045. if (!arguments.length) return this._timeout;
  1046. this._timeout = v;
  1047. return this;
  1048. };
  1049. /**
  1050. * Starts trying to reconnect if reconnection is enabled and we have not
  1051. * started reconnecting yet
  1052. *
  1053. * @api private
  1054. */
  1055. Manager.prototype.maybeReconnectOnOpen = function () {
  1056. // Only try to reconnect if it's the first time we're connecting
  1057. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  1058. // keeps reconnection from firing twice for the same reconnection loop
  1059. this.reconnect();
  1060. }
  1061. };
  1062. /**
  1063. * Sets the current transport `socket`.
  1064. *
  1065. * @param {Function} optional, callback
  1066. * @return {Manager} self
  1067. * @api public
  1068. */
  1069. Manager.prototype.open = Manager.prototype.connect = function (fn, opts) {
  1070. if (~this.readyState.indexOf('open')) return this;
  1071. this.engine = eio(this.uri, this.opts);
  1072. var socket = this.engine;
  1073. var self = this;
  1074. this.readyState = 'opening';
  1075. this.skipReconnect = false;
  1076. // emit `open`
  1077. var openSub = on(socket, 'open', function () {
  1078. self.onopen();
  1079. fn && fn();
  1080. });
  1081. // emit `connect_error`
  1082. var errorSub = on(socket, 'error', function (data) {
  1083. self.cleanup();
  1084. self.readyState = 'closed';
  1085. self.emitAll('connect_error', data);
  1086. if (fn) {
  1087. var err = new Error('Connection error');
  1088. err.data = data;
  1089. fn(err);
  1090. } else {
  1091. // Only do this if there is no fn to handle the error
  1092. self.maybeReconnectOnOpen();
  1093. }
  1094. });
  1095. // emit `connect_timeout`
  1096. if (false !== this._timeout) {
  1097. var timeout = this._timeout;
  1098. // set timer
  1099. var timer = setTimeout(function () {
  1100. openSub.destroy();
  1101. socket.close();
  1102. socket.emit('error', 'timeout');
  1103. self.emitAll('connect_timeout', timeout);
  1104. }, timeout);
  1105. this.subs.push({
  1106. destroy: function destroy() {
  1107. clearTimeout(timer);
  1108. }
  1109. });
  1110. }
  1111. this.subs.push(openSub);
  1112. this.subs.push(errorSub);
  1113. return this;
  1114. };
  1115. /**
  1116. * Called upon transport open.
  1117. *
  1118. * @api private
  1119. */
  1120. Manager.prototype.onopen = function () {
  1121. // clear old subs
  1122. this.cleanup();
  1123. // mark as open
  1124. this.readyState = 'open';
  1125. this.emit('open');
  1126. // add new subs
  1127. var socket = this.engine;
  1128. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  1129. this.subs.push(on(socket, 'ping', bind(this, 'onping')));
  1130. this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
  1131. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  1132. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  1133. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  1134. };
  1135. /**
  1136. * Called upon a ping.
  1137. *
  1138. * @api private
  1139. */
  1140. Manager.prototype.onping = function () {
  1141. this.lastPing = new Date();
  1142. this.emitAll('ping');
  1143. };
  1144. /**
  1145. * Called upon a packet.
  1146. *
  1147. * @api private
  1148. */
  1149. Manager.prototype.onpong = function () {
  1150. this.emitAll('pong', new Date() - this.lastPing);
  1151. };
  1152. /**
  1153. * Called with data.
  1154. *
  1155. * @api private
  1156. */
  1157. Manager.prototype.ondata = function (data) {
  1158. this.decoder.add(data);
  1159. };
  1160. /**
  1161. * Called when parser fully decodes a packet.
  1162. *
  1163. * @api private
  1164. */
  1165. Manager.prototype.ondecoded = function (packet) {
  1166. this.emit('packet', packet);
  1167. };
  1168. /**
  1169. * Called upon socket error.
  1170. *
  1171. * @api private
  1172. */
  1173. Manager.prototype.onerror = function (err) {
  1174. this.emitAll('error', err);
  1175. };
  1176. /**
  1177. * Creates a new socket for the given `nsp`.
  1178. *
  1179. * @return {Socket}
  1180. * @api public
  1181. */
  1182. Manager.prototype.socket = function (nsp, opts) {
  1183. var socket = this.nsps[nsp];
  1184. if (!socket) {
  1185. socket = new Socket(this, nsp, opts);
  1186. this.nsps[nsp] = socket;
  1187. var self = this;
  1188. socket.on('connecting', onConnecting);
  1189. socket.on('connect', function () {
  1190. socket.id = self.generateId(nsp);
  1191. });
  1192. if (this.autoConnect) {
  1193. // manually call here since connecting event is fired before listening
  1194. onConnecting();
  1195. }
  1196. }
  1197. function onConnecting() {
  1198. if (!~indexOf(self.connecting, socket)) {
  1199. self.connecting.push(socket);
  1200. }
  1201. }
  1202. return socket;
  1203. };
  1204. /**
  1205. * Called upon a socket close.
  1206. *
  1207. * @param {Socket} socket
  1208. */
  1209. Manager.prototype.destroy = function (socket) {
  1210. var index = indexOf(this.connecting, socket);
  1211. if (~index) this.connecting.splice(index, 1);
  1212. if (this.connecting.length) return;
  1213. this.close();
  1214. };
  1215. /**
  1216. * Writes a packet.
  1217. *
  1218. * @param {Object} packet
  1219. * @api private
  1220. */
  1221. Manager.prototype.packet = function (packet) {
  1222. var self = this;
  1223. if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
  1224. if (!self.encoding) {
  1225. // encode, then write to engine with result
  1226. self.encoding = true;
  1227. this.encoder.encode(packet, function (encodedPackets) {
  1228. for (var i = 0; i < encodedPackets.length; i++) {
  1229. self.engine.write(encodedPackets[i], packet.options);
  1230. }
  1231. self.encoding = false;
  1232. self.processPacketQueue();
  1233. });
  1234. } else {
  1235. // add packet to the queue
  1236. self.packetBuffer.push(packet);
  1237. }
  1238. };
  1239. /**
  1240. * If packet buffer is non-empty, begins encoding the
  1241. * next packet in line.
  1242. *
  1243. * @api private
  1244. */
  1245. Manager.prototype.processPacketQueue = function () {
  1246. if (this.packetBuffer.length > 0 && !this.encoding) {
  1247. var pack = this.packetBuffer.shift();
  1248. this.packet(pack);
  1249. }
  1250. };
  1251. /**
  1252. * Clean up transport subscriptions and packet buffer.
  1253. *
  1254. * @api private
  1255. */
  1256. Manager.prototype.cleanup = function () {
  1257. var subsLength = this.subs.length;
  1258. for (var i = 0; i < subsLength; i++) {
  1259. var sub = this.subs.shift();
  1260. sub.destroy();
  1261. }
  1262. this.packetBuffer = [];
  1263. this.encoding = false;
  1264. this.lastPing = null;
  1265. this.decoder.destroy();
  1266. };
  1267. /**
  1268. * Close the current socket.
  1269. *
  1270. * @api private
  1271. */
  1272. Manager.prototype.close = Manager.prototype.disconnect = function () {
  1273. this.skipReconnect = true;
  1274. this.reconnecting = false;
  1275. if ('opening' === this.readyState) {
  1276. // `onclose` will not fire because
  1277. // an open event never happened
  1278. this.cleanup();
  1279. }
  1280. this.backoff.reset();
  1281. this.readyState = 'closed';
  1282. if (this.engine) this.engine.close();
  1283. };
  1284. /**
  1285. * Called upon engine close.
  1286. *
  1287. * @api private
  1288. */
  1289. Manager.prototype.onclose = function (reason) {
  1290. this.cleanup();
  1291. this.backoff.reset();
  1292. this.readyState = 'closed';
  1293. this.emit('close', reason);
  1294. if (this._reconnection && !this.skipReconnect) {
  1295. this.reconnect();
  1296. }
  1297. };
  1298. /**
  1299. * Attempt a reconnection.
  1300. *
  1301. * @api private
  1302. */
  1303. Manager.prototype.reconnect = function () {
  1304. if (this.reconnecting || this.skipReconnect) return this;
  1305. var self = this;
  1306. if (this.backoff.attempts >= this._reconnectionAttempts) {
  1307. this.backoff.reset();
  1308. this.emitAll('reconnect_failed');
  1309. this.reconnecting = false;
  1310. } else {
  1311. var delay = this.backoff.duration();
  1312. this.reconnecting = true;
  1313. var timer = setTimeout(function () {
  1314. if (self.skipReconnect) return;
  1315. self.emitAll('reconnect_attempt', self.backoff.attempts);
  1316. self.emitAll('reconnecting', self.backoff.attempts);
  1317. // check again for the case socket closed in above events
  1318. if (self.skipReconnect) return;
  1319. self.open(function (err) {
  1320. if (err) {
  1321. self.reconnecting = false;
  1322. self.reconnect();
  1323. self.emitAll('reconnect_error', err.data);
  1324. } else {
  1325. self.onreconnect();
  1326. }
  1327. });
  1328. }, delay);
  1329. this.subs.push({
  1330. destroy: function destroy() {
  1331. clearTimeout(timer);
  1332. }
  1333. });
  1334. }
  1335. };
  1336. /**
  1337. * Called upon successful reconnect.
  1338. *
  1339. * @api private
  1340. */
  1341. Manager.prototype.onreconnect = function () {
  1342. var attempt = this.backoff.attempts;
  1343. this.reconnecting = false;
  1344. this.backoff.reset();
  1345. this.updateSocketIds();
  1346. this.emitAll('reconnect', attempt);
  1347. };
  1348. /***/ }),
  1349. /* 10 */
  1350. /***/ (function(module, exports, __webpack_require__) {
  1351. module.exports = __webpack_require__(11);
  1352. /**
  1353. * Exports parser
  1354. *
  1355. * @api public
  1356. *
  1357. */
  1358. module.exports.parser = __webpack_require__(18);
  1359. /***/ }),
  1360. /* 11 */
  1361. /***/ (function(module, exports, __webpack_require__) {
  1362. /**
  1363. * Module dependencies.
  1364. */
  1365. var transports = __webpack_require__(12);
  1366. var Emitter = __webpack_require__(5);
  1367. var debug = __webpack_require__(3)('engine.io-client:socket');
  1368. var index = __webpack_require__(32);
  1369. var parser = __webpack_require__(18);
  1370. var parseuri = __webpack_require__(2);
  1371. var parseqs = __webpack_require__(26);
  1372. /**
  1373. * Module exports.
  1374. */
  1375. module.exports = Socket;
  1376. /**
  1377. * Socket constructor.
  1378. *
  1379. * @param {String|Object} uri or options
  1380. * @param {Object} options
  1381. * @api public
  1382. */
  1383. function Socket (uri, opts) {
  1384. if (!(this instanceof Socket)) return new Socket(uri, opts);
  1385. opts = opts || {};
  1386. if (uri && 'object' === typeof uri) {
  1387. opts = uri;
  1388. uri = null;
  1389. }
  1390. if (uri) {
  1391. uri = parseuri(uri);
  1392. opts.hostname = uri.host;
  1393. opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
  1394. opts.port = uri.port;
  1395. if (uri.query) opts.query = uri.query;
  1396. } else if (opts.host) {
  1397. opts.hostname = parseuri(opts.host).host;
  1398. }
  1399. this.secure = null != opts.secure ? opts.secure
  1400. : (typeof location !== 'undefined' && 'https:' === location.protocol);
  1401. if (opts.hostname && !opts.port) {
  1402. // if no port is specified manually, use the protocol default
  1403. opts.port = this.secure ? '443' : '80';
  1404. }
  1405. this.agent = opts.agent || false;
  1406. this.hostname = opts.hostname ||
  1407. (typeof location !== 'undefined' ? location.hostname : 'localhost');
  1408. this.port = opts.port || (typeof location !== 'undefined' && location.port
  1409. ? location.port
  1410. : (this.secure ? 443 : 80));
  1411. this.query = opts.query || {};
  1412. if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
  1413. this.upgrade = false !== opts.upgrade;
  1414. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  1415. this.forceJSONP = !!opts.forceJSONP;
  1416. this.jsonp = false !== opts.jsonp;
  1417. this.forceBase64 = !!opts.forceBase64;
  1418. this.enablesXDR = !!opts.enablesXDR;
  1419. this.withCredentials = false !== opts.withCredentials;
  1420. this.timestampParam = opts.timestampParam || 't';
  1421. this.timestampRequests = opts.timestampRequests;
  1422. this.transports = opts.transports || ['polling', 'websocket'];
  1423. this.transportOptions = opts.transportOptions || {};
  1424. this.readyState = '';
  1425. this.writeBuffer = [];
  1426. this.prevBufferLen = 0;
  1427. this.policyPort = opts.policyPort || 843;
  1428. this.rememberUpgrade = opts.rememberUpgrade || false;
  1429. this.binaryType = null;
  1430. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  1431. this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
  1432. if (true === this.perMessageDeflate) this.perMessageDeflate = {};
  1433. if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
  1434. this.perMessageDeflate.threshold = 1024;
  1435. }
  1436. // SSL options for Node.js client
  1437. this.pfx = opts.pfx || null;
  1438. this.key = opts.key || null;
  1439. this.passphrase = opts.passphrase || null;
  1440. this.cert = opts.cert || null;
  1441. this.ca = opts.ca || null;
  1442. this.ciphers = opts.ciphers || null;
  1443. this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
  1444. this.forceNode = !!opts.forceNode;
  1445. // detect ReactNative environment
  1446. this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative');
  1447. // other options for Node.js or ReactNative client
  1448. if (typeof self === 'undefined' || this.isReactNative) {
  1449. if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
  1450. this.extraHeaders = opts.extraHeaders;
  1451. }
  1452. if (opts.localAddress) {
  1453. this.localAddress = opts.localAddress;
  1454. }
  1455. }
  1456. // set on handshake
  1457. this.id = null;
  1458. this.upgrades = null;
  1459. this.pingInterval = null;
  1460. this.pingTimeout = null;
  1461. // set on heartbeat
  1462. this.pingIntervalTimer = null;
  1463. this.pingTimeoutTimer = null;
  1464. this.open();
  1465. }
  1466. Socket.priorWebsocketSuccess = false;
  1467. /**
  1468. * Mix in `Emitter`.
  1469. */
  1470. Emitter(Socket.prototype);
  1471. /**
  1472. * Protocol version.
  1473. *
  1474. * @api public
  1475. */
  1476. Socket.protocol = parser.protocol; // this is an int
  1477. /**
  1478. * Expose deps for legacy compatibility
  1479. * and standalone browser access.
  1480. */
  1481. Socket.Socket = Socket;
  1482. Socket.Transport = __webpack_require__(17);
  1483. Socket.transports = __webpack_require__(12);
  1484. Socket.parser = __webpack_require__(18);
  1485. /**
  1486. * Creates transport of the given type.
  1487. *
  1488. * @param {String} transport name
  1489. * @return {Transport}
  1490. * @api private
  1491. */
  1492. Socket.prototype.createTransport = function (name) {
  1493. var query = clone(this.query);
  1494. // append engine.io protocol identifier
  1495. query.EIO = parser.protocol;
  1496. // transport name
  1497. query.transport = name;
  1498. // per-transport options
  1499. var options = this.transportOptions[name] || {};
  1500. // session id if we already have one
  1501. if (this.id) query.sid = this.id;
  1502. var transport = new transports[name]({
  1503. query: query,
  1504. socket: this,
  1505. agent: options.agent || this.agent,
  1506. hostname: options.hostname || this.hostname,
  1507. port: options.port || this.port,
  1508. secure: options.secure || this.secure,
  1509. path: options.path || this.path,
  1510. forceJSONP: options.forceJSONP || this.forceJSONP,
  1511. jsonp: options.jsonp || this.jsonp,
  1512. forceBase64: options.forceBase64 || this.forceBase64,
  1513. enablesXDR: options.enablesXDR || this.enablesXDR,
  1514. withCredentials: options.withCredentials || this.withCredentials,
  1515. timestampRequests: options.timestampRequests || this.timestampRequests,
  1516. timestampParam: options.timestampParam || this.timestampParam,
  1517. policyPort: options.policyPort || this.policyPort,
  1518. pfx: options.pfx || this.pfx,
  1519. key: options.key || this.key,
  1520. passphrase: options.passphrase || this.passphrase,
  1521. cert: options.cert || this.cert,
  1522. ca: options.ca || this.ca,
  1523. ciphers: options.ciphers || this.ciphers,
  1524. rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
  1525. perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
  1526. extraHeaders: options.extraHeaders || this.extraHeaders,
  1527. forceNode: options.forceNode || this.forceNode,
  1528. localAddress: options.localAddress || this.localAddress,
  1529. requestTimeout: options.requestTimeout || this.requestTimeout,
  1530. protocols: options.protocols || void (0),
  1531. isReactNative: this.isReactNative
  1532. });
  1533. return transport;
  1534. };
  1535. function clone (obj) {
  1536. var o = {};
  1537. for (var i in obj) {
  1538. if (obj.hasOwnProperty(i)) {
  1539. o[i] = obj[i];
  1540. }
  1541. }
  1542. return o;
  1543. }
  1544. /**
  1545. * Initializes transport to use and starts probe.
  1546. *
  1547. * @api private
  1548. */
  1549. Socket.prototype.open = function () {
  1550. var transport;
  1551. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
  1552. transport = 'websocket';
  1553. } else if (0 === this.transports.length) {
  1554. // Emit error on next tick so it can be listened to
  1555. var self = this;
  1556. setTimeout(function () {
  1557. self.emit('error', 'No transports available');
  1558. }, 0);
  1559. return;
  1560. } else {
  1561. transport = this.transports[0];
  1562. }
  1563. this.readyState = 'opening';
  1564. // Retry with the next transport if the transport is disabled (jsonp: false)
  1565. try {
  1566. transport = this.createTransport(transport);
  1567. } catch (e) {
  1568. this.transports.shift();
  1569. this.open();
  1570. return;
  1571. }
  1572. transport.open();
  1573. this.setTransport(transport);
  1574. };
  1575. /**
  1576. * Sets the current transport. Disables the existing one (if any).
  1577. *
  1578. * @api private
  1579. */
  1580. Socket.prototype.setTransport = function (transport) {
  1581. var self = this;
  1582. if (this.transport) {
  1583. this.transport.removeAllListeners();
  1584. }
  1585. // set up transport
  1586. this.transport = transport;
  1587. // set up transport listeners
  1588. transport
  1589. .on('drain', function () {
  1590. self.onDrain();
  1591. })
  1592. .on('packet', function (packet) {
  1593. self.onPacket(packet);
  1594. })
  1595. .on('error', function (e) {
  1596. self.onError(e);
  1597. })
  1598. .on('close', function () {
  1599. self.onClose('transport close');
  1600. });
  1601. };
  1602. /**
  1603. * Probes a transport.
  1604. *
  1605. * @param {String} transport name
  1606. * @api private
  1607. */
  1608. Socket.prototype.probe = function (name) {
  1609. var transport = this.createTransport(name, { probe: 1 });
  1610. var failed = false;
  1611. var self = this;
  1612. Socket.priorWebsocketSuccess = false;
  1613. function onTransportOpen () {
  1614. if (self.onlyBinaryUpgrades) {
  1615. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  1616. failed = failed || upgradeLosesBinary;
  1617. }
  1618. if (failed) return;
  1619. transport.send([{ type: 'ping', data: 'probe' }]);
  1620. transport.once('packet', function (msg) {
  1621. if (failed) return;
  1622. if ('pong' === msg.type && 'probe' === msg.data) {
  1623. self.upgrading = true;
  1624. self.emit('upgrading', transport);
  1625. if (!transport) return;
  1626. Socket.priorWebsocketSuccess = 'websocket' === transport.name;
  1627. self.transport.pause(function () {
  1628. if (failed) return;
  1629. if ('closed' === self.readyState) return;
  1630. cleanup();
  1631. self.setTransport(transport);
  1632. transport.send([{ type: 'upgrade' }]);
  1633. self.emit('upgrade', transport);
  1634. transport = null;
  1635. self.upgrading = false;
  1636. self.flush();
  1637. });
  1638. } else {
  1639. var err = new Error('probe error');
  1640. err.transport = transport.name;
  1641. self.emit('upgradeError', err);
  1642. }
  1643. });
  1644. }
  1645. function freezeTransport () {
  1646. if (failed) return;
  1647. // Any callback called by transport should be ignored since now
  1648. failed = true;
  1649. cleanup();
  1650. transport.close();
  1651. transport = null;
  1652. }
  1653. // Handle any error that happens while probing
  1654. function onerror (err) {
  1655. var error = new Error('probe error: ' + err);
  1656. error.transport = transport.name;
  1657. freezeTransport();
  1658. self.emit('upgradeError', error);
  1659. }
  1660. function onTransportClose () {
  1661. onerror('transport closed');
  1662. }
  1663. // When the socket is closed while we're probing
  1664. function onclose () {
  1665. onerror('socket closed');
  1666. }
  1667. // When the socket is upgraded while we're probing
  1668. function onupgrade (to) {
  1669. if (transport && to.name !== transport.name) {
  1670. freezeTransport();
  1671. }
  1672. }
  1673. // Remove all listeners on the transport and on self
  1674. function cleanup () {
  1675. transport.removeListener('open', onTransportOpen);
  1676. transport.removeListener('error', onerror);
  1677. transport.removeListener('close', onTransportClose);
  1678. self.removeListener('close', onclose);
  1679. self.removeListener('upgrading', onupgrade);
  1680. }
  1681. transport.once('open', onTransportOpen);
  1682. transport.once('error', onerror);
  1683. transport.once('close', onTransportClose);
  1684. this.once('close', onclose);
  1685. this.once('upgrading', onupgrade);
  1686. transport.open();
  1687. };
  1688. /**
  1689. * Called when connection is deemed open.
  1690. *
  1691. * @api public
  1692. */
  1693. Socket.prototype.onOpen = function () {
  1694. this.readyState = 'open';
  1695. Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
  1696. this.emit('open');
  1697. this.flush();
  1698. // we check for `readyState` in case an `open`
  1699. // listener already closed the socket
  1700. if ('open' === this.readyState && this.upgrade && this.transport.pause) {
  1701. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  1702. this.probe(this.upgrades[i]);
  1703. }
  1704. }
  1705. };
  1706. /**
  1707. * Handles a packet.
  1708. *
  1709. * @api private
  1710. */
  1711. Socket.prototype.onPacket = function (packet) {
  1712. if ('opening' === this.readyState || 'open' === this.readyState ||
  1713. 'closing' === this.readyState) {
  1714. this.emit('packet', packet);
  1715. // Socket is live - any packet counts
  1716. this.emit('heartbeat');
  1717. switch (packet.type) {
  1718. case 'open':
  1719. this.onHandshake(JSON.parse(packet.data));
  1720. break;
  1721. case 'pong':
  1722. this.setPing();
  1723. this.emit('pong');
  1724. break;
  1725. case 'error':
  1726. var err = new Error('server error');
  1727. err.code = packet.data;
  1728. this.onError(err);
  1729. break;
  1730. case 'message':
  1731. this.emit('data', packet.data);
  1732. this.emit('message', packet.data);
  1733. break;
  1734. }
  1735. } else {
  1736. }
  1737. };
  1738. /**
  1739. * Called upon handshake completion.
  1740. *
  1741. * @param {Object} handshake obj
  1742. * @api private
  1743. */
  1744. Socket.prototype.onHandshake = function (data) {
  1745. this.emit('handshake', data);
  1746. this.id = data.sid;
  1747. this.transport.query.sid = data.sid;
  1748. this.upgrades = this.filterUpgrades(data.upgrades);
  1749. this.pingInterval = data.pingInterval;
  1750. this.pingTimeout = data.pingTimeout;
  1751. this.onOpen();
  1752. // In case open handler closes socket
  1753. if ('closed' === this.readyState) return;
  1754. this.setPing();
  1755. // Prolong liveness of socket on heartbeat
  1756. this.removeListener('heartbeat', this.onHeartbeat);
  1757. this.on('heartbeat', this.onHeartbeat);
  1758. };
  1759. /**
  1760. * Resets ping timeout.
  1761. *
  1762. * @api private
  1763. */
  1764. Socket.prototype.onHeartbeat = function (timeout) {
  1765. clearTimeout(this.pingTimeoutTimer);
  1766. var self = this;
  1767. self.pingTimeoutTimer = setTimeout(function () {
  1768. if ('closed' === self.readyState) return;
  1769. self.onClose('ping timeout');
  1770. }, timeout || (self.pingInterval + self.pingTimeout));
  1771. };
  1772. /**
  1773. * Pings server every `this.pingInterval` and expects response
  1774. * within `this.pingTimeout` or closes connection.
  1775. *
  1776. * @api private
  1777. */
  1778. Socket.prototype.setPing = function () {
  1779. var self = this;
  1780. clearTimeout(self.pingIntervalTimer);
  1781. self.pingIntervalTimer = setTimeout(function () {
  1782. self.ping();
  1783. self.onHeartbeat(self.pingTimeout);
  1784. }, self.pingInterval);
  1785. };
  1786. /**
  1787. * Sends a ping packet.
  1788. *
  1789. * @api private
  1790. */
  1791. Socket.prototype.ping = function () {
  1792. var self = this;
  1793. this.sendPacket('ping', function () {
  1794. self.emit('ping');
  1795. });
  1796. };
  1797. /**
  1798. * Called on `drain` event
  1799. *
  1800. * @api private
  1801. */
  1802. Socket.prototype.onDrain = function () {
  1803. this.writeBuffer.splice(0, this.prevBufferLen);
  1804. // setting prevBufferLen = 0 is very important
  1805. // for example, when upgrading, upgrade packet is sent over,
  1806. // and a nonzero prevBufferLen could cause problems on `drain`
  1807. this.prevBufferLen = 0;
  1808. if (0 === this.writeBuffer.length) {
  1809. this.emit('drain');
  1810. } else {
  1811. this.flush();
  1812. }
  1813. };
  1814. /**
  1815. * Flush write buffers.
  1816. *
  1817. * @api private
  1818. */
  1819. Socket.prototype.flush = function () {
  1820. if ('closed' !== this.readyState && this.transport.writable &&
  1821. !this.upgrading && this.writeBuffer.length) {
  1822. this.transport.send(this.writeBuffer);
  1823. // keep track of current length of writeBuffer
  1824. // splice writeBuffer and callbackBuffer on `drain`
  1825. this.prevBufferLen = this.writeBuffer.length;
  1826. this.emit('flush');
  1827. }
  1828. };
  1829. /**
  1830. * Sends a message.
  1831. *
  1832. * @param {String} message.
  1833. * @param {Function} callback function.
  1834. * @param {Object} options.
  1835. * @return {Socket} for chaining.
  1836. * @api public
  1837. */
  1838. Socket.prototype.write =
  1839. Socket.prototype.send = function (msg, options, fn) {
  1840. this.sendPacket('message', msg, options, fn);
  1841. return this;
  1842. };
  1843. /**
  1844. * Sends a packet.
  1845. *
  1846. * @param {String} packet type.
  1847. * @param {String} data.
  1848. * @param {Object} options.
  1849. * @param {Function} callback function.
  1850. * @api private
  1851. */
  1852. Socket.prototype.sendPacket = function (type, data, options, fn) {
  1853. if ('function' === typeof data) {
  1854. fn = data;
  1855. data = undefined;
  1856. }
  1857. if ('function' === typeof options) {
  1858. fn = options;
  1859. options = null;
  1860. }
  1861. if ('closing' === this.readyState || 'closed' === this.readyState) {
  1862. return;
  1863. }
  1864. options = options || {};
  1865. options.compress = false !== options.compress;
  1866. var packet = {
  1867. type: type,
  1868. data: data,
  1869. options: options
  1870. };
  1871. this.emit('packetCreate', packet);
  1872. this.writeBuffer.push(packet);
  1873. if (fn) this.once('flush', fn);
  1874. this.flush();
  1875. };
  1876. /**
  1877. * Closes the connection.
  1878. *
  1879. * @api private
  1880. */
  1881. Socket.prototype.close = function () {
  1882. if ('opening' === this.readyState || 'open' === this.readyState) {
  1883. this.readyState = 'closing';
  1884. var self = this;
  1885. if (this.writeBuffer.length) {
  1886. this.once('drain', function () {
  1887. if (this.upgrading) {
  1888. waitForUpgrade();
  1889. } else {
  1890. close();
  1891. }
  1892. });
  1893. } else if (this.upgrading) {
  1894. waitForUpgrade();
  1895. } else {
  1896. close();
  1897. }
  1898. }
  1899. function close () {
  1900. self.onClose('forced close');
  1901. self.transport.close();
  1902. }
  1903. function cleanupAndClose () {
  1904. self.removeListener('upgrade', cleanupAndClose);
  1905. self.removeListener('upgradeError', cleanupAndClose);
  1906. close();
  1907. }
  1908. function waitForUpgrade () {
  1909. // wait for upgrade to finish since we can't send packets while pausing a transport
  1910. self.once('upgrade', cleanupAndClose);
  1911. self.once('upgradeError', cleanupAndClose);
  1912. }
  1913. return this;
  1914. };
  1915. /**
  1916. * Called upon transport error
  1917. *
  1918. * @api private
  1919. */
  1920. Socket.prototype.onError = function (err) {
  1921. Socket.priorWebsocketSuccess = false;
  1922. this.emit('error', err);
  1923. this.onClose('transport error', err);
  1924. };
  1925. /**
  1926. * Called upon transport close.
  1927. *
  1928. * @api private
  1929. */
  1930. Socket.prototype.onClose = function (reason, desc) {
  1931. if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
  1932. var self = this;
  1933. // clear timers
  1934. clearTimeout(this.pingIntervalTimer);
  1935. clearTimeout(this.pingTimeoutTimer);
  1936. // stop event from firing again for transport
  1937. this.transport.removeAllListeners('close');
  1938. // ensure transport won't stay open
  1939. this.transport.close();
  1940. // ignore further transport communication
  1941. this.transport.removeAllListeners();
  1942. // set ready state
  1943. this.readyState = 'closed';
  1944. // clear session id
  1945. this.id = null;
  1946. // emit close event
  1947. this.emit('close', reason, desc);
  1948. // clean buffers after, so users can still
  1949. // grab the buffers on `close` event
  1950. self.writeBuffer = [];
  1951. self.prevBufferLen = 0;
  1952. }
  1953. };
  1954. /**
  1955. * Filters upgrades, returning only those matching client transports.
  1956. *
  1957. * @param {Array} server upgrades
  1958. * @api private
  1959. *
  1960. */
  1961. Socket.prototype.filterUpgrades = function (upgrades) {
  1962. var filteredUpgrades = [];
  1963. for (var i = 0, j = upgrades.length; i < j; i++) {
  1964. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  1965. }
  1966. return filteredUpgrades;
  1967. };
  1968. /***/ }),
  1969. /* 12 */
  1970. /***/ (function(module, exports, __webpack_require__) {
  1971. /**
  1972. * Module dependencies
  1973. */
  1974. var XMLHttpRequest = __webpack_require__(13);
  1975. var XHR = __webpack_require__(15);
  1976. var JSONP = __webpack_require__(29);
  1977. var websocket = __webpack_require__(30);
  1978. /**
  1979. * Export transports.
  1980. */
  1981. exports.polling = polling;
  1982. exports.websocket = websocket;
  1983. /**
  1984. * Polling transport polymorphic constructor.
  1985. * Decides on xhr vs jsonp based on feature detection.
  1986. *
  1987. * @api private
  1988. */
  1989. function polling (opts) {
  1990. var xhr;
  1991. var xd = false;
  1992. var xs = false;
  1993. var jsonp = false !== opts.jsonp;
  1994. if (typeof location !== 'undefined') {
  1995. var isSSL = 'https:' === location.protocol;
  1996. var port = location.port;
  1997. // some user agents have empty `location.port`
  1998. if (!port) {
  1999. port = isSSL ? 443 : 80;
  2000. }
  2001. xd = opts.hostname !== location.hostname || port !== opts.port;
  2002. xs = opts.secure !== isSSL;
  2003. }
  2004. opts.xdomain = xd;
  2005. opts.xscheme = xs;
  2006. xhr = new XMLHttpRequest(opts);
  2007. if ('open' in xhr && !opts.forceJSONP) {
  2008. return new XHR(opts);
  2009. } else {
  2010. if (!jsonp) throw new Error('JSONP disabled');
  2011. return new JSONP(opts);
  2012. }
  2013. }
  2014. /***/ }),
  2015. /* 13 */
  2016. /***/ (function(module, exports, __webpack_require__) {
  2017. // browser shim for xmlhttprequest module
  2018. var hasCORS = __webpack_require__(14);
  2019. module.exports = function (opts) {
  2020. var xdomain = opts.xdomain;
  2021. // scheme must be same when usign XDomainRequest
  2022. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  2023. var xscheme = opts.xscheme;
  2024. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  2025. // https://github.com/Automattic/engine.io-client/pull/217
  2026. var enablesXDR = opts.enablesXDR;
  2027. // XMLHttpRequest can be disabled on IE
  2028. try {
  2029. if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  2030. return new XMLHttpRequest();
  2031. }
  2032. } catch (e) { }
  2033. // Use XDomainRequest for IE8 if enablesXDR is true
  2034. // because loading bar keeps flashing when using jsonp-polling
  2035. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  2036. try {
  2037. if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
  2038. return new XDomainRequest();
  2039. }
  2040. } catch (e) { }
  2041. if (!xdomain) {
  2042. try {
  2043. return new self[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
  2044. } catch (e) { }
  2045. }
  2046. };
  2047. /***/ }),
  2048. /* 14 */
  2049. /***/ (function(module, exports) {
  2050. /**
  2051. * Module exports.
  2052. *
  2053. * Logic borrowed from Modernizr:
  2054. *
  2055. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  2056. */
  2057. try {
  2058. module.exports = typeof XMLHttpRequest !== 'undefined' &&
  2059. 'withCredentials' in new XMLHttpRequest();
  2060. } catch (err) {
  2061. // if XMLHttp support is disabled in IE then it will throw
  2062. // when trying to create
  2063. module.exports = false;
  2064. }
  2065. /***/ }),
  2066. /* 15 */
  2067. /***/ (function(module, exports, __webpack_require__) {
  2068. /* global attachEvent */
  2069. /**
  2070. * Module requirements.
  2071. */
  2072. var XMLHttpRequest = __webpack_require__(13);
  2073. var Polling = __webpack_require__(16);
  2074. var Emitter = __webpack_require__(5);
  2075. var inherit = __webpack_require__(27);
  2076. var debug = __webpack_require__(3)('engine.io-client:polling-xhr');
  2077. /**
  2078. * Module exports.
  2079. */
  2080. module.exports = XHR;
  2081. module.exports.Request = Request;
  2082. /**
  2083. * Empty function
  2084. */
  2085. function empty () {}
  2086. /**
  2087. * XHR Polling constructor.
  2088. *
  2089. * @param {Object} opts
  2090. * @api public
  2091. */
  2092. function XHR (opts) {
  2093. Polling.call(this, opts);
  2094. this.requestTimeout = opts.requestTimeout;
  2095. this.extraHeaders = opts.extraHeaders;
  2096. if (typeof location !== 'undefined') {
  2097. var isSSL = 'https:' === location.protocol;
  2098. var port = location.port;
  2099. // some user agents have empty `location.port`
  2100. if (!port) {
  2101. port = isSSL ? 443 : 80;
  2102. }
  2103. this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
  2104. port !== opts.port;
  2105. this.xs = opts.secure !== isSSL;
  2106. }
  2107. }
  2108. /**
  2109. * Inherits from Polling.
  2110. */
  2111. inherit(XHR, Polling);
  2112. /**
  2113. * XHR supports binary
  2114. */
  2115. XHR.prototype.supportsBinary = true;
  2116. /**
  2117. * Creates a request.
  2118. *
  2119. * @param {String} method
  2120. * @api private
  2121. */
  2122. XHR.prototype.request = function (opts) {
  2123. opts = opts || {};
  2124. opts.uri = this.uri();
  2125. opts.xd = this.xd;
  2126. opts.xs = this.xs;
  2127. opts.agent = this.agent || false;
  2128. opts.supportsBinary = this.supportsBinary;
  2129. opts.enablesXDR = this.enablesXDR;
  2130. opts.withCredentials = this.withCredentials;
  2131. // SSL options for Node.js client
  2132. opts.pfx = this.pfx;
  2133. opts.key = this.key;
  2134. opts.passphrase = this.passphrase;
  2135. opts.cert = this.cert;
  2136. opts.ca = this.ca;
  2137. opts.ciphers = this.ciphers;
  2138. opts.rejectUnauthorized = this.rejectUnauthorized;
  2139. opts.requestTimeout = this.requestTimeout;
  2140. // other options for Node.js client
  2141. opts.extraHeaders = this.extraHeaders;
  2142. return new Request(opts);
  2143. };
  2144. /**
  2145. * Sends data.
  2146. *
  2147. * @param {String} data to send.
  2148. * @param {Function} called upon flush.
  2149. * @api private
  2150. */
  2151. XHR.prototype.doWrite = function (data, fn) {
  2152. var isBinary = typeof data !== 'string' && data !== undefined;
  2153. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  2154. var self = this;
  2155. req.on('success', fn);
  2156. req.on('error', function (err) {
  2157. self.onError('xhr post error', err);
  2158. });
  2159. this.sendXhr = req;
  2160. };
  2161. /**
  2162. * Starts a poll cycle.
  2163. *
  2164. * @api private
  2165. */
  2166. XHR.prototype.doPoll = function () {
  2167. var req = this.request();
  2168. var self = this;
  2169. req.on('data', function (data) {
  2170. self.onData(data);
  2171. });
  2172. req.on('error', function (err) {
  2173. self.onError('xhr poll error', err);
  2174. });
  2175. this.pollXhr = req;
  2176. };
  2177. /**
  2178. * Request constructor
  2179. *
  2180. * @param {Object} options
  2181. * @api public
  2182. */
  2183. function Request (opts) {
  2184. this.method = opts.method || 'GET';
  2185. this.uri = opts.uri;
  2186. this.xd = !!opts.xd;
  2187. this.xs = !!opts.xs;
  2188. this.async = false !== opts.async;
  2189. this.data = undefined !== opts.data ? opts.data : null;
  2190. this.agent = opts.agent;
  2191. this.isBinary = opts.isBinary;
  2192. this.supportsBinary = opts.supportsBinary;
  2193. this.enablesXDR = opts.enablesXDR;
  2194. this.withCredentials = opts.withCredentials;
  2195. this.requestTimeout = opts.requestTimeout;
  2196. // SSL options for Node.js client
  2197. this.pfx = opts.pfx;
  2198. this.key = opts.key;
  2199. this.passphrase = opts.passphrase;
  2200. this.cert = opts.cert;
  2201. this.ca = opts.ca;
  2202. this.ciphers = opts.ciphers;
  2203. this.rejectUnauthorized = opts.rejectUnauthorized;
  2204. // other options for Node.js client
  2205. this.extraHeaders = opts.extraHeaders;
  2206. this.create();
  2207. }
  2208. /**
  2209. * Mix in `Emitter`.
  2210. */
  2211. Emitter(Request.prototype);
  2212. /**
  2213. * Creates the XHR object and sends the request.
  2214. *
  2215. * @api private
  2216. */
  2217. Request.prototype.create = function () {
  2218. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  2219. // SSL options for Node.js client
  2220. opts.pfx = this.pfx;
  2221. opts.key = this.key;
  2222. opts.passphrase = this.passphrase;
  2223. opts.cert = this.cert;
  2224. opts.ca = this.ca;
  2225. opts.ciphers = this.ciphers;
  2226. opts.rejectUnauthorized = this.rejectUnauthorized;
  2227. var xhr = this.xhr = new XMLHttpRequest(opts);
  2228. var self = this;
  2229. try {
  2230. xhr.open(this.method, this.uri, this.async);
  2231. try {
  2232. if (this.extraHeaders) {
  2233. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  2234. for (var i in this.extraHeaders) {
  2235. if (this.extraHeaders.hasOwnProperty(i)) {
  2236. xhr.setRequestHeader(i, this.extraHeaders[i]);
  2237. }
  2238. }
  2239. }
  2240. } catch (e) {}
  2241. if ('POST' === this.method) {
  2242. try {
  2243. if (this.isBinary) {
  2244. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  2245. } else {
  2246. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  2247. }
  2248. } catch (e) {}
  2249. }
  2250. try {
  2251. xhr.setRequestHeader('Accept', '*/*');
  2252. } catch (e) {}
  2253. // ie6 check
  2254. if ('withCredentials' in xhr) {
  2255. xhr.withCredentials = this.withCredentials;
  2256. }
  2257. if (this.requestTimeout) {
  2258. xhr.timeout = this.requestTimeout;
  2259. }
  2260. if (this.hasXDR()) {
  2261. xhr.onload = function () {
  2262. self.onLoad();
  2263. };
  2264. xhr.onerror = function () {
  2265. self.onError(xhr.responseText);
  2266. };
  2267. } else {
  2268. xhr.onreadystatechange = function () {
  2269. if (xhr.readyState === 2) {
  2270. try {
  2271. var contentType = xhr.getResponseHeader('Content-Type');
  2272. if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
  2273. xhr.responseType = 'arraybuffer';
  2274. }
  2275. } catch (e) {}
  2276. }
  2277. if (4 !== xhr.readyState) return;
  2278. if (200 === xhr.status || 1223 === xhr.status) {
  2279. self.onLoad();
  2280. } else {
  2281. // make sure the `error` event handler that's user-set
  2282. // does not throw in the same tick and gets caught here
  2283. setTimeout(function () {
  2284. self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
  2285. }, 0);
  2286. }
  2287. };
  2288. }
  2289. xhr.send(this.data);
  2290. } catch (e) {
  2291. // Need to defer since .create() is called directly fhrom the constructor
  2292. // and thus the 'error' event can only be only bound *after* this exception
  2293. // occurs. Therefore, also, we cannot throw here at all.
  2294. setTimeout(function () {
  2295. self.onError(e);
  2296. }, 0);
  2297. return;
  2298. }
  2299. if (typeof document !== 'undefined') {
  2300. this.index = Request.requestsCount++;
  2301. Request.requests[this.index] = this;
  2302. }
  2303. };
  2304. /**
  2305. * Called upon successful response.
  2306. *
  2307. * @api private
  2308. */
  2309. Request.prototype.onSuccess = function () {
  2310. this.emit('success');
  2311. this.cleanup();
  2312. };
  2313. /**
  2314. * Called if we have data.
  2315. *
  2316. * @api private
  2317. */
  2318. Request.prototype.onData = function (data) {
  2319. this.emit('data', data);
  2320. this.onSuccess();
  2321. };
  2322. /**
  2323. * Called upon error.
  2324. *
  2325. * @api private
  2326. */
  2327. Request.prototype.onError = function (err) {
  2328. this.emit('error', err);
  2329. this.cleanup(true);
  2330. };
  2331. /**
  2332. * Cleans up house.
  2333. *
  2334. * @api private
  2335. */
  2336. Request.prototype.cleanup = function (fromError) {
  2337. if ('undefined' === typeof this.xhr || null === this.xhr) {
  2338. return;
  2339. }
  2340. // xmlhttprequest
  2341. if (this.hasXDR()) {
  2342. this.xhr.onload = this.xhr.onerror = empty;
  2343. } else {
  2344. this.xhr.onreadystatechange = empty;
  2345. }
  2346. if (fromError) {
  2347. try {
  2348. this.xhr.abort();
  2349. } catch (e) {}
  2350. }
  2351. if (typeof document !== 'undefined') {
  2352. delete Request.requests[this.index];
  2353. }
  2354. this.xhr = null;
  2355. };
  2356. /**
  2357. * Called upon load.
  2358. *
  2359. * @api private
  2360. */
  2361. Request.prototype.onLoad = function () {
  2362. var data;
  2363. try {
  2364. var contentType;
  2365. try {
  2366. contentType = this.xhr.getResponseHeader('Content-Type');
  2367. } catch (e) {}
  2368. if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
  2369. data = this.xhr.response || this.xhr.responseText;
  2370. } else {
  2371. data = this.xhr.responseText;
  2372. }
  2373. } catch (e) {
  2374. this.onError(e);
  2375. }
  2376. if (null != data) {
  2377. this.onData(data);
  2378. }
  2379. };
  2380. /**
  2381. * Check if it has XDomainRequest.
  2382. *
  2383. * @api private
  2384. */
  2385. Request.prototype.hasXDR = function () {
  2386. return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
  2387. };
  2388. /**
  2389. * Aborts the request.
  2390. *
  2391. * @api public
  2392. */
  2393. Request.prototype.abort = function () {
  2394. this.cleanup();
  2395. };
  2396. /**
  2397. * Aborts pending requests when unloading the window. This is needed to prevent
  2398. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  2399. * emitted.
  2400. */
  2401. Request.requestsCount = 0;
  2402. Request.requests = {};
  2403. if (typeof document !== 'undefined') {
  2404. if (typeof attachEvent === 'function') {
  2405. attachEvent('onunload', unloadHandler);
  2406. } else if (typeof addEventListener === 'function') {
  2407. var terminationEvent = 'onpagehide' in self ? 'pagehide' : 'unload';
  2408. addEventListener(terminationEvent, unloadHandler, false);
  2409. }
  2410. }
  2411. function unloadHandler () {
  2412. for (var i in Request.requests) {
  2413. if (Request.requests.hasOwnProperty(i)) {
  2414. Request.requests[i].abort();
  2415. }
  2416. }
  2417. }
  2418. /***/ }),
  2419. /* 16 */
  2420. /***/ (function(module, exports, __webpack_require__) {
  2421. /**
  2422. * Module dependencies.
  2423. */
  2424. var Transport = __webpack_require__(17);
  2425. var parseqs = __webpack_require__(26);
  2426. var parser = __webpack_require__(18);
  2427. var inherit = __webpack_require__(27);
  2428. var yeast = __webpack_require__(28);
  2429. var debug = __webpack_require__(3)('engine.io-client:polling');
  2430. /**
  2431. * Module exports.
  2432. */
  2433. module.exports = Polling;
  2434. /**
  2435. * Is XHR2 supported?
  2436. */
  2437. var hasXHR2 = (function () {
  2438. var XMLHttpRequest = __webpack_require__(13);
  2439. var xhr = new XMLHttpRequest({ xdomain: false });
  2440. return null != xhr.responseType;
  2441. })();
  2442. /**
  2443. * Polling interface.
  2444. *
  2445. * @param {Object} opts
  2446. * @api private
  2447. */
  2448. function Polling (opts) {
  2449. var forceBase64 = (opts && opts.forceBase64);
  2450. if (!hasXHR2 || forceBase64) {
  2451. this.supportsBinary = false;
  2452. }
  2453. Transport.call(this, opts);
  2454. }
  2455. /**
  2456. * Inherits from Transport.
  2457. */
  2458. inherit(Polling, Transport);
  2459. /**
  2460. * Transport name.
  2461. */
  2462. Polling.prototype.name = 'polling';
  2463. /**
  2464. * Opens the socket (triggers polling). We write a PING message to determine
  2465. * when the transport is open.
  2466. *
  2467. * @api private
  2468. */
  2469. Polling.prototype.doOpen = function () {
  2470. this.poll();
  2471. };
  2472. /**
  2473. * Pauses polling.
  2474. *
  2475. * @param {Function} callback upon buffers are flushed and transport is paused
  2476. * @api private
  2477. */
  2478. Polling.prototype.pause = function (onPause) {
  2479. var self = this;
  2480. this.readyState = 'pausing';
  2481. function pause () {
  2482. self.readyState = 'paused';
  2483. onPause();
  2484. }
  2485. if (this.polling || !this.writable) {
  2486. var total = 0;
  2487. if (this.polling) {
  2488. total++;
  2489. this.once('pollComplete', function () {
  2490. --total || pause();
  2491. });
  2492. }
  2493. if (!this.writable) {
  2494. total++;
  2495. this.once('drain', function () {
  2496. --total || pause();
  2497. });
  2498. }
  2499. } else {
  2500. pause();
  2501. }
  2502. };
  2503. /**
  2504. * Starts polling cycle.
  2505. *
  2506. * @api public
  2507. */
  2508. Polling.prototype.poll = function () {
  2509. this.polling = true;
  2510. this.doPoll();
  2511. this.emit('poll');
  2512. };
  2513. /**
  2514. * Overloads onData to detect payloads.
  2515. *
  2516. * @api private
  2517. */
  2518. Polling.prototype.onData = function (data) {
  2519. var self = this;
  2520. var callback = function (packet, index, total) {
  2521. // if its the first message we consider the transport open
  2522. if ('opening' === self.readyState) {
  2523. self.onOpen();
  2524. }
  2525. // if its a close packet, we close the ongoing requests
  2526. if ('close' === packet.type) {
  2527. self.onClose();
  2528. return false;
  2529. }
  2530. // otherwise bypass onData and handle the message
  2531. self.onPacket(packet);
  2532. };
  2533. // decode payload
  2534. parser.decodePayload(data, this.socket.binaryType, callback);
  2535. // if an event did not trigger closing
  2536. if ('closed' !== this.readyState) {
  2537. // if we got data we're not polling
  2538. this.polling = false;
  2539. this.emit('pollComplete');
  2540. if ('open' === this.readyState) {
  2541. this.poll();
  2542. } else {
  2543. }
  2544. }
  2545. };
  2546. /**
  2547. * For polling, send a close packet.
  2548. *
  2549. * @api private
  2550. */
  2551. Polling.prototype.doClose = function () {
  2552. var self = this;
  2553. function close () {
  2554. self.write([{ type: 'close' }]);
  2555. }
  2556. if ('open' === this.readyState) {
  2557. close();
  2558. } else {
  2559. // in case we're trying to close while
  2560. // handshaking is in progress (GH-164)
  2561. this.once('open', close);
  2562. }
  2563. };
  2564. /**
  2565. * Writes a packets payload.
  2566. *
  2567. * @param {Array} data packets
  2568. * @param {Function} drain callback
  2569. * @api private
  2570. */
  2571. Polling.prototype.write = function (packets) {
  2572. var self = this;
  2573. this.writable = false;
  2574. var callbackfn = function () {
  2575. self.writable = true;
  2576. self.emit('drain');
  2577. };
  2578. parser.encodePayload(packets, this.supportsBinary, function (data) {
  2579. self.doWrite(data, callbackfn);
  2580. });
  2581. };
  2582. /**
  2583. * Generates uri for connection.
  2584. *
  2585. * @api private
  2586. */
  2587. Polling.prototype.uri = function () {
  2588. var query = this.query || {};
  2589. var schema = this.secure ? 'https' : 'http';
  2590. var port = '';
  2591. // cache busting is forced
  2592. if (false !== this.timestampRequests) {
  2593. query[this.timestampParam] = yeast();
  2594. }
  2595. if (!this.supportsBinary && !query.sid) {
  2596. query.b64 = 1;
  2597. }
  2598. query = parseqs.encode(query);
  2599. // avoid port if default for schema
  2600. if (this.port && (('https' === schema && Number(this.port) !== 443) ||
  2601. ('http' === schema && Number(this.port) !== 80))) {
  2602. port = ':' + this.port;
  2603. }
  2604. // prepend ? to query
  2605. if (query.length) {
  2606. query = '?' + query;
  2607. }
  2608. var ipv6 = this.hostname.indexOf(':') !== -1;
  2609. return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
  2610. };
  2611. /***/ }),
  2612. /* 17 */
  2613. /***/ (function(module, exports, __webpack_require__) {
  2614. /**
  2615. * Module dependencies.
  2616. */
  2617. var parser = __webpack_require__(18);
  2618. var Emitter = __webpack_require__(5);
  2619. /**
  2620. * Module exports.
  2621. */
  2622. module.exports = Transport;
  2623. /**
  2624. * Transport abstract constructor.
  2625. *
  2626. * @param {Object} options.
  2627. * @api private
  2628. */
  2629. function Transport (opts) {
  2630. this.path = opts.path;
  2631. this.hostname = opts.hostname;
  2632. this.port = opts.port;
  2633. this.secure = opts.secure;
  2634. this.query = opts.query;
  2635. this.timestampParam = opts.timestampParam;
  2636. this.timestampRequests = opts.timestampRequests;
  2637. this.readyState = '';
  2638. this.agent = opts.agent || false;
  2639. this.socket = opts.socket;
  2640. this.enablesXDR = opts.enablesXDR;
  2641. this.withCredentials = opts.withCredentials;
  2642. // SSL options for Node.js client
  2643. this.pfx = opts.pfx;
  2644. this.key = opts.key;
  2645. this.passphrase = opts.passphrase;
  2646. this.cert = opts.cert;
  2647. this.ca = opts.ca;
  2648. this.ciphers = opts.ciphers;
  2649. this.rejectUnauthorized = opts.rejectUnauthorized;
  2650. this.forceNode = opts.forceNode;
  2651. // results of ReactNative environment detection
  2652. this.isReactNative = opts.isReactNative;
  2653. // other options for Node.js client
  2654. this.extraHeaders = opts.extraHeaders;
  2655. this.localAddress = opts.localAddress;
  2656. }
  2657. /**
  2658. * Mix in `Emitter`.
  2659. */
  2660. Emitter(Transport.prototype);
  2661. /**
  2662. * Emits an error.
  2663. *
  2664. * @param {String} str
  2665. * @return {Transport} for chaining
  2666. * @api public
  2667. */
  2668. Transport.prototype.onError = function (msg, desc) {
  2669. var err = new Error(msg);
  2670. err.type = 'TransportError';
  2671. err.description = desc;
  2672. this.emit('error', err);
  2673. return this;
  2674. };
  2675. /**
  2676. * Opens the transport.
  2677. *
  2678. * @api public
  2679. */
  2680. Transport.prototype.open = function () {
  2681. if ('closed' === this.readyState || '' === this.readyState) {
  2682. this.readyState = 'opening';
  2683. this.doOpen();
  2684. }
  2685. return this;
  2686. };
  2687. /**
  2688. * Closes the transport.
  2689. *
  2690. * @api private
  2691. */
  2692. Transport.prototype.close = function () {
  2693. if ('opening' === this.readyState || 'open' === this.readyState) {
  2694. this.doClose();
  2695. this.onClose();
  2696. }
  2697. return this;
  2698. };
  2699. /**
  2700. * Sends multiple packets.
  2701. *
  2702. * @param {Array} packets
  2703. * @api private
  2704. */
  2705. Transport.prototype.send = function (packets) {
  2706. if ('open' === this.readyState) {
  2707. this.write(packets);
  2708. } else {
  2709. throw new Error('Transport not open');
  2710. }
  2711. };
  2712. /**
  2713. * Called upon open
  2714. *
  2715. * @api private
  2716. */
  2717. Transport.prototype.onOpen = function () {
  2718. this.readyState = 'open';
  2719. this.writable = true;
  2720. this.emit('open');
  2721. };
  2722. /**
  2723. * Called with data.
  2724. *
  2725. * @param {String} data
  2726. * @api private
  2727. */
  2728. Transport.prototype.onData = function (data) {
  2729. var packet = parser.decodePacket(data, this.socket.binaryType);
  2730. this.onPacket(packet);
  2731. };
  2732. /**
  2733. * Called with a decoded packet.
  2734. */
  2735. Transport.prototype.onPacket = function (packet) {
  2736. this.emit('packet', packet);
  2737. };
  2738. /**
  2739. * Called upon close.
  2740. *
  2741. * @api private
  2742. */
  2743. Transport.prototype.onClose = function () {
  2744. this.readyState = 'closed';
  2745. this.emit('close');
  2746. };
  2747. /***/ }),
  2748. /* 18 */
  2749. /***/ (function(module, exports, __webpack_require__) {
  2750. /**
  2751. * Module dependencies.
  2752. */
  2753. var keys = __webpack_require__(19);
  2754. var hasBinary = __webpack_require__(20);
  2755. var sliceBuffer = __webpack_require__(21);
  2756. var after = __webpack_require__(22);
  2757. var utf8 = __webpack_require__(23);
  2758. var base64encoder;
  2759. if (typeof ArrayBuffer !== 'undefined') {
  2760. base64encoder = __webpack_require__(24);
  2761. }
  2762. /**
  2763. * Check if we are running an android browser. That requires us to use
  2764. * ArrayBuffer with polling transports...
  2765. *
  2766. * http://ghinda.net/jpeg-blob-ajax-android/
  2767. */
  2768. var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
  2769. /**
  2770. * Check if we are running in PhantomJS.
  2771. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  2772. * https://github.com/ariya/phantomjs/issues/11395
  2773. * @type boolean
  2774. */
  2775. var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
  2776. /**
  2777. * When true, avoids using Blobs to encode payloads.
  2778. * @type boolean
  2779. */
  2780. var dontSendBlobs = isAndroid || isPhantomJS;
  2781. /**
  2782. * Current protocol version.
  2783. */
  2784. exports.protocol = 3;
  2785. /**
  2786. * Packet types.
  2787. */
  2788. var packets = exports.packets = {
  2789. open: 0 // non-ws
  2790. , close: 1 // non-ws
  2791. , ping: 2
  2792. , pong: 3
  2793. , message: 4
  2794. , upgrade: 5
  2795. , noop: 6
  2796. };
  2797. var packetslist = keys(packets);
  2798. /**
  2799. * Premade error packet.
  2800. */
  2801. var err = { type: 'error', data: 'parser error' };
  2802. /**
  2803. * Create a blob api even for blob builder when vendor prefixes exist
  2804. */
  2805. var Blob = __webpack_require__(25);
  2806. /**
  2807. * Encodes a packet.
  2808. *
  2809. * <packet type id> [ <data> ]
  2810. *
  2811. * Example:
  2812. *
  2813. * 5hello world
  2814. * 3
  2815. * 4
  2816. *
  2817. * Binary is encoded in an identical principle
  2818. *
  2819. * @api private
  2820. */
  2821. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  2822. if (typeof supportsBinary === 'function') {
  2823. callback = supportsBinary;
  2824. supportsBinary = false;
  2825. }
  2826. if (typeof utf8encode === 'function') {
  2827. callback = utf8encode;
  2828. utf8encode = null;
  2829. }
  2830. var data = (packet.data === undefined)
  2831. ? undefined
  2832. : packet.data.buffer || packet.data;
  2833. if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
  2834. return encodeArrayBuffer(packet, supportsBinary, callback);
  2835. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  2836. return encodeBlob(packet, supportsBinary, callback);
  2837. }
  2838. // might be an object with { base64: true, data: dataAsBase64String }
  2839. if (data && data.base64) {
  2840. return encodeBase64Object(packet, callback);
  2841. }
  2842. // Sending data as a utf-8 string
  2843. var encoded = packets[packet.type];
  2844. // data fragment is optional
  2845. if (undefined !== packet.data) {
  2846. encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
  2847. }
  2848. return callback('' + encoded);
  2849. };
  2850. function encodeBase64Object(packet, callback) {
  2851. // packet data is an object { base64: true, data: dataAsBase64String }
  2852. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  2853. return callback(message);
  2854. }
  2855. /**
  2856. * Encode packet helpers for binary types
  2857. */
  2858. function encodeArrayBuffer(packet, supportsBinary, callback) {
  2859. if (!supportsBinary) {
  2860. return exports.encodeBase64Packet(packet, callback);
  2861. }
  2862. var data = packet.data;
  2863. var contentArray = new Uint8Array(data);
  2864. var resultBuffer = new Uint8Array(1 + data.byteLength);
  2865. resultBuffer[0] = packets[packet.type];
  2866. for (var i = 0; i < contentArray.length; i++) {
  2867. resultBuffer[i+1] = contentArray[i];
  2868. }
  2869. return callback(resultBuffer.buffer);
  2870. }
  2871. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  2872. if (!supportsBinary) {
  2873. return exports.encodeBase64Packet(packet, callback);
  2874. }
  2875. var fr = new FileReader();
  2876. fr.onload = function() {
  2877. exports.encodePacket({ type: packet.type, data: fr.result }, supportsBinary, true, callback);
  2878. };
  2879. return fr.readAsArrayBuffer(packet.data);
  2880. }
  2881. function encodeBlob(packet, supportsBinary, callback) {
  2882. if (!supportsBinary) {
  2883. return exports.encodeBase64Packet(packet, callback);
  2884. }
  2885. if (dontSendBlobs) {
  2886. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  2887. }
  2888. var length = new Uint8Array(1);
  2889. length[0] = packets[packet.type];
  2890. var blob = new Blob([length.buffer, packet.data]);
  2891. return callback(blob);
  2892. }
  2893. /**
  2894. * Encodes a packet with binary data in a base64 string
  2895. *
  2896. * @param {Object} packet, has `type` and `data`
  2897. * @return {String} base64 encoded message
  2898. */
  2899. exports.encodeBase64Packet = function(packet, callback) {
  2900. var message = 'b' + exports.packets[packet.type];
  2901. if (typeof Blob !== 'undefined' && packet.data instanceof Blob) {
  2902. var fr = new FileReader();
  2903. fr.onload = function() {
  2904. var b64 = fr.result.split(',')[1];
  2905. callback(message + b64);
  2906. };
  2907. return fr.readAsDataURL(packet.data);
  2908. }
  2909. var b64data;
  2910. try {
  2911. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  2912. } catch (e) {
  2913. // iPhone Safari doesn't let you apply with typed arrays
  2914. var typed = new Uint8Array(packet.data);
  2915. var basic = new Array(typed.length);
  2916. for (var i = 0; i < typed.length; i++) {
  2917. basic[i] = typed[i];
  2918. }
  2919. b64data = String.fromCharCode.apply(null, basic);
  2920. }
  2921. message += btoa(b64data);
  2922. return callback(message);
  2923. };
  2924. /**
  2925. * Decodes a packet. Changes format to Blob if requested.
  2926. *
  2927. * @return {Object} with `type` and `data` (if any)
  2928. * @api private
  2929. */
  2930. exports.decodePacket = function (data, binaryType, utf8decode) {
  2931. if (data === undefined) {
  2932. return err;
  2933. }
  2934. // String data
  2935. if (typeof data === 'string') {
  2936. if (data.charAt(0) === 'b') {
  2937. return exports.decodeBase64Packet(data.substr(1), binaryType);
  2938. }
  2939. if (utf8decode) {
  2940. data = tryDecode(data);
  2941. if (data === false) {
  2942. return err;
  2943. }
  2944. }
  2945. var type = data.charAt(0);
  2946. if (Number(type) != type || !packetslist[type]) {
  2947. return err;
  2948. }
  2949. if (data.length > 1) {
  2950. return { type: packetslist[type], data: data.substring(1) };
  2951. } else {
  2952. return { type: packetslist[type] };
  2953. }
  2954. }
  2955. var asArray = new Uint8Array(data);
  2956. var type = asArray[0];
  2957. var rest = sliceBuffer(data, 1);
  2958. if (Blob && binaryType === 'blob') {
  2959. rest = new Blob([rest]);
  2960. }
  2961. return { type: packetslist[type], data: rest };
  2962. };
  2963. function tryDecode(data) {
  2964. try {
  2965. data = utf8.decode(data, { strict: false });
  2966. } catch (e) {
  2967. return false;
  2968. }
  2969. return data;
  2970. }
  2971. /**
  2972. * Decodes a packet encoded in a base64 string
  2973. *
  2974. * @param {String} base64 encoded message
  2975. * @return {Object} with `type` and `data` (if any)
  2976. */
  2977. exports.decodeBase64Packet = function(msg, binaryType) {
  2978. var type = packetslist[msg.charAt(0)];
  2979. if (!base64encoder) {
  2980. return { type: type, data: { base64: true, data: msg.substr(1) } };
  2981. }
  2982. var data = base64encoder.decode(msg.substr(1));
  2983. if (binaryType === 'blob' && Blob) {
  2984. data = new Blob([data]);
  2985. }
  2986. return { type: type, data: data };
  2987. };
  2988. /**
  2989. * Encodes multiple messages (payload).
  2990. *
  2991. * <length>:data
  2992. *
  2993. * Example:
  2994. *
  2995. * 11:hello world2:hi
  2996. *
  2997. * If any contents are binary, they will be encoded as base64 strings. Base64
  2998. * encoded strings are marked with a b before the length specifier
  2999. *
  3000. * @param {Array} packets
  3001. * @api private
  3002. */
  3003. exports.encodePayload = function (packets, supportsBinary, callback) {
  3004. if (typeof supportsBinary === 'function') {
  3005. callback = supportsBinary;
  3006. supportsBinary = null;
  3007. }
  3008. var isBinary = hasBinary(packets);
  3009. if (supportsBinary && isBinary) {
  3010. if (Blob && !dontSendBlobs) {
  3011. return exports.encodePayloadAsBlob(packets, callback);
  3012. }
  3013. return exports.encodePayloadAsArrayBuffer(packets, callback);
  3014. }
  3015. if (!packets.length) {
  3016. return callback('0:');
  3017. }
  3018. function setLengthHeader(message) {
  3019. return message.length + ':' + message;
  3020. }
  3021. function encodeOne(packet, doneCallback) {
  3022. exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
  3023. doneCallback(null, setLengthHeader(message));
  3024. });
  3025. }
  3026. map(packets, encodeOne, function(err, results) {
  3027. return callback(results.join(''));
  3028. });
  3029. };
  3030. /**
  3031. * Async array map using after
  3032. */
  3033. function map(ary, each, done) {
  3034. var result = new Array(ary.length);
  3035. var next = after(ary.length, done);
  3036. var eachWithIndex = function(i, el, cb) {
  3037. each(el, function(error, msg) {
  3038. result[i] = msg;
  3039. cb(error, result);
  3040. });
  3041. };
  3042. for (var i = 0; i < ary.length; i++) {
  3043. eachWithIndex(i, ary[i], next);
  3044. }
  3045. }
  3046. /*
  3047. * Decodes data when a payload is maybe expected. Possible binary contents are
  3048. * decoded from their base64 representation
  3049. *
  3050. * @param {String} data, callback method
  3051. * @api public
  3052. */
  3053. exports.decodePayload = function (data, binaryType, callback) {
  3054. if (typeof data !== 'string') {
  3055. return exports.decodePayloadAsBinary(data, binaryType, callback);
  3056. }
  3057. if (typeof binaryType === 'function') {
  3058. callback = binaryType;
  3059. binaryType = null;
  3060. }
  3061. var packet;
  3062. if (data === '') {
  3063. // parser error - ignoring payload
  3064. return callback(err, 0, 1);
  3065. }
  3066. var length = '', n, msg;
  3067. for (var i = 0, l = data.length; i < l; i++) {
  3068. var chr = data.charAt(i);
  3069. if (chr !== ':') {
  3070. length += chr;
  3071. continue;
  3072. }
  3073. if (length === '' || (length != (n = Number(length)))) {
  3074. // parser error - ignoring payload
  3075. return callback(err, 0, 1);
  3076. }
  3077. msg = data.substr(i + 1, n);
  3078. if (length != msg.length) {
  3079. // parser error - ignoring payload
  3080. return callback(err, 0, 1);
  3081. }
  3082. if (msg.length) {
  3083. packet = exports.decodePacket(msg, binaryType, false);
  3084. if (err.type === packet.type && err.data === packet.data) {
  3085. // parser error in individual packet - ignoring payload
  3086. return callback(err, 0, 1);
  3087. }
  3088. var ret = callback(packet, i + n, l);
  3089. if (false === ret) return;
  3090. }
  3091. // advance cursor
  3092. i += n;
  3093. length = '';
  3094. }
  3095. if (length !== '') {
  3096. // parser error - ignoring payload
  3097. return callback(err, 0, 1);
  3098. }
  3099. };
  3100. /**
  3101. * Encodes multiple messages (payload) as binary.
  3102. *
  3103. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  3104. * 255><data>
  3105. *
  3106. * Example:
  3107. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  3108. *
  3109. * @param {Array} packets
  3110. * @return {ArrayBuffer} encoded payload
  3111. * @api private
  3112. */
  3113. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  3114. if (!packets.length) {
  3115. return callback(new ArrayBuffer(0));
  3116. }
  3117. function encodeOne(packet, doneCallback) {
  3118. exports.encodePacket(packet, true, true, function(data) {
  3119. return doneCallback(null, data);
  3120. });
  3121. }
  3122. map(packets, encodeOne, function(err, encodedPackets) {
  3123. var totalLength = encodedPackets.reduce(function(acc, p) {
  3124. var len;
  3125. if (typeof p === 'string'){
  3126. len = p.length;
  3127. } else {
  3128. len = p.byteLength;
  3129. }
  3130. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  3131. }, 0);
  3132. var resultArray = new Uint8Array(totalLength);
  3133. var bufferIndex = 0;
  3134. encodedPackets.forEach(function(p) {
  3135. var isString = typeof p === 'string';
  3136. var ab = p;
  3137. if (isString) {
  3138. var view = new Uint8Array(p.length);
  3139. for (var i = 0; i < p.length; i++) {
  3140. view[i] = p.charCodeAt(i);
  3141. }
  3142. ab = view.buffer;
  3143. }
  3144. if (isString) { // not true binary
  3145. resultArray[bufferIndex++] = 0;
  3146. } else { // true binary
  3147. resultArray[bufferIndex++] = 1;
  3148. }
  3149. var lenStr = ab.byteLength.toString();
  3150. for (var i = 0; i < lenStr.length; i++) {
  3151. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  3152. }
  3153. resultArray[bufferIndex++] = 255;
  3154. var view = new Uint8Array(ab);
  3155. for (var i = 0; i < view.length; i++) {
  3156. resultArray[bufferIndex++] = view[i];
  3157. }
  3158. });
  3159. return callback(resultArray.buffer);
  3160. });
  3161. };
  3162. /**
  3163. * Encode as Blob
  3164. */
  3165. exports.encodePayloadAsBlob = function(packets, callback) {
  3166. function encodeOne(packet, doneCallback) {
  3167. exports.encodePacket(packet, true, true, function(encoded) {
  3168. var binaryIdentifier = new Uint8Array(1);
  3169. binaryIdentifier[0] = 1;
  3170. if (typeof encoded === 'string') {
  3171. var view = new Uint8Array(encoded.length);
  3172. for (var i = 0; i < encoded.length; i++) {
  3173. view[i] = encoded.charCodeAt(i);
  3174. }
  3175. encoded = view.buffer;
  3176. binaryIdentifier[0] = 0;
  3177. }
  3178. var len = (encoded instanceof ArrayBuffer)
  3179. ? encoded.byteLength
  3180. : encoded.size;
  3181. var lenStr = len.toString();
  3182. var lengthAry = new Uint8Array(lenStr.length + 1);
  3183. for (var i = 0; i < lenStr.length; i++) {
  3184. lengthAry[i] = parseInt(lenStr[i]);
  3185. }
  3186. lengthAry[lenStr.length] = 255;
  3187. if (Blob) {
  3188. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  3189. doneCallback(null, blob);
  3190. }
  3191. });
  3192. }
  3193. map(packets, encodeOne, function(err, results) {
  3194. return callback(new Blob(results));
  3195. });
  3196. };
  3197. /*
  3198. * Decodes data when a payload is maybe expected. Strings are decoded by
  3199. * interpreting each byte as a key code for entries marked to start with 0. See
  3200. * description of encodePayloadAsBinary
  3201. *
  3202. * @param {ArrayBuffer} data, callback method
  3203. * @api public
  3204. */
  3205. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  3206. if (typeof binaryType === 'function') {
  3207. callback = binaryType;
  3208. binaryType = null;
  3209. }
  3210. var bufferTail = data;
  3211. var buffers = [];
  3212. while (bufferTail.byteLength > 0) {
  3213. var tailArray = new Uint8Array(bufferTail);
  3214. var isString = tailArray[0] === 0;
  3215. var msgLength = '';
  3216. for (var i = 1; ; i++) {
  3217. if (tailArray[i] === 255) break;
  3218. // 310 = char length of Number.MAX_VALUE
  3219. if (msgLength.length > 310) {
  3220. return callback(err, 0, 1);
  3221. }
  3222. msgLength += tailArray[i];
  3223. }
  3224. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  3225. msgLength = parseInt(msgLength);
  3226. var msg = sliceBuffer(bufferTail, 0, msgLength);
  3227. if (isString) {
  3228. try {
  3229. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  3230. } catch (e) {
  3231. // iPhone Safari doesn't let you apply to typed arrays
  3232. var typed = new Uint8Array(msg);
  3233. msg = '';
  3234. for (var i = 0; i < typed.length; i++) {
  3235. msg += String.fromCharCode(typed[i]);
  3236. }
  3237. }
  3238. }
  3239. buffers.push(msg);
  3240. bufferTail = sliceBuffer(bufferTail, msgLength);
  3241. }
  3242. var total = buffers.length;
  3243. buffers.forEach(function(buffer, i) {
  3244. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  3245. });
  3246. };
  3247. /***/ }),
  3248. /* 19 */
  3249. /***/ (function(module, exports) {
  3250. /**
  3251. * Gets the keys for an object.
  3252. *
  3253. * @return {Array} keys
  3254. * @api private
  3255. */
  3256. module.exports = Object.keys || function keys (obj){
  3257. var arr = [];
  3258. var has = Object.prototype.hasOwnProperty;
  3259. for (var i in obj) {
  3260. if (has.call(obj, i)) {
  3261. arr.push(i);
  3262. }
  3263. }
  3264. return arr;
  3265. };
  3266. /***/ }),
  3267. /* 20 */
  3268. /***/ (function(module, exports, __webpack_require__) {
  3269. /* global Blob File */
  3270. /*
  3271. * Module requirements.
  3272. */
  3273. var isArray = __webpack_require__(7);
  3274. var toString = Object.prototype.toString;
  3275. var withNativeBlob = typeof Blob === 'function' ||
  3276. typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]';
  3277. var withNativeFile = typeof File === 'function' ||
  3278. typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]';
  3279. /**
  3280. * Module exports.
  3281. */
  3282. module.exports = hasBinary;
  3283. /**
  3284. * Checks for binary data.
  3285. *
  3286. * Supports Buffer, ArrayBuffer, Blob and File.
  3287. *
  3288. * @param {Object} anything
  3289. * @api public
  3290. */
  3291. function hasBinary (obj) {
  3292. if (!obj || typeof obj !== 'object') {
  3293. return false;
  3294. }
  3295. if (isArray(obj)) {
  3296. for (var i = 0, l = obj.length; i < l; i++) {
  3297. if (hasBinary(obj[i])) {
  3298. return true;
  3299. }
  3300. }
  3301. return false;
  3302. }
  3303. if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
  3304. (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) ||
  3305. (withNativeBlob && obj instanceof Blob) ||
  3306. (withNativeFile && obj instanceof File)
  3307. ) {
  3308. return true;
  3309. }
  3310. // see: https://github.com/Automattic/has-binary/pull/4
  3311. if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) {
  3312. return hasBinary(obj.toJSON(), true);
  3313. }
  3314. for (var key in obj) {
  3315. if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
  3316. return true;
  3317. }
  3318. }
  3319. return false;
  3320. }
  3321. /***/ }),
  3322. /* 21 */
  3323. /***/ (function(module, exports) {
  3324. /**
  3325. * An abstraction for slicing an arraybuffer even when
  3326. * ArrayBuffer.prototype.slice is not supported
  3327. *
  3328. * @api public
  3329. */
  3330. module.exports = function(arraybuffer, start, end) {
  3331. var bytes = arraybuffer.byteLength;
  3332. start = start || 0;
  3333. end = end || bytes;
  3334. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  3335. if (start < 0) { start += bytes; }
  3336. if (end < 0) { end += bytes; }
  3337. if (end > bytes) { end = bytes; }
  3338. if (start >= bytes || start >= end || bytes === 0) {
  3339. return new ArrayBuffer(0);
  3340. }
  3341. var abv = new Uint8Array(arraybuffer);
  3342. var result = new Uint8Array(end - start);
  3343. for (var i = start, ii = 0; i < end; i++, ii++) {
  3344. result[ii] = abv[i];
  3345. }
  3346. return result.buffer;
  3347. };
  3348. /***/ }),
  3349. /* 22 */
  3350. /***/ (function(module, exports) {
  3351. module.exports = after
  3352. function after(count, callback, err_cb) {
  3353. var bail = false
  3354. err_cb = err_cb || noop
  3355. proxy.count = count
  3356. return (count === 0) ? callback() : proxy
  3357. function proxy(err, result) {
  3358. if (proxy.count <= 0) {
  3359. throw new Error('after called too many times')
  3360. }
  3361. --proxy.count
  3362. // after first error, rest are passed to err_cb
  3363. if (err) {
  3364. bail = true
  3365. callback(err)
  3366. // future error callbacks will go to error handler
  3367. callback = err_cb
  3368. } else if (proxy.count === 0 && !bail) {
  3369. callback(null, result)
  3370. }
  3371. }
  3372. }
  3373. function noop() {}
  3374. /***/ }),
  3375. /* 23 */
  3376. /***/ (function(module, exports) {
  3377. /*! https://mths.be/utf8js v2.1.2 by @mathias */
  3378. var stringFromCharCode = String.fromCharCode;
  3379. // Taken from https://mths.be/punycode
  3380. function ucs2decode(string) {
  3381. var output = [];
  3382. var counter = 0;
  3383. var length = string.length;
  3384. var value;
  3385. var extra;
  3386. while (counter < length) {
  3387. value = string.charCodeAt(counter++);
  3388. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  3389. // high surrogate, and there is a next character
  3390. extra = string.charCodeAt(counter++);
  3391. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  3392. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  3393. } else {
  3394. // unmatched surrogate; only append this code unit, in case the next
  3395. // code unit is the high surrogate of a surrogate pair
  3396. output.push(value);
  3397. counter--;
  3398. }
  3399. } else {
  3400. output.push(value);
  3401. }
  3402. }
  3403. return output;
  3404. }
  3405. // Taken from https://mths.be/punycode
  3406. function ucs2encode(array) {
  3407. var length = array.length;
  3408. var index = -1;
  3409. var value;
  3410. var output = '';
  3411. while (++index < length) {
  3412. value = array[index];
  3413. if (value > 0xFFFF) {
  3414. value -= 0x10000;
  3415. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  3416. value = 0xDC00 | value & 0x3FF;
  3417. }
  3418. output += stringFromCharCode(value);
  3419. }
  3420. return output;
  3421. }
  3422. function checkScalarValue(codePoint, strict) {
  3423. if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
  3424. if (strict) {
  3425. throw Error(
  3426. 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
  3427. ' is not a scalar value'
  3428. );
  3429. }
  3430. return false;
  3431. }
  3432. return true;
  3433. }
  3434. /*--------------------------------------------------------------------------*/
  3435. function createByte(codePoint, shift) {
  3436. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  3437. }
  3438. function encodeCodePoint(codePoint, strict) {
  3439. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  3440. return stringFromCharCode(codePoint);
  3441. }
  3442. var symbol = '';
  3443. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  3444. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  3445. }
  3446. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  3447. if (!checkScalarValue(codePoint, strict)) {
  3448. codePoint = 0xFFFD;
  3449. }
  3450. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  3451. symbol += createByte(codePoint, 6);
  3452. }
  3453. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  3454. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  3455. symbol += createByte(codePoint, 12);
  3456. symbol += createByte(codePoint, 6);
  3457. }
  3458. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  3459. return symbol;
  3460. }
  3461. function utf8encode(string, opts) {
  3462. opts = opts || {};
  3463. var strict = false !== opts.strict;
  3464. var codePoints = ucs2decode(string);
  3465. var length = codePoints.length;
  3466. var index = -1;
  3467. var codePoint;
  3468. var byteString = '';
  3469. while (++index < length) {
  3470. codePoint = codePoints[index];
  3471. byteString += encodeCodePoint(codePoint, strict);
  3472. }
  3473. return byteString;
  3474. }
  3475. /*--------------------------------------------------------------------------*/
  3476. function readContinuationByte() {
  3477. if (byteIndex >= byteCount) {
  3478. throw Error('Invalid byte index');
  3479. }
  3480. var continuationByte = byteArray[byteIndex] & 0xFF;
  3481. byteIndex++;
  3482. if ((continuationByte & 0xC0) == 0x80) {
  3483. return continuationByte & 0x3F;
  3484. }
  3485. // If we end up here, it’s not a continuation byte
  3486. throw Error('Invalid continuation byte');
  3487. }
  3488. function decodeSymbol(strict) {
  3489. var byte1;
  3490. var byte2;
  3491. var byte3;
  3492. var byte4;
  3493. var codePoint;
  3494. if (byteIndex > byteCount) {
  3495. throw Error('Invalid byte index');
  3496. }
  3497. if (byteIndex == byteCount) {
  3498. return false;
  3499. }
  3500. // Read first byte
  3501. byte1 = byteArray[byteIndex] & 0xFF;
  3502. byteIndex++;
  3503. // 1-byte sequence (no continuation bytes)
  3504. if ((byte1 & 0x80) == 0) {
  3505. return byte1;
  3506. }
  3507. // 2-byte sequence
  3508. if ((byte1 & 0xE0) == 0xC0) {
  3509. byte2 = readContinuationByte();
  3510. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  3511. if (codePoint >= 0x80) {
  3512. return codePoint;
  3513. } else {
  3514. throw Error('Invalid continuation byte');
  3515. }
  3516. }
  3517. // 3-byte sequence (may include unpaired surrogates)
  3518. if ((byte1 & 0xF0) == 0xE0) {
  3519. byte2 = readContinuationByte();
  3520. byte3 = readContinuationByte();
  3521. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  3522. if (codePoint >= 0x0800) {
  3523. return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD;
  3524. } else {
  3525. throw Error('Invalid continuation byte');
  3526. }
  3527. }
  3528. // 4-byte sequence
  3529. if ((byte1 & 0xF8) == 0xF0) {
  3530. byte2 = readContinuationByte();
  3531. byte3 = readContinuationByte();
  3532. byte4 = readContinuationByte();
  3533. codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
  3534. (byte3 << 0x06) | byte4;
  3535. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  3536. return codePoint;
  3537. }
  3538. }
  3539. throw Error('Invalid UTF-8 detected');
  3540. }
  3541. var byteArray;
  3542. var byteCount;
  3543. var byteIndex;
  3544. function utf8decode(byteString, opts) {
  3545. opts = opts || {};
  3546. var strict = false !== opts.strict;
  3547. byteArray = ucs2decode(byteString);
  3548. byteCount = byteArray.length;
  3549. byteIndex = 0;
  3550. var codePoints = [];
  3551. var tmp;
  3552. while ((tmp = decodeSymbol(strict)) !== false) {
  3553. codePoints.push(tmp);
  3554. }
  3555. return ucs2encode(codePoints);
  3556. }
  3557. module.exports = {
  3558. version: '2.1.2',
  3559. encode: utf8encode,
  3560. decode: utf8decode
  3561. };
  3562. /***/ }),
  3563. /* 24 */
  3564. /***/ (function(module, exports) {
  3565. /*
  3566. * base64-arraybuffer
  3567. * https://github.com/niklasvh/base64-arraybuffer
  3568. *
  3569. * Copyright (c) 2012 Niklas von Hertzen
  3570. * Licensed under the MIT license.
  3571. */
  3572. (function(){
  3573. "use strict";
  3574. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3575. // Use a lookup table to find the index.
  3576. var lookup = new Uint8Array(256);
  3577. for (var i = 0; i < chars.length; i++) {
  3578. lookup[chars.charCodeAt(i)] = i;
  3579. }
  3580. exports.encode = function(arraybuffer) {
  3581. var bytes = new Uint8Array(arraybuffer),
  3582. i, len = bytes.length, base64 = "";
  3583. for (i = 0; i < len; i+=3) {
  3584. base64 += chars[bytes[i] >> 2];
  3585. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  3586. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  3587. base64 += chars[bytes[i + 2] & 63];
  3588. }
  3589. if ((len % 3) === 2) {
  3590. base64 = base64.substring(0, base64.length - 1) + "=";
  3591. } else if (len % 3 === 1) {
  3592. base64 = base64.substring(0, base64.length - 2) + "==";
  3593. }
  3594. return base64;
  3595. };
  3596. exports.decode = function(base64) {
  3597. var bufferLength = base64.length * 0.75,
  3598. len = base64.length, i, p = 0,
  3599. encoded1, encoded2, encoded3, encoded4;
  3600. if (base64[base64.length - 1] === "=") {
  3601. bufferLength--;
  3602. if (base64[base64.length - 2] === "=") {
  3603. bufferLength--;
  3604. }
  3605. }
  3606. var arraybuffer = new ArrayBuffer(bufferLength),
  3607. bytes = new Uint8Array(arraybuffer);
  3608. for (i = 0; i < len; i+=4) {
  3609. encoded1 = lookup[base64.charCodeAt(i)];
  3610. encoded2 = lookup[base64.charCodeAt(i+1)];
  3611. encoded3 = lookup[base64.charCodeAt(i+2)];
  3612. encoded4 = lookup[base64.charCodeAt(i+3)];
  3613. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  3614. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  3615. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  3616. }
  3617. return arraybuffer;
  3618. };
  3619. })();
  3620. /***/ }),
  3621. /* 25 */
  3622. /***/ (function(module, exports) {
  3623. /**
  3624. * Create a blob builder even when vendor prefixes exist
  3625. */
  3626. var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
  3627. typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :
  3628. typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
  3629. typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
  3630. false;
  3631. /**
  3632. * Check if Blob constructor is supported
  3633. */
  3634. var blobSupported = (function() {
  3635. try {
  3636. var a = new Blob(['hi']);
  3637. return a.size === 2;
  3638. } catch(e) {
  3639. return false;
  3640. }
  3641. })();
  3642. /**
  3643. * Check if Blob constructor supports ArrayBufferViews
  3644. * Fails in Safari 6, so we need to map to ArrayBuffers there.
  3645. */
  3646. var blobSupportsArrayBufferView = blobSupported && (function() {
  3647. try {
  3648. var b = new Blob([new Uint8Array([1,2])]);
  3649. return b.size === 2;
  3650. } catch(e) {
  3651. return false;
  3652. }
  3653. })();
  3654. /**
  3655. * Check if BlobBuilder is supported
  3656. */
  3657. var blobBuilderSupported = BlobBuilder
  3658. && BlobBuilder.prototype.append
  3659. && BlobBuilder.prototype.getBlob;
  3660. /**
  3661. * Helper function that maps ArrayBufferViews to ArrayBuffers
  3662. * Used by BlobBuilder constructor and old browsers that didn't
  3663. * support it in the Blob constructor.
  3664. */
  3665. function mapArrayBufferViews(ary) {
  3666. return ary.map(function(chunk) {
  3667. if (chunk.buffer instanceof ArrayBuffer) {
  3668. var buf = chunk.buffer;
  3669. // if this is a subarray, make a copy so we only
  3670. // include the subarray region from the underlying buffer
  3671. if (chunk.byteLength !== buf.byteLength) {
  3672. var copy = new Uint8Array(chunk.byteLength);
  3673. copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
  3674. buf = copy.buffer;
  3675. }
  3676. return buf;
  3677. }
  3678. return chunk;
  3679. });
  3680. }
  3681. function BlobBuilderConstructor(ary, options) {
  3682. options = options || {};
  3683. var bb = new BlobBuilder();
  3684. mapArrayBufferViews(ary).forEach(function(part) {
  3685. bb.append(part);
  3686. });
  3687. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  3688. };
  3689. function BlobConstructor(ary, options) {
  3690. return new Blob(mapArrayBufferViews(ary), options || {});
  3691. };
  3692. if (typeof Blob !== 'undefined') {
  3693. BlobBuilderConstructor.prototype = Blob.prototype;
  3694. BlobConstructor.prototype = Blob.prototype;
  3695. }
  3696. module.exports = (function() {
  3697. if (blobSupported) {
  3698. return blobSupportsArrayBufferView ? Blob : BlobConstructor;
  3699. } else if (blobBuilderSupported) {
  3700. return BlobBuilderConstructor;
  3701. } else {
  3702. return undefined;
  3703. }
  3704. })();
  3705. /***/ }),
  3706. /* 26 */
  3707. /***/ (function(module, exports) {
  3708. /**
  3709. * Compiles a querystring
  3710. * Returns string representation of the object
  3711. *
  3712. * @param {Object}
  3713. * @api private
  3714. */
  3715. exports.encode = function (obj) {
  3716. var str = '';
  3717. for (var i in obj) {
  3718. if (obj.hasOwnProperty(i)) {
  3719. if (str.length) str += '&';
  3720. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  3721. }
  3722. }
  3723. return str;
  3724. };
  3725. /**
  3726. * Parses a simple querystring into an object
  3727. *
  3728. * @param {String} qs
  3729. * @api private
  3730. */
  3731. exports.decode = function(qs){
  3732. var qry = {};
  3733. var pairs = qs.split('&');
  3734. for (var i = 0, l = pairs.length; i < l; i++) {
  3735. var pair = pairs[i].split('=');
  3736. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  3737. }
  3738. return qry;
  3739. };
  3740. /***/ }),
  3741. /* 27 */
  3742. /***/ (function(module, exports) {
  3743. module.exports = function(a, b){
  3744. var fn = function(){};
  3745. fn.prototype = b.prototype;
  3746. a.prototype = new fn;
  3747. a.prototype.constructor = a;
  3748. };
  3749. /***/ }),
  3750. /* 28 */
  3751. /***/ (function(module, exports) {
  3752. 'use strict';
  3753. var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
  3754. , length = 64
  3755. , map = {}
  3756. , seed = 0
  3757. , i = 0
  3758. , prev;
  3759. /**
  3760. * Return a string representing the specified number.
  3761. *
  3762. * @param {Number} num The number to convert.
  3763. * @returns {String} The string representation of the number.
  3764. * @api public
  3765. */
  3766. function encode(num) {
  3767. var encoded = '';
  3768. do {
  3769. encoded = alphabet[num % length] + encoded;
  3770. num = Math.floor(num / length);
  3771. } while (num > 0);
  3772. return encoded;
  3773. }
  3774. /**
  3775. * Return the integer value specified by the given string.
  3776. *
  3777. * @param {String} str The string to convert.
  3778. * @returns {Number} The integer value represented by the string.
  3779. * @api public
  3780. */
  3781. function decode(str) {
  3782. var decoded = 0;
  3783. for (i = 0; i < str.length; i++) {
  3784. decoded = decoded * length + map[str.charAt(i)];
  3785. }
  3786. return decoded;
  3787. }
  3788. /**
  3789. * Yeast: A tiny growing id generator.
  3790. *
  3791. * @returns {String} A unique id.
  3792. * @api public
  3793. */
  3794. function yeast() {
  3795. var now = encode(+new Date());
  3796. if (now !== prev) return seed = 0, prev = now;
  3797. return now +'.'+ encode(seed++);
  3798. }
  3799. //
  3800. // Map each character to its index.
  3801. //
  3802. for (; i < length; i++) map[alphabet[i]] = i;
  3803. //
  3804. // Expose the `yeast`, `encode` and `decode` functions.
  3805. //
  3806. yeast.encode = encode;
  3807. yeast.decode = decode;
  3808. module.exports = yeast;
  3809. /***/ }),
  3810. /* 29 */
  3811. /***/ (function(module, exports, __webpack_require__) {
  3812. /* WEBPACK VAR INJECTION */(function(global) {/**
  3813. * Module requirements.
  3814. */
  3815. var Polling = __webpack_require__(16);
  3816. var inherit = __webpack_require__(27);
  3817. /**
  3818. * Module exports.
  3819. */
  3820. module.exports = JSONPPolling;
  3821. /**
  3822. * Cached regular expressions.
  3823. */
  3824. var rNewline = /\n/g;
  3825. var rEscapedNewline = /\\n/g;
  3826. /**
  3827. * Global JSONP callbacks.
  3828. */
  3829. var callbacks;
  3830. /**
  3831. * Noop.
  3832. */
  3833. function empty () { }
  3834. /**
  3835. * Until https://github.com/tc39/proposal-global is shipped.
  3836. */
  3837. function glob () {
  3838. return typeof self !== 'undefined' ? self
  3839. : typeof window !== 'undefined' ? window
  3840. : typeof global !== 'undefined' ? global : {};
  3841. }
  3842. /**
  3843. * JSONP Polling constructor.
  3844. *
  3845. * @param {Object} opts.
  3846. * @api public
  3847. */
  3848. function JSONPPolling (opts) {
  3849. Polling.call(this, opts);
  3850. this.query = this.query || {};
  3851. // define global callbacks array if not present
  3852. // we do this here (lazily) to avoid unneeded global pollution
  3853. if (!callbacks) {
  3854. // we need to consider multiple engines in the same page
  3855. var global = glob();
  3856. callbacks = global.___eio = (global.___eio || []);
  3857. }
  3858. // callback identifier
  3859. this.index = callbacks.length;
  3860. // add callback to jsonp global
  3861. var self = this;
  3862. callbacks.push(function (msg) {
  3863. self.onData(msg);
  3864. });
  3865. // append to query string
  3866. this.query.j = this.index;
  3867. // prevent spurious errors from being emitted when the window is unloaded
  3868. if (typeof addEventListener === 'function') {
  3869. addEventListener('beforeunload', function () {
  3870. if (self.script) self.script.onerror = empty;
  3871. }, false);
  3872. }
  3873. }
  3874. /**
  3875. * Inherits from Polling.
  3876. */
  3877. inherit(JSONPPolling, Polling);
  3878. /*
  3879. * JSONP only supports binary as base64 encoded strings
  3880. */
  3881. JSONPPolling.prototype.supportsBinary = false;
  3882. /**
  3883. * Closes the socket.
  3884. *
  3885. * @api private
  3886. */
  3887. JSONPPolling.prototype.doClose = function () {
  3888. if (this.script) {
  3889. this.script.parentNode.removeChild(this.script);
  3890. this.script = null;
  3891. }
  3892. if (this.form) {
  3893. this.form.parentNode.removeChild(this.form);
  3894. this.form = null;
  3895. this.iframe = null;
  3896. }
  3897. Polling.prototype.doClose.call(this);
  3898. };
  3899. /**
  3900. * Starts a poll cycle.
  3901. *
  3902. * @api private
  3903. */
  3904. JSONPPolling.prototype.doPoll = function () {
  3905. var self = this;
  3906. var script = document.createElement('script');
  3907. if (this.script) {
  3908. this.script.parentNode.removeChild(this.script);
  3909. this.script = null;
  3910. }
  3911. script.async = true;
  3912. script.src = this.uri();
  3913. script.onerror = function (e) {
  3914. self.onError('jsonp poll error', e);
  3915. };
  3916. var insertAt = document.getElementsByTagName('script')[0];
  3917. if (insertAt) {
  3918. insertAt.parentNode.insertBefore(script, insertAt);
  3919. } else {
  3920. (document.head || document.body).appendChild(script);
  3921. }
  3922. this.script = script;
  3923. var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
  3924. if (isUAgecko) {
  3925. setTimeout(function () {
  3926. var iframe = document.createElement('iframe');
  3927. document.body.appendChild(iframe);
  3928. document.body.removeChild(iframe);
  3929. }, 100);
  3930. }
  3931. };
  3932. /**
  3933. * Writes with a hidden iframe.
  3934. *
  3935. * @param {String} data to send
  3936. * @param {Function} called upon flush.
  3937. * @api private
  3938. */
  3939. JSONPPolling.prototype.doWrite = function (data, fn) {
  3940. var self = this;
  3941. if (!this.form) {
  3942. var form = document.createElement('form');
  3943. var area = document.createElement('textarea');
  3944. var id = this.iframeId = 'eio_iframe_' + this.index;
  3945. var iframe;
  3946. form.className = 'socketio';
  3947. form.style.position = 'absolute';
  3948. form.style.top = '-1000px';
  3949. form.style.left = '-1000px';
  3950. form.target = id;
  3951. form.method = 'POST';
  3952. form.setAttribute('accept-charset', 'utf-8');
  3953. area.name = 'd';
  3954. form.appendChild(area);
  3955. document.body.appendChild(form);
  3956. this.form = form;
  3957. this.area = area;
  3958. }
  3959. this.form.action = this.uri();
  3960. function complete () {
  3961. initIframe();
  3962. fn();
  3963. }
  3964. function initIframe () {
  3965. if (self.iframe) {
  3966. try {
  3967. self.form.removeChild(self.iframe);
  3968. } catch (e) {
  3969. self.onError('jsonp polling iframe removal error', e);
  3970. }
  3971. }
  3972. try {
  3973. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  3974. var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
  3975. iframe = document.createElement(html);
  3976. } catch (e) {
  3977. iframe = document.createElement('iframe');
  3978. iframe.name = self.iframeId;
  3979. iframe.src = 'javascript:0';
  3980. }
  3981. iframe.id = self.iframeId;
  3982. self.form.appendChild(iframe);
  3983. self.iframe = iframe;
  3984. }
  3985. initIframe();
  3986. // escape \n to prevent it from being converted into \r\n by some UAs
  3987. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  3988. data = data.replace(rEscapedNewline, '\\\n');
  3989. this.area.value = data.replace(rNewline, '\\n');
  3990. try {
  3991. this.form.submit();
  3992. } catch (e) {}
  3993. if (this.iframe.attachEvent) {
  3994. this.iframe.onreadystatechange = function () {
  3995. if (self.iframe.readyState === 'complete') {
  3996. complete();
  3997. }
  3998. };
  3999. } else {
  4000. this.iframe.onload = complete;
  4001. }
  4002. };
  4003. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  4004. /***/ }),
  4005. /* 30 */
  4006. /***/ (function(module, exports, __webpack_require__) {
  4007. /**
  4008. * Module dependencies.
  4009. */
  4010. var Transport = __webpack_require__(17);
  4011. var parser = __webpack_require__(18);
  4012. var parseqs = __webpack_require__(26);
  4013. var inherit = __webpack_require__(27);
  4014. var yeast = __webpack_require__(28);
  4015. var debug = __webpack_require__(3)('engine.io-client:websocket');
  4016. var BrowserWebSocket, NodeWebSocket;
  4017. if (typeof WebSocket !== 'undefined') {
  4018. BrowserWebSocket = WebSocket;
  4019. } else if (typeof self !== 'undefined') {
  4020. BrowserWebSocket = self.WebSocket || self.MozWebSocket;
  4021. }
  4022. if (typeof window === 'undefined') {
  4023. try {
  4024. NodeWebSocket = __webpack_require__(31);
  4025. } catch (e) { }
  4026. }
  4027. /**
  4028. * Get either the `WebSocket` or `MozWebSocket` globals
  4029. * in the browser or try to resolve WebSocket-compatible
  4030. * interface exposed by `ws` for Node-like environment.
  4031. */
  4032. var WebSocketImpl = BrowserWebSocket || NodeWebSocket;
  4033. /**
  4034. * Module exports.
  4035. */
  4036. module.exports = WS;
  4037. /**
  4038. * WebSocket transport constructor.
  4039. *
  4040. * @api {Object} connection options
  4041. * @api public
  4042. */
  4043. function WS (opts) {
  4044. var forceBase64 = (opts && opts.forceBase64);
  4045. if (forceBase64) {
  4046. this.supportsBinary = false;
  4047. }
  4048. this.perMessageDeflate = opts.perMessageDeflate;
  4049. this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
  4050. this.protocols = opts.protocols;
  4051. if (!this.usingBrowserWebSocket) {
  4052. WebSocketImpl = NodeWebSocket;
  4053. }
  4054. Transport.call(this, opts);
  4055. }
  4056. /**
  4057. * Inherits from Transport.
  4058. */
  4059. inherit(WS, Transport);
  4060. /**
  4061. * Transport name.
  4062. *
  4063. * @api public
  4064. */
  4065. WS.prototype.name = 'websocket';
  4066. /*
  4067. * WebSockets support binary
  4068. */
  4069. WS.prototype.supportsBinary = true;
  4070. /**
  4071. * Opens socket.
  4072. *
  4073. * @api private
  4074. */
  4075. WS.prototype.doOpen = function () {
  4076. if (!this.check()) {
  4077. // let probe timeout
  4078. return;
  4079. }
  4080. var uri = this.uri();
  4081. var protocols = this.protocols;
  4082. var opts = {
  4083. agent: this.agent,
  4084. perMessageDeflate: this.perMessageDeflate
  4085. };
  4086. // SSL options for Node.js client
  4087. opts.pfx = this.pfx;
  4088. opts.key = this.key;
  4089. opts.passphrase = this.passphrase;
  4090. opts.cert = this.cert;
  4091. opts.ca = this.ca;
  4092. opts.ciphers = this.ciphers;
  4093. opts.rejectUnauthorized = this.rejectUnauthorized;
  4094. if (this.extraHeaders) {
  4095. opts.headers = this.extraHeaders;
  4096. }
  4097. if (this.localAddress) {
  4098. opts.localAddress = this.localAddress;
  4099. }
  4100. try {
  4101. this.ws =
  4102. this.usingBrowserWebSocket && !this.isReactNative
  4103. ? protocols
  4104. ? new WebSocketImpl(uri, protocols)
  4105. : new WebSocketImpl(uri)
  4106. : new WebSocketImpl(uri, protocols, opts);
  4107. } catch (err) {
  4108. return this.emit('error', err);
  4109. }
  4110. if (this.ws.binaryType === undefined) {
  4111. this.supportsBinary = false;
  4112. }
  4113. if (this.ws.supports && this.ws.supports.binary) {
  4114. this.supportsBinary = true;
  4115. this.ws.binaryType = 'nodebuffer';
  4116. } else {
  4117. this.ws.binaryType = 'arraybuffer';
  4118. }
  4119. this.addEventListeners();
  4120. };
  4121. /**
  4122. * Adds event listeners to the socket
  4123. *
  4124. * @api private
  4125. */
  4126. WS.prototype.addEventListeners = function () {
  4127. var self = this;
  4128. this.ws.onopen = function () {
  4129. self.onOpen();
  4130. };
  4131. this.ws.onclose = function () {
  4132. self.onClose();
  4133. };
  4134. this.ws.onmessage = function (ev) {
  4135. self.onData(ev.data);
  4136. };
  4137. this.ws.onerror = function (e) {
  4138. self.onError('websocket error', e);
  4139. };
  4140. };
  4141. /**
  4142. * Writes data to socket.
  4143. *
  4144. * @param {Array} array of packets.
  4145. * @api private
  4146. */
  4147. WS.prototype.write = function (packets) {
  4148. var self = this;
  4149. this.writable = false;
  4150. // encodePacket efficient as it uses WS framing
  4151. // no need for encodePayload
  4152. var total = packets.length;
  4153. for (var i = 0, l = total; i < l; i++) {
  4154. (function (packet) {
  4155. parser.encodePacket(packet, self.supportsBinary, function (data) {
  4156. if (!self.usingBrowserWebSocket) {
  4157. // always create a new object (GH-437)
  4158. var opts = {};
  4159. if (packet.options) {
  4160. opts.compress = packet.options.compress;
  4161. }
  4162. if (self.perMessageDeflate) {
  4163. var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
  4164. if (len < self.perMessageDeflate.threshold) {
  4165. opts.compress = false;
  4166. }
  4167. }
  4168. }
  4169. // Sometimes the websocket has already been closed but the browser didn't
  4170. // have a chance of informing us about it yet, in that case send will
  4171. // throw an error
  4172. try {
  4173. if (self.usingBrowserWebSocket) {
  4174. // TypeError is thrown when passing the second argument on Safari
  4175. self.ws.send(data);
  4176. } else {
  4177. self.ws.send(data, opts);
  4178. }
  4179. } catch (e) {
  4180. }
  4181. --total || done();
  4182. });
  4183. })(packets[i]);
  4184. }
  4185. function done () {
  4186. self.emit('flush');
  4187. // fake drain
  4188. // defer to next tick to allow Socket to clear writeBuffer
  4189. setTimeout(function () {
  4190. self.writable = true;
  4191. self.emit('drain');
  4192. }, 0);
  4193. }
  4194. };
  4195. /**
  4196. * Called upon close
  4197. *
  4198. * @api private
  4199. */
  4200. WS.prototype.onClose = function () {
  4201. Transport.prototype.onClose.call(this);
  4202. };
  4203. /**
  4204. * Closes socket.
  4205. *
  4206. * @api private
  4207. */
  4208. WS.prototype.doClose = function () {
  4209. if (typeof this.ws !== 'undefined') {
  4210. this.ws.close();
  4211. }
  4212. };
  4213. /**
  4214. * Generates uri for connection.
  4215. *
  4216. * @api private
  4217. */
  4218. WS.prototype.uri = function () {
  4219. var query = this.query || {};
  4220. var schema = this.secure ? 'wss' : 'ws';
  4221. var port = '';
  4222. // avoid port if default for schema
  4223. if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
  4224. ('ws' === schema && Number(this.port) !== 80))) {
  4225. port = ':' + this.port;
  4226. }
  4227. // append timestamp to URI
  4228. if (this.timestampRequests) {
  4229. query[this.timestampParam] = yeast();
  4230. }
  4231. // communicate binary support capabilities
  4232. if (!this.supportsBinary) {
  4233. query.b64 = 1;
  4234. }
  4235. query = parseqs.encode(query);
  4236. // prepend ? to query
  4237. if (query.length) {
  4238. query = '?' + query;
  4239. }
  4240. var ipv6 = this.hostname.indexOf(':') !== -1;
  4241. return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
  4242. };
  4243. /**
  4244. * Feature detection for WebSocket.
  4245. *
  4246. * @return {Boolean} whether this transport is available.
  4247. * @api public
  4248. */
  4249. WS.prototype.check = function () {
  4250. return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
  4251. };
  4252. /***/ }),
  4253. /* 31 */
  4254. /***/ (function(module, exports) {
  4255. /* (ignored) */
  4256. /***/ }),
  4257. /* 32 */
  4258. /***/ (function(module, exports) {
  4259. var indexOf = [].indexOf;
  4260. module.exports = function(arr, obj){
  4261. if (indexOf) return arr.indexOf(obj);
  4262. for (var i = 0; i < arr.length; ++i) {
  4263. if (arr[i] === obj) return i;
  4264. }
  4265. return -1;
  4266. };
  4267. /***/ }),
  4268. /* 33 */
  4269. /***/ (function(module, exports, __webpack_require__) {
  4270. 'use strict';
  4271. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  4272. /**
  4273. * Module dependencies.
  4274. */
  4275. var parser = __webpack_require__(4);
  4276. var Emitter = __webpack_require__(5);
  4277. var toArray = __webpack_require__(34);
  4278. var on = __webpack_require__(35);
  4279. var bind = __webpack_require__(36);
  4280. var debug = __webpack_require__(3)('socket.io-client:socket');
  4281. var parseqs = __webpack_require__(26);
  4282. var hasBin = __webpack_require__(20);
  4283. /**
  4284. * Module exports.
  4285. */
  4286. module.exports = exports = Socket;
  4287. /**
  4288. * Internal events (blacklisted).
  4289. * These events can't be emitted by the user.
  4290. *
  4291. * @api private
  4292. */
  4293. var events = {
  4294. connect: 1,
  4295. connect_error: 1,
  4296. connect_timeout: 1,
  4297. connecting: 1,
  4298. disconnect: 1,
  4299. error: 1,
  4300. reconnect: 1,
  4301. reconnect_attempt: 1,
  4302. reconnect_failed: 1,
  4303. reconnect_error: 1,
  4304. reconnecting: 1,
  4305. ping: 1,
  4306. pong: 1
  4307. };
  4308. /**
  4309. * Shortcut to `Emitter#emit`.
  4310. */
  4311. var emit = Emitter.prototype.emit;
  4312. /**
  4313. * `Socket` constructor.
  4314. *
  4315. * @api public
  4316. */
  4317. function Socket(io, nsp, opts) {
  4318. this.io = io;
  4319. this.nsp = nsp;
  4320. this.json = this; // compat
  4321. this.ids = 0;
  4322. this.acks = {};
  4323. this.receiveBuffer = [];
  4324. this.sendBuffer = [];
  4325. this.connected = false;
  4326. this.disconnected = true;
  4327. this.flags = {};
  4328. if (opts && opts.query) {
  4329. this.query = opts.query;
  4330. }
  4331. if (this.io.autoConnect) this.open();
  4332. }
  4333. /**
  4334. * Mix in `Emitter`.
  4335. */
  4336. Emitter(Socket.prototype);
  4337. /**
  4338. * Subscribe to open, close and packet events
  4339. *
  4340. * @api private
  4341. */
  4342. Socket.prototype.subEvents = function () {
  4343. if (this.subs) return;
  4344. var io = this.io;
  4345. this.subs = [on(io, 'open', bind(this, 'onopen')), on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose'))];
  4346. };
  4347. /**
  4348. * "Opens" the socket.
  4349. *
  4350. * @api public
  4351. */
  4352. Socket.prototype.open = Socket.prototype.connect = function () {
  4353. if (this.connected) return this;
  4354. this.subEvents();
  4355. this.io.open(); // ensure open
  4356. if ('open' === this.io.readyState) this.onopen();
  4357. this.emit('connecting');
  4358. return this;
  4359. };
  4360. /**
  4361. * Sends a `message` event.
  4362. *
  4363. * @return {Socket} self
  4364. * @api public
  4365. */
  4366. Socket.prototype.send = function () {
  4367. var args = toArray(arguments);
  4368. args.unshift('message');
  4369. this.emit.apply(this, args);
  4370. return this;
  4371. };
  4372. /**
  4373. * Override `emit`.
  4374. * If the event is in `events`, it's emitted normally.
  4375. *
  4376. * @param {String} event name
  4377. * @return {Socket} self
  4378. * @api public
  4379. */
  4380. Socket.prototype.emit = function (ev) {
  4381. if (events.hasOwnProperty(ev)) {
  4382. emit.apply(this, arguments);
  4383. return this;
  4384. }
  4385. var args = toArray(arguments);
  4386. var packet = {
  4387. type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
  4388. data: args
  4389. };
  4390. packet.options = {};
  4391. packet.options.compress = !this.flags || false !== this.flags.compress;
  4392. // event ack callback
  4393. if ('function' === typeof args[args.length - 1]) {
  4394. this.acks[this.ids] = args.pop();
  4395. packet.id = this.ids++;
  4396. }
  4397. if (this.connected) {
  4398. this.packet(packet);
  4399. } else {
  4400. this.sendBuffer.push(packet);
  4401. }
  4402. this.flags = {};
  4403. return this;
  4404. };
  4405. /**
  4406. * Sends a packet.
  4407. *
  4408. * @param {Object} packet
  4409. * @api private
  4410. */
  4411. Socket.prototype.packet = function (packet) {
  4412. packet.nsp = this.nsp;
  4413. this.io.packet(packet);
  4414. };
  4415. /**
  4416. * Called upon engine `open`.
  4417. *
  4418. * @api private
  4419. */
  4420. Socket.prototype.onopen = function () {
  4421. // write connect packet if necessary
  4422. if ('/' !== this.nsp) {
  4423. if (this.query) {
  4424. var query = _typeof(this.query) === 'object' ? parseqs.encode(this.query) : this.query;
  4425. this.packet({ type: parser.CONNECT, query: query });
  4426. } else {
  4427. this.packet({ type: parser.CONNECT });
  4428. }
  4429. }
  4430. };
  4431. /**
  4432. * Called upon engine `close`.
  4433. *
  4434. * @param {String} reason
  4435. * @api private
  4436. */
  4437. Socket.prototype.onclose = function (reason) {
  4438. this.connected = false;
  4439. this.disconnected = true;
  4440. delete this.id;
  4441. this.emit('disconnect', reason);
  4442. };
  4443. /**
  4444. * Called with socket packet.
  4445. *
  4446. * @param {Object} packet
  4447. * @api private
  4448. */
  4449. Socket.prototype.onpacket = function (packet) {
  4450. var sameNamespace = packet.nsp === this.nsp;
  4451. var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';
  4452. if (!sameNamespace && !rootNamespaceError) return;
  4453. switch (packet.type) {
  4454. case parser.CONNECT:
  4455. this.onconnect();
  4456. break;
  4457. case parser.EVENT:
  4458. this.onevent(packet);
  4459. break;
  4460. case parser.BINARY_EVENT:
  4461. this.onevent(packet);
  4462. break;
  4463. case parser.ACK:
  4464. this.onack(packet);
  4465. break;
  4466. case parser.BINARY_ACK:
  4467. this.onack(packet);
  4468. break;
  4469. case parser.DISCONNECT:
  4470. this.ondisconnect();
  4471. break;
  4472. case parser.ERROR:
  4473. this.emit('error', packet.data);
  4474. break;
  4475. }
  4476. };
  4477. /**
  4478. * Called upon a server event.
  4479. *
  4480. * @param {Object} packet
  4481. * @api private
  4482. */
  4483. Socket.prototype.onevent = function (packet) {
  4484. var args = packet.data || [];
  4485. if (null != packet.id) {
  4486. args.push(this.ack(packet.id));
  4487. }
  4488. if (this.connected) {
  4489. emit.apply(this, args);
  4490. } else {
  4491. this.receiveBuffer.push(args);
  4492. }
  4493. };
  4494. /**
  4495. * Produces an ack callback to emit with an event.
  4496. *
  4497. * @api private
  4498. */
  4499. Socket.prototype.ack = function (id) {
  4500. var self = this;
  4501. var sent = false;
  4502. return function () {
  4503. // prevent double callbacks
  4504. if (sent) return;
  4505. sent = true;
  4506. var args = toArray(arguments);
  4507. self.packet({
  4508. type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
  4509. id: id,
  4510. data: args
  4511. });
  4512. };
  4513. };
  4514. /**
  4515. * Called upon a server acknowlegement.
  4516. *
  4517. * @param {Object} packet
  4518. * @api private
  4519. */
  4520. Socket.prototype.onack = function (packet) {
  4521. var ack = this.acks[packet.id];
  4522. if ('function' === typeof ack) {
  4523. ack.apply(this, packet.data);
  4524. delete this.acks[packet.id];
  4525. } else {}
  4526. };
  4527. /**
  4528. * Called upon server connect.
  4529. *
  4530. * @api private
  4531. */
  4532. Socket.prototype.onconnect = function () {
  4533. this.connected = true;
  4534. this.disconnected = false;
  4535. this.emit('connect');
  4536. this.emitBuffered();
  4537. };
  4538. /**
  4539. * Emit buffered events (received and emitted).
  4540. *
  4541. * @api private
  4542. */
  4543. Socket.prototype.emitBuffered = function () {
  4544. var i;
  4545. for (i = 0; i < this.receiveBuffer.length; i++) {
  4546. emit.apply(this, this.receiveBuffer[i]);
  4547. }
  4548. this.receiveBuffer = [];
  4549. for (i = 0; i < this.sendBuffer.length; i++) {
  4550. this.packet(this.sendBuffer[i]);
  4551. }
  4552. this.sendBuffer = [];
  4553. };
  4554. /**
  4555. * Called upon server disconnect.
  4556. *
  4557. * @api private
  4558. */
  4559. Socket.prototype.ondisconnect = function () {
  4560. this.destroy();
  4561. this.onclose('io server disconnect');
  4562. };
  4563. /**
  4564. * Called upon forced client/server side disconnections,
  4565. * this method ensures the manager stops tracking us and
  4566. * that reconnections don't get triggered for this.
  4567. *
  4568. * @api private.
  4569. */
  4570. Socket.prototype.destroy = function () {
  4571. if (this.subs) {
  4572. // clean subscriptions to avoid reconnections
  4573. for (var i = 0; i < this.subs.length; i++) {
  4574. this.subs[i].destroy();
  4575. }
  4576. this.subs = null;
  4577. }
  4578. this.io.destroy(this);
  4579. };
  4580. /**
  4581. * Disconnects the socket manually.
  4582. *
  4583. * @return {Socket} self
  4584. * @api public
  4585. */
  4586. Socket.prototype.close = Socket.prototype.disconnect = function () {
  4587. if (this.connected) {
  4588. this.packet({ type: parser.DISCONNECT });
  4589. }
  4590. // remove socket from pool
  4591. this.destroy();
  4592. if (this.connected) {
  4593. // fire events
  4594. this.onclose('io client disconnect');
  4595. }
  4596. return this;
  4597. };
  4598. /**
  4599. * Sets the compress flag.
  4600. *
  4601. * @param {Boolean} if `true`, compresses the sending data
  4602. * @return {Socket} self
  4603. * @api public
  4604. */
  4605. Socket.prototype.compress = function (compress) {
  4606. this.flags.compress = compress;
  4607. return this;
  4608. };
  4609. /**
  4610. * Sets the binary flag
  4611. *
  4612. * @param {Boolean} whether the emitted data contains binary
  4613. * @return {Socket} self
  4614. * @api public
  4615. */
  4616. Socket.prototype.binary = function (binary) {
  4617. this.flags.binary = binary;
  4618. return this;
  4619. };
  4620. /***/ }),
  4621. /* 34 */
  4622. /***/ (function(module, exports) {
  4623. module.exports = toArray
  4624. function toArray(list, index) {
  4625. var array = []
  4626. index = index || 0
  4627. for (var i = index || 0; i < list.length; i++) {
  4628. array[i - index] = list[i]
  4629. }
  4630. return array
  4631. }
  4632. /***/ }),
  4633. /* 35 */
  4634. /***/ (function(module, exports) {
  4635. "use strict";
  4636. /**
  4637. * Module exports.
  4638. */
  4639. module.exports = on;
  4640. /**
  4641. * Helper for subscriptions.
  4642. *
  4643. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  4644. * @param {String} event name
  4645. * @param {Function} callback
  4646. * @api public
  4647. */
  4648. function on(obj, ev, fn) {
  4649. obj.on(ev, fn);
  4650. return {
  4651. destroy: function destroy() {
  4652. obj.removeListener(ev, fn);
  4653. }
  4654. };
  4655. }
  4656. /***/ }),
  4657. /* 36 */
  4658. /***/ (function(module, exports) {
  4659. /**
  4660. * Slice reference.
  4661. */
  4662. var slice = [].slice;
  4663. /**
  4664. * Bind `obj` to `fn`.
  4665. *
  4666. * @param {Object} obj
  4667. * @param {Function|String} fn or string
  4668. * @return {Function}
  4669. * @api public
  4670. */
  4671. module.exports = function(obj, fn){
  4672. if ('string' == typeof fn) fn = obj[fn];
  4673. if ('function' != typeof fn) throw new Error('bind() requires a function');
  4674. var args = slice.call(arguments, 2);
  4675. return function(){
  4676. return fn.apply(obj, args.concat(slice.call(arguments)));
  4677. }
  4678. };
  4679. /***/ }),
  4680. /* 37 */
  4681. /***/ (function(module, exports) {
  4682. /**
  4683. * Expose `Backoff`.
  4684. */
  4685. module.exports = Backoff;
  4686. /**
  4687. * Initialize backoff timer with `opts`.
  4688. *
  4689. * - `min` initial timeout in milliseconds [100]
  4690. * - `max` max timeout [10000]
  4691. * - `jitter` [0]
  4692. * - `factor` [2]
  4693. *
  4694. * @param {Object} opts
  4695. * @api public
  4696. */
  4697. function Backoff(opts) {
  4698. opts = opts || {};
  4699. this.ms = opts.min || 100;
  4700. this.max = opts.max || 10000;
  4701. this.factor = opts.factor || 2;
  4702. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  4703. this.attempts = 0;
  4704. }
  4705. /**
  4706. * Return the backoff duration.
  4707. *
  4708. * @return {Number}
  4709. * @api public
  4710. */
  4711. Backoff.prototype.duration = function(){
  4712. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  4713. if (this.jitter) {
  4714. var rand = Math.random();
  4715. var deviation = Math.floor(rand * this.jitter * ms);
  4716. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  4717. }
  4718. return Math.min(ms, this.max) | 0;
  4719. };
  4720. /**
  4721. * Reset the number of attempts.
  4722. *
  4723. * @api public
  4724. */
  4725. Backoff.prototype.reset = function(){
  4726. this.attempts = 0;
  4727. };
  4728. /**
  4729. * Set the minimum duration
  4730. *
  4731. * @api public
  4732. */
  4733. Backoff.prototype.setMin = function(min){
  4734. this.ms = min;
  4735. };
  4736. /**
  4737. * Set the maximum duration
  4738. *
  4739. * @api public
  4740. */
  4741. Backoff.prototype.setMax = function(max){
  4742. this.max = max;
  4743. };
  4744. /**
  4745. * Set the jitter
  4746. *
  4747. * @api public
  4748. */
  4749. Backoff.prototype.setJitter = function(jitter){
  4750. this.jitter = jitter;
  4751. };
  4752. /***/ })
  4753. /******/ ])
  4754. });
  4755. ;
  4756. //# sourceMappingURL=socket.io.slim.dev.js.map