You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5818 lines
181 KiB

4 years ago
  1. /* sockjs-client v1.4.0 | http://sockjs.org | MIT license */
  2. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.SockJS = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  3. (function (global){
  4. 'use strict';
  5. var transportList = require('./transport-list');
  6. module.exports = require('./main')(transportList);
  7. // TODO can't get rid of this until all servers do
  8. if ('_sockjs_onload' in global) {
  9. setTimeout(global._sockjs_onload, 1);
  10. }
  11. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12. },{"./main":14,"./transport-list":16}],2:[function(require,module,exports){
  13. 'use strict';
  14. var inherits = require('inherits')
  15. , Event = require('./event')
  16. ;
  17. function CloseEvent() {
  18. Event.call(this);
  19. this.initEvent('close', false, false);
  20. this.wasClean = false;
  21. this.code = 0;
  22. this.reason = '';
  23. }
  24. inherits(CloseEvent, Event);
  25. module.exports = CloseEvent;
  26. },{"./event":4,"inherits":57}],3:[function(require,module,exports){
  27. 'use strict';
  28. var inherits = require('inherits')
  29. , EventTarget = require('./eventtarget')
  30. ;
  31. function EventEmitter() {
  32. EventTarget.call(this);
  33. }
  34. inherits(EventEmitter, EventTarget);
  35. EventEmitter.prototype.removeAllListeners = function(type) {
  36. if (type) {
  37. delete this._listeners[type];
  38. } else {
  39. this._listeners = {};
  40. }
  41. };
  42. EventEmitter.prototype.once = function(type, listener) {
  43. var self = this
  44. , fired = false;
  45. function g() {
  46. self.removeListener(type, g);
  47. if (!fired) {
  48. fired = true;
  49. listener.apply(this, arguments);
  50. }
  51. }
  52. this.on(type, g);
  53. };
  54. EventEmitter.prototype.emit = function() {
  55. var type = arguments[0];
  56. var listeners = this._listeners[type];
  57. if (!listeners) {
  58. return;
  59. }
  60. // equivalent of Array.prototype.slice.call(arguments, 1);
  61. var l = arguments.length;
  62. var args = new Array(l - 1);
  63. for (var ai = 1; ai < l; ai++) {
  64. args[ai - 1] = arguments[ai];
  65. }
  66. for (var i = 0; i < listeners.length; i++) {
  67. listeners[i].apply(this, args);
  68. }
  69. };
  70. EventEmitter.prototype.on = EventEmitter.prototype.addListener = EventTarget.prototype.addEventListener;
  71. EventEmitter.prototype.removeListener = EventTarget.prototype.removeEventListener;
  72. module.exports.EventEmitter = EventEmitter;
  73. },{"./eventtarget":5,"inherits":57}],4:[function(require,module,exports){
  74. 'use strict';
  75. function Event(eventType) {
  76. this.type = eventType;
  77. }
  78. Event.prototype.initEvent = function(eventType, canBubble, cancelable) {
  79. this.type = eventType;
  80. this.bubbles = canBubble;
  81. this.cancelable = cancelable;
  82. this.timeStamp = +new Date();
  83. return this;
  84. };
  85. Event.prototype.stopPropagation = function() {};
  86. Event.prototype.preventDefault = function() {};
  87. Event.CAPTURING_PHASE = 1;
  88. Event.AT_TARGET = 2;
  89. Event.BUBBLING_PHASE = 3;
  90. module.exports = Event;
  91. },{}],5:[function(require,module,exports){
  92. 'use strict';
  93. /* Simplified implementation of DOM2 EventTarget.
  94. * http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget
  95. */
  96. function EventTarget() {
  97. this._listeners = {};
  98. }
  99. EventTarget.prototype.addEventListener = function(eventType, listener) {
  100. if (!(eventType in this._listeners)) {
  101. this._listeners[eventType] = [];
  102. }
  103. var arr = this._listeners[eventType];
  104. // #4
  105. if (arr.indexOf(listener) === -1) {
  106. // Make a copy so as not to interfere with a current dispatchEvent.
  107. arr = arr.concat([listener]);
  108. }
  109. this._listeners[eventType] = arr;
  110. };
  111. EventTarget.prototype.removeEventListener = function(eventType, listener) {
  112. var arr = this._listeners[eventType];
  113. if (!arr) {
  114. return;
  115. }
  116. var idx = arr.indexOf(listener);
  117. if (idx !== -1) {
  118. if (arr.length > 1) {
  119. // Make a copy so as not to interfere with a current dispatchEvent.
  120. this._listeners[eventType] = arr.slice(0, idx).concat(arr.slice(idx + 1));
  121. } else {
  122. delete this._listeners[eventType];
  123. }
  124. return;
  125. }
  126. };
  127. EventTarget.prototype.dispatchEvent = function() {
  128. var event = arguments[0];
  129. var t = event.type;
  130. // equivalent of Array.prototype.slice.call(arguments, 0);
  131. var args = arguments.length === 1 ? [event] : Array.apply(null, arguments);
  132. // TODO: This doesn't match the real behavior; per spec, onfoo get
  133. // their place in line from the /first/ time they're set from
  134. // non-null. Although WebKit bumps it to the end every time it's
  135. // set.
  136. if (this['on' + t]) {
  137. this['on' + t].apply(this, args);
  138. }
  139. if (t in this._listeners) {
  140. // Grab a reference to the listeners list. removeEventListener may alter the list.
  141. var listeners = this._listeners[t];
  142. for (var i = 0; i < listeners.length; i++) {
  143. listeners[i].apply(this, args);
  144. }
  145. }
  146. };
  147. module.exports = EventTarget;
  148. },{}],6:[function(require,module,exports){
  149. 'use strict';
  150. var inherits = require('inherits')
  151. , Event = require('./event')
  152. ;
  153. function TransportMessageEvent(data) {
  154. Event.call(this);
  155. this.initEvent('message', false, false);
  156. this.data = data;
  157. }
  158. inherits(TransportMessageEvent, Event);
  159. module.exports = TransportMessageEvent;
  160. },{"./event":4,"inherits":57}],7:[function(require,module,exports){
  161. 'use strict';
  162. var JSON3 = require('json3')
  163. , iframeUtils = require('./utils/iframe')
  164. ;
  165. function FacadeJS(transport) {
  166. this._transport = transport;
  167. transport.on('message', this._transportMessage.bind(this));
  168. transport.on('close', this._transportClose.bind(this));
  169. }
  170. FacadeJS.prototype._transportClose = function(code, reason) {
  171. iframeUtils.postMessage('c', JSON3.stringify([code, reason]));
  172. };
  173. FacadeJS.prototype._transportMessage = function(frame) {
  174. iframeUtils.postMessage('t', frame);
  175. };
  176. FacadeJS.prototype._send = function(data) {
  177. this._transport.send(data);
  178. };
  179. FacadeJS.prototype._close = function() {
  180. this._transport.close();
  181. this._transport.removeAllListeners();
  182. };
  183. module.exports = FacadeJS;
  184. },{"./utils/iframe":47,"json3":58}],8:[function(require,module,exports){
  185. (function (process){
  186. 'use strict';
  187. var urlUtils = require('./utils/url')
  188. , eventUtils = require('./utils/event')
  189. , JSON3 = require('json3')
  190. , FacadeJS = require('./facade')
  191. , InfoIframeReceiver = require('./info-iframe-receiver')
  192. , iframeUtils = require('./utils/iframe')
  193. , loc = require('./location')
  194. ;
  195. var debug = function() {};
  196. if (process.env.NODE_ENV !== 'production') {
  197. debug = require('debug')('sockjs-client:iframe-bootstrap');
  198. }
  199. module.exports = function(SockJS, availableTransports) {
  200. var transportMap = {};
  201. availableTransports.forEach(function(at) {
  202. if (at.facadeTransport) {
  203. transportMap[at.facadeTransport.transportName] = at.facadeTransport;
  204. }
  205. });
  206. // hard-coded for the info iframe
  207. // TODO see if we can make this more dynamic
  208. transportMap[InfoIframeReceiver.transportName] = InfoIframeReceiver;
  209. var parentOrigin;
  210. /* eslint-disable camelcase */
  211. SockJS.bootstrap_iframe = function() {
  212. /* eslint-enable camelcase */
  213. var facade;
  214. iframeUtils.currentWindowId = loc.hash.slice(1);
  215. var onMessage = function(e) {
  216. if (e.source !== parent) {
  217. return;
  218. }
  219. if (typeof parentOrigin === 'undefined') {
  220. parentOrigin = e.origin;
  221. }
  222. if (e.origin !== parentOrigin) {
  223. return;
  224. }
  225. var iframeMessage;
  226. try {
  227. iframeMessage = JSON3.parse(e.data);
  228. } catch (ignored) {
  229. debug('bad json', e.data);
  230. return;
  231. }
  232. if (iframeMessage.windowId !== iframeUtils.currentWindowId) {
  233. return;
  234. }
  235. switch (iframeMessage.type) {
  236. case 's':
  237. var p;
  238. try {
  239. p = JSON3.parse(iframeMessage.data);
  240. } catch (ignored) {
  241. debug('bad json', iframeMessage.data);
  242. break;
  243. }
  244. var version = p[0];
  245. var transport = p[1];
  246. var transUrl = p[2];
  247. var baseUrl = p[3];
  248. debug(version, transport, transUrl, baseUrl);
  249. // change this to semver logic
  250. if (version !== SockJS.version) {
  251. throw new Error('Incompatible SockJS! Main site uses:' +
  252. ' "' + version + '", the iframe:' +
  253. ' "' + SockJS.version + '".');
  254. }
  255. if (!urlUtils.isOriginEqual(transUrl, loc.href) ||
  256. !urlUtils.isOriginEqual(baseUrl, loc.href)) {
  257. throw new Error('Can\'t connect to different domain from within an ' +
  258. 'iframe. (' + loc.href + ', ' + transUrl + ', ' + baseUrl + ')');
  259. }
  260. facade = new FacadeJS(new transportMap[transport](transUrl, baseUrl));
  261. break;
  262. case 'm':
  263. facade._send(iframeMessage.data);
  264. break;
  265. case 'c':
  266. if (facade) {
  267. facade._close();
  268. }
  269. facade = null;
  270. break;
  271. }
  272. };
  273. eventUtils.attachEvent('message', onMessage);
  274. // Start
  275. iframeUtils.postMessage('s');
  276. };
  277. };
  278. }).call(this,{ env: {} })
  279. },{"./facade":7,"./info-iframe-receiver":10,"./location":13,"./utils/event":46,"./utils/iframe":47,"./utils/url":52,"debug":55,"json3":58}],9:[function(require,module,exports){
  280. (function (process){
  281. 'use strict';
  282. var EventEmitter = require('events').EventEmitter
  283. , inherits = require('inherits')
  284. , JSON3 = require('json3')
  285. , objectUtils = require('./utils/object')
  286. ;
  287. var debug = function() {};
  288. if (process.env.NODE_ENV !== 'production') {
  289. debug = require('debug')('sockjs-client:info-ajax');
  290. }
  291. function InfoAjax(url, AjaxObject) {
  292. EventEmitter.call(this);
  293. var self = this;
  294. var t0 = +new Date();
  295. this.xo = new AjaxObject('GET', url);
  296. this.xo.once('finish', function(status, text) {
  297. var info, rtt;
  298. if (status === 200) {
  299. rtt = (+new Date()) - t0;
  300. if (text) {
  301. try {
  302. info = JSON3.parse(text);
  303. } catch (e) {
  304. debug('bad json', text);
  305. }
  306. }
  307. if (!objectUtils.isObject(info)) {
  308. info = {};
  309. }
  310. }
  311. self.emit('finish', info, rtt);
  312. self.removeAllListeners();
  313. });
  314. }
  315. inherits(InfoAjax, EventEmitter);
  316. InfoAjax.prototype.close = function() {
  317. this.removeAllListeners();
  318. this.xo.close();
  319. };
  320. module.exports = InfoAjax;
  321. }).call(this,{ env: {} })
  322. },{"./utils/object":49,"debug":55,"events":3,"inherits":57,"json3":58}],10:[function(require,module,exports){
  323. 'use strict';
  324. var inherits = require('inherits')
  325. , EventEmitter = require('events').EventEmitter
  326. , JSON3 = require('json3')
  327. , XHRLocalObject = require('./transport/sender/xhr-local')
  328. , InfoAjax = require('./info-ajax')
  329. ;
  330. function InfoReceiverIframe(transUrl) {
  331. var self = this;
  332. EventEmitter.call(this);
  333. this.ir = new InfoAjax(transUrl, XHRLocalObject);
  334. this.ir.once('finish', function(info, rtt) {
  335. self.ir = null;
  336. self.emit('message', JSON3.stringify([info, rtt]));
  337. });
  338. }
  339. inherits(InfoReceiverIframe, EventEmitter);
  340. InfoReceiverIframe.transportName = 'iframe-info-receiver';
  341. InfoReceiverIframe.prototype.close = function() {
  342. if (this.ir) {
  343. this.ir.close();
  344. this.ir = null;
  345. }
  346. this.removeAllListeners();
  347. };
  348. module.exports = InfoReceiverIframe;
  349. },{"./info-ajax":9,"./transport/sender/xhr-local":37,"events":3,"inherits":57,"json3":58}],11:[function(require,module,exports){
  350. (function (process,global){
  351. 'use strict';
  352. var EventEmitter = require('events').EventEmitter
  353. , inherits = require('inherits')
  354. , JSON3 = require('json3')
  355. , utils = require('./utils/event')
  356. , IframeTransport = require('./transport/iframe')
  357. , InfoReceiverIframe = require('./info-iframe-receiver')
  358. ;
  359. var debug = function() {};
  360. if (process.env.NODE_ENV !== 'production') {
  361. debug = require('debug')('sockjs-client:info-iframe');
  362. }
  363. function InfoIframe(baseUrl, url) {
  364. var self = this;
  365. EventEmitter.call(this);
  366. var go = function() {
  367. var ifr = self.ifr = new IframeTransport(InfoReceiverIframe.transportName, url, baseUrl);
  368. ifr.once('message', function(msg) {
  369. if (msg) {
  370. var d;
  371. try {
  372. d = JSON3.parse(msg);
  373. } catch (e) {
  374. debug('bad json', msg);
  375. self.emit('finish');
  376. self.close();
  377. return;
  378. }
  379. var info = d[0], rtt = d[1];
  380. self.emit('finish', info, rtt);
  381. }
  382. self.close();
  383. });
  384. ifr.once('close', function() {
  385. self.emit('finish');
  386. self.close();
  387. });
  388. };
  389. // TODO this seems the same as the 'needBody' from transports
  390. if (!global.document.body) {
  391. utils.attachEvent('load', go);
  392. } else {
  393. go();
  394. }
  395. }
  396. inherits(InfoIframe, EventEmitter);
  397. InfoIframe.enabled = function() {
  398. return IframeTransport.enabled();
  399. };
  400. InfoIframe.prototype.close = function() {
  401. if (this.ifr) {
  402. this.ifr.close();
  403. }
  404. this.removeAllListeners();
  405. this.ifr = null;
  406. };
  407. module.exports = InfoIframe;
  408. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  409. },{"./info-iframe-receiver":10,"./transport/iframe":22,"./utils/event":46,"debug":55,"events":3,"inherits":57,"json3":58}],12:[function(require,module,exports){
  410. (function (process){
  411. 'use strict';
  412. var EventEmitter = require('events').EventEmitter
  413. , inherits = require('inherits')
  414. , urlUtils = require('./utils/url')
  415. , XDR = require('./transport/sender/xdr')
  416. , XHRCors = require('./transport/sender/xhr-cors')
  417. , XHRLocal = require('./transport/sender/xhr-local')
  418. , XHRFake = require('./transport/sender/xhr-fake')
  419. , InfoIframe = require('./info-iframe')
  420. , InfoAjax = require('./info-ajax')
  421. ;
  422. var debug = function() {};
  423. if (process.env.NODE_ENV !== 'production') {
  424. debug = require('debug')('sockjs-client:info-receiver');
  425. }
  426. function InfoReceiver(baseUrl, urlInfo) {
  427. debug(baseUrl);
  428. var self = this;
  429. EventEmitter.call(this);
  430. setTimeout(function() {
  431. self.doXhr(baseUrl, urlInfo);
  432. }, 0);
  433. }
  434. inherits(InfoReceiver, EventEmitter);
  435. // TODO this is currently ignoring the list of available transports and the whitelist
  436. InfoReceiver._getReceiver = function(baseUrl, url, urlInfo) {
  437. // determine method of CORS support (if needed)
  438. if (urlInfo.sameOrigin) {
  439. return new InfoAjax(url, XHRLocal);
  440. }
  441. if (XHRCors.enabled) {
  442. return new InfoAjax(url, XHRCors);
  443. }
  444. if (XDR.enabled && urlInfo.sameScheme) {
  445. return new InfoAjax(url, XDR);
  446. }
  447. if (InfoIframe.enabled()) {
  448. return new InfoIframe(baseUrl, url);
  449. }
  450. return new InfoAjax(url, XHRFake);
  451. };
  452. InfoReceiver.prototype.doXhr = function(baseUrl, urlInfo) {
  453. var self = this
  454. , url = urlUtils.addPath(baseUrl, '/info')
  455. ;
  456. debug('doXhr', url);
  457. this.xo = InfoReceiver._getReceiver(baseUrl, url, urlInfo);
  458. this.timeoutRef = setTimeout(function() {
  459. debug('timeout');
  460. self._cleanup(false);
  461. self.emit('finish');
  462. }, InfoReceiver.timeout);
  463. this.xo.once('finish', function(info, rtt) {
  464. debug('finish', info, rtt);
  465. self._cleanup(true);
  466. self.emit('finish', info, rtt);
  467. });
  468. };
  469. InfoReceiver.prototype._cleanup = function(wasClean) {
  470. debug('_cleanup');
  471. clearTimeout(this.timeoutRef);
  472. this.timeoutRef = null;
  473. if (!wasClean && this.xo) {
  474. this.xo.close();
  475. }
  476. this.xo = null;
  477. };
  478. InfoReceiver.prototype.close = function() {
  479. debug('close');
  480. this.removeAllListeners();
  481. this._cleanup(false);
  482. };
  483. InfoReceiver.timeout = 8000;
  484. module.exports = InfoReceiver;
  485. }).call(this,{ env: {} })
  486. },{"./info-ajax":9,"./info-iframe":11,"./transport/sender/xdr":34,"./transport/sender/xhr-cors":35,"./transport/sender/xhr-fake":36,"./transport/sender/xhr-local":37,"./utils/url":52,"debug":55,"events":3,"inherits":57}],13:[function(require,module,exports){
  487. (function (global){
  488. 'use strict';
  489. module.exports = global.location || {
  490. origin: 'http://localhost:80'
  491. , protocol: 'http:'
  492. , host: 'localhost'
  493. , port: 80
  494. , href: 'http://localhost/'
  495. , hash: ''
  496. };
  497. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  498. },{}],14:[function(require,module,exports){
  499. (function (process,global){
  500. 'use strict';
  501. require('./shims');
  502. var URL = require('url-parse')
  503. , inherits = require('inherits')
  504. , JSON3 = require('json3')
  505. , random = require('./utils/random')
  506. , escape = require('./utils/escape')
  507. , urlUtils = require('./utils/url')
  508. , eventUtils = require('./utils/event')
  509. , transport = require('./utils/transport')
  510. , objectUtils = require('./utils/object')
  511. , browser = require('./utils/browser')
  512. , log = require('./utils/log')
  513. , Event = require('./event/event')
  514. , EventTarget = require('./event/eventtarget')
  515. , loc = require('./location')
  516. , CloseEvent = require('./event/close')
  517. , TransportMessageEvent = require('./event/trans-message')
  518. , InfoReceiver = require('./info-receiver')
  519. ;
  520. var debug = function() {};
  521. if (process.env.NODE_ENV !== 'production') {
  522. debug = require('debug')('sockjs-client:main');
  523. }
  524. var transports;
  525. // follow constructor steps defined at http://dev.w3.org/html5/websockets/#the-websocket-interface
  526. function SockJS(url, protocols, options) {
  527. if (!(this instanceof SockJS)) {
  528. return new SockJS(url, protocols, options);
  529. }
  530. if (arguments.length < 1) {
  531. throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");
  532. }
  533. EventTarget.call(this);
  534. this.readyState = SockJS.CONNECTING;
  535. this.extensions = '';
  536. this.protocol = '';
  537. // non-standard extension
  538. options = options || {};
  539. if (options.protocols_whitelist) {
  540. log.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead.");
  541. }
  542. this._transportsWhitelist = options.transports;
  543. this._transportOptions = options.transportOptions || {};
  544. this._timeout = options.timeout || 0;
  545. var sessionId = options.sessionId || 8;
  546. if (typeof sessionId === 'function') {
  547. this._generateSessionId = sessionId;
  548. } else if (typeof sessionId === 'number') {
  549. this._generateSessionId = function() {
  550. return random.string(sessionId);
  551. };
  552. } else {
  553. throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');
  554. }
  555. this._server = options.server || random.numberString(1000);
  556. // Step 1 of WS spec - parse and validate the url. Issue #8
  557. var parsedUrl = new URL(url);
  558. if (!parsedUrl.host || !parsedUrl.protocol) {
  559. throw new SyntaxError("The URL '" + url + "' is invalid");
  560. } else if (parsedUrl.hash) {
  561. throw new SyntaxError('The URL must not contain a fragment');
  562. } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
  563. throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.");
  564. }
  565. var secure = parsedUrl.protocol === 'https:';
  566. // Step 2 - don't allow secure origin with an insecure protocol
  567. if (loc.protocol === 'https:' && !secure) {
  568. throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
  569. }
  570. // Step 3 - check port access - no need here
  571. // Step 4 - parse protocols argument
  572. if (!protocols) {
  573. protocols = [];
  574. } else if (!Array.isArray(protocols)) {
  575. protocols = [protocols];
  576. }
  577. // Step 5 - check protocols argument
  578. var sortedProtocols = protocols.sort();
  579. sortedProtocols.forEach(function(proto, i) {
  580. if (!proto) {
  581. throw new SyntaxError("The protocols entry '" + proto + "' is invalid.");
  582. }
  583. if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {
  584. throw new SyntaxError("The protocols entry '" + proto + "' is duplicated.");
  585. }
  586. });
  587. // Step 6 - convert origin
  588. var o = urlUtils.getOrigin(loc.href);
  589. this._origin = o ? o.toLowerCase() : null;
  590. // remove the trailing slash
  591. parsedUrl.set('pathname', parsedUrl.pathname.replace(/\/+$/, ''));
  592. // store the sanitized url
  593. this.url = parsedUrl.href;
  594. debug('using url', this.url);
  595. // Step 7 - start connection in background
  596. // obtain server info
  597. // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26
  598. this._urlInfo = {
  599. nullOrigin: !browser.hasDomain()
  600. , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)
  601. , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)
  602. };
  603. this._ir = new InfoReceiver(this.url, this._urlInfo);
  604. this._ir.once('finish', this._receiveInfo.bind(this));
  605. }
  606. inherits(SockJS, EventTarget);
  607. function userSetCode(code) {
  608. return code === 1000 || (code >= 3000 && code <= 4999);
  609. }
  610. SockJS.prototype.close = function(code, reason) {
  611. // Step 1
  612. if (code && !userSetCode(code)) {
  613. throw new Error('InvalidAccessError: Invalid code');
  614. }
  615. // Step 2.4 states the max is 123 bytes, but we are just checking length
  616. if (reason && reason.length > 123) {
  617. throw new SyntaxError('reason argument has an invalid length');
  618. }
  619. // Step 3.1
  620. if (this.readyState === SockJS.CLOSING || this.readyState === SockJS.CLOSED) {
  621. return;
  622. }
  623. // TODO look at docs to determine how to set this
  624. var wasClean = true;
  625. this._close(code || 1000, reason || 'Normal closure', wasClean);
  626. };
  627. SockJS.prototype.send = function(data) {
  628. // #13 - convert anything non-string to string
  629. // TODO this currently turns objects into [object Object]
  630. if (typeof data !== 'string') {
  631. data = '' + data;
  632. }
  633. if (this.readyState === SockJS.CONNECTING) {
  634. throw new Error('InvalidStateError: The connection has not been established yet');
  635. }
  636. if (this.readyState !== SockJS.OPEN) {
  637. return;
  638. }
  639. this._transport.send(escape.quote(data));
  640. };
  641. SockJS.version = require('./version');
  642. SockJS.CONNECTING = 0;
  643. SockJS.OPEN = 1;
  644. SockJS.CLOSING = 2;
  645. SockJS.CLOSED = 3;
  646. SockJS.prototype._receiveInfo = function(info, rtt) {
  647. debug('_receiveInfo', rtt);
  648. this._ir = null;
  649. if (!info) {
  650. this._close(1002, 'Cannot connect to server');
  651. return;
  652. }
  653. // establish a round-trip timeout (RTO) based on the
  654. // round-trip time (RTT)
  655. this._rto = this.countRTO(rtt);
  656. // allow server to override url used for the actual transport
  657. this._transUrl = info.base_url ? info.base_url : this.url;
  658. info = objectUtils.extend(info, this._urlInfo);
  659. debug('info', info);
  660. // determine list of desired and supported transports
  661. var enabledTransports = transports.filterToEnabled(this._transportsWhitelist, info);
  662. this._transports = enabledTransports.main;
  663. debug(this._transports.length + ' enabled transports');
  664. this._connect();
  665. };
  666. SockJS.prototype._connect = function() {
  667. for (var Transport = this._transports.shift(); Transport; Transport = this._transports.shift()) {
  668. debug('attempt', Transport.transportName);
  669. if (Transport.needBody) {
  670. if (!global.document.body ||
  671. (typeof global.document.readyState !== 'undefined' &&
  672. global.document.readyState !== 'complete' &&
  673. global.document.readyState !== 'interactive')) {
  674. debug('waiting for body');
  675. this._transports.unshift(Transport);
  676. eventUtils.attachEvent('load', this._connect.bind(this));
  677. return;
  678. }
  679. }
  680. // calculate timeout based on RTO and round trips. Default to 5s
  681. var timeoutMs = Math.max(this._timeout, (this._rto * Transport.roundTrips) || 5000);
  682. this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs);
  683. debug('using timeout', timeoutMs);
  684. var transportUrl = urlUtils.addPath(this._transUrl, '/' + this._server + '/' + this._generateSessionId());
  685. var options = this._transportOptions[Transport.transportName];
  686. debug('transport url', transportUrl);
  687. var transportObj = new Transport(transportUrl, this._transUrl, options);
  688. transportObj.on('message', this._transportMessage.bind(this));
  689. transportObj.once('close', this._transportClose.bind(this));
  690. transportObj.transportName = Transport.transportName;
  691. this._transport = transportObj;
  692. return;
  693. }
  694. this._close(2000, 'All transports failed', false);
  695. };
  696. SockJS.prototype._transportTimeout = function() {
  697. debug('_transportTimeout');
  698. if (this.readyState === SockJS.CONNECTING) {
  699. if (this._transport) {
  700. this._transport.close();
  701. }
  702. this._transportClose(2007, 'Transport timed out');
  703. }
  704. };
  705. SockJS.prototype._transportMessage = function(msg) {
  706. debug('_transportMessage', msg);
  707. var self = this
  708. , type = msg.slice(0, 1)
  709. , content = msg.slice(1)
  710. , payload
  711. ;
  712. // first check for messages that don't need a payload
  713. switch (type) {
  714. case 'o':
  715. this._open();
  716. return;
  717. case 'h':
  718. this.dispatchEvent(new Event('heartbeat'));
  719. debug('heartbeat', this.transport);
  720. return;
  721. }
  722. if (content) {
  723. try {
  724. payload = JSON3.parse(content);
  725. } catch (e) {
  726. debug('bad json', content);
  727. }
  728. }
  729. if (typeof payload === 'undefined') {
  730. debug('empty payload', content);
  731. return;
  732. }
  733. switch (type) {
  734. case 'a':
  735. if (Array.isArray(payload)) {
  736. payload.forEach(function(p) {
  737. debug('message', self.transport, p);
  738. self.dispatchEvent(new TransportMessageEvent(p));
  739. });
  740. }
  741. break;
  742. case 'm':
  743. debug('message', this.transport, payload);
  744. this.dispatchEvent(new TransportMessageEvent(payload));
  745. break;
  746. case 'c':
  747. if (Array.isArray(payload) && payload.length === 2) {
  748. this._close(payload[0], payload[1], true);
  749. }
  750. break;
  751. }
  752. };
  753. SockJS.prototype._transportClose = function(code, reason) {
  754. debug('_transportClose', this.transport, code, reason);
  755. if (this._transport) {
  756. this._transport.removeAllListeners();
  757. this._transport = null;
  758. this.transport = null;
  759. }
  760. if (!userSetCode(code) && code !== 2000 && this.readyState === SockJS.CONNECTING) {
  761. this._connect();
  762. return;
  763. }
  764. this._close(code, reason);
  765. };
  766. SockJS.prototype._open = function() {
  767. debug('_open', this._transport && this._transport.transportName, this.readyState);
  768. if (this.readyState === SockJS.CONNECTING) {
  769. if (this._transportTimeoutId) {
  770. clearTimeout(this._transportTimeoutId);
  771. this._transportTimeoutId = null;
  772. }
  773. this.readyState = SockJS.OPEN;
  774. this.transport = this._transport.transportName;
  775. this.dispatchEvent(new Event('open'));
  776. debug('connected', this.transport);
  777. } else {
  778. // The server might have been restarted, and lost track of our
  779. // connection.
  780. this._close(1006, 'Server lost session');
  781. }
  782. };
  783. SockJS.prototype._close = function(code, reason, wasClean) {
  784. debug('_close', this.transport, code, reason, wasClean, this.readyState);
  785. var forceFail = false;
  786. if (this._ir) {
  787. forceFail = true;
  788. this._ir.close();
  789. this._ir = null;
  790. }
  791. if (this._transport) {
  792. this._transport.close();
  793. this._transport = null;
  794. this.transport = null;
  795. }
  796. if (this.readyState === SockJS.CLOSED) {
  797. throw new Error('InvalidStateError: SockJS has already been closed');
  798. }
  799. this.readyState = SockJS.CLOSING;
  800. setTimeout(function() {
  801. this.readyState = SockJS.CLOSED;
  802. if (forceFail) {
  803. this.dispatchEvent(new Event('error'));
  804. }
  805. var e = new CloseEvent('close');
  806. e.wasClean = wasClean || false;
  807. e.code = code || 1000;
  808. e.reason = reason;
  809. this.dispatchEvent(e);
  810. this.onmessage = this.onclose = this.onerror = null;
  811. debug('disconnected');
  812. }.bind(this), 0);
  813. };
  814. // See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/
  815. // and RFC 2988.
  816. SockJS.prototype.countRTO = function(rtt) {
  817. // In a local environment, when using IE8/9 and the `jsonp-polling`
  818. // transport the time needed to establish a connection (the time that pass
  819. // from the opening of the transport to the call of `_dispatchOpen`) is
  820. // around 200msec (the lower bound used in the article above) and this
  821. // causes spurious timeouts. For this reason we calculate a value slightly
  822. // larger than that used in the article.
  823. if (rtt > 100) {
  824. return 4 * rtt; // rto > 400msec
  825. }
  826. return 300 + rtt; // 300msec < rto <= 400msec
  827. };
  828. module.exports = function(availableTransports) {
  829. transports = transport(availableTransports);
  830. require('./iframe-bootstrap')(SockJS, availableTransports);
  831. return SockJS;
  832. };
  833. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  834. },{"./event/close":2,"./event/event":4,"./event/eventtarget":5,"./event/trans-message":6,"./iframe-bootstrap":8,"./info-receiver":12,"./location":13,"./shims":15,"./utils/browser":44,"./utils/escape":45,"./utils/event":46,"./utils/log":48,"./utils/object":49,"./utils/random":50,"./utils/transport":51,"./utils/url":52,"./version":53,"debug":55,"inherits":57,"json3":58,"url-parse":61}],15:[function(require,module,exports){
  835. /* eslint-disable */
  836. /* jscs: disable */
  837. 'use strict';
  838. // pulled specific shims from https://github.com/es-shims/es5-shim
  839. var ArrayPrototype = Array.prototype;
  840. var ObjectPrototype = Object.prototype;
  841. var FunctionPrototype = Function.prototype;
  842. var StringPrototype = String.prototype;
  843. var array_slice = ArrayPrototype.slice;
  844. var _toString = ObjectPrototype.toString;
  845. var isFunction = function (val) {
  846. return ObjectPrototype.toString.call(val) === '[object Function]';
  847. };
  848. var isArray = function isArray(obj) {
  849. return _toString.call(obj) === '[object Array]';
  850. };
  851. var isString = function isString(obj) {
  852. return _toString.call(obj) === '[object String]';
  853. };
  854. var supportsDescriptors = Object.defineProperty && (function () {
  855. try {
  856. Object.defineProperty({}, 'x', {});
  857. return true;
  858. } catch (e) { /* this is ES3 */
  859. return false;
  860. }
  861. }());
  862. // Define configurable, writable and non-enumerable props
  863. // if they don't exist.
  864. var defineProperty;
  865. if (supportsDescriptors) {
  866. defineProperty = function (object, name, method, forceAssign) {
  867. if (!forceAssign && (name in object)) { return; }
  868. Object.defineProperty(object, name, {
  869. configurable: true,
  870. enumerable: false,
  871. writable: true,
  872. value: method
  873. });
  874. };
  875. } else {
  876. defineProperty = function (object, name, method, forceAssign) {
  877. if (!forceAssign && (name in object)) { return; }
  878. object[name] = method;
  879. };
  880. }
  881. var defineProperties = function (object, map, forceAssign) {
  882. for (var name in map) {
  883. if (ObjectPrototype.hasOwnProperty.call(map, name)) {
  884. defineProperty(object, name, map[name], forceAssign);
  885. }
  886. }
  887. };
  888. var toObject = function (o) {
  889. if (o == null) { // this matches both null and undefined
  890. throw new TypeError("can't convert " + o + ' to object');
  891. }
  892. return Object(o);
  893. };
  894. //
  895. // Util
  896. // ======
  897. //
  898. // ES5 9.4
  899. // http://es5.github.com/#x9.4
  900. // http://jsperf.com/to-integer
  901. function toInteger(num) {
  902. var n = +num;
  903. if (n !== n) { // isNaN
  904. n = 0;
  905. } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  906. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  907. }
  908. return n;
  909. }
  910. function ToUint32(x) {
  911. return x >>> 0;
  912. }
  913. //
  914. // Function
  915. // ========
  916. //
  917. // ES-5 15.3.4.5
  918. // http://es5.github.com/#x15.3.4.5
  919. function Empty() {}
  920. defineProperties(FunctionPrototype, {
  921. bind: function bind(that) { // .length is 1
  922. // 1. Let Target be the this value.
  923. var target = this;
  924. // 2. If IsCallable(Target) is false, throw a TypeError exception.
  925. if (!isFunction(target)) {
  926. throw new TypeError('Function.prototype.bind called on incompatible ' + target);
  927. }
  928. // 3. Let A be a new (possibly empty) internal list of all of the
  929. // argument values provided after thisArg (arg1, arg2 etc), in order.
  930. // XXX slicedArgs will stand in for "A" if used
  931. var args = array_slice.call(arguments, 1); // for normal call
  932. // 4. Let F be a new native ECMAScript object.
  933. // 11. Set the [[Prototype]] internal property of F to the standard
  934. // built-in Function prototype object as specified in 15.3.3.1.
  935. // 12. Set the [[Call]] internal property of F as described in
  936. // 15.3.4.5.1.
  937. // 13. Set the [[Construct]] internal property of F as described in
  938. // 15.3.4.5.2.
  939. // 14. Set the [[HasInstance]] internal property of F as described in
  940. // 15.3.4.5.3.
  941. var binder = function () {
  942. if (this instanceof bound) {
  943. // 15.3.4.5.2 [[Construct]]
  944. // When the [[Construct]] internal method of a function object,
  945. // F that was created using the bind function is called with a
  946. // list of arguments ExtraArgs, the following steps are taken:
  947. // 1. Let target be the value of F's [[TargetFunction]]
  948. // internal property.
  949. // 2. If target has no [[Construct]] internal method, a
  950. // TypeError exception is thrown.
  951. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal
  952. // property.
  953. // 4. Let args be a new list containing the same values as the
  954. // list boundArgs in the same order followed by the same
  955. // values as the list ExtraArgs in the same order.
  956. // 5. Return the result of calling the [[Construct]] internal
  957. // method of target providing args as the arguments.
  958. var result = target.apply(
  959. this,
  960. args.concat(array_slice.call(arguments))
  961. );
  962. if (Object(result) === result) {
  963. return result;
  964. }
  965. return this;
  966. } else {
  967. // 15.3.4.5.1 [[Call]]
  968. // When the [[Call]] internal method of a function object, F,
  969. // which was created using the bind function is called with a
  970. // this value and a list of arguments ExtraArgs, the following
  971. // steps are taken:
  972. // 1. Let boundArgs be the value of F's [[BoundArgs]] internal
  973. // property.
  974. // 2. Let boundThis be the value of F's [[BoundThis]] internal
  975. // property.
  976. // 3. Let target be the value of F's [[TargetFunction]] internal
  977. // property.
  978. // 4. Let args be a new list containing the same values as the
  979. // list boundArgs in the same order followed by the same
  980. // values as the list ExtraArgs in the same order.
  981. // 5. Return the result of calling the [[Call]] internal method
  982. // of target providing boundThis as the this value and
  983. // providing args as the arguments.
  984. // equiv: target.call(this, ...boundArgs, ...args)
  985. return target.apply(
  986. that,
  987. args.concat(array_slice.call(arguments))
  988. );
  989. }
  990. };
  991. // 15. If the [[Class]] internal property of Target is "Function", then
  992. // a. Let L be the length property of Target minus the length of A.
  993. // b. Set the length own property of F to either 0 or L, whichever is
  994. // larger.
  995. // 16. Else set the length own property of F to 0.
  996. var boundLength = Math.max(0, target.length - args.length);
  997. // 17. Set the attributes of the length own property of F to the values
  998. // specified in 15.3.5.1.
  999. var boundArgs = [];
  1000. for (var i = 0; i < boundLength; i++) {
  1001. boundArgs.push('$' + i);
  1002. }
  1003. // XXX Build a dynamic function with desired amount of arguments is the only
  1004. // way to set the length property of a function.
  1005. // In environments where Content Security Policies enabled (Chrome extensions,
  1006. // for ex.) all use of eval or Function costructor throws an exception.
  1007. // However in all of these environments Function.prototype.bind exists
  1008. // and so this code will never be executed.
  1009. var bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder);
  1010. if (target.prototype) {
  1011. Empty.prototype = target.prototype;
  1012. bound.prototype = new Empty();
  1013. // Clean up dangling references.
  1014. Empty.prototype = null;
  1015. }
  1016. // TODO
  1017. // 18. Set the [[Extensible]] internal property of F to true.
  1018. // TODO
  1019. // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
  1020. // 20. Call the [[DefineOwnProperty]] internal method of F with
  1021. // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
  1022. // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
  1023. // false.
  1024. // 21. Call the [[DefineOwnProperty]] internal method of F with
  1025. // arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
  1026. // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
  1027. // and false.
  1028. // TODO
  1029. // NOTE Function objects created using Function.prototype.bind do not
  1030. // have a prototype property or the [[Code]], [[FormalParameters]], and
  1031. // [[Scope]] internal properties.
  1032. // XXX can't delete prototype in pure-js.
  1033. // 22. Return F.
  1034. return bound;
  1035. }
  1036. });
  1037. //
  1038. // Array
  1039. // =====
  1040. //
  1041. // ES5 15.4.3.2
  1042. // http://es5.github.com/#x15.4.3.2
  1043. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
  1044. defineProperties(Array, { isArray: isArray });
  1045. var boxedString = Object('a');
  1046. var splitString = boxedString[0] !== 'a' || !(0 in boxedString);
  1047. var properlyBoxesContext = function properlyBoxed(method) {
  1048. // Check node 0.6.21 bug where third parameter is not boxed
  1049. var properlyBoxesNonStrict = true;
  1050. var properlyBoxesStrict = true;
  1051. if (method) {
  1052. method.call('foo', function (_, __, context) {
  1053. if (typeof context !== 'object') { properlyBoxesNonStrict = false; }
  1054. });
  1055. method.call([1], function () {
  1056. 'use strict';
  1057. properlyBoxesStrict = typeof this === 'string';
  1058. }, 'x');
  1059. }
  1060. return !!method && properlyBoxesNonStrict && properlyBoxesStrict;
  1061. };
  1062. defineProperties(ArrayPrototype, {
  1063. forEach: function forEach(fun /*, thisp*/) {
  1064. var object = toObject(this),
  1065. self = splitString && isString(this) ? this.split('') : object,
  1066. thisp = arguments[1],
  1067. i = -1,
  1068. length = self.length >>> 0;
  1069. // If no callback function or if callback is not a callable function
  1070. if (!isFunction(fun)) {
  1071. throw new TypeError(); // TODO message
  1072. }
  1073. while (++i < length) {
  1074. if (i in self) {
  1075. // Invoke the callback function with call, passing arguments:
  1076. // context, property value, property key, thisArg object
  1077. // context
  1078. fun.call(thisp, self[i], i, object);
  1079. }
  1080. }
  1081. }
  1082. }, !properlyBoxesContext(ArrayPrototype.forEach));
  1083. // ES5 15.4.4.14
  1084. // http://es5.github.com/#x15.4.4.14
  1085. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
  1086. var hasFirefox2IndexOfBug = Array.prototype.indexOf && [0, 1].indexOf(1, 2) !== -1;
  1087. defineProperties(ArrayPrototype, {
  1088. indexOf: function indexOf(sought /*, fromIndex */ ) {
  1089. var self = splitString && isString(this) ? this.split('') : toObject(this),
  1090. length = self.length >>> 0;
  1091. if (!length) {
  1092. return -1;
  1093. }
  1094. var i = 0;
  1095. if (arguments.length > 1) {
  1096. i = toInteger(arguments[1]);
  1097. }
  1098. // handle negative indices
  1099. i = i >= 0 ? i : Math.max(0, length + i);
  1100. for (; i < length; i++) {
  1101. if (i in self && self[i] === sought) {
  1102. return i;
  1103. }
  1104. }
  1105. return -1;
  1106. }
  1107. }, hasFirefox2IndexOfBug);
  1108. //
  1109. // String
  1110. // ======
  1111. //
  1112. // ES5 15.5.4.14
  1113. // http://es5.github.com/#x15.5.4.14
  1114. // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]
  1115. // Many browsers do not split properly with regular expressions or they
  1116. // do not perform the split correctly under obscure conditions.
  1117. // See http://blog.stevenlevithan.com/archives/cross-browser-split
  1118. // I've tested in many browsers and this seems to cover the deviant ones:
  1119. // 'ab'.split(/(?:ab)*/) should be ["", ""], not [""]
  1120. // '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""]
  1121. // 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not
  1122. // [undefined, "t", undefined, "e", ...]
  1123. // ''.split(/.?/) should be [], not [""]
  1124. // '.'.split(/()()/) should be ["."], not ["", "", "."]
  1125. var string_split = StringPrototype.split;
  1126. if (
  1127. 'ab'.split(/(?:ab)*/).length !== 2 ||
  1128. '.'.split(/(.?)(.?)/).length !== 4 ||
  1129. 'tesst'.split(/(s)*/)[1] === 't' ||
  1130. 'test'.split(/(?:)/, -1).length !== 4 ||
  1131. ''.split(/.?/).length ||
  1132. '.'.split(/()()/).length > 1
  1133. ) {
  1134. (function () {
  1135. var compliantExecNpcg = /()??/.exec('')[1] === void 0; // NPCG: nonparticipating capturing group
  1136. StringPrototype.split = function (separator, limit) {
  1137. var string = this;
  1138. if (separator === void 0 && limit === 0) {
  1139. return [];
  1140. }
  1141. // If `separator` is not a regex, use native split
  1142. if (_toString.call(separator) !== '[object RegExp]') {
  1143. return string_split.call(this, separator, limit);
  1144. }
  1145. var output = [],
  1146. flags = (separator.ignoreCase ? 'i' : '') +
  1147. (separator.multiline ? 'm' : '') +
  1148. (separator.extended ? 'x' : '') + // Proposed for ES6
  1149. (separator.sticky ? 'y' : ''), // Firefox 3+
  1150. lastLastIndex = 0,
  1151. // Make `global` and avoid `lastIndex` issues by working with a copy
  1152. separator2, match, lastIndex, lastLength;
  1153. separator = new RegExp(separator.source, flags + 'g');
  1154. string += ''; // Type-convert
  1155. if (!compliantExecNpcg) {
  1156. // Doesn't need flags gy, but they don't hurt
  1157. separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags);
  1158. }
  1159. /* Values for `limit`, per the spec:
  1160. * If undefined: 4294967295 // Math.pow(2, 32) - 1
  1161. * If 0, Infinity, or NaN: 0
  1162. * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
  1163. * If negative number: 4294967296 - Math.floor(Math.abs(limit))
  1164. * If other: Type-convert, then use the above rules
  1165. */
  1166. limit = limit === void 0 ?
  1167. -1 >>> 0 : // Math.pow(2, 32) - 1
  1168. ToUint32(limit);
  1169. while (match = separator.exec(string)) {
  1170. // `separator.lastIndex` is not reliable cross-browser
  1171. lastIndex = match.index + match[0].length;
  1172. if (lastIndex > lastLastIndex) {
  1173. output.push(string.slice(lastLastIndex, match.index));
  1174. // Fix browsers whose `exec` methods don't consistently return `undefined` for
  1175. // nonparticipating capturing groups
  1176. if (!compliantExecNpcg && match.length > 1) {
  1177. match[0].replace(separator2, function () {
  1178. for (var i = 1; i < arguments.length - 2; i++) {
  1179. if (arguments[i] === void 0) {
  1180. match[i] = void 0;
  1181. }
  1182. }
  1183. });
  1184. }
  1185. if (match.length > 1 && match.index < string.length) {
  1186. ArrayPrototype.push.apply(output, match.slice(1));
  1187. }
  1188. lastLength = match[0].length;
  1189. lastLastIndex = lastIndex;
  1190. if (output.length >= limit) {
  1191. break;
  1192. }
  1193. }
  1194. if (separator.lastIndex === match.index) {
  1195. separator.lastIndex++; // Avoid an infinite loop
  1196. }
  1197. }
  1198. if (lastLastIndex === string.length) {
  1199. if (lastLength || !separator.test('')) {
  1200. output.push('');
  1201. }
  1202. } else {
  1203. output.push(string.slice(lastLastIndex));
  1204. }
  1205. return output.length > limit ? output.slice(0, limit) : output;
  1206. };
  1207. }());
  1208. // [bugfix, chrome]
  1209. // If separator is undefined, then the result array contains just one String,
  1210. // which is the this value (converted to a String). If limit is not undefined,
  1211. // then the output array is truncated so that it contains no more than limit
  1212. // elements.
  1213. // "0".split(undefined, 0) -> []
  1214. } else if ('0'.split(void 0, 0).length) {
  1215. StringPrototype.split = function split(separator, limit) {
  1216. if (separator === void 0 && limit === 0) { return []; }
  1217. return string_split.call(this, separator, limit);
  1218. };
  1219. }
  1220. // ECMA-262, 3rd B.2.3
  1221. // Not an ECMAScript standard, although ECMAScript 3rd Edition has a
  1222. // non-normative section suggesting uniform semantics and it should be
  1223. // normalized across all browsers
  1224. // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
  1225. var string_substr = StringPrototype.substr;
  1226. var hasNegativeSubstrBug = ''.substr && '0b'.substr(-1) !== 'b';
  1227. defineProperties(StringPrototype, {
  1228. substr: function substr(start, length) {
  1229. return string_substr.call(
  1230. this,
  1231. start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start,
  1232. length
  1233. );
  1234. }
  1235. }, hasNegativeSubstrBug);
  1236. },{}],16:[function(require,module,exports){
  1237. 'use strict';
  1238. module.exports = [
  1239. // streaming transports
  1240. require('./transport/websocket')
  1241. , require('./transport/xhr-streaming')
  1242. , require('./transport/xdr-streaming')
  1243. , require('./transport/eventsource')
  1244. , require('./transport/lib/iframe-wrap')(require('./transport/eventsource'))
  1245. // polling transports
  1246. , require('./transport/htmlfile')
  1247. , require('./transport/lib/iframe-wrap')(require('./transport/htmlfile'))
  1248. , require('./transport/xhr-polling')
  1249. , require('./transport/xdr-polling')
  1250. , require('./transport/lib/iframe-wrap')(require('./transport/xhr-polling'))
  1251. , require('./transport/jsonp-polling')
  1252. ];
  1253. },{"./transport/eventsource":20,"./transport/htmlfile":21,"./transport/jsonp-polling":23,"./transport/lib/iframe-wrap":26,"./transport/websocket":38,"./transport/xdr-polling":39,"./transport/xdr-streaming":40,"./transport/xhr-polling":41,"./transport/xhr-streaming":42}],17:[function(require,module,exports){
  1254. (function (process,global){
  1255. 'use strict';
  1256. var EventEmitter = require('events').EventEmitter
  1257. , inherits = require('inherits')
  1258. , utils = require('../../utils/event')
  1259. , urlUtils = require('../../utils/url')
  1260. , XHR = global.XMLHttpRequest
  1261. ;
  1262. var debug = function() {};
  1263. if (process.env.NODE_ENV !== 'production') {
  1264. debug = require('debug')('sockjs-client:browser:xhr');
  1265. }
  1266. function AbstractXHRObject(method, url, payload, opts) {
  1267. debug(method, url);
  1268. var self = this;
  1269. EventEmitter.call(this);
  1270. setTimeout(function () {
  1271. self._start(method, url, payload, opts);
  1272. }, 0);
  1273. }
  1274. inherits(AbstractXHRObject, EventEmitter);
  1275. AbstractXHRObject.prototype._start = function(method, url, payload, opts) {
  1276. var self = this;
  1277. try {
  1278. this.xhr = new XHR();
  1279. } catch (x) {
  1280. // intentionally empty
  1281. }
  1282. if (!this.xhr) {
  1283. debug('no xhr');
  1284. this.emit('finish', 0, 'no xhr support');
  1285. this._cleanup();
  1286. return;
  1287. }
  1288. // several browsers cache POSTs
  1289. url = urlUtils.addQuery(url, 't=' + (+new Date()));
  1290. // Explorer tends to keep connection open, even after the
  1291. // tab gets closed: http://bugs.jquery.com/ticket/5280
  1292. this.unloadRef = utils.unloadAdd(function() {
  1293. debug('unload cleanup');
  1294. self._cleanup(true);
  1295. });
  1296. try {
  1297. this.xhr.open(method, url, true);
  1298. if (this.timeout && 'timeout' in this.xhr) {
  1299. this.xhr.timeout = this.timeout;
  1300. this.xhr.ontimeout = function() {
  1301. debug('xhr timeout');
  1302. self.emit('finish', 0, '');
  1303. self._cleanup(false);
  1304. };
  1305. }
  1306. } catch (e) {
  1307. debug('exception', e);
  1308. // IE raises an exception on wrong port.
  1309. this.emit('finish', 0, '');
  1310. this._cleanup(false);
  1311. return;
  1312. }
  1313. if ((!opts || !opts.noCredentials) && AbstractXHRObject.supportsCORS) {
  1314. debug('withCredentials');
  1315. // Mozilla docs says https://developer.mozilla.org/en/XMLHttpRequest :
  1316. // "This never affects same-site requests."
  1317. this.xhr.withCredentials = true;
  1318. }
  1319. if (opts && opts.headers) {
  1320. for (var key in opts.headers) {
  1321. this.xhr.setRequestHeader(key, opts.headers[key]);
  1322. }
  1323. }
  1324. this.xhr.onreadystatechange = function() {
  1325. if (self.xhr) {
  1326. var x = self.xhr;
  1327. var text, status;
  1328. debug('readyState', x.readyState);
  1329. switch (x.readyState) {
  1330. case 3:
  1331. // IE doesn't like peeking into responseText or status
  1332. // on Microsoft.XMLHTTP and readystate=3
  1333. try {
  1334. status = x.status;
  1335. text = x.responseText;
  1336. } catch (e) {
  1337. // intentionally empty
  1338. }
  1339. debug('status', status);
  1340. // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
  1341. if (status === 1223) {
  1342. status = 204;
  1343. }
  1344. // IE does return readystate == 3 for 404 answers.
  1345. if (status === 200 && text && text.length > 0) {
  1346. debug('chunk');
  1347. self.emit('chunk', status, text);
  1348. }
  1349. break;
  1350. case 4:
  1351. status = x.status;
  1352. debug('status', status);
  1353. // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
  1354. if (status === 1223) {
  1355. status = 204;
  1356. }
  1357. // IE returns this for a bad port
  1358. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa383770(v=vs.85).aspx
  1359. if (status === 12005 || status === 12029) {
  1360. status = 0;
  1361. }
  1362. debug('finish', status, x.responseText);
  1363. self.emit('finish', status, x.responseText);
  1364. self._cleanup(false);
  1365. break;
  1366. }
  1367. }
  1368. };
  1369. try {
  1370. self.xhr.send(payload);
  1371. } catch (e) {
  1372. self.emit('finish', 0, '');
  1373. self._cleanup(false);
  1374. }
  1375. };
  1376. AbstractXHRObject.prototype._cleanup = function(abort) {
  1377. debug('cleanup');
  1378. if (!this.xhr) {
  1379. return;
  1380. }
  1381. this.removeAllListeners();
  1382. utils.unloadDel(this.unloadRef);
  1383. // IE needs this field to be a function
  1384. this.xhr.onreadystatechange = function() {};
  1385. if (this.xhr.ontimeout) {
  1386. this.xhr.ontimeout = null;
  1387. }
  1388. if (abort) {
  1389. try {
  1390. this.xhr.abort();
  1391. } catch (x) {
  1392. // intentionally empty
  1393. }
  1394. }
  1395. this.unloadRef = this.xhr = null;
  1396. };
  1397. AbstractXHRObject.prototype.close = function() {
  1398. debug('close');
  1399. this._cleanup(true);
  1400. };
  1401. AbstractXHRObject.enabled = !!XHR;
  1402. // override XMLHttpRequest for IE6/7
  1403. // obfuscate to avoid firewalls
  1404. var axo = ['Active'].concat('Object').join('X');
  1405. if (!AbstractXHRObject.enabled && (axo in global)) {
  1406. debug('overriding xmlhttprequest');
  1407. XHR = function() {
  1408. try {
  1409. return new global[axo]('Microsoft.XMLHTTP');
  1410. } catch (e) {
  1411. return null;
  1412. }
  1413. };
  1414. AbstractXHRObject.enabled = !!new XHR();
  1415. }
  1416. var cors = false;
  1417. try {
  1418. cors = 'withCredentials' in new XHR();
  1419. } catch (ignored) {
  1420. // intentionally empty
  1421. }
  1422. AbstractXHRObject.supportsCORS = cors;
  1423. module.exports = AbstractXHRObject;
  1424. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1425. },{"../../utils/event":46,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],18:[function(require,module,exports){
  1426. (function (global){
  1427. module.exports = global.EventSource;
  1428. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1429. },{}],19:[function(require,module,exports){
  1430. (function (global){
  1431. 'use strict';
  1432. var Driver = global.WebSocket || global.MozWebSocket;
  1433. if (Driver) {
  1434. module.exports = function WebSocketBrowserDriver(url) {
  1435. return new Driver(url);
  1436. };
  1437. } else {
  1438. module.exports = undefined;
  1439. }
  1440. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1441. },{}],20:[function(require,module,exports){
  1442. 'use strict';
  1443. var inherits = require('inherits')
  1444. , AjaxBasedTransport = require('./lib/ajax-based')
  1445. , EventSourceReceiver = require('./receiver/eventsource')
  1446. , XHRCorsObject = require('./sender/xhr-cors')
  1447. , EventSourceDriver = require('eventsource')
  1448. ;
  1449. function EventSourceTransport(transUrl) {
  1450. if (!EventSourceTransport.enabled()) {
  1451. throw new Error('Transport created when disabled');
  1452. }
  1453. AjaxBasedTransport.call(this, transUrl, '/eventsource', EventSourceReceiver, XHRCorsObject);
  1454. }
  1455. inherits(EventSourceTransport, AjaxBasedTransport);
  1456. EventSourceTransport.enabled = function() {
  1457. return !!EventSourceDriver;
  1458. };
  1459. EventSourceTransport.transportName = 'eventsource';
  1460. EventSourceTransport.roundTrips = 2;
  1461. module.exports = EventSourceTransport;
  1462. },{"./lib/ajax-based":24,"./receiver/eventsource":29,"./sender/xhr-cors":35,"eventsource":18,"inherits":57}],21:[function(require,module,exports){
  1463. 'use strict';
  1464. var inherits = require('inherits')
  1465. , HtmlfileReceiver = require('./receiver/htmlfile')
  1466. , XHRLocalObject = require('./sender/xhr-local')
  1467. , AjaxBasedTransport = require('./lib/ajax-based')
  1468. ;
  1469. function HtmlFileTransport(transUrl) {
  1470. if (!HtmlfileReceiver.enabled) {
  1471. throw new Error('Transport created when disabled');
  1472. }
  1473. AjaxBasedTransport.call(this, transUrl, '/htmlfile', HtmlfileReceiver, XHRLocalObject);
  1474. }
  1475. inherits(HtmlFileTransport, AjaxBasedTransport);
  1476. HtmlFileTransport.enabled = function(info) {
  1477. return HtmlfileReceiver.enabled && info.sameOrigin;
  1478. };
  1479. HtmlFileTransport.transportName = 'htmlfile';
  1480. HtmlFileTransport.roundTrips = 2;
  1481. module.exports = HtmlFileTransport;
  1482. },{"./lib/ajax-based":24,"./receiver/htmlfile":30,"./sender/xhr-local":37,"inherits":57}],22:[function(require,module,exports){
  1483. (function (process){
  1484. 'use strict';
  1485. // Few cool transports do work only for same-origin. In order to make
  1486. // them work cross-domain we shall use iframe, served from the
  1487. // remote domain. New browsers have capabilities to communicate with
  1488. // cross domain iframe using postMessage(). In IE it was implemented
  1489. // from IE 8+, but of course, IE got some details wrong:
  1490. // http://msdn.microsoft.com/en-us/library/cc197015(v=VS.85).aspx
  1491. // http://stevesouders.com/misc/test-postmessage.php
  1492. var inherits = require('inherits')
  1493. , JSON3 = require('json3')
  1494. , EventEmitter = require('events').EventEmitter
  1495. , version = require('../version')
  1496. , urlUtils = require('../utils/url')
  1497. , iframeUtils = require('../utils/iframe')
  1498. , eventUtils = require('../utils/event')
  1499. , random = require('../utils/random')
  1500. ;
  1501. var debug = function() {};
  1502. if (process.env.NODE_ENV !== 'production') {
  1503. debug = require('debug')('sockjs-client:transport:iframe');
  1504. }
  1505. function IframeTransport(transport, transUrl, baseUrl) {
  1506. if (!IframeTransport.enabled()) {
  1507. throw new Error('Transport created when disabled');
  1508. }
  1509. EventEmitter.call(this);
  1510. var self = this;
  1511. this.origin = urlUtils.getOrigin(baseUrl);
  1512. this.baseUrl = baseUrl;
  1513. this.transUrl = transUrl;
  1514. this.transport = transport;
  1515. this.windowId = random.string(8);
  1516. var iframeUrl = urlUtils.addPath(baseUrl, '/iframe.html') + '#' + this.windowId;
  1517. debug(transport, transUrl, iframeUrl);
  1518. this.iframeObj = iframeUtils.createIframe(iframeUrl, function(r) {
  1519. debug('err callback');
  1520. self.emit('close', 1006, 'Unable to load an iframe (' + r + ')');
  1521. self.close();
  1522. });
  1523. this.onmessageCallback = this._message.bind(this);
  1524. eventUtils.attachEvent('message', this.onmessageCallback);
  1525. }
  1526. inherits(IframeTransport, EventEmitter);
  1527. IframeTransport.prototype.close = function() {
  1528. debug('close');
  1529. this.removeAllListeners();
  1530. if (this.iframeObj) {
  1531. eventUtils.detachEvent('message', this.onmessageCallback);
  1532. try {
  1533. // When the iframe is not loaded, IE raises an exception
  1534. // on 'contentWindow'.
  1535. this.postMessage('c');
  1536. } catch (x) {
  1537. // intentionally empty
  1538. }
  1539. this.iframeObj.cleanup();
  1540. this.iframeObj = null;
  1541. this.onmessageCallback = this.iframeObj = null;
  1542. }
  1543. };
  1544. IframeTransport.prototype._message = function(e) {
  1545. debug('message', e.data);
  1546. if (!urlUtils.isOriginEqual(e.origin, this.origin)) {
  1547. debug('not same origin', e.origin, this.origin);
  1548. return;
  1549. }
  1550. var iframeMessage;
  1551. try {
  1552. iframeMessage = JSON3.parse(e.data);
  1553. } catch (ignored) {
  1554. debug('bad json', e.data);
  1555. return;
  1556. }
  1557. if (iframeMessage.windowId !== this.windowId) {
  1558. debug('mismatched window id', iframeMessage.windowId, this.windowId);
  1559. return;
  1560. }
  1561. switch (iframeMessage.type) {
  1562. case 's':
  1563. this.iframeObj.loaded();
  1564. // window global dependency
  1565. this.postMessage('s', JSON3.stringify([
  1566. version
  1567. , this.transport
  1568. , this.transUrl
  1569. , this.baseUrl
  1570. ]));
  1571. break;
  1572. case 't':
  1573. this.emit('message', iframeMessage.data);
  1574. break;
  1575. case 'c':
  1576. var cdata;
  1577. try {
  1578. cdata = JSON3.parse(iframeMessage.data);
  1579. } catch (ignored) {
  1580. debug('bad json', iframeMessage.data);
  1581. return;
  1582. }
  1583. this.emit('close', cdata[0], cdata[1]);
  1584. this.close();
  1585. break;
  1586. }
  1587. };
  1588. IframeTransport.prototype.postMessage = function(type, data) {
  1589. debug('postMessage', type, data);
  1590. this.iframeObj.post(JSON3.stringify({
  1591. windowId: this.windowId
  1592. , type: type
  1593. , data: data || ''
  1594. }), this.origin);
  1595. };
  1596. IframeTransport.prototype.send = function(message) {
  1597. debug('send', message);
  1598. this.postMessage('m', message);
  1599. };
  1600. IframeTransport.enabled = function() {
  1601. return iframeUtils.iframeEnabled;
  1602. };
  1603. IframeTransport.transportName = 'iframe';
  1604. IframeTransport.roundTrips = 2;
  1605. module.exports = IframeTransport;
  1606. }).call(this,{ env: {} })
  1607. },{"../utils/event":46,"../utils/iframe":47,"../utils/random":50,"../utils/url":52,"../version":53,"debug":55,"events":3,"inherits":57,"json3":58}],23:[function(require,module,exports){
  1608. (function (global){
  1609. 'use strict';
  1610. // The simplest and most robust transport, using the well-know cross
  1611. // domain hack - JSONP. This transport is quite inefficient - one
  1612. // message could use up to one http request. But at least it works almost
  1613. // everywhere.
  1614. // Known limitations:
  1615. // o you will get a spinning cursor
  1616. // o for Konqueror a dumb timer is needed to detect errors
  1617. var inherits = require('inherits')
  1618. , SenderReceiver = require('./lib/sender-receiver')
  1619. , JsonpReceiver = require('./receiver/jsonp')
  1620. , jsonpSender = require('./sender/jsonp')
  1621. ;
  1622. function JsonPTransport(transUrl) {
  1623. if (!JsonPTransport.enabled()) {
  1624. throw new Error('Transport created when disabled');
  1625. }
  1626. SenderReceiver.call(this, transUrl, '/jsonp', jsonpSender, JsonpReceiver);
  1627. }
  1628. inherits(JsonPTransport, SenderReceiver);
  1629. JsonPTransport.enabled = function() {
  1630. return !!global.document;
  1631. };
  1632. JsonPTransport.transportName = 'jsonp-polling';
  1633. JsonPTransport.roundTrips = 1;
  1634. JsonPTransport.needBody = true;
  1635. module.exports = JsonPTransport;
  1636. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1637. },{"./lib/sender-receiver":28,"./receiver/jsonp":31,"./sender/jsonp":33,"inherits":57}],24:[function(require,module,exports){
  1638. (function (process){
  1639. 'use strict';
  1640. var inherits = require('inherits')
  1641. , urlUtils = require('../../utils/url')
  1642. , SenderReceiver = require('./sender-receiver')
  1643. ;
  1644. var debug = function() {};
  1645. if (process.env.NODE_ENV !== 'production') {
  1646. debug = require('debug')('sockjs-client:ajax-based');
  1647. }
  1648. function createAjaxSender(AjaxObject) {
  1649. return function(url, payload, callback) {
  1650. debug('create ajax sender', url, payload);
  1651. var opt = {};
  1652. if (typeof payload === 'string') {
  1653. opt.headers = {'Content-type': 'text/plain'};
  1654. }
  1655. var ajaxUrl = urlUtils.addPath(url, '/xhr_send');
  1656. var xo = new AjaxObject('POST', ajaxUrl, payload, opt);
  1657. xo.once('finish', function(status) {
  1658. debug('finish', status);
  1659. xo = null;
  1660. if (status !== 200 && status !== 204) {
  1661. return callback(new Error('http status ' + status));
  1662. }
  1663. callback();
  1664. });
  1665. return function() {
  1666. debug('abort');
  1667. xo.close();
  1668. xo = null;
  1669. var err = new Error('Aborted');
  1670. err.code = 1000;
  1671. callback(err);
  1672. };
  1673. };
  1674. }
  1675. function AjaxBasedTransport(transUrl, urlSuffix, Receiver, AjaxObject) {
  1676. SenderReceiver.call(this, transUrl, urlSuffix, createAjaxSender(AjaxObject), Receiver, AjaxObject);
  1677. }
  1678. inherits(AjaxBasedTransport, SenderReceiver);
  1679. module.exports = AjaxBasedTransport;
  1680. }).call(this,{ env: {} })
  1681. },{"../../utils/url":52,"./sender-receiver":28,"debug":55,"inherits":57}],25:[function(require,module,exports){
  1682. (function (process){
  1683. 'use strict';
  1684. var inherits = require('inherits')
  1685. , EventEmitter = require('events').EventEmitter
  1686. ;
  1687. var debug = function() {};
  1688. if (process.env.NODE_ENV !== 'production') {
  1689. debug = require('debug')('sockjs-client:buffered-sender');
  1690. }
  1691. function BufferedSender(url, sender) {
  1692. debug(url);
  1693. EventEmitter.call(this);
  1694. this.sendBuffer = [];
  1695. this.sender = sender;
  1696. this.url = url;
  1697. }
  1698. inherits(BufferedSender, EventEmitter);
  1699. BufferedSender.prototype.send = function(message) {
  1700. debug('send', message);
  1701. this.sendBuffer.push(message);
  1702. if (!this.sendStop) {
  1703. this.sendSchedule();
  1704. }
  1705. };
  1706. // For polling transports in a situation when in the message callback,
  1707. // new message is being send. If the sending connection was started
  1708. // before receiving one, it is possible to saturate the network and
  1709. // timeout due to the lack of receiving socket. To avoid that we delay
  1710. // sending messages by some small time, in order to let receiving
  1711. // connection be started beforehand. This is only a halfmeasure and
  1712. // does not fix the big problem, but it does make the tests go more
  1713. // stable on slow networks.
  1714. BufferedSender.prototype.sendScheduleWait = function() {
  1715. debug('sendScheduleWait');
  1716. var self = this;
  1717. var tref;
  1718. this.sendStop = function() {
  1719. debug('sendStop');
  1720. self.sendStop = null;
  1721. clearTimeout(tref);
  1722. };
  1723. tref = setTimeout(function() {
  1724. debug('timeout');
  1725. self.sendStop = null;
  1726. self.sendSchedule();
  1727. }, 25);
  1728. };
  1729. BufferedSender.prototype.sendSchedule = function() {
  1730. debug('sendSchedule', this.sendBuffer.length);
  1731. var self = this;
  1732. if (this.sendBuffer.length > 0) {
  1733. var payload = '[' + this.sendBuffer.join(',') + ']';
  1734. this.sendStop = this.sender(this.url, payload, function(err) {
  1735. self.sendStop = null;
  1736. if (err) {
  1737. debug('error', err);
  1738. self.emit('close', err.code || 1006, 'Sending error: ' + err);
  1739. self.close();
  1740. } else {
  1741. self.sendScheduleWait();
  1742. }
  1743. });
  1744. this.sendBuffer = [];
  1745. }
  1746. };
  1747. BufferedSender.prototype._cleanup = function() {
  1748. debug('_cleanup');
  1749. this.removeAllListeners();
  1750. };
  1751. BufferedSender.prototype.close = function() {
  1752. debug('close');
  1753. this._cleanup();
  1754. if (this.sendStop) {
  1755. this.sendStop();
  1756. this.sendStop = null;
  1757. }
  1758. };
  1759. module.exports = BufferedSender;
  1760. }).call(this,{ env: {} })
  1761. },{"debug":55,"events":3,"inherits":57}],26:[function(require,module,exports){
  1762. (function (global){
  1763. 'use strict';
  1764. var inherits = require('inherits')
  1765. , IframeTransport = require('../iframe')
  1766. , objectUtils = require('../../utils/object')
  1767. ;
  1768. module.exports = function(transport) {
  1769. function IframeWrapTransport(transUrl, baseUrl) {
  1770. IframeTransport.call(this, transport.transportName, transUrl, baseUrl);
  1771. }
  1772. inherits(IframeWrapTransport, IframeTransport);
  1773. IframeWrapTransport.enabled = function(url, info) {
  1774. if (!global.document) {
  1775. return false;
  1776. }
  1777. var iframeInfo = objectUtils.extend({}, info);
  1778. iframeInfo.sameOrigin = true;
  1779. return transport.enabled(iframeInfo) && IframeTransport.enabled();
  1780. };
  1781. IframeWrapTransport.transportName = 'iframe-' + transport.transportName;
  1782. IframeWrapTransport.needBody = true;
  1783. IframeWrapTransport.roundTrips = IframeTransport.roundTrips + transport.roundTrips - 1; // html, javascript (2) + transport - no CORS (1)
  1784. IframeWrapTransport.facadeTransport = transport;
  1785. return IframeWrapTransport;
  1786. };
  1787. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1788. },{"../../utils/object":49,"../iframe":22,"inherits":57}],27:[function(require,module,exports){
  1789. (function (process){
  1790. 'use strict';
  1791. var inherits = require('inherits')
  1792. , EventEmitter = require('events').EventEmitter
  1793. ;
  1794. var debug = function() {};
  1795. if (process.env.NODE_ENV !== 'production') {
  1796. debug = require('debug')('sockjs-client:polling');
  1797. }
  1798. function Polling(Receiver, receiveUrl, AjaxObject) {
  1799. debug(receiveUrl);
  1800. EventEmitter.call(this);
  1801. this.Receiver = Receiver;
  1802. this.receiveUrl = receiveUrl;
  1803. this.AjaxObject = AjaxObject;
  1804. this._scheduleReceiver();
  1805. }
  1806. inherits(Polling, EventEmitter);
  1807. Polling.prototype._scheduleReceiver = function() {
  1808. debug('_scheduleReceiver');
  1809. var self = this;
  1810. var poll = this.poll = new this.Receiver(this.receiveUrl, this.AjaxObject);
  1811. poll.on('message', function(msg) {
  1812. debug('message', msg);
  1813. self.emit('message', msg);
  1814. });
  1815. poll.once('close', function(code, reason) {
  1816. debug('close', code, reason, self.pollIsClosing);
  1817. self.poll = poll = null;
  1818. if (!self.pollIsClosing) {
  1819. if (reason === 'network') {
  1820. self._scheduleReceiver();
  1821. } else {
  1822. self.emit('close', code || 1006, reason);
  1823. self.removeAllListeners();
  1824. }
  1825. }
  1826. });
  1827. };
  1828. Polling.prototype.abort = function() {
  1829. debug('abort');
  1830. this.removeAllListeners();
  1831. this.pollIsClosing = true;
  1832. if (this.poll) {
  1833. this.poll.abort();
  1834. }
  1835. };
  1836. module.exports = Polling;
  1837. }).call(this,{ env: {} })
  1838. },{"debug":55,"events":3,"inherits":57}],28:[function(require,module,exports){
  1839. (function (process){
  1840. 'use strict';
  1841. var inherits = require('inherits')
  1842. , urlUtils = require('../../utils/url')
  1843. , BufferedSender = require('./buffered-sender')
  1844. , Polling = require('./polling')
  1845. ;
  1846. var debug = function() {};
  1847. if (process.env.NODE_ENV !== 'production') {
  1848. debug = require('debug')('sockjs-client:sender-receiver');
  1849. }
  1850. function SenderReceiver(transUrl, urlSuffix, senderFunc, Receiver, AjaxObject) {
  1851. var pollUrl = urlUtils.addPath(transUrl, urlSuffix);
  1852. debug(pollUrl);
  1853. var self = this;
  1854. BufferedSender.call(this, transUrl, senderFunc);
  1855. this.poll = new Polling(Receiver, pollUrl, AjaxObject);
  1856. this.poll.on('message', function(msg) {
  1857. debug('poll message', msg);
  1858. self.emit('message', msg);
  1859. });
  1860. this.poll.once('close', function(code, reason) {
  1861. debug('poll close', code, reason);
  1862. self.poll = null;
  1863. self.emit('close', code, reason);
  1864. self.close();
  1865. });
  1866. }
  1867. inherits(SenderReceiver, BufferedSender);
  1868. SenderReceiver.prototype.close = function() {
  1869. BufferedSender.prototype.close.call(this);
  1870. debug('close');
  1871. this.removeAllListeners();
  1872. if (this.poll) {
  1873. this.poll.abort();
  1874. this.poll = null;
  1875. }
  1876. };
  1877. module.exports = SenderReceiver;
  1878. }).call(this,{ env: {} })
  1879. },{"../../utils/url":52,"./buffered-sender":25,"./polling":27,"debug":55,"inherits":57}],29:[function(require,module,exports){
  1880. (function (process){
  1881. 'use strict';
  1882. var inherits = require('inherits')
  1883. , EventEmitter = require('events').EventEmitter
  1884. , EventSourceDriver = require('eventsource')
  1885. ;
  1886. var debug = function() {};
  1887. if (process.env.NODE_ENV !== 'production') {
  1888. debug = require('debug')('sockjs-client:receiver:eventsource');
  1889. }
  1890. function EventSourceReceiver(url) {
  1891. debug(url);
  1892. EventEmitter.call(this);
  1893. var self = this;
  1894. var es = this.es = new EventSourceDriver(url);
  1895. es.onmessage = function(e) {
  1896. debug('message', e.data);
  1897. self.emit('message', decodeURI(e.data));
  1898. };
  1899. es.onerror = function(e) {
  1900. debug('error', es.readyState, e);
  1901. // ES on reconnection has readyState = 0 or 1.
  1902. // on network error it's CLOSED = 2
  1903. var reason = (es.readyState !== 2 ? 'network' : 'permanent');
  1904. self._cleanup();
  1905. self._close(reason);
  1906. };
  1907. }
  1908. inherits(EventSourceReceiver, EventEmitter);
  1909. EventSourceReceiver.prototype.abort = function() {
  1910. debug('abort');
  1911. this._cleanup();
  1912. this._close('user');
  1913. };
  1914. EventSourceReceiver.prototype._cleanup = function() {
  1915. debug('cleanup');
  1916. var es = this.es;
  1917. if (es) {
  1918. es.onmessage = es.onerror = null;
  1919. es.close();
  1920. this.es = null;
  1921. }
  1922. };
  1923. EventSourceReceiver.prototype._close = function(reason) {
  1924. debug('close', reason);
  1925. var self = this;
  1926. // Safari and chrome < 15 crash if we close window before
  1927. // waiting for ES cleanup. See:
  1928. // https://code.google.com/p/chromium/issues/detail?id=89155
  1929. setTimeout(function() {
  1930. self.emit('close', null, reason);
  1931. self.removeAllListeners();
  1932. }, 200);
  1933. };
  1934. module.exports = EventSourceReceiver;
  1935. }).call(this,{ env: {} })
  1936. },{"debug":55,"events":3,"eventsource":18,"inherits":57}],30:[function(require,module,exports){
  1937. (function (process,global){
  1938. 'use strict';
  1939. var inherits = require('inherits')
  1940. , iframeUtils = require('../../utils/iframe')
  1941. , urlUtils = require('../../utils/url')
  1942. , EventEmitter = require('events').EventEmitter
  1943. , random = require('../../utils/random')
  1944. ;
  1945. var debug = function() {};
  1946. if (process.env.NODE_ENV !== 'production') {
  1947. debug = require('debug')('sockjs-client:receiver:htmlfile');
  1948. }
  1949. function HtmlfileReceiver(url) {
  1950. debug(url);
  1951. EventEmitter.call(this);
  1952. var self = this;
  1953. iframeUtils.polluteGlobalNamespace();
  1954. this.id = 'a' + random.string(6);
  1955. url = urlUtils.addQuery(url, 'c=' + decodeURIComponent(iframeUtils.WPrefix + '.' + this.id));
  1956. debug('using htmlfile', HtmlfileReceiver.htmlfileEnabled);
  1957. var constructFunc = HtmlfileReceiver.htmlfileEnabled ?
  1958. iframeUtils.createHtmlfile : iframeUtils.createIframe;
  1959. global[iframeUtils.WPrefix][this.id] = {
  1960. start: function() {
  1961. debug('start');
  1962. self.iframeObj.loaded();
  1963. }
  1964. , message: function(data) {
  1965. debug('message', data);
  1966. self.emit('message', data);
  1967. }
  1968. , stop: function() {
  1969. debug('stop');
  1970. self._cleanup();
  1971. self._close('network');
  1972. }
  1973. };
  1974. this.iframeObj = constructFunc(url, function() {
  1975. debug('callback');
  1976. self._cleanup();
  1977. self._close('permanent');
  1978. });
  1979. }
  1980. inherits(HtmlfileReceiver, EventEmitter);
  1981. HtmlfileReceiver.prototype.abort = function() {
  1982. debug('abort');
  1983. this._cleanup();
  1984. this._close('user');
  1985. };
  1986. HtmlfileReceiver.prototype._cleanup = function() {
  1987. debug('_cleanup');
  1988. if (this.iframeObj) {
  1989. this.iframeObj.cleanup();
  1990. this.iframeObj = null;
  1991. }
  1992. delete global[iframeUtils.WPrefix][this.id];
  1993. };
  1994. HtmlfileReceiver.prototype._close = function(reason) {
  1995. debug('_close', reason);
  1996. this.emit('close', null, reason);
  1997. this.removeAllListeners();
  1998. };
  1999. HtmlfileReceiver.htmlfileEnabled = false;
  2000. // obfuscate to avoid firewalls
  2001. var axo = ['Active'].concat('Object').join('X');
  2002. if (axo in global) {
  2003. try {
  2004. HtmlfileReceiver.htmlfileEnabled = !!new global[axo]('htmlfile');
  2005. } catch (x) {
  2006. // intentionally empty
  2007. }
  2008. }
  2009. HtmlfileReceiver.enabled = HtmlfileReceiver.htmlfileEnabled || iframeUtils.iframeEnabled;
  2010. module.exports = HtmlfileReceiver;
  2011. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2012. },{"../../utils/iframe":47,"../../utils/random":50,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],31:[function(require,module,exports){
  2013. (function (process,global){
  2014. 'use strict';
  2015. var utils = require('../../utils/iframe')
  2016. , random = require('../../utils/random')
  2017. , browser = require('../../utils/browser')
  2018. , urlUtils = require('../../utils/url')
  2019. , inherits = require('inherits')
  2020. , EventEmitter = require('events').EventEmitter
  2021. ;
  2022. var debug = function() {};
  2023. if (process.env.NODE_ENV !== 'production') {
  2024. debug = require('debug')('sockjs-client:receiver:jsonp');
  2025. }
  2026. function JsonpReceiver(url) {
  2027. debug(url);
  2028. var self = this;
  2029. EventEmitter.call(this);
  2030. utils.polluteGlobalNamespace();
  2031. this.id = 'a' + random.string(6);
  2032. var urlWithId = urlUtils.addQuery(url, 'c=' + encodeURIComponent(utils.WPrefix + '.' + this.id));
  2033. global[utils.WPrefix][this.id] = this._callback.bind(this);
  2034. this._createScript(urlWithId);
  2035. // Fallback mostly for Konqueror - stupid timer, 35 seconds shall be plenty.
  2036. this.timeoutId = setTimeout(function() {
  2037. debug('timeout');
  2038. self._abort(new Error('JSONP script loaded abnormally (timeout)'));
  2039. }, JsonpReceiver.timeout);
  2040. }
  2041. inherits(JsonpReceiver, EventEmitter);
  2042. JsonpReceiver.prototype.abort = function() {
  2043. debug('abort');
  2044. if (global[utils.WPrefix][this.id]) {
  2045. var err = new Error('JSONP user aborted read');
  2046. err.code = 1000;
  2047. this._abort(err);
  2048. }
  2049. };
  2050. JsonpReceiver.timeout = 35000;
  2051. JsonpReceiver.scriptErrorTimeout = 1000;
  2052. JsonpReceiver.prototype._callback = function(data) {
  2053. debug('_callback', data);
  2054. this._cleanup();
  2055. if (this.aborting) {
  2056. return;
  2057. }
  2058. if (data) {
  2059. debug('message', data);
  2060. this.emit('message', data);
  2061. }
  2062. this.emit('close', null, 'network');
  2063. this.removeAllListeners();
  2064. };
  2065. JsonpReceiver.prototype._abort = function(err) {
  2066. debug('_abort', err);
  2067. this._cleanup();
  2068. this.aborting = true;
  2069. this.emit('close', err.code, err.message);
  2070. this.removeAllListeners();
  2071. };
  2072. JsonpReceiver.prototype._cleanup = function() {
  2073. debug('_cleanup');
  2074. clearTimeout(this.timeoutId);
  2075. if (this.script2) {
  2076. this.script2.parentNode.removeChild(this.script2);
  2077. this.script2 = null;
  2078. }
  2079. if (this.script) {
  2080. var script = this.script;
  2081. // Unfortunately, you can't really abort script loading of
  2082. // the script.
  2083. script.parentNode.removeChild(script);
  2084. script.onreadystatechange = script.onerror =
  2085. script.onload = script.onclick = null;
  2086. this.script = null;
  2087. }
  2088. delete global[utils.WPrefix][this.id];
  2089. };
  2090. JsonpReceiver.prototype._scriptError = function() {
  2091. debug('_scriptError');
  2092. var self = this;
  2093. if (this.errorTimer) {
  2094. return;
  2095. }
  2096. this.errorTimer = setTimeout(function() {
  2097. if (!self.loadedOkay) {
  2098. self._abort(new Error('JSONP script loaded abnormally (onerror)'));
  2099. }
  2100. }, JsonpReceiver.scriptErrorTimeout);
  2101. };
  2102. JsonpReceiver.prototype._createScript = function(url) {
  2103. debug('_createScript', url);
  2104. var self = this;
  2105. var script = this.script = global.document.createElement('script');
  2106. var script2; // Opera synchronous load trick.
  2107. script.id = 'a' + random.string(8);
  2108. script.src = url;
  2109. script.type = 'text/javascript';
  2110. script.charset = 'UTF-8';
  2111. script.onerror = this._scriptError.bind(this);
  2112. script.onload = function() {
  2113. debug('onload');
  2114. self._abort(new Error('JSONP script loaded abnormally (onload)'));
  2115. };
  2116. // IE9 fires 'error' event after onreadystatechange or before, in random order.
  2117. // Use loadedOkay to determine if actually errored
  2118. script.onreadystatechange = function() {
  2119. debug('onreadystatechange', script.readyState);
  2120. if (/loaded|closed/.test(script.readyState)) {
  2121. if (script && script.htmlFor && script.onclick) {
  2122. self.loadedOkay = true;
  2123. try {
  2124. // In IE, actually execute the script.
  2125. script.onclick();
  2126. } catch (x) {
  2127. // intentionally empty
  2128. }
  2129. }
  2130. if (script) {
  2131. self._abort(new Error('JSONP script loaded abnormally (onreadystatechange)'));
  2132. }
  2133. }
  2134. };
  2135. // IE: event/htmlFor/onclick trick.
  2136. // One can't rely on proper order for onreadystatechange. In order to
  2137. // make sure, set a 'htmlFor' and 'event' properties, so that
  2138. // script code will be installed as 'onclick' handler for the
  2139. // script object. Later, onreadystatechange, manually execute this
  2140. // code. FF and Chrome doesn't work with 'event' and 'htmlFor'
  2141. // set. For reference see:
  2142. // http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
  2143. // Also, read on that about script ordering:
  2144. // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
  2145. if (typeof script.async === 'undefined' && global.document.attachEvent) {
  2146. // According to mozilla docs, in recent browsers script.async defaults
  2147. // to 'true', so we may use it to detect a good browser:
  2148. // https://developer.mozilla.org/en/HTML/Element/script
  2149. if (!browser.isOpera()) {
  2150. // Naively assume we're in IE
  2151. try {
  2152. script.htmlFor = script.id;
  2153. script.event = 'onclick';
  2154. } catch (x) {
  2155. // intentionally empty
  2156. }
  2157. script.async = true;
  2158. } else {
  2159. // Opera, second sync script hack
  2160. script2 = this.script2 = global.document.createElement('script');
  2161. script2.text = "try{var a = document.getElementById('" + script.id + "'); if(a)a.onerror();}catch(x){};";
  2162. script.async = script2.async = false;
  2163. }
  2164. }
  2165. if (typeof script.async !== 'undefined') {
  2166. script.async = true;
  2167. }
  2168. var head = global.document.getElementsByTagName('head')[0];
  2169. head.insertBefore(script, head.firstChild);
  2170. if (script2) {
  2171. head.insertBefore(script2, head.firstChild);
  2172. }
  2173. };
  2174. module.exports = JsonpReceiver;
  2175. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2176. },{"../../utils/browser":44,"../../utils/iframe":47,"../../utils/random":50,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],32:[function(require,module,exports){
  2177. (function (process){
  2178. 'use strict';
  2179. var inherits = require('inherits')
  2180. , EventEmitter = require('events').EventEmitter
  2181. ;
  2182. var debug = function() {};
  2183. if (process.env.NODE_ENV !== 'production') {
  2184. debug = require('debug')('sockjs-client:receiver:xhr');
  2185. }
  2186. function XhrReceiver(url, AjaxObject) {
  2187. debug(url);
  2188. EventEmitter.call(this);
  2189. var self = this;
  2190. this.bufferPosition = 0;
  2191. this.xo = new AjaxObject('POST', url, null);
  2192. this.xo.on('chunk', this._chunkHandler.bind(this));
  2193. this.xo.once('finish', function(status, text) {
  2194. debug('finish', status, text);
  2195. self._chunkHandler(status, text);
  2196. self.xo = null;
  2197. var reason = status === 200 ? 'network' : 'permanent';
  2198. debug('close', reason);
  2199. self.emit('close', null, reason);
  2200. self._cleanup();
  2201. });
  2202. }
  2203. inherits(XhrReceiver, EventEmitter);
  2204. XhrReceiver.prototype._chunkHandler = function(status, text) {
  2205. debug('_chunkHandler', status);
  2206. if (status !== 200 || !text) {
  2207. return;
  2208. }
  2209. for (var idx = -1; ; this.bufferPosition += idx + 1) {
  2210. var buf = text.slice(this.bufferPosition);
  2211. idx = buf.indexOf('\n');
  2212. if (idx === -1) {
  2213. break;
  2214. }
  2215. var msg = buf.slice(0, idx);
  2216. if (msg) {
  2217. debug('message', msg);
  2218. this.emit('message', msg);
  2219. }
  2220. }
  2221. };
  2222. XhrReceiver.prototype._cleanup = function() {
  2223. debug('_cleanup');
  2224. this.removeAllListeners();
  2225. };
  2226. XhrReceiver.prototype.abort = function() {
  2227. debug('abort');
  2228. if (this.xo) {
  2229. this.xo.close();
  2230. debug('close');
  2231. this.emit('close', null, 'user');
  2232. this.xo = null;
  2233. }
  2234. this._cleanup();
  2235. };
  2236. module.exports = XhrReceiver;
  2237. }).call(this,{ env: {} })
  2238. },{"debug":55,"events":3,"inherits":57}],33:[function(require,module,exports){
  2239. (function (process,global){
  2240. 'use strict';
  2241. var random = require('../../utils/random')
  2242. , urlUtils = require('../../utils/url')
  2243. ;
  2244. var debug = function() {};
  2245. if (process.env.NODE_ENV !== 'production') {
  2246. debug = require('debug')('sockjs-client:sender:jsonp');
  2247. }
  2248. var form, area;
  2249. function createIframe(id) {
  2250. debug('createIframe', id);
  2251. try {
  2252. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  2253. return global.document.createElement('<iframe name="' + id + '">');
  2254. } catch (x) {
  2255. var iframe = global.document.createElement('iframe');
  2256. iframe.name = id;
  2257. return iframe;
  2258. }
  2259. }
  2260. function createForm() {
  2261. debug('createForm');
  2262. form = global.document.createElement('form');
  2263. form.style.display = 'none';
  2264. form.style.position = 'absolute';
  2265. form.method = 'POST';
  2266. form.enctype = 'application/x-www-form-urlencoded';
  2267. form.acceptCharset = 'UTF-8';
  2268. area = global.document.createElement('textarea');
  2269. area.name = 'd';
  2270. form.appendChild(area);
  2271. global.document.body.appendChild(form);
  2272. }
  2273. module.exports = function(url, payload, callback) {
  2274. debug(url, payload);
  2275. if (!form) {
  2276. createForm();
  2277. }
  2278. var id = 'a' + random.string(8);
  2279. form.target = id;
  2280. form.action = urlUtils.addQuery(urlUtils.addPath(url, '/jsonp_send'), 'i=' + id);
  2281. var iframe = createIframe(id);
  2282. iframe.id = id;
  2283. iframe.style.display = 'none';
  2284. form.appendChild(iframe);
  2285. try {
  2286. area.value = payload;
  2287. } catch (e) {
  2288. // seriously broken browsers get here
  2289. }
  2290. form.submit();
  2291. var completed = function(err) {
  2292. debug('completed', id, err);
  2293. if (!iframe.onerror) {
  2294. return;
  2295. }
  2296. iframe.onreadystatechange = iframe.onerror = iframe.onload = null;
  2297. // Opera mini doesn't like if we GC iframe
  2298. // immediately, thus this timeout.
  2299. setTimeout(function() {
  2300. debug('cleaning up', id);
  2301. iframe.parentNode.removeChild(iframe);
  2302. iframe = null;
  2303. }, 500);
  2304. area.value = '';
  2305. // It is not possible to detect if the iframe succeeded or
  2306. // failed to submit our form.
  2307. callback(err);
  2308. };
  2309. iframe.onerror = function() {
  2310. debug('onerror', id);
  2311. completed();
  2312. };
  2313. iframe.onload = function() {
  2314. debug('onload', id);
  2315. completed();
  2316. };
  2317. iframe.onreadystatechange = function(e) {
  2318. debug('onreadystatechange', id, iframe.readyState, e);
  2319. if (iframe.readyState === 'complete') {
  2320. completed();
  2321. }
  2322. };
  2323. return function() {
  2324. debug('aborted', id);
  2325. completed(new Error('Aborted'));
  2326. };
  2327. };
  2328. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2329. },{"../../utils/random":50,"../../utils/url":52,"debug":55}],34:[function(require,module,exports){
  2330. (function (process,global){
  2331. 'use strict';
  2332. var EventEmitter = require('events').EventEmitter
  2333. , inherits = require('inherits')
  2334. , eventUtils = require('../../utils/event')
  2335. , browser = require('../../utils/browser')
  2336. , urlUtils = require('../../utils/url')
  2337. ;
  2338. var debug = function() {};
  2339. if (process.env.NODE_ENV !== 'production') {
  2340. debug = require('debug')('sockjs-client:sender:xdr');
  2341. }
  2342. // References:
  2343. // http://ajaxian.com/archives/100-line-ajax-wrapper
  2344. // http://msdn.microsoft.com/en-us/library/cc288060(v=VS.85).aspx
  2345. function XDRObject(method, url, payload) {
  2346. debug(method, url);
  2347. var self = this;
  2348. EventEmitter.call(this);
  2349. setTimeout(function() {
  2350. self._start(method, url, payload);
  2351. }, 0);
  2352. }
  2353. inherits(XDRObject, EventEmitter);
  2354. XDRObject.prototype._start = function(method, url, payload) {
  2355. debug('_start');
  2356. var self = this;
  2357. var xdr = new global.XDomainRequest();
  2358. // IE caches even POSTs
  2359. url = urlUtils.addQuery(url, 't=' + (+new Date()));
  2360. xdr.onerror = function() {
  2361. debug('onerror');
  2362. self._error();
  2363. };
  2364. xdr.ontimeout = function() {
  2365. debug('ontimeout');
  2366. self._error();
  2367. };
  2368. xdr.onprogress = function() {
  2369. debug('progress', xdr.responseText);
  2370. self.emit('chunk', 200, xdr.responseText);
  2371. };
  2372. xdr.onload = function() {
  2373. debug('load');
  2374. self.emit('finish', 200, xdr.responseText);
  2375. self._cleanup(false);
  2376. };
  2377. this.xdr = xdr;
  2378. this.unloadRef = eventUtils.unloadAdd(function() {
  2379. self._cleanup(true);
  2380. });
  2381. try {
  2382. // Fails with AccessDenied if port number is bogus
  2383. this.xdr.open(method, url);
  2384. if (this.timeout) {
  2385. this.xdr.timeout = this.timeout;
  2386. }
  2387. this.xdr.send(payload);
  2388. } catch (x) {
  2389. this._error();
  2390. }
  2391. };
  2392. XDRObject.prototype._error = function() {
  2393. this.emit('finish', 0, '');
  2394. this._cleanup(false);
  2395. };
  2396. XDRObject.prototype._cleanup = function(abort) {
  2397. debug('cleanup', abort);
  2398. if (!this.xdr) {
  2399. return;
  2400. }
  2401. this.removeAllListeners();
  2402. eventUtils.unloadDel(this.unloadRef);
  2403. this.xdr.ontimeout = this.xdr.onerror = this.xdr.onprogress = this.xdr.onload = null;
  2404. if (abort) {
  2405. try {
  2406. this.xdr.abort();
  2407. } catch (x) {
  2408. // intentionally empty
  2409. }
  2410. }
  2411. this.unloadRef = this.xdr = null;
  2412. };
  2413. XDRObject.prototype.close = function() {
  2414. debug('close');
  2415. this._cleanup(true);
  2416. };
  2417. // IE 8/9 if the request target uses the same scheme - #79
  2418. XDRObject.enabled = !!(global.XDomainRequest && browser.hasDomain());
  2419. module.exports = XDRObject;
  2420. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2421. },{"../../utils/browser":44,"../../utils/event":46,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],35:[function(require,module,exports){
  2422. 'use strict';
  2423. var inherits = require('inherits')
  2424. , XhrDriver = require('../driver/xhr')
  2425. ;
  2426. function XHRCorsObject(method, url, payload, opts) {
  2427. XhrDriver.call(this, method, url, payload, opts);
  2428. }
  2429. inherits(XHRCorsObject, XhrDriver);
  2430. XHRCorsObject.enabled = XhrDriver.enabled && XhrDriver.supportsCORS;
  2431. module.exports = XHRCorsObject;
  2432. },{"../driver/xhr":17,"inherits":57}],36:[function(require,module,exports){
  2433. 'use strict';
  2434. var EventEmitter = require('events').EventEmitter
  2435. , inherits = require('inherits')
  2436. ;
  2437. function XHRFake(/* method, url, payload, opts */) {
  2438. var self = this;
  2439. EventEmitter.call(this);
  2440. this.to = setTimeout(function() {
  2441. self.emit('finish', 200, '{}');
  2442. }, XHRFake.timeout);
  2443. }
  2444. inherits(XHRFake, EventEmitter);
  2445. XHRFake.prototype.close = function() {
  2446. clearTimeout(this.to);
  2447. };
  2448. XHRFake.timeout = 2000;
  2449. module.exports = XHRFake;
  2450. },{"events":3,"inherits":57}],37:[function(require,module,exports){
  2451. 'use strict';
  2452. var inherits = require('inherits')
  2453. , XhrDriver = require('../driver/xhr')
  2454. ;
  2455. function XHRLocalObject(method, url, payload /*, opts */) {
  2456. XhrDriver.call(this, method, url, payload, {
  2457. noCredentials: true
  2458. });
  2459. }
  2460. inherits(XHRLocalObject, XhrDriver);
  2461. XHRLocalObject.enabled = XhrDriver.enabled;
  2462. module.exports = XHRLocalObject;
  2463. },{"../driver/xhr":17,"inherits":57}],38:[function(require,module,exports){
  2464. (function (process){
  2465. 'use strict';
  2466. var utils = require('../utils/event')
  2467. , urlUtils = require('../utils/url')
  2468. , inherits = require('inherits')
  2469. , EventEmitter = require('events').EventEmitter
  2470. , WebsocketDriver = require('./driver/websocket')
  2471. ;
  2472. var debug = function() {};
  2473. if (process.env.NODE_ENV !== 'production') {
  2474. debug = require('debug')('sockjs-client:websocket');
  2475. }
  2476. function WebSocketTransport(transUrl, ignore, options) {
  2477. if (!WebSocketTransport.enabled()) {
  2478. throw new Error('Transport created when disabled');
  2479. }
  2480. EventEmitter.call(this);
  2481. debug('constructor', transUrl);
  2482. var self = this;
  2483. var url = urlUtils.addPath(transUrl, '/websocket');
  2484. if (url.slice(0, 5) === 'https') {
  2485. url = 'wss' + url.slice(5);
  2486. } else {
  2487. url = 'ws' + url.slice(4);
  2488. }
  2489. this.url = url;
  2490. this.ws = new WebsocketDriver(this.url, [], options);
  2491. this.ws.onmessage = function(e) {
  2492. debug('message event', e.data);
  2493. self.emit('message', e.data);
  2494. };
  2495. // Firefox has an interesting bug. If a websocket connection is
  2496. // created after onunload, it stays alive even when user
  2497. // navigates away from the page. In such situation let's lie -
  2498. // let's not open the ws connection at all. See:
  2499. // https://github.com/sockjs/sockjs-client/issues/28
  2500. // https://bugzilla.mozilla.org/show_bug.cgi?id=696085
  2501. this.unloadRef = utils.unloadAdd(function() {
  2502. debug('unload');
  2503. self.ws.close();
  2504. });
  2505. this.ws.onclose = function(e) {
  2506. debug('close event', e.code, e.reason);
  2507. self.emit('close', e.code, e.reason);
  2508. self._cleanup();
  2509. };
  2510. this.ws.onerror = function(e) {
  2511. debug('error event', e);
  2512. self.emit('close', 1006, 'WebSocket connection broken');
  2513. self._cleanup();
  2514. };
  2515. }
  2516. inherits(WebSocketTransport, EventEmitter);
  2517. WebSocketTransport.prototype.send = function(data) {
  2518. var msg = '[' + data + ']';
  2519. debug('send', msg);
  2520. this.ws.send(msg);
  2521. };
  2522. WebSocketTransport.prototype.close = function() {
  2523. debug('close');
  2524. var ws = this.ws;
  2525. this._cleanup();
  2526. if (ws) {
  2527. ws.close();
  2528. }
  2529. };
  2530. WebSocketTransport.prototype._cleanup = function() {
  2531. debug('_cleanup');
  2532. var ws = this.ws;
  2533. if (ws) {
  2534. ws.onmessage = ws.onclose = ws.onerror = null;
  2535. }
  2536. utils.unloadDel(this.unloadRef);
  2537. this.unloadRef = this.ws = null;
  2538. this.removeAllListeners();
  2539. };
  2540. WebSocketTransport.enabled = function() {
  2541. debug('enabled');
  2542. return !!WebsocketDriver;
  2543. };
  2544. WebSocketTransport.transportName = 'websocket';
  2545. // In theory, ws should require 1 round trip. But in chrome, this is
  2546. // not very stable over SSL. Most likely a ws connection requires a
  2547. // separate SSL connection, in which case 2 round trips are an
  2548. // absolute minumum.
  2549. WebSocketTransport.roundTrips = 2;
  2550. module.exports = WebSocketTransport;
  2551. }).call(this,{ env: {} })
  2552. },{"../utils/event":46,"../utils/url":52,"./driver/websocket":19,"debug":55,"events":3,"inherits":57}],39:[function(require,module,exports){
  2553. 'use strict';
  2554. var inherits = require('inherits')
  2555. , AjaxBasedTransport = require('./lib/ajax-based')
  2556. , XdrStreamingTransport = require('./xdr-streaming')
  2557. , XhrReceiver = require('./receiver/xhr')
  2558. , XDRObject = require('./sender/xdr')
  2559. ;
  2560. function XdrPollingTransport(transUrl) {
  2561. if (!XDRObject.enabled) {
  2562. throw new Error('Transport created when disabled');
  2563. }
  2564. AjaxBasedTransport.call(this, transUrl, '/xhr', XhrReceiver, XDRObject);
  2565. }
  2566. inherits(XdrPollingTransport, AjaxBasedTransport);
  2567. XdrPollingTransport.enabled = XdrStreamingTransport.enabled;
  2568. XdrPollingTransport.transportName = 'xdr-polling';
  2569. XdrPollingTransport.roundTrips = 2; // preflight, ajax
  2570. module.exports = XdrPollingTransport;
  2571. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xdr":34,"./xdr-streaming":40,"inherits":57}],40:[function(require,module,exports){
  2572. 'use strict';
  2573. var inherits = require('inherits')
  2574. , AjaxBasedTransport = require('./lib/ajax-based')
  2575. , XhrReceiver = require('./receiver/xhr')
  2576. , XDRObject = require('./sender/xdr')
  2577. ;
  2578. // According to:
  2579. // http://stackoverflow.com/questions/1641507/detect-browser-support-for-cross-domain-xmlhttprequests
  2580. // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
  2581. function XdrStreamingTransport(transUrl) {
  2582. if (!XDRObject.enabled) {
  2583. throw new Error('Transport created when disabled');
  2584. }
  2585. AjaxBasedTransport.call(this, transUrl, '/xhr_streaming', XhrReceiver, XDRObject);
  2586. }
  2587. inherits(XdrStreamingTransport, AjaxBasedTransport);
  2588. XdrStreamingTransport.enabled = function(info) {
  2589. if (info.cookie_needed || info.nullOrigin) {
  2590. return false;
  2591. }
  2592. return XDRObject.enabled && info.sameScheme;
  2593. };
  2594. XdrStreamingTransport.transportName = 'xdr-streaming';
  2595. XdrStreamingTransport.roundTrips = 2; // preflight, ajax
  2596. module.exports = XdrStreamingTransport;
  2597. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xdr":34,"inherits":57}],41:[function(require,module,exports){
  2598. 'use strict';
  2599. var inherits = require('inherits')
  2600. , AjaxBasedTransport = require('./lib/ajax-based')
  2601. , XhrReceiver = require('./receiver/xhr')
  2602. , XHRCorsObject = require('./sender/xhr-cors')
  2603. , XHRLocalObject = require('./sender/xhr-local')
  2604. ;
  2605. function XhrPollingTransport(transUrl) {
  2606. if (!XHRLocalObject.enabled && !XHRCorsObject.enabled) {
  2607. throw new Error('Transport created when disabled');
  2608. }
  2609. AjaxBasedTransport.call(this, transUrl, '/xhr', XhrReceiver, XHRCorsObject);
  2610. }
  2611. inherits(XhrPollingTransport, AjaxBasedTransport);
  2612. XhrPollingTransport.enabled = function(info) {
  2613. if (info.nullOrigin) {
  2614. return false;
  2615. }
  2616. if (XHRLocalObject.enabled && info.sameOrigin) {
  2617. return true;
  2618. }
  2619. return XHRCorsObject.enabled;
  2620. };
  2621. XhrPollingTransport.transportName = 'xhr-polling';
  2622. XhrPollingTransport.roundTrips = 2; // preflight, ajax
  2623. module.exports = XhrPollingTransport;
  2624. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xhr-cors":35,"./sender/xhr-local":37,"inherits":57}],42:[function(require,module,exports){
  2625. (function (global){
  2626. 'use strict';
  2627. var inherits = require('inherits')
  2628. , AjaxBasedTransport = require('./lib/ajax-based')
  2629. , XhrReceiver = require('./receiver/xhr')
  2630. , XHRCorsObject = require('./sender/xhr-cors')
  2631. , XHRLocalObject = require('./sender/xhr-local')
  2632. , browser = require('../utils/browser')
  2633. ;
  2634. function XhrStreamingTransport(transUrl) {
  2635. if (!XHRLocalObject.enabled && !XHRCorsObject.enabled) {
  2636. throw new Error('Transport created when disabled');
  2637. }
  2638. AjaxBasedTransport.call(this, transUrl, '/xhr_streaming', XhrReceiver, XHRCorsObject);
  2639. }
  2640. inherits(XhrStreamingTransport, AjaxBasedTransport);
  2641. XhrStreamingTransport.enabled = function(info) {
  2642. if (info.nullOrigin) {
  2643. return false;
  2644. }
  2645. // Opera doesn't support xhr-streaming #60
  2646. // But it might be able to #92
  2647. if (browser.isOpera()) {
  2648. return false;
  2649. }
  2650. return XHRCorsObject.enabled;
  2651. };
  2652. XhrStreamingTransport.transportName = 'xhr-streaming';
  2653. XhrStreamingTransport.roundTrips = 2; // preflight, ajax
  2654. // Safari gets confused when a streaming ajax request is started
  2655. // before onload. This causes the load indicator to spin indefinetely.
  2656. // Only require body when used in a browser
  2657. XhrStreamingTransport.needBody = !!global.document;
  2658. module.exports = XhrStreamingTransport;
  2659. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2660. },{"../utils/browser":44,"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xhr-cors":35,"./sender/xhr-local":37,"inherits":57}],43:[function(require,module,exports){
  2661. (function (global){
  2662. 'use strict';
  2663. if (global.crypto && global.crypto.getRandomValues) {
  2664. module.exports.randomBytes = function(length) {
  2665. var bytes = new Uint8Array(length);
  2666. global.crypto.getRandomValues(bytes);
  2667. return bytes;
  2668. };
  2669. } else {
  2670. module.exports.randomBytes = function(length) {
  2671. var bytes = new Array(length);
  2672. for (var i = 0; i < length; i++) {
  2673. bytes[i] = Math.floor(Math.random() * 256);
  2674. }
  2675. return bytes;
  2676. };
  2677. }
  2678. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2679. },{}],44:[function(require,module,exports){
  2680. (function (global){
  2681. 'use strict';
  2682. module.exports = {
  2683. isOpera: function() {
  2684. return global.navigator &&
  2685. /opera/i.test(global.navigator.userAgent);
  2686. }
  2687. , isKonqueror: function() {
  2688. return global.navigator &&
  2689. /konqueror/i.test(global.navigator.userAgent);
  2690. }
  2691. // #187 wrap document.domain in try/catch because of WP8 from file:///
  2692. , hasDomain: function () {
  2693. // non-browser client always has a domain
  2694. if (!global.document) {
  2695. return true;
  2696. }
  2697. try {
  2698. return !!global.document.domain;
  2699. } catch (e) {
  2700. return false;
  2701. }
  2702. }
  2703. };
  2704. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2705. },{}],45:[function(require,module,exports){
  2706. 'use strict';
  2707. var JSON3 = require('json3');
  2708. // Some extra characters that Chrome gets wrong, and substitutes with
  2709. // something else on the wire.
  2710. // eslint-disable-next-line no-control-regex
  2711. var extraEscapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g
  2712. , extraLookup;
  2713. // This may be quite slow, so let's delay until user actually uses bad
  2714. // characters.
  2715. var unrollLookup = function(escapable) {
  2716. var i;
  2717. var unrolled = {};
  2718. var c = [];
  2719. for (i = 0; i < 65536; i++) {
  2720. c.push( String.fromCharCode(i) );
  2721. }
  2722. escapable.lastIndex = 0;
  2723. c.join('').replace(escapable, function(a) {
  2724. unrolled[ a ] = '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  2725. return '';
  2726. });
  2727. escapable.lastIndex = 0;
  2728. return unrolled;
  2729. };
  2730. // Quote string, also taking care of unicode characters that browsers
  2731. // often break. Especially, take care of unicode surrogates:
  2732. // http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates
  2733. module.exports = {
  2734. quote: function(string) {
  2735. var quoted = JSON3.stringify(string);
  2736. // In most cases this should be very fast and good enough.
  2737. extraEscapable.lastIndex = 0;
  2738. if (!extraEscapable.test(quoted)) {
  2739. return quoted;
  2740. }
  2741. if (!extraLookup) {
  2742. extraLookup = unrollLookup(extraEscapable);
  2743. }
  2744. return quoted.replace(extraEscapable, function(a) {
  2745. return extraLookup[a];
  2746. });
  2747. }
  2748. };
  2749. },{"json3":58}],46:[function(require,module,exports){
  2750. (function (global){
  2751. 'use strict';
  2752. var random = require('./random');
  2753. var onUnload = {}
  2754. , afterUnload = false
  2755. // detect google chrome packaged apps because they don't allow the 'unload' event
  2756. , isChromePackagedApp = global.chrome && global.chrome.app && global.chrome.app.runtime
  2757. ;
  2758. module.exports = {
  2759. attachEvent: function(event, listener) {
  2760. if (typeof global.addEventListener !== 'undefined') {
  2761. global.addEventListener(event, listener, false);
  2762. } else if (global.document && global.attachEvent) {
  2763. // IE quirks.
  2764. // According to: http://stevesouders.com/misc/test-postmessage.php
  2765. // the message gets delivered only to 'document', not 'window'.
  2766. global.document.attachEvent('on' + event, listener);
  2767. // I get 'window' for ie8.
  2768. global.attachEvent('on' + event, listener);
  2769. }
  2770. }
  2771. , detachEvent: function(event, listener) {
  2772. if (typeof global.addEventListener !== 'undefined') {
  2773. global.removeEventListener(event, listener, false);
  2774. } else if (global.document && global.detachEvent) {
  2775. global.document.detachEvent('on' + event, listener);
  2776. global.detachEvent('on' + event, listener);
  2777. }
  2778. }
  2779. , unloadAdd: function(listener) {
  2780. if (isChromePackagedApp) {
  2781. return null;
  2782. }
  2783. var ref = random.string(8);
  2784. onUnload[ref] = listener;
  2785. if (afterUnload) {
  2786. setTimeout(this.triggerUnloadCallbacks, 0);
  2787. }
  2788. return ref;
  2789. }
  2790. , unloadDel: function(ref) {
  2791. if (ref in onUnload) {
  2792. delete onUnload[ref];
  2793. }
  2794. }
  2795. , triggerUnloadCallbacks: function() {
  2796. for (var ref in onUnload) {
  2797. onUnload[ref]();
  2798. delete onUnload[ref];
  2799. }
  2800. }
  2801. };
  2802. var unloadTriggered = function() {
  2803. if (afterUnload) {
  2804. return;
  2805. }
  2806. afterUnload = true;
  2807. module.exports.triggerUnloadCallbacks();
  2808. };
  2809. // 'unload' alone is not reliable in opera within an iframe, but we
  2810. // can't use `beforeunload` as IE fires it on javascript: links.
  2811. if (!isChromePackagedApp) {
  2812. module.exports.attachEvent('unload', unloadTriggered);
  2813. }
  2814. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2815. },{"./random":50}],47:[function(require,module,exports){
  2816. (function (process,global){
  2817. 'use strict';
  2818. var eventUtils = require('./event')
  2819. , JSON3 = require('json3')
  2820. , browser = require('./browser')
  2821. ;
  2822. var debug = function() {};
  2823. if (process.env.NODE_ENV !== 'production') {
  2824. debug = require('debug')('sockjs-client:utils:iframe');
  2825. }
  2826. module.exports = {
  2827. WPrefix: '_jp'
  2828. , currentWindowId: null
  2829. , polluteGlobalNamespace: function() {
  2830. if (!(module.exports.WPrefix in global)) {
  2831. global[module.exports.WPrefix] = {};
  2832. }
  2833. }
  2834. , postMessage: function(type, data) {
  2835. if (global.parent !== global) {
  2836. global.parent.postMessage(JSON3.stringify({
  2837. windowId: module.exports.currentWindowId
  2838. , type: type
  2839. , data: data || ''
  2840. }), '*');
  2841. } else {
  2842. debug('Cannot postMessage, no parent window.', type, data);
  2843. }
  2844. }
  2845. , createIframe: function(iframeUrl, errorCallback) {
  2846. var iframe = global.document.createElement('iframe');
  2847. var tref, unloadRef;
  2848. var unattach = function() {
  2849. debug('unattach');
  2850. clearTimeout(tref);
  2851. // Explorer had problems with that.
  2852. try {
  2853. iframe.onload = null;
  2854. } catch (x) {
  2855. // intentionally empty
  2856. }
  2857. iframe.onerror = null;
  2858. };
  2859. var cleanup = function() {
  2860. debug('cleanup');
  2861. if (iframe) {
  2862. unattach();
  2863. // This timeout makes chrome fire onbeforeunload event
  2864. // within iframe. Without the timeout it goes straight to
  2865. // onunload.
  2866. setTimeout(function() {
  2867. if (iframe) {
  2868. iframe.parentNode.removeChild(iframe);
  2869. }
  2870. iframe = null;
  2871. }, 0);
  2872. eventUtils.unloadDel(unloadRef);
  2873. }
  2874. };
  2875. var onerror = function(err) {
  2876. debug('onerror', err);
  2877. if (iframe) {
  2878. cleanup();
  2879. errorCallback(err);
  2880. }
  2881. };
  2882. var post = function(msg, origin) {
  2883. debug('post', msg, origin);
  2884. setTimeout(function() {
  2885. try {
  2886. // When the iframe is not loaded, IE raises an exception
  2887. // on 'contentWindow'.
  2888. if (iframe && iframe.contentWindow) {
  2889. iframe.contentWindow.postMessage(msg, origin);
  2890. }
  2891. } catch (x) {
  2892. // intentionally empty
  2893. }
  2894. }, 0);
  2895. };
  2896. iframe.src = iframeUrl;
  2897. iframe.style.display = 'none';
  2898. iframe.style.position = 'absolute';
  2899. iframe.onerror = function() {
  2900. onerror('onerror');
  2901. };
  2902. iframe.onload = function() {
  2903. debug('onload');
  2904. // `onload` is triggered before scripts on the iframe are
  2905. // executed. Give it few seconds to actually load stuff.
  2906. clearTimeout(tref);
  2907. tref = setTimeout(function() {
  2908. onerror('onload timeout');
  2909. }, 2000);
  2910. };
  2911. global.document.body.appendChild(iframe);
  2912. tref = setTimeout(function() {
  2913. onerror('timeout');
  2914. }, 15000);
  2915. unloadRef = eventUtils.unloadAdd(cleanup);
  2916. return {
  2917. post: post
  2918. , cleanup: cleanup
  2919. , loaded: unattach
  2920. };
  2921. }
  2922. /* eslint no-undef: "off", new-cap: "off" */
  2923. , createHtmlfile: function(iframeUrl, errorCallback) {
  2924. var axo = ['Active'].concat('Object').join('X');
  2925. var doc = new global[axo]('htmlfile');
  2926. var tref, unloadRef;
  2927. var iframe;
  2928. var unattach = function() {
  2929. clearTimeout(tref);
  2930. iframe.onerror = null;
  2931. };
  2932. var cleanup = function() {
  2933. if (doc) {
  2934. unattach();
  2935. eventUtils.unloadDel(unloadRef);
  2936. iframe.parentNode.removeChild(iframe);
  2937. iframe = doc = null;
  2938. CollectGarbage();
  2939. }
  2940. };
  2941. var onerror = function(r) {
  2942. debug('onerror', r);
  2943. if (doc) {
  2944. cleanup();
  2945. errorCallback(r);
  2946. }
  2947. };
  2948. var post = function(msg, origin) {
  2949. try {
  2950. // When the iframe is not loaded, IE raises an exception
  2951. // on 'contentWindow'.
  2952. setTimeout(function() {
  2953. if (iframe && iframe.contentWindow) {
  2954. iframe.contentWindow.postMessage(msg, origin);
  2955. }
  2956. }, 0);
  2957. } catch (x) {
  2958. // intentionally empty
  2959. }
  2960. };
  2961. doc.open();
  2962. doc.write('<html><s' + 'cript>' +
  2963. 'document.domain="' + global.document.domain + '";' +
  2964. '</s' + 'cript></html>');
  2965. doc.close();
  2966. doc.parentWindow[module.exports.WPrefix] = global[module.exports.WPrefix];
  2967. var c = doc.createElement('div');
  2968. doc.body.appendChild(c);
  2969. iframe = doc.createElement('iframe');
  2970. c.appendChild(iframe);
  2971. iframe.src = iframeUrl;
  2972. iframe.onerror = function() {
  2973. onerror('onerror');
  2974. };
  2975. tref = setTimeout(function() {
  2976. onerror('timeout');
  2977. }, 15000);
  2978. unloadRef = eventUtils.unloadAdd(cleanup);
  2979. return {
  2980. post: post
  2981. , cleanup: cleanup
  2982. , loaded: unattach
  2983. };
  2984. }
  2985. };
  2986. module.exports.iframeEnabled = false;
  2987. if (global.document) {
  2988. // postMessage misbehaves in konqueror 4.6.5 - the messages are delivered with
  2989. // huge delay, or not at all.
  2990. module.exports.iframeEnabled = (typeof global.postMessage === 'function' ||
  2991. typeof global.postMessage === 'object') && (!browser.isKonqueror());
  2992. }
  2993. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2994. },{"./browser":44,"./event":46,"debug":55,"json3":58}],48:[function(require,module,exports){
  2995. (function (global){
  2996. 'use strict';
  2997. var logObject = {};
  2998. ['log', 'debug', 'warn'].forEach(function (level) {
  2999. var levelExists;
  3000. try {
  3001. levelExists = global.console && global.console[level] && global.console[level].apply;
  3002. } catch(e) {
  3003. // do nothing
  3004. }
  3005. logObject[level] = levelExists ? function () {
  3006. return global.console[level].apply(global.console, arguments);
  3007. } : (level === 'log' ? function () {} : logObject.log);
  3008. });
  3009. module.exports = logObject;
  3010. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3011. },{}],49:[function(require,module,exports){
  3012. 'use strict';
  3013. module.exports = {
  3014. isObject: function(obj) {
  3015. var type = typeof obj;
  3016. return type === 'function' || type === 'object' && !!obj;
  3017. }
  3018. , extend: function(obj) {
  3019. if (!this.isObject(obj)) {
  3020. return obj;
  3021. }
  3022. var source, prop;
  3023. for (var i = 1, length = arguments.length; i < length; i++) {
  3024. source = arguments[i];
  3025. for (prop in source) {
  3026. if (Object.prototype.hasOwnProperty.call(source, prop)) {
  3027. obj[prop] = source[prop];
  3028. }
  3029. }
  3030. }
  3031. return obj;
  3032. }
  3033. };
  3034. },{}],50:[function(require,module,exports){
  3035. 'use strict';
  3036. /* global crypto:true */
  3037. var crypto = require('crypto');
  3038. // This string has length 32, a power of 2, so the modulus doesn't introduce a
  3039. // bias.
  3040. var _randomStringChars = 'abcdefghijklmnopqrstuvwxyz012345';
  3041. module.exports = {
  3042. string: function(length) {
  3043. var max = _randomStringChars.length;
  3044. var bytes = crypto.randomBytes(length);
  3045. var ret = [];
  3046. for (var i = 0; i < length; i++) {
  3047. ret.push(_randomStringChars.substr(bytes[i] % max, 1));
  3048. }
  3049. return ret.join('');
  3050. }
  3051. , number: function(max) {
  3052. return Math.floor(Math.random() * max);
  3053. }
  3054. , numberString: function(max) {
  3055. var t = ('' + (max - 1)).length;
  3056. var p = new Array(t + 1).join('0');
  3057. return (p + this.number(max)).slice(-t);
  3058. }
  3059. };
  3060. },{"crypto":43}],51:[function(require,module,exports){
  3061. (function (process){
  3062. 'use strict';
  3063. var debug = function() {};
  3064. if (process.env.NODE_ENV !== 'production') {
  3065. debug = require('debug')('sockjs-client:utils:transport');
  3066. }
  3067. module.exports = function(availableTransports) {
  3068. return {
  3069. filterToEnabled: function(transportsWhitelist, info) {
  3070. var transports = {
  3071. main: []
  3072. , facade: []
  3073. };
  3074. if (!transportsWhitelist) {
  3075. transportsWhitelist = [];
  3076. } else if (typeof transportsWhitelist === 'string') {
  3077. transportsWhitelist = [transportsWhitelist];
  3078. }
  3079. availableTransports.forEach(function(trans) {
  3080. if (!trans) {
  3081. return;
  3082. }
  3083. if (trans.transportName === 'websocket' && info.websocket === false) {
  3084. debug('disabled from server', 'websocket');
  3085. return;
  3086. }
  3087. if (transportsWhitelist.length &&
  3088. transportsWhitelist.indexOf(trans.transportName) === -1) {
  3089. debug('not in whitelist', trans.transportName);
  3090. return;
  3091. }
  3092. if (trans.enabled(info)) {
  3093. debug('enabled', trans.transportName);
  3094. transports.main.push(trans);
  3095. if (trans.facadeTransport) {
  3096. transports.facade.push(trans.facadeTransport);
  3097. }
  3098. } else {
  3099. debug('disabled', trans.transportName);
  3100. }
  3101. });
  3102. return transports;
  3103. }
  3104. };
  3105. };
  3106. }).call(this,{ env: {} })
  3107. },{"debug":55}],52:[function(require,module,exports){
  3108. (function (process){
  3109. 'use strict';
  3110. var URL = require('url-parse');
  3111. var debug = function() {};
  3112. if (process.env.NODE_ENV !== 'production') {
  3113. debug = require('debug')('sockjs-client:utils:url');
  3114. }
  3115. module.exports = {
  3116. getOrigin: function(url) {
  3117. if (!url) {
  3118. return null;
  3119. }
  3120. var p = new URL(url);
  3121. if (p.protocol === 'file:') {
  3122. return null;
  3123. }
  3124. var port = p.port;
  3125. if (!port) {
  3126. port = (p.protocol === 'https:') ? '443' : '80';
  3127. }
  3128. return p.protocol + '//' + p.hostname + ':' + port;
  3129. }
  3130. , isOriginEqual: function(a, b) {
  3131. var res = this.getOrigin(a) === this.getOrigin(b);
  3132. debug('same', a, b, res);
  3133. return res;
  3134. }
  3135. , isSchemeEqual: function(a, b) {
  3136. return (a.split(':')[0] === b.split(':')[0]);
  3137. }
  3138. , addPath: function (url, path) {
  3139. var qs = url.split('?');
  3140. return qs[0] + path + (qs[1] ? '?' + qs[1] : '');
  3141. }
  3142. , addQuery: function (url, q) {
  3143. return url + (url.indexOf('?') === -1 ? ('?' + q) : ('&' + q));
  3144. }
  3145. };
  3146. }).call(this,{ env: {} })
  3147. },{"debug":55,"url-parse":61}],53:[function(require,module,exports){
  3148. module.exports = '1.4.0';
  3149. },{}],54:[function(require,module,exports){
  3150. /**
  3151. * Helpers.
  3152. */
  3153. var s = 1000;
  3154. var m = s * 60;
  3155. var h = m * 60;
  3156. var d = h * 24;
  3157. var w = d * 7;
  3158. var y = d * 365.25;
  3159. /**
  3160. * Parse or format the given `val`.
  3161. *
  3162. * Options:
  3163. *
  3164. * - `long` verbose formatting [false]
  3165. *
  3166. * @param {String|Number} val
  3167. * @param {Object} [options]
  3168. * @throws {Error} throw an error if val is not a non-empty string or a number
  3169. * @return {String|Number}
  3170. * @api public
  3171. */
  3172. module.exports = function(val, options) {
  3173. options = options || {};
  3174. var type = typeof val;
  3175. if (type === 'string' && val.length > 0) {
  3176. return parse(val);
  3177. } else if (type === 'number' && isNaN(val) === false) {
  3178. return options.long ? fmtLong(val) : fmtShort(val);
  3179. }
  3180. throw new Error(
  3181. 'val is not a non-empty string or a valid number. val=' +
  3182. JSON.stringify(val)
  3183. );
  3184. };
  3185. /**
  3186. * Parse the given `str` and return milliseconds.
  3187. *
  3188. * @param {String} str
  3189. * @return {Number}
  3190. * @api private
  3191. */
  3192. function parse(str) {
  3193. str = String(str);
  3194. if (str.length > 100) {
  3195. return;
  3196. }
  3197. var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  3198. str
  3199. );
  3200. if (!match) {
  3201. return;
  3202. }
  3203. var n = parseFloat(match[1]);
  3204. var type = (match[2] || 'ms').toLowerCase();
  3205. switch (type) {
  3206. case 'years':
  3207. case 'year':
  3208. case 'yrs':
  3209. case 'yr':
  3210. case 'y':
  3211. return n * y;
  3212. case 'weeks':
  3213. case 'week':
  3214. case 'w':
  3215. return n * w;
  3216. case 'days':
  3217. case 'day':
  3218. case 'd':
  3219. return n * d;
  3220. case 'hours':
  3221. case 'hour':
  3222. case 'hrs':
  3223. case 'hr':
  3224. case 'h':
  3225. return n * h;
  3226. case 'minutes':
  3227. case 'minute':
  3228. case 'mins':
  3229. case 'min':
  3230. case 'm':
  3231. return n * m;
  3232. case 'seconds':
  3233. case 'second':
  3234. case 'secs':
  3235. case 'sec':
  3236. case 's':
  3237. return n * s;
  3238. case 'milliseconds':
  3239. case 'millisecond':
  3240. case 'msecs':
  3241. case 'msec':
  3242. case 'ms':
  3243. return n;
  3244. default:
  3245. return undefined;
  3246. }
  3247. }
  3248. /**
  3249. * Short format for `ms`.
  3250. *
  3251. * @param {Number} ms
  3252. * @return {String}
  3253. * @api private
  3254. */
  3255. function fmtShort(ms) {
  3256. var msAbs = Math.abs(ms);
  3257. if (msAbs >= d) {
  3258. return Math.round(ms / d) + 'd';
  3259. }
  3260. if (msAbs >= h) {
  3261. return Math.round(ms / h) + 'h';
  3262. }
  3263. if (msAbs >= m) {
  3264. return Math.round(ms / m) + 'm';
  3265. }
  3266. if (msAbs >= s) {
  3267. return Math.round(ms / s) + 's';
  3268. }
  3269. return ms + 'ms';
  3270. }
  3271. /**
  3272. * Long format for `ms`.
  3273. *
  3274. * @param {Number} ms
  3275. * @return {String}
  3276. * @api private
  3277. */
  3278. function fmtLong(ms) {
  3279. var msAbs = Math.abs(ms);
  3280. if (msAbs >= d) {
  3281. return plural(ms, msAbs, d, 'day');
  3282. }
  3283. if (msAbs >= h) {
  3284. return plural(ms, msAbs, h, 'hour');
  3285. }
  3286. if (msAbs >= m) {
  3287. return plural(ms, msAbs, m, 'minute');
  3288. }
  3289. if (msAbs >= s) {
  3290. return plural(ms, msAbs, s, 'second');
  3291. }
  3292. return ms + ' ms';
  3293. }
  3294. /**
  3295. * Pluralization helper.
  3296. */
  3297. function plural(ms, msAbs, n, name) {
  3298. var isPlural = msAbs >= n * 1.5;
  3299. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  3300. }
  3301. },{}],55:[function(require,module,exports){
  3302. (function (process){
  3303. "use strict";
  3304. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  3305. /* eslint-env browser */
  3306. /**
  3307. * This is the web browser implementation of `debug()`.
  3308. */
  3309. exports.log = log;
  3310. exports.formatArgs = formatArgs;
  3311. exports.save = save;
  3312. exports.load = load;
  3313. exports.useColors = useColors;
  3314. exports.storage = localstorage();
  3315. /**
  3316. * Colors.
  3317. */
  3318. exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  3319. /**
  3320. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  3321. * and the Firebug extension (any Firefox version) are known
  3322. * to support "%c" CSS customizations.
  3323. *
  3324. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  3325. */
  3326. // eslint-disable-next-line complexity
  3327. function useColors() {
  3328. // NB: In an Electron preload script, document will be defined but not fully
  3329. // initialized. Since we know we're in Chrome, we'll just detect this case
  3330. // explicitly
  3331. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  3332. return true;
  3333. } // Internet Explorer and Edge do not support colors.
  3334. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  3335. return false;
  3336. } // Is webkit? http://stackoverflow.com/a/16459606/376773
  3337. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  3338. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
  3339. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
  3340. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  3341. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
  3342. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  3343. }
  3344. /**
  3345. * Colorize log arguments if enabled.
  3346. *
  3347. * @api public
  3348. */
  3349. function formatArgs(args) {
  3350. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  3351. if (!this.useColors) {
  3352. return;
  3353. }
  3354. var c = 'color: ' + this.color;
  3355. args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
  3356. // arguments passed either before or after the %c, so we need to
  3357. // figure out the correct index to insert the CSS into
  3358. var index = 0;
  3359. var lastC = 0;
  3360. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  3361. if (match === '%%') {
  3362. return;
  3363. }
  3364. index++;
  3365. if (match === '%c') {
  3366. // We only are interested in the *last* %c
  3367. // (the user may have provided their own)
  3368. lastC = index;
  3369. }
  3370. });
  3371. args.splice(lastC, 0, c);
  3372. }
  3373. /**
  3374. * Invokes `console.log()` when available.
  3375. * No-op when `console.log` is not a "function".
  3376. *
  3377. * @api public
  3378. */
  3379. function log() {
  3380. var _console;
  3381. // This hackery is required for IE8/9, where
  3382. // the `console.log` function doesn't have 'apply'
  3383. return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
  3384. }
  3385. /**
  3386. * Save `namespaces`.
  3387. *
  3388. * @param {String} namespaces
  3389. * @api private
  3390. */
  3391. function save(namespaces) {
  3392. try {
  3393. if (namespaces) {
  3394. exports.storage.setItem('debug', namespaces);
  3395. } else {
  3396. exports.storage.removeItem('debug');
  3397. }
  3398. } catch (error) {// Swallow
  3399. // XXX (@Qix-) should we be logging these?
  3400. }
  3401. }
  3402. /**
  3403. * Load `namespaces`.
  3404. *
  3405. * @return {String} returns the previously persisted debug modes
  3406. * @api private
  3407. */
  3408. function load() {
  3409. var r;
  3410. try {
  3411. r = exports.storage.getItem('debug');
  3412. } catch (error) {} // Swallow
  3413. // XXX (@Qix-) should we be logging these?
  3414. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  3415. if (!r && typeof process !== 'undefined' && 'env' in process) {
  3416. r = process.env.DEBUG;
  3417. }
  3418. return r;
  3419. }
  3420. /**
  3421. * Localstorage attempts to return the localstorage.
  3422. *
  3423. * This is necessary because safari throws
  3424. * when a user disables cookies/localstorage
  3425. * and you attempt to access it.
  3426. *
  3427. * @return {LocalStorage}
  3428. * @api private
  3429. */
  3430. function localstorage() {
  3431. try {
  3432. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  3433. // The Browser also has localStorage in the global context.
  3434. return localStorage;
  3435. } catch (error) {// Swallow
  3436. // XXX (@Qix-) should we be logging these?
  3437. }
  3438. }
  3439. module.exports = require('./common')(exports);
  3440. var formatters = module.exports.formatters;
  3441. /**
  3442. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  3443. */
  3444. formatters.j = function (v) {
  3445. try {
  3446. return JSON.stringify(v);
  3447. } catch (error) {
  3448. return '[UnexpectedJSONParseError]: ' + error.message;
  3449. }
  3450. };
  3451. }).call(this,{ env: {} })
  3452. },{"./common":56}],56:[function(require,module,exports){
  3453. "use strict";
  3454. /**
  3455. * This is the common logic for both the Node.js and web browser
  3456. * implementations of `debug()`.
  3457. */
  3458. function setup(env) {
  3459. createDebug.debug = createDebug;
  3460. createDebug.default = createDebug;
  3461. createDebug.coerce = coerce;
  3462. createDebug.disable = disable;
  3463. createDebug.enable = enable;
  3464. createDebug.enabled = enabled;
  3465. createDebug.humanize = require('ms');
  3466. Object.keys(env).forEach(function (key) {
  3467. createDebug[key] = env[key];
  3468. });
  3469. /**
  3470. * Active `debug` instances.
  3471. */
  3472. createDebug.instances = [];
  3473. /**
  3474. * The currently active debug mode names, and names to skip.
  3475. */
  3476. createDebug.names = [];
  3477. createDebug.skips = [];
  3478. /**
  3479. * Map of special "%n" handling functions, for the debug "format" argument.
  3480. *
  3481. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  3482. */
  3483. createDebug.formatters = {};
  3484. /**
  3485. * Selects a color for a debug namespace
  3486. * @param {String} namespace The namespace string for the for the debug instance to be colored
  3487. * @return {Number|String} An ANSI color code for the given namespace
  3488. * @api private
  3489. */
  3490. function selectColor(namespace) {
  3491. var hash = 0;
  3492. for (var i = 0; i < namespace.length; i++) {
  3493. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  3494. hash |= 0; // Convert to 32bit integer
  3495. }
  3496. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  3497. }
  3498. createDebug.selectColor = selectColor;
  3499. /**
  3500. * Create a debugger with the given `namespace`.
  3501. *
  3502. * @param {String} namespace
  3503. * @return {Function}
  3504. * @api public
  3505. */
  3506. function createDebug(namespace) {
  3507. var prevTime;
  3508. function debug() {
  3509. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3510. args[_key] = arguments[_key];
  3511. }
  3512. // Disabled?
  3513. if (!debug.enabled) {
  3514. return;
  3515. }
  3516. var self = debug; // Set `diff` timestamp
  3517. var curr = Number(new Date());
  3518. var ms = curr - (prevTime || curr);
  3519. self.diff = ms;
  3520. self.prev = prevTime;
  3521. self.curr = curr;
  3522. prevTime = curr;
  3523. args[0] = createDebug.coerce(args[0]);
  3524. if (typeof args[0] !== 'string') {
  3525. // Anything else let's inspect with %O
  3526. args.unshift('%O');
  3527. } // Apply any `formatters` transformations
  3528. var index = 0;
  3529. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  3530. // If we encounter an escaped % then don't increase the array index
  3531. if (match === '%%') {
  3532. return match;
  3533. }
  3534. index++;
  3535. var formatter = createDebug.formatters[format];
  3536. if (typeof formatter === 'function') {
  3537. var val = args[index];
  3538. match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
  3539. args.splice(index, 1);
  3540. index--;
  3541. }
  3542. return match;
  3543. }); // Apply env-specific formatting (colors, etc.)
  3544. createDebug.formatArgs.call(self, args);
  3545. var logFn = self.log || createDebug.log;
  3546. logFn.apply(self, args);
  3547. }
  3548. debug.namespace = namespace;
  3549. debug.enabled = createDebug.enabled(namespace);
  3550. debug.useColors = createDebug.useColors();
  3551. debug.color = selectColor(namespace);
  3552. debug.destroy = destroy;
  3553. debug.extend = extend; // Debug.formatArgs = formatArgs;
  3554. // debug.rawLog = rawLog;
  3555. // env-specific initialization logic for debug instances
  3556. if (typeof createDebug.init === 'function') {
  3557. createDebug.init(debug);
  3558. }
  3559. createDebug.instances.push(debug);
  3560. return debug;
  3561. }
  3562. function destroy() {
  3563. var index = createDebug.instances.indexOf(this);
  3564. if (index !== -1) {
  3565. createDebug.instances.splice(index, 1);
  3566. return true;
  3567. }
  3568. return false;
  3569. }
  3570. function extend(namespace, delimiter) {
  3571. return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  3572. }
  3573. /**
  3574. * Enables a debug mode by namespaces. This can include modes
  3575. * separated by a colon and wildcards.
  3576. *
  3577. * @param {String} namespaces
  3578. * @api public
  3579. */
  3580. function enable(namespaces) {
  3581. createDebug.save(namespaces);
  3582. createDebug.names = [];
  3583. createDebug.skips = [];
  3584. var i;
  3585. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  3586. var len = split.length;
  3587. for (i = 0; i < len; i++) {
  3588. if (!split[i]) {
  3589. // ignore empty strings
  3590. continue;
  3591. }
  3592. namespaces = split[i].replace(/\*/g, '.*?');
  3593. if (namespaces[0] === '-') {
  3594. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  3595. } else {
  3596. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  3597. }
  3598. }
  3599. for (i = 0; i < createDebug.instances.length; i++) {
  3600. var instance = createDebug.instances[i];
  3601. instance.enabled = createDebug.enabled(instance.namespace);
  3602. }
  3603. }
  3604. /**
  3605. * Disable debug output.
  3606. *
  3607. * @api public
  3608. */
  3609. function disable() {
  3610. createDebug.enable('');
  3611. }
  3612. /**
  3613. * Returns true if the given mode name is enabled, false otherwise.
  3614. *
  3615. * @param {String} name
  3616. * @return {Boolean}
  3617. * @api public
  3618. */
  3619. function enabled(name) {
  3620. if (name[name.length - 1] === '*') {
  3621. return true;
  3622. }
  3623. var i;
  3624. var len;
  3625. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  3626. if (createDebug.skips[i].test(name)) {
  3627. return false;
  3628. }
  3629. }
  3630. for (i = 0, len = createDebug.names.length; i < len; i++) {
  3631. if (createDebug.names[i].test(name)) {
  3632. return true;
  3633. }
  3634. }
  3635. return false;
  3636. }
  3637. /**
  3638. * Coerce `val`.
  3639. *
  3640. * @param {Mixed} val
  3641. * @return {Mixed}
  3642. * @api private
  3643. */
  3644. function coerce(val) {
  3645. if (val instanceof Error) {
  3646. return val.stack || val.message;
  3647. }
  3648. return val;
  3649. }
  3650. createDebug.enable(createDebug.load());
  3651. return createDebug;
  3652. }
  3653. module.exports = setup;
  3654. },{"ms":54}],57:[function(require,module,exports){
  3655. if (typeof Object.create === 'function') {
  3656. // implementation from standard node.js 'util' module
  3657. module.exports = function inherits(ctor, superCtor) {
  3658. ctor.super_ = superCtor
  3659. ctor.prototype = Object.create(superCtor.prototype, {
  3660. constructor: {
  3661. value: ctor,
  3662. enumerable: false,
  3663. writable: true,
  3664. configurable: true
  3665. }
  3666. });
  3667. };
  3668. } else {
  3669. // old school shim for old browsers
  3670. module.exports = function inherits(ctor, superCtor) {
  3671. ctor.super_ = superCtor
  3672. var TempCtor = function () {}
  3673. TempCtor.prototype = superCtor.prototype
  3674. ctor.prototype = new TempCtor()
  3675. ctor.prototype.constructor = ctor
  3676. }
  3677. }
  3678. },{}],58:[function(require,module,exports){
  3679. (function (global){
  3680. /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
  3681. ;(function () {
  3682. // Detect the `define` function exposed by asynchronous module loaders. The
  3683. // strict `define` check is necessary for compatibility with `r.js`.
  3684. var isLoader = typeof define === "function" && define.amd;
  3685. // A set of types used to distinguish objects from primitives.
  3686. var objectTypes = {
  3687. "function": true,
  3688. "object": true
  3689. };
  3690. // Detect the `exports` object exposed by CommonJS implementations.
  3691. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
  3692. // Use the `global` object exposed by Node (including Browserify via
  3693. // `insert-module-globals`), Narwhal, and Ringo as the default context,
  3694. // and the `window` object in browsers. Rhino exports a `global` function
  3695. // instead.
  3696. var root = objectTypes[typeof window] && window || this,
  3697. freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
  3698. if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
  3699. root = freeGlobal;
  3700. }
  3701. // Public: Initializes JSON 3 using the given `context` object, attaching the
  3702. // `stringify` and `parse` functions to the specified `exports` object.
  3703. function runInContext(context, exports) {
  3704. context || (context = root["Object"]());
  3705. exports || (exports = root["Object"]());
  3706. // Native constructor aliases.
  3707. var Number = context["Number"] || root["Number"],
  3708. String = context["String"] || root["String"],
  3709. Object = context["Object"] || root["Object"],
  3710. Date = context["Date"] || root["Date"],
  3711. SyntaxError = context["SyntaxError"] || root["SyntaxError"],
  3712. TypeError = context["TypeError"] || root["TypeError"],
  3713. Math = context["Math"] || root["Math"],
  3714. nativeJSON = context["JSON"] || root["JSON"];
  3715. // Delegate to the native `stringify` and `parse` implementations.
  3716. if (typeof nativeJSON == "object" && nativeJSON) {
  3717. exports.stringify = nativeJSON.stringify;
  3718. exports.parse = nativeJSON.parse;
  3719. }
  3720. // Convenience aliases.
  3721. var objectProto = Object.prototype,
  3722. getClass = objectProto.toString,
  3723. isProperty, forEach, undef;
  3724. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  3725. var isExtended = new Date(-3509827334573292);
  3726. try {
  3727. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  3728. // results for certain dates in Opera >= 10.53.
  3729. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  3730. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  3731. // but clips the values returned by the date methods to the range of
  3732. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  3733. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  3734. } catch (exception) {}
  3735. // Internal: Determines whether the native `JSON.stringify` and `parse`
  3736. // implementations are spec-compliant. Based on work by Ken Snyder.
  3737. function has(name) {
  3738. if (has[name] !== undef) {
  3739. // Return cached feature test result.
  3740. return has[name];
  3741. }
  3742. var isSupported;
  3743. if (name == "bug-string-char-index") {
  3744. // IE <= 7 doesn't support accessing string characters using square
  3745. // bracket notation. IE 8 only supports this for primitives.
  3746. isSupported = "a"[0] != "a";
  3747. } else if (name == "json") {
  3748. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  3749. // supported.
  3750. isSupported = has("json-stringify") && has("json-parse");
  3751. } else {
  3752. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  3753. // Test `JSON.stringify`.
  3754. if (name == "json-stringify") {
  3755. var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  3756. if (stringifySupported) {
  3757. // A test function object with a custom `toJSON` method.
  3758. (value = function () {
  3759. return 1;
  3760. }).toJSON = value;
  3761. try {
  3762. stringifySupported =
  3763. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  3764. // primitives as object literals.
  3765. stringify(0) === "0" &&
  3766. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  3767. // literals.
  3768. stringify(new Number()) === "0" &&
  3769. stringify(new String()) == '""' &&
  3770. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  3771. // does not define a canonical JSON representation (this applies to
  3772. // objects with `toJSON` properties as well, *unless* they are nested
  3773. // within an object or array).
  3774. stringify(getClass) === undef &&
  3775. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  3776. // FF 3.1b3 pass this test.
  3777. stringify(undef) === undef &&
  3778. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  3779. // respectively, if the value is omitted entirely.
  3780. stringify() === undef &&
  3781. // FF 3.1b1, 2 throw an error if the given value is not a number,
  3782. // string, array, object, Boolean, or `null` literal. This applies to
  3783. // objects with custom `toJSON` methods as well, unless they are nested
  3784. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  3785. // methods entirely.
  3786. stringify(value) === "1" &&
  3787. stringify([value]) == "[1]" &&
  3788. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  3789. // `"[null]"`.
  3790. stringify([undef]) == "[null]" &&
  3791. // YUI 3.0.0b1 fails to serialize `null` literals.
  3792. stringify(null) == "null" &&
  3793. // FF 3.1b1, 2 halts serialization if an array contains a function:
  3794. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  3795. // elides non-JSON values from objects and arrays, unless they
  3796. // define custom `toJSON` methods.
  3797. stringify([undef, getClass, null]) == "[null,null,null]" &&
  3798. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  3799. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  3800. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  3801. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  3802. stringify(null, value) === "1" &&
  3803. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  3804. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  3805. // serialize extended years.
  3806. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  3807. // The milliseconds are optional in ES 5, but required in 5.1.
  3808. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  3809. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  3810. // four-digit years instead of six-digit years. Credits: @Yaffle.
  3811. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  3812. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  3813. // values less than 1000. Credits: @Yaffle.
  3814. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  3815. } catch (exception) {
  3816. stringifySupported = false;
  3817. }
  3818. }
  3819. isSupported = stringifySupported;
  3820. }
  3821. // Test `JSON.parse`.
  3822. if (name == "json-parse") {
  3823. var parse = exports.parse;
  3824. if (typeof parse == "function") {
  3825. try {
  3826. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  3827. // Conforming implementations should also coerce the initial argument to
  3828. // a string prior to parsing.
  3829. if (parse("0") === 0 && !parse(false)) {
  3830. // Simple parsing test.
  3831. value = parse(serialized);
  3832. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  3833. if (parseSupported) {
  3834. try {
  3835. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  3836. parseSupported = !parse('"\t"');
  3837. } catch (exception) {}
  3838. if (parseSupported) {
  3839. try {
  3840. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  3841. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  3842. // certain octal literals.
  3843. parseSupported = parse("01") !== 1;
  3844. } catch (exception) {}
  3845. }
  3846. if (parseSupported) {
  3847. try {
  3848. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  3849. // points. These environments, along with FF 3.1b1 and 2,
  3850. // also allow trailing commas in JSON objects and arrays.
  3851. parseSupported = parse("1.") !== 1;
  3852. } catch (exception) {}
  3853. }
  3854. }
  3855. }
  3856. } catch (exception) {
  3857. parseSupported = false;
  3858. }
  3859. }
  3860. isSupported = parseSupported;
  3861. }
  3862. }
  3863. return has[name] = !!isSupported;
  3864. }
  3865. if (!has("json")) {
  3866. // Common `[[Class]]` name aliases.
  3867. var functionClass = "[object Function]",
  3868. dateClass = "[object Date]",
  3869. numberClass = "[object Number]",
  3870. stringClass = "[object String]",
  3871. arrayClass = "[object Array]",
  3872. booleanClass = "[object Boolean]";
  3873. // Detect incomplete support for accessing string characters by index.
  3874. var charIndexBuggy = has("bug-string-char-index");
  3875. // Define additional utility methods if the `Date` methods are buggy.
  3876. if (!isExtended) {
  3877. var floor = Math.floor;
  3878. // A mapping between the months of the year and the number of days between
  3879. // January 1st and the first of the respective month.
  3880. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  3881. // Internal: Calculates the number of days between the Unix epoch and the
  3882. // first day of the given month.
  3883. var getDay = function (year, month) {
  3884. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  3885. };
  3886. }
  3887. // Internal: Determines if a property is a direct property of the given
  3888. // object. Delegates to the native `Object#hasOwnProperty` method.
  3889. if (!(isProperty = objectProto.hasOwnProperty)) {
  3890. isProperty = function (property) {
  3891. var members = {}, constructor;
  3892. if ((members.__proto__ = null, members.__proto__ = {
  3893. // The *proto* property cannot be set multiple times in recent
  3894. // versions of Firefox and SeaMonkey.
  3895. "toString": 1
  3896. }, members).toString != getClass) {
  3897. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  3898. // supports the mutable *proto* property.
  3899. isProperty = function (property) {
  3900. // Capture and break the object's prototype chain (see section 8.6.2
  3901. // of the ES 5.1 spec). The parenthesized expression prevents an
  3902. // unsafe transformation by the Closure Compiler.
  3903. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  3904. // Restore the original prototype chain.
  3905. this.__proto__ = original;
  3906. return result;
  3907. };
  3908. } else {
  3909. // Capture a reference to the top-level `Object` constructor.
  3910. constructor = members.constructor;
  3911. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  3912. // other environments.
  3913. isProperty = function (property) {
  3914. var parent = (this.constructor || constructor).prototype;
  3915. return property in this && !(property in parent && this[property] === parent[property]);
  3916. };
  3917. }
  3918. members = null;
  3919. return isProperty.call(this, property);
  3920. };
  3921. }
  3922. // Internal: Normalizes the `for...in` iteration algorithm across
  3923. // environments. Each enumerated key is yielded to a `callback` function.
  3924. forEach = function (object, callback) {
  3925. var size = 0, Properties, members, property;
  3926. // Tests for bugs in the current environment's `for...in` algorithm. The
  3927. // `valueOf` property inherits the non-enumerable flag from
  3928. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  3929. (Properties = function () {
  3930. this.valueOf = 0;
  3931. }).prototype.valueOf = 0;
  3932. // Iterate over a new instance of the `Properties` class.
  3933. members = new Properties();
  3934. for (property in members) {
  3935. // Ignore all properties inherited from `Object.prototype`.
  3936. if (isProperty.call(members, property)) {
  3937. size++;
  3938. }
  3939. }
  3940. Properties = members = null;
  3941. // Normalize the iteration algorithm.
  3942. if (!size) {
  3943. // A list of non-enumerable properties inherited from `Object.prototype`.
  3944. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  3945. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  3946. // properties.
  3947. forEach = function (object, callback) {
  3948. var isFunction = getClass.call(object) == functionClass, property, length;
  3949. var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
  3950. for (property in object) {
  3951. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  3952. // certain conditions; IE does not.
  3953. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  3954. callback(property);
  3955. }
  3956. }
  3957. // Manually invoke the callback for each non-enumerable property.
  3958. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  3959. };
  3960. } else if (size == 2) {
  3961. // Safari <= 2.0.4 enumerates shadowed properties twice.
  3962. forEach = function (object, callback) {
  3963. // Create a set of iterated properties.
  3964. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  3965. for (property in object) {
  3966. // Store each property name to prevent double enumeration. The
  3967. // `prototype` property of functions is not enumerated due to cross-
  3968. // environment inconsistencies.
  3969. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  3970. callback(property);
  3971. }
  3972. }
  3973. };
  3974. } else {
  3975. // No bugs detected; use the standard `for...in` algorithm.
  3976. forEach = function (object, callback) {
  3977. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  3978. for (property in object) {
  3979. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  3980. callback(property);
  3981. }
  3982. }
  3983. // Manually invoke the callback for the `constructor` property due to
  3984. // cross-environment inconsistencies.
  3985. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  3986. callback(property);
  3987. }
  3988. };
  3989. }
  3990. return forEach(object, callback);
  3991. };
  3992. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  3993. // `filter` argument may specify either a function that alters how object and
  3994. // array members are serialized, or an array of strings and numbers that
  3995. // indicates which properties should be serialized. The optional `width`
  3996. // argument may be either a string or number that specifies the indentation
  3997. // level of the output.
  3998. if (!has("json-stringify")) {
  3999. // Internal: A map of control characters and their escaped equivalents.
  4000. var Escapes = {
  4001. 92: "\\\\",
  4002. 34: '\\"',
  4003. 8: "\\b",
  4004. 12: "\\f",
  4005. 10: "\\n",
  4006. 13: "\\r",
  4007. 9: "\\t"
  4008. };
  4009. // Internal: Converts `value` into a zero-padded string such that its
  4010. // length is at least equal to `width`. The `width` must be <= 6.
  4011. var leadingZeroes = "000000";
  4012. var toPaddedString = function (width, value) {
  4013. // The `|| 0` expression is necessary to work around a bug in
  4014. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  4015. return (leadingZeroes + (value || 0)).slice(-width);
  4016. };
  4017. // Internal: Double-quotes a string `value`, replacing all ASCII control
  4018. // characters (characters with code unit values between 0 and 31) with
  4019. // their escaped equivalents. This is an implementation of the
  4020. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  4021. var unicodePrefix = "\\u00";
  4022. var quote = function (value) {
  4023. var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
  4024. var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
  4025. for (; index < length; index++) {
  4026. var charCode = value.charCodeAt(index);
  4027. // If the character is a control character, append its Unicode or
  4028. // shorthand escape sequence; otherwise, append the character as-is.
  4029. switch (charCode) {
  4030. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  4031. result += Escapes[charCode];
  4032. break;
  4033. default:
  4034. if (charCode < 32) {
  4035. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  4036. break;
  4037. }
  4038. result += useCharIndex ? symbols[index] : value.charAt(index);
  4039. }
  4040. }
  4041. return result + '"';
  4042. };
  4043. // Internal: Recursively serializes an object. Implements the
  4044. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  4045. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  4046. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  4047. try {
  4048. // Necessary for host object support.
  4049. value = object[property];
  4050. } catch (exception) {}
  4051. if (typeof value == "object" && value) {
  4052. className = getClass.call(value);
  4053. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  4054. if (value > -1 / 0 && value < 1 / 0) {
  4055. // Dates are serialized according to the `Date#toJSON` method
  4056. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  4057. // for the ISO 8601 date time string format.
  4058. if (getDay) {
  4059. // Manually compute the year, month, date, hours, minutes,
  4060. // seconds, and milliseconds if the `getUTC*` methods are
  4061. // buggy. Adapted from @Yaffle's `date-shim` project.
  4062. date = floor(value / 864e5);
  4063. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  4064. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  4065. date = 1 + date - getDay(year, month);
  4066. // The `time` value specifies the time within the day (see ES
  4067. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  4068. // to compute `A modulo B`, as the `%` operator does not
  4069. // correspond to the `modulo` operation for negative numbers.
  4070. time = (value % 864e5 + 864e5) % 864e5;
  4071. // The hours, minutes, seconds, and milliseconds are obtained by
  4072. // decomposing the time within the day. See section 15.9.1.10.
  4073. hours = floor(time / 36e5) % 24;
  4074. minutes = floor(time / 6e4) % 60;
  4075. seconds = floor(time / 1e3) % 60;
  4076. milliseconds = time % 1e3;
  4077. } else {
  4078. year = value.getUTCFullYear();
  4079. month = value.getUTCMonth();
  4080. date = value.getUTCDate();
  4081. hours = value.getUTCHours();
  4082. minutes = value.getUTCMinutes();
  4083. seconds = value.getUTCSeconds();
  4084. milliseconds = value.getUTCMilliseconds();
  4085. }
  4086. // Serialize extended years correctly.
  4087. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  4088. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  4089. // Months, dates, hours, minutes, and seconds should have two
  4090. // digits; milliseconds should have three.
  4091. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  4092. // Milliseconds are optional in ES 5.0, but required in 5.1.
  4093. "." + toPaddedString(3, milliseconds) + "Z";
  4094. } else {
  4095. value = null;
  4096. }
  4097. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  4098. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  4099. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  4100. // ignores all `toJSON` methods on these objects unless they are
  4101. // defined directly on an instance.
  4102. value = value.toJSON(property);
  4103. }
  4104. }
  4105. if (callback) {
  4106. // If a replacement function was provided, call it to obtain the value
  4107. // for serialization.
  4108. value = callback.call(object, property, value);
  4109. }
  4110. if (value === null) {
  4111. return "null";
  4112. }
  4113. className = getClass.call(value);
  4114. if (className == booleanClass) {
  4115. // Booleans are represented literally.
  4116. return "" + value;
  4117. } else if (className == numberClass) {
  4118. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  4119. // `"null"`.
  4120. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  4121. } else if (className == stringClass) {
  4122. // Strings are double-quoted and escaped.
  4123. return quote("" + value);
  4124. }
  4125. // Recursively serialize objects and arrays.
  4126. if (typeof value == "object") {
  4127. // Check for cyclic structures. This is a linear search; performance
  4128. // is inversely proportional to the number of unique nested objects.
  4129. for (length = stack.length; length--;) {
  4130. if (stack[length] === value) {
  4131. // Cyclic structures cannot be serialized by `JSON.stringify`.
  4132. throw TypeError();
  4133. }
  4134. }
  4135. // Add the object to the stack of traversed objects.
  4136. stack.push(value);
  4137. results = [];
  4138. // Save the current indentation level and indent one additional level.
  4139. prefix = indentation;
  4140. indentation += whitespace;
  4141. if (className == arrayClass) {
  4142. // Recursively serialize array elements.
  4143. for (index = 0, length = value.length; index < length; index++) {
  4144. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  4145. results.push(element === undef ? "null" : element);
  4146. }
  4147. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  4148. } else {
  4149. // Recursively serialize object members. Members are selected from
  4150. // either a user-specified list of property names, or the object
  4151. // itself.
  4152. forEach(properties || value, function (property) {
  4153. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  4154. if (element !== undef) {
  4155. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  4156. // is not the empty string, let `member` {quote(property) + ":"}
  4157. // be the concatenation of `member` and the `space` character."
  4158. // The "`space` character" refers to the literal space
  4159. // character, not the `space` {width} argument provided to
  4160. // `JSON.stringify`.
  4161. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  4162. }
  4163. });
  4164. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  4165. }
  4166. // Remove the object from the traversed object stack.
  4167. stack.pop();
  4168. return result;
  4169. }
  4170. };
  4171. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  4172. exports.stringify = function (source, filter, width) {
  4173. var whitespace, callback, properties, className;
  4174. if (objectTypes[typeof filter] && filter) {
  4175. if ((className = getClass.call(filter)) == functionClass) {
  4176. callback = filter;
  4177. } else if (className == arrayClass) {
  4178. // Convert the property names array into a makeshift set.
  4179. properties = {};
  4180. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  4181. }
  4182. }
  4183. if (width) {
  4184. if ((className = getClass.call(width)) == numberClass) {
  4185. // Convert the `width` to an integer and create a string containing
  4186. // `width` number of space characters.
  4187. if ((width -= width % 1) > 0) {
  4188. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  4189. }
  4190. } else if (className == stringClass) {
  4191. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  4192. }
  4193. }
  4194. // Opera <= 7.54u2 discards the values associated with empty string keys
  4195. // (`""`) only if they are used directly within an object member list
  4196. // (e.g., `!("" in { "": 1})`).
  4197. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  4198. };
  4199. }
  4200. // Public: Parses a JSON source string.
  4201. if (!has("json-parse")) {
  4202. var fromCharCode = String.fromCharCode;
  4203. // Internal: A map of escaped control characters and their unescaped
  4204. // equivalents.
  4205. var Unescapes = {
  4206. 92: "\\",
  4207. 34: '"',
  4208. 47: "/",
  4209. 98: "\b",
  4210. 116: "\t",
  4211. 110: "\n",
  4212. 102: "\f",
  4213. 114: "\r"
  4214. };
  4215. // Internal: Stores the parser state.
  4216. var Index, Source;
  4217. // Internal: Resets the parser state and throws a `SyntaxError`.
  4218. var abort = function () {
  4219. Index = Source = null;
  4220. throw SyntaxError();
  4221. };
  4222. // Internal: Returns the next token, or `"$"` if the parser has reached
  4223. // the end of the source string. A token may be a string, number, `null`
  4224. // literal, or Boolean literal.
  4225. var lex = function () {
  4226. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  4227. while (Index < length) {
  4228. charCode = source.charCodeAt(Index);
  4229. switch (charCode) {
  4230. case 9: case 10: case 13: case 32:
  4231. // Skip whitespace tokens, including tabs, carriage returns, line
  4232. // feeds, and space characters.
  4233. Index++;
  4234. break;
  4235. case 123: case 125: case 91: case 93: case 58: case 44:
  4236. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  4237. // the current position.
  4238. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  4239. Index++;
  4240. return value;
  4241. case 34:
  4242. // `"` delimits a JSON string; advance to the next character and
  4243. // begin parsing the string. String tokens are prefixed with the
  4244. // sentinel `@` character to distinguish them from punctuators and
  4245. // end-of-string tokens.
  4246. for (value = "@", Index++; Index < length;) {
  4247. charCode = source.charCodeAt(Index);
  4248. if (charCode < 32) {
  4249. // Unescaped ASCII control characters (those with a code unit
  4250. // less than the space character) are not permitted.
  4251. abort();
  4252. } else if (charCode == 92) {
  4253. // A reverse solidus (`\`) marks the beginning of an escaped
  4254. // control character (including `"`, `\`, and `/`) or Unicode
  4255. // escape sequence.
  4256. charCode = source.charCodeAt(++Index);
  4257. switch (charCode) {
  4258. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  4259. // Revive escaped control characters.
  4260. value += Unescapes[charCode];
  4261. Index++;
  4262. break;
  4263. case 117:
  4264. // `\u` marks the beginning of a Unicode escape sequence.
  4265. // Advance to the first character and validate the
  4266. // four-digit code point.
  4267. begin = ++Index;
  4268. for (position = Index + 4; Index < position; Index++) {
  4269. charCode = source.charCodeAt(Index);
  4270. // A valid sequence comprises four hexdigits (case-
  4271. // insensitive) that form a single hexadecimal value.
  4272. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  4273. // Invalid Unicode escape sequence.
  4274. abort();
  4275. }
  4276. }
  4277. // Revive the escaped character.
  4278. value += fromCharCode("0x" + source.slice(begin, Index));
  4279. break;
  4280. default:
  4281. // Invalid escape sequence.
  4282. abort();
  4283. }
  4284. } else {
  4285. if (charCode == 34) {
  4286. // An unescaped double-quote character marks the end of the
  4287. // string.
  4288. break;
  4289. }
  4290. charCode = source.charCodeAt(Index);
  4291. begin = Index;
  4292. // Optimize for the common case where a string is valid.
  4293. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  4294. charCode = source.charCodeAt(++Index);
  4295. }
  4296. // Append the string as-is.
  4297. value += source.slice(begin, Index);
  4298. }
  4299. }
  4300. if (source.charCodeAt(Index) == 34) {
  4301. // Advance to the next character and return the revived string.
  4302. Index++;
  4303. return value;
  4304. }
  4305. // Unterminated string.
  4306. abort();
  4307. default:
  4308. // Parse numbers and literals.
  4309. begin = Index;
  4310. // Advance past the negative sign, if one is specified.
  4311. if (charCode == 45) {
  4312. isSigned = true;
  4313. charCode = source.charCodeAt(++Index);
  4314. }
  4315. // Parse an integer or floating-point value.
  4316. if (charCode >= 48 && charCode <= 57) {
  4317. // Leading zeroes are interpreted as octal literals.
  4318. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  4319. // Illegal octal literal.
  4320. abort();
  4321. }
  4322. isSigned = false;
  4323. // Parse the integer component.
  4324. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  4325. // Floats cannot contain a leading decimal point; however, this
  4326. // case is already accounted for by the parser.
  4327. if (source.charCodeAt(Index) == 46) {
  4328. position = ++Index;
  4329. // Parse the decimal component.
  4330. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  4331. if (position == Index) {
  4332. // Illegal trailing decimal.
  4333. abort();
  4334. }
  4335. Index = position;
  4336. }
  4337. // Parse exponents. The `e` denoting the exponent is
  4338. // case-insensitive.
  4339. charCode = source.charCodeAt(Index);
  4340. if (charCode == 101 || charCode == 69) {
  4341. charCode = source.charCodeAt(++Index);
  4342. // Skip past the sign following the exponent, if one is
  4343. // specified.
  4344. if (charCode == 43 || charCode == 45) {
  4345. Index++;
  4346. }
  4347. // Parse the exponential component.
  4348. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  4349. if (position == Index) {
  4350. // Illegal empty exponent.
  4351. abort();
  4352. }
  4353. Index = position;
  4354. }
  4355. // Coerce the parsed value to a JavaScript number.
  4356. return +source.slice(begin, Index);
  4357. }
  4358. // A negative sign may only precede numbers.
  4359. if (isSigned) {
  4360. abort();
  4361. }
  4362. // `true`, `false`, and `null` literals.
  4363. if (source.slice(Index, Index + 4) == "true") {
  4364. Index += 4;
  4365. return true;
  4366. } else if (source.slice(Index, Index + 5) == "false") {
  4367. Index += 5;
  4368. return false;
  4369. } else if (source.slice(Index, Index + 4) == "null") {
  4370. Index += 4;
  4371. return null;
  4372. }
  4373. // Unrecognized token.
  4374. abort();
  4375. }
  4376. }
  4377. // Return the sentinel `$` character if the parser has reached the end
  4378. // of the source string.
  4379. return "$";
  4380. };
  4381. // Internal: Parses a JSON `value` token.
  4382. var get = function (value) {
  4383. var results, hasMembers;
  4384. if (value == "$") {
  4385. // Unexpected end of input.
  4386. abort();
  4387. }
  4388. if (typeof value == "string") {
  4389. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  4390. // Remove the sentinel `@` character.
  4391. return value.slice(1);
  4392. }
  4393. // Parse object and array literals.
  4394. if (value == "[") {
  4395. // Parses a JSON array, returning a new JavaScript array.
  4396. results = [];
  4397. for (;; hasMembers || (hasMembers = true)) {
  4398. value = lex();
  4399. // A closing square bracket marks the end of the array literal.
  4400. if (value == "]") {
  4401. break;
  4402. }
  4403. // If the array literal contains elements, the current token
  4404. // should be a comma separating the previous element from the
  4405. // next.
  4406. if (hasMembers) {
  4407. if (value == ",") {
  4408. value = lex();
  4409. if (value == "]") {
  4410. // Unexpected trailing `,` in array literal.
  4411. abort();
  4412. }
  4413. } else {
  4414. // A `,` must separate each array element.
  4415. abort();
  4416. }
  4417. }
  4418. // Elisions and leading commas are not permitted.
  4419. if (value == ",") {
  4420. abort();
  4421. }
  4422. results.push(get(value));
  4423. }
  4424. return results;
  4425. } else if (value == "{") {
  4426. // Parses a JSON object, returning a new JavaScript object.
  4427. results = {};
  4428. for (;; hasMembers || (hasMembers = true)) {
  4429. value = lex();
  4430. // A closing curly brace marks the end of the object literal.
  4431. if (value == "}") {
  4432. break;
  4433. }
  4434. // If the object literal contains members, the current token
  4435. // should be a comma separator.
  4436. if (hasMembers) {
  4437. if (value == ",") {
  4438. value = lex();
  4439. if (value == "}") {
  4440. // Unexpected trailing `,` in object literal.
  4441. abort();
  4442. }
  4443. } else {
  4444. // A `,` must separate each object member.
  4445. abort();
  4446. }
  4447. }
  4448. // Leading commas are not permitted, object property names must be
  4449. // double-quoted strings, and a `:` must separate each property
  4450. // name and value.
  4451. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  4452. abort();
  4453. }
  4454. results[value.slice(1)] = get(lex());
  4455. }
  4456. return results;
  4457. }
  4458. // Unexpected token encountered.
  4459. abort();
  4460. }
  4461. return value;
  4462. };
  4463. // Internal: Updates a traversed object member.
  4464. var update = function (source, property, callback) {
  4465. var element = walk(source, property, callback);
  4466. if (element === undef) {
  4467. delete source[property];
  4468. } else {
  4469. source[property] = element;
  4470. }
  4471. };
  4472. // Internal: Recursively traverses a parsed JSON object, invoking the
  4473. // `callback` function for each value. This is an implementation of the
  4474. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  4475. var walk = function (source, property, callback) {
  4476. var value = source[property], length;
  4477. if (typeof value == "object" && value) {
  4478. // `forEach` can't be used to traverse an array in Opera <= 8.54
  4479. // because its `Object#hasOwnProperty` implementation returns `false`
  4480. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  4481. if (getClass.call(value) == arrayClass) {
  4482. for (length = value.length; length--;) {
  4483. update(value, length, callback);
  4484. }
  4485. } else {
  4486. forEach(value, function (property) {
  4487. update(value, property, callback);
  4488. });
  4489. }
  4490. }
  4491. return callback.call(source, property, value);
  4492. };
  4493. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  4494. exports.parse = function (source, callback) {
  4495. var result, value;
  4496. Index = 0;
  4497. Source = "" + source;
  4498. result = get(lex());
  4499. // If a JSON string contains multiple tokens, it is invalid.
  4500. if (lex() != "$") {
  4501. abort();
  4502. }
  4503. // Reset the parser state.
  4504. Index = Source = null;
  4505. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  4506. };
  4507. }
  4508. }
  4509. exports["runInContext"] = runInContext;
  4510. return exports;
  4511. }
  4512. if (freeExports && !isLoader) {
  4513. // Export for CommonJS environments.
  4514. runInContext(root, freeExports);
  4515. } else {
  4516. // Export for web browsers and JavaScript engines.
  4517. var nativeJSON = root.JSON,
  4518. previousJSON = root["JSON3"],
  4519. isRestored = false;
  4520. var JSON3 = runInContext(root, (root["JSON3"] = {
  4521. // Public: Restores the original value of the global `JSON` object and
  4522. // returns a reference to the `JSON3` object.
  4523. "noConflict": function () {
  4524. if (!isRestored) {
  4525. isRestored = true;
  4526. root.JSON = nativeJSON;
  4527. root["JSON3"] = previousJSON;
  4528. nativeJSON = previousJSON = null;
  4529. }
  4530. return JSON3;
  4531. }
  4532. }));
  4533. root.JSON = {
  4534. "parse": JSON3.parse,
  4535. "stringify": JSON3.stringify
  4536. };
  4537. }
  4538. // Export for asynchronous module loaders.
  4539. if (isLoader) {
  4540. define(function () {
  4541. return JSON3;
  4542. });
  4543. }
  4544. }).call(this);
  4545. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4546. },{}],59:[function(require,module,exports){
  4547. 'use strict';
  4548. var has = Object.prototype.hasOwnProperty;
  4549. /**
  4550. * Decode a URI encoded string.
  4551. *
  4552. * @param {String} input The URI encoded string.
  4553. * @returns {String} The decoded string.
  4554. * @api private
  4555. */
  4556. function decode(input) {
  4557. return decodeURIComponent(input.replace(/\+/g, ' '));
  4558. }
  4559. /**
  4560. * Simple query string parser.
  4561. *
  4562. * @param {String} query The query string that needs to be parsed.
  4563. * @returns {Object}
  4564. * @api public
  4565. */
  4566. function querystring(query) {
  4567. var parser = /([^=?&]+)=?([^&]*)/g
  4568. , result = {}
  4569. , part;
  4570. while (part = parser.exec(query)) {
  4571. var key = decode(part[1])
  4572. , value = decode(part[2]);
  4573. //
  4574. // Prevent overriding of existing properties. This ensures that build-in
  4575. // methods like `toString` or __proto__ are not overriden by malicious
  4576. // querystrings.
  4577. //
  4578. if (key in result) continue;
  4579. result[key] = value;
  4580. }
  4581. return result;
  4582. }
  4583. /**
  4584. * Transform a query string to an object.
  4585. *
  4586. * @param {Object} obj Object that should be transformed.
  4587. * @param {String} prefix Optional prefix.
  4588. * @returns {String}
  4589. * @api public
  4590. */
  4591. function querystringify(obj, prefix) {
  4592. prefix = prefix || '';
  4593. var pairs = [];
  4594. //
  4595. // Optionally prefix with a '?' if needed
  4596. //
  4597. if ('string' !== typeof prefix) prefix = '?';
  4598. for (var key in obj) {
  4599. if (has.call(obj, key)) {
  4600. pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
  4601. }
  4602. }
  4603. return pairs.length ? prefix + pairs.join('&') : '';
  4604. }
  4605. //
  4606. // Expose the module.
  4607. //
  4608. exports.stringify = querystringify;
  4609. exports.parse = querystring;
  4610. },{}],60:[function(require,module,exports){
  4611. 'use strict';
  4612. /**
  4613. * Check if we're required to add a port number.
  4614. *
  4615. * @see https://url.spec.whatwg.org/#default-port
  4616. * @param {Number|String} port Port number we need to check
  4617. * @param {String} protocol Protocol we need to check against.
  4618. * @returns {Boolean} Is it a default port for the given protocol
  4619. * @api private
  4620. */
  4621. module.exports = function required(port, protocol) {
  4622. protocol = protocol.split(':')[0];
  4623. port = +port;
  4624. if (!port) return false;
  4625. switch (protocol) {
  4626. case 'http':
  4627. case 'ws':
  4628. return port !== 80;
  4629. case 'https':
  4630. case 'wss':
  4631. return port !== 443;
  4632. case 'ftp':
  4633. return port !== 21;
  4634. case 'gopher':
  4635. return port !== 70;
  4636. case 'file':
  4637. return false;
  4638. }
  4639. return port !== 0;
  4640. };
  4641. },{}],61:[function(require,module,exports){
  4642. (function (global){
  4643. 'use strict';
  4644. var required = require('requires-port')
  4645. , qs = require('querystringify')
  4646. , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i
  4647. , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//;
  4648. /**
  4649. * These are the parse rules for the URL parser, it informs the parser
  4650. * about:
  4651. *
  4652. * 0. The char it Needs to parse, if it's a string it should be done using
  4653. * indexOf, RegExp using exec and NaN means set as current value.
  4654. * 1. The property we should set when parsing this value.
  4655. * 2. Indication if it's backwards or forward parsing, when set as number it's
  4656. * the value of extra chars that should be split off.
  4657. * 3. Inherit from location if non existing in the parser.
  4658. * 4. `toLowerCase` the resulting value.
  4659. */
  4660. var rules = [
  4661. ['#', 'hash'], // Extract from the back.
  4662. ['?', 'query'], // Extract from the back.
  4663. function sanitize(address) { // Sanitize what is left of the address
  4664. return address.replace('\\', '/');
  4665. },
  4666. ['/', 'pathname'], // Extract from the back.
  4667. ['@', 'auth', 1], // Extract from the front.
  4668. [NaN, 'host', undefined, 1, 1], // Set left over value.
  4669. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back.
  4670. [NaN, 'hostname', undefined, 1, 1] // Set left over.
  4671. ];
  4672. /**
  4673. * These properties should not be copied or inherited from. This is only needed
  4674. * for all non blob URL's as a blob URL does not include a hash, only the
  4675. * origin.
  4676. *
  4677. * @type {Object}
  4678. * @private
  4679. */
  4680. var ignore = { hash: 1, query: 1 };
  4681. /**
  4682. * The location object differs when your code is loaded through a normal page,
  4683. * Worker or through a worker using a blob. And with the blobble begins the
  4684. * trouble as the location object will contain the URL of the blob, not the
  4685. * location of the page where our code is loaded in. The actual origin is
  4686. * encoded in the `pathname` so we can thankfully generate a good "default"
  4687. * location from it so we can generate proper relative URL's again.
  4688. *
  4689. * @param {Object|String} loc Optional default location object.
  4690. * @returns {Object} lolcation object.
  4691. * @public
  4692. */
  4693. function lolcation(loc) {
  4694. var location = global && global.location || {};
  4695. loc = loc || location;
  4696. var finaldestination = {}
  4697. , type = typeof loc
  4698. , key;
  4699. if ('blob:' === loc.protocol) {
  4700. finaldestination = new Url(unescape(loc.pathname), {});
  4701. } else if ('string' === type) {
  4702. finaldestination = new Url(loc, {});
  4703. for (key in ignore) delete finaldestination[key];
  4704. } else if ('object' === type) {
  4705. for (key in loc) {
  4706. if (key in ignore) continue;
  4707. finaldestination[key] = loc[key];
  4708. }
  4709. if (finaldestination.slashes === undefined) {
  4710. finaldestination.slashes = slashes.test(loc.href);
  4711. }
  4712. }
  4713. return finaldestination;
  4714. }
  4715. /**
  4716. * @typedef ProtocolExtract
  4717. * @type Object
  4718. * @property {String} protocol Protocol matched in the URL, in lowercase.
  4719. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
  4720. * @property {String} rest Rest of the URL that is not part of the protocol.
  4721. */
  4722. /**
  4723. * Extract protocol information from a URL with/without double slash ("//").
  4724. *
  4725. * @param {String} address URL we want to extract from.
  4726. * @return {ProtocolExtract} Extracted information.
  4727. * @private
  4728. */
  4729. function extractProtocol(address) {
  4730. var match = protocolre.exec(address);
  4731. return {
  4732. protocol: match[1] ? match[1].toLowerCase() : '',
  4733. slashes: !!match[2],
  4734. rest: match[3]
  4735. };
  4736. }
  4737. /**
  4738. * Resolve a relative URL pathname against a base URL pathname.
  4739. *
  4740. * @param {String} relative Pathname of the relative URL.
  4741. * @param {String} base Pathname of the base URL.
  4742. * @return {String} Resolved pathname.
  4743. * @private
  4744. */
  4745. function resolve(relative, base) {
  4746. var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
  4747. , i = path.length
  4748. , last = path[i - 1]
  4749. , unshift = false
  4750. , up = 0;
  4751. while (i--) {
  4752. if (path[i] === '.') {
  4753. path.splice(i, 1);
  4754. } else if (path[i] === '..') {
  4755. path.splice(i, 1);
  4756. up++;
  4757. } else if (up) {
  4758. if (i === 0) unshift = true;
  4759. path.splice(i, 1);
  4760. up--;
  4761. }
  4762. }
  4763. if (unshift) path.unshift('');
  4764. if (last === '.' || last === '..') path.push('');
  4765. return path.join('/');
  4766. }
  4767. /**
  4768. * The actual URL instance. Instead of returning an object we've opted-in to
  4769. * create an actual constructor as it's much more memory efficient and
  4770. * faster and it pleases my OCD.
  4771. *
  4772. * It is worth noting that we should not use `URL` as class name to prevent
  4773. * clashes with the global URL instance that got introduced in browsers.
  4774. *
  4775. * @constructor
  4776. * @param {String} address URL we want to parse.
  4777. * @param {Object|String} location Location defaults for relative paths.
  4778. * @param {Boolean|Function} parser Parser for the query string.
  4779. * @private
  4780. */
  4781. function Url(address, location, parser) {
  4782. if (!(this instanceof Url)) {
  4783. return new Url(address, location, parser);
  4784. }
  4785. var relative, extracted, parse, instruction, index, key
  4786. , instructions = rules.slice()
  4787. , type = typeof location
  4788. , url = this
  4789. , i = 0;
  4790. //
  4791. // The following if statements allows this module two have compatibility with
  4792. // 2 different API:
  4793. //
  4794. // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  4795. // where the boolean indicates that the query string should also be parsed.
  4796. //
  4797. // 2. The `URL` interface of the browser which accepts a URL, object as
  4798. // arguments. The supplied object will be used as default values / fall-back
  4799. // for relative paths.
  4800. //
  4801. if ('object' !== type && 'string' !== type) {
  4802. parser = location;
  4803. location = null;
  4804. }
  4805. if (parser && 'function' !== typeof parser) parser = qs.parse;
  4806. location = lolcation(location);
  4807. //
  4808. // Extract protocol information before running the instructions.
  4809. //
  4810. extracted = extractProtocol(address || '');
  4811. relative = !extracted.protocol && !extracted.slashes;
  4812. url.slashes = extracted.slashes || relative && location.slashes;
  4813. url.protocol = extracted.protocol || location.protocol || '';
  4814. address = extracted.rest;
  4815. //
  4816. // When the authority component is absent the URL starts with a path
  4817. // component.
  4818. //
  4819. if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];
  4820. for (; i < instructions.length; i++) {
  4821. instruction = instructions[i];
  4822. if (typeof instruction === 'function') {
  4823. address = instruction(address);
  4824. continue;
  4825. }
  4826. parse = instruction[0];
  4827. key = instruction[1];
  4828. if (parse !== parse) {
  4829. url[key] = address;
  4830. } else if ('string' === typeof parse) {
  4831. if (~(index = address.indexOf(parse))) {
  4832. if ('number' === typeof instruction[2]) {
  4833. url[key] = address.slice(0, index);
  4834. address = address.slice(index + instruction[2]);
  4835. } else {
  4836. url[key] = address.slice(index);
  4837. address = address.slice(0, index);
  4838. }
  4839. }
  4840. } else if ((index = parse.exec(address))) {
  4841. url[key] = index[1];
  4842. address = address.slice(0, index.index);
  4843. }
  4844. url[key] = url[key] || (
  4845. relative && instruction[3] ? location[key] || '' : ''
  4846. );
  4847. //
  4848. // Hostname, host and protocol should be lowercased so they can be used to
  4849. // create a proper `origin`.
  4850. //
  4851. if (instruction[4]) url[key] = url[key].toLowerCase();
  4852. }
  4853. //
  4854. // Also parse the supplied query string in to an object. If we're supplied
  4855. // with a custom parser as function use that instead of the default build-in
  4856. // parser.
  4857. //
  4858. if (parser) url.query = parser(url.query);
  4859. //
  4860. // If the URL is relative, resolve the pathname against the base URL.
  4861. //
  4862. if (
  4863. relative
  4864. && location.slashes
  4865. && url.pathname.charAt(0) !== '/'
  4866. && (url.pathname !== '' || location.pathname !== '')
  4867. ) {
  4868. url.pathname = resolve(url.pathname, location.pathname);
  4869. }
  4870. //
  4871. // We should not add port numbers if they are already the default port number
  4872. // for a given protocol. As the host also contains the port number we're going
  4873. // override it with the hostname which contains no port number.
  4874. //
  4875. if (!required(url.port, url.protocol)) {
  4876. url.host = url.hostname;
  4877. url.port = '';
  4878. }
  4879. //
  4880. // Parse down the `auth` for the username and password.
  4881. //
  4882. url.username = url.password = '';
  4883. if (url.auth) {
  4884. instruction = url.auth.split(':');
  4885. url.username = instruction[0] || '';
  4886. url.password = instruction[1] || '';
  4887. }
  4888. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  4889. ? url.protocol +'//'+ url.host
  4890. : 'null';
  4891. //
  4892. // The href is just the compiled result.
  4893. //
  4894. url.href = url.toString();
  4895. }
  4896. /**
  4897. * This is convenience method for changing properties in the URL instance to
  4898. * insure that they all propagate correctly.
  4899. *
  4900. * @param {String} part Property we need to adjust.
  4901. * @param {Mixed} value The newly assigned value.
  4902. * @param {Boolean|Function} fn When setting the query, it will be the function
  4903. * used to parse the query.
  4904. * When setting the protocol, double slash will be
  4905. * removed from the final url if it is true.
  4906. * @returns {URL} URL instance for chaining.
  4907. * @public
  4908. */
  4909. function set(part, value, fn) {
  4910. var url = this;
  4911. switch (part) {
  4912. case 'query':
  4913. if ('string' === typeof value && value.length) {
  4914. value = (fn || qs.parse)(value);
  4915. }
  4916. url[part] = value;
  4917. break;
  4918. case 'port':
  4919. url[part] = value;
  4920. if (!required(value, url.protocol)) {
  4921. url.host = url.hostname;
  4922. url[part] = '';
  4923. } else if (value) {
  4924. url.host = url.hostname +':'+ value;
  4925. }
  4926. break;
  4927. case 'hostname':
  4928. url[part] = value;
  4929. if (url.port) value += ':'+ url.port;
  4930. url.host = value;
  4931. break;
  4932. case 'host':
  4933. url[part] = value;
  4934. if (/:\d+$/.test(value)) {
  4935. value = value.split(':');
  4936. url.port = value.pop();
  4937. url.hostname = value.join(':');
  4938. } else {
  4939. url.hostname = value;
  4940. url.port = '';
  4941. }
  4942. break;
  4943. case 'protocol':
  4944. url.protocol = value.toLowerCase();
  4945. url.slashes = !fn;
  4946. break;
  4947. case 'pathname':
  4948. case 'hash':
  4949. if (value) {
  4950. var char = part === 'pathname' ? '/' : '#';
  4951. url[part] = value.charAt(0) !== char ? char + value : value;
  4952. } else {
  4953. url[part] = value;
  4954. }
  4955. break;
  4956. default:
  4957. url[part] = value;
  4958. }
  4959. for (var i = 0; i < rules.length; i++) {
  4960. var ins = rules[i];
  4961. if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  4962. }
  4963. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  4964. ? url.protocol +'//'+ url.host
  4965. : 'null';
  4966. url.href = url.toString();
  4967. return url;
  4968. }
  4969. /**
  4970. * Transform the properties back in to a valid and full URL string.
  4971. *
  4972. * @param {Function} stringify Optional query stringify function.
  4973. * @returns {String} Compiled version of the URL.
  4974. * @public
  4975. */
  4976. function toString(stringify) {
  4977. if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  4978. var query
  4979. , url = this
  4980. , protocol = url.protocol;
  4981. if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
  4982. var result = protocol + (url.slashes ? '//' : '');
  4983. if (url.username) {
  4984. result += url.username;
  4985. if (url.password) result += ':'+ url.password;
  4986. result += '@';
  4987. }
  4988. result += url.host + url.pathname;
  4989. query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  4990. if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  4991. if (url.hash) result += url.hash;
  4992. return result;
  4993. }
  4994. Url.prototype = { set: set, toString: toString };
  4995. //
  4996. // Expose the URL parser and some additional properties that might be useful for
  4997. // others or testing.
  4998. //
  4999. Url.extractProtocol = extractProtocol;
  5000. Url.location = lolcation;
  5001. Url.qs = qs;
  5002. module.exports = Url;
  5003. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5004. },{"querystringify":59,"requires-port":60}]},{},[1])(1)
  5005. });
  5006. //# sourceMappingURL=sockjs.js.map