· 6 years ago · Mar 23, 2020, 12:40 AM
1(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){
2"use strict";
3var __importDefault = (this && this.__importDefault) || function (mod) {
4 return (mod && mod.__esModule) ? mod : { "default": mod };
5};
6Object.defineProperty(exports, "__esModule", { value: true });
7const axios_1 = __importDefault(require("axios"));
8const socket_io_client_1 = __importDefault(require("socket.io-client"));
9const login = async () => {
10 const token = window.localStorage.getItem("global-addon-data-token");
11 if (!token) {
12 const email = prompt("Podaj email:");
13 const password = prompt("Podaj hasło:");
14 const { data: { user, token: userToken } } = await axios_1.default.post("http://global.ct8.pl/api/auth/login", { email, password });
15 window.localStorage.setItem("global-addon-data-token", userToken);
16 init(userToken);
17 }
18 init(token);
19};
20const init = (token) => {
21 const socket = socket_io_client_1.default("http://global.ct8.pl", {
22 transportOptions: {
23 polling: {
24 extraHeaders: {
25 'authorization': `Bearer ${token}`
26 }
27 }
28 }
29 });
30 socket.on("connected", () => {
31 socket.emit("joinRoom");
32 });
33 const parseMessage = (data) => ({
34 k: 0,
35 n: `[G] ${data.nickname}`,
36 s: "",
37 t: data.message,
38 ts: new Date(data.createdAt).getTime() / 1000
39 });
40 socket.on("message", (data) => {
41 const parsedMessages = data.map(parseMessage);
42 // @ts-ignore
43 window.parseInput({
44 c: { ...parsedMessages }
45 });
46 });
47 // @ts-ignore
48 const oldCS = window.chatSend;
49 // @ts-ignore
50 window.chatSend = (message) => {
51 if (!message.startsWith("/w ")) {
52 return oldCS(message);
53 }
54 const msg = message.substring(3, message.length);
55 socket.emit('message', { msg });
56 };
57};
58login();
59
60},{"axios":4,"socket.io-client":65}],2:[function(require,module,exports){
61module.exports = after
62
63function after(count, callback, err_cb) {
64 var bail = false
65 err_cb = err_cb || noop
66 proxy.count = count
67
68 return (count === 0) ? callback() : proxy
69
70 function proxy(err, result) {
71 if (proxy.count <= 0) {
72 throw new Error('after called too many times')
73 }
74 --proxy.count
75
76 // after first error, rest are passed to err_cb
77 if (err) {
78 bail = true
79 callback(err)
80 // future error callbacks will go to error handler
81 callback = err_cb
82 } else if (proxy.count === 0 && !bail) {
83 callback(null, result)
84 }
85 }
86}
87
88function noop() {}
89
90},{}],3:[function(require,module,exports){
91/**
92 * An abstraction for slicing an arraybuffer even when
93 * ArrayBuffer.prototype.slice is not supported
94 *
95 * @api public
96 */
97
98module.exports = function(arraybuffer, start, end) {
99 var bytes = arraybuffer.byteLength;
100 start = start || 0;
101 end = end || bytes;
102
103 if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
104
105 if (start < 0) { start += bytes; }
106 if (end < 0) { end += bytes; }
107 if (end > bytes) { end = bytes; }
108
109 if (start >= bytes || start >= end || bytes === 0) {
110 return new ArrayBuffer(0);
111 }
112
113 var abv = new Uint8Array(arraybuffer);
114 var result = new Uint8Array(end - start);
115 for (var i = start, ii = 0; i < end; i++, ii++) {
116 result[ii] = abv[i];
117 }
118 return result.buffer;
119};
120
121},{}],4:[function(require,module,exports){
122module.exports = require('./lib/axios');
123},{"./lib/axios":6}],5:[function(require,module,exports){
124'use strict';
125
126var utils = require('./../utils');
127var settle = require('./../core/settle');
128var buildURL = require('./../helpers/buildURL');
129var buildFullPath = require('../core/buildFullPath');
130var parseHeaders = require('./../helpers/parseHeaders');
131var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
132var createError = require('../core/createError');
133
134module.exports = function xhrAdapter(config) {
135 return new Promise(function dispatchXhrRequest(resolve, reject) {
136 var requestData = config.data;
137 var requestHeaders = config.headers;
138
139 if (utils.isFormData(requestData)) {
140 delete requestHeaders['Content-Type']; // Let the browser set it
141 }
142
143 var request = new XMLHttpRequest();
144
145 // HTTP basic authentication
146 if (config.auth) {
147 var username = config.auth.username || '';
148 var password = config.auth.password || '';
149 requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
150 }
151
152 var fullPath = buildFullPath(config.baseURL, config.url);
153 request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
154
155 // Set the request timeout in MS
156 request.timeout = config.timeout;
157
158 // Listen for ready state
159 request.onreadystatechange = function handleLoad() {
160 if (!request || request.readyState !== 4) {
161 return;
162 }
163
164 // The request errored out and we didn't get a response, this will be
165 // handled by onerror instead
166 // With one exception: request that using file: protocol, most browsers
167 // will return status as 0 even though it's a successful request
168 if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
169 return;
170 }
171
172 // Prepare the response
173 var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
174 var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
175 var response = {
176 data: responseData,
177 status: request.status,
178 statusText: request.statusText,
179 headers: responseHeaders,
180 config: config,
181 request: request
182 };
183
184 settle(resolve, reject, response);
185
186 // Clean up request
187 request = null;
188 };
189
190 // Handle browser request cancellation (as opposed to a manual cancellation)
191 request.onabort = function handleAbort() {
192 if (!request) {
193 return;
194 }
195
196 reject(createError('Request aborted', config, 'ECONNABORTED', request));
197
198 // Clean up request
199 request = null;
200 };
201
202 // Handle low level network errors
203 request.onerror = function handleError() {
204 // Real errors are hidden from us by the browser
205 // onerror should only fire if it's a network error
206 reject(createError('Network Error', config, null, request));
207
208 // Clean up request
209 request = null;
210 };
211
212 // Handle timeout
213 request.ontimeout = function handleTimeout() {
214 var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
215 if (config.timeoutErrorMessage) {
216 timeoutErrorMessage = config.timeoutErrorMessage;
217 }
218 reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
219 request));
220
221 // Clean up request
222 request = null;
223 };
224
225 // Add xsrf header
226 // This is only done if running in a standard browser environment.
227 // Specifically not if we're in a web worker, or react-native.
228 if (utils.isStandardBrowserEnv()) {
229 var cookies = require('./../helpers/cookies');
230
231 // Add xsrf header
232 var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
233 cookies.read(config.xsrfCookieName) :
234 undefined;
235
236 if (xsrfValue) {
237 requestHeaders[config.xsrfHeaderName] = xsrfValue;
238 }
239 }
240
241 // Add headers to the request
242 if ('setRequestHeader' in request) {
243 utils.forEach(requestHeaders, function setRequestHeader(val, key) {
244 if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
245 // Remove Content-Type if data is undefined
246 delete requestHeaders[key];
247 } else {
248 // Otherwise add header to the request
249 request.setRequestHeader(key, val);
250 }
251 });
252 }
253
254 // Add withCredentials to request if needed
255 if (!utils.isUndefined(config.withCredentials)) {
256 request.withCredentials = !!config.withCredentials;
257 }
258
259 // Add responseType to request if needed
260 if (config.responseType) {
261 try {
262 request.responseType = config.responseType;
263 } catch (e) {
264 // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
265 // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
266 if (config.responseType !== 'json') {
267 throw e;
268 }
269 }
270 }
271
272 // Handle progress if needed
273 if (typeof config.onDownloadProgress === 'function') {
274 request.addEventListener('progress', config.onDownloadProgress);
275 }
276
277 // Not all browsers support upload events
278 if (typeof config.onUploadProgress === 'function' && request.upload) {
279 request.upload.addEventListener('progress', config.onUploadProgress);
280 }
281
282 if (config.cancelToken) {
283 // Handle cancellation
284 config.cancelToken.promise.then(function onCanceled(cancel) {
285 if (!request) {
286 return;
287 }
288
289 request.abort();
290 reject(cancel);
291 // Clean up request
292 request = null;
293 });
294 }
295
296 if (requestData === undefined) {
297 requestData = null;
298 }
299
300 // Send the request
301 request.send(requestData);
302 });
303};
304
305},{"../core/buildFullPath":12,"../core/createError":13,"./../core/settle":17,"./../helpers/buildURL":21,"./../helpers/cookies":23,"./../helpers/isURLSameOrigin":25,"./../helpers/parseHeaders":27,"./../utils":29}],6:[function(require,module,exports){
306'use strict';
307
308var utils = require('./utils');
309var bind = require('./helpers/bind');
310var Axios = require('./core/Axios');
311var mergeConfig = require('./core/mergeConfig');
312var defaults = require('./defaults');
313
314/**
315 * Create an instance of Axios
316 *
317 * @param {Object} defaultConfig The default config for the instance
318 * @return {Axios} A new instance of Axios
319 */
320function createInstance(defaultConfig) {
321 var context = new Axios(defaultConfig);
322 var instance = bind(Axios.prototype.request, context);
323
324 // Copy axios.prototype to instance
325 utils.extend(instance, Axios.prototype, context);
326
327 // Copy context to instance
328 utils.extend(instance, context);
329
330 return instance;
331}
332
333// Create the default instance to be exported
334var axios = createInstance(defaults);
335
336// Expose Axios class to allow class inheritance
337axios.Axios = Axios;
338
339// Factory for creating new instances
340axios.create = function create(instanceConfig) {
341 return createInstance(mergeConfig(axios.defaults, instanceConfig));
342};
343
344// Expose Cancel & CancelToken
345axios.Cancel = require('./cancel/Cancel');
346axios.CancelToken = require('./cancel/CancelToken');
347axios.isCancel = require('./cancel/isCancel');
348
349// Expose all/spread
350axios.all = function all(promises) {
351 return Promise.all(promises);
352};
353axios.spread = require('./helpers/spread');
354
355module.exports = axios;
356
357// Allow use of default import syntax in TypeScript
358module.exports.default = axios;
359
360},{"./cancel/Cancel":7,"./cancel/CancelToken":8,"./cancel/isCancel":9,"./core/Axios":10,"./core/mergeConfig":16,"./defaults":19,"./helpers/bind":20,"./helpers/spread":28,"./utils":29}],7:[function(require,module,exports){
361'use strict';
362
363/**
364 * A `Cancel` is an object that is thrown when an operation is canceled.
365 *
366 * @class
367 * @param {string=} message The message.
368 */
369function Cancel(message) {
370 this.message = message;
371}
372
373Cancel.prototype.toString = function toString() {
374 return 'Cancel' + (this.message ? ': ' + this.message : '');
375};
376
377Cancel.prototype.__CANCEL__ = true;
378
379module.exports = Cancel;
380
381},{}],8:[function(require,module,exports){
382'use strict';
383
384var Cancel = require('./Cancel');
385
386/**
387 * A `CancelToken` is an object that can be used to request cancellation of an operation.
388 *
389 * @class
390 * @param {Function} executor The executor function.
391 */
392function CancelToken(executor) {
393 if (typeof executor !== 'function') {
394 throw new TypeError('executor must be a function.');
395 }
396
397 var resolvePromise;
398 this.promise = new Promise(function promiseExecutor(resolve) {
399 resolvePromise = resolve;
400 });
401
402 var token = this;
403 executor(function cancel(message) {
404 if (token.reason) {
405 // Cancellation has already been requested
406 return;
407 }
408
409 token.reason = new Cancel(message);
410 resolvePromise(token.reason);
411 });
412}
413
414/**
415 * Throws a `Cancel` if cancellation has been requested.
416 */
417CancelToken.prototype.throwIfRequested = function throwIfRequested() {
418 if (this.reason) {
419 throw this.reason;
420 }
421};
422
423/**
424 * Returns an object that contains a new `CancelToken` and a function that, when called,
425 * cancels the `CancelToken`.
426 */
427CancelToken.source = function source() {
428 var cancel;
429 var token = new CancelToken(function executor(c) {
430 cancel = c;
431 });
432 return {
433 token: token,
434 cancel: cancel
435 };
436};
437
438module.exports = CancelToken;
439
440},{"./Cancel":7}],9:[function(require,module,exports){
441'use strict';
442
443module.exports = function isCancel(value) {
444 return !!(value && value.__CANCEL__);
445};
446
447},{}],10:[function(require,module,exports){
448'use strict';
449
450var utils = require('./../utils');
451var buildURL = require('../helpers/buildURL');
452var InterceptorManager = require('./InterceptorManager');
453var dispatchRequest = require('./dispatchRequest');
454var mergeConfig = require('./mergeConfig');
455
456/**
457 * Create a new instance of Axios
458 *
459 * @param {Object} instanceConfig The default config for the instance
460 */
461function Axios(instanceConfig) {
462 this.defaults = instanceConfig;
463 this.interceptors = {
464 request: new InterceptorManager(),
465 response: new InterceptorManager()
466 };
467}
468
469/**
470 * Dispatch a request
471 *
472 * @param {Object} config The config specific for this request (merged with this.defaults)
473 */
474Axios.prototype.request = function request(config) {
475 /*eslint no-param-reassign:0*/
476 // Allow for axios('example/url'[, config]) a la fetch API
477 if (typeof config === 'string') {
478 config = arguments[1] || {};
479 config.url = arguments[0];
480 } else {
481 config = config || {};
482 }
483
484 config = mergeConfig(this.defaults, config);
485
486 // Set config.method
487 if (config.method) {
488 config.method = config.method.toLowerCase();
489 } else if (this.defaults.method) {
490 config.method = this.defaults.method.toLowerCase();
491 } else {
492 config.method = 'get';
493 }
494
495 // Hook up interceptors middleware
496 var chain = [dispatchRequest, undefined];
497 var promise = Promise.resolve(config);
498
499 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
500 chain.unshift(interceptor.fulfilled, interceptor.rejected);
501 });
502
503 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
504 chain.push(interceptor.fulfilled, interceptor.rejected);
505 });
506
507 while (chain.length) {
508 promise = promise.then(chain.shift(), chain.shift());
509 }
510
511 return promise;
512};
513
514Axios.prototype.getUri = function getUri(config) {
515 config = mergeConfig(this.defaults, config);
516 return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
517};
518
519// Provide aliases for supported request methods
520utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
521 /*eslint func-names:0*/
522 Axios.prototype[method] = function(url, config) {
523 return this.request(utils.merge(config || {}, {
524 method: method,
525 url: url
526 }));
527 };
528});
529
530utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
531 /*eslint func-names:0*/
532 Axios.prototype[method] = function(url, data, config) {
533 return this.request(utils.merge(config || {}, {
534 method: method,
535 url: url,
536 data: data
537 }));
538 };
539});
540
541module.exports = Axios;
542
543},{"../helpers/buildURL":21,"./../utils":29,"./InterceptorManager":11,"./dispatchRequest":14,"./mergeConfig":16}],11:[function(require,module,exports){
544'use strict';
545
546var utils = require('./../utils');
547
548function InterceptorManager() {
549 this.handlers = [];
550}
551
552/**
553 * Add a new interceptor to the stack
554 *
555 * @param {Function} fulfilled The function to handle `then` for a `Promise`
556 * @param {Function} rejected The function to handle `reject` for a `Promise`
557 *
558 * @return {Number} An ID used to remove interceptor later
559 */
560InterceptorManager.prototype.use = function use(fulfilled, rejected) {
561 this.handlers.push({
562 fulfilled: fulfilled,
563 rejected: rejected
564 });
565 return this.handlers.length - 1;
566};
567
568/**
569 * Remove an interceptor from the stack
570 *
571 * @param {Number} id The ID that was returned by `use`
572 */
573InterceptorManager.prototype.eject = function eject(id) {
574 if (this.handlers[id]) {
575 this.handlers[id] = null;
576 }
577};
578
579/**
580 * Iterate over all the registered interceptors
581 *
582 * This method is particularly useful for skipping over any
583 * interceptors that may have become `null` calling `eject`.
584 *
585 * @param {Function} fn The function to call for each interceptor
586 */
587InterceptorManager.prototype.forEach = function forEach(fn) {
588 utils.forEach(this.handlers, function forEachHandler(h) {
589 if (h !== null) {
590 fn(h);
591 }
592 });
593};
594
595module.exports = InterceptorManager;
596
597},{"./../utils":29}],12:[function(require,module,exports){
598'use strict';
599
600var isAbsoluteURL = require('../helpers/isAbsoluteURL');
601var combineURLs = require('../helpers/combineURLs');
602
603/**
604 * Creates a new URL by combining the baseURL with the requestedURL,
605 * only when the requestedURL is not already an absolute URL.
606 * If the requestURL is absolute, this function returns the requestedURL untouched.
607 *
608 * @param {string} baseURL The base URL
609 * @param {string} requestedURL Absolute or relative URL to combine
610 * @returns {string} The combined full path
611 */
612module.exports = function buildFullPath(baseURL, requestedURL) {
613 if (baseURL && !isAbsoluteURL(requestedURL)) {
614 return combineURLs(baseURL, requestedURL);
615 }
616 return requestedURL;
617};
618
619},{"../helpers/combineURLs":22,"../helpers/isAbsoluteURL":24}],13:[function(require,module,exports){
620'use strict';
621
622var enhanceError = require('./enhanceError');
623
624/**
625 * Create an Error with the specified message, config, error code, request and response.
626 *
627 * @param {string} message The error message.
628 * @param {Object} config The config.
629 * @param {string} [code] The error code (for example, 'ECONNABORTED').
630 * @param {Object} [request] The request.
631 * @param {Object} [response] The response.
632 * @returns {Error} The created error.
633 */
634module.exports = function createError(message, config, code, request, response) {
635 var error = new Error(message);
636 return enhanceError(error, config, code, request, response);
637};
638
639},{"./enhanceError":15}],14:[function(require,module,exports){
640'use strict';
641
642var utils = require('./../utils');
643var transformData = require('./transformData');
644var isCancel = require('../cancel/isCancel');
645var defaults = require('../defaults');
646
647/**
648 * Throws a `Cancel` if cancellation has been requested.
649 */
650function throwIfCancellationRequested(config) {
651 if (config.cancelToken) {
652 config.cancelToken.throwIfRequested();
653 }
654}
655
656/**
657 * Dispatch a request to the server using the configured adapter.
658 *
659 * @param {object} config The config that is to be used for the request
660 * @returns {Promise} The Promise to be fulfilled
661 */
662module.exports = function dispatchRequest(config) {
663 throwIfCancellationRequested(config);
664
665 // Ensure headers exist
666 config.headers = config.headers || {};
667
668 // Transform request data
669 config.data = transformData(
670 config.data,
671 config.headers,
672 config.transformRequest
673 );
674
675 // Flatten headers
676 config.headers = utils.merge(
677 config.headers.common || {},
678 config.headers[config.method] || {},
679 config.headers
680 );
681
682 utils.forEach(
683 ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
684 function cleanHeaderConfig(method) {
685 delete config.headers[method];
686 }
687 );
688
689 var adapter = config.adapter || defaults.adapter;
690
691 return adapter(config).then(function onAdapterResolution(response) {
692 throwIfCancellationRequested(config);
693
694 // Transform response data
695 response.data = transformData(
696 response.data,
697 response.headers,
698 config.transformResponse
699 );
700
701 return response;
702 }, function onAdapterRejection(reason) {
703 if (!isCancel(reason)) {
704 throwIfCancellationRequested(config);
705
706 // Transform response data
707 if (reason && reason.response) {
708 reason.response.data = transformData(
709 reason.response.data,
710 reason.response.headers,
711 config.transformResponse
712 );
713 }
714 }
715
716 return Promise.reject(reason);
717 });
718};
719
720},{"../cancel/isCancel":9,"../defaults":19,"./../utils":29,"./transformData":18}],15:[function(require,module,exports){
721'use strict';
722
723/**
724 * Update an Error with the specified config, error code, and response.
725 *
726 * @param {Error} error The error to update.
727 * @param {Object} config The config.
728 * @param {string} [code] The error code (for example, 'ECONNABORTED').
729 * @param {Object} [request] The request.
730 * @param {Object} [response] The response.
731 * @returns {Error} The error.
732 */
733module.exports = function enhanceError(error, config, code, request, response) {
734 error.config = config;
735 if (code) {
736 error.code = code;
737 }
738
739 error.request = request;
740 error.response = response;
741 error.isAxiosError = true;
742
743 error.toJSON = function() {
744 return {
745 // Standard
746 message: this.message,
747 name: this.name,
748 // Microsoft
749 description: this.description,
750 number: this.number,
751 // Mozilla
752 fileName: this.fileName,
753 lineNumber: this.lineNumber,
754 columnNumber: this.columnNumber,
755 stack: this.stack,
756 // Axios
757 config: this.config,
758 code: this.code
759 };
760 };
761 return error;
762};
763
764},{}],16:[function(require,module,exports){
765'use strict';
766
767var utils = require('../utils');
768
769/**
770 * Config-specific merge-function which creates a new config-object
771 * by merging two configuration objects together.
772 *
773 * @param {Object} config1
774 * @param {Object} config2
775 * @returns {Object} New object resulting from merging config2 to config1
776 */
777module.exports = function mergeConfig(config1, config2) {
778 // eslint-disable-next-line no-param-reassign
779 config2 = config2 || {};
780 var config = {};
781
782 var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
783 var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
784 var defaultToConfig2Keys = [
785 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
786 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
787 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
788 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
789 'httpsAgent', 'cancelToken', 'socketPath'
790 ];
791
792 utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
793 if (typeof config2[prop] !== 'undefined') {
794 config[prop] = config2[prop];
795 }
796 });
797
798 utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
799 if (utils.isObject(config2[prop])) {
800 config[prop] = utils.deepMerge(config1[prop], config2[prop]);
801 } else if (typeof config2[prop] !== 'undefined') {
802 config[prop] = config2[prop];
803 } else if (utils.isObject(config1[prop])) {
804 config[prop] = utils.deepMerge(config1[prop]);
805 } else if (typeof config1[prop] !== 'undefined') {
806 config[prop] = config1[prop];
807 }
808 });
809
810 utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
811 if (typeof config2[prop] !== 'undefined') {
812 config[prop] = config2[prop];
813 } else if (typeof config1[prop] !== 'undefined') {
814 config[prop] = config1[prop];
815 }
816 });
817
818 var axiosKeys = valueFromConfig2Keys
819 .concat(mergeDeepPropertiesKeys)
820 .concat(defaultToConfig2Keys);
821
822 var otherKeys = Object
823 .keys(config2)
824 .filter(function filterAxiosKeys(key) {
825 return axiosKeys.indexOf(key) === -1;
826 });
827
828 utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
829 if (typeof config2[prop] !== 'undefined') {
830 config[prop] = config2[prop];
831 } else if (typeof config1[prop] !== 'undefined') {
832 config[prop] = config1[prop];
833 }
834 });
835
836 return config;
837};
838
839},{"../utils":29}],17:[function(require,module,exports){
840'use strict';
841
842var createError = require('./createError');
843
844/**
845 * Resolve or reject a Promise based on response status.
846 *
847 * @param {Function} resolve A function that resolves the promise.
848 * @param {Function} reject A function that rejects the promise.
849 * @param {object} response The response.
850 */
851module.exports = function settle(resolve, reject, response) {
852 var validateStatus = response.config.validateStatus;
853 if (!validateStatus || validateStatus(response.status)) {
854 resolve(response);
855 } else {
856 reject(createError(
857 'Request failed with status code ' + response.status,
858 response.config,
859 null,
860 response.request,
861 response
862 ));
863 }
864};
865
866},{"./createError":13}],18:[function(require,module,exports){
867'use strict';
868
869var utils = require('./../utils');
870
871/**
872 * Transform the data for a request or a response
873 *
874 * @param {Object|String} data The data to be transformed
875 * @param {Array} headers The headers for the request or response
876 * @param {Array|Function} fns A single function or Array of functions
877 * @returns {*} The resulting transformed data
878 */
879module.exports = function transformData(data, headers, fns) {
880 /*eslint no-param-reassign:0*/
881 utils.forEach(fns, function transform(fn) {
882 data = fn(data, headers);
883 });
884
885 return data;
886};
887
888},{"./../utils":29}],19:[function(require,module,exports){
889(function (process){
890'use strict';
891
892var utils = require('./utils');
893var normalizeHeaderName = require('./helpers/normalizeHeaderName');
894
895var DEFAULT_CONTENT_TYPE = {
896 'Content-Type': 'application/x-www-form-urlencoded'
897};
898
899function setContentTypeIfUnset(headers, value) {
900 if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
901 headers['Content-Type'] = value;
902 }
903}
904
905function getDefaultAdapter() {
906 var adapter;
907 if (typeof XMLHttpRequest !== 'undefined') {
908 // For browsers use XHR adapter
909 adapter = require('./adapters/xhr');
910 } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
911 // For node use HTTP adapter
912 adapter = require('./adapters/http');
913 }
914 return adapter;
915}
916
917var defaults = {
918 adapter: getDefaultAdapter(),
919
920 transformRequest: [function transformRequest(data, headers) {
921 normalizeHeaderName(headers, 'Accept');
922 normalizeHeaderName(headers, 'Content-Type');
923 if (utils.isFormData(data) ||
924 utils.isArrayBuffer(data) ||
925 utils.isBuffer(data) ||
926 utils.isStream(data) ||
927 utils.isFile(data) ||
928 utils.isBlob(data)
929 ) {
930 return data;
931 }
932 if (utils.isArrayBufferView(data)) {
933 return data.buffer;
934 }
935 if (utils.isURLSearchParams(data)) {
936 setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
937 return data.toString();
938 }
939 if (utils.isObject(data)) {
940 setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
941 return JSON.stringify(data);
942 }
943 return data;
944 }],
945
946 transformResponse: [function transformResponse(data) {
947 /*eslint no-param-reassign:0*/
948 if (typeof data === 'string') {
949 try {
950 data = JSON.parse(data);
951 } catch (e) { /* Ignore */ }
952 }
953 return data;
954 }],
955
956 /**
957 * A timeout in milliseconds to abort a request. If set to 0 (default) a
958 * timeout is not created.
959 */
960 timeout: 0,
961
962 xsrfCookieName: 'XSRF-TOKEN',
963 xsrfHeaderName: 'X-XSRF-TOKEN',
964
965 maxContentLength: -1,
966
967 validateStatus: function validateStatus(status) {
968 return status >= 200 && status < 300;
969 }
970};
971
972defaults.headers = {
973 common: {
974 'Accept': 'application/json, text/plain, */*'
975 }
976};
977
978utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
979 defaults.headers[method] = {};
980});
981
982utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
983 defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
984});
985
986module.exports = defaults;
987
988}).call(this,require('_process'))
989},{"./adapters/http":5,"./adapters/xhr":5,"./helpers/normalizeHeaderName":26,"./utils":29,"_process":64}],20:[function(require,module,exports){
990'use strict';
991
992module.exports = function bind(fn, thisArg) {
993 return function wrap() {
994 var args = new Array(arguments.length);
995 for (var i = 0; i < args.length; i++) {
996 args[i] = arguments[i];
997 }
998 return fn.apply(thisArg, args);
999 };
1000};
1001
1002},{}],21:[function(require,module,exports){
1003'use strict';
1004
1005var utils = require('./../utils');
1006
1007function encode(val) {
1008 return encodeURIComponent(val).
1009 replace(/%40/gi, '@').
1010 replace(/%3A/gi, ':').
1011 replace(/%24/g, '$').
1012 replace(/%2C/gi, ',').
1013 replace(/%20/g, '+').
1014 replace(/%5B/gi, '[').
1015 replace(/%5D/gi, ']');
1016}
1017
1018/**
1019 * Build a URL by appending params to the end
1020 *
1021 * @param {string} url The base of the url (e.g., http://www.google.com)
1022 * @param {object} [params] The params to be appended
1023 * @returns {string} The formatted url
1024 */
1025module.exports = function buildURL(url, params, paramsSerializer) {
1026 /*eslint no-param-reassign:0*/
1027 if (!params) {
1028 return url;
1029 }
1030
1031 var serializedParams;
1032 if (paramsSerializer) {
1033 serializedParams = paramsSerializer(params);
1034 } else if (utils.isURLSearchParams(params)) {
1035 serializedParams = params.toString();
1036 } else {
1037 var parts = [];
1038
1039 utils.forEach(params, function serialize(val, key) {
1040 if (val === null || typeof val === 'undefined') {
1041 return;
1042 }
1043
1044 if (utils.isArray(val)) {
1045 key = key + '[]';
1046 } else {
1047 val = [val];
1048 }
1049
1050 utils.forEach(val, function parseValue(v) {
1051 if (utils.isDate(v)) {
1052 v = v.toISOString();
1053 } else if (utils.isObject(v)) {
1054 v = JSON.stringify(v);
1055 }
1056 parts.push(encode(key) + '=' + encode(v));
1057 });
1058 });
1059
1060 serializedParams = parts.join('&');
1061 }
1062
1063 if (serializedParams) {
1064 var hashmarkIndex = url.indexOf('#');
1065 if (hashmarkIndex !== -1) {
1066 url = url.slice(0, hashmarkIndex);
1067 }
1068
1069 url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1070 }
1071
1072 return url;
1073};
1074
1075},{"./../utils":29}],22:[function(require,module,exports){
1076'use strict';
1077
1078/**
1079 * Creates a new URL by combining the specified URLs
1080 *
1081 * @param {string} baseURL The base URL
1082 * @param {string} relativeURL The relative URL
1083 * @returns {string} The combined URL
1084 */
1085module.exports = function combineURLs(baseURL, relativeURL) {
1086 return relativeURL
1087 ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
1088 : baseURL;
1089};
1090
1091},{}],23:[function(require,module,exports){
1092'use strict';
1093
1094var utils = require('./../utils');
1095
1096module.exports = (
1097 utils.isStandardBrowserEnv() ?
1098
1099 // Standard browser envs support document.cookie
1100 (function standardBrowserEnv() {
1101 return {
1102 write: function write(name, value, expires, path, domain, secure) {
1103 var cookie = [];
1104 cookie.push(name + '=' + encodeURIComponent(value));
1105
1106 if (utils.isNumber(expires)) {
1107 cookie.push('expires=' + new Date(expires).toGMTString());
1108 }
1109
1110 if (utils.isString(path)) {
1111 cookie.push('path=' + path);
1112 }
1113
1114 if (utils.isString(domain)) {
1115 cookie.push('domain=' + domain);
1116 }
1117
1118 if (secure === true) {
1119 cookie.push('secure');
1120 }
1121
1122 document.cookie = cookie.join('; ');
1123 },
1124
1125 read: function read(name) {
1126 var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
1127 return (match ? decodeURIComponent(match[3]) : null);
1128 },
1129
1130 remove: function remove(name) {
1131 this.write(name, '', Date.now() - 86400000);
1132 }
1133 };
1134 })() :
1135
1136 // Non standard browser env (web workers, react-native) lack needed support.
1137 (function nonStandardBrowserEnv() {
1138 return {
1139 write: function write() {},
1140 read: function read() { return null; },
1141 remove: function remove() {}
1142 };
1143 })()
1144);
1145
1146},{"./../utils":29}],24:[function(require,module,exports){
1147'use strict';
1148
1149/**
1150 * Determines whether the specified URL is absolute
1151 *
1152 * @param {string} url The URL to test
1153 * @returns {boolean} True if the specified URL is absolute, otherwise false
1154 */
1155module.exports = function isAbsoluteURL(url) {
1156 // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
1157 // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
1158 // by any combination of letters, digits, plus, period, or hyphen.
1159 return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
1160};
1161
1162},{}],25:[function(require,module,exports){
1163'use strict';
1164
1165var utils = require('./../utils');
1166
1167module.exports = (
1168 utils.isStandardBrowserEnv() ?
1169
1170 // Standard browser envs have full support of the APIs needed to test
1171 // whether the request URL is of the same origin as current location.
1172 (function standardBrowserEnv() {
1173 var msie = /(msie|trident)/i.test(navigator.userAgent);
1174 var urlParsingNode = document.createElement('a');
1175 var originURL;
1176
1177 /**
1178 * Parse a URL to discover it's components
1179 *
1180 * @param {String} url The URL to be parsed
1181 * @returns {Object}
1182 */
1183 function resolveURL(url) {
1184 var href = url;
1185
1186 if (msie) {
1187 // IE needs attribute set twice to normalize properties
1188 urlParsingNode.setAttribute('href', href);
1189 href = urlParsingNode.href;
1190 }
1191
1192 urlParsingNode.setAttribute('href', href);
1193
1194 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
1195 return {
1196 href: urlParsingNode.href,
1197 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
1198 host: urlParsingNode.host,
1199 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
1200 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
1201 hostname: urlParsingNode.hostname,
1202 port: urlParsingNode.port,
1203 pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
1204 urlParsingNode.pathname :
1205 '/' + urlParsingNode.pathname
1206 };
1207 }
1208
1209 originURL = resolveURL(window.location.href);
1210
1211 /**
1212 * Determine if a URL shares the same origin as the current location
1213 *
1214 * @param {String} requestURL The URL to test
1215 * @returns {boolean} True if URL shares the same origin, otherwise false
1216 */
1217 return function isURLSameOrigin(requestURL) {
1218 var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
1219 return (parsed.protocol === originURL.protocol &&
1220 parsed.host === originURL.host);
1221 };
1222 })() :
1223
1224 // Non standard browser envs (web workers, react-native) lack needed support.
1225 (function nonStandardBrowserEnv() {
1226 return function isURLSameOrigin() {
1227 return true;
1228 };
1229 })()
1230);
1231
1232},{"./../utils":29}],26:[function(require,module,exports){
1233'use strict';
1234
1235var utils = require('../utils');
1236
1237module.exports = function normalizeHeaderName(headers, normalizedName) {
1238 utils.forEach(headers, function processHeader(value, name) {
1239 if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
1240 headers[normalizedName] = value;
1241 delete headers[name];
1242 }
1243 });
1244};
1245
1246},{"../utils":29}],27:[function(require,module,exports){
1247'use strict';
1248
1249var utils = require('./../utils');
1250
1251// Headers whose duplicates are ignored by node
1252// c.f. https://nodejs.org/api/http.html#http_message_headers
1253var ignoreDuplicateOf = [
1254 'age', 'authorization', 'content-length', 'content-type', 'etag',
1255 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1256 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1257 'referer', 'retry-after', 'user-agent'
1258];
1259
1260/**
1261 * Parse headers into an object
1262 *
1263 * ```
1264 * Date: Wed, 27 Aug 2014 08:58:49 GMT
1265 * Content-Type: application/json
1266 * Connection: keep-alive
1267 * Transfer-Encoding: chunked
1268 * ```
1269 *
1270 * @param {String} headers Headers needing to be parsed
1271 * @returns {Object} Headers parsed into an object
1272 */
1273module.exports = function parseHeaders(headers) {
1274 var parsed = {};
1275 var key;
1276 var val;
1277 var i;
1278
1279 if (!headers) { return parsed; }
1280
1281 utils.forEach(headers.split('\n'), function parser(line) {
1282 i = line.indexOf(':');
1283 key = utils.trim(line.substr(0, i)).toLowerCase();
1284 val = utils.trim(line.substr(i + 1));
1285
1286 if (key) {
1287 if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
1288 return;
1289 }
1290 if (key === 'set-cookie') {
1291 parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
1292 } else {
1293 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1294 }
1295 }
1296 });
1297
1298 return parsed;
1299};
1300
1301},{"./../utils":29}],28:[function(require,module,exports){
1302'use strict';
1303
1304/**
1305 * Syntactic sugar for invoking a function and expanding an array for arguments.
1306 *
1307 * Common use case would be to use `Function.prototype.apply`.
1308 *
1309 * ```js
1310 * function f(x, y, z) {}
1311 * var args = [1, 2, 3];
1312 * f.apply(null, args);
1313 * ```
1314 *
1315 * With `spread` this example can be re-written.
1316 *
1317 * ```js
1318 * spread(function(x, y, z) {})([1, 2, 3]);
1319 * ```
1320 *
1321 * @param {Function} callback
1322 * @returns {Function}
1323 */
1324module.exports = function spread(callback) {
1325 return function wrap(arr) {
1326 return callback.apply(null, arr);
1327 };
1328};
1329
1330},{}],29:[function(require,module,exports){
1331'use strict';
1332
1333var bind = require('./helpers/bind');
1334
1335/*global toString:true*/
1336
1337// utils is a library of generic helper functions non-specific to axios
1338
1339var toString = Object.prototype.toString;
1340
1341/**
1342 * Determine if a value is an Array
1343 *
1344 * @param {Object} val The value to test
1345 * @returns {boolean} True if value is an Array, otherwise false
1346 */
1347function isArray(val) {
1348 return toString.call(val) === '[object Array]';
1349}
1350
1351/**
1352 * Determine if a value is undefined
1353 *
1354 * @param {Object} val The value to test
1355 * @returns {boolean} True if the value is undefined, otherwise false
1356 */
1357function isUndefined(val) {
1358 return typeof val === 'undefined';
1359}
1360
1361/**
1362 * Determine if a value is a Buffer
1363 *
1364 * @param {Object} val The value to test
1365 * @returns {boolean} True if value is a Buffer, otherwise false
1366 */
1367function isBuffer(val) {
1368 return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
1369 && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
1370}
1371
1372/**
1373 * Determine if a value is an ArrayBuffer
1374 *
1375 * @param {Object} val The value to test
1376 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
1377 */
1378function isArrayBuffer(val) {
1379 return toString.call(val) === '[object ArrayBuffer]';
1380}
1381
1382/**
1383 * Determine if a value is a FormData
1384 *
1385 * @param {Object} val The value to test
1386 * @returns {boolean} True if value is an FormData, otherwise false
1387 */
1388function isFormData(val) {
1389 return (typeof FormData !== 'undefined') && (val instanceof FormData);
1390}
1391
1392/**
1393 * Determine if a value is a view on an ArrayBuffer
1394 *
1395 * @param {Object} val The value to test
1396 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
1397 */
1398function isArrayBufferView(val) {
1399 var result;
1400 if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
1401 result = ArrayBuffer.isView(val);
1402 } else {
1403 result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
1404 }
1405 return result;
1406}
1407
1408/**
1409 * Determine if a value is a String
1410 *
1411 * @param {Object} val The value to test
1412 * @returns {boolean} True if value is a String, otherwise false
1413 */
1414function isString(val) {
1415 return typeof val === 'string';
1416}
1417
1418/**
1419 * Determine if a value is a Number
1420 *
1421 * @param {Object} val The value to test
1422 * @returns {boolean} True if value is a Number, otherwise false
1423 */
1424function isNumber(val) {
1425 return typeof val === 'number';
1426}
1427
1428/**
1429 * Determine if a value is an Object
1430 *
1431 * @param {Object} val The value to test
1432 * @returns {boolean} True if value is an Object, otherwise false
1433 */
1434function isObject(val) {
1435 return val !== null && typeof val === 'object';
1436}
1437
1438/**
1439 * Determine if a value is a Date
1440 *
1441 * @param {Object} val The value to test
1442 * @returns {boolean} True if value is a Date, otherwise false
1443 */
1444function isDate(val) {
1445 return toString.call(val) === '[object Date]';
1446}
1447
1448/**
1449 * Determine if a value is a File
1450 *
1451 * @param {Object} val The value to test
1452 * @returns {boolean} True if value is a File, otherwise false
1453 */
1454function isFile(val) {
1455 return toString.call(val) === '[object File]';
1456}
1457
1458/**
1459 * Determine if a value is a Blob
1460 *
1461 * @param {Object} val The value to test
1462 * @returns {boolean} True if value is a Blob, otherwise false
1463 */
1464function isBlob(val) {
1465 return toString.call(val) === '[object Blob]';
1466}
1467
1468/**
1469 * Determine if a value is a Function
1470 *
1471 * @param {Object} val The value to test
1472 * @returns {boolean} True if value is a Function, otherwise false
1473 */
1474function isFunction(val) {
1475 return toString.call(val) === '[object Function]';
1476}
1477
1478/**
1479 * Determine if a value is a Stream
1480 *
1481 * @param {Object} val The value to test
1482 * @returns {boolean} True if value is a Stream, otherwise false
1483 */
1484function isStream(val) {
1485 return isObject(val) && isFunction(val.pipe);
1486}
1487
1488/**
1489 * Determine if a value is a URLSearchParams object
1490 *
1491 * @param {Object} val The value to test
1492 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
1493 */
1494function isURLSearchParams(val) {
1495 return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
1496}
1497
1498/**
1499 * Trim excess whitespace off the beginning and end of a string
1500 *
1501 * @param {String} str The String to trim
1502 * @returns {String} The String freed of excess whitespace
1503 */
1504function trim(str) {
1505 return str.replace(/^\s*/, '').replace(/\s*$/, '');
1506}
1507
1508/**
1509 * Determine if we're running in a standard browser environment
1510 *
1511 * This allows axios to run in a web worker, and react-native.
1512 * Both environments support XMLHttpRequest, but not fully standard globals.
1513 *
1514 * web workers:
1515 * typeof window -> undefined
1516 * typeof document -> undefined
1517 *
1518 * react-native:
1519 * navigator.product -> 'ReactNative'
1520 * nativescript
1521 * navigator.product -> 'NativeScript' or 'NS'
1522 */
1523function isStandardBrowserEnv() {
1524 if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
1525 navigator.product === 'NativeScript' ||
1526 navigator.product === 'NS')) {
1527 return false;
1528 }
1529 return (
1530 typeof window !== 'undefined' &&
1531 typeof document !== 'undefined'
1532 );
1533}
1534
1535/**
1536 * Iterate over an Array or an Object invoking a function for each item.
1537 *
1538 * If `obj` is an Array callback will be called passing
1539 * the value, index, and complete array for each item.
1540 *
1541 * If 'obj' is an Object callback will be called passing
1542 * the value, key, and complete object for each property.
1543 *
1544 * @param {Object|Array} obj The object to iterate
1545 * @param {Function} fn The callback to invoke for each item
1546 */
1547function forEach(obj, fn) {
1548 // Don't bother if no value provided
1549 if (obj === null || typeof obj === 'undefined') {
1550 return;
1551 }
1552
1553 // Force an array if not already something iterable
1554 if (typeof obj !== 'object') {
1555 /*eslint no-param-reassign:0*/
1556 obj = [obj];
1557 }
1558
1559 if (isArray(obj)) {
1560 // Iterate over array values
1561 for (var i = 0, l = obj.length; i < l; i++) {
1562 fn.call(null, obj[i], i, obj);
1563 }
1564 } else {
1565 // Iterate over object keys
1566 for (var key in obj) {
1567 if (Object.prototype.hasOwnProperty.call(obj, key)) {
1568 fn.call(null, obj[key], key, obj);
1569 }
1570 }
1571 }
1572}
1573
1574/**
1575 * Accepts varargs expecting each argument to be an object, then
1576 * immutably merges the properties of each object and returns result.
1577 *
1578 * When multiple objects contain the same key the later object in
1579 * the arguments list will take precedence.
1580 *
1581 * Example:
1582 *
1583 * ```js
1584 * var result = merge({foo: 123}, {foo: 456});
1585 * console.log(result.foo); // outputs 456
1586 * ```
1587 *
1588 * @param {Object} obj1 Object to merge
1589 * @returns {Object} Result of all merge properties
1590 */
1591function merge(/* obj1, obj2, obj3, ... */) {
1592 var result = {};
1593 function assignValue(val, key) {
1594 if (typeof result[key] === 'object' && typeof val === 'object') {
1595 result[key] = merge(result[key], val);
1596 } else {
1597 result[key] = val;
1598 }
1599 }
1600
1601 for (var i = 0, l = arguments.length; i < l; i++) {
1602 forEach(arguments[i], assignValue);
1603 }
1604 return result;
1605}
1606
1607/**
1608 * Function equal to merge with the difference being that no reference
1609 * to original objects is kept.
1610 *
1611 * @see merge
1612 * @param {Object} obj1 Object to merge
1613 * @returns {Object} Result of all merge properties
1614 */
1615function deepMerge(/* obj1, obj2, obj3, ... */) {
1616 var result = {};
1617 function assignValue(val, key) {
1618 if (typeof result[key] === 'object' && typeof val === 'object') {
1619 result[key] = deepMerge(result[key], val);
1620 } else if (typeof val === 'object') {
1621 result[key] = deepMerge({}, val);
1622 } else {
1623 result[key] = val;
1624 }
1625 }
1626
1627 for (var i = 0, l = arguments.length; i < l; i++) {
1628 forEach(arguments[i], assignValue);
1629 }
1630 return result;
1631}
1632
1633/**
1634 * Extends object a by mutably adding to it the properties of object b.
1635 *
1636 * @param {Object} a The object to be extended
1637 * @param {Object} b The object to copy properties from
1638 * @param {Object} thisArg The object to bind function to
1639 * @return {Object} The resulting value of object a
1640 */
1641function extend(a, b, thisArg) {
1642 forEach(b, function assignValue(val, key) {
1643 if (thisArg && typeof val === 'function') {
1644 a[key] = bind(val, thisArg);
1645 } else {
1646 a[key] = val;
1647 }
1648 });
1649 return a;
1650}
1651
1652module.exports = {
1653 isArray: isArray,
1654 isArrayBuffer: isArrayBuffer,
1655 isBuffer: isBuffer,
1656 isFormData: isFormData,
1657 isArrayBufferView: isArrayBufferView,
1658 isString: isString,
1659 isNumber: isNumber,
1660 isObject: isObject,
1661 isUndefined: isUndefined,
1662 isDate: isDate,
1663 isFile: isFile,
1664 isBlob: isBlob,
1665 isFunction: isFunction,
1666 isStream: isStream,
1667 isURLSearchParams: isURLSearchParams,
1668 isStandardBrowserEnv: isStandardBrowserEnv,
1669 forEach: forEach,
1670 merge: merge,
1671 deepMerge: deepMerge,
1672 extend: extend,
1673 trim: trim
1674};
1675
1676},{"./helpers/bind":20}],30:[function(require,module,exports){
1677
1678/**
1679 * Expose `Backoff`.
1680 */
1681
1682module.exports = Backoff;
1683
1684/**
1685 * Initialize backoff timer with `opts`.
1686 *
1687 * - `min` initial timeout in milliseconds [100]
1688 * - `max` max timeout [10000]
1689 * - `jitter` [0]
1690 * - `factor` [2]
1691 *
1692 * @param {Object} opts
1693 * @api public
1694 */
1695
1696function Backoff(opts) {
1697 opts = opts || {};
1698 this.ms = opts.min || 100;
1699 this.max = opts.max || 10000;
1700 this.factor = opts.factor || 2;
1701 this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
1702 this.attempts = 0;
1703}
1704
1705/**
1706 * Return the backoff duration.
1707 *
1708 * @return {Number}
1709 * @api public
1710 */
1711
1712Backoff.prototype.duration = function(){
1713 var ms = this.ms * Math.pow(this.factor, this.attempts++);
1714 if (this.jitter) {
1715 var rand = Math.random();
1716 var deviation = Math.floor(rand * this.jitter * ms);
1717 ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
1718 }
1719 return Math.min(ms, this.max) | 0;
1720};
1721
1722/**
1723 * Reset the number of attempts.
1724 *
1725 * @api public
1726 */
1727
1728Backoff.prototype.reset = function(){
1729 this.attempts = 0;
1730};
1731
1732/**
1733 * Set the minimum duration
1734 *
1735 * @api public
1736 */
1737
1738Backoff.prototype.setMin = function(min){
1739 this.ms = min;
1740};
1741
1742/**
1743 * Set the maximum duration
1744 *
1745 * @api public
1746 */
1747
1748Backoff.prototype.setMax = function(max){
1749 this.max = max;
1750};
1751
1752/**
1753 * Set the jitter
1754 *
1755 * @api public
1756 */
1757
1758Backoff.prototype.setJitter = function(jitter){
1759 this.jitter = jitter;
1760};
1761
1762
1763},{}],31:[function(require,module,exports){
1764/*
1765 * base64-arraybuffer
1766 * https://github.com/niklasvh/base64-arraybuffer
1767 *
1768 * Copyright (c) 2012 Niklas von Hertzen
1769 * Licensed under the MIT license.
1770 */
1771(function(){
1772 "use strict";
1773
1774 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1775
1776 // Use a lookup table to find the index.
1777 var lookup = new Uint8Array(256);
1778 for (var i = 0; i < chars.length; i++) {
1779 lookup[chars.charCodeAt(i)] = i;
1780 }
1781
1782 exports.encode = function(arraybuffer) {
1783 var bytes = new Uint8Array(arraybuffer),
1784 i, len = bytes.length, base64 = "";
1785
1786 for (i = 0; i < len; i+=3) {
1787 base64 += chars[bytes[i] >> 2];
1788 base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
1789 base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
1790 base64 += chars[bytes[i + 2] & 63];
1791 }
1792
1793 if ((len % 3) === 2) {
1794 base64 = base64.substring(0, base64.length - 1) + "=";
1795 } else if (len % 3 === 1) {
1796 base64 = base64.substring(0, base64.length - 2) + "==";
1797 }
1798
1799 return base64;
1800 };
1801
1802 exports.decode = function(base64) {
1803 var bufferLength = base64.length * 0.75,
1804 len = base64.length, i, p = 0,
1805 encoded1, encoded2, encoded3, encoded4;
1806
1807 if (base64[base64.length - 1] === "=") {
1808 bufferLength--;
1809 if (base64[base64.length - 2] === "=") {
1810 bufferLength--;
1811 }
1812 }
1813
1814 var arraybuffer = new ArrayBuffer(bufferLength),
1815 bytes = new Uint8Array(arraybuffer);
1816
1817 for (i = 0; i < len; i+=4) {
1818 encoded1 = lookup[base64.charCodeAt(i)];
1819 encoded2 = lookup[base64.charCodeAt(i+1)];
1820 encoded3 = lookup[base64.charCodeAt(i+2)];
1821 encoded4 = lookup[base64.charCodeAt(i+3)];
1822
1823 bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
1824 bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
1825 bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
1826 }
1827
1828 return arraybuffer;
1829 };
1830})();
1831
1832},{}],32:[function(require,module,exports){
1833'use strict'
1834
1835exports.byteLength = byteLength
1836exports.toByteArray = toByteArray
1837exports.fromByteArray = fromByteArray
1838
1839var lookup = []
1840var revLookup = []
1841var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
1842
1843var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1844for (var i = 0, len = code.length; i < len; ++i) {
1845 lookup[i] = code[i]
1846 revLookup[code.charCodeAt(i)] = i
1847}
1848
1849// Support decoding URL-safe base64 strings, as Node.js does.
1850// See: https://en.wikipedia.org/wiki/Base64#URL_applications
1851revLookup['-'.charCodeAt(0)] = 62
1852revLookup['_'.charCodeAt(0)] = 63
1853
1854function getLens (b64) {
1855 var len = b64.length
1856
1857 if (len % 4 > 0) {
1858 throw new Error('Invalid string. Length must be a multiple of 4')
1859 }
1860
1861 // Trim off extra bytes after placeholder bytes are found
1862 // See: https://github.com/beatgammit/base64-js/issues/42
1863 var validLen = b64.indexOf('=')
1864 if (validLen === -1) validLen = len
1865
1866 var placeHoldersLen = validLen === len
1867 ? 0
1868 : 4 - (validLen % 4)
1869
1870 return [validLen, placeHoldersLen]
1871}
1872
1873// base64 is 4/3 + up to two characters of the original data
1874function byteLength (b64) {
1875 var lens = getLens(b64)
1876 var validLen = lens[0]
1877 var placeHoldersLen = lens[1]
1878 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1879}
1880
1881function _byteLength (b64, validLen, placeHoldersLen) {
1882 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
1883}
1884
1885function toByteArray (b64) {
1886 var tmp
1887 var lens = getLens(b64)
1888 var validLen = lens[0]
1889 var placeHoldersLen = lens[1]
1890
1891 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
1892
1893 var curByte = 0
1894
1895 // if there are placeholders, only get up to the last complete 4 chars
1896 var len = placeHoldersLen > 0
1897 ? validLen - 4
1898 : validLen
1899
1900 var i
1901 for (i = 0; i < len; i += 4) {
1902 tmp =
1903 (revLookup[b64.charCodeAt(i)] << 18) |
1904 (revLookup[b64.charCodeAt(i + 1)] << 12) |
1905 (revLookup[b64.charCodeAt(i + 2)] << 6) |
1906 revLookup[b64.charCodeAt(i + 3)]
1907 arr[curByte++] = (tmp >> 16) & 0xFF
1908 arr[curByte++] = (tmp >> 8) & 0xFF
1909 arr[curByte++] = tmp & 0xFF
1910 }
1911
1912 if (placeHoldersLen === 2) {
1913 tmp =
1914 (revLookup[b64.charCodeAt(i)] << 2) |
1915 (revLookup[b64.charCodeAt(i + 1)] >> 4)
1916 arr[curByte++] = tmp & 0xFF
1917 }
1918
1919 if (placeHoldersLen === 1) {
1920 tmp =
1921 (revLookup[b64.charCodeAt(i)] << 10) |
1922 (revLookup[b64.charCodeAt(i + 1)] << 4) |
1923 (revLookup[b64.charCodeAt(i + 2)] >> 2)
1924 arr[curByte++] = (tmp >> 8) & 0xFF
1925 arr[curByte++] = tmp & 0xFF
1926 }
1927
1928 return arr
1929}
1930
1931function tripletToBase64 (num) {
1932 return lookup[num >> 18 & 0x3F] +
1933 lookup[num >> 12 & 0x3F] +
1934 lookup[num >> 6 & 0x3F] +
1935 lookup[num & 0x3F]
1936}
1937
1938function encodeChunk (uint8, start, end) {
1939 var tmp
1940 var output = []
1941 for (var i = start; i < end; i += 3) {
1942 tmp =
1943 ((uint8[i] << 16) & 0xFF0000) +
1944 ((uint8[i + 1] << 8) & 0xFF00) +
1945 (uint8[i + 2] & 0xFF)
1946 output.push(tripletToBase64(tmp))
1947 }
1948 return output.join('')
1949}
1950
1951function fromByteArray (uint8) {
1952 var tmp
1953 var len = uint8.length
1954 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
1955 var parts = []
1956 var maxChunkLength = 16383 // must be multiple of 3
1957
1958 // go through the array every three bytes, we'll deal with trailing stuff later
1959 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1960 parts.push(encodeChunk(
1961 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
1962 ))
1963 }
1964
1965 // pad the end with zeros, but make sure to not forget the extra bytes
1966 if (extraBytes === 1) {
1967 tmp = uint8[len - 1]
1968 parts.push(
1969 lookup[tmp >> 2] +
1970 lookup[(tmp << 4) & 0x3F] +
1971 '=='
1972 )
1973 } else if (extraBytes === 2) {
1974 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
1975 parts.push(
1976 lookup[tmp >> 10] +
1977 lookup[(tmp >> 4) & 0x3F] +
1978 lookup[(tmp << 2) & 0x3F] +
1979 '='
1980 )
1981 }
1982
1983 return parts.join('')
1984}
1985
1986},{}],33:[function(require,module,exports){
1987/**
1988 * Create a blob builder even when vendor prefixes exist
1989 */
1990
1991var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
1992 typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :
1993 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
1994 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
1995 false;
1996
1997/**
1998 * Check if Blob constructor is supported
1999 */
2000
2001var blobSupported = (function() {
2002 try {
2003 var a = new Blob(['hi']);
2004 return a.size === 2;
2005 } catch(e) {
2006 return false;
2007 }
2008})();
2009
2010/**
2011 * Check if Blob constructor supports ArrayBufferViews
2012 * Fails in Safari 6, so we need to map to ArrayBuffers there.
2013 */
2014
2015var blobSupportsArrayBufferView = blobSupported && (function() {
2016 try {
2017 var b = new Blob([new Uint8Array([1,2])]);
2018 return b.size === 2;
2019 } catch(e) {
2020 return false;
2021 }
2022})();
2023
2024/**
2025 * Check if BlobBuilder is supported
2026 */
2027
2028var blobBuilderSupported = BlobBuilder
2029 && BlobBuilder.prototype.append
2030 && BlobBuilder.prototype.getBlob;
2031
2032/**
2033 * Helper function that maps ArrayBufferViews to ArrayBuffers
2034 * Used by BlobBuilder constructor and old browsers that didn't
2035 * support it in the Blob constructor.
2036 */
2037
2038function mapArrayBufferViews(ary) {
2039 return ary.map(function(chunk) {
2040 if (chunk.buffer instanceof ArrayBuffer) {
2041 var buf = chunk.buffer;
2042
2043 // if this is a subarray, make a copy so we only
2044 // include the subarray region from the underlying buffer
2045 if (chunk.byteLength !== buf.byteLength) {
2046 var copy = new Uint8Array(chunk.byteLength);
2047 copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
2048 buf = copy.buffer;
2049 }
2050
2051 return buf;
2052 }
2053
2054 return chunk;
2055 });
2056}
2057
2058function BlobBuilderConstructor(ary, options) {
2059 options = options || {};
2060
2061 var bb = new BlobBuilder();
2062 mapArrayBufferViews(ary).forEach(function(part) {
2063 bb.append(part);
2064 });
2065
2066 return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
2067};
2068
2069function BlobConstructor(ary, options) {
2070 return new Blob(mapArrayBufferViews(ary), options || {});
2071};
2072
2073if (typeof Blob !== 'undefined') {
2074 BlobBuilderConstructor.prototype = Blob.prototype;
2075 BlobConstructor.prototype = Blob.prototype;
2076}
2077
2078module.exports = (function() {
2079 if (blobSupported) {
2080 return blobSupportsArrayBufferView ? Blob : BlobConstructor;
2081 } else if (blobBuilderSupported) {
2082 return BlobBuilderConstructor;
2083 } else {
2084 return undefined;
2085 }
2086})();
2087
2088},{}],34:[function(require,module,exports){
2089
2090},{}],35:[function(require,module,exports){
2091(function (Buffer){
2092/*!
2093 * The buffer module from node.js, for the browser.
2094 *
2095 * @author Feross Aboukhadijeh <https://feross.org>
2096 * @license MIT
2097 */
2098/* eslint-disable no-proto */
2099
2100'use strict'
2101
2102var base64 = require('base64-js')
2103var ieee754 = require('ieee754')
2104var customInspectSymbol =
2105 (typeof Symbol === 'function' && typeof Symbol.for === 'function')
2106 ? Symbol.for('nodejs.util.inspect.custom')
2107 : null
2108
2109exports.Buffer = Buffer
2110exports.SlowBuffer = SlowBuffer
2111exports.INSPECT_MAX_BYTES = 50
2112
2113var K_MAX_LENGTH = 0x7fffffff
2114exports.kMaxLength = K_MAX_LENGTH
2115
2116/**
2117 * If `Buffer.TYPED_ARRAY_SUPPORT`:
2118 * === true Use Uint8Array implementation (fastest)
2119 * === false Print warning and recommend using `buffer` v4.x which has an Object
2120 * implementation (most compatible, even IE6)
2121 *
2122 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
2123 * Opera 11.6+, iOS 4.2+.
2124 *
2125 * We report that the browser does not support typed arrays if the are not subclassable
2126 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
2127 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
2128 * for __proto__ and has a buggy typed array implementation.
2129 */
2130Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
2131
2132if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
2133 typeof console.error === 'function') {
2134 console.error(
2135 'This browser lacks typed array (Uint8Array) support which is required by ' +
2136 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
2137 )
2138}
2139
2140function typedArraySupport () {
2141 // Can typed array instances can be augmented?
2142 try {
2143 var arr = new Uint8Array(1)
2144 var proto = { foo: function () { return 42 } }
2145 Object.setPrototypeOf(proto, Uint8Array.prototype)
2146 Object.setPrototypeOf(arr, proto)
2147 return arr.foo() === 42
2148 } catch (e) {
2149 return false
2150 }
2151}
2152
2153Object.defineProperty(Buffer.prototype, 'parent', {
2154 enumerable: true,
2155 get: function () {
2156 if (!Buffer.isBuffer(this)) return undefined
2157 return this.buffer
2158 }
2159})
2160
2161Object.defineProperty(Buffer.prototype, 'offset', {
2162 enumerable: true,
2163 get: function () {
2164 if (!Buffer.isBuffer(this)) return undefined
2165 return this.byteOffset
2166 }
2167})
2168
2169function createBuffer (length) {
2170 if (length > K_MAX_LENGTH) {
2171 throw new RangeError('The value "' + length + '" is invalid for option "size"')
2172 }
2173 // Return an augmented `Uint8Array` instance
2174 var buf = new Uint8Array(length)
2175 Object.setPrototypeOf(buf, Buffer.prototype)
2176 return buf
2177}
2178
2179/**
2180 * The Buffer constructor returns instances of `Uint8Array` that have their
2181 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
2182 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
2183 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
2184 * returns a single octet.
2185 *
2186 * The `Uint8Array` prototype remains unmodified.
2187 */
2188
2189function Buffer (arg, encodingOrOffset, length) {
2190 // Common case.
2191 if (typeof arg === 'number') {
2192 if (typeof encodingOrOffset === 'string') {
2193 throw new TypeError(
2194 'The "string" argument must be of type string. Received type number'
2195 )
2196 }
2197 return allocUnsafe(arg)
2198 }
2199 return from(arg, encodingOrOffset, length)
2200}
2201
2202// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
2203if (typeof Symbol !== 'undefined' && Symbol.species != null &&
2204 Buffer[Symbol.species] === Buffer) {
2205 Object.defineProperty(Buffer, Symbol.species, {
2206 value: null,
2207 configurable: true,
2208 enumerable: false,
2209 writable: false
2210 })
2211}
2212
2213Buffer.poolSize = 8192 // not used by this implementation
2214
2215function from (value, encodingOrOffset, length) {
2216 if (typeof value === 'string') {
2217 return fromString(value, encodingOrOffset)
2218 }
2219
2220 if (ArrayBuffer.isView(value)) {
2221 return fromArrayLike(value)
2222 }
2223
2224 if (value == null) {
2225 throw new TypeError(
2226 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
2227 'or Array-like Object. Received type ' + (typeof value)
2228 )
2229 }
2230
2231 if (isInstance(value, ArrayBuffer) ||
2232 (value && isInstance(value.buffer, ArrayBuffer))) {
2233 return fromArrayBuffer(value, encodingOrOffset, length)
2234 }
2235
2236 if (typeof SharedArrayBuffer !== 'undefined' &&
2237 (isInstance(value, SharedArrayBuffer) ||
2238 (value && isInstance(value.buffer, SharedArrayBuffer)))) {
2239 return fromArrayBuffer(value, encodingOrOffset, length)
2240 }
2241
2242 if (typeof value === 'number') {
2243 throw new TypeError(
2244 'The "value" argument must not be of type number. Received type number'
2245 )
2246 }
2247
2248 var valueOf = value.valueOf && value.valueOf()
2249 if (valueOf != null && valueOf !== value) {
2250 return Buffer.from(valueOf, encodingOrOffset, length)
2251 }
2252
2253 var b = fromObject(value)
2254 if (b) return b
2255
2256 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
2257 typeof value[Symbol.toPrimitive] === 'function') {
2258 return Buffer.from(
2259 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
2260 )
2261 }
2262
2263 throw new TypeError(
2264 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
2265 'or Array-like Object. Received type ' + (typeof value)
2266 )
2267}
2268
2269/**
2270 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
2271 * if value is a number.
2272 * Buffer.from(str[, encoding])
2273 * Buffer.from(array)
2274 * Buffer.from(buffer)
2275 * Buffer.from(arrayBuffer[, byteOffset[, length]])
2276 **/
2277Buffer.from = function (value, encodingOrOffset, length) {
2278 return from(value, encodingOrOffset, length)
2279}
2280
2281// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
2282// https://github.com/feross/buffer/pull/148
2283Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
2284Object.setPrototypeOf(Buffer, Uint8Array)
2285
2286function assertSize (size) {
2287 if (typeof size !== 'number') {
2288 throw new TypeError('"size" argument must be of type number')
2289 } else if (size < 0) {
2290 throw new RangeError('The value "' + size + '" is invalid for option "size"')
2291 }
2292}
2293
2294function alloc (size, fill, encoding) {
2295 assertSize(size)
2296 if (size <= 0) {
2297 return createBuffer(size)
2298 }
2299 if (fill !== undefined) {
2300 // Only pay attention to encoding if it's a string. This
2301 // prevents accidentally sending in a number that would
2302 // be interpretted as a start offset.
2303 return typeof encoding === 'string'
2304 ? createBuffer(size).fill(fill, encoding)
2305 : createBuffer(size).fill(fill)
2306 }
2307 return createBuffer(size)
2308}
2309
2310/**
2311 * Creates a new filled Buffer instance.
2312 * alloc(size[, fill[, encoding]])
2313 **/
2314Buffer.alloc = function (size, fill, encoding) {
2315 return alloc(size, fill, encoding)
2316}
2317
2318function allocUnsafe (size) {
2319 assertSize(size)
2320 return createBuffer(size < 0 ? 0 : checked(size) | 0)
2321}
2322
2323/**
2324 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
2325 * */
2326Buffer.allocUnsafe = function (size) {
2327 return allocUnsafe(size)
2328}
2329/**
2330 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
2331 */
2332Buffer.allocUnsafeSlow = function (size) {
2333 return allocUnsafe(size)
2334}
2335
2336function fromString (string, encoding) {
2337 if (typeof encoding !== 'string' || encoding === '') {
2338 encoding = 'utf8'
2339 }
2340
2341 if (!Buffer.isEncoding(encoding)) {
2342 throw new TypeError('Unknown encoding: ' + encoding)
2343 }
2344
2345 var length = byteLength(string, encoding) | 0
2346 var buf = createBuffer(length)
2347
2348 var actual = buf.write(string, encoding)
2349
2350 if (actual !== length) {
2351 // Writing a hex string, for example, that contains invalid characters will
2352 // cause everything after the first invalid character to be ignored. (e.g.
2353 // 'abxxcd' will be treated as 'ab')
2354 buf = buf.slice(0, actual)
2355 }
2356
2357 return buf
2358}
2359
2360function fromArrayLike (array) {
2361 var length = array.length < 0 ? 0 : checked(array.length) | 0
2362 var buf = createBuffer(length)
2363 for (var i = 0; i < length; i += 1) {
2364 buf[i] = array[i] & 255
2365 }
2366 return buf
2367}
2368
2369function fromArrayBuffer (array, byteOffset, length) {
2370 if (byteOffset < 0 || array.byteLength < byteOffset) {
2371 throw new RangeError('"offset" is outside of buffer bounds')
2372 }
2373
2374 if (array.byteLength < byteOffset + (length || 0)) {
2375 throw new RangeError('"length" is outside of buffer bounds')
2376 }
2377
2378 var buf
2379 if (byteOffset === undefined && length === undefined) {
2380 buf = new Uint8Array(array)
2381 } else if (length === undefined) {
2382 buf = new Uint8Array(array, byteOffset)
2383 } else {
2384 buf = new Uint8Array(array, byteOffset, length)
2385 }
2386
2387 // Return an augmented `Uint8Array` instance
2388 Object.setPrototypeOf(buf, Buffer.prototype)
2389
2390 return buf
2391}
2392
2393function fromObject (obj) {
2394 if (Buffer.isBuffer(obj)) {
2395 var len = checked(obj.length) | 0
2396 var buf = createBuffer(len)
2397
2398 if (buf.length === 0) {
2399 return buf
2400 }
2401
2402 obj.copy(buf, 0, 0, len)
2403 return buf
2404 }
2405
2406 if (obj.length !== undefined) {
2407 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
2408 return createBuffer(0)
2409 }
2410 return fromArrayLike(obj)
2411 }
2412
2413 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
2414 return fromArrayLike(obj.data)
2415 }
2416}
2417
2418function checked (length) {
2419 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
2420 // length is NaN (which is otherwise coerced to zero.)
2421 if (length >= K_MAX_LENGTH) {
2422 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
2423 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
2424 }
2425 return length | 0
2426}
2427
2428function SlowBuffer (length) {
2429 if (+length != length) { // eslint-disable-line eqeqeq
2430 length = 0
2431 }
2432 return Buffer.alloc(+length)
2433}
2434
2435Buffer.isBuffer = function isBuffer (b) {
2436 return b != null && b._isBuffer === true &&
2437 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
2438}
2439
2440Buffer.compare = function compare (a, b) {
2441 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
2442 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
2443 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
2444 throw new TypeError(
2445 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
2446 )
2447 }
2448
2449 if (a === b) return 0
2450
2451 var x = a.length
2452 var y = b.length
2453
2454 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2455 if (a[i] !== b[i]) {
2456 x = a[i]
2457 y = b[i]
2458 break
2459 }
2460 }
2461
2462 if (x < y) return -1
2463 if (y < x) return 1
2464 return 0
2465}
2466
2467Buffer.isEncoding = function isEncoding (encoding) {
2468 switch (String(encoding).toLowerCase()) {
2469 case 'hex':
2470 case 'utf8':
2471 case 'utf-8':
2472 case 'ascii':
2473 case 'latin1':
2474 case 'binary':
2475 case 'base64':
2476 case 'ucs2':
2477 case 'ucs-2':
2478 case 'utf16le':
2479 case 'utf-16le':
2480 return true
2481 default:
2482 return false
2483 }
2484}
2485
2486Buffer.concat = function concat (list, length) {
2487 if (!Array.isArray(list)) {
2488 throw new TypeError('"list" argument must be an Array of Buffers')
2489 }
2490
2491 if (list.length === 0) {
2492 return Buffer.alloc(0)
2493 }
2494
2495 var i
2496 if (length === undefined) {
2497 length = 0
2498 for (i = 0; i < list.length; ++i) {
2499 length += list[i].length
2500 }
2501 }
2502
2503 var buffer = Buffer.allocUnsafe(length)
2504 var pos = 0
2505 for (i = 0; i < list.length; ++i) {
2506 var buf = list[i]
2507 if (isInstance(buf, Uint8Array)) {
2508 buf = Buffer.from(buf)
2509 }
2510 if (!Buffer.isBuffer(buf)) {
2511 throw new TypeError('"list" argument must be an Array of Buffers')
2512 }
2513 buf.copy(buffer, pos)
2514 pos += buf.length
2515 }
2516 return buffer
2517}
2518
2519function byteLength (string, encoding) {
2520 if (Buffer.isBuffer(string)) {
2521 return string.length
2522 }
2523 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
2524 return string.byteLength
2525 }
2526 if (typeof string !== 'string') {
2527 throw new TypeError(
2528 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
2529 'Received type ' + typeof string
2530 )
2531 }
2532
2533 var len = string.length
2534 var mustMatch = (arguments.length > 2 && arguments[2] === true)
2535 if (!mustMatch && len === 0) return 0
2536
2537 // Use a for loop to avoid recursion
2538 var loweredCase = false
2539 for (;;) {
2540 switch (encoding) {
2541 case 'ascii':
2542 case 'latin1':
2543 case 'binary':
2544 return len
2545 case 'utf8':
2546 case 'utf-8':
2547 return utf8ToBytes(string).length
2548 case 'ucs2':
2549 case 'ucs-2':
2550 case 'utf16le':
2551 case 'utf-16le':
2552 return len * 2
2553 case 'hex':
2554 return len >>> 1
2555 case 'base64':
2556 return base64ToBytes(string).length
2557 default:
2558 if (loweredCase) {
2559 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
2560 }
2561 encoding = ('' + encoding).toLowerCase()
2562 loweredCase = true
2563 }
2564 }
2565}
2566Buffer.byteLength = byteLength
2567
2568function slowToString (encoding, start, end) {
2569 var loweredCase = false
2570
2571 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2572 // property of a typed array.
2573
2574 // This behaves neither like String nor Uint8Array in that we set start/end
2575 // to their upper/lower bounds if the value passed is out of range.
2576 // undefined is handled specially as per ECMA-262 6th Edition,
2577 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2578 if (start === undefined || start < 0) {
2579 start = 0
2580 }
2581 // Return early if start > this.length. Done here to prevent potential uint32
2582 // coercion fail below.
2583 if (start > this.length) {
2584 return ''
2585 }
2586
2587 if (end === undefined || end > this.length) {
2588 end = this.length
2589 }
2590
2591 if (end <= 0) {
2592 return ''
2593 }
2594
2595 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
2596 end >>>= 0
2597 start >>>= 0
2598
2599 if (end <= start) {
2600 return ''
2601 }
2602
2603 if (!encoding) encoding = 'utf8'
2604
2605 while (true) {
2606 switch (encoding) {
2607 case 'hex':
2608 return hexSlice(this, start, end)
2609
2610 case 'utf8':
2611 case 'utf-8':
2612 return utf8Slice(this, start, end)
2613
2614 case 'ascii':
2615 return asciiSlice(this, start, end)
2616
2617 case 'latin1':
2618 case 'binary':
2619 return latin1Slice(this, start, end)
2620
2621 case 'base64':
2622 return base64Slice(this, start, end)
2623
2624 case 'ucs2':
2625 case 'ucs-2':
2626 case 'utf16le':
2627 case 'utf-16le':
2628 return utf16leSlice(this, start, end)
2629
2630 default:
2631 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2632 encoding = (encoding + '').toLowerCase()
2633 loweredCase = true
2634 }
2635 }
2636}
2637
2638// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
2639// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
2640// reliably in a browserify context because there could be multiple different
2641// copies of the 'buffer' package in use. This method works even for Buffer
2642// instances that were created from another copy of the `buffer` package.
2643// See: https://github.com/feross/buffer/issues/154
2644Buffer.prototype._isBuffer = true
2645
2646function swap (b, n, m) {
2647 var i = b[n]
2648 b[n] = b[m]
2649 b[m] = i
2650}
2651
2652Buffer.prototype.swap16 = function swap16 () {
2653 var len = this.length
2654 if (len % 2 !== 0) {
2655 throw new RangeError('Buffer size must be a multiple of 16-bits')
2656 }
2657 for (var i = 0; i < len; i += 2) {
2658 swap(this, i, i + 1)
2659 }
2660 return this
2661}
2662
2663Buffer.prototype.swap32 = function swap32 () {
2664 var len = this.length
2665 if (len % 4 !== 0) {
2666 throw new RangeError('Buffer size must be a multiple of 32-bits')
2667 }
2668 for (var i = 0; i < len; i += 4) {
2669 swap(this, i, i + 3)
2670 swap(this, i + 1, i + 2)
2671 }
2672 return this
2673}
2674
2675Buffer.prototype.swap64 = function swap64 () {
2676 var len = this.length
2677 if (len % 8 !== 0) {
2678 throw new RangeError('Buffer size must be a multiple of 64-bits')
2679 }
2680 for (var i = 0; i < len; i += 8) {
2681 swap(this, i, i + 7)
2682 swap(this, i + 1, i + 6)
2683 swap(this, i + 2, i + 5)
2684 swap(this, i + 3, i + 4)
2685 }
2686 return this
2687}
2688
2689Buffer.prototype.toString = function toString () {
2690 var length = this.length
2691 if (length === 0) return ''
2692 if (arguments.length === 0) return utf8Slice(this, 0, length)
2693 return slowToString.apply(this, arguments)
2694}
2695
2696Buffer.prototype.toLocaleString = Buffer.prototype.toString
2697
2698Buffer.prototype.equals = function equals (b) {
2699 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2700 if (this === b) return true
2701 return Buffer.compare(this, b) === 0
2702}
2703
2704Buffer.prototype.inspect = function inspect () {
2705 var str = ''
2706 var max = exports.INSPECT_MAX_BYTES
2707 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
2708 if (this.length > max) str += ' ... '
2709 return '<Buffer ' + str + '>'
2710}
2711if (customInspectSymbol) {
2712 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
2713}
2714
2715Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2716 if (isInstance(target, Uint8Array)) {
2717 target = Buffer.from(target, target.offset, target.byteLength)
2718 }
2719 if (!Buffer.isBuffer(target)) {
2720 throw new TypeError(
2721 'The "target" argument must be one of type Buffer or Uint8Array. ' +
2722 'Received type ' + (typeof target)
2723 )
2724 }
2725
2726 if (start === undefined) {
2727 start = 0
2728 }
2729 if (end === undefined) {
2730 end = target ? target.length : 0
2731 }
2732 if (thisStart === undefined) {
2733 thisStart = 0
2734 }
2735 if (thisEnd === undefined) {
2736 thisEnd = this.length
2737 }
2738
2739 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2740 throw new RangeError('out of range index')
2741 }
2742
2743 if (thisStart >= thisEnd && start >= end) {
2744 return 0
2745 }
2746 if (thisStart >= thisEnd) {
2747 return -1
2748 }
2749 if (start >= end) {
2750 return 1
2751 }
2752
2753 start >>>= 0
2754 end >>>= 0
2755 thisStart >>>= 0
2756 thisEnd >>>= 0
2757
2758 if (this === target) return 0
2759
2760 var x = thisEnd - thisStart
2761 var y = end - start
2762 var len = Math.min(x, y)
2763
2764 var thisCopy = this.slice(thisStart, thisEnd)
2765 var targetCopy = target.slice(start, end)
2766
2767 for (var i = 0; i < len; ++i) {
2768 if (thisCopy[i] !== targetCopy[i]) {
2769 x = thisCopy[i]
2770 y = targetCopy[i]
2771 break
2772 }
2773 }
2774
2775 if (x < y) return -1
2776 if (y < x) return 1
2777 return 0
2778}
2779
2780// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2781// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2782//
2783// Arguments:
2784// - buffer - a Buffer to search
2785// - val - a string, Buffer, or number
2786// - byteOffset - an index into `buffer`; will be clamped to an int32
2787// - encoding - an optional encoding, relevant is val is a string
2788// - dir - true for indexOf, false for lastIndexOf
2789function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2790 // Empty buffer means no match
2791 if (buffer.length === 0) return -1
2792
2793 // Normalize byteOffset
2794 if (typeof byteOffset === 'string') {
2795 encoding = byteOffset
2796 byteOffset = 0
2797 } else if (byteOffset > 0x7fffffff) {
2798 byteOffset = 0x7fffffff
2799 } else if (byteOffset < -0x80000000) {
2800 byteOffset = -0x80000000
2801 }
2802 byteOffset = +byteOffset // Coerce to Number.
2803 if (numberIsNaN(byteOffset)) {
2804 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2805 byteOffset = dir ? 0 : (buffer.length - 1)
2806 }
2807
2808 // Normalize byteOffset: negative offsets start from the end of the buffer
2809 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2810 if (byteOffset >= buffer.length) {
2811 if (dir) return -1
2812 else byteOffset = buffer.length - 1
2813 } else if (byteOffset < 0) {
2814 if (dir) byteOffset = 0
2815 else return -1
2816 }
2817
2818 // Normalize val
2819 if (typeof val === 'string') {
2820 val = Buffer.from(val, encoding)
2821 }
2822
2823 // Finally, search either indexOf (if dir is true) or lastIndexOf
2824 if (Buffer.isBuffer(val)) {
2825 // Special case: looking for empty string/buffer always fails
2826 if (val.length === 0) {
2827 return -1
2828 }
2829 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2830 } else if (typeof val === 'number') {
2831 val = val & 0xFF // Search for a byte value [0-255]
2832 if (typeof Uint8Array.prototype.indexOf === 'function') {
2833 if (dir) {
2834 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2835 } else {
2836 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2837 }
2838 }
2839 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
2840 }
2841
2842 throw new TypeError('val must be string, number or Buffer')
2843}
2844
2845function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2846 var indexSize = 1
2847 var arrLength = arr.length
2848 var valLength = val.length
2849
2850 if (encoding !== undefined) {
2851 encoding = String(encoding).toLowerCase()
2852 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2853 encoding === 'utf16le' || encoding === 'utf-16le') {
2854 if (arr.length < 2 || val.length < 2) {
2855 return -1
2856 }
2857 indexSize = 2
2858 arrLength /= 2
2859 valLength /= 2
2860 byteOffset /= 2
2861 }
2862 }
2863
2864 function read (buf, i) {
2865 if (indexSize === 1) {
2866 return buf[i]
2867 } else {
2868 return buf.readUInt16BE(i * indexSize)
2869 }
2870 }
2871
2872 var i
2873 if (dir) {
2874 var foundIndex = -1
2875 for (i = byteOffset; i < arrLength; i++) {
2876 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2877 if (foundIndex === -1) foundIndex = i
2878 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2879 } else {
2880 if (foundIndex !== -1) i -= i - foundIndex
2881 foundIndex = -1
2882 }
2883 }
2884 } else {
2885 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2886 for (i = byteOffset; i >= 0; i--) {
2887 var found = true
2888 for (var j = 0; j < valLength; j++) {
2889 if (read(arr, i + j) !== read(val, j)) {
2890 found = false
2891 break
2892 }
2893 }
2894 if (found) return i
2895 }
2896 }
2897
2898 return -1
2899}
2900
2901Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2902 return this.indexOf(val, byteOffset, encoding) !== -1
2903}
2904
2905Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2906 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2907}
2908
2909Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2910 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2911}
2912
2913function hexWrite (buf, string, offset, length) {
2914 offset = Number(offset) || 0
2915 var remaining = buf.length - offset
2916 if (!length) {
2917 length = remaining
2918 } else {
2919 length = Number(length)
2920 if (length > remaining) {
2921 length = remaining
2922 }
2923 }
2924
2925 var strLen = string.length
2926
2927 if (length > strLen / 2) {
2928 length = strLen / 2
2929 }
2930 for (var i = 0; i < length; ++i) {
2931 var parsed = parseInt(string.substr(i * 2, 2), 16)
2932 if (numberIsNaN(parsed)) return i
2933 buf[offset + i] = parsed
2934 }
2935 return i
2936}
2937
2938function utf8Write (buf, string, offset, length) {
2939 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2940}
2941
2942function asciiWrite (buf, string, offset, length) {
2943 return blitBuffer(asciiToBytes(string), buf, offset, length)
2944}
2945
2946function latin1Write (buf, string, offset, length) {
2947 return asciiWrite(buf, string, offset, length)
2948}
2949
2950function base64Write (buf, string, offset, length) {
2951 return blitBuffer(base64ToBytes(string), buf, offset, length)
2952}
2953
2954function ucs2Write (buf, string, offset, length) {
2955 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2956}
2957
2958Buffer.prototype.write = function write (string, offset, length, encoding) {
2959 // Buffer#write(string)
2960 if (offset === undefined) {
2961 encoding = 'utf8'
2962 length = this.length
2963 offset = 0
2964 // Buffer#write(string, encoding)
2965 } else if (length === undefined && typeof offset === 'string') {
2966 encoding = offset
2967 length = this.length
2968 offset = 0
2969 // Buffer#write(string, offset[, length][, encoding])
2970 } else if (isFinite(offset)) {
2971 offset = offset >>> 0
2972 if (isFinite(length)) {
2973 length = length >>> 0
2974 if (encoding === undefined) encoding = 'utf8'
2975 } else {
2976 encoding = length
2977 length = undefined
2978 }
2979 } else {
2980 throw new Error(
2981 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2982 )
2983 }
2984
2985 var remaining = this.length - offset
2986 if (length === undefined || length > remaining) length = remaining
2987
2988 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2989 throw new RangeError('Attempt to write outside buffer bounds')
2990 }
2991
2992 if (!encoding) encoding = 'utf8'
2993
2994 var loweredCase = false
2995 for (;;) {
2996 switch (encoding) {
2997 case 'hex':
2998 return hexWrite(this, string, offset, length)
2999
3000 case 'utf8':
3001 case 'utf-8':
3002 return utf8Write(this, string, offset, length)
3003
3004 case 'ascii':
3005 return asciiWrite(this, string, offset, length)
3006
3007 case 'latin1':
3008 case 'binary':
3009 return latin1Write(this, string, offset, length)
3010
3011 case 'base64':
3012 // Warning: maxLength not taken into account in base64Write
3013 return base64Write(this, string, offset, length)
3014
3015 case 'ucs2':
3016 case 'ucs-2':
3017 case 'utf16le':
3018 case 'utf-16le':
3019 return ucs2Write(this, string, offset, length)
3020
3021 default:
3022 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
3023 encoding = ('' + encoding).toLowerCase()
3024 loweredCase = true
3025 }
3026 }
3027}
3028
3029Buffer.prototype.toJSON = function toJSON () {
3030 return {
3031 type: 'Buffer',
3032 data: Array.prototype.slice.call(this._arr || this, 0)
3033 }
3034}
3035
3036function base64Slice (buf, start, end) {
3037 if (start === 0 && end === buf.length) {
3038 return base64.fromByteArray(buf)
3039 } else {
3040 return base64.fromByteArray(buf.slice(start, end))
3041 }
3042}
3043
3044function utf8Slice (buf, start, end) {
3045 end = Math.min(buf.length, end)
3046 var res = []
3047
3048 var i = start
3049 while (i < end) {
3050 var firstByte = buf[i]
3051 var codePoint = null
3052 var bytesPerSequence = (firstByte > 0xEF) ? 4
3053 : (firstByte > 0xDF) ? 3
3054 : (firstByte > 0xBF) ? 2
3055 : 1
3056
3057 if (i + bytesPerSequence <= end) {
3058 var secondByte, thirdByte, fourthByte, tempCodePoint
3059
3060 switch (bytesPerSequence) {
3061 case 1:
3062 if (firstByte < 0x80) {
3063 codePoint = firstByte
3064 }
3065 break
3066 case 2:
3067 secondByte = buf[i + 1]
3068 if ((secondByte & 0xC0) === 0x80) {
3069 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
3070 if (tempCodePoint > 0x7F) {
3071 codePoint = tempCodePoint
3072 }
3073 }
3074 break
3075 case 3:
3076 secondByte = buf[i + 1]
3077 thirdByte = buf[i + 2]
3078 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
3079 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
3080 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
3081 codePoint = tempCodePoint
3082 }
3083 }
3084 break
3085 case 4:
3086 secondByte = buf[i + 1]
3087 thirdByte = buf[i + 2]
3088 fourthByte = buf[i + 3]
3089 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
3090 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
3091 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
3092 codePoint = tempCodePoint
3093 }
3094 }
3095 }
3096 }
3097
3098 if (codePoint === null) {
3099 // we did not generate a valid codePoint so insert a
3100 // replacement char (U+FFFD) and advance only 1 byte
3101 codePoint = 0xFFFD
3102 bytesPerSequence = 1
3103 } else if (codePoint > 0xFFFF) {
3104 // encode to utf16 (surrogate pair dance)
3105 codePoint -= 0x10000
3106 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
3107 codePoint = 0xDC00 | codePoint & 0x3FF
3108 }
3109
3110 res.push(codePoint)
3111 i += bytesPerSequence
3112 }
3113
3114 return decodeCodePointsArray(res)
3115}
3116
3117// Based on http://stackoverflow.com/a/22747272/680742, the browser with
3118// the lowest limit is Chrome, with 0x10000 args.
3119// We go 1 magnitude less, for safety
3120var MAX_ARGUMENTS_LENGTH = 0x1000
3121
3122function decodeCodePointsArray (codePoints) {
3123 var len = codePoints.length
3124 if (len <= MAX_ARGUMENTS_LENGTH) {
3125 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
3126 }
3127
3128 // Decode in chunks to avoid "call stack size exceeded".
3129 var res = ''
3130 var i = 0
3131 while (i < len) {
3132 res += String.fromCharCode.apply(
3133 String,
3134 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
3135 )
3136 }
3137 return res
3138}
3139
3140function asciiSlice (buf, start, end) {
3141 var ret = ''
3142 end = Math.min(buf.length, end)
3143
3144 for (var i = start; i < end; ++i) {
3145 ret += String.fromCharCode(buf[i] & 0x7F)
3146 }
3147 return ret
3148}
3149
3150function latin1Slice (buf, start, end) {
3151 var ret = ''
3152 end = Math.min(buf.length, end)
3153
3154 for (var i = start; i < end; ++i) {
3155 ret += String.fromCharCode(buf[i])
3156 }
3157 return ret
3158}
3159
3160function hexSlice (buf, start, end) {
3161 var len = buf.length
3162
3163 if (!start || start < 0) start = 0
3164 if (!end || end < 0 || end > len) end = len
3165
3166 var out = ''
3167 for (var i = start; i < end; ++i) {
3168 out += hexSliceLookupTable[buf[i]]
3169 }
3170 return out
3171}
3172
3173function utf16leSlice (buf, start, end) {
3174 var bytes = buf.slice(start, end)
3175 var res = ''
3176 for (var i = 0; i < bytes.length; i += 2) {
3177 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
3178 }
3179 return res
3180}
3181
3182Buffer.prototype.slice = function slice (start, end) {
3183 var len = this.length
3184 start = ~~start
3185 end = end === undefined ? len : ~~end
3186
3187 if (start < 0) {
3188 start += len
3189 if (start < 0) start = 0
3190 } else if (start > len) {
3191 start = len
3192 }
3193
3194 if (end < 0) {
3195 end += len
3196 if (end < 0) end = 0
3197 } else if (end > len) {
3198 end = len
3199 }
3200
3201 if (end < start) end = start
3202
3203 var newBuf = this.subarray(start, end)
3204 // Return an augmented `Uint8Array` instance
3205 Object.setPrototypeOf(newBuf, Buffer.prototype)
3206
3207 return newBuf
3208}
3209
3210/*
3211 * Need to make sure that buffer isn't trying to write out of bounds.
3212 */
3213function checkOffset (offset, ext, length) {
3214 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
3215 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
3216}
3217
3218Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
3219 offset = offset >>> 0
3220 byteLength = byteLength >>> 0
3221 if (!noAssert) checkOffset(offset, byteLength, this.length)
3222
3223 var val = this[offset]
3224 var mul = 1
3225 var i = 0
3226 while (++i < byteLength && (mul *= 0x100)) {
3227 val += this[offset + i] * mul
3228 }
3229
3230 return val
3231}
3232
3233Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
3234 offset = offset >>> 0
3235 byteLength = byteLength >>> 0
3236 if (!noAssert) {
3237 checkOffset(offset, byteLength, this.length)
3238 }
3239
3240 var val = this[offset + --byteLength]
3241 var mul = 1
3242 while (byteLength > 0 && (mul *= 0x100)) {
3243 val += this[offset + --byteLength] * mul
3244 }
3245
3246 return val
3247}
3248
3249Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
3250 offset = offset >>> 0
3251 if (!noAssert) checkOffset(offset, 1, this.length)
3252 return this[offset]
3253}
3254
3255Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
3256 offset = offset >>> 0
3257 if (!noAssert) checkOffset(offset, 2, this.length)
3258 return this[offset] | (this[offset + 1] << 8)
3259}
3260
3261Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
3262 offset = offset >>> 0
3263 if (!noAssert) checkOffset(offset, 2, this.length)
3264 return (this[offset] << 8) | this[offset + 1]
3265}
3266
3267Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
3268 offset = offset >>> 0
3269 if (!noAssert) checkOffset(offset, 4, this.length)
3270
3271 return ((this[offset]) |
3272 (this[offset + 1] << 8) |
3273 (this[offset + 2] << 16)) +
3274 (this[offset + 3] * 0x1000000)
3275}
3276
3277Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
3278 offset = offset >>> 0
3279 if (!noAssert) checkOffset(offset, 4, this.length)
3280
3281 return (this[offset] * 0x1000000) +
3282 ((this[offset + 1] << 16) |
3283 (this[offset + 2] << 8) |
3284 this[offset + 3])
3285}
3286
3287Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
3288 offset = offset >>> 0
3289 byteLength = byteLength >>> 0
3290 if (!noAssert) checkOffset(offset, byteLength, this.length)
3291
3292 var val = this[offset]
3293 var mul = 1
3294 var i = 0
3295 while (++i < byteLength && (mul *= 0x100)) {
3296 val += this[offset + i] * mul
3297 }
3298 mul *= 0x80
3299
3300 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3301
3302 return val
3303}
3304
3305Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
3306 offset = offset >>> 0
3307 byteLength = byteLength >>> 0
3308 if (!noAssert) checkOffset(offset, byteLength, this.length)
3309
3310 var i = byteLength
3311 var mul = 1
3312 var val = this[offset + --i]
3313 while (i > 0 && (mul *= 0x100)) {
3314 val += this[offset + --i] * mul
3315 }
3316 mul *= 0x80
3317
3318 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
3319
3320 return val
3321}
3322
3323Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
3324 offset = offset >>> 0
3325 if (!noAssert) checkOffset(offset, 1, this.length)
3326 if (!(this[offset] & 0x80)) return (this[offset])
3327 return ((0xff - this[offset] + 1) * -1)
3328}
3329
3330Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
3331 offset = offset >>> 0
3332 if (!noAssert) checkOffset(offset, 2, this.length)
3333 var val = this[offset] | (this[offset + 1] << 8)
3334 return (val & 0x8000) ? val | 0xFFFF0000 : val
3335}
3336
3337Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
3338 offset = offset >>> 0
3339 if (!noAssert) checkOffset(offset, 2, this.length)
3340 var val = this[offset + 1] | (this[offset] << 8)
3341 return (val & 0x8000) ? val | 0xFFFF0000 : val
3342}
3343
3344Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
3345 offset = offset >>> 0
3346 if (!noAssert) checkOffset(offset, 4, this.length)
3347
3348 return (this[offset]) |
3349 (this[offset + 1] << 8) |
3350 (this[offset + 2] << 16) |
3351 (this[offset + 3] << 24)
3352}
3353
3354Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
3355 offset = offset >>> 0
3356 if (!noAssert) checkOffset(offset, 4, this.length)
3357
3358 return (this[offset] << 24) |
3359 (this[offset + 1] << 16) |
3360 (this[offset + 2] << 8) |
3361 (this[offset + 3])
3362}
3363
3364Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
3365 offset = offset >>> 0
3366 if (!noAssert) checkOffset(offset, 4, this.length)
3367 return ieee754.read(this, offset, true, 23, 4)
3368}
3369
3370Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
3371 offset = offset >>> 0
3372 if (!noAssert) checkOffset(offset, 4, this.length)
3373 return ieee754.read(this, offset, false, 23, 4)
3374}
3375
3376Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
3377 offset = offset >>> 0
3378 if (!noAssert) checkOffset(offset, 8, this.length)
3379 return ieee754.read(this, offset, true, 52, 8)
3380}
3381
3382Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
3383 offset = offset >>> 0
3384 if (!noAssert) checkOffset(offset, 8, this.length)
3385 return ieee754.read(this, offset, false, 52, 8)
3386}
3387
3388function checkInt (buf, value, offset, ext, max, min) {
3389 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
3390 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
3391 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3392}
3393
3394Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
3395 value = +value
3396 offset = offset >>> 0
3397 byteLength = byteLength >>> 0
3398 if (!noAssert) {
3399 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3400 checkInt(this, value, offset, byteLength, maxBytes, 0)
3401 }
3402
3403 var mul = 1
3404 var i = 0
3405 this[offset] = value & 0xFF
3406 while (++i < byteLength && (mul *= 0x100)) {
3407 this[offset + i] = (value / mul) & 0xFF
3408 }
3409
3410 return offset + byteLength
3411}
3412
3413Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
3414 value = +value
3415 offset = offset >>> 0
3416 byteLength = byteLength >>> 0
3417 if (!noAssert) {
3418 var maxBytes = Math.pow(2, 8 * byteLength) - 1
3419 checkInt(this, value, offset, byteLength, maxBytes, 0)
3420 }
3421
3422 var i = byteLength - 1
3423 var mul = 1
3424 this[offset + i] = value & 0xFF
3425 while (--i >= 0 && (mul *= 0x100)) {
3426 this[offset + i] = (value / mul) & 0xFF
3427 }
3428
3429 return offset + byteLength
3430}
3431
3432Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
3433 value = +value
3434 offset = offset >>> 0
3435 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
3436 this[offset] = (value & 0xff)
3437 return offset + 1
3438}
3439
3440Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
3441 value = +value
3442 offset = offset >>> 0
3443 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3444 this[offset] = (value & 0xff)
3445 this[offset + 1] = (value >>> 8)
3446 return offset + 2
3447}
3448
3449Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
3450 value = +value
3451 offset = offset >>> 0
3452 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
3453 this[offset] = (value >>> 8)
3454 this[offset + 1] = (value & 0xff)
3455 return offset + 2
3456}
3457
3458Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
3459 value = +value
3460 offset = offset >>> 0
3461 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3462 this[offset + 3] = (value >>> 24)
3463 this[offset + 2] = (value >>> 16)
3464 this[offset + 1] = (value >>> 8)
3465 this[offset] = (value & 0xff)
3466 return offset + 4
3467}
3468
3469Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
3470 value = +value
3471 offset = offset >>> 0
3472 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
3473 this[offset] = (value >>> 24)
3474 this[offset + 1] = (value >>> 16)
3475 this[offset + 2] = (value >>> 8)
3476 this[offset + 3] = (value & 0xff)
3477 return offset + 4
3478}
3479
3480Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
3481 value = +value
3482 offset = offset >>> 0
3483 if (!noAssert) {
3484 var limit = Math.pow(2, (8 * byteLength) - 1)
3485
3486 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3487 }
3488
3489 var i = 0
3490 var mul = 1
3491 var sub = 0
3492 this[offset] = value & 0xFF
3493 while (++i < byteLength && (mul *= 0x100)) {
3494 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
3495 sub = 1
3496 }
3497 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3498 }
3499
3500 return offset + byteLength
3501}
3502
3503Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
3504 value = +value
3505 offset = offset >>> 0
3506 if (!noAssert) {
3507 var limit = Math.pow(2, (8 * byteLength) - 1)
3508
3509 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3510 }
3511
3512 var i = byteLength - 1
3513 var mul = 1
3514 var sub = 0
3515 this[offset + i] = value & 0xFF
3516 while (--i >= 0 && (mul *= 0x100)) {
3517 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3518 sub = 1
3519 }
3520 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3521 }
3522
3523 return offset + byteLength
3524}
3525
3526Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
3527 value = +value
3528 offset = offset >>> 0
3529 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
3530 if (value < 0) value = 0xff + value + 1
3531 this[offset] = (value & 0xff)
3532 return offset + 1
3533}
3534
3535Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
3536 value = +value
3537 offset = offset >>> 0
3538 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3539 this[offset] = (value & 0xff)
3540 this[offset + 1] = (value >>> 8)
3541 return offset + 2
3542}
3543
3544Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
3545 value = +value
3546 offset = offset >>> 0
3547 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3548 this[offset] = (value >>> 8)
3549 this[offset + 1] = (value & 0xff)
3550 return offset + 2
3551}
3552
3553Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
3554 value = +value
3555 offset = offset >>> 0
3556 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3557 this[offset] = (value & 0xff)
3558 this[offset + 1] = (value >>> 8)
3559 this[offset + 2] = (value >>> 16)
3560 this[offset + 3] = (value >>> 24)
3561 return offset + 4
3562}
3563
3564Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
3565 value = +value
3566 offset = offset >>> 0
3567 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3568 if (value < 0) value = 0xffffffff + value + 1
3569 this[offset] = (value >>> 24)
3570 this[offset + 1] = (value >>> 16)
3571 this[offset + 2] = (value >>> 8)
3572 this[offset + 3] = (value & 0xff)
3573 return offset + 4
3574}
3575
3576function checkIEEE754 (buf, value, offset, ext, max, min) {
3577 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3578 if (offset < 0) throw new RangeError('Index out of range')
3579}
3580
3581function writeFloat (buf, value, offset, littleEndian, noAssert) {
3582 value = +value
3583 offset = offset >>> 0
3584 if (!noAssert) {
3585 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3586 }
3587 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3588 return offset + 4
3589}
3590
3591Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
3592 return writeFloat(this, value, offset, true, noAssert)
3593}
3594
3595Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
3596 return writeFloat(this, value, offset, false, noAssert)
3597}
3598
3599function writeDouble (buf, value, offset, littleEndian, noAssert) {
3600 value = +value
3601 offset = offset >>> 0
3602 if (!noAssert) {
3603 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3604 }
3605 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3606 return offset + 8
3607}
3608
3609Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
3610 return writeDouble(this, value, offset, true, noAssert)
3611}
3612
3613Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
3614 return writeDouble(this, value, offset, false, noAssert)
3615}
3616
3617// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3618Buffer.prototype.copy = function copy (target, targetStart, start, end) {
3619 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
3620 if (!start) start = 0
3621 if (!end && end !== 0) end = this.length
3622 if (targetStart >= target.length) targetStart = target.length
3623 if (!targetStart) targetStart = 0
3624 if (end > 0 && end < start) end = start
3625
3626 // Copy 0 bytes; we're done
3627 if (end === start) return 0
3628 if (target.length === 0 || this.length === 0) return 0
3629
3630 // Fatal error conditions
3631 if (targetStart < 0) {
3632 throw new RangeError('targetStart out of bounds')
3633 }
3634 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
3635 if (end < 0) throw new RangeError('sourceEnd out of bounds')
3636
3637 // Are we oob?
3638 if (end > this.length) end = this.length
3639 if (target.length - targetStart < end - start) {
3640 end = target.length - targetStart + start
3641 }
3642
3643 var len = end - start
3644
3645 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
3646 // Use built-in when available, missing from IE11
3647 this.copyWithin(targetStart, start, end)
3648 } else if (this === target && start < targetStart && targetStart < end) {
3649 // descending copy from end
3650 for (var i = len - 1; i >= 0; --i) {
3651 target[i + targetStart] = this[i + start]
3652 }
3653 } else {
3654 Uint8Array.prototype.set.call(
3655 target,
3656 this.subarray(start, end),
3657 targetStart
3658 )
3659 }
3660
3661 return len
3662}
3663
3664// Usage:
3665// buffer.fill(number[, offset[, end]])
3666// buffer.fill(buffer[, offset[, end]])
3667// buffer.fill(string[, offset[, end]][, encoding])
3668Buffer.prototype.fill = function fill (val, start, end, encoding) {
3669 // Handle string cases:
3670 if (typeof val === 'string') {
3671 if (typeof start === 'string') {
3672 encoding = start
3673 start = 0
3674 end = this.length
3675 } else if (typeof end === 'string') {
3676 encoding = end
3677 end = this.length
3678 }
3679 if (encoding !== undefined && typeof encoding !== 'string') {
3680 throw new TypeError('encoding must be a string')
3681 }
3682 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3683 throw new TypeError('Unknown encoding: ' + encoding)
3684 }
3685 if (val.length === 1) {
3686 var code = val.charCodeAt(0)
3687 if ((encoding === 'utf8' && code < 128) ||
3688 encoding === 'latin1') {
3689 // Fast path: If `val` fits into a single byte, use that numeric value.
3690 val = code
3691 }
3692 }
3693 } else if (typeof val === 'number') {
3694 val = val & 255
3695 } else if (typeof val === 'boolean') {
3696 val = Number(val)
3697 }
3698
3699 // Invalid ranges are not set to a default, so can range check early.
3700 if (start < 0 || this.length < start || this.length < end) {
3701 throw new RangeError('Out of range index')
3702 }
3703
3704 if (end <= start) {
3705 return this
3706 }
3707
3708 start = start >>> 0
3709 end = end === undefined ? this.length : end >>> 0
3710
3711 if (!val) val = 0
3712
3713 var i
3714 if (typeof val === 'number') {
3715 for (i = start; i < end; ++i) {
3716 this[i] = val
3717 }
3718 } else {
3719 var bytes = Buffer.isBuffer(val)
3720 ? val
3721 : Buffer.from(val, encoding)
3722 var len = bytes.length
3723 if (len === 0) {
3724 throw new TypeError('The value "' + val +
3725 '" is invalid for argument "value"')
3726 }
3727 for (i = 0; i < end - start; ++i) {
3728 this[i + start] = bytes[i % len]
3729 }
3730 }
3731
3732 return this
3733}
3734
3735// HELPER FUNCTIONS
3736// ================
3737
3738var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3739
3740function base64clean (str) {
3741 // Node takes equal signs as end of the Base64 encoding
3742 str = str.split('=')[0]
3743 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3744 str = str.trim().replace(INVALID_BASE64_RE, '')
3745 // Node converts strings with length < 2 to ''
3746 if (str.length < 2) return ''
3747 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3748 while (str.length % 4 !== 0) {
3749 str = str + '='
3750 }
3751 return str
3752}
3753
3754function utf8ToBytes (string, units) {
3755 units = units || Infinity
3756 var codePoint
3757 var length = string.length
3758 var leadSurrogate = null
3759 var bytes = []
3760
3761 for (var i = 0; i < length; ++i) {
3762 codePoint = string.charCodeAt(i)
3763
3764 // is surrogate component
3765 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3766 // last char was a lead
3767 if (!leadSurrogate) {
3768 // no lead yet
3769 if (codePoint > 0xDBFF) {
3770 // unexpected trail
3771 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3772 continue
3773 } else if (i + 1 === length) {
3774 // unpaired lead
3775 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3776 continue
3777 }
3778
3779 // valid lead
3780 leadSurrogate = codePoint
3781
3782 continue
3783 }
3784
3785 // 2 leads in a row
3786 if (codePoint < 0xDC00) {
3787 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3788 leadSurrogate = codePoint
3789 continue
3790 }
3791
3792 // valid surrogate pair
3793 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3794 } else if (leadSurrogate) {
3795 // valid bmp char, but last char was a lead
3796 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3797 }
3798
3799 leadSurrogate = null
3800
3801 // encode utf8
3802 if (codePoint < 0x80) {
3803 if ((units -= 1) < 0) break
3804 bytes.push(codePoint)
3805 } else if (codePoint < 0x800) {
3806 if ((units -= 2) < 0) break
3807 bytes.push(
3808 codePoint >> 0x6 | 0xC0,
3809 codePoint & 0x3F | 0x80
3810 )
3811 } else if (codePoint < 0x10000) {
3812 if ((units -= 3) < 0) break
3813 bytes.push(
3814 codePoint >> 0xC | 0xE0,
3815 codePoint >> 0x6 & 0x3F | 0x80,
3816 codePoint & 0x3F | 0x80
3817 )
3818 } else if (codePoint < 0x110000) {
3819 if ((units -= 4) < 0) break
3820 bytes.push(
3821 codePoint >> 0x12 | 0xF0,
3822 codePoint >> 0xC & 0x3F | 0x80,
3823 codePoint >> 0x6 & 0x3F | 0x80,
3824 codePoint & 0x3F | 0x80
3825 )
3826 } else {
3827 throw new Error('Invalid code point')
3828 }
3829 }
3830
3831 return bytes
3832}
3833
3834function asciiToBytes (str) {
3835 var byteArray = []
3836 for (var i = 0; i < str.length; ++i) {
3837 // Node's code seems to be doing this and not & 0x7F..
3838 byteArray.push(str.charCodeAt(i) & 0xFF)
3839 }
3840 return byteArray
3841}
3842
3843function utf16leToBytes (str, units) {
3844 var c, hi, lo
3845 var byteArray = []
3846 for (var i = 0; i < str.length; ++i) {
3847 if ((units -= 2) < 0) break
3848
3849 c = str.charCodeAt(i)
3850 hi = c >> 8
3851 lo = c % 256
3852 byteArray.push(lo)
3853 byteArray.push(hi)
3854 }
3855
3856 return byteArray
3857}
3858
3859function base64ToBytes (str) {
3860 return base64.toByteArray(base64clean(str))
3861}
3862
3863function blitBuffer (src, dst, offset, length) {
3864 for (var i = 0; i < length; ++i) {
3865 if ((i + offset >= dst.length) || (i >= src.length)) break
3866 dst[i + offset] = src[i]
3867 }
3868 return i
3869}
3870
3871// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
3872// the `instanceof` check but they should be treated as of that type.
3873// See: https://github.com/feross/buffer/issues/166
3874function isInstance (obj, type) {
3875 return obj instanceof type ||
3876 (obj != null && obj.constructor != null && obj.constructor.name != null &&
3877 obj.constructor.name === type.name)
3878}
3879function numberIsNaN (obj) {
3880 // For IE11 support
3881 return obj !== obj // eslint-disable-line no-self-compare
3882}
3883
3884// Create lookup table for `toString('hex')`
3885// See: https://github.com/feross/buffer/issues/219
3886var hexSliceLookupTable = (function () {
3887 var alphabet = '0123456789abcdef'
3888 var table = new Array(256)
3889 for (var i = 0; i < 16; ++i) {
3890 var i16 = i * 16
3891 for (var j = 0; j < 16; ++j) {
3892 table[i16 + j] = alphabet[i] + alphabet[j]
3893 }
3894 }
3895 return table
3896})()
3897
3898}).call(this,require("buffer").Buffer)
3899},{"base64-js":32,"buffer":35,"ieee754":58}],36:[function(require,module,exports){
3900/**
3901 * Slice reference.
3902 */
3903
3904var slice = [].slice;
3905
3906/**
3907 * Bind `obj` to `fn`.
3908 *
3909 * @param {Object} obj
3910 * @param {Function|String} fn or string
3911 * @return {Function}
3912 * @api public
3913 */
3914
3915module.exports = function(obj, fn){
3916 if ('string' == typeof fn) fn = obj[fn];
3917 if ('function' != typeof fn) throw new Error('bind() requires a function');
3918 var args = slice.call(arguments, 2);
3919 return function(){
3920 return fn.apply(obj, args.concat(slice.call(arguments)));
3921 }
3922};
3923
3924},{}],37:[function(require,module,exports){
3925
3926/**
3927 * Expose `Emitter`.
3928 */
3929
3930if (typeof module !== 'undefined') {
3931 module.exports = Emitter;
3932}
3933
3934/**
3935 * Initialize a new `Emitter`.
3936 *
3937 * @api public
3938 */
3939
3940function Emitter(obj) {
3941 if (obj) return mixin(obj);
3942};
3943
3944/**
3945 * Mixin the emitter properties.
3946 *
3947 * @param {Object} obj
3948 * @return {Object}
3949 * @api private
3950 */
3951
3952function mixin(obj) {
3953 for (var key in Emitter.prototype) {
3954 obj[key] = Emitter.prototype[key];
3955 }
3956 return obj;
3957}
3958
3959/**
3960 * Listen on the given `event` with `fn`.
3961 *
3962 * @param {String} event
3963 * @param {Function} fn
3964 * @return {Emitter}
3965 * @api public
3966 */
3967
3968Emitter.prototype.on =
3969Emitter.prototype.addEventListener = function(event, fn){
3970 this._callbacks = this._callbacks || {};
3971 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
3972 .push(fn);
3973 return this;
3974};
3975
3976/**
3977 * Adds an `event` listener that will be invoked a single
3978 * time then automatically removed.
3979 *
3980 * @param {String} event
3981 * @param {Function} fn
3982 * @return {Emitter}
3983 * @api public
3984 */
3985
3986Emitter.prototype.once = function(event, fn){
3987 function on() {
3988 this.off(event, on);
3989 fn.apply(this, arguments);
3990 }
3991
3992 on.fn = fn;
3993 this.on(event, on);
3994 return this;
3995};
3996
3997/**
3998 * Remove the given callback for `event` or all
3999 * registered callbacks.
4000 *
4001 * @param {String} event
4002 * @param {Function} fn
4003 * @return {Emitter}
4004 * @api public
4005 */
4006
4007Emitter.prototype.off =
4008Emitter.prototype.removeListener =
4009Emitter.prototype.removeAllListeners =
4010Emitter.prototype.removeEventListener = function(event, fn){
4011 this._callbacks = this._callbacks || {};
4012
4013 // all
4014 if (0 == arguments.length) {
4015 this._callbacks = {};
4016 return this;
4017 }
4018
4019 // specific event
4020 var callbacks = this._callbacks['$' + event];
4021 if (!callbacks) return this;
4022
4023 // remove all handlers
4024 if (1 == arguments.length) {
4025 delete this._callbacks['$' + event];
4026 return this;
4027 }
4028
4029 // remove specific handler
4030 var cb;
4031 for (var i = 0; i < callbacks.length; i++) {
4032 cb = callbacks[i];
4033 if (cb === fn || cb.fn === fn) {
4034 callbacks.splice(i, 1);
4035 break;
4036 }
4037 }
4038 return this;
4039};
4040
4041/**
4042 * Emit `event` with the given args.
4043 *
4044 * @param {String} event
4045 * @param {Mixed} ...
4046 * @return {Emitter}
4047 */
4048
4049Emitter.prototype.emit = function(event){
4050 this._callbacks = this._callbacks || {};
4051 var args = [].slice.call(arguments, 1)
4052 , callbacks = this._callbacks['$' + event];
4053
4054 if (callbacks) {
4055 callbacks = callbacks.slice(0);
4056 for (var i = 0, len = callbacks.length; i < len; ++i) {
4057 callbacks[i].apply(this, args);
4058 }
4059 }
4060
4061 return this;
4062};
4063
4064/**
4065 * Return array of callbacks for `event`.
4066 *
4067 * @param {String} event
4068 * @return {Array}
4069 * @api public
4070 */
4071
4072Emitter.prototype.listeners = function(event){
4073 this._callbacks = this._callbacks || {};
4074 return this._callbacks['$' + event] || [];
4075};
4076
4077/**
4078 * Check if this emitter has `event` handlers.
4079 *
4080 * @param {String} event
4081 * @return {Boolean}
4082 * @api public
4083 */
4084
4085Emitter.prototype.hasListeners = function(event){
4086 return !! this.listeners(event).length;
4087};
4088
4089},{}],38:[function(require,module,exports){
4090
4091module.exports = function(a, b){
4092 var fn = function(){};
4093 fn.prototype = b.prototype;
4094 a.prototype = new fn;
4095 a.prototype.constructor = a;
4096};
4097},{}],39:[function(require,module,exports){
4098(function (process){
4099/**
4100 * This is the web browser implementation of `debug()`.
4101 *
4102 * Expose `debug()` as the module.
4103 */
4104
4105exports = module.exports = require('./debug');
4106exports.log = log;
4107exports.formatArgs = formatArgs;
4108exports.save = save;
4109exports.load = load;
4110exports.useColors = useColors;
4111exports.storage = 'undefined' != typeof chrome
4112 && 'undefined' != typeof chrome.storage
4113 ? chrome.storage.local
4114 : localstorage();
4115
4116/**
4117 * Colors.
4118 */
4119
4120exports.colors = [
4121 '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC',
4122 '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF',
4123 '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC',
4124 '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF',
4125 '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC',
4126 '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033',
4127 '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366',
4128 '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933',
4129 '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC',
4130 '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF',
4131 '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'
4132];
4133
4134/**
4135 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
4136 * and the Firebug extension (any Firefox version) are known
4137 * to support "%c" CSS customizations.
4138 *
4139 * TODO: add a `localStorage` variable to explicitly enable/disable colors
4140 */
4141
4142function useColors() {
4143 // NB: In an Electron preload script, document will be defined but not fully
4144 // initialized. Since we know we're in Chrome, we'll just detect this case
4145 // explicitly
4146 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
4147 return true;
4148 }
4149
4150 // Internet Explorer and Edge do not support colors.
4151 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
4152 return false;
4153 }
4154
4155 // is webkit? http://stackoverflow.com/a/16459606/376773
4156 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
4157 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
4158 // is firebug? http://stackoverflow.com/a/398120/376773
4159 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
4160 // is firefox >= v31?
4161 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
4162 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
4163 // double check webkit in userAgent just in case we are in a worker
4164 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
4165}
4166
4167/**
4168 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
4169 */
4170
4171exports.formatters.j = function(v) {
4172 try {
4173 return JSON.stringify(v);
4174 } catch (err) {
4175 return '[UnexpectedJSONParseError]: ' + err.message;
4176 }
4177};
4178
4179
4180/**
4181 * Colorize log arguments if enabled.
4182 *
4183 * @api public
4184 */
4185
4186function formatArgs(args) {
4187 var useColors = this.useColors;
4188
4189 args[0] = (useColors ? '%c' : '')
4190 + this.namespace
4191 + (useColors ? ' %c' : ' ')
4192 + args[0]
4193 + (useColors ? '%c ' : ' ')
4194 + '+' + exports.humanize(this.diff);
4195
4196 if (!useColors) return;
4197
4198 var c = 'color: ' + this.color;
4199 args.splice(1, 0, c, 'color: inherit')
4200
4201 // the final "%c" is somewhat tricky, because there could be other
4202 // arguments passed either before or after the %c, so we need to
4203 // figure out the correct index to insert the CSS into
4204 var index = 0;
4205 var lastC = 0;
4206 args[0].replace(/%[a-zA-Z%]/g, function(match) {
4207 if ('%%' === match) return;
4208 index++;
4209 if ('%c' === match) {
4210 // we only are interested in the *last* %c
4211 // (the user may have provided their own)
4212 lastC = index;
4213 }
4214 });
4215
4216 args.splice(lastC, 0, c);
4217}
4218
4219/**
4220 * Invokes `console.log()` when available.
4221 * No-op when `console.log` is not a "function".
4222 *
4223 * @api public
4224 */
4225
4226function log() {
4227 // this hackery is required for IE8/9, where
4228 // the `console.log` function doesn't have 'apply'
4229 return 'object' === typeof console
4230 && console.log
4231 && Function.prototype.apply.call(console.log, console, arguments);
4232}
4233
4234/**
4235 * Save `namespaces`.
4236 *
4237 * @param {String} namespaces
4238 * @api private
4239 */
4240
4241function save(namespaces) {
4242 try {
4243 if (null == namespaces) {
4244 exports.storage.removeItem('debug');
4245 } else {
4246 exports.storage.debug = namespaces;
4247 }
4248 } catch(e) {}
4249}
4250
4251/**
4252 * Load `namespaces`.
4253 *
4254 * @return {String} returns the previously persisted debug modes
4255 * @api private
4256 */
4257
4258function load() {
4259 var r;
4260 try {
4261 r = exports.storage.debug;
4262 } catch(e) {}
4263
4264 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
4265 if (!r && typeof process !== 'undefined' && 'env' in process) {
4266 r = process.env.DEBUG;
4267 }
4268
4269 return r;
4270}
4271
4272/**
4273 * Enable namespaces listed in `localStorage.debug` initially.
4274 */
4275
4276exports.enable(load());
4277
4278/**
4279 * Localstorage attempts to return the localstorage.
4280 *
4281 * This is necessary because safari throws
4282 * when a user disables cookies/localstorage
4283 * and you attempt to access it.
4284 *
4285 * @return {LocalStorage}
4286 * @api private
4287 */
4288
4289function localstorage() {
4290 try {
4291 return window.localStorage;
4292 } catch (e) {}
4293}
4294
4295}).call(this,require('_process'))
4296},{"./debug":40,"_process":64}],40:[function(require,module,exports){
4297
4298/**
4299 * This is the common logic for both the Node.js and web browser
4300 * implementations of `debug()`.
4301 *
4302 * Expose `debug()` as the module.
4303 */
4304
4305exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
4306exports.coerce = coerce;
4307exports.disable = disable;
4308exports.enable = enable;
4309exports.enabled = enabled;
4310exports.humanize = require('ms');
4311
4312/**
4313 * Active `debug` instances.
4314 */
4315exports.instances = [];
4316
4317/**
4318 * The currently active debug mode names, and names to skip.
4319 */
4320
4321exports.names = [];
4322exports.skips = [];
4323
4324/**
4325 * Map of special "%n" handling functions, for the debug "format" argument.
4326 *
4327 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
4328 */
4329
4330exports.formatters = {};
4331
4332/**
4333 * Select a color.
4334 * @param {String} namespace
4335 * @return {Number}
4336 * @api private
4337 */
4338
4339function selectColor(namespace) {
4340 var hash = 0, i;
4341
4342 for (i in namespace) {
4343 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
4344 hash |= 0; // Convert to 32bit integer
4345 }
4346
4347 return exports.colors[Math.abs(hash) % exports.colors.length];
4348}
4349
4350/**
4351 * Create a debugger with the given `namespace`.
4352 *
4353 * @param {String} namespace
4354 * @return {Function}
4355 * @api public
4356 */
4357
4358function createDebug(namespace) {
4359
4360 var prevTime;
4361
4362 function debug() {
4363 // disabled?
4364 if (!debug.enabled) return;
4365
4366 var self = debug;
4367
4368 // set `diff` timestamp
4369 var curr = +new Date();
4370 var ms = curr - (prevTime || curr);
4371 self.diff = ms;
4372 self.prev = prevTime;
4373 self.curr = curr;
4374 prevTime = curr;
4375
4376 // turn the `arguments` into a proper Array
4377 var args = new Array(arguments.length);
4378 for (var i = 0; i < args.length; i++) {
4379 args[i] = arguments[i];
4380 }
4381
4382 args[0] = exports.coerce(args[0]);
4383
4384 if ('string' !== typeof args[0]) {
4385 // anything else let's inspect with %O
4386 args.unshift('%O');
4387 }
4388
4389 // apply any `formatters` transformations
4390 var index = 0;
4391 args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
4392 // if we encounter an escaped % then don't increase the array index
4393 if (match === '%%') return match;
4394 index++;
4395 var formatter = exports.formatters[format];
4396 if ('function' === typeof formatter) {
4397 var val = args[index];
4398 match = formatter.call(self, val);
4399
4400 // now we need to remove `args[index]` since it's inlined in the `format`
4401 args.splice(index, 1);
4402 index--;
4403 }
4404 return match;
4405 });
4406
4407 // apply env-specific formatting (colors, etc.)
4408 exports.formatArgs.call(self, args);
4409
4410 var logFn = debug.log || exports.log || console.log.bind(console);
4411 logFn.apply(self, args);
4412 }
4413
4414 debug.namespace = namespace;
4415 debug.enabled = exports.enabled(namespace);
4416 debug.useColors = exports.useColors();
4417 debug.color = selectColor(namespace);
4418 debug.destroy = destroy;
4419
4420 // env-specific initialization logic for debug instances
4421 if ('function' === typeof exports.init) {
4422 exports.init(debug);
4423 }
4424
4425 exports.instances.push(debug);
4426
4427 return debug;
4428}
4429
4430function destroy () {
4431 var index = exports.instances.indexOf(this);
4432 if (index !== -1) {
4433 exports.instances.splice(index, 1);
4434 return true;
4435 } else {
4436 return false;
4437 }
4438}
4439
4440/**
4441 * Enables a debug mode by namespaces. This can include modes
4442 * separated by a colon and wildcards.
4443 *
4444 * @param {String} namespaces
4445 * @api public
4446 */
4447
4448function enable(namespaces) {
4449 exports.save(namespaces);
4450
4451 exports.names = [];
4452 exports.skips = [];
4453
4454 var i;
4455 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
4456 var len = split.length;
4457
4458 for (i = 0; i < len; i++) {
4459 if (!split[i]) continue; // ignore empty strings
4460 namespaces = split[i].replace(/\*/g, '.*?');
4461 if (namespaces[0] === '-') {
4462 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
4463 } else {
4464 exports.names.push(new RegExp('^' + namespaces + '$'));
4465 }
4466 }
4467
4468 for (i = 0; i < exports.instances.length; i++) {
4469 var instance = exports.instances[i];
4470 instance.enabled = exports.enabled(instance.namespace);
4471 }
4472}
4473
4474/**
4475 * Disable debug output.
4476 *
4477 * @api public
4478 */
4479
4480function disable() {
4481 exports.enable('');
4482}
4483
4484/**
4485 * Returns true if the given mode name is enabled, false otherwise.
4486 *
4487 * @param {String} name
4488 * @return {Boolean}
4489 * @api public
4490 */
4491
4492function enabled(name) {
4493 if (name[name.length - 1] === '*') {
4494 return true;
4495 }
4496 var i, len;
4497 for (i = 0, len = exports.skips.length; i < len; i++) {
4498 if (exports.skips[i].test(name)) {
4499 return false;
4500 }
4501 }
4502 for (i = 0, len = exports.names.length; i < len; i++) {
4503 if (exports.names[i].test(name)) {
4504 return true;
4505 }
4506 }
4507 return false;
4508}
4509
4510/**
4511 * Coerce `val`.
4512 *
4513 * @param {Mixed} val
4514 * @return {Mixed}
4515 * @api private
4516 */
4517
4518function coerce(val) {
4519 if (val instanceof Error) return val.stack || val.message;
4520 return val;
4521}
4522
4523},{"ms":61}],41:[function(require,module,exports){
4524
4525module.exports = require('./socket');
4526
4527/**
4528 * Exports parser
4529 *
4530 * @api public
4531 *
4532 */
4533module.exports.parser = require('engine.io-parser');
4534
4535},{"./socket":42,"engine.io-parser":53}],42:[function(require,module,exports){
4536/**
4537 * Module dependencies.
4538 */
4539
4540var transports = require('./transports/index');
4541var Emitter = require('component-emitter');
4542var debug = require('debug')('engine.io-client:socket');
4543var index = require('indexof');
4544var parser = require('engine.io-parser');
4545var parseuri = require('parseuri');
4546var parseqs = require('parseqs');
4547
4548/**
4549 * Module exports.
4550 */
4551
4552module.exports = Socket;
4553
4554/**
4555 * Socket constructor.
4556 *
4557 * @param {String|Object} uri or options
4558 * @param {Object} options
4559 * @api public
4560 */
4561
4562function Socket (uri, opts) {
4563 if (!(this instanceof Socket)) return new Socket(uri, opts);
4564
4565 opts = opts || {};
4566
4567 if (uri && 'object' === typeof uri) {
4568 opts = uri;
4569 uri = null;
4570 }
4571
4572 if (uri) {
4573 uri = parseuri(uri);
4574 opts.hostname = uri.host;
4575 opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
4576 opts.port = uri.port;
4577 if (uri.query) opts.query = uri.query;
4578 } else if (opts.host) {
4579 opts.hostname = parseuri(opts.host).host;
4580 }
4581
4582 this.secure = null != opts.secure ? opts.secure
4583 : (typeof location !== 'undefined' && 'https:' === location.protocol);
4584
4585 if (opts.hostname && !opts.port) {
4586 // if no port is specified manually, use the protocol default
4587 opts.port = this.secure ? '443' : '80';
4588 }
4589
4590 this.agent = opts.agent || false;
4591 this.hostname = opts.hostname ||
4592 (typeof location !== 'undefined' ? location.hostname : 'localhost');
4593 this.port = opts.port || (typeof location !== 'undefined' && location.port
4594 ? location.port
4595 : (this.secure ? 443 : 80));
4596 this.query = opts.query || {};
4597 if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
4598 this.upgrade = false !== opts.upgrade;
4599 this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
4600 this.forceJSONP = !!opts.forceJSONP;
4601 this.jsonp = false !== opts.jsonp;
4602 this.forceBase64 = !!opts.forceBase64;
4603 this.enablesXDR = !!opts.enablesXDR;
4604 this.withCredentials = false !== opts.withCredentials;
4605 this.timestampParam = opts.timestampParam || 't';
4606 this.timestampRequests = opts.timestampRequests;
4607 this.transports = opts.transports || ['polling', 'websocket'];
4608 this.transportOptions = opts.transportOptions || {};
4609 this.readyState = '';
4610 this.writeBuffer = [];
4611 this.prevBufferLen = 0;
4612 this.policyPort = opts.policyPort || 843;
4613 this.rememberUpgrade = opts.rememberUpgrade || false;
4614 this.binaryType = null;
4615 this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
4616 this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
4617
4618 if (true === this.perMessageDeflate) this.perMessageDeflate = {};
4619 if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
4620 this.perMessageDeflate.threshold = 1024;
4621 }
4622
4623 // SSL options for Node.js client
4624 this.pfx = opts.pfx || null;
4625 this.key = opts.key || null;
4626 this.passphrase = opts.passphrase || null;
4627 this.cert = opts.cert || null;
4628 this.ca = opts.ca || null;
4629 this.ciphers = opts.ciphers || null;
4630 this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
4631 this.forceNode = !!opts.forceNode;
4632
4633 // detect ReactNative environment
4634 this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative');
4635
4636 // other options for Node.js or ReactNative client
4637 if (typeof self === 'undefined' || this.isReactNative) {
4638 if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
4639 this.extraHeaders = opts.extraHeaders;
4640 }
4641
4642 if (opts.localAddress) {
4643 this.localAddress = opts.localAddress;
4644 }
4645 }
4646
4647 // set on handshake
4648 this.id = null;
4649 this.upgrades = null;
4650 this.pingInterval = null;
4651 this.pingTimeout = null;
4652
4653 // set on heartbeat
4654 this.pingIntervalTimer = null;
4655 this.pingTimeoutTimer = null;
4656
4657 this.open();
4658}
4659
4660Socket.priorWebsocketSuccess = false;
4661
4662/**
4663 * Mix in `Emitter`.
4664 */
4665
4666Emitter(Socket.prototype);
4667
4668/**
4669 * Protocol version.
4670 *
4671 * @api public
4672 */
4673
4674Socket.protocol = parser.protocol; // this is an int
4675
4676/**
4677 * Expose deps for legacy compatibility
4678 * and standalone browser access.
4679 */
4680
4681Socket.Socket = Socket;
4682Socket.Transport = require('./transport');
4683Socket.transports = require('./transports/index');
4684Socket.parser = require('engine.io-parser');
4685
4686/**
4687 * Creates transport of the given type.
4688 *
4689 * @param {String} transport name
4690 * @return {Transport}
4691 * @api private
4692 */
4693
4694Socket.prototype.createTransport = function (name) {
4695 debug('creating transport "%s"', name);
4696 var query = clone(this.query);
4697
4698 // append engine.io protocol identifier
4699 query.EIO = parser.protocol;
4700
4701 // transport name
4702 query.transport = name;
4703
4704 // per-transport options
4705 var options = this.transportOptions[name] || {};
4706
4707 // session id if we already have one
4708 if (this.id) query.sid = this.id;
4709
4710 var transport = new transports[name]({
4711 query: query,
4712 socket: this,
4713 agent: options.agent || this.agent,
4714 hostname: options.hostname || this.hostname,
4715 port: options.port || this.port,
4716 secure: options.secure || this.secure,
4717 path: options.path || this.path,
4718 forceJSONP: options.forceJSONP || this.forceJSONP,
4719 jsonp: options.jsonp || this.jsonp,
4720 forceBase64: options.forceBase64 || this.forceBase64,
4721 enablesXDR: options.enablesXDR || this.enablesXDR,
4722 withCredentials: options.withCredentials || this.withCredentials,
4723 timestampRequests: options.timestampRequests || this.timestampRequests,
4724 timestampParam: options.timestampParam || this.timestampParam,
4725 policyPort: options.policyPort || this.policyPort,
4726 pfx: options.pfx || this.pfx,
4727 key: options.key || this.key,
4728 passphrase: options.passphrase || this.passphrase,
4729 cert: options.cert || this.cert,
4730 ca: options.ca || this.ca,
4731 ciphers: options.ciphers || this.ciphers,
4732 rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
4733 perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
4734 extraHeaders: options.extraHeaders || this.extraHeaders,
4735 forceNode: options.forceNode || this.forceNode,
4736 localAddress: options.localAddress || this.localAddress,
4737 requestTimeout: options.requestTimeout || this.requestTimeout,
4738 protocols: options.protocols || void (0),
4739 isReactNative: this.isReactNative
4740 });
4741
4742 return transport;
4743};
4744
4745function clone (obj) {
4746 var o = {};
4747 for (var i in obj) {
4748 if (obj.hasOwnProperty(i)) {
4749 o[i] = obj[i];
4750 }
4751 }
4752 return o;
4753}
4754
4755/**
4756 * Initializes transport to use and starts probe.
4757 *
4758 * @api private
4759 */
4760Socket.prototype.open = function () {
4761 var transport;
4762 if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
4763 transport = 'websocket';
4764 } else if (0 === this.transports.length) {
4765 // Emit error on next tick so it can be listened to
4766 var self = this;
4767 setTimeout(function () {
4768 self.emit('error', 'No transports available');
4769 }, 0);
4770 return;
4771 } else {
4772 transport = this.transports[0];
4773 }
4774 this.readyState = 'opening';
4775
4776 // Retry with the next transport if the transport is disabled (jsonp: false)
4777 try {
4778 transport = this.createTransport(transport);
4779 } catch (e) {
4780 this.transports.shift();
4781 this.open();
4782 return;
4783 }
4784
4785 transport.open();
4786 this.setTransport(transport);
4787};
4788
4789/**
4790 * Sets the current transport. Disables the existing one (if any).
4791 *
4792 * @api private
4793 */
4794
4795Socket.prototype.setTransport = function (transport) {
4796 debug('setting transport %s', transport.name);
4797 var self = this;
4798
4799 if (this.transport) {
4800 debug('clearing existing transport %s', this.transport.name);
4801 this.transport.removeAllListeners();
4802 }
4803
4804 // set up transport
4805 this.transport = transport;
4806
4807 // set up transport listeners
4808 transport
4809 .on('drain', function () {
4810 self.onDrain();
4811 })
4812 .on('packet', function (packet) {
4813 self.onPacket(packet);
4814 })
4815 .on('error', function (e) {
4816 self.onError(e);
4817 })
4818 .on('close', function () {
4819 self.onClose('transport close');
4820 });
4821};
4822
4823/**
4824 * Probes a transport.
4825 *
4826 * @param {String} transport name
4827 * @api private
4828 */
4829
4830Socket.prototype.probe = function (name) {
4831 debug('probing transport "%s"', name);
4832 var transport = this.createTransport(name, { probe: 1 });
4833 var failed = false;
4834 var self = this;
4835
4836 Socket.priorWebsocketSuccess = false;
4837
4838 function onTransportOpen () {
4839 if (self.onlyBinaryUpgrades) {
4840 var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
4841 failed = failed || upgradeLosesBinary;
4842 }
4843 if (failed) return;
4844
4845 debug('probe transport "%s" opened', name);
4846 transport.send([{ type: 'ping', data: 'probe' }]);
4847 transport.once('packet', function (msg) {
4848 if (failed) return;
4849 if ('pong' === msg.type && 'probe' === msg.data) {
4850 debug('probe transport "%s" pong', name);
4851 self.upgrading = true;
4852 self.emit('upgrading', transport);
4853 if (!transport) return;
4854 Socket.priorWebsocketSuccess = 'websocket' === transport.name;
4855
4856 debug('pausing current transport "%s"', self.transport.name);
4857 self.transport.pause(function () {
4858 if (failed) return;
4859 if ('closed' === self.readyState) return;
4860 debug('changing transport and sending upgrade packet');
4861
4862 cleanup();
4863
4864 self.setTransport(transport);
4865 transport.send([{ type: 'upgrade' }]);
4866 self.emit('upgrade', transport);
4867 transport = null;
4868 self.upgrading = false;
4869 self.flush();
4870 });
4871 } else {
4872 debug('probe transport "%s" failed', name);
4873 var err = new Error('probe error');
4874 err.transport = transport.name;
4875 self.emit('upgradeError', err);
4876 }
4877 });
4878 }
4879
4880 function freezeTransport () {
4881 if (failed) return;
4882
4883 // Any callback called by transport should be ignored since now
4884 failed = true;
4885
4886 cleanup();
4887
4888 transport.close();
4889 transport = null;
4890 }
4891
4892 // Handle any error that happens while probing
4893 function onerror (err) {
4894 var error = new Error('probe error: ' + err);
4895 error.transport = transport.name;
4896
4897 freezeTransport();
4898
4899 debug('probe transport "%s" failed because of error: %s', name, err);
4900
4901 self.emit('upgradeError', error);
4902 }
4903
4904 function onTransportClose () {
4905 onerror('transport closed');
4906 }
4907
4908 // When the socket is closed while we're probing
4909 function onclose () {
4910 onerror('socket closed');
4911 }
4912
4913 // When the socket is upgraded while we're probing
4914 function onupgrade (to) {
4915 if (transport && to.name !== transport.name) {
4916 debug('"%s" works - aborting "%s"', to.name, transport.name);
4917 freezeTransport();
4918 }
4919 }
4920
4921 // Remove all listeners on the transport and on self
4922 function cleanup () {
4923 transport.removeListener('open', onTransportOpen);
4924 transport.removeListener('error', onerror);
4925 transport.removeListener('close', onTransportClose);
4926 self.removeListener('close', onclose);
4927 self.removeListener('upgrading', onupgrade);
4928 }
4929
4930 transport.once('open', onTransportOpen);
4931 transport.once('error', onerror);
4932 transport.once('close', onTransportClose);
4933
4934 this.once('close', onclose);
4935 this.once('upgrading', onupgrade);
4936
4937 transport.open();
4938};
4939
4940/**
4941 * Called when connection is deemed open.
4942 *
4943 * @api public
4944 */
4945
4946Socket.prototype.onOpen = function () {
4947 debug('socket open');
4948 this.readyState = 'open';
4949 Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
4950 this.emit('open');
4951 this.flush();
4952
4953 // we check for `readyState` in case an `open`
4954 // listener already closed the socket
4955 if ('open' === this.readyState && this.upgrade && this.transport.pause) {
4956 debug('starting upgrade probes');
4957 for (var i = 0, l = this.upgrades.length; i < l; i++) {
4958 this.probe(this.upgrades[i]);
4959 }
4960 }
4961};
4962
4963/**
4964 * Handles a packet.
4965 *
4966 * @api private
4967 */
4968
4969Socket.prototype.onPacket = function (packet) {
4970 if ('opening' === this.readyState || 'open' === this.readyState ||
4971 'closing' === this.readyState) {
4972 debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
4973
4974 this.emit('packet', packet);
4975
4976 // Socket is live - any packet counts
4977 this.emit('heartbeat');
4978
4979 switch (packet.type) {
4980 case 'open':
4981 this.onHandshake(JSON.parse(packet.data));
4982 break;
4983
4984 case 'pong':
4985 this.setPing();
4986 this.emit('pong');
4987 break;
4988
4989 case 'error':
4990 var err = new Error('server error');
4991 err.code = packet.data;
4992 this.onError(err);
4993 break;
4994
4995 case 'message':
4996 this.emit('data', packet.data);
4997 this.emit('message', packet.data);
4998 break;
4999 }
5000 } else {
5001 debug('packet received with socket readyState "%s"', this.readyState);
5002 }
5003};
5004
5005/**
5006 * Called upon handshake completion.
5007 *
5008 * @param {Object} handshake obj
5009 * @api private
5010 */
5011
5012Socket.prototype.onHandshake = function (data) {
5013 this.emit('handshake', data);
5014 this.id = data.sid;
5015 this.transport.query.sid = data.sid;
5016 this.upgrades = this.filterUpgrades(data.upgrades);
5017 this.pingInterval = data.pingInterval;
5018 this.pingTimeout = data.pingTimeout;
5019 this.onOpen();
5020 // In case open handler closes socket
5021 if ('closed' === this.readyState) return;
5022 this.setPing();
5023
5024 // Prolong liveness of socket on heartbeat
5025 this.removeListener('heartbeat', this.onHeartbeat);
5026 this.on('heartbeat', this.onHeartbeat);
5027};
5028
5029/**
5030 * Resets ping timeout.
5031 *
5032 * @api private
5033 */
5034
5035Socket.prototype.onHeartbeat = function (timeout) {
5036 clearTimeout(this.pingTimeoutTimer);
5037 var self = this;
5038 self.pingTimeoutTimer = setTimeout(function () {
5039 if ('closed' === self.readyState) return;
5040 self.onClose('ping timeout');
5041 }, timeout || (self.pingInterval + self.pingTimeout));
5042};
5043
5044/**
5045 * Pings server every `this.pingInterval` and expects response
5046 * within `this.pingTimeout` or closes connection.
5047 *
5048 * @api private
5049 */
5050
5051Socket.prototype.setPing = function () {
5052 var self = this;
5053 clearTimeout(self.pingIntervalTimer);
5054 self.pingIntervalTimer = setTimeout(function () {
5055 debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
5056 self.ping();
5057 self.onHeartbeat(self.pingTimeout);
5058 }, self.pingInterval);
5059};
5060
5061/**
5062* Sends a ping packet.
5063*
5064* @api private
5065*/
5066
5067Socket.prototype.ping = function () {
5068 var self = this;
5069 this.sendPacket('ping', function () {
5070 self.emit('ping');
5071 });
5072};
5073
5074/**
5075 * Called on `drain` event
5076 *
5077 * @api private
5078 */
5079
5080Socket.prototype.onDrain = function () {
5081 this.writeBuffer.splice(0, this.prevBufferLen);
5082
5083 // setting prevBufferLen = 0 is very important
5084 // for example, when upgrading, upgrade packet is sent over,
5085 // and a nonzero prevBufferLen could cause problems on `drain`
5086 this.prevBufferLen = 0;
5087
5088 if (0 === this.writeBuffer.length) {
5089 this.emit('drain');
5090 } else {
5091 this.flush();
5092 }
5093};
5094
5095/**
5096 * Flush write buffers.
5097 *
5098 * @api private
5099 */
5100
5101Socket.prototype.flush = function () {
5102 if ('closed' !== this.readyState && this.transport.writable &&
5103 !this.upgrading && this.writeBuffer.length) {
5104 debug('flushing %d packets in socket', this.writeBuffer.length);
5105 this.transport.send(this.writeBuffer);
5106 // keep track of current length of writeBuffer
5107 // splice writeBuffer and callbackBuffer on `drain`
5108 this.prevBufferLen = this.writeBuffer.length;
5109 this.emit('flush');
5110 }
5111};
5112
5113/**
5114 * Sends a message.
5115 *
5116 * @param {String} message.
5117 * @param {Function} callback function.
5118 * @param {Object} options.
5119 * @return {Socket} for chaining.
5120 * @api public
5121 */
5122
5123Socket.prototype.write =
5124Socket.prototype.send = function (msg, options, fn) {
5125 this.sendPacket('message', msg, options, fn);
5126 return this;
5127};
5128
5129/**
5130 * Sends a packet.
5131 *
5132 * @param {String} packet type.
5133 * @param {String} data.
5134 * @param {Object} options.
5135 * @param {Function} callback function.
5136 * @api private
5137 */
5138
5139Socket.prototype.sendPacket = function (type, data, options, fn) {
5140 if ('function' === typeof data) {
5141 fn = data;
5142 data = undefined;
5143 }
5144
5145 if ('function' === typeof options) {
5146 fn = options;
5147 options = null;
5148 }
5149
5150 if ('closing' === this.readyState || 'closed' === this.readyState) {
5151 return;
5152 }
5153
5154 options = options || {};
5155 options.compress = false !== options.compress;
5156
5157 var packet = {
5158 type: type,
5159 data: data,
5160 options: options
5161 };
5162 this.emit('packetCreate', packet);
5163 this.writeBuffer.push(packet);
5164 if (fn) this.once('flush', fn);
5165 this.flush();
5166};
5167
5168/**
5169 * Closes the connection.
5170 *
5171 * @api private
5172 */
5173
5174Socket.prototype.close = function () {
5175 if ('opening' === this.readyState || 'open' === this.readyState) {
5176 this.readyState = 'closing';
5177
5178 var self = this;
5179
5180 if (this.writeBuffer.length) {
5181 this.once('drain', function () {
5182 if (this.upgrading) {
5183 waitForUpgrade();
5184 } else {
5185 close();
5186 }
5187 });
5188 } else if (this.upgrading) {
5189 waitForUpgrade();
5190 } else {
5191 close();
5192 }
5193 }
5194
5195 function close () {
5196 self.onClose('forced close');
5197 debug('socket closing - telling transport to close');
5198 self.transport.close();
5199 }
5200
5201 function cleanupAndClose () {
5202 self.removeListener('upgrade', cleanupAndClose);
5203 self.removeListener('upgradeError', cleanupAndClose);
5204 close();
5205 }
5206
5207 function waitForUpgrade () {
5208 // wait for upgrade to finish since we can't send packets while pausing a transport
5209 self.once('upgrade', cleanupAndClose);
5210 self.once('upgradeError', cleanupAndClose);
5211 }
5212
5213 return this;
5214};
5215
5216/**
5217 * Called upon transport error
5218 *
5219 * @api private
5220 */
5221
5222Socket.prototype.onError = function (err) {
5223 debug('socket error %j', err);
5224 Socket.priorWebsocketSuccess = false;
5225 this.emit('error', err);
5226 this.onClose('transport error', err);
5227};
5228
5229/**
5230 * Called upon transport close.
5231 *
5232 * @api private
5233 */
5234
5235Socket.prototype.onClose = function (reason, desc) {
5236 if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
5237 debug('socket close with reason: "%s"', reason);
5238 var self = this;
5239
5240 // clear timers
5241 clearTimeout(this.pingIntervalTimer);
5242 clearTimeout(this.pingTimeoutTimer);
5243
5244 // stop event from firing again for transport
5245 this.transport.removeAllListeners('close');
5246
5247 // ensure transport won't stay open
5248 this.transport.close();
5249
5250 // ignore further transport communication
5251 this.transport.removeAllListeners();
5252
5253 // set ready state
5254 this.readyState = 'closed';
5255
5256 // clear session id
5257 this.id = null;
5258
5259 // emit close event
5260 this.emit('close', reason, desc);
5261
5262 // clean buffers after, so users can still
5263 // grab the buffers on `close` event
5264 self.writeBuffer = [];
5265 self.prevBufferLen = 0;
5266 }
5267};
5268
5269/**
5270 * Filters upgrades, returning only those matching client transports.
5271 *
5272 * @param {Array} server upgrades
5273 * @api private
5274 *
5275 */
5276
5277Socket.prototype.filterUpgrades = function (upgrades) {
5278 var filteredUpgrades = [];
5279 for (var i = 0, j = upgrades.length; i < j; i++) {
5280 if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
5281 }
5282 return filteredUpgrades;
5283};
5284
5285},{"./transport":43,"./transports/index":44,"component-emitter":37,"debug":50,"engine.io-parser":53,"indexof":59,"parseqs":62,"parseuri":63}],43:[function(require,module,exports){
5286/**
5287 * Module dependencies.
5288 */
5289
5290var parser = require('engine.io-parser');
5291var Emitter = require('component-emitter');
5292
5293/**
5294 * Module exports.
5295 */
5296
5297module.exports = Transport;
5298
5299/**
5300 * Transport abstract constructor.
5301 *
5302 * @param {Object} options.
5303 * @api private
5304 */
5305
5306function Transport (opts) {
5307 this.path = opts.path;
5308 this.hostname = opts.hostname;
5309 this.port = opts.port;
5310 this.secure = opts.secure;
5311 this.query = opts.query;
5312 this.timestampParam = opts.timestampParam;
5313 this.timestampRequests = opts.timestampRequests;
5314 this.readyState = '';
5315 this.agent = opts.agent || false;
5316 this.socket = opts.socket;
5317 this.enablesXDR = opts.enablesXDR;
5318 this.withCredentials = opts.withCredentials;
5319
5320 // SSL options for Node.js client
5321 this.pfx = opts.pfx;
5322 this.key = opts.key;
5323 this.passphrase = opts.passphrase;
5324 this.cert = opts.cert;
5325 this.ca = opts.ca;
5326 this.ciphers = opts.ciphers;
5327 this.rejectUnauthorized = opts.rejectUnauthorized;
5328 this.forceNode = opts.forceNode;
5329
5330 // results of ReactNative environment detection
5331 this.isReactNative = opts.isReactNative;
5332
5333 // other options for Node.js client
5334 this.extraHeaders = opts.extraHeaders;
5335 this.localAddress = opts.localAddress;
5336}
5337
5338/**
5339 * Mix in `Emitter`.
5340 */
5341
5342Emitter(Transport.prototype);
5343
5344/**
5345 * Emits an error.
5346 *
5347 * @param {String} str
5348 * @return {Transport} for chaining
5349 * @api public
5350 */
5351
5352Transport.prototype.onError = function (msg, desc) {
5353 var err = new Error(msg);
5354 err.type = 'TransportError';
5355 err.description = desc;
5356 this.emit('error', err);
5357 return this;
5358};
5359
5360/**
5361 * Opens the transport.
5362 *
5363 * @api public
5364 */
5365
5366Transport.prototype.open = function () {
5367 if ('closed' === this.readyState || '' === this.readyState) {
5368 this.readyState = 'opening';
5369 this.doOpen();
5370 }
5371
5372 return this;
5373};
5374
5375/**
5376 * Closes the transport.
5377 *
5378 * @api private
5379 */
5380
5381Transport.prototype.close = function () {
5382 if ('opening' === this.readyState || 'open' === this.readyState) {
5383 this.doClose();
5384 this.onClose();
5385 }
5386
5387 return this;
5388};
5389
5390/**
5391 * Sends multiple packets.
5392 *
5393 * @param {Array} packets
5394 * @api private
5395 */
5396
5397Transport.prototype.send = function (packets) {
5398 if ('open' === this.readyState) {
5399 this.write(packets);
5400 } else {
5401 throw new Error('Transport not open');
5402 }
5403};
5404
5405/**
5406 * Called upon open
5407 *
5408 * @api private
5409 */
5410
5411Transport.prototype.onOpen = function () {
5412 this.readyState = 'open';
5413 this.writable = true;
5414 this.emit('open');
5415};
5416
5417/**
5418 * Called with data.
5419 *
5420 * @param {String} data
5421 * @api private
5422 */
5423
5424Transport.prototype.onData = function (data) {
5425 var packet = parser.decodePacket(data, this.socket.binaryType);
5426 this.onPacket(packet);
5427};
5428
5429/**
5430 * Called with a decoded packet.
5431 */
5432
5433Transport.prototype.onPacket = function (packet) {
5434 this.emit('packet', packet);
5435};
5436
5437/**
5438 * Called upon close.
5439 *
5440 * @api private
5441 */
5442
5443Transport.prototype.onClose = function () {
5444 this.readyState = 'closed';
5445 this.emit('close');
5446};
5447
5448},{"component-emitter":37,"engine.io-parser":53}],44:[function(require,module,exports){
5449/**
5450 * Module dependencies
5451 */
5452
5453var XMLHttpRequest = require('xmlhttprequest-ssl');
5454var XHR = require('./polling-xhr');
5455var JSONP = require('./polling-jsonp');
5456var websocket = require('./websocket');
5457
5458/**
5459 * Export transports.
5460 */
5461
5462exports.polling = polling;
5463exports.websocket = websocket;
5464
5465/**
5466 * Polling transport polymorphic constructor.
5467 * Decides on xhr vs jsonp based on feature detection.
5468 *
5469 * @api private
5470 */
5471
5472function polling (opts) {
5473 var xhr;
5474 var xd = false;
5475 var xs = false;
5476 var jsonp = false !== opts.jsonp;
5477
5478 if (typeof location !== 'undefined') {
5479 var isSSL = 'https:' === location.protocol;
5480 var port = location.port;
5481
5482 // some user agents have empty `location.port`
5483 if (!port) {
5484 port = isSSL ? 443 : 80;
5485 }
5486
5487 xd = opts.hostname !== location.hostname || port !== opts.port;
5488 xs = opts.secure !== isSSL;
5489 }
5490
5491 opts.xdomain = xd;
5492 opts.xscheme = xs;
5493 xhr = new XMLHttpRequest(opts);
5494
5495 if ('open' in xhr && !opts.forceJSONP) {
5496 return new XHR(opts);
5497 } else {
5498 if (!jsonp) throw new Error('JSONP disabled');
5499 return new JSONP(opts);
5500 }
5501}
5502
5503},{"./polling-jsonp":45,"./polling-xhr":46,"./websocket":48,"xmlhttprequest-ssl":49}],45:[function(require,module,exports){
5504(function (global){
5505/**
5506 * Module requirements.
5507 */
5508
5509var Polling = require('./polling');
5510var inherit = require('component-inherit');
5511
5512/**
5513 * Module exports.
5514 */
5515
5516module.exports = JSONPPolling;
5517
5518/**
5519 * Cached regular expressions.
5520 */
5521
5522var rNewline = /\n/g;
5523var rEscapedNewline = /\\n/g;
5524
5525/**
5526 * Global JSONP callbacks.
5527 */
5528
5529var callbacks;
5530
5531/**
5532 * Noop.
5533 */
5534
5535function empty () { }
5536
5537/**
5538 * Until https://github.com/tc39/proposal-global is shipped.
5539 */
5540function glob () {
5541 return typeof self !== 'undefined' ? self
5542 : typeof window !== 'undefined' ? window
5543 : typeof global !== 'undefined' ? global : {};
5544}
5545
5546/**
5547 * JSONP Polling constructor.
5548 *
5549 * @param {Object} opts.
5550 * @api public
5551 */
5552
5553function JSONPPolling (opts) {
5554 Polling.call(this, opts);
5555
5556 this.query = this.query || {};
5557
5558 // define global callbacks array if not present
5559 // we do this here (lazily) to avoid unneeded global pollution
5560 if (!callbacks) {
5561 // we need to consider multiple engines in the same page
5562 var global = glob();
5563 callbacks = global.___eio = (global.___eio || []);
5564 }
5565
5566 // callback identifier
5567 this.index = callbacks.length;
5568
5569 // add callback to jsonp global
5570 var self = this;
5571 callbacks.push(function (msg) {
5572 self.onData(msg);
5573 });
5574
5575 // append to query string
5576 this.query.j = this.index;
5577
5578 // prevent spurious errors from being emitted when the window is unloaded
5579 if (typeof addEventListener === 'function') {
5580 addEventListener('beforeunload', function () {
5581 if (self.script) self.script.onerror = empty;
5582 }, false);
5583 }
5584}
5585
5586/**
5587 * Inherits from Polling.
5588 */
5589
5590inherit(JSONPPolling, Polling);
5591
5592/*
5593 * JSONP only supports binary as base64 encoded strings
5594 */
5595
5596JSONPPolling.prototype.supportsBinary = false;
5597
5598/**
5599 * Closes the socket.
5600 *
5601 * @api private
5602 */
5603
5604JSONPPolling.prototype.doClose = function () {
5605 if (this.script) {
5606 this.script.parentNode.removeChild(this.script);
5607 this.script = null;
5608 }
5609
5610 if (this.form) {
5611 this.form.parentNode.removeChild(this.form);
5612 this.form = null;
5613 this.iframe = null;
5614 }
5615
5616 Polling.prototype.doClose.call(this);
5617};
5618
5619/**
5620 * Starts a poll cycle.
5621 *
5622 * @api private
5623 */
5624
5625JSONPPolling.prototype.doPoll = function () {
5626 var self = this;
5627 var script = document.createElement('script');
5628
5629 if (this.script) {
5630 this.script.parentNode.removeChild(this.script);
5631 this.script = null;
5632 }
5633
5634 script.async = true;
5635 script.src = this.uri();
5636 script.onerror = function (e) {
5637 self.onError('jsonp poll error', e);
5638 };
5639
5640 var insertAt = document.getElementsByTagName('script')[0];
5641 if (insertAt) {
5642 insertAt.parentNode.insertBefore(script, insertAt);
5643 } else {
5644 (document.head || document.body).appendChild(script);
5645 }
5646 this.script = script;
5647
5648 var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
5649
5650 if (isUAgecko) {
5651 setTimeout(function () {
5652 var iframe = document.createElement('iframe');
5653 document.body.appendChild(iframe);
5654 document.body.removeChild(iframe);
5655 }, 100);
5656 }
5657};
5658
5659/**
5660 * Writes with a hidden iframe.
5661 *
5662 * @param {String} data to send
5663 * @param {Function} called upon flush.
5664 * @api private
5665 */
5666
5667JSONPPolling.prototype.doWrite = function (data, fn) {
5668 var self = this;
5669
5670 if (!this.form) {
5671 var form = document.createElement('form');
5672 var area = document.createElement('textarea');
5673 var id = this.iframeId = 'eio_iframe_' + this.index;
5674 var iframe;
5675
5676 form.className = 'socketio';
5677 form.style.position = 'absolute';
5678 form.style.top = '-1000px';
5679 form.style.left = '-1000px';
5680 form.target = id;
5681 form.method = 'POST';
5682 form.setAttribute('accept-charset', 'utf-8');
5683 area.name = 'd';
5684 form.appendChild(area);
5685 document.body.appendChild(form);
5686
5687 this.form = form;
5688 this.area = area;
5689 }
5690
5691 this.form.action = this.uri();
5692
5693 function complete () {
5694 initIframe();
5695 fn();
5696 }
5697
5698 function initIframe () {
5699 if (self.iframe) {
5700 try {
5701 self.form.removeChild(self.iframe);
5702 } catch (e) {
5703 self.onError('jsonp polling iframe removal error', e);
5704 }
5705 }
5706
5707 try {
5708 // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
5709 var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
5710 iframe = document.createElement(html);
5711 } catch (e) {
5712 iframe = document.createElement('iframe');
5713 iframe.name = self.iframeId;
5714 iframe.src = 'javascript:0';
5715 }
5716
5717 iframe.id = self.iframeId;
5718
5719 self.form.appendChild(iframe);
5720 self.iframe = iframe;
5721 }
5722
5723 initIframe();
5724
5725 // escape \n to prevent it from being converted into \r\n by some UAs
5726 // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
5727 data = data.replace(rEscapedNewline, '\\\n');
5728 this.area.value = data.replace(rNewline, '\\n');
5729
5730 try {
5731 this.form.submit();
5732 } catch (e) {}
5733
5734 if (this.iframe.attachEvent) {
5735 this.iframe.onreadystatechange = function () {
5736 if (self.iframe.readyState === 'complete') {
5737 complete();
5738 }
5739 };
5740 } else {
5741 this.iframe.onload = complete;
5742 }
5743};
5744
5745}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5746},{"./polling":47,"component-inherit":38}],46:[function(require,module,exports){
5747/* global attachEvent */
5748
5749/**
5750 * Module requirements.
5751 */
5752
5753var XMLHttpRequest = require('xmlhttprequest-ssl');
5754var Polling = require('./polling');
5755var Emitter = require('component-emitter');
5756var inherit = require('component-inherit');
5757var debug = require('debug')('engine.io-client:polling-xhr');
5758
5759/**
5760 * Module exports.
5761 */
5762
5763module.exports = XHR;
5764module.exports.Request = Request;
5765
5766/**
5767 * Empty function
5768 */
5769
5770function empty () {}
5771
5772/**
5773 * XHR Polling constructor.
5774 *
5775 * @param {Object} opts
5776 * @api public
5777 */
5778
5779function XHR (opts) {
5780 Polling.call(this, opts);
5781 this.requestTimeout = opts.requestTimeout;
5782 this.extraHeaders = opts.extraHeaders;
5783
5784 if (typeof location !== 'undefined') {
5785 var isSSL = 'https:' === location.protocol;
5786 var port = location.port;
5787
5788 // some user agents have empty `location.port`
5789 if (!port) {
5790 port = isSSL ? 443 : 80;
5791 }
5792
5793 this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
5794 port !== opts.port;
5795 this.xs = opts.secure !== isSSL;
5796 }
5797}
5798
5799/**
5800 * Inherits from Polling.
5801 */
5802
5803inherit(XHR, Polling);
5804
5805/**
5806 * XHR supports binary
5807 */
5808
5809XHR.prototype.supportsBinary = true;
5810
5811/**
5812 * Creates a request.
5813 *
5814 * @param {String} method
5815 * @api private
5816 */
5817
5818XHR.prototype.request = function (opts) {
5819 opts = opts || {};
5820 opts.uri = this.uri();
5821 opts.xd = this.xd;
5822 opts.xs = this.xs;
5823 opts.agent = this.agent || false;
5824 opts.supportsBinary = this.supportsBinary;
5825 opts.enablesXDR = this.enablesXDR;
5826 opts.withCredentials = this.withCredentials;
5827
5828 // SSL options for Node.js client
5829 opts.pfx = this.pfx;
5830 opts.key = this.key;
5831 opts.passphrase = this.passphrase;
5832 opts.cert = this.cert;
5833 opts.ca = this.ca;
5834 opts.ciphers = this.ciphers;
5835 opts.rejectUnauthorized = this.rejectUnauthorized;
5836 opts.requestTimeout = this.requestTimeout;
5837
5838 // other options for Node.js client
5839 opts.extraHeaders = this.extraHeaders;
5840
5841 return new Request(opts);
5842};
5843
5844/**
5845 * Sends data.
5846 *
5847 * @param {String} data to send.
5848 * @param {Function} called upon flush.
5849 * @api private
5850 */
5851
5852XHR.prototype.doWrite = function (data, fn) {
5853 var isBinary = typeof data !== 'string' && data !== undefined;
5854 var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
5855 var self = this;
5856 req.on('success', fn);
5857 req.on('error', function (err) {
5858 self.onError('xhr post error', err);
5859 });
5860 this.sendXhr = req;
5861};
5862
5863/**
5864 * Starts a poll cycle.
5865 *
5866 * @api private
5867 */
5868
5869XHR.prototype.doPoll = function () {
5870 debug('xhr poll');
5871 var req = this.request();
5872 var self = this;
5873 req.on('data', function (data) {
5874 self.onData(data);
5875 });
5876 req.on('error', function (err) {
5877 self.onError('xhr poll error', err);
5878 });
5879 this.pollXhr = req;
5880};
5881
5882/**
5883 * Request constructor
5884 *
5885 * @param {Object} options
5886 * @api public
5887 */
5888
5889function Request (opts) {
5890 this.method = opts.method || 'GET';
5891 this.uri = opts.uri;
5892 this.xd = !!opts.xd;
5893 this.xs = !!opts.xs;
5894 this.async = false !== opts.async;
5895 this.data = undefined !== opts.data ? opts.data : null;
5896 this.agent = opts.agent;
5897 this.isBinary = opts.isBinary;
5898 this.supportsBinary = opts.supportsBinary;
5899 this.enablesXDR = opts.enablesXDR;
5900 this.withCredentials = opts.withCredentials;
5901 this.requestTimeout = opts.requestTimeout;
5902
5903 // SSL options for Node.js client
5904 this.pfx = opts.pfx;
5905 this.key = opts.key;
5906 this.passphrase = opts.passphrase;
5907 this.cert = opts.cert;
5908 this.ca = opts.ca;
5909 this.ciphers = opts.ciphers;
5910 this.rejectUnauthorized = opts.rejectUnauthorized;
5911
5912 // other options for Node.js client
5913 this.extraHeaders = opts.extraHeaders;
5914
5915 this.create();
5916}
5917
5918/**
5919 * Mix in `Emitter`.
5920 */
5921
5922Emitter(Request.prototype);
5923
5924/**
5925 * Creates the XHR object and sends the request.
5926 *
5927 * @api private
5928 */
5929
5930Request.prototype.create = function () {
5931 var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
5932
5933 // SSL options for Node.js client
5934 opts.pfx = this.pfx;
5935 opts.key = this.key;
5936 opts.passphrase = this.passphrase;
5937 opts.cert = this.cert;
5938 opts.ca = this.ca;
5939 opts.ciphers = this.ciphers;
5940 opts.rejectUnauthorized = this.rejectUnauthorized;
5941
5942 var xhr = this.xhr = new XMLHttpRequest(opts);
5943 var self = this;
5944
5945 try {
5946 debug('xhr open %s: %s', this.method, this.uri);
5947 xhr.open(this.method, this.uri, this.async);
5948 try {
5949 if (this.extraHeaders) {
5950 xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
5951 for (var i in this.extraHeaders) {
5952 if (this.extraHeaders.hasOwnProperty(i)) {
5953 xhr.setRequestHeader(i, this.extraHeaders[i]);
5954 }
5955 }
5956 }
5957 } catch (e) {}
5958
5959 if ('POST' === this.method) {
5960 try {
5961 if (this.isBinary) {
5962 xhr.setRequestHeader('Content-type', 'application/octet-stream');
5963 } else {
5964 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
5965 }
5966 } catch (e) {}
5967 }
5968
5969 try {
5970 xhr.setRequestHeader('Accept', '*/*');
5971 } catch (e) {}
5972
5973 // ie6 check
5974 if ('withCredentials' in xhr) {
5975 xhr.withCredentials = this.withCredentials;
5976 }
5977
5978 if (this.requestTimeout) {
5979 xhr.timeout = this.requestTimeout;
5980 }
5981
5982 if (this.hasXDR()) {
5983 xhr.onload = function () {
5984 self.onLoad();
5985 };
5986 xhr.onerror = function () {
5987 self.onError(xhr.responseText);
5988 };
5989 } else {
5990 xhr.onreadystatechange = function () {
5991 if (xhr.readyState === 2) {
5992 try {
5993 var contentType = xhr.getResponseHeader('Content-Type');
5994 if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
5995 xhr.responseType = 'arraybuffer';
5996 }
5997 } catch (e) {}
5998 }
5999 if (4 !== xhr.readyState) return;
6000 if (200 === xhr.status || 1223 === xhr.status) {
6001 self.onLoad();
6002 } else {
6003 // make sure the `error` event handler that's user-set
6004 // does not throw in the same tick and gets caught here
6005 setTimeout(function () {
6006 self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
6007 }, 0);
6008 }
6009 };
6010 }
6011
6012 debug('xhr data %s', this.data);
6013 xhr.send(this.data);
6014 } catch (e) {
6015 // Need to defer since .create() is called directly fhrom the constructor
6016 // and thus the 'error' event can only be only bound *after* this exception
6017 // occurs. Therefore, also, we cannot throw here at all.
6018 setTimeout(function () {
6019 self.onError(e);
6020 }, 0);
6021 return;
6022 }
6023
6024 if (typeof document !== 'undefined') {
6025 this.index = Request.requestsCount++;
6026 Request.requests[this.index] = this;
6027 }
6028};
6029
6030/**
6031 * Called upon successful response.
6032 *
6033 * @api private
6034 */
6035
6036Request.prototype.onSuccess = function () {
6037 this.emit('success');
6038 this.cleanup();
6039};
6040
6041/**
6042 * Called if we have data.
6043 *
6044 * @api private
6045 */
6046
6047Request.prototype.onData = function (data) {
6048 this.emit('data', data);
6049 this.onSuccess();
6050};
6051
6052/**
6053 * Called upon error.
6054 *
6055 * @api private
6056 */
6057
6058Request.prototype.onError = function (err) {
6059 this.emit('error', err);
6060 this.cleanup(true);
6061};
6062
6063/**
6064 * Cleans up house.
6065 *
6066 * @api private
6067 */
6068
6069Request.prototype.cleanup = function (fromError) {
6070 if ('undefined' === typeof this.xhr || null === this.xhr) {
6071 return;
6072 }
6073 // xmlhttprequest
6074 if (this.hasXDR()) {
6075 this.xhr.onload = this.xhr.onerror = empty;
6076 } else {
6077 this.xhr.onreadystatechange = empty;
6078 }
6079
6080 if (fromError) {
6081 try {
6082 this.xhr.abort();
6083 } catch (e) {}
6084 }
6085
6086 if (typeof document !== 'undefined') {
6087 delete Request.requests[this.index];
6088 }
6089
6090 this.xhr = null;
6091};
6092
6093/**
6094 * Called upon load.
6095 *
6096 * @api private
6097 */
6098
6099Request.prototype.onLoad = function () {
6100 var data;
6101 try {
6102 var contentType;
6103 try {
6104 contentType = this.xhr.getResponseHeader('Content-Type');
6105 } catch (e) {}
6106 if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
6107 data = this.xhr.response || this.xhr.responseText;
6108 } else {
6109 data = this.xhr.responseText;
6110 }
6111 } catch (e) {
6112 this.onError(e);
6113 }
6114 if (null != data) {
6115 this.onData(data);
6116 }
6117};
6118
6119/**
6120 * Check if it has XDomainRequest.
6121 *
6122 * @api private
6123 */
6124
6125Request.prototype.hasXDR = function () {
6126 return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
6127};
6128
6129/**
6130 * Aborts the request.
6131 *
6132 * @api public
6133 */
6134
6135Request.prototype.abort = function () {
6136 this.cleanup();
6137};
6138
6139/**
6140 * Aborts pending requests when unloading the window. This is needed to prevent
6141 * memory leaks (e.g. when using IE) and to ensure that no spurious error is
6142 * emitted.
6143 */
6144
6145Request.requestsCount = 0;
6146Request.requests = {};
6147
6148if (typeof document !== 'undefined') {
6149 if (typeof attachEvent === 'function') {
6150 attachEvent('onunload', unloadHandler);
6151 } else if (typeof addEventListener === 'function') {
6152 var terminationEvent = 'onpagehide' in self ? 'pagehide' : 'unload';
6153 addEventListener(terminationEvent, unloadHandler, false);
6154 }
6155}
6156
6157function unloadHandler () {
6158 for (var i in Request.requests) {
6159 if (Request.requests.hasOwnProperty(i)) {
6160 Request.requests[i].abort();
6161 }
6162 }
6163}
6164
6165},{"./polling":47,"component-emitter":37,"component-inherit":38,"debug":50,"xmlhttprequest-ssl":49}],47:[function(require,module,exports){
6166/**
6167 * Module dependencies.
6168 */
6169
6170var Transport = require('../transport');
6171var parseqs = require('parseqs');
6172var parser = require('engine.io-parser');
6173var inherit = require('component-inherit');
6174var yeast = require('yeast');
6175var debug = require('debug')('engine.io-client:polling');
6176
6177/**
6178 * Module exports.
6179 */
6180
6181module.exports = Polling;
6182
6183/**
6184 * Is XHR2 supported?
6185 */
6186
6187var hasXHR2 = (function () {
6188 var XMLHttpRequest = require('xmlhttprequest-ssl');
6189 var xhr = new XMLHttpRequest({ xdomain: false });
6190 return null != xhr.responseType;
6191})();
6192
6193/**
6194 * Polling interface.
6195 *
6196 * @param {Object} opts
6197 * @api private
6198 */
6199
6200function Polling (opts) {
6201 var forceBase64 = (opts && opts.forceBase64);
6202 if (!hasXHR2 || forceBase64) {
6203 this.supportsBinary = false;
6204 }
6205 Transport.call(this, opts);
6206}
6207
6208/**
6209 * Inherits from Transport.
6210 */
6211
6212inherit(Polling, Transport);
6213
6214/**
6215 * Transport name.
6216 */
6217
6218Polling.prototype.name = 'polling';
6219
6220/**
6221 * Opens the socket (triggers polling). We write a PING message to determine
6222 * when the transport is open.
6223 *
6224 * @api private
6225 */
6226
6227Polling.prototype.doOpen = function () {
6228 this.poll();
6229};
6230
6231/**
6232 * Pauses polling.
6233 *
6234 * @param {Function} callback upon buffers are flushed and transport is paused
6235 * @api private
6236 */
6237
6238Polling.prototype.pause = function (onPause) {
6239 var self = this;
6240
6241 this.readyState = 'pausing';
6242
6243 function pause () {
6244 debug('paused');
6245 self.readyState = 'paused';
6246 onPause();
6247 }
6248
6249 if (this.polling || !this.writable) {
6250 var total = 0;
6251
6252 if (this.polling) {
6253 debug('we are currently polling - waiting to pause');
6254 total++;
6255 this.once('pollComplete', function () {
6256 debug('pre-pause polling complete');
6257 --total || pause();
6258 });
6259 }
6260
6261 if (!this.writable) {
6262 debug('we are currently writing - waiting to pause');
6263 total++;
6264 this.once('drain', function () {
6265 debug('pre-pause writing complete');
6266 --total || pause();
6267 });
6268 }
6269 } else {
6270 pause();
6271 }
6272};
6273
6274/**
6275 * Starts polling cycle.
6276 *
6277 * @api public
6278 */
6279
6280Polling.prototype.poll = function () {
6281 debug('polling');
6282 this.polling = true;
6283 this.doPoll();
6284 this.emit('poll');
6285};
6286
6287/**
6288 * Overloads onData to detect payloads.
6289 *
6290 * @api private
6291 */
6292
6293Polling.prototype.onData = function (data) {
6294 var self = this;
6295 debug('polling got data %s', data);
6296 var callback = function (packet, index, total) {
6297 // if its the first message we consider the transport open
6298 if ('opening' === self.readyState) {
6299 self.onOpen();
6300 }
6301
6302 // if its a close packet, we close the ongoing requests
6303 if ('close' === packet.type) {
6304 self.onClose();
6305 return false;
6306 }
6307
6308 // otherwise bypass onData and handle the message
6309 self.onPacket(packet);
6310 };
6311
6312 // decode payload
6313 parser.decodePayload(data, this.socket.binaryType, callback);
6314
6315 // if an event did not trigger closing
6316 if ('closed' !== this.readyState) {
6317 // if we got data we're not polling
6318 this.polling = false;
6319 this.emit('pollComplete');
6320
6321 if ('open' === this.readyState) {
6322 this.poll();
6323 } else {
6324 debug('ignoring poll - transport state "%s"', this.readyState);
6325 }
6326 }
6327};
6328
6329/**
6330 * For polling, send a close packet.
6331 *
6332 * @api private
6333 */
6334
6335Polling.prototype.doClose = function () {
6336 var self = this;
6337
6338 function close () {
6339 debug('writing close packet');
6340 self.write([{ type: 'close' }]);
6341 }
6342
6343 if ('open' === this.readyState) {
6344 debug('transport open - closing');
6345 close();
6346 } else {
6347 // in case we're trying to close while
6348 // handshaking is in progress (GH-164)
6349 debug('transport not open - deferring close');
6350 this.once('open', close);
6351 }
6352};
6353
6354/**
6355 * Writes a packets payload.
6356 *
6357 * @param {Array} data packets
6358 * @param {Function} drain callback
6359 * @api private
6360 */
6361
6362Polling.prototype.write = function (packets) {
6363 var self = this;
6364 this.writable = false;
6365 var callbackfn = function () {
6366 self.writable = true;
6367 self.emit('drain');
6368 };
6369
6370 parser.encodePayload(packets, this.supportsBinary, function (data) {
6371 self.doWrite(data, callbackfn);
6372 });
6373};
6374
6375/**
6376 * Generates uri for connection.
6377 *
6378 * @api private
6379 */
6380
6381Polling.prototype.uri = function () {
6382 var query = this.query || {};
6383 var schema = this.secure ? 'https' : 'http';
6384 var port = '';
6385
6386 // cache busting is forced
6387 if (false !== this.timestampRequests) {
6388 query[this.timestampParam] = yeast();
6389 }
6390
6391 if (!this.supportsBinary && !query.sid) {
6392 query.b64 = 1;
6393 }
6394
6395 query = parseqs.encode(query);
6396
6397 // avoid port if default for schema
6398 if (this.port && (('https' === schema && Number(this.port) !== 443) ||
6399 ('http' === schema && Number(this.port) !== 80))) {
6400 port = ':' + this.port;
6401 }
6402
6403 // prepend ? to query
6404 if (query.length) {
6405 query = '?' + query;
6406 }
6407
6408 var ipv6 = this.hostname.indexOf(':') !== -1;
6409 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
6410};
6411
6412},{"../transport":43,"component-inherit":38,"debug":50,"engine.io-parser":53,"parseqs":62,"xmlhttprequest-ssl":49,"yeast":77}],48:[function(require,module,exports){
6413(function (Buffer){
6414/**
6415 * Module dependencies.
6416 */
6417
6418var Transport = require('../transport');
6419var parser = require('engine.io-parser');
6420var parseqs = require('parseqs');
6421var inherit = require('component-inherit');
6422var yeast = require('yeast');
6423var debug = require('debug')('engine.io-client:websocket');
6424
6425var BrowserWebSocket, NodeWebSocket;
6426
6427if (typeof WebSocket !== 'undefined') {
6428 BrowserWebSocket = WebSocket;
6429} else if (typeof self !== 'undefined') {
6430 BrowserWebSocket = self.WebSocket || self.MozWebSocket;
6431}
6432
6433if (typeof window === 'undefined') {
6434 try {
6435 NodeWebSocket = require('ws');
6436 } catch (e) { }
6437}
6438
6439/**
6440 * Get either the `WebSocket` or `MozWebSocket` globals
6441 * in the browser or try to resolve WebSocket-compatible
6442 * interface exposed by `ws` for Node-like environment.
6443 */
6444
6445var WebSocketImpl = BrowserWebSocket || NodeWebSocket;
6446
6447/**
6448 * Module exports.
6449 */
6450
6451module.exports = WS;
6452
6453/**
6454 * WebSocket transport constructor.
6455 *
6456 * @api {Object} connection options
6457 * @api public
6458 */
6459
6460function WS (opts) {
6461 var forceBase64 = (opts && opts.forceBase64);
6462 if (forceBase64) {
6463 this.supportsBinary = false;
6464 }
6465 this.perMessageDeflate = opts.perMessageDeflate;
6466 this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
6467 this.protocols = opts.protocols;
6468 if (!this.usingBrowserWebSocket) {
6469 WebSocketImpl = NodeWebSocket;
6470 }
6471 Transport.call(this, opts);
6472}
6473
6474/**
6475 * Inherits from Transport.
6476 */
6477
6478inherit(WS, Transport);
6479
6480/**
6481 * Transport name.
6482 *
6483 * @api public
6484 */
6485
6486WS.prototype.name = 'websocket';
6487
6488/*
6489 * WebSockets support binary
6490 */
6491
6492WS.prototype.supportsBinary = true;
6493
6494/**
6495 * Opens socket.
6496 *
6497 * @api private
6498 */
6499
6500WS.prototype.doOpen = function () {
6501 if (!this.check()) {
6502 // let probe timeout
6503 return;
6504 }
6505
6506 var uri = this.uri();
6507 var protocols = this.protocols;
6508 var opts = {
6509 agent: this.agent,
6510 perMessageDeflate: this.perMessageDeflate
6511 };
6512
6513 // SSL options for Node.js client
6514 opts.pfx = this.pfx;
6515 opts.key = this.key;
6516 opts.passphrase = this.passphrase;
6517 opts.cert = this.cert;
6518 opts.ca = this.ca;
6519 opts.ciphers = this.ciphers;
6520 opts.rejectUnauthorized = this.rejectUnauthorized;
6521 if (this.extraHeaders) {
6522 opts.headers = this.extraHeaders;
6523 }
6524 if (this.localAddress) {
6525 opts.localAddress = this.localAddress;
6526 }
6527
6528 try {
6529 this.ws =
6530 this.usingBrowserWebSocket && !this.isReactNative
6531 ? protocols
6532 ? new WebSocketImpl(uri, protocols)
6533 : new WebSocketImpl(uri)
6534 : new WebSocketImpl(uri, protocols, opts);
6535 } catch (err) {
6536 return this.emit('error', err);
6537 }
6538
6539 if (this.ws.binaryType === undefined) {
6540 this.supportsBinary = false;
6541 }
6542
6543 if (this.ws.supports && this.ws.supports.binary) {
6544 this.supportsBinary = true;
6545 this.ws.binaryType = 'nodebuffer';
6546 } else {
6547 this.ws.binaryType = 'arraybuffer';
6548 }
6549
6550 this.addEventListeners();
6551};
6552
6553/**
6554 * Adds event listeners to the socket
6555 *
6556 * @api private
6557 */
6558
6559WS.prototype.addEventListeners = function () {
6560 var self = this;
6561
6562 this.ws.onopen = function () {
6563 self.onOpen();
6564 };
6565 this.ws.onclose = function () {
6566 self.onClose();
6567 };
6568 this.ws.onmessage = function (ev) {
6569 self.onData(ev.data);
6570 };
6571 this.ws.onerror = function (e) {
6572 self.onError('websocket error', e);
6573 };
6574};
6575
6576/**
6577 * Writes data to socket.
6578 *
6579 * @param {Array} array of packets.
6580 * @api private
6581 */
6582
6583WS.prototype.write = function (packets) {
6584 var self = this;
6585 this.writable = false;
6586
6587 // encodePacket efficient as it uses WS framing
6588 // no need for encodePayload
6589 var total = packets.length;
6590 for (var i = 0, l = total; i < l; i++) {
6591 (function (packet) {
6592 parser.encodePacket(packet, self.supportsBinary, function (data) {
6593 if (!self.usingBrowserWebSocket) {
6594 // always create a new object (GH-437)
6595 var opts = {};
6596 if (packet.options) {
6597 opts.compress = packet.options.compress;
6598 }
6599
6600 if (self.perMessageDeflate) {
6601 var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
6602 if (len < self.perMessageDeflate.threshold) {
6603 opts.compress = false;
6604 }
6605 }
6606 }
6607
6608 // Sometimes the websocket has already been closed but the browser didn't
6609 // have a chance of informing us about it yet, in that case send will
6610 // throw an error
6611 try {
6612 if (self.usingBrowserWebSocket) {
6613 // TypeError is thrown when passing the second argument on Safari
6614 self.ws.send(data);
6615 } else {
6616 self.ws.send(data, opts);
6617 }
6618 } catch (e) {
6619 debug('websocket closed before onclose event');
6620 }
6621
6622 --total || done();
6623 });
6624 })(packets[i]);
6625 }
6626
6627 function done () {
6628 self.emit('flush');
6629
6630 // fake drain
6631 // defer to next tick to allow Socket to clear writeBuffer
6632 setTimeout(function () {
6633 self.writable = true;
6634 self.emit('drain');
6635 }, 0);
6636 }
6637};
6638
6639/**
6640 * Called upon close
6641 *
6642 * @api private
6643 */
6644
6645WS.prototype.onClose = function () {
6646 Transport.prototype.onClose.call(this);
6647};
6648
6649/**
6650 * Closes socket.
6651 *
6652 * @api private
6653 */
6654
6655WS.prototype.doClose = function () {
6656 if (typeof this.ws !== 'undefined') {
6657 this.ws.close();
6658 }
6659};
6660
6661/**
6662 * Generates uri for connection.
6663 *
6664 * @api private
6665 */
6666
6667WS.prototype.uri = function () {
6668 var query = this.query || {};
6669 var schema = this.secure ? 'wss' : 'ws';
6670 var port = '';
6671
6672 // avoid port if default for schema
6673 if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
6674 ('ws' === schema && Number(this.port) !== 80))) {
6675 port = ':' + this.port;
6676 }
6677
6678 // append timestamp to URI
6679 if (this.timestampRequests) {
6680 query[this.timestampParam] = yeast();
6681 }
6682
6683 // communicate binary support capabilities
6684 if (!this.supportsBinary) {
6685 query.b64 = 1;
6686 }
6687
6688 query = parseqs.encode(query);
6689
6690 // prepend ? to query
6691 if (query.length) {
6692 query = '?' + query;
6693 }
6694
6695 var ipv6 = this.hostname.indexOf(':') !== -1;
6696 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
6697};
6698
6699/**
6700 * Feature detection for WebSocket.
6701 *
6702 * @return {Boolean} whether this transport is available.
6703 * @api public
6704 */
6705
6706WS.prototype.check = function () {
6707 return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
6708};
6709
6710}).call(this,require("buffer").Buffer)
6711},{"../transport":43,"buffer":35,"component-inherit":38,"debug":50,"engine.io-parser":53,"parseqs":62,"ws":34,"yeast":77}],49:[function(require,module,exports){
6712// browser shim for xmlhttprequest module
6713
6714var hasCORS = require('has-cors');
6715
6716module.exports = function (opts) {
6717 var xdomain = opts.xdomain;
6718
6719 // scheme must be same when usign XDomainRequest
6720 // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
6721 var xscheme = opts.xscheme;
6722
6723 // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
6724 // https://github.com/Automattic/engine.io-client/pull/217
6725 var enablesXDR = opts.enablesXDR;
6726
6727 // XMLHttpRequest can be disabled on IE
6728 try {
6729 if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
6730 return new XMLHttpRequest();
6731 }
6732 } catch (e) { }
6733
6734 // Use XDomainRequest for IE8 if enablesXDR is true
6735 // because loading bar keeps flashing when using jsonp-polling
6736 // https://github.com/yujiosaka/socke.io-ie8-loading-example
6737 try {
6738 if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
6739 return new XDomainRequest();
6740 }
6741 } catch (e) { }
6742
6743 if (!xdomain) {
6744 try {
6745 return new self[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
6746 } catch (e) { }
6747 }
6748};
6749
6750},{"has-cors":57}],50:[function(require,module,exports){
6751(function (process){
6752/* eslint-env browser */
6753
6754/**
6755 * This is the web browser implementation of `debug()`.
6756 */
6757
6758exports.log = log;
6759exports.formatArgs = formatArgs;
6760exports.save = save;
6761exports.load = load;
6762exports.useColors = useColors;
6763exports.storage = localstorage();
6764
6765/**
6766 * Colors.
6767 */
6768
6769exports.colors = [
6770 '#0000CC',
6771 '#0000FF',
6772 '#0033CC',
6773 '#0033FF',
6774 '#0066CC',
6775 '#0066FF',
6776 '#0099CC',
6777 '#0099FF',
6778 '#00CC00',
6779 '#00CC33',
6780 '#00CC66',
6781 '#00CC99',
6782 '#00CCCC',
6783 '#00CCFF',
6784 '#3300CC',
6785 '#3300FF',
6786 '#3333CC',
6787 '#3333FF',
6788 '#3366CC',
6789 '#3366FF',
6790 '#3399CC',
6791 '#3399FF',
6792 '#33CC00',
6793 '#33CC33',
6794 '#33CC66',
6795 '#33CC99',
6796 '#33CCCC',
6797 '#33CCFF',
6798 '#6600CC',
6799 '#6600FF',
6800 '#6633CC',
6801 '#6633FF',
6802 '#66CC00',
6803 '#66CC33',
6804 '#9900CC',
6805 '#9900FF',
6806 '#9933CC',
6807 '#9933FF',
6808 '#99CC00',
6809 '#99CC33',
6810 '#CC0000',
6811 '#CC0033',
6812 '#CC0066',
6813 '#CC0099',
6814 '#CC00CC',
6815 '#CC00FF',
6816 '#CC3300',
6817 '#CC3333',
6818 '#CC3366',
6819 '#CC3399',
6820 '#CC33CC',
6821 '#CC33FF',
6822 '#CC6600',
6823 '#CC6633',
6824 '#CC9900',
6825 '#CC9933',
6826 '#CCCC00',
6827 '#CCCC33',
6828 '#FF0000',
6829 '#FF0033',
6830 '#FF0066',
6831 '#FF0099',
6832 '#FF00CC',
6833 '#FF00FF',
6834 '#FF3300',
6835 '#FF3333',
6836 '#FF3366',
6837 '#FF3399',
6838 '#FF33CC',
6839 '#FF33FF',
6840 '#FF6600',
6841 '#FF6633',
6842 '#FF9900',
6843 '#FF9933',
6844 '#FFCC00',
6845 '#FFCC33'
6846];
6847
6848/**
6849 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
6850 * and the Firebug extension (any Firefox version) are known
6851 * to support "%c" CSS customizations.
6852 *
6853 * TODO: add a `localStorage` variable to explicitly enable/disable colors
6854 */
6855
6856// eslint-disable-next-line complexity
6857function useColors() {
6858 // NB: In an Electron preload script, document will be defined but not fully
6859 // initialized. Since we know we're in Chrome, we'll just detect this case
6860 // explicitly
6861 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
6862 return true;
6863 }
6864
6865 // Internet Explorer and Edge do not support colors.
6866 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
6867 return false;
6868 }
6869
6870 // Is webkit? http://stackoverflow.com/a/16459606/376773
6871 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
6872 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
6873 // Is firebug? http://stackoverflow.com/a/398120/376773
6874 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
6875 // Is firefox >= v31?
6876 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
6877 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
6878 // Double check webkit in userAgent just in case we are in a worker
6879 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
6880}
6881
6882/**
6883 * Colorize log arguments if enabled.
6884 *
6885 * @api public
6886 */
6887
6888function formatArgs(args) {
6889 args[0] = (this.useColors ? '%c' : '') +
6890 this.namespace +
6891 (this.useColors ? ' %c' : ' ') +
6892 args[0] +
6893 (this.useColors ? '%c ' : ' ') +
6894 '+' + module.exports.humanize(this.diff);
6895
6896 if (!this.useColors) {
6897 return;
6898 }
6899
6900 const c = 'color: ' + this.color;
6901 args.splice(1, 0, c, 'color: inherit');
6902
6903 // The final "%c" is somewhat tricky, because there could be other
6904 // arguments passed either before or after the %c, so we need to
6905 // figure out the correct index to insert the CSS into
6906 let index = 0;
6907 let lastC = 0;
6908 args[0].replace(/%[a-zA-Z%]/g, match => {
6909 if (match === '%%') {
6910 return;
6911 }
6912 index++;
6913 if (match === '%c') {
6914 // We only are interested in the *last* %c
6915 // (the user may have provided their own)
6916 lastC = index;
6917 }
6918 });
6919
6920 args.splice(lastC, 0, c);
6921}
6922
6923/**
6924 * Invokes `console.log()` when available.
6925 * No-op when `console.log` is not a "function".
6926 *
6927 * @api public
6928 */
6929function log(...args) {
6930 // This hackery is required for IE8/9, where
6931 // the `console.log` function doesn't have 'apply'
6932 return typeof console === 'object' &&
6933 console.log &&
6934 console.log(...args);
6935}
6936
6937/**
6938 * Save `namespaces`.
6939 *
6940 * @param {String} namespaces
6941 * @api private
6942 */
6943function save(namespaces) {
6944 try {
6945 if (namespaces) {
6946 exports.storage.setItem('debug', namespaces);
6947 } else {
6948 exports.storage.removeItem('debug');
6949 }
6950 } catch (error) {
6951 // Swallow
6952 // XXX (@Qix-) should we be logging these?
6953 }
6954}
6955
6956/**
6957 * Load `namespaces`.
6958 *
6959 * @return {String} returns the previously persisted debug modes
6960 * @api private
6961 */
6962function load() {
6963 let r;
6964 try {
6965 r = exports.storage.getItem('debug');
6966 } catch (error) {
6967 // Swallow
6968 // XXX (@Qix-) should we be logging these?
6969 }
6970
6971 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
6972 if (!r && typeof process !== 'undefined' && 'env' in process) {
6973 r = process.env.DEBUG;
6974 }
6975
6976 return r;
6977}
6978
6979/**
6980 * Localstorage attempts to return the localstorage.
6981 *
6982 * This is necessary because safari throws
6983 * when a user disables cookies/localstorage
6984 * and you attempt to access it.
6985 *
6986 * @return {LocalStorage}
6987 * @api private
6988 */
6989
6990function localstorage() {
6991 try {
6992 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
6993 // The Browser also has localStorage in the global context.
6994 return localStorage;
6995 } catch (error) {
6996 // Swallow
6997 // XXX (@Qix-) should we be logging these?
6998 }
6999}
7000
7001module.exports = require('./common')(exports);
7002
7003const {formatters} = module.exports;
7004
7005/**
7006 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
7007 */
7008
7009formatters.j = function (v) {
7010 try {
7011 return JSON.stringify(v);
7012 } catch (error) {
7013 return '[UnexpectedJSONParseError]: ' + error.message;
7014 }
7015};
7016
7017}).call(this,require('_process'))
7018},{"./common":51,"_process":64}],51:[function(require,module,exports){
7019
7020/**
7021 * This is the common logic for both the Node.js and web browser
7022 * implementations of `debug()`.
7023 */
7024
7025function setup(env) {
7026 createDebug.debug = createDebug;
7027 createDebug.default = createDebug;
7028 createDebug.coerce = coerce;
7029 createDebug.disable = disable;
7030 createDebug.enable = enable;
7031 createDebug.enabled = enabled;
7032 createDebug.humanize = require('ms');
7033
7034 Object.keys(env).forEach(key => {
7035 createDebug[key] = env[key];
7036 });
7037
7038 /**
7039 * Active `debug` instances.
7040 */
7041 createDebug.instances = [];
7042
7043 /**
7044 * The currently active debug mode names, and names to skip.
7045 */
7046
7047 createDebug.names = [];
7048 createDebug.skips = [];
7049
7050 /**
7051 * Map of special "%n" handling functions, for the debug "format" argument.
7052 *
7053 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
7054 */
7055 createDebug.formatters = {};
7056
7057 /**
7058 * Selects a color for a debug namespace
7059 * @param {String} namespace The namespace string for the for the debug instance to be colored
7060 * @return {Number|String} An ANSI color code for the given namespace
7061 * @api private
7062 */
7063 function selectColor(namespace) {
7064 let hash = 0;
7065
7066 for (let i = 0; i < namespace.length; i++) {
7067 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
7068 hash |= 0; // Convert to 32bit integer
7069 }
7070
7071 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
7072 }
7073 createDebug.selectColor = selectColor;
7074
7075 /**
7076 * Create a debugger with the given `namespace`.
7077 *
7078 * @param {String} namespace
7079 * @return {Function}
7080 * @api public
7081 */
7082 function createDebug(namespace) {
7083 let prevTime;
7084
7085 function debug(...args) {
7086 // Disabled?
7087 if (!debug.enabled) {
7088 return;
7089 }
7090
7091 const self = debug;
7092
7093 // Set `diff` timestamp
7094 const curr = Number(new Date());
7095 const ms = curr - (prevTime || curr);
7096 self.diff = ms;
7097 self.prev = prevTime;
7098 self.curr = curr;
7099 prevTime = curr;
7100
7101 args[0] = createDebug.coerce(args[0]);
7102
7103 if (typeof args[0] !== 'string') {
7104 // Anything else let's inspect with %O
7105 args.unshift('%O');
7106 }
7107
7108 // Apply any `formatters` transformations
7109 let index = 0;
7110 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
7111 // If we encounter an escaped % then don't increase the array index
7112 if (match === '%%') {
7113 return match;
7114 }
7115 index++;
7116 const formatter = createDebug.formatters[format];
7117 if (typeof formatter === 'function') {
7118 const val = args[index];
7119 match = formatter.call(self, val);
7120
7121 // Now we need to remove `args[index]` since it's inlined in the `format`
7122 args.splice(index, 1);
7123 index--;
7124 }
7125 return match;
7126 });
7127
7128 // Apply env-specific formatting (colors, etc.)
7129 createDebug.formatArgs.call(self, args);
7130
7131 const logFn = self.log || createDebug.log;
7132 logFn.apply(self, args);
7133 }
7134
7135 debug.namespace = namespace;
7136 debug.enabled = createDebug.enabled(namespace);
7137 debug.useColors = createDebug.useColors();
7138 debug.color = selectColor(namespace);
7139 debug.destroy = destroy;
7140 debug.extend = extend;
7141 // Debug.formatArgs = formatArgs;
7142 // debug.rawLog = rawLog;
7143
7144 // env-specific initialization logic for debug instances
7145 if (typeof createDebug.init === 'function') {
7146 createDebug.init(debug);
7147 }
7148
7149 createDebug.instances.push(debug);
7150
7151 return debug;
7152 }
7153
7154 function destroy() {
7155 const index = createDebug.instances.indexOf(this);
7156 if (index !== -1) {
7157 createDebug.instances.splice(index, 1);
7158 return true;
7159 }
7160 return false;
7161 }
7162
7163 function extend(namespace, delimiter) {
7164 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
7165 newDebug.log = this.log;
7166 return newDebug;
7167 }
7168
7169 /**
7170 * Enables a debug mode by namespaces. This can include modes
7171 * separated by a colon and wildcards.
7172 *
7173 * @param {String} namespaces
7174 * @api public
7175 */
7176 function enable(namespaces) {
7177 createDebug.save(namespaces);
7178
7179 createDebug.names = [];
7180 createDebug.skips = [];
7181
7182 let i;
7183 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
7184 const len = split.length;
7185
7186 for (i = 0; i < len; i++) {
7187 if (!split[i]) {
7188 // ignore empty strings
7189 continue;
7190 }
7191
7192 namespaces = split[i].replace(/\*/g, '.*?');
7193
7194 if (namespaces[0] === '-') {
7195 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
7196 } else {
7197 createDebug.names.push(new RegExp('^' + namespaces + '$'));
7198 }
7199 }
7200
7201 for (i = 0; i < createDebug.instances.length; i++) {
7202 const instance = createDebug.instances[i];
7203 instance.enabled = createDebug.enabled(instance.namespace);
7204 }
7205 }
7206
7207 /**
7208 * Disable debug output.
7209 *
7210 * @return {String} namespaces
7211 * @api public
7212 */
7213 function disable() {
7214 const namespaces = [
7215 ...createDebug.names.map(toNamespace),
7216 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
7217 ].join(',');
7218 createDebug.enable('');
7219 return namespaces;
7220 }
7221
7222 /**
7223 * Returns true if the given mode name is enabled, false otherwise.
7224 *
7225 * @param {String} name
7226 * @return {Boolean}
7227 * @api public
7228 */
7229 function enabled(name) {
7230 if (name[name.length - 1] === '*') {
7231 return true;
7232 }
7233
7234 let i;
7235 let len;
7236
7237 for (i = 0, len = createDebug.skips.length; i < len; i++) {
7238 if (createDebug.skips[i].test(name)) {
7239 return false;
7240 }
7241 }
7242
7243 for (i = 0, len = createDebug.names.length; i < len; i++) {
7244 if (createDebug.names[i].test(name)) {
7245 return true;
7246 }
7247 }
7248
7249 return false;
7250 }
7251
7252 /**
7253 * Convert regexp to namespace
7254 *
7255 * @param {RegExp} regxep
7256 * @return {String} namespace
7257 * @api private
7258 */
7259 function toNamespace(regexp) {
7260 return regexp.toString()
7261 .substring(2, regexp.toString().length - 2)
7262 .replace(/\.\*\?$/, '*');
7263 }
7264
7265 /**
7266 * Coerce `val`.
7267 *
7268 * @param {Mixed} val
7269 * @return {Mixed}
7270 * @api private
7271 */
7272 function coerce(val) {
7273 if (val instanceof Error) {
7274 return val.stack || val.message;
7275 }
7276 return val;
7277 }
7278
7279 createDebug.enable(createDebug.load());
7280
7281 return createDebug;
7282}
7283
7284module.exports = setup;
7285
7286},{"ms":52}],52:[function(require,module,exports){
7287/**
7288 * Helpers.
7289 */
7290
7291var s = 1000;
7292var m = s * 60;
7293var h = m * 60;
7294var d = h * 24;
7295var w = d * 7;
7296var y = d * 365.25;
7297
7298/**
7299 * Parse or format the given `val`.
7300 *
7301 * Options:
7302 *
7303 * - `long` verbose formatting [false]
7304 *
7305 * @param {String|Number} val
7306 * @param {Object} [options]
7307 * @throws {Error} throw an error if val is not a non-empty string or a number
7308 * @return {String|Number}
7309 * @api public
7310 */
7311
7312module.exports = function(val, options) {
7313 options = options || {};
7314 var type = typeof val;
7315 if (type === 'string' && val.length > 0) {
7316 return parse(val);
7317 } else if (type === 'number' && isFinite(val)) {
7318 return options.long ? fmtLong(val) : fmtShort(val);
7319 }
7320 throw new Error(
7321 'val is not a non-empty string or a valid number. val=' +
7322 JSON.stringify(val)
7323 );
7324};
7325
7326/**
7327 * Parse the given `str` and return milliseconds.
7328 *
7329 * @param {String} str
7330 * @return {Number}
7331 * @api private
7332 */
7333
7334function parse(str) {
7335 str = String(str);
7336 if (str.length > 100) {
7337 return;
7338 }
7339 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
7340 str
7341 );
7342 if (!match) {
7343 return;
7344 }
7345 var n = parseFloat(match[1]);
7346 var type = (match[2] || 'ms').toLowerCase();
7347 switch (type) {
7348 case 'years':
7349 case 'year':
7350 case 'yrs':
7351 case 'yr':
7352 case 'y':
7353 return n * y;
7354 case 'weeks':
7355 case 'week':
7356 case 'w':
7357 return n * w;
7358 case 'days':
7359 case 'day':
7360 case 'd':
7361 return n * d;
7362 case 'hours':
7363 case 'hour':
7364 case 'hrs':
7365 case 'hr':
7366 case 'h':
7367 return n * h;
7368 case 'minutes':
7369 case 'minute':
7370 case 'mins':
7371 case 'min':
7372 case 'm':
7373 return n * m;
7374 case 'seconds':
7375 case 'second':
7376 case 'secs':
7377 case 'sec':
7378 case 's':
7379 return n * s;
7380 case 'milliseconds':
7381 case 'millisecond':
7382 case 'msecs':
7383 case 'msec':
7384 case 'ms':
7385 return n;
7386 default:
7387 return undefined;
7388 }
7389}
7390
7391/**
7392 * Short format for `ms`.
7393 *
7394 * @param {Number} ms
7395 * @return {String}
7396 * @api private
7397 */
7398
7399function fmtShort(ms) {
7400 var msAbs = Math.abs(ms);
7401 if (msAbs >= d) {
7402 return Math.round(ms / d) + 'd';
7403 }
7404 if (msAbs >= h) {
7405 return Math.round(ms / h) + 'h';
7406 }
7407 if (msAbs >= m) {
7408 return Math.round(ms / m) + 'm';
7409 }
7410 if (msAbs >= s) {
7411 return Math.round(ms / s) + 's';
7412 }
7413 return ms + 'ms';
7414}
7415
7416/**
7417 * Long format for `ms`.
7418 *
7419 * @param {Number} ms
7420 * @return {String}
7421 * @api private
7422 */
7423
7424function fmtLong(ms) {
7425 var msAbs = Math.abs(ms);
7426 if (msAbs >= d) {
7427 return plural(ms, msAbs, d, 'day');
7428 }
7429 if (msAbs >= h) {
7430 return plural(ms, msAbs, h, 'hour');
7431 }
7432 if (msAbs >= m) {
7433 return plural(ms, msAbs, m, 'minute');
7434 }
7435 if (msAbs >= s) {
7436 return plural(ms, msAbs, s, 'second');
7437 }
7438 return ms + ' ms';
7439}
7440
7441/**
7442 * Pluralization helper.
7443 */
7444
7445function plural(ms, msAbs, n, name) {
7446 var isPlural = msAbs >= n * 1.5;
7447 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
7448}
7449
7450},{}],53:[function(require,module,exports){
7451/**
7452 * Module dependencies.
7453 */
7454
7455var keys = require('./keys');
7456var hasBinary = require('has-binary2');
7457var sliceBuffer = require('arraybuffer.slice');
7458var after = require('after');
7459var utf8 = require('./utf8');
7460
7461var base64encoder;
7462if (typeof ArrayBuffer !== 'undefined') {
7463 base64encoder = require('base64-arraybuffer');
7464}
7465
7466/**
7467 * Check if we are running an android browser. That requires us to use
7468 * ArrayBuffer with polling transports...
7469 *
7470 * http://ghinda.net/jpeg-blob-ajax-android/
7471 */
7472
7473var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
7474
7475/**
7476 * Check if we are running in PhantomJS.
7477 * Uploading a Blob with PhantomJS does not work correctly, as reported here:
7478 * https://github.com/ariya/phantomjs/issues/11395
7479 * @type boolean
7480 */
7481var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
7482
7483/**
7484 * When true, avoids using Blobs to encode payloads.
7485 * @type boolean
7486 */
7487var dontSendBlobs = isAndroid || isPhantomJS;
7488
7489/**
7490 * Current protocol version.
7491 */
7492
7493exports.protocol = 3;
7494
7495/**
7496 * Packet types.
7497 */
7498
7499var packets = exports.packets = {
7500 open: 0 // non-ws
7501 , close: 1 // non-ws
7502 , ping: 2
7503 , pong: 3
7504 , message: 4
7505 , upgrade: 5
7506 , noop: 6
7507};
7508
7509var packetslist = keys(packets);
7510
7511/**
7512 * Premade error packet.
7513 */
7514
7515var err = { type: 'error', data: 'parser error' };
7516
7517/**
7518 * Create a blob api even for blob builder when vendor prefixes exist
7519 */
7520
7521var Blob = require('blob');
7522
7523/**
7524 * Encodes a packet.
7525 *
7526 * <packet type id> [ <data> ]
7527 *
7528 * Example:
7529 *
7530 * 5hello world
7531 * 3
7532 * 4
7533 *
7534 * Binary is encoded in an identical principle
7535 *
7536 * @api private
7537 */
7538
7539exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
7540 if (typeof supportsBinary === 'function') {
7541 callback = supportsBinary;
7542 supportsBinary = false;
7543 }
7544
7545 if (typeof utf8encode === 'function') {
7546 callback = utf8encode;
7547 utf8encode = null;
7548 }
7549
7550 var data = (packet.data === undefined)
7551 ? undefined
7552 : packet.data.buffer || packet.data;
7553
7554 if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
7555 return encodeArrayBuffer(packet, supportsBinary, callback);
7556 } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
7557 return encodeBlob(packet, supportsBinary, callback);
7558 }
7559
7560 // might be an object with { base64: true, data: dataAsBase64String }
7561 if (data && data.base64) {
7562 return encodeBase64Object(packet, callback);
7563 }
7564
7565 // Sending data as a utf-8 string
7566 var encoded = packets[packet.type];
7567
7568 // data fragment is optional
7569 if (undefined !== packet.data) {
7570 encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
7571 }
7572
7573 return callback('' + encoded);
7574
7575};
7576
7577function encodeBase64Object(packet, callback) {
7578 // packet data is an object { base64: true, data: dataAsBase64String }
7579 var message = 'b' + exports.packets[packet.type] + packet.data.data;
7580 return callback(message);
7581}
7582
7583/**
7584 * Encode packet helpers for binary types
7585 */
7586
7587function encodeArrayBuffer(packet, supportsBinary, callback) {
7588 if (!supportsBinary) {
7589 return exports.encodeBase64Packet(packet, callback);
7590 }
7591
7592 var data = packet.data;
7593 var contentArray = new Uint8Array(data);
7594 var resultBuffer = new Uint8Array(1 + data.byteLength);
7595
7596 resultBuffer[0] = packets[packet.type];
7597 for (var i = 0; i < contentArray.length; i++) {
7598 resultBuffer[i+1] = contentArray[i];
7599 }
7600
7601 return callback(resultBuffer.buffer);
7602}
7603
7604function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
7605 if (!supportsBinary) {
7606 return exports.encodeBase64Packet(packet, callback);
7607 }
7608
7609 var fr = new FileReader();
7610 fr.onload = function() {
7611 exports.encodePacket({ type: packet.type, data: fr.result }, supportsBinary, true, callback);
7612 };
7613 return fr.readAsArrayBuffer(packet.data);
7614}
7615
7616function encodeBlob(packet, supportsBinary, callback) {
7617 if (!supportsBinary) {
7618 return exports.encodeBase64Packet(packet, callback);
7619 }
7620
7621 if (dontSendBlobs) {
7622 return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
7623 }
7624
7625 var length = new Uint8Array(1);
7626 length[0] = packets[packet.type];
7627 var blob = new Blob([length.buffer, packet.data]);
7628
7629 return callback(blob);
7630}
7631
7632/**
7633 * Encodes a packet with binary data in a base64 string
7634 *
7635 * @param {Object} packet, has `type` and `data`
7636 * @return {String} base64 encoded message
7637 */
7638
7639exports.encodeBase64Packet = function(packet, callback) {
7640 var message = 'b' + exports.packets[packet.type];
7641 if (typeof Blob !== 'undefined' && packet.data instanceof Blob) {
7642 var fr = new FileReader();
7643 fr.onload = function() {
7644 var b64 = fr.result.split(',')[1];
7645 callback(message + b64);
7646 };
7647 return fr.readAsDataURL(packet.data);
7648 }
7649
7650 var b64data;
7651 try {
7652 b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
7653 } catch (e) {
7654 // iPhone Safari doesn't let you apply with typed arrays
7655 var typed = new Uint8Array(packet.data);
7656 var basic = new Array(typed.length);
7657 for (var i = 0; i < typed.length; i++) {
7658 basic[i] = typed[i];
7659 }
7660 b64data = String.fromCharCode.apply(null, basic);
7661 }
7662 message += btoa(b64data);
7663 return callback(message);
7664};
7665
7666/**
7667 * Decodes a packet. Changes format to Blob if requested.
7668 *
7669 * @return {Object} with `type` and `data` (if any)
7670 * @api private
7671 */
7672
7673exports.decodePacket = function (data, binaryType, utf8decode) {
7674 if (data === undefined) {
7675 return err;
7676 }
7677 // String data
7678 if (typeof data === 'string') {
7679 if (data.charAt(0) === 'b') {
7680 return exports.decodeBase64Packet(data.substr(1), binaryType);
7681 }
7682
7683 if (utf8decode) {
7684 data = tryDecode(data);
7685 if (data === false) {
7686 return err;
7687 }
7688 }
7689 var type = data.charAt(0);
7690
7691 if (Number(type) != type || !packetslist[type]) {
7692 return err;
7693 }
7694
7695 if (data.length > 1) {
7696 return { type: packetslist[type], data: data.substring(1) };
7697 } else {
7698 return { type: packetslist[type] };
7699 }
7700 }
7701
7702 var asArray = new Uint8Array(data);
7703 var type = asArray[0];
7704 var rest = sliceBuffer(data, 1);
7705 if (Blob && binaryType === 'blob') {
7706 rest = new Blob([rest]);
7707 }
7708 return { type: packetslist[type], data: rest };
7709};
7710
7711function tryDecode(data) {
7712 try {
7713 data = utf8.decode(data, { strict: false });
7714 } catch (e) {
7715 return false;
7716 }
7717 return data;
7718}
7719
7720/**
7721 * Decodes a packet encoded in a base64 string
7722 *
7723 * @param {String} base64 encoded message
7724 * @return {Object} with `type` and `data` (if any)
7725 */
7726
7727exports.decodeBase64Packet = function(msg, binaryType) {
7728 var type = packetslist[msg.charAt(0)];
7729 if (!base64encoder) {
7730 return { type: type, data: { base64: true, data: msg.substr(1) } };
7731 }
7732
7733 var data = base64encoder.decode(msg.substr(1));
7734
7735 if (binaryType === 'blob' && Blob) {
7736 data = new Blob([data]);
7737 }
7738
7739 return { type: type, data: data };
7740};
7741
7742/**
7743 * Encodes multiple messages (payload).
7744 *
7745 * <length>:data
7746 *
7747 * Example:
7748 *
7749 * 11:hello world2:hi
7750 *
7751 * If any contents are binary, they will be encoded as base64 strings. Base64
7752 * encoded strings are marked with a b before the length specifier
7753 *
7754 * @param {Array} packets
7755 * @api private
7756 */
7757
7758exports.encodePayload = function (packets, supportsBinary, callback) {
7759 if (typeof supportsBinary === 'function') {
7760 callback = supportsBinary;
7761 supportsBinary = null;
7762 }
7763
7764 var isBinary = hasBinary(packets);
7765
7766 if (supportsBinary && isBinary) {
7767 if (Blob && !dontSendBlobs) {
7768 return exports.encodePayloadAsBlob(packets, callback);
7769 }
7770
7771 return exports.encodePayloadAsArrayBuffer(packets, callback);
7772 }
7773
7774 if (!packets.length) {
7775 return callback('0:');
7776 }
7777
7778 function setLengthHeader(message) {
7779 return message.length + ':' + message;
7780 }
7781
7782 function encodeOne(packet, doneCallback) {
7783 exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
7784 doneCallback(null, setLengthHeader(message));
7785 });
7786 }
7787
7788 map(packets, encodeOne, function(err, results) {
7789 return callback(results.join(''));
7790 });
7791};
7792
7793/**
7794 * Async array map using after
7795 */
7796
7797function map(ary, each, done) {
7798 var result = new Array(ary.length);
7799 var next = after(ary.length, done);
7800
7801 var eachWithIndex = function(i, el, cb) {
7802 each(el, function(error, msg) {
7803 result[i] = msg;
7804 cb(error, result);
7805 });
7806 };
7807
7808 for (var i = 0; i < ary.length; i++) {
7809 eachWithIndex(i, ary[i], next);
7810 }
7811}
7812
7813/*
7814 * Decodes data when a payload is maybe expected. Possible binary contents are
7815 * decoded from their base64 representation
7816 *
7817 * @param {String} data, callback method
7818 * @api public
7819 */
7820
7821exports.decodePayload = function (data, binaryType, callback) {
7822 if (typeof data !== 'string') {
7823 return exports.decodePayloadAsBinary(data, binaryType, callback);
7824 }
7825
7826 if (typeof binaryType === 'function') {
7827 callback = binaryType;
7828 binaryType = null;
7829 }
7830
7831 var packet;
7832 if (data === '') {
7833 // parser error - ignoring payload
7834 return callback(err, 0, 1);
7835 }
7836
7837 var length = '', n, msg;
7838
7839 for (var i = 0, l = data.length; i < l; i++) {
7840 var chr = data.charAt(i);
7841
7842 if (chr !== ':') {
7843 length += chr;
7844 continue;
7845 }
7846
7847 if (length === '' || (length != (n = Number(length)))) {
7848 // parser error - ignoring payload
7849 return callback(err, 0, 1);
7850 }
7851
7852 msg = data.substr(i + 1, n);
7853
7854 if (length != msg.length) {
7855 // parser error - ignoring payload
7856 return callback(err, 0, 1);
7857 }
7858
7859 if (msg.length) {
7860 packet = exports.decodePacket(msg, binaryType, false);
7861
7862 if (err.type === packet.type && err.data === packet.data) {
7863 // parser error in individual packet - ignoring payload
7864 return callback(err, 0, 1);
7865 }
7866
7867 var ret = callback(packet, i + n, l);
7868 if (false === ret) return;
7869 }
7870
7871 // advance cursor
7872 i += n;
7873 length = '';
7874 }
7875
7876 if (length !== '') {
7877 // parser error - ignoring payload
7878 return callback(err, 0, 1);
7879 }
7880
7881};
7882
7883/**
7884 * Encodes multiple messages (payload) as binary.
7885 *
7886 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
7887 * 255><data>
7888 *
7889 * Example:
7890 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
7891 *
7892 * @param {Array} packets
7893 * @return {ArrayBuffer} encoded payload
7894 * @api private
7895 */
7896
7897exports.encodePayloadAsArrayBuffer = function(packets, callback) {
7898 if (!packets.length) {
7899 return callback(new ArrayBuffer(0));
7900 }
7901
7902 function encodeOne(packet, doneCallback) {
7903 exports.encodePacket(packet, true, true, function(data) {
7904 return doneCallback(null, data);
7905 });
7906 }
7907
7908 map(packets, encodeOne, function(err, encodedPackets) {
7909 var totalLength = encodedPackets.reduce(function(acc, p) {
7910 var len;
7911 if (typeof p === 'string'){
7912 len = p.length;
7913 } else {
7914 len = p.byteLength;
7915 }
7916 return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
7917 }, 0);
7918
7919 var resultArray = new Uint8Array(totalLength);
7920
7921 var bufferIndex = 0;
7922 encodedPackets.forEach(function(p) {
7923 var isString = typeof p === 'string';
7924 var ab = p;
7925 if (isString) {
7926 var view = new Uint8Array(p.length);
7927 for (var i = 0; i < p.length; i++) {
7928 view[i] = p.charCodeAt(i);
7929 }
7930 ab = view.buffer;
7931 }
7932
7933 if (isString) { // not true binary
7934 resultArray[bufferIndex++] = 0;
7935 } else { // true binary
7936 resultArray[bufferIndex++] = 1;
7937 }
7938
7939 var lenStr = ab.byteLength.toString();
7940 for (var i = 0; i < lenStr.length; i++) {
7941 resultArray[bufferIndex++] = parseInt(lenStr[i]);
7942 }
7943 resultArray[bufferIndex++] = 255;
7944
7945 var view = new Uint8Array(ab);
7946 for (var i = 0; i < view.length; i++) {
7947 resultArray[bufferIndex++] = view[i];
7948 }
7949 });
7950
7951 return callback(resultArray.buffer);
7952 });
7953};
7954
7955/**
7956 * Encode as Blob
7957 */
7958
7959exports.encodePayloadAsBlob = function(packets, callback) {
7960 function encodeOne(packet, doneCallback) {
7961 exports.encodePacket(packet, true, true, function(encoded) {
7962 var binaryIdentifier = new Uint8Array(1);
7963 binaryIdentifier[0] = 1;
7964 if (typeof encoded === 'string') {
7965 var view = new Uint8Array(encoded.length);
7966 for (var i = 0; i < encoded.length; i++) {
7967 view[i] = encoded.charCodeAt(i);
7968 }
7969 encoded = view.buffer;
7970 binaryIdentifier[0] = 0;
7971 }
7972
7973 var len = (encoded instanceof ArrayBuffer)
7974 ? encoded.byteLength
7975 : encoded.size;
7976
7977 var lenStr = len.toString();
7978 var lengthAry = new Uint8Array(lenStr.length + 1);
7979 for (var i = 0; i < lenStr.length; i++) {
7980 lengthAry[i] = parseInt(lenStr[i]);
7981 }
7982 lengthAry[lenStr.length] = 255;
7983
7984 if (Blob) {
7985 var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
7986 doneCallback(null, blob);
7987 }
7988 });
7989 }
7990
7991 map(packets, encodeOne, function(err, results) {
7992 return callback(new Blob(results));
7993 });
7994};
7995
7996/*
7997 * Decodes data when a payload is maybe expected. Strings are decoded by
7998 * interpreting each byte as a key code for entries marked to start with 0. See
7999 * description of encodePayloadAsBinary
8000 *
8001 * @param {ArrayBuffer} data, callback method
8002 * @api public
8003 */
8004
8005exports.decodePayloadAsBinary = function (data, binaryType, callback) {
8006 if (typeof binaryType === 'function') {
8007 callback = binaryType;
8008 binaryType = null;
8009 }
8010
8011 var bufferTail = data;
8012 var buffers = [];
8013
8014 while (bufferTail.byteLength > 0) {
8015 var tailArray = new Uint8Array(bufferTail);
8016 var isString = tailArray[0] === 0;
8017 var msgLength = '';
8018
8019 for (var i = 1; ; i++) {
8020 if (tailArray[i] === 255) break;
8021
8022 // 310 = char length of Number.MAX_VALUE
8023 if (msgLength.length > 310) {
8024 return callback(err, 0, 1);
8025 }
8026
8027 msgLength += tailArray[i];
8028 }
8029
8030 bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
8031 msgLength = parseInt(msgLength);
8032
8033 var msg = sliceBuffer(bufferTail, 0, msgLength);
8034 if (isString) {
8035 try {
8036 msg = String.fromCharCode.apply(null, new Uint8Array(msg));
8037 } catch (e) {
8038 // iPhone Safari doesn't let you apply to typed arrays
8039 var typed = new Uint8Array(msg);
8040 msg = '';
8041 for (var i = 0; i < typed.length; i++) {
8042 msg += String.fromCharCode(typed[i]);
8043 }
8044 }
8045 }
8046
8047 buffers.push(msg);
8048 bufferTail = sliceBuffer(bufferTail, msgLength);
8049 }
8050
8051 var total = buffers.length;
8052 buffers.forEach(function(buffer, i) {
8053 callback(exports.decodePacket(buffer, binaryType, true), i, total);
8054 });
8055};
8056
8057},{"./keys":54,"./utf8":55,"after":2,"arraybuffer.slice":3,"base64-arraybuffer":31,"blob":33,"has-binary2":56}],54:[function(require,module,exports){
8058
8059/**
8060 * Gets the keys for an object.
8061 *
8062 * @return {Array} keys
8063 * @api private
8064 */
8065
8066module.exports = Object.keys || function keys (obj){
8067 var arr = [];
8068 var has = Object.prototype.hasOwnProperty;
8069
8070 for (var i in obj) {
8071 if (has.call(obj, i)) {
8072 arr.push(i);
8073 }
8074 }
8075 return arr;
8076};
8077
8078},{}],55:[function(require,module,exports){
8079/*! https://mths.be/utf8js v2.1.2 by @mathias */
8080
8081var stringFromCharCode = String.fromCharCode;
8082
8083// Taken from https://mths.be/punycode
8084function ucs2decode(string) {
8085 var output = [];
8086 var counter = 0;
8087 var length = string.length;
8088 var value;
8089 var extra;
8090 while (counter < length) {
8091 value = string.charCodeAt(counter++);
8092 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
8093 // high surrogate, and there is a next character
8094 extra = string.charCodeAt(counter++);
8095 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
8096 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
8097 } else {
8098 // unmatched surrogate; only append this code unit, in case the next
8099 // code unit is the high surrogate of a surrogate pair
8100 output.push(value);
8101 counter--;
8102 }
8103 } else {
8104 output.push(value);
8105 }
8106 }
8107 return output;
8108}
8109
8110// Taken from https://mths.be/punycode
8111function ucs2encode(array) {
8112 var length = array.length;
8113 var index = -1;
8114 var value;
8115 var output = '';
8116 while (++index < length) {
8117 value = array[index];
8118 if (value > 0xFFFF) {
8119 value -= 0x10000;
8120 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
8121 value = 0xDC00 | value & 0x3FF;
8122 }
8123 output += stringFromCharCode(value);
8124 }
8125 return output;
8126}
8127
8128function checkScalarValue(codePoint, strict) {
8129 if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
8130 if (strict) {
8131 throw Error(
8132 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
8133 ' is not a scalar value'
8134 );
8135 }
8136 return false;
8137 }
8138 return true;
8139}
8140/*--------------------------------------------------------------------------*/
8141
8142function createByte(codePoint, shift) {
8143 return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
8144}
8145
8146function encodeCodePoint(codePoint, strict) {
8147 if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
8148 return stringFromCharCode(codePoint);
8149 }
8150 var symbol = '';
8151 if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
8152 symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
8153 }
8154 else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
8155 if (!checkScalarValue(codePoint, strict)) {
8156 codePoint = 0xFFFD;
8157 }
8158 symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
8159 symbol += createByte(codePoint, 6);
8160 }
8161 else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
8162 symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
8163 symbol += createByte(codePoint, 12);
8164 symbol += createByte(codePoint, 6);
8165 }
8166 symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
8167 return symbol;
8168}
8169
8170function utf8encode(string, opts) {
8171 opts = opts || {};
8172 var strict = false !== opts.strict;
8173
8174 var codePoints = ucs2decode(string);
8175 var length = codePoints.length;
8176 var index = -1;
8177 var codePoint;
8178 var byteString = '';
8179 while (++index < length) {
8180 codePoint = codePoints[index];
8181 byteString += encodeCodePoint(codePoint, strict);
8182 }
8183 return byteString;
8184}
8185
8186/*--------------------------------------------------------------------------*/
8187
8188function readContinuationByte() {
8189 if (byteIndex >= byteCount) {
8190 throw Error('Invalid byte index');
8191 }
8192
8193 var continuationByte = byteArray[byteIndex] & 0xFF;
8194 byteIndex++;
8195
8196 if ((continuationByte & 0xC0) == 0x80) {
8197 return continuationByte & 0x3F;
8198 }
8199
8200 // If we end up here, it’s not a continuation byte
8201 throw Error('Invalid continuation byte');
8202}
8203
8204function decodeSymbol(strict) {
8205 var byte1;
8206 var byte2;
8207 var byte3;
8208 var byte4;
8209 var codePoint;
8210
8211 if (byteIndex > byteCount) {
8212 throw Error('Invalid byte index');
8213 }
8214
8215 if (byteIndex == byteCount) {
8216 return false;
8217 }
8218
8219 // Read first byte
8220 byte1 = byteArray[byteIndex] & 0xFF;
8221 byteIndex++;
8222
8223 // 1-byte sequence (no continuation bytes)
8224 if ((byte1 & 0x80) == 0) {
8225 return byte1;
8226 }
8227
8228 // 2-byte sequence
8229 if ((byte1 & 0xE0) == 0xC0) {
8230 byte2 = readContinuationByte();
8231 codePoint = ((byte1 & 0x1F) << 6) | byte2;
8232 if (codePoint >= 0x80) {
8233 return codePoint;
8234 } else {
8235 throw Error('Invalid continuation byte');
8236 }
8237 }
8238
8239 // 3-byte sequence (may include unpaired surrogates)
8240 if ((byte1 & 0xF0) == 0xE0) {
8241 byte2 = readContinuationByte();
8242 byte3 = readContinuationByte();
8243 codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
8244 if (codePoint >= 0x0800) {
8245 return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD;
8246 } else {
8247 throw Error('Invalid continuation byte');
8248 }
8249 }
8250
8251 // 4-byte sequence
8252 if ((byte1 & 0xF8) == 0xF0) {
8253 byte2 = readContinuationByte();
8254 byte3 = readContinuationByte();
8255 byte4 = readContinuationByte();
8256 codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
8257 (byte3 << 0x06) | byte4;
8258 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
8259 return codePoint;
8260 }
8261 }
8262
8263 throw Error('Invalid UTF-8 detected');
8264}
8265
8266var byteArray;
8267var byteCount;
8268var byteIndex;
8269function utf8decode(byteString, opts) {
8270 opts = opts || {};
8271 var strict = false !== opts.strict;
8272
8273 byteArray = ucs2decode(byteString);
8274 byteCount = byteArray.length;
8275 byteIndex = 0;
8276 var codePoints = [];
8277 var tmp;
8278 while ((tmp = decodeSymbol(strict)) !== false) {
8279 codePoints.push(tmp);
8280 }
8281 return ucs2encode(codePoints);
8282}
8283
8284module.exports = {
8285 version: '2.1.2',
8286 encode: utf8encode,
8287 decode: utf8decode
8288};
8289
8290},{}],56:[function(require,module,exports){
8291(function (Buffer){
8292/* global Blob File */
8293
8294/*
8295 * Module requirements.
8296 */
8297
8298var isArray = require('isarray');
8299
8300var toString = Object.prototype.toString;
8301var withNativeBlob = typeof Blob === 'function' ||
8302 typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]';
8303var withNativeFile = typeof File === 'function' ||
8304 typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]';
8305
8306/**
8307 * Module exports.
8308 */
8309
8310module.exports = hasBinary;
8311
8312/**
8313 * Checks for binary data.
8314 *
8315 * Supports Buffer, ArrayBuffer, Blob and File.
8316 *
8317 * @param {Object} anything
8318 * @api public
8319 */
8320
8321function hasBinary (obj) {
8322 if (!obj || typeof obj !== 'object') {
8323 return false;
8324 }
8325
8326 if (isArray(obj)) {
8327 for (var i = 0, l = obj.length; i < l; i++) {
8328 if (hasBinary(obj[i])) {
8329 return true;
8330 }
8331 }
8332 return false;
8333 }
8334
8335 if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
8336 (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) ||
8337 (withNativeBlob && obj instanceof Blob) ||
8338 (withNativeFile && obj instanceof File)
8339 ) {
8340 return true;
8341 }
8342
8343 // see: https://github.com/Automattic/has-binary/pull/4
8344 if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) {
8345 return hasBinary(obj.toJSON(), true);
8346 }
8347
8348 for (var key in obj) {
8349 if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
8350 return true;
8351 }
8352 }
8353
8354 return false;
8355}
8356
8357}).call(this,require("buffer").Buffer)
8358},{"buffer":35,"isarray":60}],57:[function(require,module,exports){
8359
8360/**
8361 * Module exports.
8362 *
8363 * Logic borrowed from Modernizr:
8364 *
8365 * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
8366 */
8367
8368try {
8369 module.exports = typeof XMLHttpRequest !== 'undefined' &&
8370 'withCredentials' in new XMLHttpRequest();
8371} catch (err) {
8372 // if XMLHttp support is disabled in IE then it will throw
8373 // when trying to create
8374 module.exports = false;
8375}
8376
8377},{}],58:[function(require,module,exports){
8378exports.read = function (buffer, offset, isLE, mLen, nBytes) {
8379 var e, m
8380 var eLen = (nBytes * 8) - mLen - 1
8381 var eMax = (1 << eLen) - 1
8382 var eBias = eMax >> 1
8383 var nBits = -7
8384 var i = isLE ? (nBytes - 1) : 0
8385 var d = isLE ? -1 : 1
8386 var s = buffer[offset + i]
8387
8388 i += d
8389
8390 e = s & ((1 << (-nBits)) - 1)
8391 s >>= (-nBits)
8392 nBits += eLen
8393 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
8394
8395 m = e & ((1 << (-nBits)) - 1)
8396 e >>= (-nBits)
8397 nBits += mLen
8398 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
8399
8400 if (e === 0) {
8401 e = 1 - eBias
8402 } else if (e === eMax) {
8403 return m ? NaN : ((s ? -1 : 1) * Infinity)
8404 } else {
8405 m = m + Math.pow(2, mLen)
8406 e = e - eBias
8407 }
8408 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
8409}
8410
8411exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
8412 var e, m, c
8413 var eLen = (nBytes * 8) - mLen - 1
8414 var eMax = (1 << eLen) - 1
8415 var eBias = eMax >> 1
8416 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
8417 var i = isLE ? 0 : (nBytes - 1)
8418 var d = isLE ? 1 : -1
8419 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
8420
8421 value = Math.abs(value)
8422
8423 if (isNaN(value) || value === Infinity) {
8424 m = isNaN(value) ? 1 : 0
8425 e = eMax
8426 } else {
8427 e = Math.floor(Math.log(value) / Math.LN2)
8428 if (value * (c = Math.pow(2, -e)) < 1) {
8429 e--
8430 c *= 2
8431 }
8432 if (e + eBias >= 1) {
8433 value += rt / c
8434 } else {
8435 value += rt * Math.pow(2, 1 - eBias)
8436 }
8437 if (value * c >= 2) {
8438 e++
8439 c /= 2
8440 }
8441
8442 if (e + eBias >= eMax) {
8443 m = 0
8444 e = eMax
8445 } else if (e + eBias >= 1) {
8446 m = ((value * c) - 1) * Math.pow(2, mLen)
8447 e = e + eBias
8448 } else {
8449 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
8450 e = 0
8451 }
8452 }
8453
8454 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
8455
8456 e = (e << mLen) | m
8457 eLen += mLen
8458 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
8459
8460 buffer[offset + i - d] |= s * 128
8461}
8462
8463},{}],59:[function(require,module,exports){
8464
8465var indexOf = [].indexOf;
8466
8467module.exports = function(arr, obj){
8468 if (indexOf) return arr.indexOf(obj);
8469 for (var i = 0; i < arr.length; ++i) {
8470 if (arr[i] === obj) return i;
8471 }
8472 return -1;
8473};
8474},{}],60:[function(require,module,exports){
8475var toString = {}.toString;
8476
8477module.exports = Array.isArray || function (arr) {
8478 return toString.call(arr) == '[object Array]';
8479};
8480
8481},{}],61:[function(require,module,exports){
8482/**
8483 * Helpers.
8484 */
8485
8486var s = 1000;
8487var m = s * 60;
8488var h = m * 60;
8489var d = h * 24;
8490var y = d * 365.25;
8491
8492/**
8493 * Parse or format the given `val`.
8494 *
8495 * Options:
8496 *
8497 * - `long` verbose formatting [false]
8498 *
8499 * @param {String|Number} val
8500 * @param {Object} [options]
8501 * @throws {Error} throw an error if val is not a non-empty string or a number
8502 * @return {String|Number}
8503 * @api public
8504 */
8505
8506module.exports = function(val, options) {
8507 options = options || {};
8508 var type = typeof val;
8509 if (type === 'string' && val.length > 0) {
8510 return parse(val);
8511 } else if (type === 'number' && isNaN(val) === false) {
8512 return options.long ? fmtLong(val) : fmtShort(val);
8513 }
8514 throw new Error(
8515 'val is not a non-empty string or a valid number. val=' +
8516 JSON.stringify(val)
8517 );
8518};
8519
8520/**
8521 * Parse the given `str` and return milliseconds.
8522 *
8523 * @param {String} str
8524 * @return {Number}
8525 * @api private
8526 */
8527
8528function parse(str) {
8529 str = String(str);
8530 if (str.length > 100) {
8531 return;
8532 }
8533 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
8534 str
8535 );
8536 if (!match) {
8537 return;
8538 }
8539 var n = parseFloat(match[1]);
8540 var type = (match[2] || 'ms').toLowerCase();
8541 switch (type) {
8542 case 'years':
8543 case 'year':
8544 case 'yrs':
8545 case 'yr':
8546 case 'y':
8547 return n * y;
8548 case 'days':
8549 case 'day':
8550 case 'd':
8551 return n * d;
8552 case 'hours':
8553 case 'hour':
8554 case 'hrs':
8555 case 'hr':
8556 case 'h':
8557 return n * h;
8558 case 'minutes':
8559 case 'minute':
8560 case 'mins':
8561 case 'min':
8562 case 'm':
8563 return n * m;
8564 case 'seconds':
8565 case 'second':
8566 case 'secs':
8567 case 'sec':
8568 case 's':
8569 return n * s;
8570 case 'milliseconds':
8571 case 'millisecond':
8572 case 'msecs':
8573 case 'msec':
8574 case 'ms':
8575 return n;
8576 default:
8577 return undefined;
8578 }
8579}
8580
8581/**
8582 * Short format for `ms`.
8583 *
8584 * @param {Number} ms
8585 * @return {String}
8586 * @api private
8587 */
8588
8589function fmtShort(ms) {
8590 if (ms >= d) {
8591 return Math.round(ms / d) + 'd';
8592 }
8593 if (ms >= h) {
8594 return Math.round(ms / h) + 'h';
8595 }
8596 if (ms >= m) {
8597 return Math.round(ms / m) + 'm';
8598 }
8599 if (ms >= s) {
8600 return Math.round(ms / s) + 's';
8601 }
8602 return ms + 'ms';
8603}
8604
8605/**
8606 * Long format for `ms`.
8607 *
8608 * @param {Number} ms
8609 * @return {String}
8610 * @api private
8611 */
8612
8613function fmtLong(ms) {
8614 return plural(ms, d, 'day') ||
8615 plural(ms, h, 'hour') ||
8616 plural(ms, m, 'minute') ||
8617 plural(ms, s, 'second') ||
8618 ms + ' ms';
8619}
8620
8621/**
8622 * Pluralization helper.
8623 */
8624
8625function plural(ms, n, name) {
8626 if (ms < n) {
8627 return;
8628 }
8629 if (ms < n * 1.5) {
8630 return Math.floor(ms / n) + ' ' + name;
8631 }
8632 return Math.ceil(ms / n) + ' ' + name + 's';
8633}
8634
8635},{}],62:[function(require,module,exports){
8636/**
8637 * Compiles a querystring
8638 * Returns string representation of the object
8639 *
8640 * @param {Object}
8641 * @api private
8642 */
8643
8644exports.encode = function (obj) {
8645 var str = '';
8646
8647 for (var i in obj) {
8648 if (obj.hasOwnProperty(i)) {
8649 if (str.length) str += '&';
8650 str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
8651 }
8652 }
8653
8654 return str;
8655};
8656
8657/**
8658 * Parses a simple querystring into an object
8659 *
8660 * @param {String} qs
8661 * @api private
8662 */
8663
8664exports.decode = function(qs){
8665 var qry = {};
8666 var pairs = qs.split('&');
8667 for (var i = 0, l = pairs.length; i < l; i++) {
8668 var pair = pairs[i].split('=');
8669 qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
8670 }
8671 return qry;
8672};
8673
8674},{}],63:[function(require,module,exports){
8675/**
8676 * Parses an URI
8677 *
8678 * @author Steven Levithan <stevenlevithan.com> (MIT license)
8679 * @api private
8680 */
8681
8682var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
8683
8684var parts = [
8685 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
8686];
8687
8688module.exports = function parseuri(str) {
8689 var src = str,
8690 b = str.indexOf('['),
8691 e = str.indexOf(']');
8692
8693 if (b != -1 && e != -1) {
8694 str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
8695 }
8696
8697 var m = re.exec(str || ''),
8698 uri = {},
8699 i = 14;
8700
8701 while (i--) {
8702 uri[parts[i]] = m[i] || '';
8703 }
8704
8705 if (b != -1 && e != -1) {
8706 uri.source = src;
8707 uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
8708 uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
8709 uri.ipv6uri = true;
8710 }
8711
8712 return uri;
8713};
8714
8715},{}],64:[function(require,module,exports){
8716// shim for using process in browser
8717var process = module.exports = {};
8718
8719// cached from whatever global is present so that test runners that stub it
8720// don't break things. But we need to wrap it in a try catch in case it is
8721// wrapped in strict mode code which doesn't define any globals. It's inside a
8722// function because try/catches deoptimize in certain engines.
8723
8724var cachedSetTimeout;
8725var cachedClearTimeout;
8726
8727function defaultSetTimout() {
8728 throw new Error('setTimeout has not been defined');
8729}
8730function defaultClearTimeout () {
8731 throw new Error('clearTimeout has not been defined');
8732}
8733(function () {
8734 try {
8735 if (typeof setTimeout === 'function') {
8736 cachedSetTimeout = setTimeout;
8737 } else {
8738 cachedSetTimeout = defaultSetTimout;
8739 }
8740 } catch (e) {
8741 cachedSetTimeout = defaultSetTimout;
8742 }
8743 try {
8744 if (typeof clearTimeout === 'function') {
8745 cachedClearTimeout = clearTimeout;
8746 } else {
8747 cachedClearTimeout = defaultClearTimeout;
8748 }
8749 } catch (e) {
8750 cachedClearTimeout = defaultClearTimeout;
8751 }
8752} ())
8753function runTimeout(fun) {
8754 if (cachedSetTimeout === setTimeout) {
8755 //normal enviroments in sane situations
8756 return setTimeout(fun, 0);
8757 }
8758 // if setTimeout wasn't available but was latter defined
8759 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
8760 cachedSetTimeout = setTimeout;
8761 return setTimeout(fun, 0);
8762 }
8763 try {
8764 // when when somebody has screwed with setTimeout but no I.E. maddness
8765 return cachedSetTimeout(fun, 0);
8766 } catch(e){
8767 try {
8768 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
8769 return cachedSetTimeout.call(null, fun, 0);
8770 } catch(e){
8771 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
8772 return cachedSetTimeout.call(this, fun, 0);
8773 }
8774 }
8775
8776
8777}
8778function runClearTimeout(marker) {
8779 if (cachedClearTimeout === clearTimeout) {
8780 //normal enviroments in sane situations
8781 return clearTimeout(marker);
8782 }
8783 // if clearTimeout wasn't available but was latter defined
8784 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
8785 cachedClearTimeout = clearTimeout;
8786 return clearTimeout(marker);
8787 }
8788 try {
8789 // when when somebody has screwed with setTimeout but no I.E. maddness
8790 return cachedClearTimeout(marker);
8791 } catch (e){
8792 try {
8793 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
8794 return cachedClearTimeout.call(null, marker);
8795 } catch (e){
8796 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
8797 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
8798 return cachedClearTimeout.call(this, marker);
8799 }
8800 }
8801
8802
8803
8804}
8805var queue = [];
8806var draining = false;
8807var currentQueue;
8808var queueIndex = -1;
8809
8810function cleanUpNextTick() {
8811 if (!draining || !currentQueue) {
8812 return;
8813 }
8814 draining = false;
8815 if (currentQueue.length) {
8816 queue = currentQueue.concat(queue);
8817 } else {
8818 queueIndex = -1;
8819 }
8820 if (queue.length) {
8821 drainQueue();
8822 }
8823}
8824
8825function drainQueue() {
8826 if (draining) {
8827 return;
8828 }
8829 var timeout = runTimeout(cleanUpNextTick);
8830 draining = true;
8831
8832 var len = queue.length;
8833 while(len) {
8834 currentQueue = queue;
8835 queue = [];
8836 while (++queueIndex < len) {
8837 if (currentQueue) {
8838 currentQueue[queueIndex].run();
8839 }
8840 }
8841 queueIndex = -1;
8842 len = queue.length;
8843 }
8844 currentQueue = null;
8845 draining = false;
8846 runClearTimeout(timeout);
8847}
8848
8849process.nextTick = function (fun) {
8850 var args = new Array(arguments.length - 1);
8851 if (arguments.length > 1) {
8852 for (var i = 1; i < arguments.length; i++) {
8853 args[i - 1] = arguments[i];
8854 }
8855 }
8856 queue.push(new Item(fun, args));
8857 if (queue.length === 1 && !draining) {
8858 runTimeout(drainQueue);
8859 }
8860};
8861
8862// v8 likes predictible objects
8863function Item(fun, array) {
8864 this.fun = fun;
8865 this.array = array;
8866}
8867Item.prototype.run = function () {
8868 this.fun.apply(null, this.array);
8869};
8870process.title = 'browser';
8871process.browser = true;
8872process.env = {};
8873process.argv = [];
8874process.version = ''; // empty string to avoid regexp issues
8875process.versions = {};
8876
8877function noop() {}
8878
8879process.on = noop;
8880process.addListener = noop;
8881process.once = noop;
8882process.off = noop;
8883process.removeListener = noop;
8884process.removeAllListeners = noop;
8885process.emit = noop;
8886process.prependListener = noop;
8887process.prependOnceListener = noop;
8888
8889process.listeners = function (name) { return [] }
8890
8891process.binding = function (name) {
8892 throw new Error('process.binding is not supported');
8893};
8894
8895process.cwd = function () { return '/' };
8896process.chdir = function (dir) {
8897 throw new Error('process.chdir is not supported');
8898};
8899process.umask = function() { return 0; };
8900
8901},{}],65:[function(require,module,exports){
8902
8903/**
8904 * Module dependencies.
8905 */
8906
8907var url = require('./url');
8908var parser = require('socket.io-parser');
8909var Manager = require('./manager');
8910var debug = require('debug')('socket.io-client');
8911
8912/**
8913 * Module exports.
8914 */
8915
8916module.exports = exports = lookup;
8917
8918/**
8919 * Managers cache.
8920 */
8921
8922var cache = exports.managers = {};
8923
8924/**
8925 * Looks up an existing `Manager` for multiplexing.
8926 * If the user summons:
8927 *
8928 * `io('http://localhost/a');`
8929 * `io('http://localhost/b');`
8930 *
8931 * We reuse the existing instance based on same scheme/port/host,
8932 * and we initialize sockets for each namespace.
8933 *
8934 * @api public
8935 */
8936
8937function lookup (uri, opts) {
8938 if (typeof uri === 'object') {
8939 opts = uri;
8940 uri = undefined;
8941 }
8942
8943 opts = opts || {};
8944
8945 var parsed = url(uri);
8946 var source = parsed.source;
8947 var id = parsed.id;
8948 var path = parsed.path;
8949 var sameNamespace = cache[id] && path in cache[id].nsps;
8950 var newConnection = opts.forceNew || opts['force new connection'] ||
8951 false === opts.multiplex || sameNamespace;
8952
8953 var io;
8954
8955 if (newConnection) {
8956 debug('ignoring socket cache for %s', source);
8957 io = Manager(source, opts);
8958 } else {
8959 if (!cache[id]) {
8960 debug('new io instance for %s', source);
8961 cache[id] = Manager(source, opts);
8962 }
8963 io = cache[id];
8964 }
8965 if (parsed.query && !opts.query) {
8966 opts.query = parsed.query;
8967 }
8968 return io.socket(parsed.path, opts);
8969}
8970
8971/**
8972 * Protocol version.
8973 *
8974 * @api public
8975 */
8976
8977exports.protocol = parser.protocol;
8978
8979/**
8980 * `connect`.
8981 *
8982 * @param {String} uri
8983 * @api public
8984 */
8985
8986exports.connect = lookup;
8987
8988/**
8989 * Expose constructors for standalone build.
8990 *
8991 * @api public
8992 */
8993
8994exports.Manager = require('./manager');
8995exports.Socket = require('./socket');
8996
8997},{"./manager":66,"./socket":68,"./url":69,"debug":70,"socket.io-parser":74}],66:[function(require,module,exports){
8998
8999/**
9000 * Module dependencies.
9001 */
9002
9003var eio = require('engine.io-client');
9004var Socket = require('./socket');
9005var Emitter = require('component-emitter');
9006var parser = require('socket.io-parser');
9007var on = require('./on');
9008var bind = require('component-bind');
9009var debug = require('debug')('socket.io-client:manager');
9010var indexOf = require('indexof');
9011var Backoff = require('backo2');
9012
9013/**
9014 * IE6+ hasOwnProperty
9015 */
9016
9017var has = Object.prototype.hasOwnProperty;
9018
9019/**
9020 * Module exports
9021 */
9022
9023module.exports = Manager;
9024
9025/**
9026 * `Manager` constructor.
9027 *
9028 * @param {String} engine instance or engine uri/opts
9029 * @param {Object} options
9030 * @api public
9031 */
9032
9033function Manager (uri, opts) {
9034 if (!(this instanceof Manager)) return new Manager(uri, opts);
9035 if (uri && ('object' === typeof uri)) {
9036 opts = uri;
9037 uri = undefined;
9038 }
9039 opts = opts || {};
9040
9041 opts.path = opts.path || '/socket.io';
9042 this.nsps = {};
9043 this.subs = [];
9044 this.opts = opts;
9045 this.reconnection(opts.reconnection !== false);
9046 this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
9047 this.reconnectionDelay(opts.reconnectionDelay || 1000);
9048 this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
9049 this.randomizationFactor(opts.randomizationFactor || 0.5);
9050 this.backoff = new Backoff({
9051 min: this.reconnectionDelay(),
9052 max: this.reconnectionDelayMax(),
9053 jitter: this.randomizationFactor()
9054 });
9055 this.timeout(null == opts.timeout ? 20000 : opts.timeout);
9056 this.readyState = 'closed';
9057 this.uri = uri;
9058 this.connecting = [];
9059 this.lastPing = null;
9060 this.encoding = false;
9061 this.packetBuffer = [];
9062 var _parser = opts.parser || parser;
9063 this.encoder = new _parser.Encoder();
9064 this.decoder = new _parser.Decoder();
9065 this.autoConnect = opts.autoConnect !== false;
9066 if (this.autoConnect) this.open();
9067}
9068
9069/**
9070 * Propagate given event to sockets and emit on `this`
9071 *
9072 * @api private
9073 */
9074
9075Manager.prototype.emitAll = function () {
9076 this.emit.apply(this, arguments);
9077 for (var nsp in this.nsps) {
9078 if (has.call(this.nsps, nsp)) {
9079 this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
9080 }
9081 }
9082};
9083
9084/**
9085 * Update `socket.id` of all sockets
9086 *
9087 * @api private
9088 */
9089
9090Manager.prototype.updateSocketIds = function () {
9091 for (var nsp in this.nsps) {
9092 if (has.call(this.nsps, nsp)) {
9093 this.nsps[nsp].id = this.generateId(nsp);
9094 }
9095 }
9096};
9097
9098/**
9099 * generate `socket.id` for the given `nsp`
9100 *
9101 * @param {String} nsp
9102 * @return {String}
9103 * @api private
9104 */
9105
9106Manager.prototype.generateId = function (nsp) {
9107 return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id;
9108};
9109
9110/**
9111 * Mix in `Emitter`.
9112 */
9113
9114Emitter(Manager.prototype);
9115
9116/**
9117 * Sets the `reconnection` config.
9118 *
9119 * @param {Boolean} true/false if it should automatically reconnect
9120 * @return {Manager} self or value
9121 * @api public
9122 */
9123
9124Manager.prototype.reconnection = function (v) {
9125 if (!arguments.length) return this._reconnection;
9126 this._reconnection = !!v;
9127 return this;
9128};
9129
9130/**
9131 * Sets the reconnection attempts config.
9132 *
9133 * @param {Number} max reconnection attempts before giving up
9134 * @return {Manager} self or value
9135 * @api public
9136 */
9137
9138Manager.prototype.reconnectionAttempts = function (v) {
9139 if (!arguments.length) return this._reconnectionAttempts;
9140 this._reconnectionAttempts = v;
9141 return this;
9142};
9143
9144/**
9145 * Sets the delay between reconnections.
9146 *
9147 * @param {Number} delay
9148 * @return {Manager} self or value
9149 * @api public
9150 */
9151
9152Manager.prototype.reconnectionDelay = function (v) {
9153 if (!arguments.length) return this._reconnectionDelay;
9154 this._reconnectionDelay = v;
9155 this.backoff && this.backoff.setMin(v);
9156 return this;
9157};
9158
9159Manager.prototype.randomizationFactor = function (v) {
9160 if (!arguments.length) return this._randomizationFactor;
9161 this._randomizationFactor = v;
9162 this.backoff && this.backoff.setJitter(v);
9163 return this;
9164};
9165
9166/**
9167 * Sets the maximum delay between reconnections.
9168 *
9169 * @param {Number} delay
9170 * @return {Manager} self or value
9171 * @api public
9172 */
9173
9174Manager.prototype.reconnectionDelayMax = function (v) {
9175 if (!arguments.length) return this._reconnectionDelayMax;
9176 this._reconnectionDelayMax = v;
9177 this.backoff && this.backoff.setMax(v);
9178 return this;
9179};
9180
9181/**
9182 * Sets the connection timeout. `false` to disable
9183 *
9184 * @return {Manager} self or value
9185 * @api public
9186 */
9187
9188Manager.prototype.timeout = function (v) {
9189 if (!arguments.length) return this._timeout;
9190 this._timeout = v;
9191 return this;
9192};
9193
9194/**
9195 * Starts trying to reconnect if reconnection is enabled and we have not
9196 * started reconnecting yet
9197 *
9198 * @api private
9199 */
9200
9201Manager.prototype.maybeReconnectOnOpen = function () {
9202 // Only try to reconnect if it's the first time we're connecting
9203 if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
9204 // keeps reconnection from firing twice for the same reconnection loop
9205 this.reconnect();
9206 }
9207};
9208
9209/**
9210 * Sets the current transport `socket`.
9211 *
9212 * @param {Function} optional, callback
9213 * @return {Manager} self
9214 * @api public
9215 */
9216
9217Manager.prototype.open =
9218Manager.prototype.connect = function (fn, opts) {
9219 debug('readyState %s', this.readyState);
9220 if (~this.readyState.indexOf('open')) return this;
9221
9222 debug('opening %s', this.uri);
9223 this.engine = eio(this.uri, this.opts);
9224 var socket = this.engine;
9225 var self = this;
9226 this.readyState = 'opening';
9227 this.skipReconnect = false;
9228
9229 // emit `open`
9230 var openSub = on(socket, 'open', function () {
9231 self.onopen();
9232 fn && fn();
9233 });
9234
9235 // emit `connect_error`
9236 var errorSub = on(socket, 'error', function (data) {
9237 debug('connect_error');
9238 self.cleanup();
9239 self.readyState = 'closed';
9240 self.emitAll('connect_error', data);
9241 if (fn) {
9242 var err = new Error('Connection error');
9243 err.data = data;
9244 fn(err);
9245 } else {
9246 // Only do this if there is no fn to handle the error
9247 self.maybeReconnectOnOpen();
9248 }
9249 });
9250
9251 // emit `connect_timeout`
9252 if (false !== this._timeout) {
9253 var timeout = this._timeout;
9254 debug('connect attempt will timeout after %d', timeout);
9255
9256 // set timer
9257 var timer = setTimeout(function () {
9258 debug('connect attempt timed out after %d', timeout);
9259 openSub.destroy();
9260 socket.close();
9261 socket.emit('error', 'timeout');
9262 self.emitAll('connect_timeout', timeout);
9263 }, timeout);
9264
9265 this.subs.push({
9266 destroy: function () {
9267 clearTimeout(timer);
9268 }
9269 });
9270 }
9271
9272 this.subs.push(openSub);
9273 this.subs.push(errorSub);
9274
9275 return this;
9276};
9277
9278/**
9279 * Called upon transport open.
9280 *
9281 * @api private
9282 */
9283
9284Manager.prototype.onopen = function () {
9285 debug('open');
9286
9287 // clear old subs
9288 this.cleanup();
9289
9290 // mark as open
9291 this.readyState = 'open';
9292 this.emit('open');
9293
9294 // add new subs
9295 var socket = this.engine;
9296 this.subs.push(on(socket, 'data', bind(this, 'ondata')));
9297 this.subs.push(on(socket, 'ping', bind(this, 'onping')));
9298 this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
9299 this.subs.push(on(socket, 'error', bind(this, 'onerror')));
9300 this.subs.push(on(socket, 'close', bind(this, 'onclose')));
9301 this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
9302};
9303
9304/**
9305 * Called upon a ping.
9306 *
9307 * @api private
9308 */
9309
9310Manager.prototype.onping = function () {
9311 this.lastPing = new Date();
9312 this.emitAll('ping');
9313};
9314
9315/**
9316 * Called upon a packet.
9317 *
9318 * @api private
9319 */
9320
9321Manager.prototype.onpong = function () {
9322 this.emitAll('pong', new Date() - this.lastPing);
9323};
9324
9325/**
9326 * Called with data.
9327 *
9328 * @api private
9329 */
9330
9331Manager.prototype.ondata = function (data) {
9332 this.decoder.add(data);
9333};
9334
9335/**
9336 * Called when parser fully decodes a packet.
9337 *
9338 * @api private
9339 */
9340
9341Manager.prototype.ondecoded = function (packet) {
9342 this.emit('packet', packet);
9343};
9344
9345/**
9346 * Called upon socket error.
9347 *
9348 * @api private
9349 */
9350
9351Manager.prototype.onerror = function (err) {
9352 debug('error', err);
9353 this.emitAll('error', err);
9354};
9355
9356/**
9357 * Creates a new socket for the given `nsp`.
9358 *
9359 * @return {Socket}
9360 * @api public
9361 */
9362
9363Manager.prototype.socket = function (nsp, opts) {
9364 var socket = this.nsps[nsp];
9365 if (!socket) {
9366 socket = new Socket(this, nsp, opts);
9367 this.nsps[nsp] = socket;
9368 var self = this;
9369 socket.on('connecting', onConnecting);
9370 socket.on('connect', function () {
9371 socket.id = self.generateId(nsp);
9372 });
9373
9374 if (this.autoConnect) {
9375 // manually call here since connecting event is fired before listening
9376 onConnecting();
9377 }
9378 }
9379
9380 function onConnecting () {
9381 if (!~indexOf(self.connecting, socket)) {
9382 self.connecting.push(socket);
9383 }
9384 }
9385
9386 return socket;
9387};
9388
9389/**
9390 * Called upon a socket close.
9391 *
9392 * @param {Socket} socket
9393 */
9394
9395Manager.prototype.destroy = function (socket) {
9396 var index = indexOf(this.connecting, socket);
9397 if (~index) this.connecting.splice(index, 1);
9398 if (this.connecting.length) return;
9399
9400 this.close();
9401};
9402
9403/**
9404 * Writes a packet.
9405 *
9406 * @param {Object} packet
9407 * @api private
9408 */
9409
9410Manager.prototype.packet = function (packet) {
9411 debug('writing packet %j', packet);
9412 var self = this;
9413 if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
9414
9415 if (!self.encoding) {
9416 // encode, then write to engine with result
9417 self.encoding = true;
9418 this.encoder.encode(packet, function (encodedPackets) {
9419 for (var i = 0; i < encodedPackets.length; i++) {
9420 self.engine.write(encodedPackets[i], packet.options);
9421 }
9422 self.encoding = false;
9423 self.processPacketQueue();
9424 });
9425 } else { // add packet to the queue
9426 self.packetBuffer.push(packet);
9427 }
9428};
9429
9430/**
9431 * If packet buffer is non-empty, begins encoding the
9432 * next packet in line.
9433 *
9434 * @api private
9435 */
9436
9437Manager.prototype.processPacketQueue = function () {
9438 if (this.packetBuffer.length > 0 && !this.encoding) {
9439 var pack = this.packetBuffer.shift();
9440 this.packet(pack);
9441 }
9442};
9443
9444/**
9445 * Clean up transport subscriptions and packet buffer.
9446 *
9447 * @api private
9448 */
9449
9450Manager.prototype.cleanup = function () {
9451 debug('cleanup');
9452
9453 var subsLength = this.subs.length;
9454 for (var i = 0; i < subsLength; i++) {
9455 var sub = this.subs.shift();
9456 sub.destroy();
9457 }
9458
9459 this.packetBuffer = [];
9460 this.encoding = false;
9461 this.lastPing = null;
9462
9463 this.decoder.destroy();
9464};
9465
9466/**
9467 * Close the current socket.
9468 *
9469 * @api private
9470 */
9471
9472Manager.prototype.close =
9473Manager.prototype.disconnect = function () {
9474 debug('disconnect');
9475 this.skipReconnect = true;
9476 this.reconnecting = false;
9477 if ('opening' === this.readyState) {
9478 // `onclose` will not fire because
9479 // an open event never happened
9480 this.cleanup();
9481 }
9482 this.backoff.reset();
9483 this.readyState = 'closed';
9484 if (this.engine) this.engine.close();
9485};
9486
9487/**
9488 * Called upon engine close.
9489 *
9490 * @api private
9491 */
9492
9493Manager.prototype.onclose = function (reason) {
9494 debug('onclose');
9495
9496 this.cleanup();
9497 this.backoff.reset();
9498 this.readyState = 'closed';
9499 this.emit('close', reason);
9500
9501 if (this._reconnection && !this.skipReconnect) {
9502 this.reconnect();
9503 }
9504};
9505
9506/**
9507 * Attempt a reconnection.
9508 *
9509 * @api private
9510 */
9511
9512Manager.prototype.reconnect = function () {
9513 if (this.reconnecting || this.skipReconnect) return this;
9514
9515 var self = this;
9516
9517 if (this.backoff.attempts >= this._reconnectionAttempts) {
9518 debug('reconnect failed');
9519 this.backoff.reset();
9520 this.emitAll('reconnect_failed');
9521 this.reconnecting = false;
9522 } else {
9523 var delay = this.backoff.duration();
9524 debug('will wait %dms before reconnect attempt', delay);
9525
9526 this.reconnecting = true;
9527 var timer = setTimeout(function () {
9528 if (self.skipReconnect) return;
9529
9530 debug('attempting reconnect');
9531 self.emitAll('reconnect_attempt', self.backoff.attempts);
9532 self.emitAll('reconnecting', self.backoff.attempts);
9533
9534 // check again for the case socket closed in above events
9535 if (self.skipReconnect) return;
9536
9537 self.open(function (err) {
9538 if (err) {
9539 debug('reconnect attempt error');
9540 self.reconnecting = false;
9541 self.reconnect();
9542 self.emitAll('reconnect_error', err.data);
9543 } else {
9544 debug('reconnect success');
9545 self.onreconnect();
9546 }
9547 });
9548 }, delay);
9549
9550 this.subs.push({
9551 destroy: function () {
9552 clearTimeout(timer);
9553 }
9554 });
9555 }
9556};
9557
9558/**
9559 * Called upon successful reconnect.
9560 *
9561 * @api private
9562 */
9563
9564Manager.prototype.onreconnect = function () {
9565 var attempt = this.backoff.attempts;
9566 this.reconnecting = false;
9567 this.backoff.reset();
9568 this.updateSocketIds();
9569 this.emitAll('reconnect', attempt);
9570};
9571
9572},{"./on":67,"./socket":68,"backo2":30,"component-bind":36,"component-emitter":37,"debug":70,"engine.io-client":41,"indexof":59,"socket.io-parser":74}],67:[function(require,module,exports){
9573
9574/**
9575 * Module exports.
9576 */
9577
9578module.exports = on;
9579
9580/**
9581 * Helper for subscriptions.
9582 *
9583 * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
9584 * @param {String} event name
9585 * @param {Function} callback
9586 * @api public
9587 */
9588
9589function on (obj, ev, fn) {
9590 obj.on(ev, fn);
9591 return {
9592 destroy: function () {
9593 obj.removeListener(ev, fn);
9594 }
9595 };
9596}
9597
9598},{}],68:[function(require,module,exports){
9599
9600/**
9601 * Module dependencies.
9602 */
9603
9604var parser = require('socket.io-parser');
9605var Emitter = require('component-emitter');
9606var toArray = require('to-array');
9607var on = require('./on');
9608var bind = require('component-bind');
9609var debug = require('debug')('socket.io-client:socket');
9610var parseqs = require('parseqs');
9611var hasBin = require('has-binary2');
9612
9613/**
9614 * Module exports.
9615 */
9616
9617module.exports = exports = Socket;
9618
9619/**
9620 * Internal events (blacklisted).
9621 * These events can't be emitted by the user.
9622 *
9623 * @api private
9624 */
9625
9626var events = {
9627 connect: 1,
9628 connect_error: 1,
9629 connect_timeout: 1,
9630 connecting: 1,
9631 disconnect: 1,
9632 error: 1,
9633 reconnect: 1,
9634 reconnect_attempt: 1,
9635 reconnect_failed: 1,
9636 reconnect_error: 1,
9637 reconnecting: 1,
9638 ping: 1,
9639 pong: 1
9640};
9641
9642/**
9643 * Shortcut to `Emitter#emit`.
9644 */
9645
9646var emit = Emitter.prototype.emit;
9647
9648/**
9649 * `Socket` constructor.
9650 *
9651 * @api public
9652 */
9653
9654function Socket (io, nsp, opts) {
9655 this.io = io;
9656 this.nsp = nsp;
9657 this.json = this; // compat
9658 this.ids = 0;
9659 this.acks = {};
9660 this.receiveBuffer = [];
9661 this.sendBuffer = [];
9662 this.connected = false;
9663 this.disconnected = true;
9664 this.flags = {};
9665 if (opts && opts.query) {
9666 this.query = opts.query;
9667 }
9668 if (this.io.autoConnect) this.open();
9669}
9670
9671/**
9672 * Mix in `Emitter`.
9673 */
9674
9675Emitter(Socket.prototype);
9676
9677/**
9678 * Subscribe to open, close and packet events
9679 *
9680 * @api private
9681 */
9682
9683Socket.prototype.subEvents = function () {
9684 if (this.subs) return;
9685
9686 var io = this.io;
9687 this.subs = [
9688 on(io, 'open', bind(this, 'onopen')),
9689 on(io, 'packet', bind(this, 'onpacket')),
9690 on(io, 'close', bind(this, 'onclose'))
9691 ];
9692};
9693
9694/**
9695 * "Opens" the socket.
9696 *
9697 * @api public
9698 */
9699
9700Socket.prototype.open =
9701Socket.prototype.connect = function () {
9702 if (this.connected) return this;
9703
9704 this.subEvents();
9705 this.io.open(); // ensure open
9706 if ('open' === this.io.readyState) this.onopen();
9707 this.emit('connecting');
9708 return this;
9709};
9710
9711/**
9712 * Sends a `message` event.
9713 *
9714 * @return {Socket} self
9715 * @api public
9716 */
9717
9718Socket.prototype.send = function () {
9719 var args = toArray(arguments);
9720 args.unshift('message');
9721 this.emit.apply(this, args);
9722 return this;
9723};
9724
9725/**
9726 * Override `emit`.
9727 * If the event is in `events`, it's emitted normally.
9728 *
9729 * @param {String} event name
9730 * @return {Socket} self
9731 * @api public
9732 */
9733
9734Socket.prototype.emit = function (ev) {
9735 if (events.hasOwnProperty(ev)) {
9736 emit.apply(this, arguments);
9737 return this;
9738 }
9739
9740 var args = toArray(arguments);
9741 var packet = {
9742 type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
9743 data: args
9744 };
9745
9746 packet.options = {};
9747 packet.options.compress = !this.flags || false !== this.flags.compress;
9748
9749 // event ack callback
9750 if ('function' === typeof args[args.length - 1]) {
9751 debug('emitting packet with ack id %d', this.ids);
9752 this.acks[this.ids] = args.pop();
9753 packet.id = this.ids++;
9754 }
9755
9756 if (this.connected) {
9757 this.packet(packet);
9758 } else {
9759 this.sendBuffer.push(packet);
9760 }
9761
9762 this.flags = {};
9763
9764 return this;
9765};
9766
9767/**
9768 * Sends a packet.
9769 *
9770 * @param {Object} packet
9771 * @api private
9772 */
9773
9774Socket.prototype.packet = function (packet) {
9775 packet.nsp = this.nsp;
9776 this.io.packet(packet);
9777};
9778
9779/**
9780 * Called upon engine `open`.
9781 *
9782 * @api private
9783 */
9784
9785Socket.prototype.onopen = function () {
9786 debug('transport is open - connecting');
9787
9788 // write connect packet if necessary
9789 if ('/' !== this.nsp) {
9790 if (this.query) {
9791 var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query;
9792 debug('sending connect packet with query %s', query);
9793 this.packet({type: parser.CONNECT, query: query});
9794 } else {
9795 this.packet({type: parser.CONNECT});
9796 }
9797 }
9798};
9799
9800/**
9801 * Called upon engine `close`.
9802 *
9803 * @param {String} reason
9804 * @api private
9805 */
9806
9807Socket.prototype.onclose = function (reason) {
9808 debug('close (%s)', reason);
9809 this.connected = false;
9810 this.disconnected = true;
9811 delete this.id;
9812 this.emit('disconnect', reason);
9813};
9814
9815/**
9816 * Called with socket packet.
9817 *
9818 * @param {Object} packet
9819 * @api private
9820 */
9821
9822Socket.prototype.onpacket = function (packet) {
9823 var sameNamespace = packet.nsp === this.nsp;
9824 var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';
9825
9826 if (!sameNamespace && !rootNamespaceError) return;
9827
9828 switch (packet.type) {
9829 case parser.CONNECT:
9830 this.onconnect();
9831 break;
9832
9833 case parser.EVENT:
9834 this.onevent(packet);
9835 break;
9836
9837 case parser.BINARY_EVENT:
9838 this.onevent(packet);
9839 break;
9840
9841 case parser.ACK:
9842 this.onack(packet);
9843 break;
9844
9845 case parser.BINARY_ACK:
9846 this.onack(packet);
9847 break;
9848
9849 case parser.DISCONNECT:
9850 this.ondisconnect();
9851 break;
9852
9853 case parser.ERROR:
9854 this.emit('error', packet.data);
9855 break;
9856 }
9857};
9858
9859/**
9860 * Called upon a server event.
9861 *
9862 * @param {Object} packet
9863 * @api private
9864 */
9865
9866Socket.prototype.onevent = function (packet) {
9867 var args = packet.data || [];
9868 debug('emitting event %j', args);
9869
9870 if (null != packet.id) {
9871 debug('attaching ack callback to event');
9872 args.push(this.ack(packet.id));
9873 }
9874
9875 if (this.connected) {
9876 emit.apply(this, args);
9877 } else {
9878 this.receiveBuffer.push(args);
9879 }
9880};
9881
9882/**
9883 * Produces an ack callback to emit with an event.
9884 *
9885 * @api private
9886 */
9887
9888Socket.prototype.ack = function (id) {
9889 var self = this;
9890 var sent = false;
9891 return function () {
9892 // prevent double callbacks
9893 if (sent) return;
9894 sent = true;
9895 var args = toArray(arguments);
9896 debug('sending ack %j', args);
9897
9898 self.packet({
9899 type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
9900 id: id,
9901 data: args
9902 });
9903 };
9904};
9905
9906/**
9907 * Called upon a server acknowlegement.
9908 *
9909 * @param {Object} packet
9910 * @api private
9911 */
9912
9913Socket.prototype.onack = function (packet) {
9914 var ack = this.acks[packet.id];
9915 if ('function' === typeof ack) {
9916 debug('calling ack %s with %j', packet.id, packet.data);
9917 ack.apply(this, packet.data);
9918 delete this.acks[packet.id];
9919 } else {
9920 debug('bad ack %s', packet.id);
9921 }
9922};
9923
9924/**
9925 * Called upon server connect.
9926 *
9927 * @api private
9928 */
9929
9930Socket.prototype.onconnect = function () {
9931 this.connected = true;
9932 this.disconnected = false;
9933 this.emit('connect');
9934 this.emitBuffered();
9935};
9936
9937/**
9938 * Emit buffered events (received and emitted).
9939 *
9940 * @api private
9941 */
9942
9943Socket.prototype.emitBuffered = function () {
9944 var i;
9945 for (i = 0; i < this.receiveBuffer.length; i++) {
9946 emit.apply(this, this.receiveBuffer[i]);
9947 }
9948 this.receiveBuffer = [];
9949
9950 for (i = 0; i < this.sendBuffer.length; i++) {
9951 this.packet(this.sendBuffer[i]);
9952 }
9953 this.sendBuffer = [];
9954};
9955
9956/**
9957 * Called upon server disconnect.
9958 *
9959 * @api private
9960 */
9961
9962Socket.prototype.ondisconnect = function () {
9963 debug('server disconnect (%s)', this.nsp);
9964 this.destroy();
9965 this.onclose('io server disconnect');
9966};
9967
9968/**
9969 * Called upon forced client/server side disconnections,
9970 * this method ensures the manager stops tracking us and
9971 * that reconnections don't get triggered for this.
9972 *
9973 * @api private.
9974 */
9975
9976Socket.prototype.destroy = function () {
9977 if (this.subs) {
9978 // clean subscriptions to avoid reconnections
9979 for (var i = 0; i < this.subs.length; i++) {
9980 this.subs[i].destroy();
9981 }
9982 this.subs = null;
9983 }
9984
9985 this.io.destroy(this);
9986};
9987
9988/**
9989 * Disconnects the socket manually.
9990 *
9991 * @return {Socket} self
9992 * @api public
9993 */
9994
9995Socket.prototype.close =
9996Socket.prototype.disconnect = function () {
9997 if (this.connected) {
9998 debug('performing disconnect (%s)', this.nsp);
9999 this.packet({ type: parser.DISCONNECT });
10000 }
10001
10002 // remove socket from pool
10003 this.destroy();
10004
10005 if (this.connected) {
10006 // fire events
10007 this.onclose('io client disconnect');
10008 }
10009 return this;
10010};
10011
10012/**
10013 * Sets the compress flag.
10014 *
10015 * @param {Boolean} if `true`, compresses the sending data
10016 * @return {Socket} self
10017 * @api public
10018 */
10019
10020Socket.prototype.compress = function (compress) {
10021 this.flags.compress = compress;
10022 return this;
10023};
10024
10025/**
10026 * Sets the binary flag
10027 *
10028 * @param {Boolean} whether the emitted data contains binary
10029 * @return {Socket} self
10030 * @api public
10031 */
10032
10033Socket.prototype.binary = function (binary) {
10034 this.flags.binary = binary;
10035 return this;
10036};
10037
10038},{"./on":67,"component-bind":36,"component-emitter":37,"debug":70,"has-binary2":56,"parseqs":62,"socket.io-parser":74,"to-array":76}],69:[function(require,module,exports){
10039
10040/**
10041 * Module dependencies.
10042 */
10043
10044var parseuri = require('parseuri');
10045var debug = require('debug')('socket.io-client:url');
10046
10047/**
10048 * Module exports.
10049 */
10050
10051module.exports = url;
10052
10053/**
10054 * URL parser.
10055 *
10056 * @param {String} url
10057 * @param {Object} An object meant to mimic window.location.
10058 * Defaults to window.location.
10059 * @api public
10060 */
10061
10062function url (uri, loc) {
10063 var obj = uri;
10064
10065 // default to window.location
10066 loc = loc || (typeof location !== 'undefined' && location);
10067 if (null == uri) uri = loc.protocol + '//' + loc.host;
10068
10069 // relative path support
10070 if ('string' === typeof uri) {
10071 if ('/' === uri.charAt(0)) {
10072 if ('/' === uri.charAt(1)) {
10073 uri = loc.protocol + uri;
10074 } else {
10075 uri = loc.host + uri;
10076 }
10077 }
10078
10079 if (!/^(https?|wss?):\/\//.test(uri)) {
10080 debug('protocol-less url %s', uri);
10081 if ('undefined' !== typeof loc) {
10082 uri = loc.protocol + '//' + uri;
10083 } else {
10084 uri = 'https://' + uri;
10085 }
10086 }
10087
10088 // parse
10089 debug('parse %s', uri);
10090 obj = parseuri(uri);
10091 }
10092
10093 // make sure we treat `localhost:80` and `localhost` equally
10094 if (!obj.port) {
10095 if (/^(http|ws)$/.test(obj.protocol)) {
10096 obj.port = '80';
10097 } else if (/^(http|ws)s$/.test(obj.protocol)) {
10098 obj.port = '443';
10099 }
10100 }
10101
10102 obj.path = obj.path || '/';
10103
10104 var ipv6 = obj.host.indexOf(':') !== -1;
10105 var host = ipv6 ? '[' + obj.host + ']' : obj.host;
10106
10107 // define unique id
10108 obj.id = obj.protocol + '://' + host + ':' + obj.port;
10109 // define href
10110 obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port));
10111
10112 return obj;
10113}
10114
10115},{"debug":70,"parseuri":63}],70:[function(require,module,exports){
10116arguments[4][50][0].apply(exports,arguments)
10117},{"./common":71,"_process":64,"dup":50}],71:[function(require,module,exports){
10118arguments[4][51][0].apply(exports,arguments)
10119},{"dup":51,"ms":72}],72:[function(require,module,exports){
10120arguments[4][52][0].apply(exports,arguments)
10121},{"dup":52}],73:[function(require,module,exports){
10122/*global Blob,File*/
10123
10124/**
10125 * Module requirements
10126 */
10127
10128var isArray = require('isarray');
10129var isBuf = require('./is-buffer');
10130var toString = Object.prototype.toString;
10131var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]');
10132var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]');
10133
10134/**
10135 * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
10136 * Anything with blobs or files should be fed through removeBlobs before coming
10137 * here.
10138 *
10139 * @param {Object} packet - socket.io event packet
10140 * @return {Object} with deconstructed packet and list of buffers
10141 * @api public
10142 */
10143
10144exports.deconstructPacket = function(packet) {
10145 var buffers = [];
10146 var packetData = packet.data;
10147 var pack = packet;
10148 pack.data = _deconstructPacket(packetData, buffers);
10149 pack.attachments = buffers.length; // number of binary 'attachments'
10150 return {packet: pack, buffers: buffers};
10151};
10152
10153function _deconstructPacket(data, buffers) {
10154 if (!data) return data;
10155
10156 if (isBuf(data)) {
10157 var placeholder = { _placeholder: true, num: buffers.length };
10158 buffers.push(data);
10159 return placeholder;
10160 } else if (isArray(data)) {
10161 var newData = new Array(data.length);
10162 for (var i = 0; i < data.length; i++) {
10163 newData[i] = _deconstructPacket(data[i], buffers);
10164 }
10165 return newData;
10166 } else if (typeof data === 'object' && !(data instanceof Date)) {
10167 var newData = {};
10168 for (var key in data) {
10169 newData[key] = _deconstructPacket(data[key], buffers);
10170 }
10171 return newData;
10172 }
10173 return data;
10174}
10175
10176/**
10177 * Reconstructs a binary packet from its placeholder packet and buffers
10178 *
10179 * @param {Object} packet - event packet with placeholders
10180 * @param {Array} buffers - binary buffers to put in placeholder positions
10181 * @return {Object} reconstructed packet
10182 * @api public
10183 */
10184
10185exports.reconstructPacket = function(packet, buffers) {
10186 packet.data = _reconstructPacket(packet.data, buffers);
10187 packet.attachments = undefined; // no longer useful
10188 return packet;
10189};
10190
10191function _reconstructPacket(data, buffers) {
10192 if (!data) return data;
10193
10194 if (data && data._placeholder) {
10195 return buffers[data.num]; // appropriate buffer (should be natural order anyway)
10196 } else if (isArray(data)) {
10197 for (var i = 0; i < data.length; i++) {
10198 data[i] = _reconstructPacket(data[i], buffers);
10199 }
10200 } else if (typeof data === 'object') {
10201 for (var key in data) {
10202 data[key] = _reconstructPacket(data[key], buffers);
10203 }
10204 }
10205
10206 return data;
10207}
10208
10209/**
10210 * Asynchronously removes Blobs or Files from data via
10211 * FileReader's readAsArrayBuffer method. Used before encoding
10212 * data as msgpack. Calls callback with the blobless data.
10213 *
10214 * @param {Object} data
10215 * @param {Function} callback
10216 * @api private
10217 */
10218
10219exports.removeBlobs = function(data, callback) {
10220 function _removeBlobs(obj, curKey, containingObject) {
10221 if (!obj) return obj;
10222
10223 // convert any blob
10224 if ((withNativeBlob && obj instanceof Blob) ||
10225 (withNativeFile && obj instanceof File)) {
10226 pendingBlobs++;
10227
10228 // async filereader
10229 var fileReader = new FileReader();
10230 fileReader.onload = function() { // this.result == arraybuffer
10231 if (containingObject) {
10232 containingObject[curKey] = this.result;
10233 }
10234 else {
10235 bloblessData = this.result;
10236 }
10237
10238 // if nothing pending its callback time
10239 if(! --pendingBlobs) {
10240 callback(bloblessData);
10241 }
10242 };
10243
10244 fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
10245 } else if (isArray(obj)) { // handle array
10246 for (var i = 0; i < obj.length; i++) {
10247 _removeBlobs(obj[i], i, obj);
10248 }
10249 } else if (typeof obj === 'object' && !isBuf(obj)) { // and object
10250 for (var key in obj) {
10251 _removeBlobs(obj[key], key, obj);
10252 }
10253 }
10254 }
10255
10256 var pendingBlobs = 0;
10257 var bloblessData = data;
10258 _removeBlobs(bloblessData);
10259 if (!pendingBlobs) {
10260 callback(bloblessData);
10261 }
10262};
10263
10264},{"./is-buffer":75,"isarray":60}],74:[function(require,module,exports){
10265
10266/**
10267 * Module dependencies.
10268 */
10269
10270var debug = require('debug')('socket.io-parser');
10271var Emitter = require('component-emitter');
10272var binary = require('./binary');
10273var isArray = require('isarray');
10274var isBuf = require('./is-buffer');
10275
10276/**
10277 * Protocol version.
10278 *
10279 * @api public
10280 */
10281
10282exports.protocol = 4;
10283
10284/**
10285 * Packet types.
10286 *
10287 * @api public
10288 */
10289
10290exports.types = [
10291 'CONNECT',
10292 'DISCONNECT',
10293 'EVENT',
10294 'ACK',
10295 'ERROR',
10296 'BINARY_EVENT',
10297 'BINARY_ACK'
10298];
10299
10300/**
10301 * Packet type `connect`.
10302 *
10303 * @api public
10304 */
10305
10306exports.CONNECT = 0;
10307
10308/**
10309 * Packet type `disconnect`.
10310 *
10311 * @api public
10312 */
10313
10314exports.DISCONNECT = 1;
10315
10316/**
10317 * Packet type `event`.
10318 *
10319 * @api public
10320 */
10321
10322exports.EVENT = 2;
10323
10324/**
10325 * Packet type `ack`.
10326 *
10327 * @api public
10328 */
10329
10330exports.ACK = 3;
10331
10332/**
10333 * Packet type `error`.
10334 *
10335 * @api public
10336 */
10337
10338exports.ERROR = 4;
10339
10340/**
10341 * Packet type 'binary event'
10342 *
10343 * @api public
10344 */
10345
10346exports.BINARY_EVENT = 5;
10347
10348/**
10349 * Packet type `binary ack`. For acks with binary arguments.
10350 *
10351 * @api public
10352 */
10353
10354exports.BINARY_ACK = 6;
10355
10356/**
10357 * Encoder constructor.
10358 *
10359 * @api public
10360 */
10361
10362exports.Encoder = Encoder;
10363
10364/**
10365 * Decoder constructor.
10366 *
10367 * @api public
10368 */
10369
10370exports.Decoder = Decoder;
10371
10372/**
10373 * A socket.io Encoder instance
10374 *
10375 * @api public
10376 */
10377
10378function Encoder() {}
10379
10380var ERROR_PACKET = exports.ERROR + '"encode error"';
10381
10382/**
10383 * Encode a packet as a single string if non-binary, or as a
10384 * buffer sequence, depending on packet type.
10385 *
10386 * @param {Object} obj - packet object
10387 * @param {Function} callback - function to handle encodings (likely engine.write)
10388 * @return Calls callback with Array of encodings
10389 * @api public
10390 */
10391
10392Encoder.prototype.encode = function(obj, callback){
10393 debug('encoding packet %j', obj);
10394
10395 if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
10396 encodeAsBinary(obj, callback);
10397 } else {
10398 var encoding = encodeAsString(obj);
10399 callback([encoding]);
10400 }
10401};
10402
10403/**
10404 * Encode packet as string.
10405 *
10406 * @param {Object} packet
10407 * @return {String} encoded
10408 * @api private
10409 */
10410
10411function encodeAsString(obj) {
10412
10413 // first is type
10414 var str = '' + obj.type;
10415
10416 // attachments if we have them
10417 if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
10418 str += obj.attachments + '-';
10419 }
10420
10421 // if we have a namespace other than `/`
10422 // we append it followed by a comma `,`
10423 if (obj.nsp && '/' !== obj.nsp) {
10424 str += obj.nsp + ',';
10425 }
10426
10427 // immediately followed by the id
10428 if (null != obj.id) {
10429 str += obj.id;
10430 }
10431
10432 // json data
10433 if (null != obj.data) {
10434 var payload = tryStringify(obj.data);
10435 if (payload !== false) {
10436 str += payload;
10437 } else {
10438 return ERROR_PACKET;
10439 }
10440 }
10441
10442 debug('encoded %j as %s', obj, str);
10443 return str;
10444}
10445
10446function tryStringify(str) {
10447 try {
10448 return JSON.stringify(str);
10449 } catch(e){
10450 return false;
10451 }
10452}
10453
10454/**
10455 * Encode packet as 'buffer sequence' by removing blobs, and
10456 * deconstructing packet into object with placeholders and
10457 * a list of buffers.
10458 *
10459 * @param {Object} packet
10460 * @return {Buffer} encoded
10461 * @api private
10462 */
10463
10464function encodeAsBinary(obj, callback) {
10465
10466 function writeEncoding(bloblessData) {
10467 var deconstruction = binary.deconstructPacket(bloblessData);
10468 var pack = encodeAsString(deconstruction.packet);
10469 var buffers = deconstruction.buffers;
10470
10471 buffers.unshift(pack); // add packet info to beginning of data list
10472 callback(buffers); // write all the buffers
10473 }
10474
10475 binary.removeBlobs(obj, writeEncoding);
10476}
10477
10478/**
10479 * A socket.io Decoder instance
10480 *
10481 * @return {Object} decoder
10482 * @api public
10483 */
10484
10485function Decoder() {
10486 this.reconstructor = null;
10487}
10488
10489/**
10490 * Mix in `Emitter` with Decoder.
10491 */
10492
10493Emitter(Decoder.prototype);
10494
10495/**
10496 * Decodes an encoded packet string into packet JSON.
10497 *
10498 * @param {String} obj - encoded packet
10499 * @return {Object} packet
10500 * @api public
10501 */
10502
10503Decoder.prototype.add = function(obj) {
10504 var packet;
10505 if (typeof obj === 'string') {
10506 packet = decodeString(obj);
10507 if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json
10508 this.reconstructor = new BinaryReconstructor(packet);
10509
10510 // no attachments, labeled binary but no binary data to follow
10511 if (this.reconstructor.reconPack.attachments === 0) {
10512 this.emit('decoded', packet);
10513 }
10514 } else { // non-binary full packet
10515 this.emit('decoded', packet);
10516 }
10517 } else if (isBuf(obj) || obj.base64) { // raw binary data
10518 if (!this.reconstructor) {
10519 throw new Error('got binary data when not reconstructing a packet');
10520 } else {
10521 packet = this.reconstructor.takeBinaryData(obj);
10522 if (packet) { // received final buffer
10523 this.reconstructor = null;
10524 this.emit('decoded', packet);
10525 }
10526 }
10527 } else {
10528 throw new Error('Unknown type: ' + obj);
10529 }
10530};
10531
10532/**
10533 * Decode a packet String (JSON data)
10534 *
10535 * @param {String} str
10536 * @return {Object} packet
10537 * @api private
10538 */
10539
10540function decodeString(str) {
10541 var i = 0;
10542 // look up type
10543 var p = {
10544 type: Number(str.charAt(0))
10545 };
10546
10547 if (null == exports.types[p.type]) {
10548 return error('unknown packet type ' + p.type);
10549 }
10550
10551 // look up attachments if type binary
10552 if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) {
10553 var buf = '';
10554 while (str.charAt(++i) !== '-') {
10555 buf += str.charAt(i);
10556 if (i == str.length) break;
10557 }
10558 if (buf != Number(buf) || str.charAt(i) !== '-') {
10559 throw new Error('Illegal attachments');
10560 }
10561 p.attachments = Number(buf);
10562 }
10563
10564 // look up namespace (if any)
10565 if ('/' === str.charAt(i + 1)) {
10566 p.nsp = '';
10567 while (++i) {
10568 var c = str.charAt(i);
10569 if (',' === c) break;
10570 p.nsp += c;
10571 if (i === str.length) break;
10572 }
10573 } else {
10574 p.nsp = '/';
10575 }
10576
10577 // look up id
10578 var next = str.charAt(i + 1);
10579 if ('' !== next && Number(next) == next) {
10580 p.id = '';
10581 while (++i) {
10582 var c = str.charAt(i);
10583 if (null == c || Number(c) != c) {
10584 --i;
10585 break;
10586 }
10587 p.id += str.charAt(i);
10588 if (i === str.length) break;
10589 }
10590 p.id = Number(p.id);
10591 }
10592
10593 // look up json data
10594 if (str.charAt(++i)) {
10595 var payload = tryParse(str.substr(i));
10596 var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload));
10597 if (isPayloadValid) {
10598 p.data = payload;
10599 } else {
10600 return error('invalid payload');
10601 }
10602 }
10603
10604 debug('decoded %s as %j', str, p);
10605 return p;
10606}
10607
10608function tryParse(str) {
10609 try {
10610 return JSON.parse(str);
10611 } catch(e){
10612 return false;
10613 }
10614}
10615
10616/**
10617 * Deallocates a parser's resources
10618 *
10619 * @api public
10620 */
10621
10622Decoder.prototype.destroy = function() {
10623 if (this.reconstructor) {
10624 this.reconstructor.finishedReconstruction();
10625 }
10626};
10627
10628/**
10629 * A manager of a binary event's 'buffer sequence'. Should
10630 * be constructed whenever a packet of type BINARY_EVENT is
10631 * decoded.
10632 *
10633 * @param {Object} packet
10634 * @return {BinaryReconstructor} initialized reconstructor
10635 * @api private
10636 */
10637
10638function BinaryReconstructor(packet) {
10639 this.reconPack = packet;
10640 this.buffers = [];
10641}
10642
10643/**
10644 * Method to be called when binary data received from connection
10645 * after a BINARY_EVENT packet.
10646 *
10647 * @param {Buffer | ArrayBuffer} binData - the raw binary data received
10648 * @return {null | Object} returns null if more binary data is expected or
10649 * a reconstructed packet object if all buffers have been received.
10650 * @api private
10651 */
10652
10653BinaryReconstructor.prototype.takeBinaryData = function(binData) {
10654 this.buffers.push(binData);
10655 if (this.buffers.length === this.reconPack.attachments) { // done with buffer list
10656 var packet = binary.reconstructPacket(this.reconPack, this.buffers);
10657 this.finishedReconstruction();
10658 return packet;
10659 }
10660 return null;
10661};
10662
10663/**
10664 * Cleans up binary packet reconstruction variables.
10665 *
10666 * @api private
10667 */
10668
10669BinaryReconstructor.prototype.finishedReconstruction = function() {
10670 this.reconPack = null;
10671 this.buffers = [];
10672};
10673
10674function error(msg) {
10675 return {
10676 type: exports.ERROR,
10677 data: 'parser error: ' + msg
10678 };
10679}
10680
10681},{"./binary":73,"./is-buffer":75,"component-emitter":37,"debug":39,"isarray":60}],75:[function(require,module,exports){
10682(function (Buffer){
10683
10684module.exports = isBuf;
10685
10686var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function';
10687var withNativeArrayBuffer = typeof ArrayBuffer === 'function';
10688
10689var isView = function (obj) {
10690 return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer);
10691};
10692
10693/**
10694 * Returns true if obj is a buffer or an arraybuffer.
10695 *
10696 * @api private
10697 */
10698
10699function isBuf(obj) {
10700 return (withNativeBuffer && Buffer.isBuffer(obj)) ||
10701 (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)));
10702}
10703
10704}).call(this,require("buffer").Buffer)
10705},{"buffer":35}],76:[function(require,module,exports){
10706module.exports = toArray
10707
10708function toArray(list, index) {
10709 var array = []
10710
10711 index = index || 0
10712
10713 for (var i = index || 0; i < list.length; i++) {
10714 array[i - index] = list[i]
10715 }
10716
10717 return array
10718}
10719
10720},{}],77:[function(require,module,exports){
10721'use strict';
10722
10723var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
10724 , length = 64
10725 , map = {}
10726 , seed = 0
10727 , i = 0
10728 , prev;
10729
10730/**
10731 * Return a string representing the specified number.
10732 *
10733 * @param {Number} num The number to convert.
10734 * @returns {String} The string representation of the number.
10735 * @api public
10736 */
10737function encode(num) {
10738 var encoded = '';
10739
10740 do {
10741 encoded = alphabet[num % length] + encoded;
10742 num = Math.floor(num / length);
10743 } while (num > 0);
10744
10745 return encoded;
10746}
10747
10748/**
10749 * Return the integer value specified by the given string.
10750 *
10751 * @param {String} str The string to convert.
10752 * @returns {Number} The integer value represented by the string.
10753 * @api public
10754 */
10755function decode(str) {
10756 var decoded = 0;
10757
10758 for (i = 0; i < str.length; i++) {
10759 decoded = decoded * length + map[str.charAt(i)];
10760 }
10761
10762 return decoded;
10763}
10764
10765/**
10766 * Yeast: A tiny growing id generator.
10767 *
10768 * @returns {String} A unique id.
10769 * @api public
10770 */
10771function yeast() {
10772 var now = encode(+new Date());
10773
10774 if (now !== prev) return seed = 0, prev = now;
10775 return now +'.'+ encode(seed++);
10776}
10777
10778//
10779// Map each character to its index.
10780//
10781for (; i < length; i++) map[alphabet[i]] = i;
10782
10783//
10784// Expose the `yeast`, `encode` and `decode` functions.
10785//
10786yeast.encode = encode;
10787yeast.decode = decode;
10788module.exports = yeast;
10789
10790},{}]},{},[1]);