PageRenderTime 110ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/js/skynet.bundle.js

https://github.com/SYCCON/skynet
JavaScript | 8844 lines | 5505 code | 1357 blank | 1982 comment | 1405 complexity | a72b3b54dea417156436f69a63e3f0ce MD5 | raw 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.skynet=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. var Connection = _dereq_('./lib/Connection');
  3. module.exports = {
  4. createConnection: function (opt){
  5. return new Connection(opt);
  6. }
  7. }
  8. },{"./lib/Connection":2}],2:[function(_dereq_,module,exports){
  9. 'use strict';
  10. var util = _dereq_('util');
  11. var EventEmitter = _dereq_('events').EventEmitter;
  12. var socketIoClient = _dereq_("socket.io-client");
  13. var DEFAULT_TIMEOUT = 10000;
  14. function Connection(opt){
  15. EventEmitter.call(this);
  16. this._callbackHandlers = {};
  17. this._ackId = 0;
  18. this.options = opt || {};
  19. this.options.options = this.options.options || {};
  20. this.options.options.transports = this.options.options.transports || ['websocket'];
  21. this.options.forceNew = (opt.forceNew != null) ? opt.forceNew : false;
  22. this.options.server = this.options.server || 'ws://skynet.im';
  23. this.options.port = this.options.port || 80;
  24. // if(this.options.server && this.options.port){
  25. if(this.options.server.indexOf("http") === -1 && this.options.server.indexOf("ws") === -1 && this.options.server.indexOf("wss") === -1 ){
  26. this.options.server = "ws://" + this.options.server;
  27. }
  28. // network = this.options.server + ":" + this.options.port;
  29. // }
  30. var network = this.options.server + ':' + this.options.port;
  31. console.log('trying', network);
  32. this.socket = socketIoClient(network, this.options.options); // || "ws://skynet.im");
  33. // this.socket = io.connect(this.options.server || "http://skynet.im", {
  34. // port: this.options.port || 80,
  35. // forceNew: this.options.forceNew,
  36. // multiplex: !this.options.forceNew,
  37. // 'force new connection': this.options.forceNew
  38. // });
  39. this.options.protocol = "websocket";
  40. this.setup();
  41. }
  42. util.inherits(Connection, EventEmitter);
  43. Connection.prototype.setup = function(){
  44. var self = this;
  45. this.socket.once('connect', function(){
  46. this.emit('connect');
  47. this.socket.on('messageAck', function(data){
  48. if(self._callbackHandlers[data.ack]){
  49. try{
  50. self._callbackHandlers[data.ack](data.payload);
  51. delete self._callbackHandlers[data.ack];
  52. }
  53. catch(err){
  54. console.log('error resolving callback', err);
  55. }
  56. }
  57. });
  58. this.socket.on('message', function(data){
  59. self._handleAckRequest('message', data);
  60. });
  61. //this.emit.bind(this, 'message'));
  62. this.socket.on('config', function(data){
  63. self._handleAckRequest('config', data);
  64. });
  65. this.socket.on('disconnect', this.emit.bind(this, 'disconnect'));
  66. this.socket.on('identify', this.identify.bind(this));
  67. this.socket.on('ready', this.emit.bind(this, 'ready'));
  68. this.socket.on('notReady', this.emit.bind(this, 'notReady'));
  69. this.socket.on('tb', this.emit.bind(this, 'tb'));
  70. this.socket.on('unboundSocket', this.emit.bind(this, 'unboundSocket'));
  71. }.bind(this));
  72. return this;
  73. };
  74. //Provide callback when message with ack requests comes in from another client
  75. Connection.prototype._handleAckRequest = function(topic, data){
  76. var self = this;
  77. if(data){
  78. if(data.ack && data.fromUuid){
  79. //TODO clean these up if not used
  80. self.emit(topic, data, function(response){
  81. self.socket.emit('messageAck', {
  82. devices: data.fromUuid,
  83. ack: data.ack,
  84. payload: response
  85. });
  86. });
  87. }else{
  88. self.emit(topic, data);
  89. }
  90. }
  91. };
  92. //Allow for making RPC requests to other clients
  93. Connection.prototype._emitWithAck = function(topic, data, fn){
  94. var self = this;
  95. if(data){
  96. if(fn){
  97. var ack = ++this._ackId;
  98. data.ack = ack;
  99. self._callbackHandlers[ack] = fn;
  100. var timeout = data.timeout || DEFAULT_TIMEOUT;
  101. //remove handlers
  102. setTimeout(function(){
  103. if(self._callbackHandlers[ack]){
  104. self._callbackHandlers[ack]({error: 'timeout ' + timeout});
  105. delete self._callbackHandlers[ack];
  106. }
  107. }, timeout);
  108. }
  109. //console.log('emitting ack', topic, data);
  110. this.socket.emit(topic, data);
  111. }
  112. return this;
  113. };
  114. Connection.prototype.identify = function(){
  115. this.socket.emit('identity', {
  116. uuid: this.options.uuid,
  117. token: this.options.token,
  118. protocol: this.options.protocol
  119. });
  120. return this;
  121. };
  122. Connection.prototype.message = function(data, fn) {
  123. return this._emitWithAck('message', data, fn);
  124. };
  125. Connection.prototype.config = function(data, fn) {
  126. return this._emitWithAck('gatewayConfig', data, fn);
  127. };
  128. Connection.prototype.gatewayConfig = function(data, fn) {
  129. return this._emitWithAck('gatewayConfig', data, fn);
  130. };
  131. // send plain text
  132. Connection.prototype.send = function(text) {
  133. if(text){
  134. text = text.toString();
  135. this.socket.send(text);
  136. }
  137. return this;
  138. };
  139. Connection.prototype.update = function(data, fn) {
  140. this.socket.emit('update', data, fn);
  141. return this;
  142. };
  143. Connection.prototype.register = function(data, fn) {
  144. this.socket.emit('register', data, fn);
  145. return this;
  146. };
  147. Connection.prototype.unregister = function(data, fn) {
  148. this.socket.emit('unregister', data, fn);
  149. return this;
  150. };
  151. Connection.prototype.whoami = function(data, fn) {
  152. this.socket.emit('whoami', data, fn);
  153. return this;
  154. };
  155. Connection.prototype.devices = function(data, fn) {
  156. this.socket.emit('devices', data, fn);
  157. return this;
  158. };
  159. Connection.prototype.mydevices = function(data, fn) {
  160. this.socket.emit('mydevices', data, fn);
  161. return this;
  162. };
  163. Connection.prototype.status = function(data) {
  164. this.socket.emit('status', data);
  165. return this;
  166. };
  167. Connection.prototype.subscribe = function(data, fn) {
  168. if(typeof data === 'string'){
  169. data = {uuid: data};
  170. }
  171. this.socket.emit('subscribe', data, fn);
  172. return this;
  173. };
  174. Connection.prototype.unsubscribe = function(data, fn) {
  175. if(typeof data === 'string'){
  176. data = {uuid: data};
  177. }
  178. this.socket.emit('unsubscribe', data, fn);
  179. return this;
  180. };
  181. Connection.prototype.authenticate = function(data, fn) {
  182. this.socket.emit('authenticate', data, fn);
  183. return this;
  184. };
  185. Connection.prototype.events = function(data, fn) {
  186. this.socket.emit('events', data, fn);
  187. return this;
  188. };
  189. Connection.prototype.data = function(data, fn) {
  190. this.socket.emit('data', data, fn);
  191. return this;
  192. };
  193. Connection.prototype.getdata = function(data, fn) {
  194. this.socket.emit('getdata', data, fn);
  195. return this;
  196. };
  197. Connection.prototype.localdevices = function(fn) {
  198. this.socket.emit('localdevices', {}, fn);
  199. return this;
  200. };
  201. Connection.prototype.textBroadcast = function(data) {
  202. if(typeof data !== 'string'){
  203. data = String(data);
  204. }
  205. this.socket.emit('tb', data);
  206. return this;
  207. };
  208. Connection.prototype.directText = function(data) {
  209. if(typeof data === 'object' && data.payload && typeof data.payload === 'string' && data.devices){
  210. this.socket.emit('directText', data);
  211. }
  212. else{
  213. console.log('directText requires an object with a string payload property, and a devices property');
  214. }
  215. return this;
  216. };
  217. Connection.prototype.subscribeText = function(data, fn) {
  218. if(typeof data === 'string'){
  219. data = {uuid: data};
  220. }
  221. this.socket.emit('subscribeText', data, fn);
  222. return this;
  223. };
  224. Connection.prototype.unsubscribeText = function(data, fn) {
  225. if(typeof data === 'string'){
  226. data = {uuid: data};
  227. }
  228. this.socket.emit('unsubscribeText', data, fn);
  229. return this;
  230. };
  231. Connection.prototype.close = function(){
  232. return this;
  233. };
  234. module.exports = Connection;
  235. },{"events":49,"socket.io-client":3,"util":53}],3:[function(_dereq_,module,exports){
  236. module.exports = _dereq_('./lib/');
  237. },{"./lib/":4}],4:[function(_dereq_,module,exports){
  238. /**
  239. * Module dependencies.
  240. */
  241. var url = _dereq_('./url');
  242. var parser = _dereq_('socket.io-parser');
  243. var Manager = _dereq_('./manager');
  244. var debug = _dereq_('debug')('socket.io-client');
  245. /**
  246. * Module exports.
  247. */
  248. module.exports = exports = lookup;
  249. /**
  250. * Managers cache.
  251. */
  252. var cache = exports.managers = {};
  253. /**
  254. * Looks up an existing `Manager` for multiplexing.
  255. * If the user summons:
  256. *
  257. * `io('http://localhost/a');`
  258. * `io('http://localhost/b');`
  259. *
  260. * We reuse the existing instance based on same scheme/port/host,
  261. * and we initialize sockets for each namespace.
  262. *
  263. * @api public
  264. */
  265. function lookup(uri, opts) {
  266. if (typeof uri == 'object') {
  267. opts = uri;
  268. uri = undefined;
  269. }
  270. opts = opts || {};
  271. var parsed = url(uri);
  272. var source = parsed.source;
  273. var id = parsed.id;
  274. var io;
  275. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  276. debug('ignoring socket cache for %s', source);
  277. io = Manager(source, opts);
  278. } else {
  279. if (!cache[id]) {
  280. debug('new io instance for %s', source);
  281. cache[id] = Manager(source, opts);
  282. }
  283. io = cache[id];
  284. }
  285. return io.socket(parsed.path);
  286. }
  287. /**
  288. * Protocol version.
  289. *
  290. * @api public
  291. */
  292. exports.protocol = parser.protocol;
  293. /**
  294. * `connect`.
  295. *
  296. * @param {String} uri
  297. * @api public
  298. */
  299. exports.connect = lookup;
  300. /**
  301. * Expose constructors for standalone build.
  302. *
  303. * @api public
  304. */
  305. exports.Manager = _dereq_('./manager');
  306. exports.Socket = _dereq_('./socket');
  307. },{"./manager":5,"./socket":7,"./url":8,"debug":11,"socket.io-parser":41}],5:[function(_dereq_,module,exports){
  308. /**
  309. * Module dependencies.
  310. */
  311. var url = _dereq_('./url');
  312. var eio = _dereq_('engine.io-client');
  313. var Socket = _dereq_('./socket');
  314. var Emitter = _dereq_('component-emitter');
  315. var parser = _dereq_('socket.io-parser');
  316. var on = _dereq_('./on');
  317. var bind = _dereq_('component-bind');
  318. var object = _dereq_('object-component');
  319. var debug = _dereq_('debug')('socket.io-client:manager');
  320. /**
  321. * Module exports
  322. */
  323. module.exports = Manager;
  324. /**
  325. * `Manager` constructor.
  326. *
  327. * @param {String} engine instance or engine uri/opts
  328. * @param {Object} options
  329. * @api public
  330. */
  331. function Manager(uri, opts){
  332. if (!(this instanceof Manager)) return new Manager(uri, opts);
  333. if (uri && ('object' == typeof uri)) {
  334. opts = uri;
  335. uri = undefined;
  336. }
  337. opts = opts || {};
  338. opts.path = opts.path || '/socket.io';
  339. this.nsps = {};
  340. this.subs = [];
  341. this.opts = opts;
  342. this.reconnection(opts.reconnection !== false);
  343. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  344. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  345. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  346. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  347. this.readyState = 'closed';
  348. this.uri = uri;
  349. this.connected = 0;
  350. this.attempts = 0;
  351. this.encoding = false;
  352. this.packetBuffer = [];
  353. this.encoder = new parser.Encoder();
  354. this.decoder = new parser.Decoder();
  355. this.open();
  356. }
  357. /**
  358. * Propagate given event to sockets and emit on `this`
  359. *
  360. * @api private
  361. */
  362. Manager.prototype.emitAll = function() {
  363. this.emit.apply(this, arguments);
  364. for (var nsp in this.nsps) {
  365. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  366. }
  367. };
  368. /**
  369. * Mix in `Emitter`.
  370. */
  371. Emitter(Manager.prototype);
  372. /**
  373. * Sets the `reconnection` config.
  374. *
  375. * @param {Boolean} true/false if it should automatically reconnect
  376. * @return {Manager} self or value
  377. * @api public
  378. */
  379. Manager.prototype.reconnection = function(v){
  380. if (!arguments.length) return this._reconnection;
  381. this._reconnection = !!v;
  382. return this;
  383. };
  384. /**
  385. * Sets the reconnection attempts config.
  386. *
  387. * @param {Number} max reconnection attempts before giving up
  388. * @return {Manager} self or value
  389. * @api public
  390. */
  391. Manager.prototype.reconnectionAttempts = function(v){
  392. if (!arguments.length) return this._reconnectionAttempts;
  393. this._reconnectionAttempts = v;
  394. return this;
  395. };
  396. /**
  397. * Sets the delay between reconnections.
  398. *
  399. * @param {Number} delay
  400. * @return {Manager} self or value
  401. * @api public
  402. */
  403. Manager.prototype.reconnectionDelay = function(v){
  404. if (!arguments.length) return this._reconnectionDelay;
  405. this._reconnectionDelay = v;
  406. return this;
  407. };
  408. /**
  409. * Sets the maximum delay between reconnections.
  410. *
  411. * @param {Number} delay
  412. * @return {Manager} self or value
  413. * @api public
  414. */
  415. Manager.prototype.reconnectionDelayMax = function(v){
  416. if (!arguments.length) return this._reconnectionDelayMax;
  417. this._reconnectionDelayMax = v;
  418. return this;
  419. };
  420. /**
  421. * Sets the connection timeout. `false` to disable
  422. *
  423. * @return {Manager} self or value
  424. * @api public
  425. */
  426. Manager.prototype.timeout = function(v){
  427. if (!arguments.length) return this._timeout;
  428. this._timeout = v;
  429. return this;
  430. };
  431. /**
  432. * Starts trying to reconnect if reconnection is enabled and we have not
  433. * started reconnecting yet
  434. *
  435. * @api private
  436. */
  437. Manager.prototype.maybeReconnectOnOpen = function() {
  438. if (!this.openReconnect && !this.reconnecting && this._reconnection) {
  439. // keeps reconnection from firing twice for the same reconnection loop
  440. this.openReconnect = true;
  441. this.reconnect();
  442. }
  443. };
  444. /**
  445. * Sets the current transport `socket`.
  446. *
  447. * @param {Function} optional, callback
  448. * @return {Manager} self
  449. * @api public
  450. */
  451. Manager.prototype.open =
  452. Manager.prototype.connect = function(fn){
  453. debug('readyState %s', this.readyState);
  454. if (~this.readyState.indexOf('open')) return this;
  455. debug('opening %s', this.uri);
  456. this.engine = eio(this.uri, this.opts);
  457. var socket = this.engine;
  458. var self = this;
  459. this.readyState = 'opening';
  460. // emit `open`
  461. var openSub = on(socket, 'open', function() {
  462. self.onopen();
  463. fn && fn();
  464. });
  465. // emit `connect_error`
  466. var errorSub = on(socket, 'error', function(data){
  467. debug('connect_error');
  468. self.cleanup();
  469. self.readyState = 'closed';
  470. self.emitAll('connect_error', data);
  471. if (fn) {
  472. var err = new Error('Connection error');
  473. err.data = data;
  474. fn(err);
  475. }
  476. self.maybeReconnectOnOpen();
  477. });
  478. // emit `connect_timeout`
  479. if (false !== this._timeout) {
  480. var timeout = this._timeout;
  481. debug('connect attempt will timeout after %d', timeout);
  482. // set timer
  483. var timer = setTimeout(function(){
  484. debug('connect attempt timed out after %d', timeout);
  485. openSub.destroy();
  486. socket.close();
  487. socket.emit('error', 'timeout');
  488. self.emitAll('connect_timeout', timeout);
  489. }, timeout);
  490. this.subs.push({
  491. destroy: function(){
  492. clearTimeout(timer);
  493. }
  494. });
  495. }
  496. this.subs.push(openSub);
  497. this.subs.push(errorSub);
  498. return this;
  499. };
  500. /**
  501. * Called upon transport open.
  502. *
  503. * @api private
  504. */
  505. Manager.prototype.onopen = function(){
  506. debug('open');
  507. // clear old subs
  508. this.cleanup();
  509. // mark as open
  510. this.readyState = 'open';
  511. this.emit('open');
  512. // add new subs
  513. var socket = this.engine;
  514. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  515. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  516. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  517. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  518. };
  519. /**
  520. * Called with data.
  521. *
  522. * @api private
  523. */
  524. Manager.prototype.ondata = function(data){
  525. this.decoder.add(data);
  526. };
  527. /**
  528. * Called when parser fully decodes a packet.
  529. *
  530. * @api private
  531. */
  532. Manager.prototype.ondecoded = function(packet) {
  533. this.emit('packet', packet);
  534. };
  535. /**
  536. * Called upon socket error.
  537. *
  538. * @api private
  539. */
  540. Manager.prototype.onerror = function(err){
  541. debug('error', err);
  542. this.emitAll('error', err);
  543. };
  544. /**
  545. * Creates a new socket for the given `nsp`.
  546. *
  547. * @return {Socket}
  548. * @api public
  549. */
  550. Manager.prototype.socket = function(nsp){
  551. var socket = this.nsps[nsp];
  552. if (!socket) {
  553. socket = new Socket(this, nsp);
  554. this.nsps[nsp] = socket;
  555. var self = this;
  556. socket.on('connect', function(){
  557. self.connected++;
  558. });
  559. }
  560. return socket;
  561. };
  562. /**
  563. * Called upon a socket close.
  564. *
  565. * @param {Socket} socket
  566. */
  567. Manager.prototype.destroy = function(socket){
  568. --this.connected || this.close();
  569. };
  570. /**
  571. * Writes a packet.
  572. *
  573. * @param {Object} packet
  574. * @api private
  575. */
  576. Manager.prototype.packet = function(packet){
  577. debug('writing packet %j', packet);
  578. var self = this;
  579. if (!self.encoding) {
  580. // encode, then write to engine with result
  581. self.encoding = true;
  582. this.encoder.encode(packet, function(encodedPackets) {
  583. for (var i = 0; i < encodedPackets.length; i++) {
  584. self.engine.write(encodedPackets[i]);
  585. }
  586. self.encoding = false;
  587. self.processPacketQueue();
  588. });
  589. } else { // add packet to the queue
  590. self.packetBuffer.push(packet);
  591. }
  592. };
  593. /**
  594. * If packet buffer is non-empty, begins encoding the
  595. * next packet in line.
  596. *
  597. * @api private
  598. */
  599. Manager.prototype.processPacketQueue = function() {
  600. if (this.packetBuffer.length > 0 && !this.encoding) {
  601. var pack = this.packetBuffer.shift();
  602. this.packet(pack);
  603. }
  604. };
  605. /**
  606. * Clean up transport subscriptions and packet buffer.
  607. *
  608. * @api private
  609. */
  610. Manager.prototype.cleanup = function(){
  611. var sub;
  612. while (sub = this.subs.shift()) sub.destroy();
  613. this.packetBuffer = [];
  614. this.encoding = false;
  615. this.decoder.destroy();
  616. };
  617. /**
  618. * Close the current socket.
  619. *
  620. * @api private
  621. */
  622. Manager.prototype.close =
  623. Manager.prototype.disconnect = function(){
  624. this.skipReconnect = true;
  625. this.engine.close();
  626. };
  627. /**
  628. * Called upon engine close.
  629. *
  630. * @api private
  631. */
  632. Manager.prototype.onclose = function(reason){
  633. debug('close');
  634. this.cleanup();
  635. this.readyState = 'closed';
  636. this.emit('close', reason);
  637. if (this._reconnection && !this.skipReconnect) {
  638. this.reconnect();
  639. }
  640. };
  641. /**
  642. * Attempt a reconnection.
  643. *
  644. * @api private
  645. */
  646. Manager.prototype.reconnect = function(){
  647. if (this.reconnecting) return this;
  648. var self = this;
  649. this.attempts++;
  650. if (this.attempts > this._reconnectionAttempts) {
  651. debug('reconnect failed');
  652. this.emitAll('reconnect_failed');
  653. this.reconnecting = false;
  654. } else {
  655. var delay = this.attempts * this.reconnectionDelay();
  656. delay = Math.min(delay, this.reconnectionDelayMax());
  657. debug('will wait %dms before reconnect attempt', delay);
  658. this.reconnecting = true;
  659. var timer = setTimeout(function(){
  660. debug('attempting reconnect');
  661. self.emitAll('reconnect_attempt', self.attempts);
  662. self.emitAll('reconnecting', self.attempts);
  663. self.open(function(err){
  664. if (err) {
  665. debug('reconnect attempt error');
  666. self.reconnecting = false;
  667. self.reconnect();
  668. self.emitAll('reconnect_error', err.data);
  669. } else {
  670. debug('reconnect success');
  671. self.onreconnect();
  672. }
  673. });
  674. }, delay);
  675. this.subs.push({
  676. destroy: function(){
  677. clearTimeout(timer);
  678. }
  679. });
  680. }
  681. };
  682. /**
  683. * Called upon successful reconnect.
  684. *
  685. * @api private
  686. */
  687. Manager.prototype.onreconnect = function(){
  688. var attempt = this.attempts;
  689. this.attempts = 0;
  690. this.reconnecting = false;
  691. this.emitAll('reconnect', attempt);
  692. };
  693. },{"./on":6,"./socket":7,"./url":8,"component-bind":9,"component-emitter":10,"debug":11,"engine.io-client":12,"object-component":38,"socket.io-parser":41}],6:[function(_dereq_,module,exports){
  694. /**
  695. * Module exports.
  696. */
  697. module.exports = on;
  698. /**
  699. * Helper for subscriptions.
  700. *
  701. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  702. * @param {String} event name
  703. * @param {Function} callback
  704. * @api public
  705. */
  706. function on(obj, ev, fn) {
  707. obj.on(ev, fn);
  708. return {
  709. destroy: function(){
  710. obj.removeListener(ev, fn);
  711. }
  712. };
  713. }
  714. },{}],7:[function(_dereq_,module,exports){
  715. /**
  716. * Module dependencies.
  717. */
  718. var parser = _dereq_('socket.io-parser');
  719. var Emitter = _dereq_('component-emitter');
  720. var toArray = _dereq_('to-array');
  721. var on = _dereq_('./on');
  722. var bind = _dereq_('component-bind');
  723. var debug = _dereq_('debug')('socket.io-client:socket');
  724. var hasBin = _dereq_('has-binary-data');
  725. var indexOf = _dereq_('indexof');
  726. /**
  727. * Module exports.
  728. */
  729. module.exports = exports = Socket;
  730. /**
  731. * Internal events (blacklisted).
  732. * These events can't be emitted by the user.
  733. *
  734. * @api private
  735. */
  736. var events = {
  737. connect: 1,
  738. connect_error: 1,
  739. connect_timeout: 1,
  740. disconnect: 1,
  741. error: 1,
  742. reconnect: 1,
  743. reconnect_attempt: 1,
  744. reconnect_failed: 1,
  745. reconnect_error: 1,
  746. reconnecting: 1
  747. };
  748. /**
  749. * Shortcut to `Emitter#emit`.
  750. */
  751. var emit = Emitter.prototype.emit;
  752. /**
  753. * `Socket` constructor.
  754. *
  755. * @api public
  756. */
  757. function Socket(io, nsp){
  758. this.io = io;
  759. this.nsp = nsp;
  760. this.json = this; // compat
  761. this.ids = 0;
  762. this.acks = {};
  763. this.open();
  764. this.receiveBuffer = [];
  765. this.sendBuffer = [];
  766. this.connected = false;
  767. this.disconnected = true;
  768. this.subEvents();
  769. }
  770. /**
  771. * Mix in `Emitter`.
  772. */
  773. Emitter(Socket.prototype);
  774. /**
  775. * Subscribe to open, close and packet events
  776. *
  777. * @api private
  778. */
  779. Socket.prototype.subEvents = function() {
  780. var io = this.io;
  781. this.subs = [
  782. on(io, 'open', bind(this, 'onopen')),
  783. on(io, 'packet', bind(this, 'onpacket')),
  784. on(io, 'close', bind(this, 'onclose'))
  785. ];
  786. };
  787. /**
  788. * Called upon engine `open`.
  789. *
  790. * @api private
  791. */
  792. Socket.prototype.open =
  793. Socket.prototype.connect = function(){
  794. if (this.connected) return this;
  795. this.io.open(); // ensure open
  796. if ('open' == this.io.readyState) this.onopen();
  797. return this;
  798. };
  799. /**
  800. * Sends a `message` event.
  801. *
  802. * @return {Socket} self
  803. * @api public
  804. */
  805. Socket.prototype.send = function(){
  806. var args = toArray(arguments);
  807. args.unshift('message');
  808. this.emit.apply(this, args);
  809. return this;
  810. };
  811. /**
  812. * Override `emit`.
  813. * If the event is in `events`, it's emitted normally.
  814. *
  815. * @param {String} event name
  816. * @return {Socket} self
  817. * @api public
  818. */
  819. Socket.prototype.emit = function(ev){
  820. if (events.hasOwnProperty(ev)) {
  821. emit.apply(this, arguments);
  822. return this;
  823. }
  824. var args = toArray(arguments);
  825. var parserType = parser.EVENT; // default
  826. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  827. var packet = { type: parserType, data: args };
  828. // event ack callback
  829. if ('function' == typeof args[args.length - 1]) {
  830. debug('emitting packet with ack id %d', this.ids);
  831. this.acks[this.ids] = args.pop();
  832. packet.id = this.ids++;
  833. }
  834. if (this.connected) {
  835. this.packet(packet);
  836. } else {
  837. this.sendBuffer.push(packet);
  838. }
  839. return this;
  840. };
  841. /**
  842. * Sends a packet.
  843. *
  844. * @param {Object} packet
  845. * @api private
  846. */
  847. Socket.prototype.packet = function(packet){
  848. packet.nsp = this.nsp;
  849. this.io.packet(packet);
  850. };
  851. /**
  852. * "Opens" the socket.
  853. *
  854. * @api private
  855. */
  856. Socket.prototype.onopen = function(){
  857. debug('transport is open - connecting');
  858. // write connect packet if necessary
  859. if ('/' != this.nsp) {
  860. this.packet({ type: parser.CONNECT });
  861. }
  862. };
  863. /**
  864. * Called upon engine `close`.
  865. *
  866. * @param {String} reason
  867. * @api private
  868. */
  869. Socket.prototype.onclose = function(reason){
  870. debug('close (%s)', reason);
  871. this.connected = false;
  872. this.disconnected = true;
  873. this.emit('disconnect', reason);
  874. };
  875. /**
  876. * Called with socket packet.
  877. *
  878. * @param {Object} packet
  879. * @api private
  880. */
  881. Socket.prototype.onpacket = function(packet){
  882. if (packet.nsp != this.nsp) return;
  883. switch (packet.type) {
  884. case parser.CONNECT:
  885. this.onconnect();
  886. break;
  887. case parser.EVENT:
  888. this.onevent(packet);
  889. break;
  890. case parser.BINARY_EVENT:
  891. this.onevent(packet);
  892. break;
  893. case parser.ACK:
  894. this.onack(packet);
  895. break;
  896. case parser.BINARY_ACK:
  897. this.onack(packet);
  898. break;
  899. case parser.DISCONNECT:
  900. this.ondisconnect();
  901. break;
  902. case parser.ERROR:
  903. this.emit('error', packet.data);
  904. break;
  905. }
  906. };
  907. /**
  908. * Called upon a server event.
  909. *
  910. * @param {Object} packet
  911. * @api private
  912. */
  913. Socket.prototype.onevent = function(packet){
  914. var args = packet.data || [];
  915. debug('emitting event %j', args);
  916. if (null != packet.id) {
  917. debug('attaching ack callback to event');
  918. args.push(this.ack(packet.id));
  919. }
  920. if (this.connected) {
  921. emit.apply(this, args);
  922. } else {
  923. this.receiveBuffer.push(args);
  924. }
  925. };
  926. /**
  927. * Produces an ack callback to emit with an event.
  928. *
  929. * @api private
  930. */
  931. Socket.prototype.ack = function(id){
  932. var self = this;
  933. var sent = false;
  934. return function(){
  935. // prevent double callbacks
  936. if (sent) return;
  937. sent = true;
  938. var args = toArray(arguments);
  939. debug('sending ack %j', args);
  940. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  941. self.packet({
  942. type: type,
  943. id: id,
  944. data: args
  945. });
  946. };
  947. };
  948. /**
  949. * Called upon a server acknowlegement.
  950. *
  951. * @param {Object} packet
  952. * @api private
  953. */
  954. Socket.prototype.onack = function(packet){
  955. debug('calling ack %s with %j', packet.id, packet.data);
  956. var fn = this.acks[packet.id];
  957. fn.apply(this, packet.data);
  958. delete this.acks[packet.id];
  959. };
  960. /**
  961. * Called upon server connect.
  962. *
  963. * @api private
  964. */
  965. Socket.prototype.onconnect = function(){
  966. this.connected = true;
  967. this.disconnected = false;
  968. this.emit('connect');
  969. this.emitBuffered();
  970. };
  971. /**
  972. * Emit buffered events (received and emitted).
  973. *
  974. * @api private
  975. */
  976. Socket.prototype.emitBuffered = function(){
  977. var i;
  978. for (i = 0; i < this.receiveBuffer.length; i++) {
  979. emit.apply(this, this.receiveBuffer[i]);
  980. }
  981. this.receiveBuffer = [];
  982. for (i = 0; i < this.sendBuffer.length; i++) {
  983. this.packet(this.sendBuffer[i]);
  984. }
  985. this.sendBuffer = [];
  986. };
  987. /**
  988. * Called upon server disconnect.
  989. *
  990. * @api private
  991. */
  992. Socket.prototype.ondisconnect = function(){
  993. debug('server disconnect (%s)', this.nsp);
  994. this.destroy();
  995. this.onclose('io server disconnect');
  996. };
  997. /**
  998. * Called upon forced client/server side disconnections,
  999. * this method ensures the manager stops tracking us and
  1000. * that reconnections don't get triggered for this.
  1001. *
  1002. * @api private.
  1003. */
  1004. Socket.prototype.destroy = function(){
  1005. // clean subscriptions to avoid reconnections
  1006. for (var i = 0; i < this.subs.length; i++) {
  1007. this.subs[i].destroy();
  1008. }
  1009. this.io.destroy(this);
  1010. };
  1011. /**
  1012. * Disconnects the socket manually.
  1013. *
  1014. * @return {Socket} self
  1015. * @api public
  1016. */
  1017. Socket.prototype.close =
  1018. Socket.prototype.disconnect = function(){
  1019. if (!this.connected) return this;
  1020. debug('performing disconnect (%s)', this.nsp);
  1021. this.packet({ type: parser.DISCONNECT });
  1022. // remove socket from pool
  1023. this.destroy();
  1024. // fire events
  1025. this.onclose('io client disconnect');
  1026. return this;
  1027. };
  1028. },{"./on":6,"component-bind":9,"component-emitter":10,"debug":11,"has-binary-data":35,"indexof":37,"socket.io-parser":41,"to-array":45}],8:[function(_dereq_,module,exports){
  1029. (function (global){
  1030. /**
  1031. * Module dependencies.
  1032. */
  1033. var parseuri = _dereq_('parseuri');
  1034. var debug = _dereq_('debug')('socket.io-client:url');
  1035. /**
  1036. * Module exports.
  1037. */
  1038. module.exports = url;
  1039. /**
  1040. * URL parser.
  1041. *
  1042. * @param {String} url
  1043. * @param {Object} An object meant to mimic window.location.
  1044. * Defaults to window.location.
  1045. * @api public
  1046. */
  1047. function url(uri, loc){
  1048. var obj = uri;
  1049. // default to window.location
  1050. var loc = loc || global.location;
  1051. if (null == uri) uri = loc.protocol + '//' + loc.hostname;
  1052. // relative path support
  1053. if ('string' == typeof uri) {
  1054. if ('/' == uri.charAt(0)) {
  1055. if ('undefined' != typeof loc) {
  1056. uri = loc.hostname + uri;
  1057. }
  1058. }
  1059. if (!/^(https?|wss?):\/\//.test(uri)) {
  1060. debug('protocol-less url %s', uri);
  1061. if ('undefined' != typeof loc) {
  1062. uri = loc.protocol + '//' + uri;
  1063. } else {
  1064. uri = 'https://' + uri;
  1065. }
  1066. }
  1067. // parse
  1068. debug('parse %s', uri);
  1069. obj = parseuri(uri);
  1070. }
  1071. // make sure we treat `localhost:80` and `localhost` equally
  1072. if (!obj.port) {
  1073. if (/^(http|ws)$/.test(obj.protocol)) {
  1074. obj.port = '80';
  1075. }
  1076. else if (/^(http|ws)s$/.test(obj.protocol)) {
  1077. obj.port = '443';
  1078. }
  1079. }
  1080. obj.path = obj.path || '/';
  1081. // define unique id
  1082. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  1083. // define href
  1084. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  1085. return obj;
  1086. }
  1087. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1088. },{"debug":11,"parseuri":39}],9:[function(_dereq_,module,exports){
  1089. /**
  1090. * Slice reference.
  1091. */
  1092. var slice = [].slice;
  1093. /**
  1094. * Bind `obj` to `fn`.
  1095. *
  1096. * @param {Object} obj
  1097. * @param {Function|String} fn or string
  1098. * @return {Function}
  1099. * @api public
  1100. */
  1101. module.exports = function(obj, fn){
  1102. if ('string' == typeof fn) fn = obj[fn];
  1103. if ('function' != typeof fn) throw new Error('bind() requires a function');
  1104. var args = slice.call(arguments, 2);
  1105. return function(){
  1106. return fn.apply(obj, args.concat(slice.call(arguments)));
  1107. }
  1108. };
  1109. },{}],10:[function(_dereq_,module,exports){
  1110. /**
  1111. * Expose `Emitter`.
  1112. */
  1113. module.exports = Emitter;
  1114. /**
  1115. * Initialize a new `Emitter`.
  1116. *
  1117. * @api public
  1118. */
  1119. function Emitter(obj) {
  1120. if (obj) return mixin(obj);
  1121. };
  1122. /**
  1123. * Mixin the emitter properties.
  1124. *
  1125. * @param {Object} obj
  1126. * @return {Object}
  1127. * @api private
  1128. */
  1129. function mixin(obj) {
  1130. for (var key in Emitter.prototype) {
  1131. obj[key] = Emitter.prototype[key];
  1132. }
  1133. return obj;
  1134. }
  1135. /**
  1136. * Listen on the given `event` with `fn`.
  1137. *
  1138. * @param {String} event
  1139. * @param {Function} fn
  1140. * @return {Emitter}
  1141. * @api public
  1142. */
  1143. Emitter.prototype.on =
  1144. Emitter.prototype.addEventListener = function(event, fn){
  1145. this._callbacks = this._callbacks || {};
  1146. (this._callbacks[event] = this._callbacks[event] || [])
  1147. .push(fn);
  1148. return this;
  1149. };
  1150. /**
  1151. * Adds an `event` listener that will be invoked a single
  1152. * time then automatically removed.
  1153. *
  1154. * @param {String} event
  1155. * @param {Function} fn
  1156. * @return {Emitter}
  1157. * @api public
  1158. */
  1159. Emitter.prototype.once = function(event, fn){
  1160. var self = this;
  1161. this._callbacks = this._callbacks || {};
  1162. function on() {
  1163. self.off(event, on);
  1164. fn.apply(this, arguments);
  1165. }
  1166. on.fn = fn;
  1167. this.on(event, on);
  1168. return this;
  1169. };
  1170. /**
  1171. * Remove the given callback for `event` or all
  1172. * registered callbacks.
  1173. *
  1174. * @param {String} event
  1175. * @param {Function} fn
  1176. * @return {Emitter}
  1177. * @api public
  1178. */
  1179. Emitter.prototype.off =
  1180. Emitter.prototype.removeListener =
  1181. Emitter.prototype.removeAllListeners =
  1182. Emitter.prototype.removeEventListener = function(event, fn){
  1183. this._callbacks = this._callbacks || {};
  1184. // all
  1185. if (0 == arguments.length) {
  1186. this._callbacks = {};
  1187. return this;
  1188. }
  1189. // specific event
  1190. var callbacks = this._callbacks[event];
  1191. if (!callbacks) return this;
  1192. // remove all handlers
  1193. if (1 == arguments.length) {
  1194. delete this._callbacks[event];
  1195. return this;
  1196. }
  1197. // remove specific handler
  1198. var cb;
  1199. for (var i = 0; i < callbacks.length; i++) {
  1200. cb = callbacks[i];
  1201. if (cb === fn || cb.fn === fn) {
  1202. callbacks.splice(i, 1);
  1203. break;
  1204. }
  1205. }
  1206. return this;
  1207. };
  1208. /**
  1209. * Emit `event` with the given args.
  1210. *
  1211. * @param {String} event
  1212. * @param {Mixed} ...
  1213. * @return {Emitter}
  1214. */
  1215. Emitter.prototype.emit = function(event){
  1216. this._callbacks = this._callbacks || {};
  1217. var args = [].slice.call(arguments, 1)
  1218. , callbacks = this._callbacks[event];
  1219. if (callbacks) {
  1220. callbacks = callbacks.slice(0);
  1221. for (var i = 0, len = callbacks.length; i < len; ++i) {
  1222. callbacks[i].apply(this, args);
  1223. }
  1224. }
  1225. return this;
  1226. };
  1227. /**
  1228. * Return array of callbacks for `event`.
  1229. *
  1230. * @param {String} event
  1231. * @return {Array}
  1232. * @api public
  1233. */
  1234. Emitter.prototype.listeners = function(event){
  1235. this._callbacks = this._callbacks || {};
  1236. return this._callbacks[event] || [];
  1237. };
  1238. /**
  1239. * Check if this emitter has `event` handlers.
  1240. *
  1241. * @param {String} event
  1242. * @return {Boolean}
  1243. * @api public
  1244. */
  1245. Emitter.prototype.hasListeners = function(event){
  1246. return !! this.listeners(event).length;
  1247. };
  1248. },{}],11:[function(_dereq_,module,exports){
  1249. /**
  1250. * Expose `debug()` as the module.
  1251. */
  1252. module.exports = debug;
  1253. /**
  1254. * Create a debugger with the given `name`.
  1255. *
  1256. * @param {String} name
  1257. * @return {Type}
  1258. * @api public
  1259. */
  1260. function debug(name) {
  1261. if (!debug.enabled(name)) return function(){};
  1262. return function(fmt){
  1263. fmt = coerce(fmt);
  1264. var curr = new Date;
  1265. var ms = curr - (debug[name] || curr);
  1266. debug[name] = curr;
  1267. fmt = name
  1268. + ' '
  1269. + fmt
  1270. + ' +' + debug.humanize(ms);
  1271. // This hackery is required for IE8
  1272. // where `console.log` doesn't have 'apply'
  1273. window.console
  1274. && console.log
  1275. && Function.prototype.apply.call(console.log, console, arguments);
  1276. }
  1277. }
  1278. /**
  1279. * The currently active debug mode names.
  1280. */
  1281. debug.names = [];
  1282. debug.skips = [];
  1283. /**
  1284. * Enables a debug mode by name. This can include modes
  1285. * separated by a colon and wildcards.
  1286. *
  1287. * @param {String} name
  1288. * @api public
  1289. */
  1290. debug.enable = function(name) {
  1291. try {
  1292. localStorage.debug = name;
  1293. } catch(e){}
  1294. var split = (name || '').split(/[\s,]+/)
  1295. , len = split.length;
  1296. for (var i = 0; i < len; i++) {
  1297. name = split[i].replace('*', '.*?');
  1298. if (name[0] === '-') {
  1299. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  1300. }
  1301. else {
  1302. debug.names.push(new RegExp('^' + name + '$'));
  1303. }
  1304. }
  1305. };
  1306. /**
  1307. * Disable debug output.
  1308. *
  1309. * @api public
  1310. */
  1311. debug.disable = function(){
  1312. debug.enable('');
  1313. };
  1314. /**
  1315. * Humanize the given `ms`.
  1316. *
  1317. * @param {Number} m
  1318. * @return {String}
  1319. * @api private
  1320. */
  1321. debug.humanize = function(ms) {
  1322. var sec = 1000
  1323. , min = 60 * 1000
  1324. , hour = 60 * min;
  1325. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  1326. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  1327. if (ms >= sec) return (ms / sec | 0) + 's';
  1328. return ms + 'ms';
  1329. };
  1330. /**
  1331. * Returns true if the given mode name is enabled, false otherwise.
  1332. *
  1333. * @param {String} name
  1334. * @return {Boolean}
  1335. * @api public
  1336. */
  1337. debug.enabled = function(name) {
  1338. for (var i = 0, len = debug.skips.length; i < len; i++) {
  1339. if (debug.skips[i].test(name)) {
  1340. return false;
  1341. }
  1342. }
  1343. for (var i = 0, len = debug.names.length; i < len; i++) {
  1344. if (debug.names[i].test(name)) {
  1345. return true;
  1346. }
  1347. }
  1348. return false;
  1349. };
  1350. /**
  1351. * Coerce `val`.
  1352. */
  1353. function coerce(val) {
  1354. if (val instanceof Error) return val.stack || val.message;
  1355. return val;
  1356. }
  1357. // persist
  1358. try {
  1359. if (window.localStorage) debug.enable(localStorage.debug);
  1360. } catch(e){}
  1361. },{}],12:[function(_dereq_,module,exports){
  1362. module.exports = _dereq_('./lib/');
  1363. },{"./lib/":13}],13:[function(_dereq_,module,exports){
  1364. module.exports = _dereq_('./socket');
  1365. /**
  1366. * Exports parser
  1367. *
  1368. * @api public
  1369. *
  1370. */
  1371. module.exports.parser = _dereq_('engine.io-parser');
  1372. },{"./socket":14,"engine.io-parser":23}],14:[function(_dereq_,module,exports){
  1373. (function (global){
  1374. /**
  1375. * Module dependencies.
  1376. */
  1377. var transports = _dereq_('./transports');
  1378. var Emitter = _dereq_('component-emitter');
  1379. var debug = _dereq_('debug')('engine.io-client:socket');
  1380. var index = _dereq_('indexof');
  1381. var parser = _dereq_('engine.io-parser');
  1382. var parseuri = _dereq_('parseuri');
  1383. var parsejson = _dereq_('parsejson');
  1384. var parseqs = _dereq_('parseqs');
  1385. /**
  1386. * Module exports.
  1387. */
  1388. module.exports = Socket;
  1389. /**
  1390. * Noop function.
  1391. *
  1392. * @api private
  1393. */
  1394. function noop(){}
  1395. /**
  1396. * Socket constructor.
  1397. *
  1398. * @param {String|Object} uri or options
  1399. * @param {Object} options
  1400. * @api public
  1401. */
  1402. function Socket(uri, opts){
  1403. if (!(this instanceof Socket)) return new Socket(uri, opts);
  1404. opts = opts || {};
  1405. if (uri && 'object' == typeof uri) {
  1406. opts = uri;
  1407. uri = null;
  1408. }
  1409. if (uri) {
  1410. uri = parseuri(uri);
  1411. opts.host = uri.host;
  1412. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  1413. opts.port = uri.port;
  1414. if (uri.query) opts.query = uri.query;
  1415. }
  1416. this.secure = null != opts.secure ? opts.secure :
  1417. (global.location && 'https:' == location.protocol);
  1418. if (opts.host) {
  1419. var pieces = opts.host.split(':');
  1420. opts.hostname = pieces.shift();
  1421. if (pieces.length) opts.port = pieces.pop();
  1422. }
  1423. this.agent = opts.agent || false;
  1424. this.hostname = opts.hostname ||
  1425. (global.location ? location.hostname : 'localhost');
  1426. this.port = opts.port || (global.location && location.port ?
  1427. location.port :
  1428. (this.secure ? 443 : 80));
  1429. this.query = opts.query || {};
  1430. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  1431. this.upgrade = false !== opts.upgrade;
  1432. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  1433. this.forceJSONP = !!opts.forceJSONP;
  1434. this.forceBase64 = !!opts.forceBase64;
  1435. this.timestampParam = opts.timestampParam || 't';
  1436. this.timestampRequests = opts.timestampRequests;
  1437. this.transports = opts.transports || ['polling', 'websocket'];
  1438. this.readyState = '';
  1439. this.writeBuffer = [];
  1440. this.callbackBuffer = [];
  1441. this.policyPort = opts.policyPort || 843;
  1442. this.rememberUpgrade = opts.rememberUpgrade || false;
  1443. this.open();
  1444. this.binaryType = null;
  1445. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  1446. }
  1447. Socket.priorWebsocketSuccess = false;
  1448. /**
  1449. * Mix in `Emitter`.
  1450. */
  1451. Emitter(Socket.prototype);
  1452. /**
  1453. * Protocol version.
  1454. *
  1455. * @api public
  1456. */
  1457. Socket.protocol = parser.protocol; // this is an int
  1458. /**
  1459. * Expose deps for legacy compatibility
  1460. * and standalone browser access.
  1461. */
  1462. Socket.Socket = Socket;
  1463. Socket.Transport = _dereq_('./transport');
  1464. Socket.transports = _dereq_('./transports');
  1465. Socket.parser = _dereq_('engine.io-parser');
  1466. /**
  1467. * Creates transport of the given type.
  1468. *
  1469. * @param {String} transport name
  1470. * @return {Transport}
  1471. * @api private
  1472. */
  1473. Socket.prototype.createTransport = function (name) {
  1474. debug('creating transport "%s"', name);
  1475. var query = clone(this.query);
  1476. // append engine.io protocol identifier
  1477. query.EIO = parser.protocol;
  1478. // transport name
  1479. query.transport = name;
  1480. // session id if we already have one
  1481. if (this.id) query.sid = this.id;
  1482. var transport = new transports[name]({
  1483. agent: this.agent,
  1484. hostname: this.hostname,
  1485. port: this.port,
  1486. secure: this.secure,
  1487. path: this.path,
  1488. query: query,
  1489. forceJSONP: this.forceJSONP,
  1490. forceBase64: this.forceBase64,
  1491. timestampRequests: this.timestampRequests,
  1492. timestampParam: this.timestampParam,
  1493. policyPort: this.policyPort,
  1494. socket: this
  1495. });
  1496. return transport;
  1497. };
  1498. function clone (obj) {
  1499. var o = {};
  1500. for (var i in obj) {
  1501. if (obj.hasOwnProperty(i)) {
  1502. o[i] = obj[i];
  1503. }
  1504. }
  1505. return o;
  1506. }
  1507. /**
  1508. * Initializes transport to use and starts probe.
  1509. *
  1510. * @api private
  1511. */
  1512. Socket.prototype.open = function () {
  1513. var transport;
  1514. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  1515. transport = 'websocket';
  1516. } else {
  1517. transport = this.transports[0];
  1518. }
  1519. this.readyState = 'opening';
  1520. var transport = this.createTransport(transport);
  1521. transport.open();
  1522. this.setTransport(transport);
  1523. };
  1524. /**
  1525. * Sets the current transport. Disables the existing one (if any).
  1526. *
  1527. * @api private
  1528. */
  1529. Socket.prototype.setTransport = function(transport){
  1530. debug('setting transport %s', transport.name);
  1531. var self = this;
  1532. if (this.transport) {
  1533. debug('clearing existing transport %s', this.transport.name);
  1534. this.transport.removeAllListeners();
  1535. }
  1536. // set up transport
  1537. this.transport = transport;
  1538. // set up transport listeners
  1539. transport
  1540. .on('drain', function(){
  1541. self.onDrain();
  1542. })
  1543. .on('packet', function(packet){
  1544. self.onPacket(packet);
  1545. })
  1546. .on('error', function(e){
  1547. self.onError(e);
  1548. })
  1549. .on('close', function(){
  1550. self.onClose('transport close');
  1551. });
  1552. };
  1553. /**
  1554. * Probes a transport.
  1555. *
  1556. * @param {String} transport name
  1557. * @api private
  1558. */
  1559. Socket.prototype.probe = function (name) {
  1560. debug('probing transport "%s"', name);
  1561. var transport = this.createTransport(name, { probe: 1 })
  1562. , failed = false
  1563. , self = this;
  1564. Socket.priorWebsocketSuccess = false;
  1565. function onTransportOpen(){
  1566. if (self.onlyBinaryUpgrades) {
  1567. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  1568. failed = failed || upgradeLosesBinary;
  1569. }
  1570. if (failed) return;
  1571. debug('probe transport "%s" opened', name);
  1572. transport.send([{ type: 'ping', data: 'probe' }]);
  1573. transport.once('packet', function (msg) {
  1574. if (failed) return;
  1575. if ('pong' == msg.type && 'probe' == msg.data) {
  1576. debug('probe transport "%s" pong', name);
  1577. self.upgrading = true;
  1578. self.emit('upgrading', transport);
  1579. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  1580. debug('pausing current transport "%s"', self.transport.name);
  1581. self.transport.pause(function () {
  1582. if (failed) return;
  1583. if ('closed' == self.readyState || 'closing' == self.readyState) {
  1584. return;
  1585. }
  1586. debug('changing transport and sending upgrade packet');
  1587. cleanup();
  1588. self.setTransport(transport);
  1589. transport.send([{ type: 'upgrade' }]);
  1590. self.emit('upgrade', transport);
  1591. transport = null;
  1592. self.upgrading = false;
  1593. self.flush();
  1594. });
  1595. } else {
  1596. debug('probe transport "%s" failed', name);
  1597. var err = new Error('probe error');
  1598. err.transport = transport.name;
  1599. self.emit('upgradeError', err);
  1600. }
  1601. });
  1602. }
  1603. function freezeTransport() {
  1604. if (failed) return;
  1605. // Any callback called by transport should be ignored since now
  1606. failed = true;
  1607. cleanup();
  1608. transport.close();
  1609. transport = null;
  1610. }
  1611. //Handle any error that happens while probing
  1612. function onerror(err) {
  1613. var error = new Error('probe error: ' + err);
  1614. error.transport = transport.name;
  1615. freezeTransport();
  1616. debug('probe transport "%s" failed because of error: %s', name, err);
  1617. self.emit('upgradeError', error);
  1618. }
  1619. function onTransportClose(){
  1620. onerror("transport closed");
  1621. }
  1622. //When the socket is closed while we're probing
  1623. function onclose(){
  1624. onerror("socket closed");
  1625. }
  1626. //When the socket is upgraded while we're probing
  1627. function onupgrade(to){
  1628. if (transport && to.name != transport.name) {
  1629. debug('"%s" works - aborting "%s"', to.name, transport.name);
  1630. freezeTransport();
  1631. }
  1632. }
  1633. //Remove all listeners on the transport and on self
  1634. function cleanup(){
  1635. transport.removeListener('open', onTransportOpen);
  1636. transport.removeListener('error', onerror);
  1637. transport.removeListener('close', onTransportClose);
  1638. self.removeListener('close', onclose);
  1639. self.removeListener('upgrading', onupgrade);
  1640. }
  1641. transport.once('open', onTransportOpen);
  1642. transport.once('error', onerror);
  1643. transport.once('close', onTransportClose);
  1644. this.once('close', onclose);
  1645. this.once('upgrading', onupgrade);
  1646. transport.open();
  1647. };
  1648. /**
  1649. * Called when connection is deemed open.
  1650. *
  1651. * @api public
  1652. */
  1653. Socket.prototype.onOpen = function () {
  1654. debug('socket open');
  1655. this.readyState = 'open';
  1656. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  1657. this.emit('open');
  1658. this.flush();
  1659. // we check for `readyState` in case an `open`
  1660. // listener already closed the socket
  1661. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  1662. debug('starting upgrade probes');
  1663. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  1664. this.probe(this.upgrades[i]);
  1665. }
  1666. }
  1667. };
  1668. /**
  1669. * Handles a packet.
  1670. *
  1671. * @api private
  1672. */
  1673. Socket.prototype.onPacket = function (packet) {
  1674. if ('opening' == this.readyState || 'open' == this.readyState) {
  1675. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  1676. this.emit('packet', packet);
  1677. // Socket is live - any packet counts
  1678. this.emit('heartbeat');
  1679. switch (packet.type) {
  1680. case 'open':
  1681. this.onHandshake(parsejson(packet.data));
  1682. break;
  1683. case 'pong':
  1684. this.setPing();
  1685. break;
  1686. case 'error':
  1687. var err = new Error('server error');
  1688. err.code = packet.data;
  1689. this.emit('error', err);
  1690. break;
  1691. case 'message':
  1692. this.emit('data', packet.data);
  1693. this.emit('message', packet.data);
  1694. break;
  1695. }
  1696. } else {
  1697. debug('packet received with socket readyState "%s"', this.readyState);
  1698. }
  1699. };
  1700. /**
  1701. * Called upon handshake completion.
  1702. *
  1703. * @param {Object} handshake obj
  1704. * @api private
  1705. */
  1706. Socket.prototype.onHandshake = function (data) {
  1707. this.emit('handshake', data);
  1708. this.id = data.sid;
  1709. this.transport.query.sid = data.sid;
  1710. this.upgrades = this.filterUpgrades(data.upgrades);
  1711. this.pingInterval = data.pingInterval;
  1712. this.pingTimeout = data.pingTimeout;
  1713. this.onOpen();
  1714. // In case open handler closes socket
  1715. if ('closed' == this.readyState) return;
  1716. this.setPing();
  1717. // Prolong liveness of socket on heartbeat
  1718. this.removeListener('heartbeat', this.onHeartbeat);
  1719. this.on('heartbeat', this.onHeartbeat);
  1720. };
  1721. /**
  1722. * Resets ping timeout.
  1723. *
  1724. * @api private
  1725. */
  1726. Socket.prototype.onHeartbeat = function (timeout) {
  1727. clearTimeout(this.pingTimeoutTimer);
  1728. var self = this;
  1729. self.pingTimeoutTimer = setTimeout(function () {
  1730. if ('closed' == self.readyState) return;
  1731. self.onClose('ping timeout');
  1732. }, timeout || (self.pingInterval + self.pingTimeout));
  1733. };
  1734. /**
  1735. * Pings server every `this.pingInterval` and expects response
  1736. * within `this.pingTimeout` or closes connection.
  1737. *
  1738. * @api private
  1739. */
  1740. Socket.prototype.setPing = function () {
  1741. var self = this;
  1742. clearTimeout(self.pingIntervalTimer);
  1743. self.pingIntervalTimer = setTimeout(function () {
  1744. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  1745. self.ping();
  1746. self.onHeartbeat(self.pingTimeout);
  1747. }, self.pingInterval);
  1748. };
  1749. /**
  1750. * Sends a ping packet.
  1751. *
  1752. * @api public
  1753. */
  1754. Socket.prototype.ping = function () {
  1755. this.sendPacket('ping');
  1756. };
  1757. /**
  1758. * Called on `drain` event
  1759. *
  1760. * @api private
  1761. */
  1762. Socket.prototype.onDrain = function() {
  1763. for (var i = 0; i < this.prevBufferLen; i++) {
  1764. if (this.callbackBuffer[i]) {
  1765. this.callbackBuffer[i]();
  1766. }
  1767. }
  1768. this.writeBuffer.splice(0, this.prevBufferLen);
  1769. this.callbackBuffer.splice(0, this.prevBufferLen);
  1770. // setting prevBufferLen = 0 is very important
  1771. // for example, when upgrading, upgrade packet is sent over,
  1772. // and a nonzero prevBufferLen could cause problems on `drain`
  1773. this.prevBufferLen = 0;
  1774. if (this.writeBuffer.length == 0) {
  1775. this.emit('drain');
  1776. } else {
  1777. this.flush();
  1778. }
  1779. };
  1780. /**
  1781. * Flush write buffers.
  1782. *
  1783. * @api private
  1784. */
  1785. Socket.prototype.flush = function () {
  1786. if ('closed' != this.readyState && this.transport.writable &&
  1787. !this.upgrading && this.writeBuffer.length) {
  1788. debug('flushing %d packets in socket', this.writeBuffer.length);
  1789. this.transport.send(this.writeBuffer);
  1790. // keep track of current length of writeBuffer
  1791. // splice writeBuffer and callbackBuffer on `drain`
  1792. this.prevBufferLen = this.writeBuffer.length;
  1793. this.emit('flush');
  1794. }
  1795. };
  1796. /**
  1797. * Sends a message.
  1798. *
  1799. * @param {String} message.
  1800. * @param {Function} callback function.
  1801. * @return {Socket} for chaining.
  1802. * @api public
  1803. */
  1804. Socket.prototype.write =
  1805. Socket.prototype.send = function (msg, fn) {
  1806. this.sendPacket('message', msg, fn);
  1807. return this;
  1808. };
  1809. /**
  1810. * Sends a packet.
  1811. *
  1812. * @param {String} packet type.
  1813. * @param {String} data.
  1814. * @param {Function} callback function.
  1815. * @api private
  1816. */
  1817. Socket.prototype.sendPacket = function (type, data, fn) {
  1818. var packet = { type: type, data: data };
  1819. this.emit('packetCreate', packet);
  1820. this.writeBuffer.push(packet);
  1821. this.callbackBuffer.push(fn);
  1822. this.flush();
  1823. };
  1824. /**
  1825. * Closes the connection.
  1826. *
  1827. * @api private
  1828. */
  1829. Socket.prototype.close = function () {
  1830. if ('opening' == this.readyState || 'open' == this.readyState) {
  1831. this.onClose('forced close');
  1832. debug('socket closing - telling transport to close');
  1833. this.transport.close();
  1834. }
  1835. return this;
  1836. };
  1837. /**
  1838. * Called upon transport error
  1839. *
  1840. * @api private
  1841. */
  1842. Socket.prototype.onError = function (err) {
  1843. debug('socket error %j', err);
  1844. Socket.priorWebsocketSuccess = false;
  1845. this.emit('error', err);
  1846. this.onClose('transport error', err);
  1847. };
  1848. /**
  1849. * Called upon transport close.
  1850. *
  1851. * @api private
  1852. */
  1853. Socket.prototype.onClose = function (reason, desc) {
  1854. if ('opening' == this.readyState || 'open' == this.readyState) {
  1855. debug('socket close with reason: "%s"', reason);
  1856. var self = this;
  1857. // clear timers
  1858. clearTimeout(this.pingIntervalTimer);
  1859. clearTimeout(this.pingTimeoutTimer);
  1860. // clean buffers in next tick, so developers can still
  1861. // grab the buffers on `close` event
  1862. setTimeout(function() {
  1863. self.writeBuffer = [];
  1864. self.callbackBuffer = [];
  1865. self.prevBufferLen = 0;
  1866. }, 0);
  1867. // stop event from firing again for transport
  1868. this.transport.removeAllListeners('close');
  1869. // ensure transport won't stay open
  1870. this.transport.close();
  1871. // ignore further transport communication
  1872. this.transport.removeAllListeners();
  1873. // set ready state
  1874. this.readyState = 'closed';
  1875. // clear session id
  1876. this.id = null;
  1877. // emit close event
  1878. this.emit('close', reason, desc);
  1879. }
  1880. };
  1881. /**
  1882. * Filters upgrades, returning only those matching client transports.
  1883. *
  1884. * @param {Array} server upgrades
  1885. * @api private
  1886. *
  1887. */
  1888. Socket.prototype.filterUpgrades = function (upgrades) {
  1889. var filteredUpgrades = [];
  1890. for (var i = 0, j = upgrades.length; i<j; i++) {
  1891. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  1892. }
  1893. return filteredUpgrades;
  1894. };
  1895. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1896. },{"./transport":15,"./transports":16,"component-emitter":10,"debug":11,"engine.io-parser":23,"indexof":37,"parsejson":32,"parseqs":33,"parseuri":39}],15:[function(_dereq_,module,exports){
  1897. /**
  1898. * Module dependencies.
  1899. */
  1900. var parser = _dereq_('engine.io-parser');
  1901. var Emitter = _dereq_('component-emitter');
  1902. /**
  1903. * Module exports.
  1904. */
  1905. module.exports = Transport;
  1906. /**
  1907. * Transport abstract constructor.
  1908. *
  1909. * @param {Object} options.
  1910. * @api private
  1911. */
  1912. function Transport (opts) {
  1913. this.path = opts.path;
  1914. this.hostname = opts.hostname;
  1915. this.port = opts.port;
  1916. this.secure = opts.secure;
  1917. this.query = opts.query;
  1918. this.timestampParam = opts.timestampParam;
  1919. this.timestampRequests = opts.timestampRequests;
  1920. this.readyState = '';
  1921. this.agent = opts.agent || false;
  1922. this.socket = opts.socket;
  1923. }
  1924. /**
  1925. * Mix in `Emitter`.
  1926. */
  1927. Emitter(Transport.prototype);
  1928. /**
  1929. * A counter used to prevent collisions in the timestamps used
  1930. * for cache busting.
  1931. */
  1932. Transport.timestamps = 0;
  1933. /**
  1934. * Emits an error.
  1935. *
  1936. * @param {String} str
  1937. * @return {Transport} for chaining
  1938. * @api public
  1939. */
  1940. Transport.prototype.onError = function (msg, desc) {
  1941. var err = new Error(msg);
  1942. err.type = 'TransportError';
  1943. err.description = desc;
  1944. this.emit('error', err);
  1945. return this;
  1946. };
  1947. /**
  1948. * Opens the transport.
  1949. *
  1950. * @api public
  1951. */
  1952. Transport.prototype.open = function () {
  1953. if ('closed' == this.readyState || '' == this.readyState) {
  1954. this.readyState = 'opening';
  1955. this.doOpen();
  1956. }
  1957. return this;
  1958. };
  1959. /**
  1960. * Closes the transport.
  1961. *
  1962. * @api private
  1963. */
  1964. Transport.prototype.close = function () {
  1965. if ('opening' == this.readyState || 'open' == this.readyState) {
  1966. this.doClose();
  1967. this.onClose();
  1968. }
  1969. return this;
  1970. };
  1971. /**
  1972. * Sends multiple packets.
  1973. *
  1974. * @param {Array} packets
  1975. * @api private
  1976. */
  1977. Transport.prototype.send = function(packets){
  1978. if ('open' == this.readyState) {
  1979. this.write(packets);
  1980. } else {
  1981. throw new Error('Transport not open');
  1982. }
  1983. };
  1984. /**
  1985. * Called upon open
  1986. *
  1987. * @api private
  1988. */
  1989. Transport.prototype.onOpen = function () {
  1990. this.readyState = 'open';
  1991. this.writable = true;
  1992. this.emit('open');
  1993. };
  1994. /**
  1995. * Called with data.
  1996. *
  1997. * @param {String} data
  1998. * @api private
  1999. */
  2000. Transport.prototype.onData = function(data){
  2001. try {
  2002. var packet = parser.decodePacket(data, this.socket.binaryType);
  2003. this.onPacket(packet);
  2004. } catch(e){
  2005. e.data = data;
  2006. this.onError('parser decode error', e);
  2007. }
  2008. };
  2009. /**
  2010. * Called with a decoded packet.
  2011. */
  2012. Transport.prototype.onPacket = function (packet) {
  2013. this.emit('packet', packet);
  2014. };
  2015. /**
  2016. * Called upon close.
  2017. *
  2018. * @api private
  2019. */
  2020. Transport.prototype.onClose = function () {
  2021. this.readyState = 'closed';
  2022. this.emit('close');
  2023. };
  2024. },{"component-emitter":10,"engine.io-parser":23}],16:[function(_dereq_,module,exports){
  2025. (function (global){
  2026. /**
  2027. * Module dependencies
  2028. */
  2029. var XMLHttpRequest = _dereq_('xmlhttprequest');
  2030. var XHR = _dereq_('./polling-xhr');
  2031. var JSONP = _dereq_('./polling-jsonp');
  2032. var websocket = _dereq_('./websocket');
  2033. /**
  2034. * Export transports.
  2035. */
  2036. exports.polling = polling;
  2037. exports.websocket = websocket;
  2038. /**
  2039. * Polling transport polymorphic constructor.
  2040. * Decides on xhr vs jsonp based on feature detection.
  2041. *
  2042. * @api private
  2043. */
  2044. function polling(opts){
  2045. var xhr;
  2046. var xd = false;
  2047. if (global.location) {
  2048. var isSSL = 'https:' == location.protocol;
  2049. var port = location.port;
  2050. // some user agents have empty `location.port`
  2051. if (!port) {
  2052. port = isSSL ? 443 : 80;
  2053. }
  2054. xd = opts.hostname != location.hostname || port != opts.port;
  2055. }
  2056. opts.xdomain = xd;
  2057. xhr = new XMLHttpRequest(opts);
  2058. if ('open' in xhr && !opts.forceJSONP) {
  2059. return new XHR(opts);
  2060. } else {
  2061. return new JSONP(opts);
  2062. }
  2063. }
  2064. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2065. },{"./polling-jsonp":17,"./polling-xhr":18,"./websocket":20,"xmlhttprequest":21}],17:[function(_dereq_,module,exports){
  2066. (function (global){
  2067. /**
  2068. * Module requirements.
  2069. */
  2070. var Polling = _dereq_('./polling');
  2071. var inherit = _dereq_('component-inherit');
  2072. /**
  2073. * Module exports.
  2074. */
  2075. module.exports = JSONPPolling;
  2076. /**
  2077. * Cached regular expressions.
  2078. */
  2079. var rNewline = /\n/g;
  2080. var rEscapedNewline = /\\n/g;
  2081. /**
  2082. * Global JSONP callbacks.
  2083. */
  2084. var callbacks;
  2085. /**
  2086. * Callbacks count.
  2087. */
  2088. var index = 0;
  2089. /**
  2090. * Noop.
  2091. */
  2092. function empty () { }
  2093. /**
  2094. * JSONP Polling constructor.
  2095. *
  2096. * @param {Object} opts.
  2097. * @api public
  2098. */
  2099. function JSONPPolling (opts) {
  2100. Polling.call(this, opts);
  2101. this.query = this.query || {};
  2102. // define global callbacks array if not present
  2103. // we do this here (lazily) to avoid unneeded global pollution
  2104. if (!callbacks) {
  2105. // we need to consider multiple engines in the same page
  2106. if (!global.___eio) global.___eio = [];
  2107. callbacks = global.___eio;
  2108. }
  2109. // callback identifier
  2110. this.index = callbacks.length;
  2111. // add callback to jsonp global
  2112. var self = this;
  2113. callbacks.push(function (msg) {
  2114. self.onData(msg);
  2115. });
  2116. // append to query string
  2117. this.query.j = this.index;
  2118. // prevent spurious errors from being emitted when the window is unloaded
  2119. if (global.document && global.addEventListener) {
  2120. global.addEventListener('beforeunload', function () {
  2121. if (self.script) self.script.onerror = empty;
  2122. });
  2123. }
  2124. }
  2125. /**
  2126. * Inherits from Polling.
  2127. */
  2128. inherit(JSONPPolling, Polling);
  2129. /*
  2130. * JSONP only supports binary as base64 encoded strings
  2131. */
  2132. JSONPPolling.prototype.supportsBinary = false;
  2133. /**
  2134. * Closes the socket.
  2135. *
  2136. * @api private
  2137. */
  2138. JSONPPolling.prototype.doClose = function () {
  2139. if (this.script) {
  2140. this.script.parentNode.removeChild(this.script);
  2141. this.script = null;
  2142. }
  2143. if (this.form) {
  2144. this.form.parentNode.removeChild(this.form);
  2145. this.form = null;
  2146. }
  2147. Polling.prototype.doClose.call(this);
  2148. };
  2149. /**
  2150. * Starts a poll cycle.
  2151. *
  2152. * @api private
  2153. */
  2154. JSONPPolling.prototype.doPoll = function () {
  2155. var self = this;
  2156. var script = document.createElement('script');
  2157. if (this.script) {
  2158. this.script.parentNode.removeChild(this.script);
  2159. this.script = null;
  2160. }
  2161. script.async = true;
  2162. script.src = this.uri();
  2163. script.onerror = function(e){
  2164. self.onError('jsonp poll error',e);
  2165. };
  2166. var insertAt = document.getElementsByTagName('script')[0];
  2167. insertAt.parentNode.insertBefore(script, insertAt);
  2168. this.script = script;
  2169. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  2170. if (isUAgecko) {
  2171. setTimeout(function () {
  2172. var iframe = document.createElement('iframe');
  2173. document.body.appendChild(iframe);
  2174. document.body.removeChild(iframe);
  2175. }, 100);
  2176. }
  2177. };
  2178. /**
  2179. * Writes with a hidden iframe.
  2180. *
  2181. * @param {String} data to send
  2182. * @param {Function} called upon flush.
  2183. * @api private
  2184. */
  2185. JSONPPolling.prototype.doWrite = function (data, fn) {
  2186. var self = this;
  2187. if (!this.form) {
  2188. var form = document.createElement('form');
  2189. var area = document.createElement('textarea');
  2190. var id = this.iframeId = 'eio_iframe_' + this.index;
  2191. var iframe;
  2192. form.className = 'socketio';
  2193. form.style.position = 'absolute';
  2194. form.style.top = '-1000px';
  2195. form.style.left = '-1000px';
  2196. form.target = id;
  2197. form.method = 'POST';
  2198. form.setAttribute('accept-charset', 'utf-8');
  2199. area.name = 'd';
  2200. form.appendChild(area);
  2201. document.body.appendChild(form);
  2202. this.form = form;
  2203. this.area = area;
  2204. }
  2205. this.form.action = this.uri();
  2206. function complete () {
  2207. initIframe();
  2208. fn();
  2209. }
  2210. function initIframe () {
  2211. if (self.iframe) {
  2212. try {
  2213. self.form.removeChild(self.iframe);
  2214. } catch (e) {
  2215. self.onError('jsonp polling iframe removal error', e);
  2216. }
  2217. }
  2218. try {
  2219. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  2220. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  2221. iframe = document.createElement(html);
  2222. } catch (e) {
  2223. iframe = document.createElement('iframe');
  2224. iframe.name = self.iframeId;
  2225. iframe.src = 'javascript:0';
  2226. }
  2227. iframe.id = self.iframeId;
  2228. self.form.appendChild(iframe);
  2229. self.iframe = iframe;
  2230. }
  2231. initIframe();
  2232. // escape \n to prevent it from being converted into \r\n by some UAs
  2233. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  2234. data = data.replace(rEscapedNewline, '\\\n');
  2235. this.area.value = data.replace(rNewline, '\\n');
  2236. try {
  2237. this.form.submit();
  2238. } catch(e) {}
  2239. if (this.iframe.attachEvent) {
  2240. this.iframe.onreadystatechange = function(){
  2241. if (self.iframe.readyState == 'complete') {
  2242. complete();
  2243. }
  2244. };
  2245. } else {
  2246. this.iframe.onload = complete;
  2247. }
  2248. };
  2249. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2250. },{"./polling":19,"component-inherit":22}],18:[function(_dereq_,module,exports){
  2251. (function (global){
  2252. /**
  2253. * Module requirements.
  2254. */
  2255. var XMLHttpRequest = _dereq_('xmlhttprequest');
  2256. var Polling = _dereq_('./polling');
  2257. var Emitter = _dereq_('component-emitter');
  2258. var inherit = _dereq_('component-inherit');
  2259. var debug = _dereq_('debug')('engine.io-client:polling-xhr');
  2260. /**
  2261. * Module exports.
  2262. */
  2263. module.exports = XHR;
  2264. module.exports.Request = Request;
  2265. /**
  2266. * Empty function
  2267. */
  2268. function empty(){}
  2269. /**
  2270. * XHR Polling constructor.
  2271. *
  2272. * @param {Object} opts
  2273. * @api public
  2274. */
  2275. function XHR(opts){
  2276. Polling.call(this, opts);
  2277. if (global.location) {
  2278. var isSSL = 'https:' == location.protocol;
  2279. var port = location.port;
  2280. // some user agents have empty `location.port`
  2281. if (!port) {
  2282. port = isSSL ? 443 : 80;
  2283. }
  2284. this.xd = opts.hostname != global.location.hostname ||
  2285. port != opts.port;
  2286. }
  2287. }
  2288. /**
  2289. * Inherits from Polling.
  2290. */
  2291. inherit(XHR, Polling);
  2292. /**
  2293. * XHR supports binary
  2294. */
  2295. XHR.prototype.supportsBinary = true;
  2296. /**
  2297. * Creates a request.
  2298. *
  2299. * @param {String} method
  2300. * @api private
  2301. */
  2302. XHR.prototype.request = function(opts){
  2303. opts = opts || {};
  2304. opts.uri = this.uri();
  2305. opts.xd = this.xd;
  2306. opts.agent = this.agent || false;
  2307. opts.supportsBinary = this.supportsBinary;
  2308. return new Request(opts);
  2309. };
  2310. /**
  2311. * Sends data.
  2312. *
  2313. * @param {String} data to send.
  2314. * @param {Function} called upon flush.
  2315. * @api private
  2316. */
  2317. XHR.prototype.doWrite = function(data, fn){
  2318. var isBinary = typeof data !== 'string' && data !== undefined;
  2319. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  2320. var self = this;
  2321. req.on('success', fn);
  2322. req.on('error', function(err){
  2323. self.onError('xhr post error', err);
  2324. });
  2325. this.sendXhr = req;
  2326. };
  2327. /**
  2328. * Starts a poll cycle.
  2329. *
  2330. * @api private
  2331. */
  2332. XHR.prototype.doPoll = function(){
  2333. debug('xhr poll');
  2334. var req = this.request();
  2335. var self = this;
  2336. req.on('data', function(data){
  2337. self.onData(data);
  2338. });
  2339. req.on('error', function(err){
  2340. self.onError('xhr poll error', err);
  2341. });
  2342. this.pollXhr = req;
  2343. };
  2344. /**
  2345. * Request constructor
  2346. *
  2347. * @param {Object} options
  2348. * @api public
  2349. */
  2350. function Request(opts){
  2351. this.method = opts.method || 'GET';
  2352. this.uri = opts.uri;
  2353. this.xd = !!opts.xd;
  2354. this.async = false !== opts.async;
  2355. this.data = undefined != opts.data ? opts.data : null;
  2356. this.agent = opts.agent;
  2357. this.create(opts.isBinary, opts.supportsBinary);
  2358. }
  2359. /**
  2360. * Mix in `Emitter`.
  2361. */
  2362. Emitter(Request.prototype);
  2363. /**
  2364. * Creates the XHR object and sends the request.
  2365. *
  2366. * @api private
  2367. */
  2368. Request.prototype.create = function(isBinary, supportsBinary){
  2369. var xhr = this.xhr = new XMLHttpRequest({ agent: this.agent, xdomain: this.xd });
  2370. var self = this;
  2371. try {
  2372. debug('xhr open %s: %s', this.method, this.uri);
  2373. xhr.open(this.method, this.uri, this.async);
  2374. if (supportsBinary) {
  2375. // This has to be done after open because Firefox is stupid
  2376. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  2377. xhr.responseType = 'arraybuffer';
  2378. }
  2379. if ('POST' == this.method) {
  2380. try {
  2381. if (isBinary) {
  2382. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  2383. } else {
  2384. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  2385. }
  2386. } catch (e) {}
  2387. }
  2388. // ie6 check
  2389. if ('withCredentials' in xhr) {
  2390. xhr.withCredentials = true;
  2391. }
  2392. xhr.onreadystatechange = function(){
  2393. var data;
  2394. try {
  2395. if (4 != xhr.readyState) return;
  2396. if (200 == xhr.status || 1223 == xhr.status) {
  2397. var contentType = xhr.getResponseHeader('Content-Type');
  2398. if (contentType === 'application/octet-stream') {
  2399. data = xhr.response;
  2400. } else {
  2401. if (!supportsBinary) {
  2402. data = xhr.responseText;
  2403. } else {
  2404. data = 'ok';
  2405. }
  2406. }
  2407. } else {
  2408. // make sure the `error` event handler that's user-set
  2409. // does not throw in the same tick and gets caught here
  2410. setTimeout(function(){
  2411. self.onError(xhr.status);
  2412. }, 0);
  2413. }
  2414. } catch (e) {
  2415. self.onError(e);
  2416. }
  2417. if (null != data) {
  2418. self.onData(data);
  2419. }
  2420. };
  2421. debug('xhr data %s', this.data);
  2422. xhr.send(this.data);
  2423. } catch (e) {
  2424. // Need to defer since .create() is called directly fhrom the constructor
  2425. // and thus the 'error' event can only be only bound *after* this exception
  2426. // occurs. Therefore, also, we cannot throw here at all.
  2427. setTimeout(function() {
  2428. self.onError(e);
  2429. }, 0);
  2430. return;
  2431. }
  2432. if (global.document) {
  2433. this.index = Request.requestsCount++;
  2434. Request.requests[this.index] = this;
  2435. }
  2436. };
  2437. /**
  2438. * Called upon successful response.
  2439. *
  2440. * @api private
  2441. */
  2442. Request.prototype.onSuccess = function(){
  2443. this.emit('success');
  2444. this.cleanup();
  2445. };
  2446. /**
  2447. * Called if we have data.
  2448. *
  2449. * @api private
  2450. */
  2451. Request.prototype.onData = function(data){
  2452. this.emit('data', data);
  2453. this.onSuccess();
  2454. };
  2455. /**
  2456. * Called upon error.
  2457. *
  2458. * @api private
  2459. */
  2460. Request.prototype.onError = function(err){
  2461. this.emit('error', err);
  2462. this.cleanup();
  2463. };
  2464. /**
  2465. * Cleans up house.
  2466. *
  2467. * @api private
  2468. */
  2469. Request.prototype.cleanup = function(){
  2470. if ('undefined' == typeof this.xhr || null === this.xhr) {
  2471. return;
  2472. }
  2473. // xmlhttprequest
  2474. this.xhr.onreadystatechange = empty;
  2475. try {
  2476. this.xhr.abort();
  2477. } catch(e) {}
  2478. if (global.document) {
  2479. delete Request.requests[this.index];
  2480. }
  2481. this.xhr = null;
  2482. };
  2483. /**
  2484. * Aborts the request.
  2485. *
  2486. * @api public
  2487. */
  2488. Request.prototype.abort = function(){
  2489. this.cleanup();
  2490. };
  2491. /**
  2492. * Aborts pending requests when unloading the window. This is needed to prevent
  2493. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  2494. * emitted.
  2495. */
  2496. if (global.document) {
  2497. Request.requestsCount = 0;
  2498. Request.requests = {};
  2499. if (global.attachEvent) {
  2500. global.attachEvent('onunload', unloadHandler);
  2501. } else if (global.addEventListener) {
  2502. global.addEventListener('beforeunload', unloadHandler);
  2503. }
  2504. }
  2505. function unloadHandler() {
  2506. for (var i in Request.requests) {
  2507. if (Request.requests.hasOwnProperty(i)) {
  2508. Request.requests[i].abort();
  2509. }
  2510. }
  2511. }
  2512. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2513. },{"./polling":19,"component-emitter":10,"component-inherit":22,"debug":11,"xmlhttprequest":21}],19:[function(_dereq_,module,exports){
  2514. /**
  2515. * Module dependencies.
  2516. */
  2517. var Transport = _dereq_('../transport');
  2518. var parseqs = _dereq_('parseqs');
  2519. var parser = _dereq_('engine.io-parser');
  2520. var inherit = _dereq_('component-inherit');
  2521. var debug = _dereq_('debug')('engine.io-client:polling');
  2522. /**
  2523. * Module exports.
  2524. */
  2525. module.exports = Polling;
  2526. /**
  2527. * Is XHR2 supported?
  2528. */
  2529. var hasXHR2 = (function() {
  2530. var XMLHttpRequest = _dereq_('xmlhttprequest');
  2531. var xhr = new XMLHttpRequest({ agent: this.agent, xdomain: false });
  2532. return null != xhr.responseType;
  2533. })();
  2534. /**
  2535. * Polling interface.
  2536. *
  2537. * @param {Object} opts
  2538. * @api private
  2539. */
  2540. function Polling(opts){
  2541. var forceBase64 = (opts && opts.forceBase64);
  2542. if (!hasXHR2 || forceBase64) {
  2543. this.supportsBinary = false;
  2544. }
  2545. Transport.call(this, opts);
  2546. }
  2547. /**
  2548. * Inherits from Transport.
  2549. */
  2550. inherit(Polling, Transport);
  2551. /**
  2552. * Transport name.
  2553. */
  2554. Polling.prototype.name = 'polling';
  2555. /**
  2556. * Opens the socket (triggers polling). We write a PING message to determine
  2557. * when the transport is open.
  2558. *
  2559. * @api private
  2560. */
  2561. Polling.prototype.doOpen = function(){
  2562. this.poll();
  2563. };
  2564. /**
  2565. * Pauses polling.
  2566. *
  2567. * @param {Function} callback upon buffers are flushed and transport is paused
  2568. * @api private
  2569. */
  2570. Polling.prototype.pause = function(onPause){
  2571. var pending = 0;
  2572. var self = this;
  2573. this.readyState = 'pausing';
  2574. function pause(){
  2575. debug('paused');
  2576. self.readyState = 'paused';
  2577. onPause();
  2578. }
  2579. if (this.polling || !this.writable) {
  2580. var total = 0;
  2581. if (this.polling) {
  2582. debug('we are currently polling - waiting to pause');
  2583. total++;
  2584. this.once('pollComplete', function(){
  2585. debug('pre-pause polling complete');
  2586. --total || pause();
  2587. });
  2588. }
  2589. if (!this.writable) {
  2590. debug('we are currently writing - waiting to pause');
  2591. total++;
  2592. this.once('drain', function(){
  2593. debug('pre-pause writing complete');
  2594. --total || pause();
  2595. });
  2596. }
  2597. } else {
  2598. pause();
  2599. }
  2600. };
  2601. /**
  2602. * Starts polling cycle.
  2603. *
  2604. * @api public
  2605. */
  2606. Polling.prototype.poll = function(){
  2607. debug('polling');
  2608. this.polling = true;
  2609. this.doPoll();
  2610. this.emit('poll');
  2611. };
  2612. /**
  2613. * Overloads onData to detect payloads.
  2614. *
  2615. * @api private
  2616. */
  2617. Polling.prototype.onData = function(data){
  2618. var self = this;
  2619. debug('polling got data %s', data);
  2620. var callback = function(packet, index, total) {
  2621. // if its the first message we consider the transport open
  2622. if ('opening' == self.readyState) {
  2623. self.onOpen();
  2624. }
  2625. // if its a close packet, we close the ongoing requests
  2626. if ('close' == packet.type) {
  2627. self.onClose();
  2628. return false;
  2629. }
  2630. // otherwise bypass onData and handle the message
  2631. self.onPacket(packet);
  2632. };
  2633. // decode payload
  2634. parser.decodePayload(data, this.socket.binaryType, callback);
  2635. // if an event did not trigger closing
  2636. if ('closed' != this.readyState) {
  2637. // if we got data we're not polling
  2638. this.polling = false;
  2639. this.emit('pollComplete');
  2640. if ('open' == this.readyState) {
  2641. this.poll();
  2642. } else {
  2643. debug('ignoring poll - transport state "%s"', this.readyState);
  2644. }
  2645. }
  2646. };
  2647. /**
  2648. * For polling, send a close packet.
  2649. *
  2650. * @api private
  2651. */
  2652. Polling.prototype.doClose = function(){
  2653. var self = this;
  2654. function close(){
  2655. debug('writing close packet');
  2656. self.write([{ type: 'close' }]);
  2657. }
  2658. if ('open' == this.readyState) {
  2659. debug('transport open - closing');
  2660. close();
  2661. } else {
  2662. // in case we're trying to close while
  2663. // handshaking is in progress (GH-164)
  2664. debug('transport not open - deferring close');
  2665. this.once('open', close);
  2666. }
  2667. };
  2668. /**
  2669. * Writes a packets payload.
  2670. *
  2671. * @param {Array} data packets
  2672. * @param {Function} drain callback
  2673. * @api private
  2674. */
  2675. Polling.prototype.write = function(packets){
  2676. var self = this;
  2677. this.writable = false;
  2678. var callbackfn = function() {
  2679. self.writable = true;
  2680. self.emit('drain');
  2681. };
  2682. var self = this;
  2683. parser.encodePayload(packets, this.supportsBinary, function(data) {
  2684. self.doWrite(data, callbackfn);
  2685. });
  2686. };
  2687. /**
  2688. * Generates uri for connection.
  2689. *
  2690. * @api private
  2691. */
  2692. Polling.prototype.uri = function(){
  2693. var query = this.query || {};
  2694. var schema = this.secure ? 'https' : 'http';
  2695. var port = '';
  2696. // cache busting is forced
  2697. if (false !== this.timestampRequests) {
  2698. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  2699. }
  2700. if (!this.supportsBinary && !query.sid) {
  2701. query.b64 = 1;
  2702. }
  2703. query = parseqs.encode(query);
  2704. // avoid port if default for schema
  2705. if (this.port && (('https' == schema && this.port != 443) ||
  2706. ('http' == schema && this.port != 80))) {
  2707. port = ':' + this.port;
  2708. }
  2709. // prepend ? to query
  2710. if (query.length) {
  2711. query = '?' + query;
  2712. }
  2713. return schema + '://' + this.hostname + port + this.path + query;
  2714. };
  2715. },{"../transport":15,"component-inherit":22,"debug":11,"engine.io-parser":23,"parseqs":33,"xmlhttprequest":21}],20:[function(_dereq_,module,exports){
  2716. /**
  2717. * Module dependencies.
  2718. */
  2719. var Transport = _dereq_('../transport');
  2720. var parser = _dereq_('engine.io-parser');
  2721. var parseqs = _dereq_('parseqs');
  2722. var inherit = _dereq_('component-inherit');
  2723. var debug = _dereq_('debug')('engine.io-client:websocket');
  2724. /**
  2725. * `ws` exposes a WebSocket-compatible interface in
  2726. * Node, or the `WebSocket` or `MozWebSocket` globals
  2727. * in the browser.
  2728. */
  2729. var WebSocket = _dereq_('ws');
  2730. /**
  2731. * Module exports.
  2732. */
  2733. module.exports = WS;
  2734. /**
  2735. * WebSocket transport constructor.
  2736. *
  2737. * @api {Object} connection options
  2738. * @api public
  2739. */
  2740. function WS(opts){
  2741. var forceBase64 = (opts && opts.forceBase64);
  2742. if (forceBase64) {
  2743. this.supportsBinary = false;
  2744. }
  2745. Transport.call(this, opts);
  2746. }
  2747. /**
  2748. * Inherits from Transport.
  2749. */
  2750. inherit(WS, Transport);
  2751. /**
  2752. * Transport name.
  2753. *
  2754. * @api public
  2755. */
  2756. WS.prototype.name = 'websocket';
  2757. /*
  2758. * WebSockets support binary
  2759. */
  2760. WS.prototype.supportsBinary = true;
  2761. /**
  2762. * Opens socket.
  2763. *
  2764. * @api private
  2765. */
  2766. WS.prototype.doOpen = function(){
  2767. if (!this.check()) {
  2768. // let probe timeout
  2769. return;
  2770. }
  2771. var self = this;
  2772. var uri = this.uri();
  2773. var protocols = void(0);
  2774. var opts = { agent: this.agent };
  2775. this.ws = new WebSocket(uri, protocols, opts);
  2776. if (this.ws.binaryType === undefined) {
  2777. this.supportsBinary = false;
  2778. }
  2779. this.ws.binaryType = 'arraybuffer';
  2780. this.addEventListeners();
  2781. };
  2782. /**
  2783. * Adds event listeners to the socket
  2784. *
  2785. * @api private
  2786. */
  2787. WS.prototype.addEventListeners = function(){
  2788. var self = this;
  2789. this.ws.onopen = function(){
  2790. self.onOpen();
  2791. };
  2792. this.ws.onclose = function(){
  2793. self.onClose();
  2794. };
  2795. this.ws.onmessage = function(ev){
  2796. self.onData(ev.data);
  2797. };
  2798. this.ws.onerror = function(e){
  2799. self.onError('websocket error', e);
  2800. };
  2801. };
  2802. /**
  2803. * Override `onData` to use a timer on iOS.
  2804. * See: https://gist.github.com/mloughran/2052006
  2805. *
  2806. * @api private
  2807. */
  2808. if ('undefined' != typeof navigator
  2809. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  2810. WS.prototype.onData = function(data){
  2811. var self = this;
  2812. setTimeout(function(){
  2813. Transport.prototype.onData.call(self, data);
  2814. }, 0);
  2815. };
  2816. }
  2817. /**
  2818. * Writes data to socket.
  2819. *
  2820. * @param {Array} array of packets.
  2821. * @api private
  2822. */
  2823. WS.prototype.write = function(packets){
  2824. var self = this;
  2825. this.writable = false;
  2826. // encodePacket efficient as it uses WS framing
  2827. // no need for encodePayload
  2828. for (var i = 0, l = packets.length; i < l; i++) {
  2829. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  2830. //Sometimes the websocket has already been closed but the browser didn't
  2831. //have a chance of informing us about it yet, in that case send will
  2832. //throw an error
  2833. try {
  2834. self.ws.send(data);
  2835. } catch (e){
  2836. debug('websocket closed before onclose event');
  2837. }
  2838. });
  2839. }
  2840. function ondrain() {
  2841. self.writable = true;
  2842. self.emit('drain');
  2843. }
  2844. // fake drain
  2845. // defer to next tick to allow Socket to clear writeBuffer
  2846. setTimeout(ondrain, 0);
  2847. };
  2848. /**
  2849. * Called upon close
  2850. *
  2851. * @api private
  2852. */
  2853. WS.prototype.onClose = function(){
  2854. Transport.prototype.onClose.call(this);
  2855. };
  2856. /**
  2857. * Closes socket.
  2858. *
  2859. * @api private
  2860. */
  2861. WS.prototype.doClose = function(){
  2862. if (typeof this.ws !== 'undefined') {
  2863. this.ws.close();
  2864. }
  2865. };
  2866. /**
  2867. * Generates uri for connection.
  2868. *
  2869. * @api private
  2870. */
  2871. WS.prototype.uri = function(){
  2872. var query = this.query || {};
  2873. var schema = this.secure ? 'wss' : 'ws';
  2874. var port = '';
  2875. // avoid port if default for schema
  2876. if (this.port && (('wss' == schema && this.port != 443)
  2877. || ('ws' == schema && this.port != 80))) {
  2878. port = ':' + this.port;
  2879. }
  2880. // append timestamp to URI
  2881. if (this.timestampRequests) {
  2882. query[this.timestampParam] = +new Date;
  2883. }
  2884. // communicate binary support capabilities
  2885. if (!this.supportsBinary) {
  2886. query.b64 = 1;
  2887. }
  2888. query = parseqs.encode(query);
  2889. // prepend ? to query
  2890. if (query.length) {
  2891. query = '?' + query;
  2892. }
  2893. return schema + '://' + this.hostname + port + this.path + query;
  2894. };
  2895. /**
  2896. * Feature detection for WebSocket.
  2897. *
  2898. * @return {Boolean} whether this transport is available.
  2899. * @api public
  2900. */
  2901. WS.prototype.check = function(){
  2902. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  2903. };
  2904. },{"../transport":15,"component-inherit":22,"debug":11,"engine.io-parser":23,"parseqs":33,"ws":34}],21:[function(_dereq_,module,exports){
  2905. // browser shim for xmlhttprequest module
  2906. var hasCORS = _dereq_('has-cors');
  2907. module.exports = function(opts) {
  2908. var xdomain = opts.xdomain;
  2909. // XMLHttpRequest can be disabled on IE
  2910. try {
  2911. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  2912. return new XMLHttpRequest();
  2913. }
  2914. } catch (e) { }
  2915. if (!xdomain) {
  2916. try {
  2917. return new ActiveXObject('Microsoft.XMLHTTP');
  2918. } catch(e) { }
  2919. }
  2920. }
  2921. },{"has-cors":30}],22:[function(_dereq_,module,exports){
  2922. module.exports = function(a, b){
  2923. var fn = function(){};
  2924. fn.prototype = b.prototype;
  2925. a.prototype = new fn;
  2926. a.prototype.constructor = a;
  2927. };
  2928. },{}],23:[function(_dereq_,module,exports){
  2929. (function (global){
  2930. /**
  2931. * Module dependencies.
  2932. */
  2933. var keys = _dereq_('./keys');
  2934. var sliceBuffer = _dereq_('arraybuffer.slice');
  2935. var base64encoder = _dereq_('base64-arraybuffer');
  2936. var after = _dereq_('after');
  2937. var utf8 = _dereq_('utf8');
  2938. /**
  2939. * Check if we are running an android browser. That requires us to use
  2940. * ArrayBuffer with polling transports...
  2941. *
  2942. * http://ghinda.net/jpeg-blob-ajax-android/
  2943. */
  2944. var isAndroid = navigator.userAgent.match(/Android/i);
  2945. /**
  2946. * Current protocol version.
  2947. */
  2948. exports.protocol = 2;
  2949. /**
  2950. * Packet types.
  2951. */
  2952. var packets = exports.packets = {
  2953. open: 0 // non-ws
  2954. , close: 1 // non-ws
  2955. , ping: 2
  2956. , pong: 3
  2957. , message: 4
  2958. , upgrade: 5
  2959. , noop: 6
  2960. };
  2961. var packetslist = keys(packets);
  2962. /**
  2963. * Premade error packet.
  2964. */
  2965. var err = { type: 'error', data: 'parser error' };
  2966. /**
  2967. * Create a blob api even for blob builder when vendor prefixes exist
  2968. */
  2969. var Blob = _dereq_('blob');
  2970. /**
  2971. * Encodes a packet.
  2972. *
  2973. * <packet type id> [ <data> ]
  2974. *
  2975. * Example:
  2976. *
  2977. * 5hello world
  2978. * 3
  2979. * 4
  2980. *
  2981. * Binary is encoded in an identical principle
  2982. *
  2983. * @api private
  2984. */
  2985. exports.encodePacket = function (packet, supportsBinary, callback) {
  2986. if (typeof supportsBinary == 'function') {
  2987. callback = supportsBinary;
  2988. supportsBinary = false;
  2989. }
  2990. var data = (packet.data === undefined)
  2991. ? undefined
  2992. : packet.data.buffer || packet.data;
  2993. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  2994. return encodeArrayBuffer(packet, supportsBinary, callback);
  2995. } else if (Blob && data instanceof global.Blob) {
  2996. return encodeBlob(packet, supportsBinary, callback);
  2997. }
  2998. // Sending data as a utf-8 string
  2999. var encoded = packets[packet.type];
  3000. // data fragment is optional
  3001. if (undefined !== packet.data) {
  3002. encoded += utf8.encode(String(packet.data));
  3003. }
  3004. return callback('' + encoded);
  3005. };
  3006. /**
  3007. * Encode packet helpers for binary types
  3008. */
  3009. function encodeArrayBuffer(packet, supportsBinary, callback) {
  3010. if (!supportsBinary) {
  3011. return exports.encodeBase64Packet(packet, callback);
  3012. }
  3013. var data = packet.data;
  3014. var contentArray = new Uint8Array(data);
  3015. var resultBuffer = new Uint8Array(1 + data.byteLength);
  3016. resultBuffer[0] = packets[packet.type];
  3017. for (var i = 0; i < contentArray.length; i++) {
  3018. resultBuffer[i+1] = contentArray[i];
  3019. }
  3020. return callback(resultBuffer.buffer);
  3021. }
  3022. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  3023. if (!supportsBinary) {
  3024. return exports.encodeBase64Packet(packet, callback);
  3025. }
  3026. var fr = new FileReader();
  3027. fr.onload = function() {
  3028. packet.data = fr.result;
  3029. exports.encodePacket(packet, supportsBinary, callback);
  3030. };
  3031. return fr.readAsArrayBuffer(packet.data);
  3032. }
  3033. function encodeBlob(packet, supportsBinary, callback) {
  3034. if (!supportsBinary) {
  3035. return exports.encodeBase64Packet(packet, callback);
  3036. }
  3037. if (isAndroid) {
  3038. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  3039. }
  3040. var length = new Uint8Array(1);
  3041. length[0] = packets[packet.type];
  3042. var blob = new Blob([length.buffer, packet.data]);
  3043. return callback(blob);
  3044. }
  3045. /**
  3046. * Encodes a packet with binary data in a base64 string
  3047. *
  3048. * @param {Object} packet, has `type` and `data`
  3049. * @return {String} base64 encoded message
  3050. */
  3051. exports.encodeBase64Packet = function(packet, callback) {
  3052. var message = 'b' + exports.packets[packet.type];
  3053. if (Blob && packet.data instanceof Blob) {
  3054. var fr = new FileReader();
  3055. fr.onload = function() {
  3056. var b64 = fr.result.split(',')[1];
  3057. callback(message + b64);
  3058. };
  3059. return fr.readAsDataURL(packet.data);
  3060. }
  3061. var b64data;
  3062. try {
  3063. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  3064. } catch (e) {
  3065. // iPhone Safari doesn't let you apply with typed arrays
  3066. var typed = new Uint8Array(packet.data);
  3067. var basic = new Array(typed.length);
  3068. for (var i = 0; i < typed.length; i++) {
  3069. basic[i] = typed[i];
  3070. }
  3071. b64data = String.fromCharCode.apply(null, basic);
  3072. }
  3073. message += global.btoa(b64data);
  3074. return callback(message);
  3075. };
  3076. /**
  3077. * Decodes a packet. Changes format to Blob if requested.
  3078. *
  3079. * @return {Object} with `type` and `data` (if any)
  3080. * @api private
  3081. */
  3082. exports.decodePacket = function (data, binaryType) {
  3083. // String data
  3084. if (typeof data == 'string' || data === undefined) {
  3085. if (data.charAt(0) == 'b') {
  3086. return exports.decodeBase64Packet(data.substr(1), binaryType);
  3087. }
  3088. data = utf8.decode(data);
  3089. var type = data.charAt(0);
  3090. if (Number(type) != type || !packetslist[type]) {
  3091. return err;
  3092. }
  3093. if (data.length > 1) {
  3094. return { type: packetslist[type], data: data.substring(1) };
  3095. } else {
  3096. return { type: packetslist[type] };
  3097. }
  3098. }
  3099. var asArray = new Uint8Array(data);
  3100. var type = asArray[0];
  3101. var rest = sliceBuffer(data, 1);
  3102. if (Blob && binaryType === 'blob') {
  3103. rest = new Blob([rest]);
  3104. }
  3105. return { type: packetslist[type], data: rest };
  3106. };
  3107. /**
  3108. * Decodes a packet encoded in a base64 string
  3109. *
  3110. * @param {String} base64 encoded message
  3111. * @return {Object} with `type` and `data` (if any)
  3112. */
  3113. exports.decodeBase64Packet = function(msg, binaryType) {
  3114. var type = packetslist[msg.charAt(0)];
  3115. if (!global.ArrayBuffer) {
  3116. return { type: type, data: { base64: true, data: msg.substr(1) } };
  3117. }
  3118. var data = base64encoder.decode(msg.substr(1));
  3119. if (binaryType === 'blob' && Blob) {
  3120. data = new Blob([data]);
  3121. }
  3122. return { type: type, data: data };
  3123. };
  3124. /**
  3125. * Encodes multiple messages (payload).
  3126. *
  3127. * <length>:data
  3128. *
  3129. * Example:
  3130. *
  3131. * 11:hello world2:hi
  3132. *
  3133. * If any contents are binary, they will be encoded as base64 strings. Base64
  3134. * encoded strings are marked with a b before the length specifier
  3135. *
  3136. * @param {Array} packets
  3137. * @api private
  3138. */
  3139. exports.encodePayload = function (packets, supportsBinary, callback) {
  3140. if (typeof supportsBinary == 'function') {
  3141. callback = supportsBinary;
  3142. supportsBinary = null;
  3143. }
  3144. if (supportsBinary) {
  3145. if (Blob && !isAndroid) {
  3146. return exports.encodePayloadAsBlob(packets, callback);
  3147. }
  3148. return exports.encodePayloadAsArrayBuffer(packets, callback);
  3149. }
  3150. if (!packets.length) {
  3151. return callback('0:');
  3152. }
  3153. function setLengthHeader(message) {
  3154. return message.length + ':' + message;
  3155. }
  3156. function encodeOne(packet, doneCallback) {
  3157. exports.encodePacket(packet, supportsBinary, function(message) {
  3158. doneCallback(null, setLengthHeader(message));
  3159. });
  3160. }
  3161. map(packets, encodeOne, function(err, results) {
  3162. return callback(results.join(''));
  3163. });
  3164. };
  3165. /**
  3166. * Async array map using after
  3167. */
  3168. function map(ary, each, done) {
  3169. var result = new Array(ary.length);
  3170. var next = after(ary.length, done);
  3171. var eachWithIndex = function(i, el, cb) {
  3172. each(el, function(error, msg) {
  3173. result[i] = msg;
  3174. cb(error, result);
  3175. });
  3176. };
  3177. for (var i = 0; i < ary.length; i++) {
  3178. eachWithIndex(i, ary[i], next);
  3179. }
  3180. }
  3181. /*
  3182. * Decodes data when a payload is maybe expected. Possible binary contents are
  3183. * decoded from their base64 representation
  3184. *
  3185. * @param {String} data, callback method
  3186. * @api public
  3187. */
  3188. exports.decodePayload = function (data, binaryType, callback) {
  3189. if (typeof data != 'string') {
  3190. return exports.decodePayloadAsBinary(data, binaryType, callback);
  3191. }
  3192. if (typeof binaryType === 'function') {
  3193. callback = binaryType;
  3194. binaryType = null;
  3195. }
  3196. var packet;
  3197. if (data == '') {
  3198. // parser error - ignoring payload
  3199. return callback(err, 0, 1);
  3200. }
  3201. var length = ''
  3202. , n, msg;
  3203. for (var i = 0, l = data.length; i < l; i++) {
  3204. var chr = data.charAt(i);
  3205. if (':' != chr) {
  3206. length += chr;
  3207. } else {
  3208. if ('' == length || (length != (n = Number(length)))) {
  3209. // parser error - ignoring payload
  3210. return callback(err, 0, 1);
  3211. }
  3212. msg = data.substr(i + 1, n);
  3213. if (length != msg.length) {
  3214. // parser error - ignoring payload
  3215. return callback(err, 0, 1);
  3216. }
  3217. if (msg.length) {
  3218. packet = exports.decodePacket(msg, binaryType);
  3219. if (err.type == packet.type && err.data == packet.data) {
  3220. // parser error in individual packet - ignoring payload
  3221. return callback(err, 0, 1);
  3222. }
  3223. var ret = callback(packet, i + n, l);
  3224. if (false === ret) return;
  3225. }
  3226. // advance cursor
  3227. i += n;
  3228. length = '';
  3229. }
  3230. }
  3231. if (length != '') {
  3232. // parser error - ignoring payload
  3233. return callback(err, 0, 1);
  3234. }
  3235. };
  3236. /**
  3237. * Encodes multiple messages (payload) as binary.
  3238. *
  3239. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  3240. * 255><data>
  3241. *
  3242. * Example:
  3243. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  3244. *
  3245. * @param {Array} packets
  3246. * @return {ArrayBuffer} encoded payload
  3247. * @api private
  3248. */
  3249. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  3250. if (!packets.length) {
  3251. return callback(new ArrayBuffer(0));
  3252. }
  3253. function encodeOne(packet, doneCallback) {
  3254. exports.encodePacket(packet, true, function(data) {
  3255. return doneCallback(null, data);
  3256. });
  3257. }
  3258. map(packets, encodeOne, function(err, encodedPackets) {
  3259. var totalLength = encodedPackets.reduce(function(acc, p) {
  3260. var len;
  3261. if (typeof p === 'string'){
  3262. len = p.length;
  3263. } else {
  3264. len = p.byteLength;
  3265. }
  3266. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  3267. }, 0);
  3268. var resultArray = new Uint8Array(totalLength);
  3269. var bufferIndex = 0;
  3270. encodedPackets.forEach(function(p) {
  3271. var isString = typeof p === 'string';
  3272. var ab = p;
  3273. if (isString) {
  3274. var view = new Uint8Array(p.length);
  3275. for (var i = 0; i < p.length; i++) {
  3276. view[i] = p.charCodeAt(i);
  3277. }
  3278. ab = view.buffer;
  3279. }
  3280. if (isString) { // not true binary
  3281. resultArray[bufferIndex++] = 0;
  3282. } else { // true binary
  3283. resultArray[bufferIndex++] = 1;
  3284. }
  3285. var lenStr = ab.byteLength.toString();
  3286. for (var i = 0; i < lenStr.length; i++) {
  3287. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  3288. }
  3289. resultArray[bufferIndex++] = 255;
  3290. var view = new Uint8Array(ab);
  3291. for (var i = 0; i < view.length; i++) {
  3292. resultArray[bufferIndex++] = view[i];
  3293. }
  3294. });
  3295. return callback(resultArray.buffer);
  3296. });
  3297. };
  3298. /**
  3299. * Encode as Blob
  3300. */
  3301. exports.encodePayloadAsBlob = function(packets, callback) {
  3302. function encodeOne(packet, doneCallback) {
  3303. exports.encodePacket(packet, true, function(encoded) {
  3304. var binaryIdentifier = new Uint8Array(1);
  3305. binaryIdentifier[0] = 1;
  3306. if (typeof encoded === 'string') {
  3307. var view = new Uint8Array(encoded.length);
  3308. for (var i = 0; i < encoded.length; i++) {
  3309. view[i] = encoded.charCodeAt(i);
  3310. }
  3311. encoded = view.buffer;
  3312. binaryIdentifier[0] = 0;
  3313. }
  3314. var len = (encoded instanceof ArrayBuffer)
  3315. ? encoded.byteLength
  3316. : encoded.size;
  3317. var lenStr = len.toString();
  3318. var lengthAry = new Uint8Array(lenStr.length + 1);
  3319. for (var i = 0; i < lenStr.length; i++) {
  3320. lengthAry[i] = parseInt(lenStr[i]);
  3321. }
  3322. lengthAry[lenStr.length] = 255;
  3323. if (Blob) {
  3324. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  3325. doneCallback(null, blob);
  3326. }
  3327. });
  3328. }
  3329. map(packets, encodeOne, function(err, results) {
  3330. return callback(new Blob(results));
  3331. });
  3332. };
  3333. /*
  3334. * Decodes data when a payload is maybe expected. Strings are decoded by
  3335. * interpreting each byte as a key code for entries marked to start with 0. See
  3336. * description of encodePayloadAsBinary
  3337. *
  3338. * @param {ArrayBuffer} data, callback method
  3339. * @api public
  3340. */
  3341. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  3342. if (typeof binaryType === 'function') {
  3343. callback = binaryType;
  3344. binaryType = null;
  3345. }
  3346. var bufferTail = data;
  3347. var buffers = [];
  3348. while (bufferTail.byteLength > 0) {
  3349. var tailArray = new Uint8Array(bufferTail);
  3350. var isString = tailArray[0] === 0;
  3351. var msgLength = '';
  3352. for (var i = 1; ; i++) {
  3353. if (tailArray[i] == 255) break;
  3354. msgLength += tailArray[i];
  3355. }
  3356. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  3357. msgLength = parseInt(msgLength);
  3358. var msg = sliceBuffer(bufferTail, 0, msgLength);
  3359. if (isString) {
  3360. try {
  3361. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  3362. } catch (e) {
  3363. // iPhone Safari doesn't let you apply to typed arrays
  3364. var typed = new Uint8Array(msg);
  3365. msg = '';
  3366. for (var i = 0; i < typed.length; i++) {
  3367. msg += String.fromCharCode(typed[i]);
  3368. }
  3369. }
  3370. }
  3371. buffers.push(msg);
  3372. bufferTail = sliceBuffer(bufferTail, msgLength);
  3373. }
  3374. var total = buffers.length;
  3375. buffers.forEach(function(buffer, i) {
  3376. callback(exports.decodePacket(buffer, binaryType), i, total);
  3377. });
  3378. };
  3379. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3380. },{"./keys":24,"after":25,"arraybuffer.slice":26,"base64-arraybuffer":27,"blob":28,"utf8":29}],24:[function(_dereq_,module,exports){
  3381. /**
  3382. * Gets the keys for an object.
  3383. *
  3384. * @return {Array} keys
  3385. * @api private
  3386. */
  3387. module.exports = Object.keys || function keys (obj){
  3388. var arr = [];
  3389. var has = Object.prototype.hasOwnProperty;
  3390. for (var i in obj) {
  3391. if (has.call(obj, i)) {
  3392. arr.push(i);
  3393. }
  3394. }
  3395. return arr;
  3396. };
  3397. },{}],25:[function(_dereq_,module,exports){
  3398. module.exports = after
  3399. function after(count, callback, err_cb) {
  3400. var bail = false
  3401. err_cb = err_cb || noop
  3402. proxy.count = count
  3403. return (count === 0) ? callback() : proxy
  3404. function proxy(err, result) {
  3405. if (proxy.count <= 0) {
  3406. throw new Error('after called too many times')
  3407. }
  3408. --proxy.count
  3409. // after first error, rest are passed to err_cb
  3410. if (err) {
  3411. bail = true
  3412. callback(err)
  3413. // future error callbacks will go to error handler
  3414. callback = err_cb
  3415. } else if (proxy.count === 0 && !bail) {
  3416. callback(null, result)
  3417. }
  3418. }
  3419. }
  3420. function noop() {}
  3421. },{}],26:[function(_dereq_,module,exports){
  3422. /**
  3423. * An abstraction for slicing an arraybuffer even when
  3424. * ArrayBuffer.prototype.slice is not supported
  3425. *
  3426. * @api public
  3427. */
  3428. module.exports = function(arraybuffer, start, end) {
  3429. var bytes = arraybuffer.byteLength;
  3430. start = start || 0;
  3431. end = end || bytes;
  3432. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  3433. if (start < 0) { start += bytes; }
  3434. if (end < 0) { end += bytes; }
  3435. if (end > bytes) { end = bytes; }
  3436. if (start >= bytes || start >= end || bytes === 0) {
  3437. return new ArrayBuffer(0);
  3438. }
  3439. var abv = new Uint8Array(arraybuffer);
  3440. var result = new Uint8Array(end - start);
  3441. for (var i = start, ii = 0; i < end; i++, ii++) {
  3442. result[ii] = abv[i];
  3443. }
  3444. return result.buffer;
  3445. };
  3446. },{}],27:[function(_dereq_,module,exports){
  3447. /*
  3448. * base64-arraybuffer
  3449. * https://github.com/niklasvh/base64-arraybuffer
  3450. *
  3451. * Copyright (c) 2012 Niklas von Hertzen
  3452. * Licensed under the MIT license.
  3453. */
  3454. (function(chars){
  3455. "use strict";
  3456. exports.encode = function(arraybuffer) {
  3457. var bytes = new Uint8Array(arraybuffer),
  3458. i, len = bytes.length, base64 = "";
  3459. for (i = 0; i < len; i+=3) {
  3460. base64 += chars[bytes[i] >> 2];
  3461. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  3462. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  3463. base64 += chars[bytes[i + 2] & 63];
  3464. }
  3465. if ((len % 3) === 2) {
  3466. base64 = base64.substring(0, base64.length - 1) + "=";
  3467. } else if (len % 3 === 1) {
  3468. base64 = base64.substring(0, base64.length - 2) + "==";
  3469. }
  3470. return base64;
  3471. };
  3472. exports.decode = function(base64) {
  3473. var bufferLength = base64.length * 0.75,
  3474. len = base64.length, i, p = 0,
  3475. encoded1, encoded2, encoded3, encoded4;
  3476. if (base64[base64.length - 1] === "=") {
  3477. bufferLength--;
  3478. if (base64[base64.length - 2] === "=") {
  3479. bufferLength--;
  3480. }
  3481. }
  3482. var arraybuffer = new ArrayBuffer(bufferLength),
  3483. bytes = new Uint8Array(arraybuffer);
  3484. for (i = 0; i < len; i+=4) {
  3485. encoded1 = chars.indexOf(base64[i]);
  3486. encoded2 = chars.indexOf(base64[i+1]);
  3487. encoded3 = chars.indexOf(base64[i+2]);
  3488. encoded4 = chars.indexOf(base64[i+3]);
  3489. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  3490. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  3491. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  3492. }
  3493. return arraybuffer;
  3494. };
  3495. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  3496. },{}],28:[function(_dereq_,module,exports){
  3497. (function (global){
  3498. /**
  3499. * Create a blob builder even when vendor prefixes exist
  3500. */
  3501. var BlobBuilder = global.BlobBuilder
  3502. || global.WebKitBlobBuilder
  3503. || global.MSBlobBuilder
  3504. || global.MozBlobBuilder;
  3505. /**
  3506. * Check if Blob constructor is supported
  3507. */
  3508. var blobSupported = (function() {
  3509. try {
  3510. var b = new Blob(['hi']);
  3511. return b.size == 2;
  3512. } catch(e) {
  3513. return false;
  3514. }
  3515. })();
  3516. /**
  3517. * Check if BlobBuilder is supported
  3518. */
  3519. var blobBuilderSupported = BlobBuilder
  3520. && BlobBuilder.prototype.append
  3521. && BlobBuilder.prototype.getBlob;
  3522. function BlobBuilderConstructor(ary, options) {
  3523. options = options || {};
  3524. var bb = new BlobBuilder();
  3525. for (var i = 0; i < ary.length; i++) {
  3526. bb.append(ary[i]);
  3527. }
  3528. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  3529. };
  3530. module.exports = (function() {
  3531. if (blobSupported) {
  3532. return global.Blob;
  3533. } else if (blobBuilderSupported) {
  3534. return BlobBuilderConstructor;
  3535. } else {
  3536. return undefined;
  3537. }
  3538. })();
  3539. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3540. },{}],29:[function(_dereq_,module,exports){
  3541. (function (global){
  3542. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  3543. ;(function(root) {
  3544. // Detect free variables `exports`
  3545. var freeExports = typeof exports == 'object' && exports;
  3546. // Detect free variable `module`
  3547. var freeModule = typeof module == 'object' && module &&
  3548. module.exports == freeExports && module;
  3549. // Detect free variable `global`, from Node.js or Browserified code,
  3550. // and use it as `root`
  3551. var freeGlobal = typeof global == 'object' && global;
  3552. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  3553. root = freeGlobal;
  3554. }
  3555. /*--------------------------------------------------------------------------*/
  3556. var stringFromCharCode = String.fromCharCode;
  3557. // Taken from http://mths.be/punycode
  3558. function ucs2decode(string) {
  3559. var output = [];
  3560. var counter = 0;
  3561. var length = string.length;
  3562. var value;
  3563. var extra;
  3564. while (counter < length) {
  3565. value = string.charCodeAt(counter++);
  3566. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  3567. // high surrogate, and there is a next character
  3568. extra = string.charCodeAt(counter++);
  3569. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  3570. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  3571. } else {
  3572. // unmatched surrogate; only append this code unit, in case the next
  3573. // code unit is the high surrogate of a surrogate pair
  3574. output.push(value);
  3575. counter--;
  3576. }
  3577. } else {
  3578. output.push(value);
  3579. }
  3580. }
  3581. return output;
  3582. }
  3583. // Taken from http://mths.be/punycode
  3584. function ucs2encode(array) {
  3585. var length = array.length;
  3586. var index = -1;
  3587. var value;
  3588. var output = '';
  3589. while (++index < length) {
  3590. value = array[index];
  3591. if (value > 0xFFFF) {
  3592. value -= 0x10000;
  3593. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  3594. value = 0xDC00 | value & 0x3FF;
  3595. }
  3596. output += stringFromCharCode(value);
  3597. }
  3598. return output;
  3599. }
  3600. /*--------------------------------------------------------------------------*/
  3601. function createByte(codePoint, shift) {
  3602. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  3603. }
  3604. function encodeCodePoint(codePoint) {
  3605. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  3606. return stringFromCharCode(codePoint);
  3607. }
  3608. var symbol = '';
  3609. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  3610. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  3611. }
  3612. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  3613. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  3614. symbol += createByte(codePoint, 6);
  3615. }
  3616. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  3617. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  3618. symbol += createByte(codePoint, 12);
  3619. symbol += createByte(codePoint, 6);
  3620. }
  3621. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  3622. return symbol;
  3623. }
  3624. function utf8encode(string) {
  3625. var codePoints = ucs2decode(string);
  3626. // console.log(JSON.stringify(codePoints.map(function(x) {
  3627. // return 'U+' + x.toString(16).toUpperCase();
  3628. // })));
  3629. var length = codePoints.length;
  3630. var index = -1;
  3631. var codePoint;
  3632. var byteString = '';
  3633. while (++index < length) {
  3634. codePoint = codePoints[index];
  3635. byteString += encodeCodePoint(codePoint);
  3636. }
  3637. return byteString;
  3638. }
  3639. /*--------------------------------------------------------------------------*/
  3640. function readContinuationByte() {
  3641. if (byteIndex >= byteCount) {
  3642. throw Error('Invalid byte index');
  3643. }
  3644. var continuationByte = byteArray[byteIndex] & 0xFF;
  3645. byteIndex++;
  3646. if ((continuationByte & 0xC0) == 0x80) {
  3647. return continuationByte & 0x3F;
  3648. }
  3649. // If we end up here, it’s not a continuation byte
  3650. throw Error('Invalid continuation byte');
  3651. }
  3652. function decodeSymbol() {
  3653. var byte1;
  3654. var byte2;
  3655. var byte3;
  3656. var byte4;
  3657. var codePoint;
  3658. if (byteIndex > byteCount) {
  3659. throw Error('Invalid byte index');
  3660. }
  3661. if (byteIndex == byteCount) {
  3662. return false;
  3663. }
  3664. // Read first byte
  3665. byte1 = byteArray[byteIndex] & 0xFF;
  3666. byteIndex++;
  3667. // 1-byte sequence (no continuation bytes)
  3668. if ((byte1 & 0x80) == 0) {
  3669. return byte1;
  3670. }
  3671. // 2-byte sequence
  3672. if ((byte1 & 0xE0) == 0xC0) {
  3673. var byte2 = readContinuationByte();
  3674. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  3675. if (codePoint >= 0x80) {
  3676. return codePoint;
  3677. } else {
  3678. throw Error('Invalid continuation byte');
  3679. }
  3680. }
  3681. // 3-byte sequence (may include unpaired surrogates)
  3682. if ((byte1 & 0xF0) == 0xE0) {
  3683. byte2 = readContinuationByte();
  3684. byte3 = readContinuationByte();
  3685. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  3686. if (codePoint >= 0x0800) {
  3687. return codePoint;
  3688. } else {
  3689. throw Error('Invalid continuation byte');
  3690. }
  3691. }
  3692. // 4-byte sequence
  3693. if ((byte1 & 0xF8) == 0xF0) {
  3694. byte2 = readContinuationByte();
  3695. byte3 = readContinuationByte();
  3696. byte4 = readContinuationByte();
  3697. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  3698. (byte3 << 0x06) | byte4;
  3699. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  3700. return codePoint;
  3701. }
  3702. }
  3703. throw Error('Invalid UTF-8 detected');
  3704. }
  3705. var byteArray;
  3706. var byteCount;
  3707. var byteIndex;
  3708. function utf8decode(byteString) {
  3709. byteArray = ucs2decode(byteString);
  3710. byteCount = byteArray.length;
  3711. byteIndex = 0;
  3712. var codePoints = [];
  3713. var tmp;
  3714. while ((tmp = decodeSymbol()) !== false) {
  3715. codePoints.push(tmp);
  3716. }
  3717. return ucs2encode(codePoints);
  3718. }
  3719. /*--------------------------------------------------------------------------*/
  3720. var utf8 = {
  3721. 'version': '2.0.0',
  3722. 'encode': utf8encode,
  3723. 'decode': utf8decode
  3724. };
  3725. // Some AMD build optimizers, like r.js, check for specific condition patterns
  3726. // like the following:
  3727. if (
  3728. typeof define == 'function' &&
  3729. typeof define.amd == 'object' &&
  3730. define.amd
  3731. ) {
  3732. define(function() {
  3733. return utf8;
  3734. });
  3735. } else if (freeExports && !freeExports.nodeType) {
  3736. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  3737. freeModule.exports = utf8;
  3738. } else { // in Narwhal or RingoJS v0.7.0-
  3739. var object = {};
  3740. var hasOwnProperty = object.hasOwnProperty;
  3741. for (var key in utf8) {
  3742. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  3743. }
  3744. }
  3745. } else { // in Rhino or a web browser
  3746. root.utf8 = utf8;
  3747. }
  3748. }(this));
  3749. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3750. },{}],30:[function(_dereq_,module,exports){
  3751. /**
  3752. * Module dependencies.
  3753. */
  3754. var global = _dereq_('global');
  3755. /**
  3756. * Module exports.
  3757. *
  3758. * Logic borrowed from Modernizr:
  3759. *
  3760. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  3761. */
  3762. try {
  3763. module.exports = 'XMLHttpRequest' in global &&
  3764. 'withCredentials' in new global.XMLHttpRequest();
  3765. } catch (err) {
  3766. // if XMLHttp support is disabled in IE then it will throw
  3767. // when trying to create
  3768. module.exports = false;
  3769. }
  3770. },{"global":31}],31:[function(_dereq_,module,exports){
  3771. /**
  3772. * Returns `this`. Execute this without a "context" (i.e. without it being
  3773. * attached to an object of the left-hand side), and `this` points to the
  3774. * "global" scope of the current JS execution.
  3775. */
  3776. module.exports = (function () { return this; })();
  3777. },{}],32:[function(_dereq_,module,exports){
  3778. (function (global){
  3779. /**
  3780. * JSON parse.
  3781. *
  3782. * @see Based on jQuery#parseJSON (MIT) and JSON2
  3783. * @api private
  3784. */
  3785. var rvalidchars = /^[\],:{}\s]*$/;
  3786. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  3787. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  3788. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  3789. var rtrimLeft = /^\s+/;
  3790. var rtrimRight = /\s+$/;
  3791. module.exports = function parsejson(data) {
  3792. if ('string' != typeof data || !data) {
  3793. return null;
  3794. }
  3795. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  3796. // Attempt to parse using the native JSON parser first
  3797. if (global.JSON && JSON.parse) {
  3798. return JSON.parse(data);
  3799. }
  3800. if (rvalidchars.test(data.replace(rvalidescape, '@')
  3801. .replace(rvalidtokens, ']')
  3802. .replace(rvalidbraces, ''))) {
  3803. return (new Function('return ' + data))();
  3804. }
  3805. };
  3806. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3807. },{}],33:[function(_dereq_,module,exports){
  3808. /**
  3809. * Compiles a querystring
  3810. * Returns string representation of the object
  3811. *
  3812. * @param {Object}
  3813. * @api private
  3814. */
  3815. exports.encode = function (obj) {
  3816. var str = '';
  3817. for (var i in obj) {
  3818. if (obj.hasOwnProperty(i)) {
  3819. if (str.length) str += '&';
  3820. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  3821. }
  3822. }
  3823. return str;
  3824. };
  3825. /**
  3826. * Parses a simple querystring into an object
  3827. *
  3828. * @param {String} qs
  3829. * @api private
  3830. */
  3831. exports.decode = function(qs){
  3832. var qry = {};
  3833. var pairs = qs.split('&');
  3834. for (var i = 0, l = pairs.length; i < l; i++) {
  3835. var pair = pairs[i].split('=');
  3836. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  3837. }
  3838. return qry;
  3839. };
  3840. },{}],34:[function(_dereq_,module,exports){
  3841. /**
  3842. * Module dependencies.
  3843. */
  3844. var global = (function() { return this; })();
  3845. /**
  3846. * WebSocket constructor.
  3847. */
  3848. var WebSocket = global.WebSocket || global.MozWebSocket;
  3849. /**
  3850. * Module exports.
  3851. */
  3852. module.exports = WebSocket ? ws : null;
  3853. /**
  3854. * WebSocket constructor.
  3855. *
  3856. * The third `opts` options object gets ignored in web browsers, since it's
  3857. * non-standard, and throws a TypeError if passed to the constructor.
  3858. * See: https://github.com/einaros/ws/issues/227
  3859. *
  3860. * @param {String} uri
  3861. * @param {Array} protocols (optional)
  3862. * @param {Object) opts (optional)
  3863. * @api public
  3864. */
  3865. function ws(uri, protocols, opts) {
  3866. var instance;
  3867. if (protocols) {
  3868. instance = new WebSocket(uri, protocols);
  3869. } else {
  3870. instance = new WebSocket(uri);
  3871. }
  3872. return instance;
  3873. }
  3874. if (WebSocket) ws.prototype = WebSocket.prototype;
  3875. },{}],35:[function(_dereq_,module,exports){
  3876. (function (global,Buffer){
  3877. /*
  3878. * Module requirements.
  3879. */
  3880. var isArray = _dereq_('isarray');
  3881. /**
  3882. * Module exports.
  3883. */
  3884. module.exports = hasBinary;
  3885. /**
  3886. * Checks for binary data.
  3887. *
  3888. * Right now only Buffer and ArrayBuffer are supported..
  3889. *
  3890. * @param {Object} anything
  3891. * @api public
  3892. */
  3893. function hasBinary(data) {
  3894. function recursiveCheckForBinary(obj) {
  3895. if (!obj) return false;
  3896. if ( (global.Buffer && Buffer.isBuffer(obj)) ||
  3897. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  3898. (global.Blob && obj instanceof Blob) ||
  3899. (global.File && obj instanceof File)
  3900. ) {
  3901. return true;
  3902. }
  3903. if (isArray(obj)) {
  3904. for (var i = 0; i < obj.length; i++) {
  3905. if (recursiveCheckForBinary(obj[i])) {
  3906. return true;
  3907. }
  3908. }
  3909. } else if (obj && 'object' == typeof obj) {
  3910. if (obj.toJSON) {
  3911. obj = obj.toJSON();
  3912. }
  3913. for (var key in obj) {
  3914. if (recursiveCheckForBinary(obj[key])) {
  3915. return true;
  3916. }
  3917. }
  3918. }
  3919. return false;
  3920. }
  3921. return recursiveCheckForBinary(data);
  3922. }
  3923. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
  3924. },{"buffer":46,"isarray":36}],36:[function(_dereq_,module,exports){
  3925. module.exports = Array.isArray || function (arr) {
  3926. return Object.prototype.toString.call(arr) == '[object Array]';
  3927. };
  3928. },{}],37:[function(_dereq_,module,exports){
  3929. var indexOf = [].indexOf;
  3930. module.exports = function(arr, obj){
  3931. if (indexOf) return arr.indexOf(obj);
  3932. for (var i = 0; i < arr.length; ++i) {
  3933. if (arr[i] === obj) return i;
  3934. }
  3935. return -1;
  3936. };
  3937. },{}],38:[function(_dereq_,module,exports){
  3938. /**
  3939. * HOP ref.
  3940. */
  3941. var has = Object.prototype.hasOwnProperty;
  3942. /**
  3943. * Return own keys in `obj`.
  3944. *
  3945. * @param {Object} obj
  3946. * @return {Array}
  3947. * @api public
  3948. */
  3949. exports.keys = Object.keys || function(obj){
  3950. var keys = [];
  3951. for (var key in obj) {
  3952. if (has.call(obj, key)) {
  3953. keys.push(key);
  3954. }
  3955. }
  3956. return keys;
  3957. };
  3958. /**
  3959. * Return own values in `obj`.
  3960. *
  3961. * @param {Object} obj
  3962. * @return {Array}
  3963. * @api public
  3964. */
  3965. exports.values = function(obj){
  3966. var vals = [];
  3967. for (var key in obj) {
  3968. if (has.call(obj, key)) {
  3969. vals.push(obj[key]);
  3970. }
  3971. }
  3972. return vals;
  3973. };
  3974. /**
  3975. * Merge `b` into `a`.
  3976. *
  3977. * @param {Object} a
  3978. * @param {Object} b
  3979. * @return {Object} a
  3980. * @api public
  3981. */
  3982. exports.merge = function(a, b){
  3983. for (var key in b) {
  3984. if (has.call(b, key)) {
  3985. a[key] = b[key];
  3986. }
  3987. }
  3988. return a;
  3989. };
  3990. /**
  3991. * Return length of `obj`.
  3992. *
  3993. * @param {Object} obj
  3994. * @return {Number}
  3995. * @api public
  3996. */
  3997. exports.length = function(obj){
  3998. return exports.keys(obj).length;
  3999. };
  4000. /**
  4001. * Check if `obj` is empty.
  4002. *
  4003. * @param {Object} obj
  4004. * @return {Boolean}
  4005. * @api public
  4006. */
  4007. exports.isEmpty = function(obj){
  4008. return 0 == exports.length(obj);
  4009. };
  4010. },{}],39:[function(_dereq_,module,exports){
  4011. /**
  4012. * Parses an URI
  4013. *
  4014. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  4015. * @api private
  4016. */
  4017. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  4018. var parts = [
  4019. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  4020. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  4021. ];
  4022. module.exports = function parseuri(str) {
  4023. var m = re.exec(str || '')
  4024. , uri = {}
  4025. , i = 14;
  4026. while (i--) {
  4027. uri[parts[i]] = m[i] || '';
  4028. }
  4029. return uri;
  4030. };
  4031. },{}],40:[function(_dereq_,module,exports){
  4032. (function (global,Buffer){
  4033. /**
  4034. * Modle requirements
  4035. */
  4036. var isArray = _dereq_('isarray');
  4037. /**
  4038. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  4039. * Anything with blobs or files should be fed through removeBlobs before coming
  4040. * here.
  4041. *
  4042. * @param {Object} packet - socket.io event packet
  4043. * @return {Object} with deconstructed packet and list of buffers
  4044. * @api public
  4045. */
  4046. exports.deconstructPacket = function(packet) {
  4047. var buffers = [];
  4048. var packetData = packet.data;
  4049. function deconstructBinPackRecursive(data) {
  4050. if (!data) return data;
  4051. if ((global.Buffer && Buffer.isBuffer(data)) ||
  4052. (global.ArrayBuffer && data instanceof ArrayBuffer)) { // replace binary
  4053. var placeholder = {_placeholder: true, num: buffers.length};
  4054. buffers.push(data);
  4055. return placeholder;
  4056. } else if (isArray(data)) {
  4057. var newData = new Array(data.length);
  4058. for (var i = 0; i < data.length; i++) {
  4059. newData[i] = deconstructBinPackRecursive(data[i]);
  4060. }
  4061. return newData;
  4062. } else if ('object' == typeof data && !(data instanceof Date)) {
  4063. var newData = {};
  4064. for (var key in data) {
  4065. newData[key] = deconstructBinPackRecursive(data[key]);
  4066. }
  4067. return newData;
  4068. }
  4069. return data;
  4070. }
  4071. var pack = packet;
  4072. pack.data = deconstructBinPackRecursive(packetData);
  4073. pack.attachments = buffers.length; // number of binary 'attachments'
  4074. return {packet: pack, buffers: buffers};
  4075. }
  4076. /**
  4077. * Reconstructs a binary packet from its placeholder packet and buffers
  4078. *
  4079. * @param {Object} packet - event packet with placeholders
  4080. * @param {Array} buffers - binary buffers to put in placeholder positions
  4081. * @return {Object} reconstructed packet
  4082. * @api public
  4083. */
  4084. exports.reconstructPacket = function(packet, buffers) {
  4085. var curPlaceHolder = 0;
  4086. function reconstructBinPackRecursive(data) {
  4087. if (data && data._placeholder) {
  4088. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  4089. return buf;
  4090. } else if (isArray(data)) {
  4091. for (var i = 0; i < data.length; i++) {
  4092. data[i] = reconstructBinPackRecursive(data[i]);
  4093. }
  4094. return data;
  4095. } else if (data && 'object' == typeof data) {
  4096. for (var key in data) {
  4097. data[key] = reconstructBinPackRecursive(data[key]);
  4098. }
  4099. return data;
  4100. }
  4101. return data;
  4102. }
  4103. packet.data = reconstructBinPackRecursive(packet.data);
  4104. packet.attachments = undefined; // no longer useful
  4105. return packet;
  4106. }
  4107. /**
  4108. * Asynchronously removes Blobs or Files from data via
  4109. * FileReader's readAsArrayBuffer method. Used before encoding
  4110. * data as msgpack. Calls callback with the blobless data.
  4111. *
  4112. * @param {Object} data
  4113. * @param {Function} callback
  4114. * @api private
  4115. */
  4116. exports.removeBlobs = function(data, callback) {
  4117. function removeBlobsRecursive(obj, curKey, containingObject) {
  4118. if (!obj) return obj;
  4119. // convert any blob
  4120. if ((global.Blob && obj instanceof Blob) ||
  4121. (global.File && obj instanceof File)) {
  4122. pendingBlobs++;
  4123. // async filereader
  4124. var fileReader = new FileReader();
  4125. fileReader.onload = function() { // this.result == arraybuffer
  4126. if (containingObject) {
  4127. containingObject[curKey] = this.result;
  4128. }
  4129. else {
  4130. bloblessData = this.result;
  4131. }
  4132. // if nothing pending its callback time
  4133. if(! --pendingBlobs) {
  4134. callback(bloblessData);
  4135. }
  4136. };
  4137. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  4138. }
  4139. if (isArray(obj)) { // handle array
  4140. for (var i = 0; i < obj.length; i++) {
  4141. removeBlobsRecursive(obj[i], i, obj);
  4142. }
  4143. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  4144. for (var key in obj) {
  4145. removeBlobsRecursive(obj[key], key, obj);
  4146. }
  4147. }
  4148. }
  4149. var pendingBlobs = 0;
  4150. var bloblessData = data;
  4151. removeBlobsRecursive(bloblessData);
  4152. if (!pendingBlobs) {
  4153. callback(bloblessData);
  4154. }
  4155. }
  4156. /**
  4157. * Returns true if obj is a buffer or an arraybuffer.
  4158. *
  4159. * @api private
  4160. */
  4161. function isBuf(obj) {
  4162. return (global.Buffer && Buffer.isBuffer(obj)) ||
  4163. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  4164. }
  4165. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
  4166. },{"buffer":46,"isarray":43}],41:[function(_dereq_,module,exports){
  4167. (function (global,Buffer){
  4168. /**
  4169. * Module dependencies.
  4170. */
  4171. var debug = _dereq_('debug')('socket.io-parser');
  4172. var json = _dereq_('json3');
  4173. var isArray = _dereq_('isarray');
  4174. var Emitter = _dereq_('emitter');
  4175. var binary = _dereq_('./binary');
  4176. /**
  4177. * Protocol version.
  4178. *
  4179. * @api public
  4180. */
  4181. exports.protocol = 3;
  4182. /**
  4183. * Packet types.
  4184. *
  4185. * @api public
  4186. */
  4187. exports.types = [
  4188. 'CONNECT',
  4189. 'DISCONNECT',
  4190. 'EVENT',
  4191. 'BINARY_EVENT',
  4192. 'ACK',
  4193. 'BINARY_ACK',
  4194. 'ERROR'
  4195. ];
  4196. /**
  4197. * Packet type `connect`.
  4198. *
  4199. * @api public
  4200. */
  4201. exports.CONNECT = 0;
  4202. /**
  4203. * Packet type `disconnect`.
  4204. *
  4205. * @api public
  4206. */
  4207. exports.DISCONNECT = 1;
  4208. /**
  4209. * Packet type `event`.
  4210. *
  4211. * @api public
  4212. */
  4213. exports.EVENT = 2;
  4214. /**
  4215. * Packet type `ack`.
  4216. *
  4217. * @api public
  4218. */
  4219. exports.ACK = 3;
  4220. /**
  4221. * Packet type `error`.
  4222. *
  4223. * @api public
  4224. */
  4225. exports.ERROR = 4;
  4226. /**
  4227. * Packet type 'binary event'
  4228. *
  4229. * @api public
  4230. */
  4231. exports.BINARY_EVENT = 5;
  4232. /**
  4233. * Packet type `binary ack`. For acks with binary arguments.
  4234. *
  4235. * @api public
  4236. */
  4237. exports.BINARY_ACK = 6;
  4238. exports.Encoder = Encoder
  4239. /**
  4240. * A socket.io Encoder instance
  4241. *
  4242. * @api public
  4243. */
  4244. function Encoder() {};
  4245. /**
  4246. * Encode a packet as a single string if non-binary, or as a
  4247. * buffer sequence, depending on packet type.
  4248. *
  4249. * @param {Object} obj - packet object
  4250. * @param {Function} callback - function to handle encodings (likely engine.write)
  4251. * @return Calls callback with Array of encodings
  4252. * @api public
  4253. */
  4254. Encoder.prototype.encode = function(obj, callback){
  4255. debug('encoding packet %j', obj);
  4256. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  4257. encodeAsBinary(obj, callback);
  4258. }
  4259. else {
  4260. var encoding = encodeAsString(obj);
  4261. callback([encoding]);
  4262. }
  4263. };
  4264. /**
  4265. * Encode packet as string.
  4266. *
  4267. * @param {Object} packet
  4268. * @return {String} encoded
  4269. * @api private
  4270. */
  4271. function encodeAsString(obj) {
  4272. var str = '';
  4273. var nsp = false;
  4274. // first is type
  4275. str += obj.type;
  4276. // attachments if we have them
  4277. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  4278. str += obj.attachments;
  4279. str += '-';
  4280. }
  4281. // if we have a namespace other than `/`
  4282. // we append it followed by a comma `,`
  4283. if (obj.nsp && '/' != obj.nsp) {
  4284. nsp = true;
  4285. str += obj.nsp;
  4286. }
  4287. // immediately followed by the id
  4288. if (null != obj.id) {
  4289. if (nsp) {
  4290. str += ',';
  4291. nsp = false;
  4292. }
  4293. str += obj.id;
  4294. }
  4295. // json data
  4296. if (null != obj.data) {
  4297. if (nsp) str += ',';
  4298. str += json.stringify(obj.data);
  4299. }
  4300. debug('encoded %j as %s', obj, str);
  4301. return str;
  4302. }
  4303. /**
  4304. * Encode packet as 'buffer sequence' by removing blobs, and
  4305. * deconstructing packet into object with placeholders and
  4306. * a list of buffers.
  4307. *
  4308. * @param {Object} packet
  4309. * @return {Buffer} encoded
  4310. * @api private
  4311. */
  4312. function encodeAsBinary(obj, callback) {
  4313. function writeEncoding(bloblessData) {
  4314. var deconstruction = binary.deconstructPacket(bloblessData);
  4315. var pack = encodeAsString(deconstruction.packet);
  4316. var buffers = deconstruction.buffers;
  4317. buffers.unshift(pack); // add packet info to beginning of data list
  4318. callback(buffers); // write all the buffers
  4319. }
  4320. binary.removeBlobs(obj, writeEncoding);
  4321. }
  4322. exports.Decoder = Decoder
  4323. /**
  4324. * A socket.io Decoder instance
  4325. *
  4326. * @return {Object} decoder
  4327. * @api public
  4328. */
  4329. function Decoder() {
  4330. this.reconstructor = null;
  4331. }
  4332. /**
  4333. * Mix in `Emitter` with Decoder.
  4334. */
  4335. Emitter(Decoder.prototype);
  4336. /**
  4337. * Decodes an ecoded packet string into packet JSON.
  4338. *
  4339. * @param {String} obj - encoded packet
  4340. * @return {Object} packet
  4341. * @api public
  4342. */
  4343. Decoder.prototype.add = function(obj) {
  4344. var packet;
  4345. if ('string' == typeof obj) {
  4346. packet = decodeString(obj);
  4347. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  4348. this.reconstructor = new BinaryReconstructor(packet);
  4349. // no attachments, labeled binary but no binary data to follow
  4350. if (this.reconstructor.reconPack.attachments == 0) {
  4351. this.emit('decoded', packet);
  4352. }
  4353. } else { // non-binary full packet
  4354. this.emit('decoded', packet);
  4355. }
  4356. }
  4357. else if ((global.Buffer && Buffer.isBuffer(obj)) ||
  4358. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  4359. obj.base64) { // raw binary data
  4360. if (!this.reconstructor) {
  4361. throw new Error('got binary data when not reconstructing a packet');
  4362. } else {
  4363. packet = this.reconstructor.takeBinaryData(obj);
  4364. if (packet) { // received final buffer
  4365. this.reconstructor = null;
  4366. this.emit('decoded', packet);
  4367. }
  4368. }
  4369. }
  4370. else {
  4371. throw new Error('Unknown type: ' + obj);
  4372. }
  4373. }
  4374. /**
  4375. * Decode a packet String (JSON data)
  4376. *
  4377. * @param {String} str
  4378. * @return {Object} packet
  4379. * @api private
  4380. */
  4381. function decodeString(str) {
  4382. var p = {};
  4383. var i = 0;
  4384. // look up type
  4385. p.type = Number(str.charAt(0));
  4386. if (null == exports.types[p.type]) return error();
  4387. // look up attachments if type binary
  4388. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  4389. p.attachments = '';
  4390. while (str.charAt(++i) != '-') {
  4391. p.attachments += str.charAt(i);
  4392. }
  4393. p.attachments = Number(p.attachments);
  4394. }
  4395. // look up namespace (if any)
  4396. if ('/' == str.charAt(i + 1)) {
  4397. p.nsp = '';
  4398. while (++i) {
  4399. var c = str.charAt(i);
  4400. if (',' == c) break;
  4401. p.nsp += c;
  4402. if (i + 1 == str.length) break;
  4403. }
  4404. } else {
  4405. p.nsp = '/';
  4406. }
  4407. // look up id
  4408. var next = str.charAt(i + 1);
  4409. if ('' != next && Number(next) == next) {
  4410. p.id = '';
  4411. while (++i) {
  4412. var c = str.charAt(i);
  4413. if (null == c || Number(c) != c) {
  4414. --i;
  4415. break;
  4416. }
  4417. p.id += str.charAt(i);
  4418. if (i + 1 == str.length) break;
  4419. }
  4420. p.id = Number(p.id);
  4421. }
  4422. // look up json data
  4423. if (str.charAt(++i)) {
  4424. try {
  4425. p.data = json.parse(str.substr(i));
  4426. } catch(e){
  4427. return error();
  4428. }
  4429. }
  4430. debug('decoded %s as %j', str, p);
  4431. return p;
  4432. };
  4433. /**
  4434. * Deallocates a parser's resources
  4435. *
  4436. * @api public
  4437. */
  4438. Decoder.prototype.destroy = function() {
  4439. if (this.reconstructor) {
  4440. this.reconstructor.finishedReconstruction();
  4441. }
  4442. }
  4443. /**
  4444. * A manager of a binary event's 'buffer sequence'. Should
  4445. * be constructed whenever a packet of type BINARY_EVENT is
  4446. * decoded.
  4447. *
  4448. * @param {Object} packet
  4449. * @return {BinaryReconstructor} initialized reconstructor
  4450. * @api private
  4451. */
  4452. function BinaryReconstructor(packet) {
  4453. this.reconPack = packet;
  4454. this.buffers = [];
  4455. }
  4456. /**
  4457. * Method to be called when binary data received from connection
  4458. * after a BINARY_EVENT packet.
  4459. *
  4460. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  4461. * @return {null | Object} returns null if more binary data is expected or
  4462. * a reconstructed packet object if all buffers have been received.
  4463. * @api private
  4464. */
  4465. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  4466. this.buffers.push(binData);
  4467. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  4468. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  4469. this.finishedReconstruction();
  4470. return packet;
  4471. }
  4472. return null;
  4473. }
  4474. /**
  4475. * Cleans up binary packet reconstruction variables.
  4476. *
  4477. * @api private
  4478. */
  4479. BinaryReconstructor.prototype.finishedReconstruction = function() {
  4480. this.reconPack = null;
  4481. this.buffers = [];
  4482. }
  4483. function error(data){
  4484. return {
  4485. type: exports.ERROR,
  4486. data: 'parser error'
  4487. };
  4488. }
  4489. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
  4490. },{"./binary":40,"buffer":46,"debug":11,"emitter":42,"isarray":43,"json3":44}],42:[function(_dereq_,module,exports){
  4491. /**
  4492. * Module dependencies.
  4493. */
  4494. var index = _dereq_('indexof');
  4495. /**
  4496. * Expose `Emitter`.
  4497. */
  4498. module.exports = Emitter;
  4499. /**
  4500. * Initialize a new `Emitter`.
  4501. *
  4502. * @api public
  4503. */
  4504. function Emitter(obj) {
  4505. if (obj) return mixin(obj);
  4506. };
  4507. /**
  4508. * Mixin the emitter properties.
  4509. *
  4510. * @param {Object} obj
  4511. * @return {Object}
  4512. * @api private
  4513. */
  4514. function mixin(obj) {
  4515. for (var key in Emitter.prototype) {
  4516. obj[key] = Emitter.prototype[key];
  4517. }
  4518. return obj;
  4519. }
  4520. /**
  4521. * Listen on the given `event` with `fn`.
  4522. *
  4523. * @param {String} event
  4524. * @param {Function} fn
  4525. * @return {Emitter}
  4526. * @api public
  4527. */
  4528. Emitter.prototype.on = function(event, fn){
  4529. this._callbacks = this._callbacks || {};
  4530. (this._callbacks[event] = this._callbacks[event] || [])
  4531. .push(fn);
  4532. return this;
  4533. };
  4534. /**
  4535. * Adds an `event` listener that will be invoked a single
  4536. * time then automatically removed.
  4537. *
  4538. * @param {String} event
  4539. * @param {Function} fn
  4540. * @return {Emitter}
  4541. * @api public
  4542. */
  4543. Emitter.prototype.once = function(event, fn){
  4544. var self = this;
  4545. this._callbacks = this._callbacks || {};
  4546. function on() {
  4547. self.off(event, on);
  4548. fn.apply(this, arguments);
  4549. }
  4550. fn._off = on;
  4551. this.on(event, on);
  4552. return this;
  4553. };
  4554. /**
  4555. * Remove the given callback for `event` or all
  4556. * registered callbacks.
  4557. *
  4558. * @param {String} event
  4559. * @param {Function} fn
  4560. * @return {Emitter}
  4561. * @api public
  4562. */
  4563. Emitter.prototype.off =
  4564. Emitter.prototype.removeListener =
  4565. Emitter.prototype.removeAllListeners = function(event, fn){
  4566. this._callbacks = this._callbacks || {};
  4567. // all
  4568. if (0 == arguments.length) {
  4569. this._callbacks = {};
  4570. return this;
  4571. }
  4572. // specific event
  4573. var callbacks = this._callbacks[event];
  4574. if (!callbacks) return this;
  4575. // remove all handlers
  4576. if (1 == arguments.length) {
  4577. delete this._callbacks[event];
  4578. return this;
  4579. }
  4580. // remove specific handler
  4581. var i = index(callbacks, fn._off || fn);
  4582. if (~i) callbacks.splice(i, 1);
  4583. return this;
  4584. };
  4585. /**
  4586. * Emit `event` with the given args.
  4587. *
  4588. * @param {String} event
  4589. * @param {Mixed} ...
  4590. * @return {Emitter}
  4591. */
  4592. Emitter.prototype.emit = function(event){
  4593. this._callbacks = this._callbacks || {};
  4594. var args = [].slice.call(arguments, 1)
  4595. , callbacks = this._callbacks[event];
  4596. if (callbacks) {
  4597. callbacks = callbacks.slice(0);
  4598. for (var i = 0, len = callbacks.length; i < len; ++i) {
  4599. callbacks[i].apply(this, args);
  4600. }
  4601. }
  4602. return this;
  4603. };
  4604. /**
  4605. * Return array of callbacks for `event`.
  4606. *
  4607. * @param {String} event
  4608. * @return {Array}
  4609. * @api public
  4610. */
  4611. Emitter.prototype.listeners = function(event){
  4612. this._callbacks = this._callbacks || {};
  4613. return this._callbacks[event] || [];
  4614. };
  4615. /**
  4616. * Check if this emitter has `event` handlers.
  4617. *
  4618. * @param {String} event
  4619. * @return {Boolean}
  4620. * @api public
  4621. */
  4622. Emitter.prototype.hasListeners = function(event){
  4623. return !! this.listeners(event).length;
  4624. };
  4625. },{"indexof":37}],43:[function(_dereq_,module,exports){
  4626. module.exports=_dereq_(36)
  4627. },{}],44:[function(_dereq_,module,exports){
  4628. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  4629. ;(function (window) {
  4630. // Convenience aliases.
  4631. var getClass = {}.toString, isProperty, forEach, undef;
  4632. // Detect the `define` function exposed by asynchronous module loaders. The
  4633. // strict `define` check is necessary for compatibility with `r.js`.
  4634. var isLoader = typeof define === "function" && define.amd;
  4635. // Detect native implementations.
  4636. var nativeJSON = typeof JSON == "object" && JSON;
  4637. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  4638. // available.
  4639. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  4640. if (JSON3 && nativeJSON) {
  4641. // Explicitly delegate to the native `stringify` and `parse`
  4642. // implementations in CommonJS environments.
  4643. JSON3.stringify = nativeJSON.stringify;
  4644. JSON3.parse = nativeJSON.parse;
  4645. } else {
  4646. // Export for web browsers, JavaScript engines, and asynchronous module
  4647. // loaders, using the global `JSON` object if available.
  4648. JSON3 = window.JSON = nativeJSON || {};
  4649. }
  4650. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  4651. var isExtended = new Date(-3509827334573292);
  4652. try {
  4653. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  4654. // results for certain dates in Opera >= 10.53.
  4655. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  4656. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  4657. // but clips the values returned by the date methods to the range of
  4658. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  4659. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  4660. } catch (exception) {}
  4661. // Internal: Determines whether the native `JSON.stringify` and `parse`
  4662. // implementations are spec-compliant. Based on work by Ken Snyder.
  4663. function has(name) {
  4664. if (has[name] !== undef) {
  4665. // Return cached feature test result.
  4666. return has[name];
  4667. }
  4668. var isSupported;
  4669. if (name == "bug-string-char-index") {
  4670. // IE <= 7 doesn't support accessing string characters using square
  4671. // bracket notation. IE 8 only supports this for primitives.
  4672. isSupported = "a"[0] != "a";
  4673. } else if (name == "json") {
  4674. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  4675. // supported.
  4676. isSupported = has("json-stringify") && has("json-parse");
  4677. } else {
  4678. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  4679. // Test `JSON.stringify`.
  4680. if (name == "json-stringify") {
  4681. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  4682. if (stringifySupported) {
  4683. // A test function object with a custom `toJSON` method.
  4684. (value = function () {
  4685. return 1;
  4686. }).toJSON = value;
  4687. try {
  4688. stringifySupported =
  4689. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  4690. // primitives as object literals.
  4691. stringify(0) === "0" &&
  4692. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  4693. // literals.
  4694. stringify(new Number()) === "0" &&
  4695. stringify(new String()) == '""' &&
  4696. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  4697. // does not define a canonical JSON representation (this applies to
  4698. // objects with `toJSON` properties as well, *unless* they are nested
  4699. // within an object or array).
  4700. stringify(getClass) === undef &&
  4701. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  4702. // FF 3.1b3 pass this test.
  4703. stringify(undef) === undef &&
  4704. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  4705. // respectively, if the value is omitted entirely.
  4706. stringify() === undef &&
  4707. // FF 3.1b1, 2 throw an error if the given value is not a number,
  4708. // string, array, object, Boolean, or `null` literal. This applies to
  4709. // objects with custom `toJSON` methods as well, unless they are nested
  4710. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  4711. // methods entirely.
  4712. stringify(value) === "1" &&
  4713. stringify([value]) == "[1]" &&
  4714. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  4715. // `"[null]"`.
  4716. stringify([undef]) == "[null]" &&
  4717. // YUI 3.0.0b1 fails to serialize `null` literals.
  4718. stringify(null) == "null" &&
  4719. // FF 3.1b1, 2 halts serialization if an array contains a function:
  4720. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  4721. // elides non-JSON values from objects and arrays, unless they
  4722. // define custom `toJSON` methods.
  4723. stringify([undef, getClass, null]) == "[null,null,null]" &&
  4724. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  4725. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  4726. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  4727. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  4728. stringify(null, value) === "1" &&
  4729. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  4730. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  4731. // serialize extended years.
  4732. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  4733. // The milliseconds are optional in ES 5, but required in 5.1.
  4734. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  4735. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  4736. // four-digit years instead of six-digit years. Credits: @Yaffle.
  4737. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  4738. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  4739. // values less than 1000. Credits: @Yaffle.
  4740. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  4741. } catch (exception) {
  4742. stringifySupported = false;
  4743. }
  4744. }
  4745. isSupported = stringifySupported;
  4746. }
  4747. // Test `JSON.parse`.
  4748. if (name == "json-parse") {
  4749. var parse = JSON3.parse;
  4750. if (typeof parse == "function") {
  4751. try {
  4752. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  4753. // Conforming implementations should also coerce the initial argument to
  4754. // a string prior to parsing.
  4755. if (parse("0") === 0 && !parse(false)) {
  4756. // Simple parsing test.
  4757. value = parse(serialized);
  4758. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  4759. if (parseSupported) {
  4760. try {
  4761. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  4762. parseSupported = !parse('"\t"');
  4763. } catch (exception) {}
  4764. if (parseSupported) {
  4765. try {
  4766. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  4767. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  4768. // certain octal literals.
  4769. parseSupported = parse("01") !== 1;
  4770. } catch (exception) {}
  4771. }
  4772. if (parseSupported) {
  4773. try {
  4774. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  4775. // points. These environments, along with FF 3.1b1 and 2,
  4776. // also allow trailing commas in JSON objects and arrays.
  4777. parseSupported = parse("1.") !== 1;
  4778. } catch (exception) {}
  4779. }
  4780. }
  4781. }
  4782. } catch (exception) {
  4783. parseSupported = false;
  4784. }
  4785. }
  4786. isSupported = parseSupported;
  4787. }
  4788. }
  4789. return has[name] = !!isSupported;
  4790. }
  4791. if (!has("json")) {
  4792. // Common `[[Class]]` name aliases.
  4793. var functionClass = "[object Function]";
  4794. var dateClass = "[object Date]";
  4795. var numberClass = "[object Number]";
  4796. var stringClass = "[object String]";
  4797. var arrayClass = "[object Array]";
  4798. var booleanClass = "[object Boolean]";
  4799. // Detect incomplete support for accessing string characters by index.
  4800. var charIndexBuggy = has("bug-string-char-index");
  4801. // Define additional utility methods if the `Date` methods are buggy.
  4802. if (!isExtended) {
  4803. var floor = Math.floor;
  4804. // A mapping between the months of the year and the number of days between
  4805. // January 1st and the first of the respective month.
  4806. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  4807. // Internal: Calculates the number of days between the Unix epoch and the
  4808. // first day of the given month.
  4809. var getDay = function (year, month) {
  4810. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  4811. };
  4812. }
  4813. // Internal: Determines if a property is a direct property of the given
  4814. // object. Delegates to the native `Object#hasOwnProperty` method.
  4815. if (!(isProperty = {}.hasOwnProperty)) {
  4816. isProperty = function (property) {
  4817. var members = {}, constructor;
  4818. if ((members.__proto__ = null, members.__proto__ = {
  4819. // The *proto* property cannot be set multiple times in recent
  4820. // versions of Firefox and SeaMonkey.
  4821. "toString": 1
  4822. }, members).toString != getClass) {
  4823. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  4824. // supports the mutable *proto* property.
  4825. isProperty = function (property) {
  4826. // Capture and break the object's prototype chain (see section 8.6.2
  4827. // of the ES 5.1 spec). The parenthesized expression prevents an
  4828. // unsafe transformation by the Closure Compiler.
  4829. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  4830. // Restore the original prototype chain.
  4831. this.__proto__ = original;
  4832. return result;
  4833. };
  4834. } else {
  4835. // Capture a reference to the top-level `Object` constructor.
  4836. constructor = members.constructor;
  4837. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  4838. // other environments.
  4839. isProperty = function (property) {
  4840. var parent = (this.constructor || constructor).prototype;
  4841. return property in this && !(property in parent && this[property] === parent[property]);
  4842. };
  4843. }
  4844. members = null;
  4845. return isProperty.call(this, property);
  4846. };
  4847. }
  4848. // Internal: A set of primitive types used by `isHostType`.
  4849. var PrimitiveTypes = {
  4850. 'boolean': 1,
  4851. 'number': 1,
  4852. 'string': 1,
  4853. 'undefined': 1
  4854. };
  4855. // Internal: Determines if the given object `property` value is a
  4856. // non-primitive.
  4857. var isHostType = function (object, property) {
  4858. var type = typeof object[property];
  4859. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  4860. };
  4861. // Internal: Normalizes the `for...in` iteration algorithm across
  4862. // environments. Each enumerated key is yielded to a `callback` function.
  4863. forEach = function (object, callback) {
  4864. var size = 0, Properties, members, property;
  4865. // Tests for bugs in the current environment's `for...in` algorithm. The
  4866. // `valueOf` property inherits the non-enumerable flag from
  4867. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  4868. (Properties = function () {
  4869. this.valueOf = 0;
  4870. }).prototype.valueOf = 0;
  4871. // Iterate over a new instance of the `Properties` class.
  4872. members = new Properties();
  4873. for (property in members) {
  4874. // Ignore all properties inherited from `Object.prototype`.
  4875. if (isProperty.call(members, property)) {
  4876. size++;
  4877. }
  4878. }
  4879. Properties = members = null;
  4880. // Normalize the iteration algorithm.
  4881. if (!size) {
  4882. // A list of non-enumerable properties inherited from `Object.prototype`.
  4883. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  4884. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  4885. // properties.
  4886. forEach = function (object, callback) {
  4887. var isFunction = getClass.call(object) == functionClass, property, length;
  4888. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  4889. for (property in object) {
  4890. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  4891. // certain conditions; IE does not.
  4892. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  4893. callback(property);
  4894. }
  4895. }
  4896. // Manually invoke the callback for each non-enumerable property.
  4897. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  4898. };
  4899. } else if (size == 2) {
  4900. // Safari <= 2.0.4 enumerates shadowed properties twice.
  4901. forEach = function (object, callback) {
  4902. // Create a set of iterated properties.
  4903. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  4904. for (property in object) {
  4905. // Store each property name to prevent double enumeration. The
  4906. // `prototype` property of functions is not enumerated due to cross-
  4907. // environment inconsistencies.
  4908. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  4909. callback(property);
  4910. }
  4911. }
  4912. };
  4913. } else {
  4914. // No bugs detected; use the standard `for...in` algorithm.
  4915. forEach = function (object, callback) {
  4916. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  4917. for (property in object) {
  4918. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  4919. callback(property);
  4920. }
  4921. }
  4922. // Manually invoke the callback for the `constructor` property due to
  4923. // cross-environment inconsistencies.
  4924. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  4925. callback(property);
  4926. }
  4927. };
  4928. }
  4929. return forEach(object, callback);
  4930. };
  4931. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  4932. // `filter` argument may specify either a function that alters how object and
  4933. // array members are serialized, or an array of strings and numbers that
  4934. // indicates which properties should be serialized. The optional `width`
  4935. // argument may be either a string or number that specifies the indentation
  4936. // level of the output.
  4937. if (!has("json-stringify")) {
  4938. // Internal: A map of control characters and their escaped equivalents.
  4939. var Escapes = {
  4940. 92: "\\\\",
  4941. 34: '\\"',
  4942. 8: "\\b",
  4943. 12: "\\f",
  4944. 10: "\\n",
  4945. 13: "\\r",
  4946. 9: "\\t"
  4947. };
  4948. // Internal: Converts `value` into a zero-padded string such that its
  4949. // length is at least equal to `width`. The `width` must be <= 6.
  4950. var leadingZeroes = "000000";
  4951. var toPaddedString = function (width, value) {
  4952. // The `|| 0` expression is necessary to work around a bug in
  4953. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  4954. return (leadingZeroes + (value || 0)).slice(-width);
  4955. };
  4956. // Internal: Double-quotes a string `value`, replacing all ASCII control
  4957. // characters (characters with code unit values between 0 and 31) with
  4958. // their escaped equivalents. This is an implementation of the
  4959. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  4960. var unicodePrefix = "\\u00";
  4961. var quote = function (value) {
  4962. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  4963. if (isLarge) {
  4964. symbols = value.split("");
  4965. }
  4966. for (; index < length; index++) {
  4967. var charCode = value.charCodeAt(index);
  4968. // If the character is a control character, append its Unicode or
  4969. // shorthand escape sequence; otherwise, append the character as-is.
  4970. switch (charCode) {
  4971. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  4972. result += Escapes[charCode];
  4973. break;
  4974. default:
  4975. if (charCode < 32) {
  4976. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  4977. break;
  4978. }
  4979. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  4980. }
  4981. }
  4982. return result + '"';
  4983. };
  4984. // Internal: Recursively serializes an object. Implements the
  4985. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  4986. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  4987. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  4988. try {
  4989. // Necessary for host object support.
  4990. value = object[property];
  4991. } catch (exception) {}
  4992. if (typeof value == "object" && value) {
  4993. className = getClass.call(value);
  4994. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  4995. if (value > -1 / 0 && value < 1 / 0) {
  4996. // Dates are serialized according to the `Date#toJSON` method
  4997. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  4998. // for the ISO 8601 date time string format.
  4999. if (getDay) {
  5000. // Manually compute the year, month, date, hours, minutes,
  5001. // seconds, and milliseconds if the `getUTC*` methods are
  5002. // buggy. Adapted from @Yaffle's `date-shim` project.
  5003. date = floor(value / 864e5);
  5004. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  5005. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  5006. date = 1 + date - getDay(year, month);
  5007. // The `time` value specifies the time within the day (see ES
  5008. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  5009. // to compute `A modulo B`, as the `%` operator does not
  5010. // correspond to the `modulo` operation for negative numbers.
  5011. time = (value % 864e5 + 864e5) % 864e5;
  5012. // The hours, minutes, seconds, and milliseconds are obtained by
  5013. // decomposing the time within the day. See section 15.9.1.10.
  5014. hours = floor(time / 36e5) % 24;
  5015. minutes = floor(time / 6e4) % 60;
  5016. seconds = floor(time / 1e3) % 60;
  5017. milliseconds = time % 1e3;
  5018. } else {
  5019. year = value.getUTCFullYear();
  5020. month = value.getUTCMonth();
  5021. date = value.getUTCDate();
  5022. hours = value.getUTCHours();
  5023. minutes = value.getUTCMinutes();
  5024. seconds = value.getUTCSeconds();
  5025. milliseconds = value.getUTCMilliseconds();
  5026. }
  5027. // Serialize extended years correctly.
  5028. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  5029. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  5030. // Months, dates, hours, minutes, and seconds should have two
  5031. // digits; milliseconds should have three.
  5032. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  5033. // Milliseconds are optional in ES 5.0, but required in 5.1.
  5034. "." + toPaddedString(3, milliseconds) + "Z";
  5035. } else {
  5036. value = null;
  5037. }
  5038. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  5039. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  5040. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  5041. // ignores all `toJSON` methods on these objects unless they are
  5042. // defined directly on an instance.
  5043. value = value.toJSON(property);
  5044. }
  5045. }
  5046. if (callback) {
  5047. // If a replacement function was provided, call it to obtain the value
  5048. // for serialization.
  5049. value = callback.call(object, property, value);
  5050. }
  5051. if (value === null) {
  5052. return "null";
  5053. }
  5054. className = getClass.call(value);
  5055. if (className == booleanClass) {
  5056. // Booleans are represented literally.
  5057. return "" + value;
  5058. } else if (className == numberClass) {
  5059. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  5060. // `"null"`.
  5061. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  5062. } else if (className == stringClass) {
  5063. // Strings are double-quoted and escaped.
  5064. return quote("" + value);
  5065. }
  5066. // Recursively serialize objects and arrays.
  5067. if (typeof value == "object") {
  5068. // Check for cyclic structures. This is a linear search; performance
  5069. // is inversely proportional to the number of unique nested objects.
  5070. for (length = stack.length; length--;) {
  5071. if (stack[length] === value) {
  5072. // Cyclic structures cannot be serialized by `JSON.stringify`.
  5073. throw TypeError();
  5074. }
  5075. }
  5076. // Add the object to the stack of traversed objects.
  5077. stack.push(value);
  5078. results = [];
  5079. // Save the current indentation level and indent one additional level.
  5080. prefix = indentation;
  5081. indentation += whitespace;
  5082. if (className == arrayClass) {
  5083. // Recursively serialize array elements.
  5084. for (index = 0, length = value.length; index < length; index++) {
  5085. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  5086. results.push(element === undef ? "null" : element);
  5087. }
  5088. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  5089. } else {
  5090. // Recursively serialize object members. Members are selected from
  5091. // either a user-specified list of property names, or the object
  5092. // itself.
  5093. forEach(properties || value, function (property) {
  5094. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  5095. if (element !== undef) {
  5096. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  5097. // is not the empty string, let `member` {quote(property) + ":"}
  5098. // be the concatenation of `member` and the `space` character."
  5099. // The "`space` character" refers to the literal space
  5100. // character, not the `space` {width} argument provided to
  5101. // `JSON.stringify`.
  5102. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  5103. }
  5104. });
  5105. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  5106. }
  5107. // Remove the object from the traversed object stack.
  5108. stack.pop();
  5109. return result;
  5110. }
  5111. };
  5112. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  5113. JSON3.stringify = function (source, filter, width) {
  5114. var whitespace, callback, properties, className;
  5115. if (typeof filter == "function" || typeof filter == "object" && filter) {
  5116. if ((className = getClass.call(filter)) == functionClass) {
  5117. callback = filter;
  5118. } else if (className == arrayClass) {
  5119. // Convert the property names array into a makeshift set.
  5120. properties = {};
  5121. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  5122. }
  5123. }
  5124. if (width) {
  5125. if ((className = getClass.call(width)) == numberClass) {
  5126. // Convert the `width` to an integer and create a string containing
  5127. // `width` number of space characters.
  5128. if ((width -= width % 1) > 0) {
  5129. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  5130. }
  5131. } else if (className == stringClass) {
  5132. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  5133. }
  5134. }
  5135. // Opera <= 7.54u2 discards the values associated with empty string keys
  5136. // (`""`) only if they are used directly within an object member list
  5137. // (e.g., `!("" in { "": 1})`).
  5138. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  5139. };
  5140. }
  5141. // Public: Parses a JSON source string.
  5142. if (!has("json-parse")) {
  5143. var fromCharCode = String.fromCharCode;
  5144. // Internal: A map of escaped control characters and their unescaped
  5145. // equivalents.
  5146. var Unescapes = {
  5147. 92: "\\",
  5148. 34: '"',
  5149. 47: "/",
  5150. 98: "\b",
  5151. 116: "\t",
  5152. 110: "\n",
  5153. 102: "\f",
  5154. 114: "\r"
  5155. };
  5156. // Internal: Stores the parser state.
  5157. var Index, Source;
  5158. // Internal: Resets the parser state and throws a `SyntaxError`.
  5159. var abort = function() {
  5160. Index = Source = null;
  5161. throw SyntaxError();
  5162. };
  5163. // Internal: Returns the next token, or `"$"` if the parser has reached
  5164. // the end of the source string. A token may be a string, number, `null`
  5165. // literal, or Boolean literal.
  5166. var lex = function () {
  5167. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  5168. while (Index < length) {
  5169. charCode = source.charCodeAt(Index);
  5170. switch (charCode) {
  5171. case 9: case 10: case 13: case 32:
  5172. // Skip whitespace tokens, including tabs, carriage returns, line
  5173. // feeds, and space characters.
  5174. Index++;
  5175. break;
  5176. case 123: case 125: case 91: case 93: case 58: case 44:
  5177. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  5178. // the current position.
  5179. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  5180. Index++;
  5181. return value;
  5182. case 34:
  5183. // `"` delimits a JSON string; advance to the next character and
  5184. // begin parsing the string. String tokens are prefixed with the
  5185. // sentinel `@` character to distinguish them from punctuators and
  5186. // end-of-string tokens.
  5187. for (value = "@", Index++; Index < length;) {
  5188. charCode = source.charCodeAt(Index);
  5189. if (charCode < 32) {
  5190. // Unescaped ASCII control characters (those with a code unit
  5191. // less than the space character) are not permitted.
  5192. abort();
  5193. } else if (charCode == 92) {
  5194. // A reverse solidus (`\`) marks the beginning of an escaped
  5195. // control character (including `"`, `\`, and `/`) or Unicode
  5196. // escape sequence.
  5197. charCode = source.charCodeAt(++Index);
  5198. switch (charCode) {
  5199. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  5200. // Revive escaped control characters.
  5201. value += Unescapes[charCode];
  5202. Index++;
  5203. break;
  5204. case 117:
  5205. // `\u` marks the beginning of a Unicode escape sequence.
  5206. // Advance to the first character and validate the
  5207. // four-digit code point.
  5208. begin = ++Index;
  5209. for (position = Index + 4; Index < position; Index++) {
  5210. charCode = source.charCodeAt(Index);
  5211. // A valid sequence comprises four hexdigits (case-
  5212. // insensitive) that form a single hexadecimal value.
  5213. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  5214. // Invalid Unicode escape sequence.
  5215. abort();
  5216. }
  5217. }
  5218. // Revive the escaped character.
  5219. value += fromCharCode("0x" + source.slice(begin, Index));
  5220. break;
  5221. default:
  5222. // Invalid escape sequence.
  5223. abort();
  5224. }
  5225. } else {
  5226. if (charCode == 34) {
  5227. // An unescaped double-quote character marks the end of the
  5228. // string.
  5229. break;
  5230. }
  5231. charCode = source.charCodeAt(Index);
  5232. begin = Index;
  5233. // Optimize for the common case where a string is valid.
  5234. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  5235. charCode = source.charCodeAt(++Index);
  5236. }
  5237. // Append the string as-is.
  5238. value += source.slice(begin, Index);
  5239. }
  5240. }
  5241. if (source.charCodeAt(Index) == 34) {
  5242. // Advance to the next character and return the revived string.
  5243. Index++;
  5244. return value;
  5245. }
  5246. // Unterminated string.
  5247. abort();
  5248. default:
  5249. // Parse numbers and literals.
  5250. begin = Index;
  5251. // Advance past the negative sign, if one is specified.
  5252. if (charCode == 45) {
  5253. isSigned = true;
  5254. charCode = source.charCodeAt(++Index);
  5255. }
  5256. // Parse an integer or floating-point value.
  5257. if (charCode >= 48 && charCode <= 57) {
  5258. // Leading zeroes are interpreted as octal literals.
  5259. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  5260. // Illegal octal literal.
  5261. abort();
  5262. }
  5263. isSigned = false;
  5264. // Parse the integer component.
  5265. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  5266. // Floats cannot contain a leading decimal point; however, this
  5267. // case is already accounted for by the parser.
  5268. if (source.charCodeAt(Index) == 46) {
  5269. position = ++Index;
  5270. // Parse the decimal component.
  5271. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  5272. if (position == Index) {
  5273. // Illegal trailing decimal.
  5274. abort();
  5275. }
  5276. Index = position;
  5277. }
  5278. // Parse exponents. The `e` denoting the exponent is
  5279. // case-insensitive.
  5280. charCode = source.charCodeAt(Index);
  5281. if (charCode == 101 || charCode == 69) {
  5282. charCode = source.charCodeAt(++Index);
  5283. // Skip past the sign following the exponent, if one is
  5284. // specified.
  5285. if (charCode == 43 || charCode == 45) {
  5286. Index++;
  5287. }
  5288. // Parse the exponential component.
  5289. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  5290. if (position == Index) {
  5291. // Illegal empty exponent.
  5292. abort();
  5293. }
  5294. Index = position;
  5295. }
  5296. // Coerce the parsed value to a JavaScript number.
  5297. return +source.slice(begin, Index);
  5298. }
  5299. // A negative sign may only precede numbers.
  5300. if (isSigned) {
  5301. abort();
  5302. }
  5303. // `true`, `false`, and `null` literals.
  5304. if (source.slice(Index, Index + 4) == "true") {
  5305. Index += 4;
  5306. return true;
  5307. } else if (source.slice(Index, Index + 5) == "false") {
  5308. Index += 5;
  5309. return false;
  5310. } else if (source.slice(Index, Index + 4) == "null") {
  5311. Index += 4;
  5312. return null;
  5313. }
  5314. // Unrecognized token.
  5315. abort();
  5316. }
  5317. }
  5318. // Return the sentinel `$` character if the parser has reached the end
  5319. // of the source string.
  5320. return "$";
  5321. };
  5322. // Internal: Parses a JSON `value` token.
  5323. var get = function (value) {
  5324. var results, hasMembers;
  5325. if (value == "$") {
  5326. // Unexpected end of input.
  5327. abort();
  5328. }
  5329. if (typeof value == "string") {
  5330. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  5331. // Remove the sentinel `@` character.
  5332. return value.slice(1);
  5333. }
  5334. // Parse object and array literals.
  5335. if (value == "[") {
  5336. // Parses a JSON array, returning a new JavaScript array.
  5337. results = [];
  5338. for (;; hasMembers || (hasMembers = true)) {
  5339. value = lex();
  5340. // A closing square bracket marks the end of the array literal.
  5341. if (value == "]") {
  5342. break;
  5343. }
  5344. // If the array literal contains elements, the current token
  5345. // should be a comma separating the previous element from the
  5346. // next.
  5347. if (hasMembers) {
  5348. if (value == ",") {
  5349. value = lex();
  5350. if (value == "]") {
  5351. // Unexpected trailing `,` in array literal.
  5352. abort();
  5353. }
  5354. } else {
  5355. // A `,` must separate each array element.
  5356. abort();
  5357. }
  5358. }
  5359. // Elisions and leading commas are not permitted.
  5360. if (value == ",") {
  5361. abort();
  5362. }
  5363. results.push(get(value));
  5364. }
  5365. return results;
  5366. } else if (value == "{") {
  5367. // Parses a JSON object, returning a new JavaScript object.
  5368. results = {};
  5369. for (;; hasMembers || (hasMembers = true)) {
  5370. value = lex();
  5371. // A closing curly brace marks the end of the object literal.
  5372. if (value == "}") {
  5373. break;
  5374. }
  5375. // If the object literal contains members, the current token
  5376. // should be a comma separator.
  5377. if (hasMembers) {
  5378. if (value == ",") {
  5379. value = lex();
  5380. if (value == "}") {
  5381. // Unexpected trailing `,` in object literal.
  5382. abort();
  5383. }
  5384. } else {
  5385. // A `,` must separate each object member.
  5386. abort();
  5387. }
  5388. }
  5389. // Leading commas are not permitted, object property names must be
  5390. // double-quoted strings, and a `:` must separate each property
  5391. // name and value.
  5392. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  5393. abort();
  5394. }
  5395. results[value.slice(1)] = get(lex());
  5396. }
  5397. return results;
  5398. }
  5399. // Unexpected token encountered.
  5400. abort();
  5401. }
  5402. return value;
  5403. };
  5404. // Internal: Updates a traversed object member.
  5405. var update = function(source, property, callback) {
  5406. var element = walk(source, property, callback);
  5407. if (element === undef) {
  5408. delete source[property];
  5409. } else {
  5410. source[property] = element;
  5411. }
  5412. };
  5413. // Internal: Recursively traverses a parsed JSON object, invoking the
  5414. // `callback` function for each value. This is an implementation of the
  5415. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  5416. var walk = function (source, property, callback) {
  5417. var value = source[property], length;
  5418. if (typeof value == "object" && value) {
  5419. // `forEach` can't be used to traverse an array in Opera <= 8.54
  5420. // because its `Object#hasOwnProperty` implementation returns `false`
  5421. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  5422. if (getClass.call(value) == arrayClass) {
  5423. for (length = value.length; length--;) {
  5424. update(value, length, callback);
  5425. }
  5426. } else {
  5427. forEach(value, function (property) {
  5428. update(value, property, callback);
  5429. });
  5430. }
  5431. }
  5432. return callback.call(source, property, value);
  5433. };
  5434. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  5435. JSON3.parse = function (source, callback) {
  5436. var result, value;
  5437. Index = 0;
  5438. Source = "" + source;
  5439. result = get(lex());
  5440. // If a JSON string contains multiple tokens, it is invalid.
  5441. if (lex() != "$") {
  5442. abort();
  5443. }
  5444. // Reset the parser state.
  5445. Index = Source = null;
  5446. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  5447. };
  5448. }
  5449. }
  5450. // Export for asynchronous module loaders.
  5451. if (isLoader) {
  5452. define(function () {
  5453. return JSON3;
  5454. });
  5455. }
  5456. }(this));
  5457. },{}],45:[function(_dereq_,module,exports){
  5458. module.exports = toArray
  5459. function toArray(list, index) {
  5460. var array = []
  5461. index = index || 0
  5462. for (var i = index || 0; i < list.length; i++) {
  5463. array[i - index] = list[i]
  5464. }
  5465. return array
  5466. }
  5467. },{}],46:[function(_dereq_,module,exports){
  5468. /*!
  5469. * The buffer module from node.js, for the browser.
  5470. *
  5471. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  5472. * @license MIT
  5473. */
  5474. var base64 = _dereq_('base64-js')
  5475. var ieee754 = _dereq_('ieee754')
  5476. exports.Buffer = Buffer
  5477. exports.SlowBuffer = Buffer
  5478. exports.INSPECT_MAX_BYTES = 50
  5479. Buffer.poolSize = 8192
  5480. /**
  5481. * If `Buffer._useTypedArrays`:
  5482. * === true Use Uint8Array implementation (fastest)
  5483. * === false Use Object implementation (compatible down to IE6)
  5484. */
  5485. Buffer._useTypedArrays = (function () {
  5486. // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+,
  5487. // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding
  5488. // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support
  5489. // because we need to be able to add all the node Buffer API methods. This is an issue
  5490. // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
  5491. try {
  5492. var buf = new ArrayBuffer(0)
  5493. var arr = new Uint8Array(buf)
  5494. arr.foo = function () { return 42 }
  5495. return 42 === arr.foo() &&
  5496. typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
  5497. } catch (e) {
  5498. return false
  5499. }
  5500. })()
  5501. /**
  5502. * Class: Buffer
  5503. * =============
  5504. *
  5505. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  5506. * with function properties for all the node `Buffer` API functions. We use
  5507. * `Uint8Array` so that square bracket notation works as expected -- it returns
  5508. * a single octet.
  5509. *
  5510. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  5511. * prototype.
  5512. */
  5513. function Buffer (subject, encoding, noZero) {
  5514. if (!(this instanceof Buffer))
  5515. return new Buffer(subject, encoding, noZero)
  5516. var type = typeof subject
  5517. if (encoding === 'base64' && type === 'string') {
  5518. subject = base64clean(subject)
  5519. }
  5520. // Find the length
  5521. var length
  5522. if (type === 'number')
  5523. length = coerce(subject)
  5524. else if (type === 'string')
  5525. length = Buffer.byteLength(subject, encoding)
  5526. else if (type === 'object')
  5527. length = coerce(subject.length) // assume that object is array-like
  5528. else
  5529. throw new Error('First argument needs to be a number, array or string.')
  5530. var buf
  5531. if (Buffer._useTypedArrays) {
  5532. // Preferred: Return an augmented `Uint8Array` instance for best performance
  5533. buf = Buffer._augment(new Uint8Array(length))
  5534. } else {
  5535. // Fallback: Return THIS instance of Buffer (created by `new`)
  5536. buf = this
  5537. buf.length = length
  5538. buf._isBuffer = true
  5539. }
  5540. var i
  5541. if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
  5542. // Speed optimization -- use set if we're copying from a typed array
  5543. buf._set(subject)
  5544. } else if (isArrayish(subject)) {
  5545. // Treat array-ish objects as a byte array
  5546. if (Buffer.isBuffer(subject)) {
  5547. for (i = 0; i < length; i++)
  5548. buf[i] = subject.readUInt8(i)
  5549. } else {
  5550. for (i = 0; i < length; i++)
  5551. buf[i] = ((subject[i] % 256) + 256) % 256
  5552. }
  5553. } else if (type === 'string') {
  5554. buf.write(subject, 0, encoding)
  5555. } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
  5556. for (i = 0; i < length; i++) {
  5557. buf[i] = 0
  5558. }
  5559. }
  5560. return buf
  5561. }
  5562. // STATIC METHODS
  5563. // ==============
  5564. Buffer.isEncoding = function (encoding) {
  5565. switch (String(encoding).toLowerCase()) {
  5566. case 'hex':
  5567. case 'utf8':
  5568. case 'utf-8':
  5569. case 'ascii':
  5570. case 'binary':
  5571. case 'base64':
  5572. case 'raw':
  5573. case 'ucs2':
  5574. case 'ucs-2':
  5575. case 'utf16le':
  5576. case 'utf-16le':
  5577. return true
  5578. default:
  5579. return false
  5580. }
  5581. }
  5582. Buffer.isBuffer = function (b) {
  5583. return !!(b !== null && b !== undefined && b._isBuffer)
  5584. }
  5585. Buffer.byteLength = function (str, encoding) {
  5586. var ret
  5587. str = str.toString()
  5588. switch (encoding || 'utf8') {
  5589. case 'hex':
  5590. ret = str.length / 2
  5591. break
  5592. case 'utf8':
  5593. case 'utf-8':
  5594. ret = utf8ToBytes(str).length
  5595. break
  5596. case 'ascii':
  5597. case 'binary':
  5598. case 'raw':
  5599. ret = str.length
  5600. break
  5601. case 'base64':
  5602. ret = base64ToBytes(str).length
  5603. break
  5604. case 'ucs2':
  5605. case 'ucs-2':
  5606. case 'utf16le':
  5607. case 'utf-16le':
  5608. ret = str.length * 2
  5609. break
  5610. default:
  5611. throw new Error('Unknown encoding')
  5612. }
  5613. return ret
  5614. }
  5615. Buffer.concat = function (list, totalLength) {
  5616. assert(isArray(list), 'Usage: Buffer.concat(list[, length])')
  5617. if (list.length === 0) {
  5618. return new Buffer(0)
  5619. } else if (list.length === 1) {
  5620. return list[0]
  5621. }
  5622. var i
  5623. if (totalLength === undefined) {
  5624. totalLength = 0
  5625. for (i = 0; i < list.length; i++) {
  5626. totalLength += list[i].length
  5627. }
  5628. }
  5629. var buf = new Buffer(totalLength)
  5630. var pos = 0
  5631. for (i = 0; i < list.length; i++) {
  5632. var item = list[i]
  5633. item.copy(buf, pos)
  5634. pos += item.length
  5635. }
  5636. return buf
  5637. }
  5638. Buffer.compare = function (a, b) {
  5639. assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers')
  5640. var x = a.length
  5641. var y = b.length
  5642. for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
  5643. if (i !== len) {
  5644. x = a[i]
  5645. y = b[i]
  5646. }
  5647. if (x < y) {
  5648. return -1
  5649. }
  5650. if (y < x) {
  5651. return 1
  5652. }
  5653. return 0
  5654. }
  5655. // BUFFER INSTANCE METHODS
  5656. // =======================
  5657. function hexWrite (buf, string, offset, length) {
  5658. offset = Number(offset) || 0
  5659. var remaining = buf.length - offset
  5660. if (!length) {
  5661. length = remaining
  5662. } else {
  5663. length = Number(length)
  5664. if (length > remaining) {
  5665. length = remaining
  5666. }
  5667. }
  5668. // must be an even number of digits
  5669. var strLen = string.length
  5670. assert(strLen % 2 === 0, 'Invalid hex string')
  5671. if (length > strLen / 2) {
  5672. length = strLen / 2
  5673. }
  5674. for (var i = 0; i < length; i++) {
  5675. var byte = parseInt(string.substr(i * 2, 2), 16)
  5676. assert(!isNaN(byte), 'Invalid hex string')
  5677. buf[offset + i] = byte
  5678. }
  5679. return i
  5680. }
  5681. function utf8Write (buf, string, offset, length) {
  5682. var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
  5683. return charsWritten
  5684. }
  5685. function asciiWrite (buf, string, offset, length) {
  5686. var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
  5687. return charsWritten
  5688. }
  5689. function binaryWrite (buf, string, offset, length) {
  5690. return asciiWrite(buf, string, offset, length)
  5691. }
  5692. function base64Write (buf, string, offset, length) {
  5693. var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
  5694. return charsWritten
  5695. }
  5696. function utf16leWrite (buf, string, offset, length) {
  5697. var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
  5698. return charsWritten
  5699. }
  5700. Buffer.prototype.write = function (string, offset, length, encoding) {
  5701. // Support both (string, offset, length, encoding)
  5702. // and the legacy (string, encoding, offset, length)
  5703. if (isFinite(offset)) {
  5704. if (!isFinite(length)) {
  5705. encoding = length
  5706. length = undefined
  5707. }
  5708. } else { // legacy
  5709. var swap = encoding
  5710. encoding = offset
  5711. offset = length
  5712. length = swap
  5713. }
  5714. offset = Number(offset) || 0
  5715. var remaining = this.length - offset
  5716. if (!length) {
  5717. length = remaining
  5718. } else {
  5719. length = Number(length)
  5720. if (length > remaining) {
  5721. length = remaining
  5722. }
  5723. }
  5724. encoding = String(encoding || 'utf8').toLowerCase()
  5725. var ret
  5726. switch (encoding) {
  5727. case 'hex':
  5728. ret = hexWrite(this, string, offset, length)
  5729. break
  5730. case 'utf8':
  5731. case 'utf-8':
  5732. ret = utf8Write(this, string, offset, length)
  5733. break
  5734. case 'ascii':
  5735. ret = asciiWrite(this, string, offset, length)
  5736. break
  5737. case 'binary':
  5738. ret = binaryWrite(this, string, offset, length)
  5739. break
  5740. case 'base64':
  5741. ret = base64Write(this, string, offset, length)
  5742. break
  5743. case 'ucs2':
  5744. case 'ucs-2':
  5745. case 'utf16le':
  5746. case 'utf-16le':
  5747. ret = utf16leWrite(this, string, offset, length)
  5748. break
  5749. default:
  5750. throw new Error('Unknown encoding')
  5751. }
  5752. return ret
  5753. }
  5754. Buffer.prototype.toString = function (encoding, start, end) {
  5755. var self = this
  5756. encoding = String(encoding || 'utf8').toLowerCase()
  5757. start = Number(start) || 0
  5758. end = (end === undefined) ? self.length : Number(end)
  5759. // Fastpath empty strings
  5760. if (end === start)
  5761. return ''
  5762. var ret
  5763. switch (encoding) {
  5764. case 'hex':
  5765. ret = hexSlice(self, start, end)
  5766. break
  5767. case 'utf8':
  5768. case 'utf-8':
  5769. ret = utf8Slice(self, start, end)
  5770. break
  5771. case 'ascii':
  5772. ret = asciiSlice(self, start, end)
  5773. break
  5774. case 'binary':
  5775. ret = binarySlice(self, start, end)
  5776. break
  5777. case 'base64':
  5778. ret = base64Slice(self, start, end)
  5779. break
  5780. case 'ucs2':
  5781. case 'ucs-2':
  5782. case 'utf16le':
  5783. case 'utf-16le':
  5784. ret = utf16leSlice(self, start, end)
  5785. break
  5786. default:
  5787. throw new Error('Unknown encoding')
  5788. }
  5789. return ret
  5790. }
  5791. Buffer.prototype.toJSON = function () {
  5792. return {
  5793. type: 'Buffer',
  5794. data: Array.prototype.slice.call(this._arr || this, 0)
  5795. }
  5796. }
  5797. Buffer.prototype.equals = function (b) {
  5798. assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
  5799. return Buffer.compare(this, b) === 0
  5800. }
  5801. Buffer.prototype.compare = function (b) {
  5802. assert(Buffer.isBuffer(b), 'Argument must be a Buffer')
  5803. return Buffer.compare(this, b)
  5804. }
  5805. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  5806. Buffer.prototype.copy = function (target, target_start, start, end) {
  5807. var source = this
  5808. if (!start) start = 0
  5809. if (!end && end !== 0) end = this.length
  5810. if (!target_start) target_start = 0
  5811. // Copy 0 bytes; we're done
  5812. if (end === start) return
  5813. if (target.length === 0 || source.length === 0) return
  5814. // Fatal error conditions
  5815. assert(end >= start, 'sourceEnd < sourceStart')
  5816. assert(target_start >= 0 && target_start < target.length,
  5817. 'targetStart out of bounds')
  5818. assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
  5819. assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
  5820. // Are we oob?
  5821. if (end > this.length)
  5822. end = this.length
  5823. if (target.length - target_start < end - start)
  5824. end = target.length - target_start + start
  5825. var len = end - start
  5826. if (len < 100 || !Buffer._useTypedArrays) {
  5827. for (var i = 0; i < len; i++) {
  5828. target[i + target_start] = this[i + start]
  5829. }
  5830. } else {
  5831. target._set(this.subarray(start, start + len), target_start)
  5832. }
  5833. }
  5834. function base64Slice (buf, start, end) {
  5835. if (start === 0 && end === buf.length) {
  5836. return base64.fromByteArray(buf)
  5837. } else {
  5838. return base64.fromByteArray(buf.slice(start, end))
  5839. }
  5840. }
  5841. function utf8Slice (buf, start, end) {
  5842. var res = ''
  5843. var tmp = ''
  5844. end = Math.min(buf.length, end)
  5845. for (var i = start; i < end; i++) {
  5846. if (buf[i] <= 0x7F) {
  5847. res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
  5848. tmp = ''
  5849. } else {
  5850. tmp += '%' + buf[i].toString(16)
  5851. }
  5852. }
  5853. return res + decodeUtf8Char(tmp)
  5854. }
  5855. function asciiSlice (buf, start, end) {
  5856. var ret = ''
  5857. end = Math.min(buf.length, end)
  5858. for (var i = start; i < end; i++) {
  5859. ret += String.fromCharCode(buf[i])
  5860. }
  5861. return ret
  5862. }
  5863. function binarySlice (buf, start, end) {
  5864. return asciiSlice(buf, start, end)
  5865. }
  5866. function hexSlice (buf, start, end) {
  5867. var len = buf.length
  5868. if (!start || start < 0) start = 0
  5869. if (!end || end < 0 || end > len) end = len
  5870. var out = ''
  5871. for (var i = start; i < end; i++) {
  5872. out += toHex(buf[i])
  5873. }
  5874. return out
  5875. }
  5876. function utf16leSlice (buf, start, end) {
  5877. var bytes = buf.slice(start, end)
  5878. var res = ''
  5879. for (var i = 0; i < bytes.length; i += 2) {
  5880. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  5881. }
  5882. return res
  5883. }
  5884. Buffer.prototype.slice = function (start, end) {
  5885. var len = this.length
  5886. start = clamp(start, len, 0)
  5887. end = clamp(end, len, len)
  5888. if (Buffer._useTypedArrays) {
  5889. return Buffer._augment(this.subarray(start, end))
  5890. } else {
  5891. var sliceLen = end - start
  5892. var newBuf = new Buffer(sliceLen, undefined, true)
  5893. for (var i = 0; i < sliceLen; i++) {
  5894. newBuf[i] = this[i + start]
  5895. }
  5896. return newBuf
  5897. }
  5898. }
  5899. // `get` will be removed in Node 0.13+
  5900. Buffer.prototype.get = function (offset) {
  5901. console.log('.get() is deprecated. Access using array indexes instead.')
  5902. return this.readUInt8(offset)
  5903. }
  5904. // `set` will be removed in Node 0.13+
  5905. Buffer.prototype.set = function (v, offset) {
  5906. console.log('.set() is deprecated. Access using array indexes instead.')
  5907. return this.writeUInt8(v, offset)
  5908. }
  5909. Buffer.prototype.readUInt8 = function (offset, noAssert) {
  5910. if (!noAssert) {
  5911. assert(offset !== undefined && offset !== null, 'missing offset')
  5912. assert(offset < this.length, 'Trying to read beyond buffer length')
  5913. }
  5914. if (offset >= this.length)
  5915. return
  5916. return this[offset]
  5917. }
  5918. function readUInt16 (buf, offset, littleEndian, noAssert) {
  5919. if (!noAssert) {
  5920. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  5921. assert(offset !== undefined && offset !== null, 'missing offset')
  5922. assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
  5923. }
  5924. var len = buf.length
  5925. if (offset >= len)
  5926. return
  5927. var val
  5928. if (littleEndian) {
  5929. val = buf[offset]
  5930. if (offset + 1 < len)
  5931. val |= buf[offset + 1] << 8
  5932. } else {
  5933. val = buf[offset] << 8
  5934. if (offset + 1 < len)
  5935. val |= buf[offset + 1]
  5936. }
  5937. return val
  5938. }
  5939. Buffer.prototype.readUInt16LE = function (offset, noAssert) {
  5940. return readUInt16(this, offset, true, noAssert)
  5941. }
  5942. Buffer.prototype.readUInt16BE = function (offset, noAssert) {
  5943. return readUInt16(this, offset, false, noAssert)
  5944. }
  5945. function readUInt32 (buf, offset, littleEndian, noAssert) {
  5946. if (!noAssert) {
  5947. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  5948. assert(offset !== undefined && offset !== null, 'missing offset')
  5949. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  5950. }
  5951. var len = buf.length
  5952. if (offset >= len)
  5953. return
  5954. var val
  5955. if (littleEndian) {
  5956. if (offset + 2 < len)
  5957. val = buf[offset + 2] << 16
  5958. if (offset + 1 < len)
  5959. val |= buf[offset + 1] << 8
  5960. val |= buf[offset]
  5961. if (offset + 3 < len)
  5962. val = val + (buf[offset + 3] << 24 >>> 0)
  5963. } else {
  5964. if (offset + 1 < len)
  5965. val = buf[offset + 1] << 16
  5966. if (offset + 2 < len)
  5967. val |= buf[offset + 2] << 8
  5968. if (offset + 3 < len)
  5969. val |= buf[offset + 3]
  5970. val = val + (buf[offset] << 24 >>> 0)
  5971. }
  5972. return val
  5973. }
  5974. Buffer.prototype.readUInt32LE = function (offset, noAssert) {
  5975. return readUInt32(this, offset, true, noAssert)
  5976. }
  5977. Buffer.prototype.readUInt32BE = function (offset, noAssert) {
  5978. return readUInt32(this, offset, false, noAssert)
  5979. }
  5980. Buffer.prototype.readInt8 = function (offset, noAssert) {
  5981. if (!noAssert) {
  5982. assert(offset !== undefined && offset !== null,
  5983. 'missing offset')
  5984. assert(offset < this.length, 'Trying to read beyond buffer length')
  5985. }
  5986. if (offset >= this.length)
  5987. return
  5988. var neg = this[offset] & 0x80
  5989. if (neg)
  5990. return (0xff - this[offset] + 1) * -1
  5991. else
  5992. return this[offset]
  5993. }
  5994. function readInt16 (buf, offset, littleEndian, noAssert) {
  5995. if (!noAssert) {
  5996. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  5997. assert(offset !== undefined && offset !== null, 'missing offset')
  5998. assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
  5999. }
  6000. var len = buf.length
  6001. if (offset >= len)
  6002. return
  6003. var val = readUInt16(buf, offset, littleEndian, true)
  6004. var neg = val & 0x8000
  6005. if (neg)
  6006. return (0xffff - val + 1) * -1
  6007. else
  6008. return val
  6009. }
  6010. Buffer.prototype.readInt16LE = function (offset, noAssert) {
  6011. return readInt16(this, offset, true, noAssert)
  6012. }
  6013. Buffer.prototype.readInt16BE = function (offset, noAssert) {
  6014. return readInt16(this, offset, false, noAssert)
  6015. }
  6016. function readInt32 (buf, offset, littleEndian, noAssert) {
  6017. if (!noAssert) {
  6018. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6019. assert(offset !== undefined && offset !== null, 'missing offset')
  6020. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  6021. }
  6022. var len = buf.length
  6023. if (offset >= len)
  6024. return
  6025. var val = readUInt32(buf, offset, littleEndian, true)
  6026. var neg = val & 0x80000000
  6027. if (neg)
  6028. return (0xffffffff - val + 1) * -1
  6029. else
  6030. return val
  6031. }
  6032. Buffer.prototype.readInt32LE = function (offset, noAssert) {
  6033. return readInt32(this, offset, true, noAssert)
  6034. }
  6035. Buffer.prototype.readInt32BE = function (offset, noAssert) {
  6036. return readInt32(this, offset, false, noAssert)
  6037. }
  6038. function readFloat (buf, offset, littleEndian, noAssert) {
  6039. if (!noAssert) {
  6040. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6041. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  6042. }
  6043. return ieee754.read(buf, offset, littleEndian, 23, 4)
  6044. }
  6045. Buffer.prototype.readFloatLE = function (offset, noAssert) {
  6046. return readFloat(this, offset, true, noAssert)
  6047. }
  6048. Buffer.prototype.readFloatBE = function (offset, noAssert) {
  6049. return readFloat(this, offset, false, noAssert)
  6050. }
  6051. function readDouble (buf, offset, littleEndian, noAssert) {
  6052. if (!noAssert) {
  6053. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6054. assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
  6055. }
  6056. return ieee754.read(buf, offset, littleEndian, 52, 8)
  6057. }
  6058. Buffer.prototype.readDoubleLE = function (offset, noAssert) {
  6059. return readDouble(this, offset, true, noAssert)
  6060. }
  6061. Buffer.prototype.readDoubleBE = function (offset, noAssert) {
  6062. return readDouble(this, offset, false, noAssert)
  6063. }
  6064. Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
  6065. if (!noAssert) {
  6066. assert(value !== undefined && value !== null, 'missing value')
  6067. assert(offset !== undefined && offset !== null, 'missing offset')
  6068. assert(offset < this.length, 'trying to write beyond buffer length')
  6069. verifuint(value, 0xff)
  6070. }
  6071. if (offset >= this.length) return
  6072. this[offset] = value
  6073. return offset + 1
  6074. }
  6075. function writeUInt16 (buf, value, offset, littleEndian, noAssert) {
  6076. if (!noAssert) {
  6077. assert(value !== undefined && value !== null, 'missing value')
  6078. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6079. assert(offset !== undefined && offset !== null, 'missing offset')
  6080. assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
  6081. verifuint(value, 0xffff)
  6082. }
  6083. var len = buf.length
  6084. if (offset >= len)
  6085. return
  6086. for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
  6087. buf[offset + i] =
  6088. (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  6089. (littleEndian ? i : 1 - i) * 8
  6090. }
  6091. return offset + 2
  6092. }
  6093. Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
  6094. return writeUInt16(this, value, offset, true, noAssert)
  6095. }
  6096. Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
  6097. return writeUInt16(this, value, offset, false, noAssert)
  6098. }
  6099. function writeUInt32 (buf, value, offset, littleEndian, noAssert) {
  6100. if (!noAssert) {
  6101. assert(value !== undefined && value !== null, 'missing value')
  6102. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6103. assert(offset !== undefined && offset !== null, 'missing offset')
  6104. assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
  6105. verifuint(value, 0xffffffff)
  6106. }
  6107. var len = buf.length
  6108. if (offset >= len)
  6109. return
  6110. for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
  6111. buf[offset + i] =
  6112. (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  6113. }
  6114. return offset + 4
  6115. }
  6116. Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
  6117. return writeUInt32(this, value, offset, true, noAssert)
  6118. }
  6119. Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
  6120. return writeUInt32(this, value, offset, false, noAssert)
  6121. }
  6122. Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
  6123. if (!noAssert) {
  6124. assert(value !== undefined && value !== null, 'missing value')
  6125. assert(offset !== undefined && offset !== null, 'missing offset')
  6126. assert(offset < this.length, 'Trying to write beyond buffer length')
  6127. verifsint(value, 0x7f, -0x80)
  6128. }
  6129. if (offset >= this.length)
  6130. return
  6131. if (value >= 0)
  6132. this.writeUInt8(value, offset, noAssert)
  6133. else
  6134. this.writeUInt8(0xff + value + 1, offset, noAssert)
  6135. return offset + 1
  6136. }
  6137. function writeInt16 (buf, value, offset, littleEndian, noAssert) {
  6138. if (!noAssert) {
  6139. assert(value !== undefined && value !== null, 'missing value')
  6140. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6141. assert(offset !== undefined && offset !== null, 'missing offset')
  6142. assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
  6143. verifsint(value, 0x7fff, -0x8000)
  6144. }
  6145. var len = buf.length
  6146. if (offset >= len)
  6147. return
  6148. if (value >= 0)
  6149. writeUInt16(buf, value, offset, littleEndian, noAssert)
  6150. else
  6151. writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
  6152. return offset + 2
  6153. }
  6154. Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
  6155. return writeInt16(this, value, offset, true, noAssert)
  6156. }
  6157. Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
  6158. return writeInt16(this, value, offset, false, noAssert)
  6159. }
  6160. function writeInt32 (buf, value, offset, littleEndian, noAssert) {
  6161. if (!noAssert) {
  6162. assert(value !== undefined && value !== null, 'missing value')
  6163. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6164. assert(offset !== undefined && offset !== null, 'missing offset')
  6165. assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
  6166. verifsint(value, 0x7fffffff, -0x80000000)
  6167. }
  6168. var len = buf.length
  6169. if (offset >= len)
  6170. return
  6171. if (value >= 0)
  6172. writeUInt32(buf, value, offset, littleEndian, noAssert)
  6173. else
  6174. writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
  6175. return offset + 4
  6176. }
  6177. Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
  6178. return writeInt32(this, value, offset, true, noAssert)
  6179. }
  6180. Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
  6181. return writeInt32(this, value, offset, false, noAssert)
  6182. }
  6183. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  6184. if (!noAssert) {
  6185. assert(value !== undefined && value !== null, 'missing value')
  6186. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6187. assert(offset !== undefined && offset !== null, 'missing offset')
  6188. assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
  6189. verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
  6190. }
  6191. var len = buf.length
  6192. if (offset >= len)
  6193. return
  6194. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  6195. return offset + 4
  6196. }
  6197. Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
  6198. return writeFloat(this, value, offset, true, noAssert)
  6199. }
  6200. Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
  6201. return writeFloat(this, value, offset, false, noAssert)
  6202. }
  6203. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  6204. if (!noAssert) {
  6205. assert(value !== undefined && value !== null, 'missing value')
  6206. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  6207. assert(offset !== undefined && offset !== null, 'missing offset')
  6208. assert(offset + 7 < buf.length,
  6209. 'Trying to write beyond buffer length')
  6210. verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
  6211. }
  6212. var len = buf.length
  6213. if (offset >= len)
  6214. return
  6215. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  6216. return offset + 8
  6217. }
  6218. Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
  6219. return writeDouble(this, value, offset, true, noAssert)
  6220. }
  6221. Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
  6222. return writeDouble(this, value, offset, false, noAssert)
  6223. }
  6224. // fill(value, start=0, end=buffer.length)
  6225. Buffer.prototype.fill = function (value, start, end) {
  6226. if (!value) value = 0
  6227. if (!start) start = 0
  6228. if (!end) end = this.length
  6229. assert(end >= start, 'end < start')
  6230. // Fill 0 bytes; we're done
  6231. if (end === start) return
  6232. if (this.length === 0) return
  6233. assert(start >= 0 && start < this.length, 'start out of bounds')
  6234. assert(end >= 0 && end <= this.length, 'end out of bounds')
  6235. var i
  6236. if (typeof value === 'number') {
  6237. for (i = start; i < end; i++) {
  6238. this[i] = value
  6239. }
  6240. } else {
  6241. var bytes = utf8ToBytes(value.toString())
  6242. var len = bytes.length
  6243. for (i = start; i < end; i++) {
  6244. this[i] = bytes[i % len]
  6245. }
  6246. }
  6247. return this
  6248. }
  6249. Buffer.prototype.inspect = function () {
  6250. var out = []
  6251. var len = this.length
  6252. for (var i = 0; i < len; i++) {
  6253. out[i] = toHex(this[i])
  6254. if (i === exports.INSPECT_MAX_BYTES) {
  6255. out[i + 1] = '...'
  6256. break
  6257. }
  6258. }
  6259. return '<Buffer ' + out.join(' ') + '>'
  6260. }
  6261. /**
  6262. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  6263. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  6264. */
  6265. Buffer.prototype.toArrayBuffer = function () {
  6266. if (typeof Uint8Array !== 'undefined') {
  6267. if (Buffer._useTypedArrays) {
  6268. return (new Buffer(this)).buffer
  6269. } else {
  6270. var buf = new Uint8Array(this.length)
  6271. for (var i = 0, len = buf.length; i < len; i += 1) {
  6272. buf[i] = this[i]
  6273. }
  6274. return buf.buffer
  6275. }
  6276. } else {
  6277. throw new Error('Buffer.toArrayBuffer not supported in this browser')
  6278. }
  6279. }
  6280. // HELPER FUNCTIONS
  6281. // ================
  6282. var BP = Buffer.prototype
  6283. /**
  6284. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  6285. */
  6286. Buffer._augment = function (arr) {
  6287. arr._isBuffer = true
  6288. // save reference to original Uint8Array get/set methods before overwriting
  6289. arr._get = arr.get
  6290. arr._set = arr.set
  6291. // deprecated, will be removed in node 0.13+
  6292. arr.get = BP.get
  6293. arr.set = BP.set
  6294. arr.write = BP.write
  6295. arr.toString = BP.toString
  6296. arr.toLocaleString = BP.toString
  6297. arr.toJSON = BP.toJSON
  6298. arr.equals = BP.equals
  6299. arr.compare = BP.compare
  6300. arr.copy = BP.copy
  6301. arr.slice = BP.slice
  6302. arr.readUInt8 = BP.readUInt8
  6303. arr.readUInt16LE = BP.readUInt16LE
  6304. arr.readUInt16BE = BP.readUInt16BE
  6305. arr.readUInt32LE = BP.readUInt32LE
  6306. arr.readUInt32BE = BP.readUInt32BE
  6307. arr.readInt8 = BP.readInt8
  6308. arr.readInt16LE = BP.readInt16LE
  6309. arr.readInt16BE = BP.readInt16BE
  6310. arr.readInt32LE = BP.readInt32LE
  6311. arr.readInt32BE = BP.readInt32BE
  6312. arr.readFloatLE = BP.readFloatLE
  6313. arr.readFloatBE = BP.readFloatBE
  6314. arr.readDoubleLE = BP.readDoubleLE
  6315. arr.readDoubleBE = BP.readDoubleBE
  6316. arr.writeUInt8 = BP.writeUInt8
  6317. arr.writeUInt16LE = BP.writeUInt16LE
  6318. arr.writeUInt16BE = BP.writeUInt16BE
  6319. arr.writeUInt32LE = BP.writeUInt32LE
  6320. arr.writeUInt32BE = BP.writeUInt32BE
  6321. arr.writeInt8 = BP.writeInt8
  6322. arr.writeInt16LE = BP.writeInt16LE
  6323. arr.writeInt16BE = BP.writeInt16BE
  6324. arr.writeInt32LE = BP.writeInt32LE
  6325. arr.writeInt32BE = BP.writeInt32BE
  6326. arr.writeFloatLE = BP.writeFloatLE
  6327. arr.writeFloatBE = BP.writeFloatBE
  6328. arr.writeDoubleLE = BP.writeDoubleLE
  6329. arr.writeDoubleBE = BP.writeDoubleBE
  6330. arr.fill = BP.fill
  6331. arr.inspect = BP.inspect
  6332. arr.toArrayBuffer = BP.toArrayBuffer
  6333. return arr
  6334. }
  6335. var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
  6336. function base64clean (str) {
  6337. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  6338. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  6339. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  6340. while (str.length % 4 !== 0) {
  6341. str = str + '='
  6342. }
  6343. return str
  6344. }
  6345. function stringtrim (str) {
  6346. if (str.trim) return str.trim()
  6347. return str.replace(/^\s+|\s+$/g, '')
  6348. }
  6349. // slice(start, end)
  6350. function clamp (index, len, defaultValue) {
  6351. if (typeof index !== 'number') return defaultValue
  6352. index = ~~index; // Coerce to integer.
  6353. if (index >= len) return len
  6354. if (index >= 0) return index
  6355. index += len
  6356. if (index >= 0) return index
  6357. return 0
  6358. }
  6359. function coerce (length) {
  6360. // Coerce length to a number (possibly NaN), round up
  6361. // in case it's fractional (e.g. 123.456) then do a
  6362. // double negate to coerce a NaN to 0. Easy, right?
  6363. length = ~~Math.ceil(+length)
  6364. return length < 0 ? 0 : length
  6365. }
  6366. function isArray (subject) {
  6367. return (Array.isArray || function (subject) {
  6368. return Object.prototype.toString.call(subject) === '[object Array]'
  6369. })(subject)
  6370. }
  6371. function isArrayish (subject) {
  6372. return isArray(subject) || Buffer.isBuffer(subject) ||
  6373. subject && typeof subject === 'object' &&
  6374. typeof subject.length === 'number'
  6375. }
  6376. function toHex (n) {
  6377. if (n < 16) return '0' + n.toString(16)
  6378. return n.toString(16)
  6379. }
  6380. function utf8ToBytes (str) {
  6381. var byteArray = []
  6382. for (var i = 0; i < str.length; i++) {
  6383. var b = str.charCodeAt(i)
  6384. if (b <= 0x7F) {
  6385. byteArray.push(b)
  6386. } else {
  6387. var start = i
  6388. if (b >= 0xD800 && b <= 0xDFFF) i++
  6389. var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
  6390. for (var j = 0; j < h.length; j++) {
  6391. byteArray.push(parseInt(h[j], 16))
  6392. }
  6393. }
  6394. }
  6395. return byteArray
  6396. }
  6397. function asciiToBytes (str) {
  6398. var byteArray = []
  6399. for (var i = 0; i < str.length; i++) {
  6400. // Node's code seems to be doing this and not & 0x7F..
  6401. byteArray.push(str.charCodeAt(i) & 0xFF)
  6402. }
  6403. return byteArray
  6404. }
  6405. function utf16leToBytes (str) {
  6406. var c, hi, lo
  6407. var byteArray = []
  6408. for (var i = 0; i < str.length; i++) {
  6409. c = str.charCodeAt(i)
  6410. hi = c >> 8
  6411. lo = c % 256
  6412. byteArray.push(lo)
  6413. byteArray.push(hi)
  6414. }
  6415. return byteArray
  6416. }
  6417. function base64ToBytes (str) {
  6418. return base64.toByteArray(str)
  6419. }
  6420. function blitBuffer (src, dst, offset, length) {
  6421. for (var i = 0; i < length; i++) {
  6422. if ((i + offset >= dst.length) || (i >= src.length))
  6423. break
  6424. dst[i + offset] = src[i]
  6425. }
  6426. return i
  6427. }
  6428. function decodeUtf8Char (str) {
  6429. try {
  6430. return decodeURIComponent(str)
  6431. } catch (err) {
  6432. return String.fromCharCode(0xFFFD) // UTF 8 invalid char
  6433. }
  6434. }
  6435. /*
  6436. * We have to make sure that the value is a valid integer. This means that it
  6437. * is non-negative. It has no fractional component and that it does not
  6438. * exceed the maximum allowed value.
  6439. */
  6440. function verifuint (value, max) {
  6441. assert(typeof value === 'number', 'cannot write a non-number as a number')
  6442. assert(value >= 0, 'specified a negative value for writing an unsigned value')
  6443. assert(value <= max, 'value is larger than maximum value for type')
  6444. assert(Math.floor(value) === value, 'value has a fractional component')
  6445. }
  6446. function verifsint (value, max, min) {
  6447. assert(typeof value === 'number', 'cannot write a non-number as a number')
  6448. assert(value <= max, 'value larger than maximum allowed value')
  6449. assert(value >= min, 'value smaller than minimum allowed value')
  6450. assert(Math.floor(value) === value, 'value has a fractional component')
  6451. }
  6452. function verifIEEE754 (value, max, min) {
  6453. assert(typeof value === 'number', 'cannot write a non-number as a number')
  6454. assert(value <= max, 'value larger than maximum allowed value')
  6455. assert(value >= min, 'value smaller than minimum allowed value')
  6456. }
  6457. function assert (test, message) {
  6458. if (!test) throw new Error(message || 'Failed assertion')
  6459. }
  6460. },{"base64-js":47,"ieee754":48}],47:[function(_dereq_,module,exports){
  6461. var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  6462. ;(function (exports) {
  6463. 'use strict';
  6464. var Arr = (typeof Uint8Array !== 'undefined')
  6465. ? Uint8Array
  6466. : Array
  6467. var PLUS = '+'.charCodeAt(0)
  6468. var SLASH = '/'.charCodeAt(0)
  6469. var NUMBER = '0'.charCodeAt(0)
  6470. var LOWER = 'a'.charCodeAt(0)
  6471. var UPPER = 'A'.charCodeAt(0)
  6472. function decode (elt) {
  6473. var code = elt.charCodeAt(0)
  6474. if (code === PLUS)
  6475. return 62 // '+'
  6476. if (code === SLASH)
  6477. return 63 // '/'
  6478. if (code < NUMBER)
  6479. return -1 //no match
  6480. if (code < NUMBER + 10)
  6481. return code - NUMBER + 26 + 26
  6482. if (code < UPPER + 26)
  6483. return code - UPPER
  6484. if (code < LOWER + 26)
  6485. return code - LOWER + 26
  6486. }
  6487. function b64ToByteArray (b64) {
  6488. var i, j, l, tmp, placeHolders, arr
  6489. if (b64.length % 4 > 0) {
  6490. throw new Error('Invalid string. Length must be a multiple of 4')
  6491. }
  6492. // the number of equal signs (place holders)
  6493. // if there are two placeholders, than the two characters before it
  6494. // represent one byte
  6495. // if there is only one, then the three characters before it represent 2 bytes
  6496. // this is just a cheap hack to not do indexOf twice
  6497. var len = b64.length
  6498. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
  6499. // base64 is 4/3 + up to two characters of the original data
  6500. arr = new Arr(b64.length * 3 / 4 - placeHolders)
  6501. // if there are placeholders, only get up to the last complete 4 chars
  6502. l = placeHolders > 0 ? b64.length - 4 : b64.length
  6503. var L = 0
  6504. function push (v) {
  6505. arr[L++] = v
  6506. }
  6507. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  6508. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
  6509. push((tmp & 0xFF0000) >> 16)
  6510. push((tmp & 0xFF00) >> 8)
  6511. push(tmp & 0xFF)
  6512. }
  6513. if (placeHolders === 2) {
  6514. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
  6515. push(tmp & 0xFF)
  6516. } else if (placeHolders === 1) {
  6517. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
  6518. push((tmp >> 8) & 0xFF)
  6519. push(tmp & 0xFF)
  6520. }
  6521. return arr
  6522. }
  6523. function uint8ToBase64 (uint8) {
  6524. var i,
  6525. extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
  6526. output = "",
  6527. temp, length
  6528. function encode (num) {
  6529. return lookup.charAt(num)
  6530. }
  6531. function tripletToBase64 (num) {
  6532. return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
  6533. }
  6534. // go through the array every three bytes, we'll deal with trailing stuff later
  6535. for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
  6536. temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  6537. output += tripletToBase64(temp)
  6538. }
  6539. // pad the end with zeros, but make sure to not forget the extra bytes
  6540. switch (extraBytes) {
  6541. case 1:
  6542. temp = uint8[uint8.length - 1]
  6543. output += encode(temp >> 2)
  6544. output += encode((temp << 4) & 0x3F)
  6545. output += '=='
  6546. break
  6547. case 2:
  6548. temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
  6549. output += encode(temp >> 10)
  6550. output += encode((temp >> 4) & 0x3F)
  6551. output += encode((temp << 2) & 0x3F)
  6552. output += '='
  6553. break
  6554. }
  6555. return output
  6556. }
  6557. exports.toByteArray = b64ToByteArray
  6558. exports.fromByteArray = uint8ToBase64
  6559. }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
  6560. },{}],48:[function(_dereq_,module,exports){
  6561. exports.read = function(buffer, offset, isLE, mLen, nBytes) {
  6562. var e, m,
  6563. eLen = nBytes * 8 - mLen - 1,
  6564. eMax = (1 << eLen) - 1,
  6565. eBias = eMax >> 1,
  6566. nBits = -7,
  6567. i = isLE ? (nBytes - 1) : 0,
  6568. d = isLE ? -1 : 1,
  6569. s = buffer[offset + i];
  6570. i += d;
  6571. e = s & ((1 << (-nBits)) - 1);
  6572. s >>= (-nBits);
  6573. nBits += eLen;
  6574. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
  6575. m = e & ((1 << (-nBits)) - 1);
  6576. e >>= (-nBits);
  6577. nBits += mLen;
  6578. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
  6579. if (e === 0) {
  6580. e = 1 - eBias;
  6581. } else if (e === eMax) {
  6582. return m ? NaN : ((s ? -1 : 1) * Infinity);
  6583. } else {
  6584. m = m + Math.pow(2, mLen);
  6585. e = e - eBias;
  6586. }
  6587. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  6588. };
  6589. exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
  6590. var e, m, c,
  6591. eLen = nBytes * 8 - mLen - 1,
  6592. eMax = (1 << eLen) - 1,
  6593. eBias = eMax >> 1,
  6594. rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
  6595. i = isLE ? 0 : (nBytes - 1),
  6596. d = isLE ? 1 : -1,
  6597. s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  6598. value = Math.abs(value);
  6599. if (isNaN(value) || value === Infinity) {
  6600. m = isNaN(value) ? 1 : 0;
  6601. e = eMax;
  6602. } else {
  6603. e = Math.floor(Math.log(value) / Math.LN2);
  6604. if (value * (c = Math.pow(2, -e)) < 1) {
  6605. e--;
  6606. c *= 2;
  6607. }
  6608. if (e + eBias >= 1) {
  6609. value += rt / c;
  6610. } else {
  6611. value += rt * Math.pow(2, 1 - eBias);
  6612. }
  6613. if (value * c >= 2) {
  6614. e++;
  6615. c /= 2;
  6616. }
  6617. if (e + eBias >= eMax) {
  6618. m = 0;
  6619. e = eMax;
  6620. } else if (e + eBias >= 1) {
  6621. m = (value * c - 1) * Math.pow(2, mLen);
  6622. e = e + eBias;
  6623. } else {
  6624. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  6625. e = 0;
  6626. }
  6627. }
  6628. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
  6629. e = (e << mLen) | m;
  6630. eLen += mLen;
  6631. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
  6632. buffer[offset + i - d] |= s * 128;
  6633. };
  6634. },{}],49:[function(_dereq_,module,exports){
  6635. // Copyright Joyent, Inc. and other Node contributors.
  6636. //
  6637. // Permission is hereby granted, free of charge, to any person obtaining a
  6638. // copy of this software and associated documentation files (the
  6639. // "Software"), to deal in the Software without restriction, including
  6640. // without limitation the rights to use, copy, modify, merge, publish,
  6641. // distribute, sublicense, and/or sell copies of the Software, and to permit
  6642. // persons to whom the Software is furnished to do so, subject to the
  6643. // following conditions:
  6644. //
  6645. // The above copyright notice and this permission notice shall be included
  6646. // in all copies or substantial portions of the Software.
  6647. //
  6648. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6649. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6650. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  6651. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  6652. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  6653. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  6654. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  6655. function EventEmitter() {
  6656. this._events = this._events || {};
  6657. this._maxListeners = this._maxListeners || undefined;
  6658. }
  6659. module.exports = EventEmitter;
  6660. // Backwards-compat with node 0.10.x
  6661. EventEmitter.EventEmitter = EventEmitter;
  6662. EventEmitter.prototype._events = undefined;
  6663. EventEmitter.prototype._maxListeners = undefined;
  6664. // By default EventEmitters will print a warning if more than 10 listeners are
  6665. // added to it. This is a useful default which helps finding memory leaks.
  6666. EventEmitter.defaultMaxListeners = 10;
  6667. // Obviously not all Emitters should be limited to 10. This function allows
  6668. // that to be increased. Set to zero for unlimited.
  6669. EventEmitter.prototype.setMaxListeners = function(n) {
  6670. if (!isNumber(n) || n < 0 || isNaN(n))
  6671. throw TypeError('n must be a positive number');
  6672. this._maxListeners = n;
  6673. return this;
  6674. };
  6675. EventEmitter.prototype.emit = function(type) {
  6676. var er, handler, len, args, i, listeners;
  6677. if (!this._events)
  6678. this._events = {};
  6679. // If there is no 'error' event listener then throw.
  6680. if (type === 'error') {
  6681. if (!this._events.error ||
  6682. (isObject(this._events.error) && !this._events.error.length)) {
  6683. er = arguments[1];
  6684. if (er instanceof Error) {
  6685. throw er; // Unhandled 'error' event
  6686. } else {
  6687. throw TypeError('Uncaught, unspecified "error" event.');
  6688. }
  6689. return false;
  6690. }
  6691. }
  6692. handler = this._events[type];
  6693. if (isUndefined(handler))
  6694. return false;
  6695. if (isFunction(handler)) {
  6696. switch (arguments.length) {
  6697. // fast cases
  6698. case 1:
  6699. handler.call(this);
  6700. break;
  6701. case 2:
  6702. handler.call(this, arguments[1]);
  6703. break;
  6704. case 3:
  6705. handler.call(this, arguments[1], arguments[2]);
  6706. break;
  6707. // slower
  6708. default:
  6709. len = arguments.length;
  6710. args = new Array(len - 1);
  6711. for (i = 1; i < len; i++)
  6712. args[i - 1] = arguments[i];
  6713. handler.apply(this, args);
  6714. }
  6715. } else if (isObject(handler)) {
  6716. len = arguments.length;
  6717. args = new Array(len - 1);
  6718. for (i = 1; i < len; i++)
  6719. args[i - 1] = arguments[i];
  6720. listeners = handler.slice();
  6721. len = listeners.length;
  6722. for (i = 0; i < len; i++)
  6723. listeners[i].apply(this, args);
  6724. }
  6725. return true;
  6726. };
  6727. EventEmitter.prototype.addListener = function(type, listener) {
  6728. var m;
  6729. if (!isFunction(listener))
  6730. throw TypeError('listener must be a function');
  6731. if (!this._events)
  6732. this._events = {};
  6733. // To avoid recursion in the case that type === "newListener"! Before
  6734. // adding it to the listeners, first emit "newListener".
  6735. if (this._events.newListener)
  6736. this.emit('newListener', type,
  6737. isFunction(listener.listener) ?
  6738. listener.listener : listener);
  6739. if (!this._events[type])
  6740. // Optimize the case of one listener. Don't need the extra array object.
  6741. this._events[type] = listener;
  6742. else if (isObject(this._events[type]))
  6743. // If we've already got an array, just append.
  6744. this._events[type].push(listener);
  6745. else
  6746. // Adding the second element, need to change to array.
  6747. this._events[type] = [this._events[type], listener];
  6748. // Check for listener leak
  6749. if (isObject(this._events[type]) && !this._events[type].warned) {
  6750. var m;
  6751. if (!isUndefined(this._maxListeners)) {
  6752. m = this._maxListeners;
  6753. } else {
  6754. m = EventEmitter.defaultMaxListeners;
  6755. }
  6756. if (m && m > 0 && this._events[type].length > m) {
  6757. this._events[type].warned = true;
  6758. console.error('(node) warning: possible EventEmitter memory ' +
  6759. 'leak detected. %d listeners added. ' +
  6760. 'Use emitter.setMaxListeners() to increase limit.',
  6761. this._events[type].length);
  6762. if (typeof console.trace === 'function') {
  6763. // not supported in IE 10
  6764. console.trace();
  6765. }
  6766. }
  6767. }
  6768. return this;
  6769. };
  6770. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  6771. EventEmitter.prototype.once = function(type, listener) {
  6772. if (!isFunction(listener))
  6773. throw TypeError('listener must be a function');
  6774. var fired = false;
  6775. function g() {
  6776. this.removeListener(type, g);
  6777. if (!fired) {
  6778. fired = true;
  6779. listener.apply(this, arguments);
  6780. }
  6781. }
  6782. g.listener = listener;
  6783. this.on(type, g);
  6784. return this;
  6785. };
  6786. // emits a 'removeListener' event iff the listener was removed
  6787. EventEmitter.prototype.removeListener = function(type, listener) {
  6788. var list, position, length, i;
  6789. if (!isFunction(listener))
  6790. throw TypeError('listener must be a function');
  6791. if (!this._events || !this._events[type])
  6792. return this;
  6793. list = this._events[type];
  6794. length = list.length;
  6795. position = -1;
  6796. if (list === listener ||
  6797. (isFunction(list.listener) && list.listener === listener)) {
  6798. delete this._events[type];
  6799. if (this._events.removeListener)
  6800. this.emit('removeListener', type, listener);
  6801. } else if (isObject(list)) {
  6802. for (i = length; i-- > 0;) {
  6803. if (list[i] === listener ||
  6804. (list[i].listener && list[i].listener === listener)) {
  6805. position = i;
  6806. break;
  6807. }
  6808. }
  6809. if (position < 0)
  6810. return this;
  6811. if (list.length === 1) {
  6812. list.length = 0;
  6813. delete this._events[type];
  6814. } else {
  6815. list.splice(position, 1);
  6816. }
  6817. if (this._events.removeListener)
  6818. this.emit('removeListener', type, listener);
  6819. }
  6820. return this;
  6821. };
  6822. EventEmitter.prototype.removeAllListeners = function(type) {
  6823. var key, listeners;
  6824. if (!this._events)
  6825. return this;
  6826. // not listening for removeListener, no need to emit
  6827. if (!this._events.removeListener) {
  6828. if (arguments.length === 0)
  6829. this._events = {};
  6830. else if (this._events[type])
  6831. delete this._events[type];
  6832. return this;
  6833. }
  6834. // emit removeListener for all listeners on all events
  6835. if (arguments.length === 0) {
  6836. for (key in this._events) {
  6837. if (key === 'removeListener') continue;
  6838. this.removeAllListeners(key);
  6839. }
  6840. this.removeAllListeners('removeListener');
  6841. this._events = {};
  6842. return this;
  6843. }
  6844. listeners = this._events[type];
  6845. if (isFunction(listeners)) {
  6846. this.removeListener(type, listeners);
  6847. } else {
  6848. // LIFO order
  6849. while (listeners.length)
  6850. this.removeListener(type, listeners[listeners.length - 1]);
  6851. }
  6852. delete this._events[type];
  6853. return this;
  6854. };
  6855. EventEmitter.prototype.listeners = function(type) {
  6856. var ret;
  6857. if (!this._events || !this._events[type])
  6858. ret = [];
  6859. else if (isFunction(this._events[type]))
  6860. ret = [this._events[type]];
  6861. else
  6862. ret = this._events[type].slice();
  6863. return ret;
  6864. };
  6865. EventEmitter.listenerCount = function(emitter, type) {
  6866. var ret;
  6867. if (!emitter._events || !emitter._events[type])
  6868. ret = 0;
  6869. else if (isFunction(emitter._events[type]))
  6870. ret = 1;
  6871. else
  6872. ret = emitter._events[type].length;
  6873. return ret;
  6874. };
  6875. function isFunction(arg) {
  6876. return typeof arg === 'function';
  6877. }
  6878. function isNumber(arg) {
  6879. return typeof arg === 'number';
  6880. }
  6881. function isObject(arg) {
  6882. return typeof arg === 'object' && arg !== null;
  6883. }
  6884. function isUndefined(arg) {
  6885. return arg === void 0;
  6886. }
  6887. },{}],50:[function(_dereq_,module,exports){
  6888. if (typeof Object.create === 'function') {
  6889. // implementation from standard node.js 'util' module
  6890. module.exports = function inherits(ctor, superCtor) {
  6891. ctor.super_ = superCtor
  6892. ctor.prototype = Object.create(superCtor.prototype, {
  6893. constructor: {
  6894. value: ctor,
  6895. enumerable: false,
  6896. writable: true,
  6897. configurable: true
  6898. }
  6899. });
  6900. };
  6901. } else {
  6902. // old school shim for old browsers
  6903. module.exports = function inherits(ctor, superCtor) {
  6904. ctor.super_ = superCtor
  6905. var TempCtor = function () {}
  6906. TempCtor.prototype = superCtor.prototype
  6907. ctor.prototype = new TempCtor()
  6908. ctor.prototype.constructor = ctor
  6909. }
  6910. }
  6911. },{}],51:[function(_dereq_,module,exports){
  6912. // shim for using process in browser
  6913. var process = module.exports = {};
  6914. process.nextTick = (function () {
  6915. var canSetImmediate = typeof window !== 'undefined'
  6916. && window.setImmediate;
  6917. var canPost = typeof window !== 'undefined'
  6918. && window.postMessage && window.addEventListener
  6919. ;
  6920. if (canSetImmediate) {
  6921. return function (f) { return window.setImmediate(f) };
  6922. }
  6923. if (canPost) {
  6924. var queue = [];
  6925. window.addEventListener('message', function (ev) {
  6926. var source = ev.source;
  6927. if ((source === window || source === null) && ev.data === 'process-tick') {
  6928. ev.stopPropagation();
  6929. if (queue.length > 0) {
  6930. var fn = queue.shift();
  6931. fn();
  6932. }
  6933. }
  6934. }, true);
  6935. return function nextTick(fn) {
  6936. queue.push(fn);
  6937. window.postMessage('process-tick', '*');
  6938. };
  6939. }
  6940. return function nextTick(fn) {
  6941. setTimeout(fn, 0);
  6942. };
  6943. })();
  6944. process.title = 'browser';
  6945. process.browser = true;
  6946. process.env = {};
  6947. process.argv = [];
  6948. function noop() {}
  6949. process.on = noop;
  6950. process.addListener = noop;
  6951. process.once = noop;
  6952. process.off = noop;
  6953. process.removeListener = noop;
  6954. process.removeAllListeners = noop;
  6955. process.emit = noop;
  6956. process.binding = function (name) {
  6957. throw new Error('process.binding is not supported');
  6958. }
  6959. // TODO(shtylman)
  6960. process.cwd = function () { return '/' };
  6961. process.chdir = function (dir) {
  6962. throw new Error('process.chdir is not supported');
  6963. };
  6964. },{}],52:[function(_dereq_,module,exports){
  6965. module.exports = function isBuffer(arg) {
  6966. return arg && typeof arg === 'object'
  6967. && typeof arg.copy === 'function'
  6968. && typeof arg.fill === 'function'
  6969. && typeof arg.readUInt8 === 'function';
  6970. }
  6971. },{}],53:[function(_dereq_,module,exports){
  6972. (function (process,global){
  6973. // Copyright Joyent, Inc. and other Node contributors.
  6974. //
  6975. // Permission is hereby granted, free of charge, to any person obtaining a
  6976. // copy of this software and associated documentation files (the
  6977. // "Software"), to deal in the Software without restriction, including
  6978. // without limitation the rights to use, copy, modify, merge, publish,
  6979. // distribute, sublicense, and/or sell copies of the Software, and to permit
  6980. // persons to whom the Software is furnished to do so, subject to the
  6981. // following conditions:
  6982. //
  6983. // The above copyright notice and this permission notice shall be included
  6984. // in all copies or substantial portions of the Software.
  6985. //
  6986. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6987. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6988. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  6989. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  6990. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  6991. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  6992. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  6993. var formatRegExp = /%[sdj%]/g;
  6994. exports.format = function(f) {
  6995. if (!isString(f)) {
  6996. var objects = [];
  6997. for (var i = 0; i < arguments.length; i++) {
  6998. objects.push(inspect(arguments[i]));
  6999. }
  7000. return objects.join(' ');
  7001. }
  7002. var i = 1;
  7003. var args = arguments;
  7004. var len = args.length;
  7005. var str = String(f).replace(formatRegExp, function(x) {
  7006. if (x === '%%') return '%';
  7007. if (i >= len) return x;
  7008. switch (x) {
  7009. case '%s': return String(args[i++]);
  7010. case '%d': return Number(args[i++]);
  7011. case '%j':
  7012. try {
  7013. return JSON.stringify(args[i++]);
  7014. } catch (_) {
  7015. return '[Circular]';
  7016. }
  7017. default:
  7018. return x;
  7019. }
  7020. });
  7021. for (var x = args[i]; i < len; x = args[++i]) {
  7022. if (isNull(x) || !isObject(x)) {
  7023. str += ' ' + x;
  7024. } else {
  7025. str += ' ' + inspect(x);
  7026. }
  7027. }
  7028. return str;
  7029. };
  7030. // Mark that a method should not be used.
  7031. // Returns a modified function which warns once by default.
  7032. // If --no-deprecation is set, then it is a no-op.
  7033. exports.deprecate = function(fn, msg) {
  7034. // Allow for deprecating things in the process of starting up.
  7035. if (isUndefined(global.process)) {
  7036. return function() {
  7037. return exports.deprecate(fn, msg).apply(this, arguments);
  7038. };
  7039. }
  7040. if (process.noDeprecation === true) {
  7041. return fn;
  7042. }
  7043. var warned = false;
  7044. function deprecated() {
  7045. if (!warned) {
  7046. if (process.throwDeprecation) {
  7047. throw new Error(msg);
  7048. } else if (process.traceDeprecation) {
  7049. console.trace(msg);
  7050. } else {
  7051. console.error(msg);
  7052. }
  7053. warned = true;
  7054. }
  7055. return fn.apply(this, arguments);
  7056. }
  7057. return deprecated;
  7058. };
  7059. var debugs = {};
  7060. var debugEnviron;
  7061. exports.debuglog = function(set) {
  7062. if (isUndefined(debugEnviron))
  7063. debugEnviron = process.env.NODE_DEBUG || '';
  7064. set = set.toUpperCase();
  7065. if (!debugs[set]) {
  7066. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  7067. var pid = process.pid;
  7068. debugs[set] = function() {
  7069. var msg = exports.format.apply(exports, arguments);
  7070. console.error('%s %d: %s', set, pid, msg);
  7071. };
  7072. } else {
  7073. debugs[set] = function() {};
  7074. }
  7075. }
  7076. return debugs[set];
  7077. };
  7078. /**
  7079. * Echos the value of a value. Trys to print the value out
  7080. * in the best way possible given the different types.
  7081. *
  7082. * @param {Object} obj The object to print out.
  7083. * @param {Object} opts Optional options object that alters the output.
  7084. */
  7085. /* legacy: obj, showHidden, depth, colors*/
  7086. function inspect(obj, opts) {
  7087. // default options
  7088. var ctx = {
  7089. seen: [],
  7090. stylize: stylizeNoColor
  7091. };
  7092. // legacy...
  7093. if (arguments.length >= 3) ctx.depth = arguments[2];
  7094. if (arguments.length >= 4) ctx.colors = arguments[3];
  7095. if (isBoolean(opts)) {
  7096. // legacy...
  7097. ctx.showHidden = opts;
  7098. } else if (opts) {
  7099. // got an "options" object
  7100. exports._extend(ctx, opts);
  7101. }
  7102. // set default options
  7103. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  7104. if (isUndefined(ctx.depth)) ctx.depth = 2;
  7105. if (isUndefined(ctx.colors)) ctx.colors = false;
  7106. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  7107. if (ctx.colors) ctx.stylize = stylizeWithColor;
  7108. return formatValue(ctx, obj, ctx.depth);
  7109. }
  7110. exports.inspect = inspect;
  7111. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  7112. inspect.colors = {
  7113. 'bold' : [1, 22],
  7114. 'italic' : [3, 23],
  7115. 'underline' : [4, 24],
  7116. 'inverse' : [7, 27],
  7117. 'white' : [37, 39],
  7118. 'grey' : [90, 39],
  7119. 'black' : [30, 39],
  7120. 'blue' : [34, 39],
  7121. 'cyan' : [36, 39],
  7122. 'green' : [32, 39],
  7123. 'magenta' : [35, 39],
  7124. 'red' : [31, 39],
  7125. 'yellow' : [33, 39]
  7126. };
  7127. // Don't use 'blue' not visible on cmd.exe
  7128. inspect.styles = {
  7129. 'special': 'cyan',
  7130. 'number': 'yellow',
  7131. 'boolean': 'yellow',
  7132. 'undefined': 'grey',
  7133. 'null': 'bold',
  7134. 'string': 'green',
  7135. 'date': 'magenta',
  7136. // "name": intentionally not styling
  7137. 'regexp': 'red'
  7138. };
  7139. function stylizeWithColor(str, styleType) {
  7140. var style = inspect.styles[styleType];
  7141. if (style) {
  7142. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  7143. '\u001b[' + inspect.colors[style][1] + 'm';
  7144. } else {
  7145. return str;
  7146. }
  7147. }
  7148. function stylizeNoColor(str, styleType) {
  7149. return str;
  7150. }
  7151. function arrayToHash(array) {
  7152. var hash = {};
  7153. array.forEach(function(val, idx) {
  7154. hash[val] = true;
  7155. });
  7156. return hash;
  7157. }
  7158. function formatValue(ctx, value, recurseTimes) {
  7159. // Provide a hook for user-specified inspect functions.
  7160. // Check that value is an object with an inspect function on it
  7161. if (ctx.customInspect &&
  7162. value &&
  7163. isFunction(value.inspect) &&
  7164. // Filter out the util module, it's inspect function is special
  7165. value.inspect !== exports.inspect &&
  7166. // Also filter out any prototype objects using the circular check.
  7167. !(value.constructor && value.constructor.prototype === value)) {
  7168. var ret = value.inspect(recurseTimes, ctx);
  7169. if (!isString(ret)) {
  7170. ret = formatValue(ctx, ret, recurseTimes);
  7171. }
  7172. return ret;
  7173. }
  7174. // Primitive types cannot have properties
  7175. var primitive = formatPrimitive(ctx, value);
  7176. if (primitive) {
  7177. return primitive;
  7178. }
  7179. // Look up the keys of the object.
  7180. var keys = Object.keys(value);
  7181. var visibleKeys = arrayToHash(keys);
  7182. if (ctx.showHidden) {
  7183. keys = Object.getOwnPropertyNames(value);
  7184. }
  7185. // IE doesn't make error fields non-enumerable
  7186. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  7187. if (isError(value)
  7188. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  7189. return formatError(value);
  7190. }
  7191. // Some type of object without properties can be shortcutted.
  7192. if (keys.length === 0) {
  7193. if (isFunction(value)) {
  7194. var name = value.name ? ': ' + value.name : '';
  7195. return ctx.stylize('[Function' + name + ']', 'special');
  7196. }
  7197. if (isRegExp(value)) {
  7198. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  7199. }
  7200. if (isDate(value)) {
  7201. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  7202. }
  7203. if (isError(value)) {
  7204. return formatError(value);
  7205. }
  7206. }
  7207. var base = '', array = false, braces = ['{', '}'];
  7208. // Make Array say that they are Array
  7209. if (isArray(value)) {
  7210. array = true;
  7211. braces = ['[', ']'];
  7212. }
  7213. // Make functions say that they are functions
  7214. if (isFunction(value)) {
  7215. var n = value.name ? ': ' + value.name : '';
  7216. base = ' [Function' + n + ']';
  7217. }
  7218. // Make RegExps say that they are RegExps
  7219. if (isRegExp(value)) {
  7220. base = ' ' + RegExp.prototype.toString.call(value);
  7221. }
  7222. // Make dates with properties first say the date
  7223. if (isDate(value)) {
  7224. base = ' ' + Date.prototype.toUTCString.call(value);
  7225. }
  7226. // Make error with message first say the error
  7227. if (isError(value)) {
  7228. base = ' ' + formatError(value);
  7229. }
  7230. if (keys.length === 0 && (!array || value.length == 0)) {
  7231. return braces[0] + base + braces[1];
  7232. }
  7233. if (recurseTimes < 0) {
  7234. if (isRegExp(value)) {
  7235. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  7236. } else {
  7237. return ctx.stylize('[Object]', 'special');
  7238. }
  7239. }
  7240. ctx.seen.push(value);
  7241. var output;
  7242. if (array) {
  7243. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  7244. } else {
  7245. output = keys.map(function(key) {
  7246. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  7247. });
  7248. }
  7249. ctx.seen.pop();
  7250. return reduceToSingleString(output, base, braces);
  7251. }
  7252. function formatPrimitive(ctx, value) {
  7253. if (isUndefined(value))
  7254. return ctx.stylize('undefined', 'undefined');
  7255. if (isString(value)) {
  7256. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  7257. .replace(/'/g, "\\'")
  7258. .replace(/\\"/g, '"') + '\'';
  7259. return ctx.stylize(simple, 'string');
  7260. }
  7261. if (isNumber(value))
  7262. return ctx.stylize('' + value, 'number');
  7263. if (isBoolean(value))
  7264. return ctx.stylize('' + value, 'boolean');
  7265. // For some reason typeof null is "object", so special case here.
  7266. if (isNull(value))
  7267. return ctx.stylize('null', 'null');
  7268. }
  7269. function formatError(value) {
  7270. return '[' + Error.prototype.toString.call(value) + ']';
  7271. }
  7272. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  7273. var output = [];
  7274. for (var i = 0, l = value.length; i < l; ++i) {
  7275. if (hasOwnProperty(value, String(i))) {
  7276. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  7277. String(i), true));
  7278. } else {
  7279. output.push('');
  7280. }
  7281. }
  7282. keys.forEach(function(key) {
  7283. if (!key.match(/^\d+$/)) {
  7284. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  7285. key, true));
  7286. }
  7287. });
  7288. return output;
  7289. }
  7290. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  7291. var name, str, desc;
  7292. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  7293. if (desc.get) {
  7294. if (desc.set) {
  7295. str = ctx.stylize('[Getter/Setter]', 'special');
  7296. } else {
  7297. str = ctx.stylize('[Getter]', 'special');
  7298. }
  7299. } else {
  7300. if (desc.set) {
  7301. str = ctx.stylize('[Setter]', 'special');
  7302. }
  7303. }
  7304. if (!hasOwnProperty(visibleKeys, key)) {
  7305. name = '[' + key + ']';
  7306. }
  7307. if (!str) {
  7308. if (ctx.seen.indexOf(desc.value) < 0) {
  7309. if (isNull(recurseTimes)) {
  7310. str = formatValue(ctx, desc.value, null);
  7311. } else {
  7312. str = formatValue(ctx, desc.value, recurseTimes - 1);
  7313. }
  7314. if (str.indexOf('\n') > -1) {
  7315. if (array) {
  7316. str = str.split('\n').map(function(line) {
  7317. return ' ' + line;
  7318. }).join('\n').substr(2);
  7319. } else {
  7320. str = '\n' + str.split('\n').map(function(line) {
  7321. return ' ' + line;
  7322. }).join('\n');
  7323. }
  7324. }
  7325. } else {
  7326. str = ctx.stylize('[Circular]', 'special');
  7327. }
  7328. }
  7329. if (isUndefined(name)) {
  7330. if (array && key.match(/^\d+$/)) {
  7331. return str;
  7332. }
  7333. name = JSON.stringify('' + key);
  7334. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  7335. name = name.substr(1, name.length - 2);
  7336. name = ctx.stylize(name, 'name');
  7337. } else {
  7338. name = name.replace(/'/g, "\\'")
  7339. .replace(/\\"/g, '"')
  7340. .replace(/(^"|"$)/g, "'");
  7341. name = ctx.stylize(name, 'string');
  7342. }
  7343. }
  7344. return name + ': ' + str;
  7345. }
  7346. function reduceToSingleString(output, base, braces) {
  7347. var numLinesEst = 0;
  7348. var length = output.reduce(function(prev, cur) {
  7349. numLinesEst++;
  7350. if (cur.indexOf('\n') >= 0) numLinesEst++;
  7351. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  7352. }, 0);
  7353. if (length > 60) {
  7354. return braces[0] +
  7355. (base === '' ? '' : base + '\n ') +
  7356. ' ' +
  7357. output.join(',\n ') +
  7358. ' ' +
  7359. braces[1];
  7360. }
  7361. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  7362. }
  7363. // NOTE: These type checking functions intentionally don't use `instanceof`
  7364. // because it is fragile and can be easily faked with `Object.create()`.
  7365. function isArray(ar) {
  7366. return Array.isArray(ar);
  7367. }
  7368. exports.isArray = isArray;
  7369. function isBoolean(arg) {
  7370. return typeof arg === 'boolean';
  7371. }
  7372. exports.isBoolean = isBoolean;
  7373. function isNull(arg) {
  7374. return arg === null;
  7375. }
  7376. exports.isNull = isNull;
  7377. function isNullOrUndefined(arg) {
  7378. return arg == null;
  7379. }
  7380. exports.isNullOrUndefined = isNullOrUndefined;
  7381. function isNumber(arg) {
  7382. return typeof arg === 'number';
  7383. }
  7384. exports.isNumber = isNumber;
  7385. function isString(arg) {
  7386. return typeof arg === 'string';
  7387. }
  7388. exports.isString = isString;
  7389. function isSymbol(arg) {
  7390. return typeof arg === 'symbol';
  7391. }
  7392. exports.isSymbol = isSymbol;
  7393. function isUndefined(arg) {
  7394. return arg === void 0;
  7395. }
  7396. exports.isUndefined = isUndefined;
  7397. function isRegExp(re) {
  7398. return isObject(re) && objectToString(re) === '[object RegExp]';
  7399. }
  7400. exports.isRegExp = isRegExp;
  7401. function isObject(arg) {
  7402. return typeof arg === 'object' && arg !== null;
  7403. }
  7404. exports.isObject = isObject;
  7405. function isDate(d) {
  7406. return isObject(d) && objectToString(d) === '[object Date]';
  7407. }
  7408. exports.isDate = isDate;
  7409. function isError(e) {
  7410. return isObject(e) &&
  7411. (objectToString(e) === '[object Error]' || e instanceof Error);
  7412. }
  7413. exports.isError = isError;
  7414. function isFunction(arg) {
  7415. return typeof arg === 'function';
  7416. }
  7417. exports.isFunction = isFunction;
  7418. function isPrimitive(arg) {
  7419. return arg === null ||
  7420. typeof arg === 'boolean' ||
  7421. typeof arg === 'number' ||
  7422. typeof arg === 'string' ||
  7423. typeof arg === 'symbol' || // ES6 symbol
  7424. typeof arg === 'undefined';
  7425. }
  7426. exports.isPrimitive = isPrimitive;
  7427. exports.isBuffer = _dereq_('./support/isBuffer');
  7428. function objectToString(o) {
  7429. return Object.prototype.toString.call(o);
  7430. }
  7431. function pad(n) {
  7432. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  7433. }
  7434. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  7435. 'Oct', 'Nov', 'Dec'];
  7436. // 26 Feb 16:19:34
  7437. function timestamp() {
  7438. var d = new Date();
  7439. var time = [pad(d.getHours()),
  7440. pad(d.getMinutes()),
  7441. pad(d.getSeconds())].join(':');
  7442. return [d.getDate(), months[d.getMonth()], time].join(' ');
  7443. }
  7444. // log is just a thin wrapper to console.log that prepends a timestamp
  7445. exports.log = function() {
  7446. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  7447. };
  7448. /**
  7449. * Inherit the prototype methods from one constructor into another.
  7450. *
  7451. * The Function.prototype.inherits from lang.js rewritten as a standalone
  7452. * function (not on Function.prototype). NOTE: If this file is to be loaded
  7453. * during bootstrapping this function needs to be rewritten using some native
  7454. * functions as prototype setup using normal JavaScript does not work as
  7455. * expected during bootstrapping (see mirror.js in r114903).
  7456. *
  7457. * @param {function} ctor Constructor function which needs to inherit the
  7458. * prototype.
  7459. * @param {function} superCtor Constructor function to inherit prototype from.
  7460. */
  7461. exports.inherits = _dereq_('inherits');
  7462. exports._extend = function(origin, add) {
  7463. // Don't do anything if add isn't an object
  7464. if (!add || !isObject(add)) return origin;
  7465. var keys = Object.keys(add);
  7466. var i = keys.length;
  7467. while (i--) {
  7468. origin[keys[i]] = add[keys[i]];
  7469. }
  7470. return origin;
  7471. };
  7472. function hasOwnProperty(obj, prop) {
  7473. return Object.prototype.hasOwnProperty.call(obj, prop);
  7474. }
  7475. }).call(this,_dereq_("q+64fw"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  7476. },{"./support/isBuffer":52,"inherits":50,"q+64fw":51}]},{},[1])
  7477. (1)
  7478. });