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.

6052 lines
132 KiB

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