PageRenderTime 83ms CodeModel.GetById 5ms app.highlight 55ms RepoModel.GetById 1ms app.codeStats 1ms

/node_modules/socket.io/node_modules/socket.io-client/socket.io.js

https://github.com/kirillKey/questSearchTrain
JavaScript | 6252 lines | 3546 code | 966 blank | 1740 comment | 1013 complexity | 44d1b2a6025c12a3af3c0d9586ca0608 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
   2
   3module.exports = _dereq_('./lib/');
   4
   5},{"./lib/":2}],2:[function(_dereq_,module,exports){
   6
   7/**
   8 * Module dependencies.
   9 */
  10
  11var url = _dereq_('./url');
  12var parser = _dereq_('socket.io-parser');
  13var Manager = _dereq_('./manager');
  14var debug = _dereq_('debug')('socket.io-client');
  15
  16/**
  17 * Module exports.
  18 */
  19
  20module.exports = exports = lookup;
  21
  22/**
  23 * Managers cache.
  24 */
  25
  26var cache = exports.managers = {};
  27
  28/**
  29 * Looks up an existing `Manager` for multiplexing.
  30 * If the user summons:
  31 *
  32 *   `io('http://localhost/a');`
  33 *   `io('http://localhost/b');`
  34 *
  35 * We reuse the existing instance based on same scheme/port/host,
  36 * and we initialize sockets for each namespace.
  37 *
  38 * @api public
  39 */
  40
  41function lookup(uri, opts) {
  42  if (typeof uri == 'object') {
  43    opts = uri;
  44    uri = undefined;
  45  }
  46
  47  opts = opts || {};
  48
  49  var parsed = url(uri);
  50  var source = parsed.source;
  51  var id = parsed.id;
  52  var io;
  53
  54  if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  55    debug('ignoring socket cache for %s', source);
  56    io = Manager(source, opts);
  57  } else {
  58    if (!cache[id]) {
  59      debug('new io instance for %s', source);
  60      cache[id] = Manager(source, opts);
  61    }
  62    io = cache[id];
  63  }
  64
  65  return io.socket(parsed.path);
  66}
  67
  68/**
  69 * Protocol version.
  70 *
  71 * @api public
  72 */
  73
  74exports.protocol = parser.protocol;
  75
  76/**
  77 * `connect`.
  78 *
  79 * @param {String} uri
  80 * @api public
  81 */
  82
  83exports.connect = lookup;
  84
  85/**
  86 * Expose constructors for standalone build.
  87 *
  88 * @api public
  89 */
  90
  91exports.Manager = _dereq_('./manager');
  92exports.Socket = _dereq_('./socket');
  93
  94},{"./manager":3,"./socket":5,"./url":6,"debug":9,"socket.io-parser":40}],3:[function(_dereq_,module,exports){
  95
  96/**
  97 * Module dependencies.
  98 */
  99
 100var url = _dereq_('./url');
 101var eio = _dereq_('engine.io-client');
 102var Socket = _dereq_('./socket');
 103var Emitter = _dereq_('component-emitter');
 104var parser = _dereq_('socket.io-parser');
 105var on = _dereq_('./on');
 106var bind = _dereq_('component-bind');
 107var object = _dereq_('object-component');
 108var debug = _dereq_('debug')('socket.io-client:manager');
 109var indexOf = _dereq_('indexof');
 110
 111/**
 112 * Module exports
 113 */
 114
 115module.exports = Manager;
 116
 117/**
 118 * `Manager` constructor.
 119 *
 120 * @param {String} engine instance or engine uri/opts
 121 * @param {Object} options
 122 * @api public
 123 */
 124
 125function Manager(uri, opts){
 126  if (!(this instanceof Manager)) return new Manager(uri, opts);
 127  if (uri && ('object' == typeof uri)) {
 128    opts = uri;
 129    uri = undefined;
 130  }
 131  opts = opts || {};
 132
 133  opts.path = opts.path || '/socket.io';
 134  this.nsps = {};
 135  this.subs = [];
 136  this.opts = opts;
 137  this.reconnection(opts.reconnection !== false);
 138  this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
 139  this.reconnectionDelay(opts.reconnectionDelay || 1000);
 140  this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
 141  this.timeout(null == opts.timeout ? 20000 : opts.timeout);
 142  this.readyState = 'closed';
 143  this.uri = uri;
 144  this.connected = [];
 145  this.attempts = 0;
 146  this.encoding = false;
 147  this.packetBuffer = [];
 148  this.encoder = new parser.Encoder();
 149  this.decoder = new parser.Decoder();
 150  this.autoConnect = opts.autoConnect !== false;
 151  if (this.autoConnect) this.open();
 152}
 153
 154/**
 155 * Propagate given event to sockets and emit on `this`
 156 *
 157 * @api private
 158 */
 159
 160Manager.prototype.emitAll = function() {
 161  this.emit.apply(this, arguments);
 162  for (var nsp in this.nsps) {
 163    this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
 164  }
 165};
 166
 167/**
 168 * Mix in `Emitter`.
 169 */
 170
 171Emitter(Manager.prototype);
 172
 173/**
 174 * Sets the `reconnection` config.
 175 *
 176 * @param {Boolean} true/false if it should automatically reconnect
 177 * @return {Manager} self or value
 178 * @api public
 179 */
 180
 181Manager.prototype.reconnection = function(v){
 182  if (!arguments.length) return this._reconnection;
 183  this._reconnection = !!v;
 184  return this;
 185};
 186
 187/**
 188 * Sets the reconnection attempts config.
 189 *
 190 * @param {Number} max reconnection attempts before giving up
 191 * @return {Manager} self or value
 192 * @api public
 193 */
 194
 195Manager.prototype.reconnectionAttempts = function(v){
 196  if (!arguments.length) return this._reconnectionAttempts;
 197  this._reconnectionAttempts = v;
 198  return this;
 199};
 200
 201/**
 202 * Sets the delay between reconnections.
 203 *
 204 * @param {Number} delay
 205 * @return {Manager} self or value
 206 * @api public
 207 */
 208
 209Manager.prototype.reconnectionDelay = function(v){
 210  if (!arguments.length) return this._reconnectionDelay;
 211  this._reconnectionDelay = v;
 212  return this;
 213};
 214
 215/**
 216 * Sets the maximum delay between reconnections.
 217 *
 218 * @param {Number} delay
 219 * @return {Manager} self or value
 220 * @api public
 221 */
 222
 223Manager.prototype.reconnectionDelayMax = function(v){
 224  if (!arguments.length) return this._reconnectionDelayMax;
 225  this._reconnectionDelayMax = v;
 226  return this;
 227};
 228
 229/**
 230 * Sets the connection timeout. `false` to disable
 231 *
 232 * @return {Manager} self or value
 233 * @api public
 234 */
 235
 236Manager.prototype.timeout = function(v){
 237  if (!arguments.length) return this._timeout;
 238  this._timeout = v;
 239  return this;
 240};
 241
 242/**
 243 * Starts trying to reconnect if reconnection is enabled and we have not
 244 * started reconnecting yet
 245 *
 246 * @api private
 247 */
 248
 249Manager.prototype.maybeReconnectOnOpen = function() {
 250  // Only try to reconnect if it's the first time we're connecting
 251  if (!this.openReconnect && !this.reconnecting && this._reconnection && this.attempts === 0) {
 252    // keeps reconnection from firing twice for the same reconnection loop
 253    this.openReconnect = true;
 254    this.reconnect();
 255  }
 256};
 257
 258
 259/**
 260 * Sets the current transport `socket`.
 261 *
 262 * @param {Function} optional, callback
 263 * @return {Manager} self
 264 * @api public
 265 */
 266
 267Manager.prototype.open =
 268Manager.prototype.connect = function(fn){
 269  debug('readyState %s', this.readyState);
 270  if (~this.readyState.indexOf('open')) return this;
 271
 272  debug('opening %s', this.uri);
 273  this.engine = eio(this.uri, this.opts);
 274  var socket = this.engine;
 275  var self = this;
 276  this.readyState = 'opening';
 277  this.skipReconnect = false;
 278
 279  // emit `open`
 280  var openSub = on(socket, 'open', function() {
 281    self.onopen();
 282    fn && fn();
 283  });
 284
 285  // emit `connect_error`
 286  var errorSub = on(socket, 'error', function(data){
 287    debug('connect_error');
 288    self.cleanup();
 289    self.readyState = 'closed';
 290    self.emitAll('connect_error', data);
 291    if (fn) {
 292      var err = new Error('Connection error');
 293      err.data = data;
 294      fn(err);
 295    }
 296
 297    self.maybeReconnectOnOpen();
 298  });
 299
 300  // emit `connect_timeout`
 301  if (false !== this._timeout) {
 302    var timeout = this._timeout;
 303    debug('connect attempt will timeout after %d', timeout);
 304
 305    // set timer
 306    var timer = setTimeout(function(){
 307      debug('connect attempt timed out after %d', timeout);
 308      openSub.destroy();
 309      socket.close();
 310      socket.emit('error', 'timeout');
 311      self.emitAll('connect_timeout', timeout);
 312    }, timeout);
 313
 314    this.subs.push({
 315      destroy: function(){
 316        clearTimeout(timer);
 317      }
 318    });
 319  }
 320
 321  this.subs.push(openSub);
 322  this.subs.push(errorSub);
 323
 324  return this;
 325};
 326
 327/**
 328 * Called upon transport open.
 329 *
 330 * @api private
 331 */
 332
 333Manager.prototype.onopen = function(){
 334  debug('open');
 335
 336  // clear old subs
 337  this.cleanup();
 338
 339  // mark as open
 340  this.readyState = 'open';
 341  this.emit('open');
 342
 343  // add new subs
 344  var socket = this.engine;
 345  this.subs.push(on(socket, 'data', bind(this, 'ondata')));
 346  this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
 347  this.subs.push(on(socket, 'error', bind(this, 'onerror')));
 348  this.subs.push(on(socket, 'close', bind(this, 'onclose')));
 349};
 350
 351/**
 352 * Called with data.
 353 *
 354 * @api private
 355 */
 356
 357Manager.prototype.ondata = function(data){
 358  this.decoder.add(data);
 359};
 360
 361/**
 362 * Called when parser fully decodes a packet.
 363 *
 364 * @api private
 365 */
 366
 367Manager.prototype.ondecoded = function(packet) {
 368  this.emit('packet', packet);
 369};
 370
 371/**
 372 * Called upon socket error.
 373 *
 374 * @api private
 375 */
 376
 377Manager.prototype.onerror = function(err){
 378  debug('error', err);
 379  this.emitAll('error', err);
 380};
 381
 382/**
 383 * Creates a new socket for the given `nsp`.
 384 *
 385 * @return {Socket}
 386 * @api public
 387 */
 388
 389Manager.prototype.socket = function(nsp){
 390  var socket = this.nsps[nsp];
 391  if (!socket) {
 392    socket = new Socket(this, nsp);
 393    this.nsps[nsp] = socket;
 394    var self = this;
 395    socket.on('connect', function(){
 396      if (!~indexOf(self.connected, socket)) {
 397        self.connected.push(socket);
 398      }
 399    });
 400  }
 401  return socket;
 402};
 403
 404/**
 405 * Called upon a socket close.
 406 *
 407 * @param {Socket} socket
 408 */
 409
 410Manager.prototype.destroy = function(socket){
 411  var index = indexOf(this.connected, socket);
 412  if (~index) this.connected.splice(index, 1);
 413  if (this.connected.length) return;
 414
 415  this.close();
 416};
 417
 418/**
 419 * Writes a packet.
 420 *
 421 * @param {Object} packet
 422 * @api private
 423 */
 424
 425Manager.prototype.packet = function(packet){
 426  debug('writing packet %j', packet);
 427  var self = this;
 428
 429  if (!self.encoding) {
 430    // encode, then write to engine with result
 431    self.encoding = true;
 432    this.encoder.encode(packet, function(encodedPackets) {
 433      for (var i = 0; i < encodedPackets.length; i++) {
 434        self.engine.write(encodedPackets[i]);
 435      }
 436      self.encoding = false;
 437      self.processPacketQueue();
 438    });
 439  } else { // add packet to the queue
 440    self.packetBuffer.push(packet);
 441  }
 442};
 443
 444/**
 445 * If packet buffer is non-empty, begins encoding the
 446 * next packet in line.
 447 *
 448 * @api private
 449 */
 450
 451Manager.prototype.processPacketQueue = function() {
 452  if (this.packetBuffer.length > 0 && !this.encoding) {
 453    var pack = this.packetBuffer.shift();
 454    this.packet(pack);
 455  }
 456};
 457
 458/**
 459 * Clean up transport subscriptions and packet buffer.
 460 *
 461 * @api private
 462 */
 463
 464Manager.prototype.cleanup = function(){
 465  var sub;
 466  while (sub = this.subs.shift()) sub.destroy();
 467
 468  this.packetBuffer = [];
 469  this.encoding = false;
 470
 471  this.decoder.destroy();
 472};
 473
 474/**
 475 * Close the current socket.
 476 *
 477 * @api private
 478 */
 479
 480Manager.prototype.close =
 481Manager.prototype.disconnect = function(){
 482  this.skipReconnect = true;
 483  this.readyState = 'closed';
 484  this.engine && this.engine.close();
 485};
 486
 487/**
 488 * Called upon engine close.
 489 *
 490 * @api private
 491 */
 492
 493Manager.prototype.onclose = function(reason){
 494  debug('close');
 495  this.cleanup();
 496  this.readyState = 'closed';
 497  this.emit('close', reason);
 498  if (this._reconnection && !this.skipReconnect) {
 499    this.reconnect();
 500  }
 501};
 502
 503/**
 504 * Attempt a reconnection.
 505 *
 506 * @api private
 507 */
 508
 509Manager.prototype.reconnect = function(){
 510  if (this.reconnecting || this.skipReconnect) return this;
 511
 512  var self = this;
 513  this.attempts++;
 514
 515  if (this.attempts > this._reconnectionAttempts) {
 516    debug('reconnect failed');
 517    this.emitAll('reconnect_failed');
 518    this.reconnecting = false;
 519  } else {
 520    var delay = this.attempts * this.reconnectionDelay();
 521    delay = Math.min(delay, this.reconnectionDelayMax());
 522    debug('will wait %dms before reconnect attempt', delay);
 523
 524    this.reconnecting = true;
 525    var timer = setTimeout(function(){
 526      if (self.skipReconnect) return;
 527
 528      debug('attempting reconnect');
 529      self.emitAll('reconnect_attempt', self.attempts);
 530      self.emitAll('reconnecting', self.attempts);
 531
 532      // check again for the case socket closed in above events
 533      if (self.skipReconnect) return;
 534
 535      self.open(function(err){
 536        if (err) {
 537          debug('reconnect attempt error');
 538          self.reconnecting = false;
 539          self.reconnect();
 540          self.emitAll('reconnect_error', err.data);
 541        } else {
 542          debug('reconnect success');
 543          self.onreconnect();
 544        }
 545      });
 546    }, delay);
 547
 548    this.subs.push({
 549      destroy: function(){
 550        clearTimeout(timer);
 551      }
 552    });
 553  }
 554};
 555
 556/**
 557 * Called upon successful reconnect.
 558 *
 559 * @api private
 560 */
 561
 562Manager.prototype.onreconnect = function(){
 563  var attempt = this.attempts;
 564  this.attempts = 0;
 565  this.reconnecting = false;
 566  this.emitAll('reconnect', attempt);
 567};
 568
 569},{"./on":4,"./socket":5,"./url":6,"component-bind":7,"component-emitter":8,"debug":9,"engine.io-client":10,"indexof":36,"object-component":37,"socket.io-parser":40}],4:[function(_dereq_,module,exports){
 570
 571/**
 572 * Module exports.
 573 */
 574
 575module.exports = on;
 576
 577/**
 578 * Helper for subscriptions.
 579 *
 580 * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
 581 * @param {String} event name
 582 * @param {Function} callback
 583 * @api public
 584 */
 585
 586function on(obj, ev, fn) {
 587  obj.on(ev, fn);
 588  return {
 589    destroy: function(){
 590      obj.removeListener(ev, fn);
 591    }
 592  };
 593}
 594
 595},{}],5:[function(_dereq_,module,exports){
 596
 597/**
 598 * Module dependencies.
 599 */
 600
 601var parser = _dereq_('socket.io-parser');
 602var Emitter = _dereq_('component-emitter');
 603var toArray = _dereq_('to-array');
 604var on = _dereq_('./on');
 605var bind = _dereq_('component-bind');
 606var debug = _dereq_('debug')('socket.io-client:socket');
 607var hasBin = _dereq_('has-binary');
 608
 609/**
 610 * Module exports.
 611 */
 612
 613module.exports = exports = Socket;
 614
 615/**
 616 * Internal events (blacklisted).
 617 * These events can't be emitted by the user.
 618 *
 619 * @api private
 620 */
 621
 622var events = {
 623  connect: 1,
 624  connect_error: 1,
 625  connect_timeout: 1,
 626  disconnect: 1,
 627  error: 1,
 628  reconnect: 1,
 629  reconnect_attempt: 1,
 630  reconnect_failed: 1,
 631  reconnect_error: 1,
 632  reconnecting: 1
 633};
 634
 635/**
 636 * Shortcut to `Emitter#emit`.
 637 */
 638
 639var emit = Emitter.prototype.emit;
 640
 641/**
 642 * `Socket` constructor.
 643 *
 644 * @api public
 645 */
 646
 647function Socket(io, nsp){
 648  this.io = io;
 649  this.nsp = nsp;
 650  this.json = this; // compat
 651  this.ids = 0;
 652  this.acks = {};
 653  if (this.io.autoConnect) this.open();
 654  this.receiveBuffer = [];
 655  this.sendBuffer = [];
 656  this.connected = false;
 657  this.disconnected = true;
 658}
 659
 660/**
 661 * Mix in `Emitter`.
 662 */
 663
 664Emitter(Socket.prototype);
 665
 666/**
 667 * Subscribe to open, close and packet events
 668 *
 669 * @api private
 670 */
 671
 672Socket.prototype.subEvents = function() {
 673  if (this.subs) return;
 674
 675  var io = this.io;
 676  this.subs = [
 677    on(io, 'open', bind(this, 'onopen')),
 678    on(io, 'packet', bind(this, 'onpacket')),
 679    on(io, 'close', bind(this, 'onclose'))
 680  ];
 681};
 682
 683/**
 684 * "Opens" the socket.
 685 *
 686 * @api public
 687 */
 688
 689Socket.prototype.open =
 690Socket.prototype.connect = function(){
 691  if (this.connected) return this;
 692
 693  this.subEvents();
 694  this.io.open(); // ensure open
 695  if ('open' == this.io.readyState) this.onopen();
 696  return this;
 697};
 698
 699/**
 700 * Sends a `message` event.
 701 *
 702 * @return {Socket} self
 703 * @api public
 704 */
 705
 706Socket.prototype.send = function(){
 707  var args = toArray(arguments);
 708  args.unshift('message');
 709  this.emit.apply(this, args);
 710  return this;
 711};
 712
 713/**
 714 * Override `emit`.
 715 * If the event is in `events`, it's emitted normally.
 716 *
 717 * @param {String} event name
 718 * @return {Socket} self
 719 * @api public
 720 */
 721
 722Socket.prototype.emit = function(ev){
 723  if (events.hasOwnProperty(ev)) {
 724    emit.apply(this, arguments);
 725    return this;
 726  }
 727
 728  var args = toArray(arguments);
 729  var parserType = parser.EVENT; // default
 730  if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
 731  var packet = { type: parserType, data: args };
 732
 733  // event ack callback
 734  if ('function' == typeof args[args.length - 1]) {
 735    debug('emitting packet with ack id %d', this.ids);
 736    this.acks[this.ids] = args.pop();
 737    packet.id = this.ids++;
 738  }
 739
 740  if (this.connected) {
 741    this.packet(packet);
 742  } else {
 743    this.sendBuffer.push(packet);
 744  }
 745
 746  return this;
 747};
 748
 749/**
 750 * Sends a packet.
 751 *
 752 * @param {Object} packet
 753 * @api private
 754 */
 755
 756Socket.prototype.packet = function(packet){
 757  packet.nsp = this.nsp;
 758  this.io.packet(packet);
 759};
 760
 761/**
 762 * Called upon engine `open`.
 763 *
 764 * @api private
 765 */
 766
 767Socket.prototype.onopen = function(){
 768  debug('transport is open - connecting');
 769
 770  // write connect packet if necessary
 771  if ('/' != this.nsp) {
 772    this.packet({ type: parser.CONNECT });
 773  }
 774};
 775
 776/**
 777 * Called upon engine `close`.
 778 *
 779 * @param {String} reason
 780 * @api private
 781 */
 782
 783Socket.prototype.onclose = function(reason){
 784  debug('close (%s)', reason);
 785  this.connected = false;
 786  this.disconnected = true;
 787  this.emit('disconnect', reason);
 788};
 789
 790/**
 791 * Called with socket packet.
 792 *
 793 * @param {Object} packet
 794 * @api private
 795 */
 796
 797Socket.prototype.onpacket = function(packet){
 798  if (packet.nsp != this.nsp) return;
 799
 800  switch (packet.type) {
 801    case parser.CONNECT:
 802      this.onconnect();
 803      break;
 804
 805    case parser.EVENT:
 806      this.onevent(packet);
 807      break;
 808
 809    case parser.BINARY_EVENT:
 810      this.onevent(packet);
 811      break;
 812
 813    case parser.ACK:
 814      this.onack(packet);
 815      break;
 816
 817    case parser.BINARY_ACK:
 818      this.onack(packet);
 819      break;
 820
 821    case parser.DISCONNECT:
 822      this.ondisconnect();
 823      break;
 824
 825    case parser.ERROR:
 826      this.emit('error', packet.data);
 827      break;
 828  }
 829};
 830
 831/**
 832 * Called upon a server event.
 833 *
 834 * @param {Object} packet
 835 * @api private
 836 */
 837
 838Socket.prototype.onevent = function(packet){
 839  var args = packet.data || [];
 840  debug('emitting event %j', args);
 841
 842  if (null != packet.id) {
 843    debug('attaching ack callback to event');
 844    args.push(this.ack(packet.id));
 845  }
 846
 847  if (this.connected) {
 848    emit.apply(this, args);
 849  } else {
 850    this.receiveBuffer.push(args);
 851  }
 852};
 853
 854/**
 855 * Produces an ack callback to emit with an event.
 856 *
 857 * @api private
 858 */
 859
 860Socket.prototype.ack = function(id){
 861  var self = this;
 862  var sent = false;
 863  return function(){
 864    // prevent double callbacks
 865    if (sent) return;
 866    sent = true;
 867    var args = toArray(arguments);
 868    debug('sending ack %j', args);
 869
 870    var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
 871    self.packet({
 872      type: type,
 873      id: id,
 874      data: args
 875    });
 876  };
 877};
 878
 879/**
 880 * Called upon a server acknowlegement.
 881 *
 882 * @param {Object} packet
 883 * @api private
 884 */
 885
 886Socket.prototype.onack = function(packet){
 887  debug('calling ack %s with %j', packet.id, packet.data);
 888  var fn = this.acks[packet.id];
 889  fn.apply(this, packet.data);
 890  delete this.acks[packet.id];
 891};
 892
 893/**
 894 * Called upon server connect.
 895 *
 896 * @api private
 897 */
 898
 899Socket.prototype.onconnect = function(){
 900  this.connected = true;
 901  this.disconnected = false;
 902  this.emit('connect');
 903  this.emitBuffered();
 904};
 905
 906/**
 907 * Emit buffered events (received and emitted).
 908 *
 909 * @api private
 910 */
 911
 912Socket.prototype.emitBuffered = function(){
 913  var i;
 914  for (i = 0; i < this.receiveBuffer.length; i++) {
 915    emit.apply(this, this.receiveBuffer[i]);
 916  }
 917  this.receiveBuffer = [];
 918
 919  for (i = 0; i < this.sendBuffer.length; i++) {
 920    this.packet(this.sendBuffer[i]);
 921  }
 922  this.sendBuffer = [];
 923};
 924
 925/**
 926 * Called upon server disconnect.
 927 *
 928 * @api private
 929 */
 930
 931Socket.prototype.ondisconnect = function(){
 932  debug('server disconnect (%s)', this.nsp);
 933  this.destroy();
 934  this.onclose('io server disconnect');
 935};
 936
 937/**
 938 * Called upon forced client/server side disconnections,
 939 * this method ensures the manager stops tracking us and
 940 * that reconnections don't get triggered for this.
 941 *
 942 * @api private.
 943 */
 944
 945Socket.prototype.destroy = function(){
 946  if (this.subs) {
 947    // clean subscriptions to avoid reconnections
 948    for (var i = 0; i < this.subs.length; i++) {
 949      this.subs[i].destroy();
 950    }
 951    this.subs = null;
 952  }
 953
 954  this.io.destroy(this);
 955};
 956
 957/**
 958 * Disconnects the socket manually.
 959 *
 960 * @return {Socket} self
 961 * @api public
 962 */
 963
 964Socket.prototype.close =
 965Socket.prototype.disconnect = function(){
 966  if (this.connected) {
 967    debug('performing disconnect (%s)', this.nsp);
 968    this.packet({ type: parser.DISCONNECT });
 969  }
 970
 971  // remove socket from pool
 972  this.destroy();
 973
 974  if (this.connected) {
 975    // fire events
 976    this.onclose('io client disconnect');
 977  }
 978  return this;
 979};
 980
 981},{"./on":4,"component-bind":7,"component-emitter":8,"debug":9,"has-binary":32,"socket.io-parser":40,"to-array":44}],6:[function(_dereq_,module,exports){
 982(function (global){
 983
 984/**
 985 * Module dependencies.
 986 */
 987
 988var parseuri = _dereq_('parseuri');
 989var debug = _dereq_('debug')('socket.io-client:url');
 990
 991/**
 992 * Module exports.
 993 */
 994
 995module.exports = url;
 996
 997/**
 998 * URL parser.
 999 *
1000 * @param {String} url
1001 * @param {Object} An object meant to mimic window.location.
1002 *                 Defaults to window.location.
1003 * @api public
1004 */
1005
1006function url(uri, loc){
1007  var obj = uri;
1008
1009  // default to window.location
1010  var loc = loc || global.location;
1011  if (null == uri) uri = loc.protocol + '//' + loc.hostname;
1012
1013  // relative path support
1014  if ('string' == typeof uri) {
1015    if ('/' == uri.charAt(0)) {
1016      if ('/' == uri.charAt(1)) {
1017        uri = loc.protocol + uri;
1018      } else {
1019        uri = loc.hostname + uri;
1020      }
1021    }
1022
1023    if (!/^(https?|wss?):\/\//.test(uri)) {
1024      debug('protocol-less url %s', uri);
1025      if ('undefined' != typeof loc) {
1026        uri = loc.protocol + '//' + uri;
1027      } else {
1028        uri = 'https://' + uri;
1029      }
1030    }
1031
1032    // parse
1033    debug('parse %s', uri);
1034    obj = parseuri(uri);
1035  }
1036
1037  // make sure we treat `localhost:80` and `localhost` equally
1038  if (!obj.port) {
1039    if (/^(http|ws)$/.test(obj.protocol)) {
1040      obj.port = '80';
1041    }
1042    else if (/^(http|ws)s$/.test(obj.protocol)) {
1043      obj.port = '443';
1044    }
1045  }
1046
1047  obj.path = obj.path || '/';
1048
1049  // define unique id
1050  obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
1051  // define href
1052  obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
1053
1054  return obj;
1055}
1056
1057}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1058},{"debug":9,"parseuri":38}],7:[function(_dereq_,module,exports){
1059/**
1060 * Slice reference.
1061 */
1062
1063var slice = [].slice;
1064
1065/**
1066 * Bind `obj` to `fn`.
1067 *
1068 * @param {Object} obj
1069 * @param {Function|String} fn or string
1070 * @return {Function}
1071 * @api public
1072 */
1073
1074module.exports = function(obj, fn){
1075  if ('string' == typeof fn) fn = obj[fn];
1076  if ('function' != typeof fn) throw new Error('bind() requires a function');
1077  var args = slice.call(arguments, 2);
1078  return function(){
1079    return fn.apply(obj, args.concat(slice.call(arguments)));
1080  }
1081};
1082
1083},{}],8:[function(_dereq_,module,exports){
1084
1085/**
1086 * Expose `Emitter`.
1087 */
1088
1089module.exports = Emitter;
1090
1091/**
1092 * Initialize a new `Emitter`.
1093 *
1094 * @api public
1095 */
1096
1097function Emitter(obj) {
1098  if (obj) return mixin(obj);
1099};
1100
1101/**
1102 * Mixin the emitter properties.
1103 *
1104 * @param {Object} obj
1105 * @return {Object}
1106 * @api private
1107 */
1108
1109function mixin(obj) {
1110  for (var key in Emitter.prototype) {
1111    obj[key] = Emitter.prototype[key];
1112  }
1113  return obj;
1114}
1115
1116/**
1117 * Listen on the given `event` with `fn`.
1118 *
1119 * @param {String} event
1120 * @param {Function} fn
1121 * @return {Emitter}
1122 * @api public
1123 */
1124
1125Emitter.prototype.on =
1126Emitter.prototype.addEventListener = function(event, fn){
1127  this._callbacks = this._callbacks || {};
1128  (this._callbacks[event] = this._callbacks[event] || [])
1129    .push(fn);
1130  return this;
1131};
1132
1133/**
1134 * Adds an `event` listener that will be invoked a single
1135 * time then automatically removed.
1136 *
1137 * @param {String} event
1138 * @param {Function} fn
1139 * @return {Emitter}
1140 * @api public
1141 */
1142
1143Emitter.prototype.once = function(event, fn){
1144  var self = this;
1145  this._callbacks = this._callbacks || {};
1146
1147  function on() {
1148    self.off(event, on);
1149    fn.apply(this, arguments);
1150  }
1151
1152  on.fn = fn;
1153  this.on(event, on);
1154  return this;
1155};
1156
1157/**
1158 * Remove the given callback for `event` or all
1159 * registered callbacks.
1160 *
1161 * @param {String} event
1162 * @param {Function} fn
1163 * @return {Emitter}
1164 * @api public
1165 */
1166
1167Emitter.prototype.off =
1168Emitter.prototype.removeListener =
1169Emitter.prototype.removeAllListeners =
1170Emitter.prototype.removeEventListener = function(event, fn){
1171  this._callbacks = this._callbacks || {};
1172
1173  // all
1174  if (0 == arguments.length) {
1175    this._callbacks = {};
1176    return this;
1177  }
1178
1179  // specific event
1180  var callbacks = this._callbacks[event];
1181  if (!callbacks) return this;
1182
1183  // remove all handlers
1184  if (1 == arguments.length) {
1185    delete this._callbacks[event];
1186    return this;
1187  }
1188
1189  // remove specific handler
1190  var cb;
1191  for (var i = 0; i < callbacks.length; i++) {
1192    cb = callbacks[i];
1193    if (cb === fn || cb.fn === fn) {
1194      callbacks.splice(i, 1);
1195      break;
1196    }
1197  }
1198  return this;
1199};
1200
1201/**
1202 * Emit `event` with the given args.
1203 *
1204 * @param {String} event
1205 * @param {Mixed} ...
1206 * @return {Emitter}
1207 */
1208
1209Emitter.prototype.emit = function(event){
1210  this._callbacks = this._callbacks || {};
1211  var args = [].slice.call(arguments, 1)
1212    , callbacks = this._callbacks[event];
1213
1214  if (callbacks) {
1215    callbacks = callbacks.slice(0);
1216    for (var i = 0, len = callbacks.length; i < len; ++i) {
1217      callbacks[i].apply(this, args);
1218    }
1219  }
1220
1221  return this;
1222};
1223
1224/**
1225 * Return array of callbacks for `event`.
1226 *
1227 * @param {String} event
1228 * @return {Array}
1229 * @api public
1230 */
1231
1232Emitter.prototype.listeners = function(event){
1233  this._callbacks = this._callbacks || {};
1234  return this._callbacks[event] || [];
1235};
1236
1237/**
1238 * Check if this emitter has `event` handlers.
1239 *
1240 * @param {String} event
1241 * @return {Boolean}
1242 * @api public
1243 */
1244
1245Emitter.prototype.hasListeners = function(event){
1246  return !! this.listeners(event).length;
1247};
1248
1249},{}],9:[function(_dereq_,module,exports){
1250
1251/**
1252 * Expose `debug()` as the module.
1253 */
1254
1255module.exports = debug;
1256
1257/**
1258 * Create a debugger with the given `name`.
1259 *
1260 * @param {String} name
1261 * @return {Type}
1262 * @api public
1263 */
1264
1265function debug(name) {
1266  if (!debug.enabled(name)) return function(){};
1267
1268  return function(fmt){
1269    fmt = coerce(fmt);
1270
1271    var curr = new Date;
1272    var ms = curr - (debug[name] || curr);
1273    debug[name] = curr;
1274
1275    fmt = name
1276      + ' '
1277      + fmt
1278      + ' +' + debug.humanize(ms);
1279
1280    // This hackery is required for IE8
1281    // where `console.log` doesn't have 'apply'
1282    window.console
1283      && console.log
1284      && Function.prototype.apply.call(console.log, console, arguments);
1285  }
1286}
1287
1288/**
1289 * The currently active debug mode names.
1290 */
1291
1292debug.names = [];
1293debug.skips = [];
1294
1295/**
1296 * Enables a debug mode by name. This can include modes
1297 * separated by a colon and wildcards.
1298 *
1299 * @param {String} name
1300 * @api public
1301 */
1302
1303debug.enable = function(name) {
1304  try {
1305    localStorage.debug = name;
1306  } catch(e){}
1307
1308  var split = (name || '').split(/[\s,]+/)
1309    , len = split.length;
1310
1311  for (var i = 0; i < len; i++) {
1312    name = split[i].replace('*', '.*?');
1313    if (name[0] === '-') {
1314      debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
1315    }
1316    else {
1317      debug.names.push(new RegExp('^' + name + '$'));
1318    }
1319  }
1320};
1321
1322/**
1323 * Disable debug output.
1324 *
1325 * @api public
1326 */
1327
1328debug.disable = function(){
1329  debug.enable('');
1330};
1331
1332/**
1333 * Humanize the given `ms`.
1334 *
1335 * @param {Number} m
1336 * @return {String}
1337 * @api private
1338 */
1339
1340debug.humanize = function(ms) {
1341  var sec = 1000
1342    , min = 60 * 1000
1343    , hour = 60 * min;
1344
1345  if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
1346  if (ms >= min) return (ms / min).toFixed(1) + 'm';
1347  if (ms >= sec) return (ms / sec | 0) + 's';
1348  return ms + 'ms';
1349};
1350
1351/**
1352 * Returns true if the given mode name is enabled, false otherwise.
1353 *
1354 * @param {String} name
1355 * @return {Boolean}
1356 * @api public
1357 */
1358
1359debug.enabled = function(name) {
1360  for (var i = 0, len = debug.skips.length; i < len; i++) {
1361    if (debug.skips[i].test(name)) {
1362      return false;
1363    }
1364  }
1365  for (var i = 0, len = debug.names.length; i < len; i++) {
1366    if (debug.names[i].test(name)) {
1367      return true;
1368    }
1369  }
1370  return false;
1371};
1372
1373/**
1374 * Coerce `val`.
1375 */
1376
1377function coerce(val) {
1378  if (val instanceof Error) return val.stack || val.message;
1379  return val;
1380}
1381
1382// persist
1383
1384try {
1385  if (window.localStorage) debug.enable(localStorage.debug);
1386} catch(e){}
1387
1388},{}],10:[function(_dereq_,module,exports){
1389
1390module.exports =  _dereq_('./lib/');
1391
1392},{"./lib/":11}],11:[function(_dereq_,module,exports){
1393
1394module.exports = _dereq_('./socket');
1395
1396/**
1397 * Exports parser
1398 *
1399 * @api public
1400 *
1401 */
1402module.exports.parser = _dereq_('engine.io-parser');
1403
1404},{"./socket":12,"engine.io-parser":21}],12:[function(_dereq_,module,exports){
1405(function (global){
1406/**
1407 * Module dependencies.
1408 */
1409
1410var transports = _dereq_('./transports');
1411var Emitter = _dereq_('component-emitter');
1412var debug = _dereq_('debug')('engine.io-client:socket');
1413var index = _dereq_('indexof');
1414var parser = _dereq_('engine.io-parser');
1415var parseuri = _dereq_('parseuri');
1416var parsejson = _dereq_('parsejson');
1417var parseqs = _dereq_('parseqs');
1418
1419/**
1420 * Module exports.
1421 */
1422
1423module.exports = Socket;
1424
1425/**
1426 * Noop function.
1427 *
1428 * @api private
1429 */
1430
1431function noop(){}
1432
1433/**
1434 * Socket constructor.
1435 *
1436 * @param {String|Object} uri or options
1437 * @param {Object} options
1438 * @api public
1439 */
1440
1441function Socket(uri, opts){
1442  if (!(this instanceof Socket)) return new Socket(uri, opts);
1443
1444  opts = opts || {};
1445
1446  if (uri && 'object' == typeof uri) {
1447    opts = uri;
1448    uri = null;
1449  }
1450
1451  if (uri) {
1452    uri = parseuri(uri);
1453    opts.host = uri.host;
1454    opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
1455    opts.port = uri.port;
1456    if (uri.query) opts.query = uri.query;
1457  }
1458
1459  this.secure = null != opts.secure ? opts.secure :
1460    (global.location && 'https:' == location.protocol);
1461
1462  if (opts.host) {
1463    var pieces = opts.host.split(':');
1464    opts.hostname = pieces.shift();
1465    if (pieces.length) opts.port = pieces.pop();
1466  }
1467
1468  this.agent = opts.agent || false;
1469  this.hostname = opts.hostname ||
1470    (global.location ? location.hostname : 'localhost');
1471  this.port = opts.port || (global.location && location.port ?
1472       location.port :
1473       (this.secure ? 443 : 80));
1474  this.query = opts.query || {};
1475  if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
1476  this.upgrade = false !== opts.upgrade;
1477  this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
1478  this.forceJSONP = !!opts.forceJSONP;
1479  this.jsonp = false !== opts.jsonp;
1480  this.forceBase64 = !!opts.forceBase64;
1481  this.enablesXDR = !!opts.enablesXDR;
1482  this.timestampParam = opts.timestampParam || 't';
1483  this.timestampRequests = opts.timestampRequests;
1484  this.transports = opts.transports || ['polling', 'websocket'];
1485  this.readyState = '';
1486  this.writeBuffer = [];
1487  this.callbackBuffer = [];
1488  this.policyPort = opts.policyPort || 843;
1489  this.rememberUpgrade = opts.rememberUpgrade || false;
1490  this.open();
1491  this.binaryType = null;
1492  this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
1493}
1494
1495Socket.priorWebsocketSuccess = false;
1496
1497/**
1498 * Mix in `Emitter`.
1499 */
1500
1501Emitter(Socket.prototype);
1502
1503/**
1504 * Protocol version.
1505 *
1506 * @api public
1507 */
1508
1509Socket.protocol = parser.protocol; // this is an int
1510
1511/**
1512 * Expose deps for legacy compatibility
1513 * and standalone browser access.
1514 */
1515
1516Socket.Socket = Socket;
1517Socket.Transport = _dereq_('./transport');
1518Socket.transports = _dereq_('./transports');
1519Socket.parser = _dereq_('engine.io-parser');
1520
1521/**
1522 * Creates transport of the given type.
1523 *
1524 * @param {String} transport name
1525 * @return {Transport}
1526 * @api private
1527 */
1528
1529Socket.prototype.createTransport = function (name) {
1530  debug('creating transport "%s"', name);
1531  var query = clone(this.query);
1532
1533  // append engine.io protocol identifier
1534  query.EIO = parser.protocol;
1535
1536  // transport name
1537  query.transport = name;
1538
1539  // session id if we already have one
1540  if (this.id) query.sid = this.id;
1541
1542  var transport = new transports[name]({
1543    agent: this.agent,
1544    hostname: this.hostname,
1545    port: this.port,
1546    secure: this.secure,
1547    path: this.path,
1548    query: query,
1549    forceJSONP: this.forceJSONP,
1550    jsonp: this.jsonp,
1551    forceBase64: this.forceBase64,
1552    enablesXDR: this.enablesXDR,
1553    timestampRequests: this.timestampRequests,
1554    timestampParam: this.timestampParam,
1555    policyPort: this.policyPort,
1556    socket: this
1557  });
1558
1559  return transport;
1560};
1561
1562function clone (obj) {
1563  var o = {};
1564  for (var i in obj) {
1565    if (obj.hasOwnProperty(i)) {
1566      o[i] = obj[i];
1567    }
1568  }
1569  return o;
1570}
1571
1572/**
1573 * Initializes transport to use and starts probe.
1574 *
1575 * @api private
1576 */
1577Socket.prototype.open = function () {
1578  var transport;
1579  if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
1580    transport = 'websocket';
1581  } else if (0 == this.transports.length) {
1582    // Emit error on next tick so it can be listened to
1583    var self = this;
1584    setTimeout(function() {
1585      self.emit('error', 'No transports available');
1586    }, 0);
1587    return;
1588  } else {
1589    transport = this.transports[0];
1590  }
1591  this.readyState = 'opening';
1592
1593  // Retry with the next transport if the transport is disabled (jsonp: false)
1594  var transport;
1595  try {
1596    transport = this.createTransport(transport);
1597  } catch (e) {
1598    this.transports.shift();
1599    this.open();
1600    return;
1601  }
1602
1603  transport.open();
1604  this.setTransport(transport);
1605};
1606
1607/**
1608 * Sets the current transport. Disables the existing one (if any).
1609 *
1610 * @api private
1611 */
1612
1613Socket.prototype.setTransport = function(transport){
1614  debug('setting transport %s', transport.name);
1615  var self = this;
1616
1617  if (this.transport) {
1618    debug('clearing existing transport %s', this.transport.name);
1619    this.transport.removeAllListeners();
1620  }
1621
1622  // set up transport
1623  this.transport = transport;
1624
1625  // set up transport listeners
1626  transport
1627  .on('drain', function(){
1628    self.onDrain();
1629  })
1630  .on('packet', function(packet){
1631    self.onPacket(packet);
1632  })
1633  .on('error', function(e){
1634    self.onError(e);
1635  })
1636  .on('close', function(){
1637    self.onClose('transport close');
1638  });
1639};
1640
1641/**
1642 * Probes a transport.
1643 *
1644 * @param {String} transport name
1645 * @api private
1646 */
1647
1648Socket.prototype.probe = function (name) {
1649  debug('probing transport "%s"', name);
1650  var transport = this.createTransport(name, { probe: 1 })
1651    , failed = false
1652    , self = this;
1653
1654  Socket.priorWebsocketSuccess = false;
1655
1656  function onTransportOpen(){
1657    if (self.onlyBinaryUpgrades) {
1658      var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
1659      failed = failed || upgradeLosesBinary;
1660    }
1661    if (failed) return;
1662
1663    debug('probe transport "%s" opened', name);
1664    transport.send([{ type: 'ping', data: 'probe' }]);
1665    transport.once('packet', function (msg) {
1666      if (failed) return;
1667      if ('pong' == msg.type && 'probe' == msg.data) {
1668        debug('probe transport "%s" pong', name);
1669        self.upgrading = true;
1670        self.emit('upgrading', transport);
1671        if (!transport) return;
1672        Socket.priorWebsocketSuccess = 'websocket' == transport.name;
1673
1674        debug('pausing current transport "%s"', self.transport.name);
1675        self.transport.pause(function () {
1676          if (failed) return;
1677          if ('closed' == self.readyState) return;
1678          debug('changing transport and sending upgrade packet');
1679
1680          cleanup();
1681
1682          self.setTransport(transport);
1683          transport.send([{ type: 'upgrade' }]);
1684          self.emit('upgrade', transport);
1685          transport = null;
1686          self.upgrading = false;
1687          self.flush();
1688        });
1689      } else {
1690        debug('probe transport "%s" failed', name);
1691        var err = new Error('probe error');
1692        err.transport = transport.name;
1693        self.emit('upgradeError', err);
1694      }
1695    });
1696  }
1697
1698  function freezeTransport() {
1699    if (failed) return;
1700
1701    // Any callback called by transport should be ignored since now
1702    failed = true;
1703
1704    cleanup();
1705
1706    transport.close();
1707    transport = null;
1708  }
1709
1710  //Handle any error that happens while probing
1711  function onerror(err) {
1712    var error = new Error('probe error: ' + err);
1713    error.transport = transport.name;
1714
1715    freezeTransport();
1716
1717    debug('probe transport "%s" failed because of error: %s', name, err);
1718
1719    self.emit('upgradeError', error);
1720  }
1721
1722  function onTransportClose(){
1723    onerror("transport closed");
1724  }
1725
1726  //When the socket is closed while we're probing
1727  function onclose(){
1728    onerror("socket closed");
1729  }
1730
1731  //When the socket is upgraded while we're probing
1732  function onupgrade(to){
1733    if (transport && to.name != transport.name) {
1734      debug('"%s" works - aborting "%s"', to.name, transport.name);
1735      freezeTransport();
1736    }
1737  }
1738
1739  //Remove all listeners on the transport and on self
1740  function cleanup(){
1741    transport.removeListener('open', onTransportOpen);
1742    transport.removeListener('error', onerror);
1743    transport.removeListener('close', onTransportClose);
1744    self.removeListener('close', onclose);
1745    self.removeListener('upgrading', onupgrade);
1746  }
1747
1748  transport.once('open', onTransportOpen);
1749  transport.once('error', onerror);
1750  transport.once('close', onTransportClose);
1751
1752  this.once('close', onclose);
1753  this.once('upgrading', onupgrade);
1754
1755  transport.open();
1756
1757};
1758
1759/**
1760 * Called when connection is deemed open.
1761 *
1762 * @api public
1763 */
1764
1765Socket.prototype.onOpen = function () {
1766  debug('socket open');
1767  this.readyState = 'open';
1768  Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
1769  this.emit('open');
1770  this.flush();
1771
1772  // we check for `readyState` in case an `open`
1773  // listener already closed the socket
1774  if ('open' == this.readyState && this.upgrade && this.transport.pause) {
1775    debug('starting upgrade probes');
1776    for (var i = 0, l = this.upgrades.length; i < l; i++) {
1777      this.probe(this.upgrades[i]);
1778    }
1779  }
1780};
1781
1782/**
1783 * Handles a packet.
1784 *
1785 * @api private
1786 */
1787
1788Socket.prototype.onPacket = function (packet) {
1789  if ('opening' == this.readyState || 'open' == this.readyState) {
1790    debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
1791
1792    this.emit('packet', packet);
1793
1794    // Socket is live - any packet counts
1795    this.emit('heartbeat');
1796
1797    switch (packet.type) {
1798      case 'open':
1799        this.onHandshake(parsejson(packet.data));
1800        break;
1801
1802      case 'pong':
1803        this.setPing();
1804        break;
1805
1806      case 'error':
1807        var err = new Error('server error');
1808        err.code = packet.data;
1809        this.emit('error', err);
1810        break;
1811
1812      case 'message':
1813        this.emit('data', packet.data);
1814        this.emit('message', packet.data);
1815        break;
1816    }
1817  } else {
1818    debug('packet received with socket readyState "%s"', this.readyState);
1819  }
1820};
1821
1822/**
1823 * Called upon handshake completion.
1824 *
1825 * @param {Object} handshake obj
1826 * @api private
1827 */
1828
1829Socket.prototype.onHandshake = function (data) {
1830  this.emit('handshake', data);
1831  this.id = data.sid;
1832  this.transport.query.sid = data.sid;
1833  this.upgrades = this.filterUpgrades(data.upgrades);
1834  this.pingInterval = data.pingInterval;
1835  this.pingTimeout = data.pingTimeout;
1836  this.onOpen();
1837  // In case open handler closes socket
1838  if  ('closed' == this.readyState) return;
1839  this.setPing();
1840
1841  // Prolong liveness of socket on heartbeat
1842  this.removeListener('heartbeat', this.onHeartbeat);
1843  this.on('heartbeat', this.onHeartbeat);
1844};
1845
1846/**
1847 * Resets ping timeout.
1848 *
1849 * @api private
1850 */
1851
1852Socket.prototype.onHeartbeat = function (timeout) {
1853  clearTimeout(this.pingTimeoutTimer);
1854  var self = this;
1855  self.pingTimeoutTimer = setTimeout(function () {
1856    if ('closed' == self.readyState) return;
1857    self.onClose('ping timeout');
1858  }, timeout || (self.pingInterval + self.pingTimeout));
1859};
1860
1861/**
1862 * Pings server every `this.pingInterval` and expects response
1863 * within `this.pingTimeout` or closes connection.
1864 *
1865 * @api private
1866 */
1867
1868Socket.prototype.setPing = function () {
1869  var self = this;
1870  clearTimeout(self.pingIntervalTimer);
1871  self.pingIntervalTimer = setTimeout(function () {
1872    debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
1873    self.ping();
1874    self.onHeartbeat(self.pingTimeout);
1875  }, self.pingInterval);
1876};
1877
1878/**
1879* Sends a ping packet.
1880*
1881* @api public
1882*/
1883
1884Socket.prototype.ping = function () {
1885  this.sendPacket('ping');
1886};
1887
1888/**
1889 * Called on `drain` event
1890 *
1891 * @api private
1892 */
1893
1894Socket.prototype.onDrain = function() {
1895  for (var i = 0; i < this.prevBufferLen; i++) {
1896    if (this.callbackBuffer[i]) {
1897      this.callbackBuffer[i]();
1898    }
1899  }
1900
1901  this.writeBuffer.splice(0, this.prevBufferLen);
1902  this.callbackBuffer.splice(0, this.prevBufferLen);
1903
1904  // setting prevBufferLen = 0 is very important
1905  // for example, when upgrading, upgrade packet is sent over,
1906  // and a nonzero prevBufferLen could cause problems on `drain`
1907  this.prevBufferLen = 0;
1908
1909  if (this.writeBuffer.length == 0) {
1910    this.emit('drain');
1911  } else {
1912    this.flush();
1913  }
1914};
1915
1916/**
1917 * Flush write buffers.
1918 *
1919 * @api private
1920 */
1921
1922Socket.prototype.flush = function () {
1923  if ('closed' != this.readyState && this.transport.writable &&
1924    !this.upgrading && this.writeBuffer.length) {
1925    debug('flushing %d packets in socket', this.writeBuffer.length);
1926    this.transport.send(this.writeBuffer);
1927    // keep track of current length of writeBuffer
1928    // splice writeBuffer and callbackBuffer on `drain`
1929    this.prevBufferLen = this.writeBuffer.length;
1930    this.emit('flush');
1931  }
1932};
1933
1934/**
1935 * Sends a message.
1936 *
1937 * @param {String} message.
1938 * @param {Function} callback function.
1939 * @return {Socket} for chaining.
1940 * @api public
1941 */
1942
1943Socket.prototype.write =
1944Socket.prototype.send = function (msg, fn) {
1945  this.sendPacket('message', msg, fn);
1946  return this;
1947};
1948
1949/**
1950 * Sends a packet.
1951 *
1952 * @param {String} packet type.
1953 * @param {String} data.
1954 * @param {Function} callback function.
1955 * @api private
1956 */
1957
1958Socket.prototype.sendPacket = function (type, data, fn) {
1959  if ('closing' == this.readyState || 'closed' == this.readyState) {
1960    return;
1961  }
1962
1963  var packet = { type: type, data: data };
1964  this.emit('packetCreate', packet);
1965  this.writeBuffer.push(packet);
1966  this.callbackBuffer.push(fn);
1967  this.flush();
1968};
1969
1970/**
1971 * Closes the connection.
1972 *
1973 * @api private
1974 */
1975
1976Socket.prototype.close = function () {
1977  if ('opening' == this.readyState || 'open' == this.readyState) {
1978    this.readyState = 'closing';
1979
1980    var self = this;
1981
1982    function close() {
1983      self.onClose('forced close');
1984      debug('socket closing - telling transport to close');
1985      self.transport.close();
1986    }
1987
1988    function cleanupAndClose() {
1989      self.removeListener('upgrade', cleanupAndClose);
1990      self.removeListener('upgradeError', cleanupAndClose);
1991      close();
1992    }
1993
1994    function waitForUpgrade() {
1995      // wait for upgrade to finish since we can't send packets while pausing a transport
1996      self.once('upgrade', cleanupAndClose);
1997      self.once('upgradeError', cleanupAndClose);
1998    }
1999
2000    if (this.writeBuffer.length) {
2001      this.once('drain', function() {
2002        if (this.upgrading) {
2003          waitForUpgrade();
2004        } else {
2005          close();
2006        }
2007      });
2008    } else if (this.upgrading) {
2009      waitForUpgrade();
2010    } else {
2011      close();
2012    }
2013  }
2014
2015  return this;
2016};
2017
2018/**
2019 * Called upon transport error
2020 *
2021 * @api private
2022 */
2023
2024Socket.prototype.onError = function (err) {
2025  debug('socket error %j', err);
2026  Socket.priorWebsocketSuccess = false;
2027  this.emit('error', err);
2028  this.onClose('transport error', err);
2029};
2030
2031/**
2032 * Called upon transport close.
2033 *
2034 * @api private
2035 */
2036
2037Socket.prototype.onClose = function (reason, desc) {
2038  if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
2039    debug('socket close with reason: "%s"', reason);
2040    var self = this;
2041
2042    // clear timers
2043    clearTimeout(this.pingIntervalTimer);
2044    clearTimeout(this.pingTimeoutTimer);
2045
2046    // clean buffers in next tick, so developers can still
2047    // grab the buffers on `close` event
2048    setTimeout(function() {
2049      self.writeBuffer = [];
2050      self.callbackBuffer = [];
2051      self.prevBufferLen = 0;
2052    }, 0);
2053
2054    // stop event from firing again for transport
2055    this.transport.removeAllListeners('close');
2056
2057    // ensure transport won't stay open
2058    this.transport.close();
2059
2060    // ignore further transport communication
2061    this.transport.removeAllListeners();
2062
2063    // set ready state
2064    this.readyState = 'closed';
2065
2066    // clear session id
2067    this.id = null;
2068
2069    // emit close event
2070    this.emit('close', reason, desc);
2071  }
2072};
2073
2074/**
2075 * Filters upgrades, returning only those matching client transports.
2076 *
2077 * @param {Array} server upgrades
2078 * @api private
2079 *
2080 */
2081
2082Socket.prototype.filterUpgrades = function (upgrades) {
2083  var filteredUpgrades = [];
2084  for (var i = 0, j = upgrades.length; i<j; i++) {
2085    if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
2086  }
2087  return filteredUpgrades;
2088};
2089
2090}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2091},{"./transport":13,"./transports":14,"component-emitter":8,"debug":9,"engine.io-parser":21,"indexof":36,"parsejson":28,"parseqs":29,"parseuri":30}],13:[function(_dereq_,module,exports){
2092/**
2093 * Module dependencies.
2094 */
2095
2096var parser = _dereq_('engine.io-parser');
2097var Emitter = _dereq_('component-emitter');
2098
2099/**
2100 * Module exports.
2101 */
2102
2103module.exports = Transport;
2104
2105/**
2106 * Transport abstract constructor.
2107 *
2108 * @param {Object} options.
2109 * @api private
2110 */
2111
2112function Transport (opts) {
2113  this.path = opts.path;
2114  this.hostname = opts.hostname;
2115  this.port = opts.port;
2116  this.secure = opts.secure;
2117  this.query = opts.query;
2118  this.timestampParam = opts.timestampParam;
2119  this.timestampRequests = opts.timestampRequests;
2120  this.readyState = '';
2121  this.agent = opts.agent || false;
2122  this.socket = opts.socket;
2123  this.enablesXDR = opts.enablesXDR;
2124}
2125
2126/**
2127 * Mix in `Emitter`.
2128 */
2129
2130Emitter(Transport.prototype);
2131
2132/**
2133 * A counter used to prevent collisions in the timestamps used
2134 * for cache busting.
2135 */
2136
2137Transport.timestamps = 0;
2138
2139/**
2140 * Emits an error.
2141 *
2142 * @param {String} str
2143 * @return {Transport} for chaining
2144 * @api public
2145 */
2146
2147Transport.prototype.onError = function (msg, desc) {
2148  var err = new Error(msg);
2149  err.type = 'TransportError';
2150  err.description = desc;
2151  this.emit('error', err);
2152  return this;
2153};
2154
2155/**
2156 * Opens the transport.
2157 *
2158 * @api public
2159 */
2160
2161Transport.prototype.open = function () {
2162  if ('closed' == this.readyState || '' == this.readyState) {
2163    this.readyState = 'opening';
2164    this.doOpen();
2165  }
2166
2167  return this;
2168};
2169
2170/**
2171 * Closes the transport.
2172 *
2173 * @api private
2174 */
2175
2176Transport.prototype.close = function () {
2177  if ('opening' == this.readyState || 'open' == this.readyState) {
2178    this.doClose();
2179    this.onClose();
2180  }
2181
2182  return this;
2183};
2184
2185/**
2186 * Sends multiple packets.
2187 *
2188 * @param {Array} packets
2189 * @api private
2190 */
2191
2192Transport.prototype.send = function(packets){
2193  if ('open' == this.readyState) {
2194    this.write(packets);
2195  } else {
2196    throw new Error('Transport not open');
2197  }
2198};
2199
2200/**
2201 * Called upon open
2202 *
2203 * @api private
2204 */
2205
2206Transport.prototype.onOpen = function () {
2207  this.readyState = 'open';
2208  this.writable = true;
2209  this.emit('open');
2210};
2211
2212/**
2213 * Called with data.
2214 *
2215 * @param {String} data
2216 * @api private
2217 */
2218
2219Transport.prototype.onData = function(data){
2220  var packet = parser.decodePacket(data, this.socket.binaryType);
2221  this.onPacket(packet);
2222};
2223
2224/**
2225 * Called with a decoded packet.
2226 */
2227
2228Transport.prototype.onPacket = function (packet) {
2229  this.emit('packet', packet);
2230};
2231
2232/**
2233 * Called upon close.
2234 *
2235 * @api private
2236 */
2237
2238Transport.prototype.onClose = function () {
2239  this.readyState = 'closed';
2240  this.emit('close');
2241};
2242
2243},{"component-emitter":8,"engine.io-parser":21}],14:[function(_dereq_,module,exports){
2244(function (global){
2245/**
2246 * Module dependencies
2247 */
2248
2249var XMLHttpRequest = _dereq_('xmlhttprequest');
2250var XHR = _dereq_('./polling-xhr');
2251var JSONP = _dereq_('./polling-jsonp');
2252var websocket = _dereq_('./websocket');
2253
2254/**
2255 * Export transports.
2256 */
2257
2258exports.polling = polling;
2259exports.websocket = websocket;
2260
2261/**
2262 * Polling transport polymorphic constructor.
2263 * Decides on xhr vs jsonp based on feature detection.
2264 *
2265 * @api private
2266 */
2267
2268function polling(opts){
2269  var xhr;
2270  var xd = false;
2271  var xs = false;
2272  var jsonp = false !== opts.jsonp;
2273
2274  if (global.location) {
2275    var isSSL = 'https:' == location.protocol;
2276    var port = location.port;
2277
2278    // some user agents have empty `location.port`
2279    if (!port) {
2280      port = isSSL ? 443 : 80;
2281    }
2282
2283    xd = opts.hostname != location.hostname || port != opts.port;
2284    xs = opts.secure != isSSL;
2285  }
2286
2287  opts.xdomain = xd;
2288  opts.xscheme = xs;
2289  xhr = new XMLHttpRequest(opts);
2290
2291  if ('open' in xhr && !opts.forceJSONP) {
2292    return new XHR(opts);
2293  } else {
2294    if (!jsonp) throw new Error('JSONP disabled');
2295    return new JSONP(opts);
2296  }
2297}
2298
2299}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2300},{"./polling-jsonp":15,"./polling-xhr":16,"./websocket":18,"xmlhttprequest":19}],15:[function(_dereq_,module,exports){
2301(function (global){
2302
2303/**
2304 * Module requirements.
2305 */
2306
2307var Polling = _dereq_('./polling');
2308var inherit = _dereq_('component-inherit');
2309
2310/**
2311 * Module exports.
2312 */
2313
2314module.exports = JSONPPolling;
2315
2316/**
2317 * Cached regular expressions.
2318 */
2319
2320var rNewline = /\n/g;
2321var rEscapedNewline = /\\n/g;
2322
2323/**
2324 * Global JSONP callbacks.
2325 */
2326
2327var callbacks;
2328
2329/**
2330 * Callbacks count.
2331 */
2332
2333var index = 0;
2334
2335/**
2336 * Noop.
2337 */
2338
2339function empty () { }
2340
2341/**
2342 * JSONP Polling constructor.
2343 *
2344 * @param {Object} opts.
2345 * @api public
2346 */
2347
2348function JSONPPolling (opts) {
2349  Polling.call(this, opts);
2350
2351  this.query = this.query || {};
2352
2353  // define global callbacks array if not present
2354  // we do this here (lazily) to avoid unneeded global pollution
2355  if (!callbacks) {
2356    // we need to consider multiple engines in the same page
2357    if (!global.___eio) global.___eio = [];
2358    callbacks = global.___eio;
2359  }
2360
2361  // callback identifier
2362  this.index = callbacks.length;
2363
2364  // add callback to jsonp global
2365  var self = this;
2366  callbacks.push(function (msg) {
2367    self.onData(msg);
2368  });
2369
2370  // append t…

Large files files are truncated, but you can click here to view the full file