diff --git a/dist/scatter.cjs.js b/dist/scatter.cjs.js index 8a409b87..60fb5e65 100644 --- a/dist/scatter.cjs.js +++ b/dist/scatter.cjs.js @@ -2,7 +2,6 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var io = _interopDefault(require('socket.io-client')); var getRandomValues = _interopDefault(require('get-random-values')); var Eos = _interopDefault(require('eosjs')); require('isomorphic-fetch'); @@ -50,7 +49,7 @@ class StorageService { const {ecc} = Eos.modules; -const host = 'ws://127.0.0.1:50005/socket.io/?EIO=3&transport=websocket'; +const host = '127.0.0.1:50005'; let socket = null; let connected = false; @@ -58,12 +57,9 @@ let paired = false; let plugin; let openRequests = []; - -let allowReconnects = true; let reconnectionTimeout = null; const reconnectOnAbnormalDisconnection = () => { - if(!allowReconnects) return; clearTimeout(reconnectionTimeout); reconnectionTimeout = setTimeout(() => { @@ -94,11 +90,16 @@ const getOrigin = () => { let appkey = StorageService.getAppKey(); if(!appkey) appkey = 'appkey:'+random(); +const send = (type = null, data = null) => { + if(type === null && data === null) socket.send('40/scatter'); + else socket.send('42/scatter,' + JSON.stringify([type, data])); +}; + let pairingPromise = null; const pair = (passthrough = false) => { return new Promise((resolve, reject) => { pairingPromise = {resolve, reject}; - socket.emit('pair', {data:{ appkey, origin:getOrigin(), passthrough }, plugin}); + send('pair', {data:{ appkey, origin:getOrigin(), passthrough }, plugin}); }) }; @@ -124,17 +125,44 @@ class SocketService { reconnectOnAbnormalDisconnection(); }, this.timeout)), new Promise((resolve, reject) => { - socket = io.connect(`${host}/scatter`, { secure:true, reconnection: false, rejectUnauthorized : false }); + socket = new WebSocket(`ws://${host}/socket.io/?EIO=3&transport=websocket`); + + socket.onclose = x => { + resolve(false); + }; - socket.on('connected', () => { + socket.onerror = err => { + console.error('err', err); + resolve(false); + }; + + socket.onopen = x => { + send(); clearTimeout(reconnectionTimeout); connected = true; pair(true).then(() => { + console.log('then pair', connected); resolve(true); }); - }); + }; + + socket.onmessage = msg => { + // Handshaking/Upgrading + if(msg.data.indexOf('42/scatter') === -1) return false; + + + // Real message + const [type, data] = JSON.parse(msg.data.replace('42/scatter,', '')); - socket.on('paired', result => { + switch(type){ + case 'paired': return msg_paired(data); + case 'rekey': return msg_rekey(); + case 'api': return msg_api(data); + } + }; + + const msg_paired = result => { + console.log('paired', result); paired = result; if(paired) { @@ -148,44 +176,46 @@ class SocketService { } pairingPromise.resolve(result); - }); + }; - socket.on('rekey', () => { + const msg_rekey = () => { appkey = 'appkey:'+random(); - socket.emit('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin}); - }); - - socket.on('event', event => { - console.log('event', event); - }); + send('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin}); + }; - socket.on('api', result => { + const msg_api = result => { const openRequest = openRequests.find(x => x.id === result.id); if(!openRequest) return; if(typeof result.result === 'object' && result.result !== null && result.result.hasOwnProperty('isError')) openRequest.reject(result.result); else openRequest.resolve(result.result); - }); - - socket.on('disconnect', () => { - console.log('Disconnected'); - connected = false; - socket = null; - - // If bad disconnect, retry connection - reconnectOnAbnormalDisconnection(); - }); - - socket.on('connect_error', () => { - allowReconnects = false; - resolve(false); - }); - - socket.on('rejected', reason => { - console.error('reason', reason); - reject(reason); - }); + }; + + + // + // socket.on('event', event => { + // console.log('event', event); + // }); + // + // socket.on('disconnect', () => { + // console.log('Disconnected') + // connected = false; + // socket = null; + // + // // If bad disconnect, retry connection + // reconnectOnAbnormalDisconnection(); + // }); + // + // socket.on('connect_error', () => { + // allowReconnects = false; + // resolve(false); + // }); + // + // socket.on('rejected', reason => { + // console.error('reason', reason); + // reject(reason); + // }); }) ]) } @@ -224,7 +254,7 @@ class SocketService { openRequests.push(Object.assign(request, {resolve, reject})); - socket.emit('api', {data:request, plugin}); + send('api', {data:request, plugin}); }); }); } @@ -305,7 +335,7 @@ class EOS extends Plugin { if(!network.isValid()) throw Error.noNetwork(); const httpEndpoint = `${network.protocol}://${network.hostport()}`; - const chainId = network.hasOwnProperty('chainId') && network.chainId.length ? network.chainId : options.chainId; + const chainId = network.hasOwnProperty('chainId') && network.chainId.length ? network.chainId : _options.chainId; // The proxy stands between the eosjs object and scatter. // This is used to add special functionality like adding `requiredFields` arrays to transactions diff --git a/dist/scatter.esm.js b/dist/scatter.esm.js index a2a1354d..4ceb2fd8 100644 --- a/dist/scatter.esm.js +++ b/dist/scatter.esm.js @@ -1,4 +1,3 @@ -import io from 'socket.io-client'; import getRandomValues from 'get-random-values'; import Eos from 'eosjs'; import 'isomorphic-fetch'; @@ -46,7 +45,7 @@ class StorageService { const {ecc} = Eos.modules; -const host = 'ws://127.0.0.1:50005/socket.io/?EIO=3&transport=websocket'; +const host = '127.0.0.1:50005'; let socket = null; let connected = false; @@ -54,12 +53,9 @@ let paired = false; let plugin; let openRequests = []; - -let allowReconnects = true; let reconnectionTimeout = null; const reconnectOnAbnormalDisconnection = () => { - if(!allowReconnects) return; clearTimeout(reconnectionTimeout); reconnectionTimeout = setTimeout(() => { @@ -90,11 +86,16 @@ const getOrigin = () => { let appkey = StorageService.getAppKey(); if(!appkey) appkey = 'appkey:'+random(); +const send = (type = null, data = null) => { + if(type === null && data === null) socket.send('40/scatter'); + else socket.send('42/scatter,' + JSON.stringify([type, data])); +}; + let pairingPromise = null; const pair = (passthrough = false) => { return new Promise((resolve, reject) => { pairingPromise = {resolve, reject}; - socket.emit('pair', {data:{ appkey, origin:getOrigin(), passthrough }, plugin}); + send('pair', {data:{ appkey, origin:getOrigin(), passthrough }, plugin}); }) }; @@ -120,17 +121,44 @@ class SocketService { reconnectOnAbnormalDisconnection(); }, this.timeout)), new Promise((resolve, reject) => { - socket = io.connect(`${host}/scatter`, { secure:true, reconnection: false, rejectUnauthorized : false }); + socket = new WebSocket(`ws://${host}/socket.io/?EIO=3&transport=websocket`); + + socket.onclose = x => { + resolve(false); + }; - socket.on('connected', () => { + socket.onerror = err => { + console.error('err', err); + resolve(false); + }; + + socket.onopen = x => { + send(); clearTimeout(reconnectionTimeout); connected = true; pair(true).then(() => { + console.log('then pair', connected); resolve(true); }); - }); + }; + + socket.onmessage = msg => { + // Handshaking/Upgrading + if(msg.data.indexOf('42/scatter') === -1) return false; + + + // Real message + const [type, data] = JSON.parse(msg.data.replace('42/scatter,', '')); - socket.on('paired', result => { + switch(type){ + case 'paired': return msg_paired(data); + case 'rekey': return msg_rekey(); + case 'api': return msg_api(data); + } + }; + + const msg_paired = result => { + console.log('paired', result); paired = result; if(paired) { @@ -144,44 +172,46 @@ class SocketService { } pairingPromise.resolve(result); - }); + }; - socket.on('rekey', () => { + const msg_rekey = () => { appkey = 'appkey:'+random(); - socket.emit('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin}); - }); - - socket.on('event', event => { - console.log('event', event); - }); + send('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin}); + }; - socket.on('api', result => { + const msg_api = result => { const openRequest = openRequests.find(x => x.id === result.id); if(!openRequest) return; if(typeof result.result === 'object' && result.result !== null && result.result.hasOwnProperty('isError')) openRequest.reject(result.result); else openRequest.resolve(result.result); - }); - - socket.on('disconnect', () => { - console.log('Disconnected'); - connected = false; - socket = null; - - // If bad disconnect, retry connection - reconnectOnAbnormalDisconnection(); - }); - - socket.on('connect_error', () => { - allowReconnects = false; - resolve(false); - }); - - socket.on('rejected', reason => { - console.error('reason', reason); - reject(reason); - }); + }; + + + // + // socket.on('event', event => { + // console.log('event', event); + // }); + // + // socket.on('disconnect', () => { + // console.log('Disconnected') + // connected = false; + // socket = null; + // + // // If bad disconnect, retry connection + // reconnectOnAbnormalDisconnection(); + // }); + // + // socket.on('connect_error', () => { + // allowReconnects = false; + // resolve(false); + // }); + // + // socket.on('rejected', reason => { + // console.error('reason', reason); + // reject(reason); + // }); }) ]) } @@ -220,7 +250,7 @@ class SocketService { openRequests.push(Object.assign(request, {resolve, reject})); - socket.emit('api', {data:request, plugin}); + send('api', {data:request, plugin}); }); }); } @@ -301,7 +331,7 @@ class EOS extends Plugin { if(!network.isValid()) throw Error.noNetwork(); const httpEndpoint = `${network.protocol}://${network.hostport()}`; - const chainId = network.hasOwnProperty('chainId') && network.chainId.length ? network.chainId : options.chainId; + const chainId = network.hasOwnProperty('chainId') && network.chainId.length ? network.chainId : _options.chainId; // The proxy stands between the eosjs object and scatter. // This is used to add special functionality like adding `requiredFields` arrays to transactions diff --git a/dist/scatter.min.js b/dist/scatter.min.js index d165c706..d2421fe1 100644 --- a/dist/scatter.min.js +++ b/dist/scatter.min.js @@ -60,7 +60,7 @@ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 141); +/******/ return __webpack_require__(__webpack_require__.s = 120); /******/ }) /************************************************************************/ /******/ ([ @@ -175,9 +175,9 @@ if (typeof Object.create === 'function') { -var base64 = __webpack_require__(179) -var ieee754 = __webpack_require__(180) -var isArray = __webpack_require__(181) +var base64 = __webpack_require__(168) +var ieee754 = __webpack_require__(169) +var isArray = __webpack_require__(170) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer @@ -1955,37 +1955,10 @@ function isnan (val) { return val !== val // eslint-disable-line no-self-compare } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }), /* 3 */ -/***/ (function(module, exports) { - -var g; - -// This works in non-strict mode -g = (function() { - return this; -})(); - -try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1,eval)("this"); -} catch(e) { - // This works if the window reference is available - if(typeof window === "object") - g = window; -} - -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} - -module.exports = g; - - -/***/ }), -/* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -2057,7 +2030,7 @@ function isBuffer(b) { // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -var util = __webpack_require__(235); +var util = __webpack_require__(194); var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { @@ -2480,10 +2453,10 @@ var objectKeys = Object.keys || function (obj) { return keys; }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }), -/* 5 */ +/* 4 */ /***/ (function(module, exports) { var core = module.exports = { version: '2.5.7' }; @@ -2491,7 +2464,7 @@ if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), -/* 6 */ +/* 5 */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 @@ -2503,12 +2476,12 @@ if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), -/* 7 */ +/* 6 */ /***/ (function(module, exports, __webpack_require__) { -var store = __webpack_require__(56)('wks'); -var uid = __webpack_require__(41); -var Symbol = __webpack_require__(6).Symbol; +var store = __webpack_require__(51)('wks'); +var uid = __webpack_require__(38); +var Symbol = __webpack_require__(5).Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { @@ -2519,11 +2492,38 @@ var $exports = module.exports = function (name) { $exports.store = store; +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { -var isObject = __webpack_require__(14); +var isObject = __webpack_require__(13); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; @@ -2534,224 +2534,22 @@ module.exports = function (it) { /* 9 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(process) {/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = __webpack_require__(171); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', - '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', - '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', - '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', - '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', - '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', - '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', - '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', - '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', - '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', - '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17))) - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -var BigInteger = __webpack_require__(126) +var BigInteger = __webpack_require__(105) //addons -__webpack_require__(238) +__webpack_require__(197) module.exports = BigInteger /***/ }), -/* 11 */ +/* 10 */ /***/ (function(module, exports, __webpack_require__) { -var global = __webpack_require__(6); -var core = __webpack_require__(5); -var ctx = __webpack_require__(38); -var hide = __webpack_require__(12); -var has = __webpack_require__(16); +var global = __webpack_require__(5); +var core = __webpack_require__(4); +var ctx = __webpack_require__(35); +var hide = __webpack_require__(11); +var has = __webpack_require__(15); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { @@ -2812,12 +2610,12 @@ module.exports = $export; /***/ }), -/* 12 */ +/* 11 */ /***/ (function(module, exports, __webpack_require__) { -var dP = __webpack_require__(13); -var createDesc = __webpack_require__(40); -module.exports = __webpack_require__(15) ? function (object, key, value) { +var dP = __webpack_require__(12); +var createDesc = __webpack_require__(37); +module.exports = __webpack_require__(14) ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; @@ -2826,15 +2624,15 @@ module.exports = __webpack_require__(15) ? function (object, key, value) { /***/ }), -/* 13 */ +/* 12 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(8); -var IE8_DOM_DEFINE = __webpack_require__(80); -var toPrimitive = __webpack_require__(52); +var IE8_DOM_DEFINE = __webpack_require__(71); +var toPrimitive = __webpack_require__(47); var dP = Object.defineProperty; -exports.f = __webpack_require__(15) ? Object.defineProperty : function defineProperty(O, P, Attributes) { +exports.f = __webpack_require__(14) ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); @@ -2848,7 +2646,7 @@ exports.f = __webpack_require__(15) ? Object.defineProperty : function definePro /***/ }), -/* 14 */ +/* 13 */ /***/ (function(module, exports) { module.exports = function (it) { @@ -2857,17 +2655,17 @@ module.exports = function (it) { /***/ }), -/* 15 */ +/* 14 */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty -module.exports = !__webpack_require__(21)(function () { +module.exports = !__webpack_require__(19)(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), -/* 16 */ +/* 15 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; @@ -2877,202 +2675,12 @@ module.exports = function (it, key) { /***/ }), -/* 17 */ -/***/ (function(module, exports) { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // 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 - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // 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. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - -/***/ }), -/* 18 */ +/* 16 */ /***/ (function(module, exports, __webpack_require__) { var Buffer = __webpack_require__(0).Buffer -var Transform = __webpack_require__(117).Transform -var StringDecoder = __webpack_require__(73).StringDecoder +var Transform = __webpack_require__(96).Transform +var StringDecoder = __webpack_require__(64).StringDecoder var inherits = __webpack_require__(1) function CipherBase (hashMode) { @@ -3172,7 +2780,7 @@ module.exports = CipherBase /***/ }), -/* 19 */ +/* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -3206,7 +2814,7 @@ module.exports = CipherBase /**/ -var pna = __webpack_require__(49); +var pna = __webpack_require__(44); /**/ /**/ @@ -3221,12 +2829,12 @@ var objectKeys = Object.keys || function (obj) { module.exports = Duplex; /**/ -var util = __webpack_require__(34); +var util = __webpack_require__(31); util.inherits = __webpack_require__(1); /**/ -var Readable = __webpack_require__(118); -var Writable = __webpack_require__(72); +var Readable = __webpack_require__(97); +var Writable = __webpack_require__(63); util.inherits(Duplex, Readable); @@ -3309,14 +2917,14 @@ Duplex.prototype._destroy = function (err, cb) { }; /***/ }), -/* 20 */ +/* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var createHash = __webpack_require__(76); -var createHmac = __webpack_require__(245); +var createHash = __webpack_require__(67); +var createHmac = __webpack_require__(204); /** @namespace hash */ @@ -3377,7 +2985,7 @@ module.exports = { }; /***/ }), -/* 21 */ +/* 19 */ /***/ (function(module, exports) { module.exports = function (exec) { @@ -3390,808 +2998,216 @@ module.exports = function (exec) { /***/ }), -/* 22 */ +/* 20 */ /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings -var IObject = __webpack_require__(82); -var defined = __webpack_require__(53); +var IObject = __webpack_require__(73); +var defined = __webpack_require__(48); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), -/* 23 */ +/* 21 */ /***/ (function(module, exports) { module.exports = {}; /***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * Expose `Emitter`. - */ - -if (true) { - module.exports = Emitter; -} - -/** - * Initialize a new `Emitter`. - * - * @api public - */ - -function Emitter(obj) { - if (obj) return mixin(obj); -}; - -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; -}; - -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks['$' + event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; -}; - -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; - -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - */ - -var keys = __webpack_require__(178); -var hasBinary = __webpack_require__(101); -var sliceBuffer = __webpack_require__(182); -var after = __webpack_require__(183); -var utf8 = __webpack_require__(184); - -var base64encoder; -if (global && global.ArrayBuffer) { - base64encoder = __webpack_require__(185); -} - -/** - * Check if we are running an android browser. That requires us to use - * ArrayBuffer with polling transports... - * - * http://ghinda.net/jpeg-blob-ajax-android/ - */ - -var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent); - -/** - * Check if we are running in PhantomJS. - * Uploading a Blob with PhantomJS does not work correctly, as reported here: - * https://github.com/ariya/phantomjs/issues/11395 - * @type boolean - */ -var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent); - -/** - * When true, avoids using Blobs to encode payloads. - * @type boolean - */ -var dontSendBlobs = isAndroid || isPhantomJS; - -/** - * Current protocol version. - */ - -exports.protocol = 3; - -/** - * Packet types. - */ - -var packets = exports.packets = { - open: 0 // non-ws - , close: 1 // non-ws - , ping: 2 - , pong: 3 - , message: 4 - , upgrade: 5 - , noop: 6 -}; - -var packetslist = keys(packets); - -/** - * Premade error packet. - */ - -var err = { type: 'error', data: 'parser error' }; - -/** - * Create a blob api even for blob builder when vendor prefixes exist - */ - -var Blob = __webpack_require__(186); - -/** - * Encodes a packet. - * - * [ ] - * - * Example: - * - * 5hello world - * 3 - * 4 - * - * Binary is encoded in an identical principle - * - * @api private - */ - -exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { - if (typeof supportsBinary === 'function') { - callback = supportsBinary; - supportsBinary = false; - } - - if (typeof utf8encode === 'function') { - callback = utf8encode; - utf8encode = null; - } - - var data = (packet.data === undefined) - ? undefined - : packet.data.buffer || packet.data; - - if (global.ArrayBuffer && data instanceof ArrayBuffer) { - return encodeArrayBuffer(packet, supportsBinary, callback); - } else if (Blob && data instanceof global.Blob) { - return encodeBlob(packet, supportsBinary, callback); - } - - // might be an object with { base64: true, data: dataAsBase64String } - if (data && data.base64) { - return encodeBase64Object(packet, callback); - } - - // Sending data as a utf-8 string - var encoded = packets[packet.type]; - - // data fragment is optional - if (undefined !== packet.data) { - encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data); - } - - return callback('' + encoded); - -}; - -function encodeBase64Object(packet, callback) { - // packet data is an object { base64: true, data: dataAsBase64String } - var message = 'b' + exports.packets[packet.type] + packet.data.data; - return callback(message); -} - -/** - * Encode packet helpers for binary types - */ - -function encodeArrayBuffer(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } - - var data = packet.data; - var contentArray = new Uint8Array(data); - var resultBuffer = new Uint8Array(1 + data.byteLength); +/* 22 */ +/***/ (function(module, exports) { - resultBuffer[0] = packets[packet.type]; - for (var i = 0; i < contentArray.length; i++) { - resultBuffer[i+1] = contentArray[i]; - } +// shim for using process in browser +var process = module.exports = {}; - return callback(resultBuffer.buffer); -} +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. -function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } +var cachedSetTimeout; +var cachedClearTimeout; - var fr = new FileReader(); - fr.onload = function() { - packet.data = fr.result; - exports.encodePacket(packet, supportsBinary, true, callback); - }; - return fr.readAsArrayBuffer(packet.data); +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); } - -function encodeBlob(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } - - if (dontSendBlobs) { - return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); - } - - var length = new Uint8Array(1); - length[0] = packets[packet.type]; - var blob = new Blob([length.buffer, packet.data]); - - return callback(blob); +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); } - -/** - * Encodes a packet with binary data in a base64 string - * - * @param {Object} packet, has `type` and `data` - * @return {String} base64 encoded message - */ - -exports.encodeBase64Packet = function(packet, callback) { - var message = 'b' + exports.packets[packet.type]; - if (Blob && packet.data instanceof global.Blob) { - var fr = new FileReader(); - fr.onload = function() { - var b64 = fr.result.split(',')[1]; - callback(message + b64); - }; - return fr.readAsDataURL(packet.data); - } - - var b64data; - try { - b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); - } catch (e) { - // iPhone Safari doesn't let you apply with typed arrays - var typed = new Uint8Array(packet.data); - var basic = new Array(typed.length); - for (var i = 0; i < typed.length; i++) { - basic[i] = typed[i]; +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; } - b64data = String.fromCharCode.apply(null, basic); - } - message += global.btoa(b64data); - return callback(message); -}; - -/** - * Decodes a packet. Changes format to Blob if requested. - * - * @return {Object} with `type` and `data` (if any) - * @api private - */ - -exports.decodePacket = function (data, binaryType, utf8decode) { - if (data === undefined) { - return err; - } - // String data - if (typeof data === 'string') { - if (data.charAt(0) === 'b') { - return exports.decodeBase64Packet(data.substr(1), binaryType); + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; } - - if (utf8decode) { - data = tryDecode(data); - if (data === false) { - return err; - } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); } - var type = data.charAt(0); - - if (Number(type) != type || !packetslist[type]) { - return err; + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); } - - if (data.length > 1) { - return { type: packetslist[type], data: data.substring(1) }; - } else { - return { type: packetslist[type] }; + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // 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 + return cachedSetTimeout.call(this, fun, 0); + } } - } - var asArray = new Uint8Array(data); - var type = asArray[0]; - var rest = sliceBuffer(data, 1); - if (Blob && binaryType === 'blob') { - rest = new Blob([rest]); - } - return { type: packetslist[type], data: rest }; -}; -function tryDecode(data) { - try { - data = utf8.decode(data, { strict: false }); - } catch (e) { - return false; - } - return data; } - -/** - * Decodes a packet encoded in a base64 string - * - * @param {String} base64 encoded message - * @return {Object} with `type` and `data` (if any) - */ - -exports.decodeBase64Packet = function(msg, binaryType) { - var type = packetslist[msg.charAt(0)]; - if (!base64encoder) { - return { type: type, data: { base64: true, data: msg.substr(1) } }; - } - - var data = base64encoder.decode(msg.substr(1)); - - if (binaryType === 'blob' && Blob) { - data = new Blob([data]); - } - - return { type: type, data: data }; -}; - -/** - * Encodes multiple messages (payload). - * - * :data - * - * Example: - * - * 11:hello world2:hi - * - * If any contents are binary, they will be encoded as base64 strings. Base64 - * encoded strings are marked with a b before the length specifier - * - * @param {Array} packets - * @api private - */ - -exports.encodePayload = function (packets, supportsBinary, callback) { - if (typeof supportsBinary === 'function') { - callback = supportsBinary; - supportsBinary = null; - } - - var isBinary = hasBinary(packets); - - if (supportsBinary && isBinary) { - if (Blob && !dontSendBlobs) { - return exports.encodePayloadAsBlob(packets, callback); +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // 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. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } } - return exports.encodePayloadAsArrayBuffer(packets, callback); - } - - if (!packets.length) { - return callback('0:'); - } - - function setLengthHeader(message) { - return message.length + ':' + message; - } - - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) { - doneCallback(null, setLengthHeader(message)); - }); - } - - map(packets, encodeOne, function(err, results) { - return callback(results.join('')); - }); -}; - -/** - * Async array map using after - */ - -function map(ary, each, done) { - var result = new Array(ary.length); - var next = after(ary.length, done); - var eachWithIndex = function(i, el, cb) { - each(el, function(error, msg) { - result[i] = msg; - cb(error, result); - }); - }; - for (var i = 0; i < ary.length; i++) { - eachWithIndex(i, ary[i], next); - } } +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; -/* - * Decodes data when a payload is maybe expected. Possible binary contents are - * decoded from their base64 representation - * - * @param {String} data, callback method - * @api public - */ - -exports.decodePayload = function (data, binaryType, callback) { - if (typeof data !== 'string') { - return exports.decodePayloadAsBinary(data, binaryType, callback); - } - - if (typeof binaryType === 'function') { - callback = binaryType; - binaryType = null; - } - - var packet; - if (data === '') { - // parser error - ignoring payload - return callback(err, 0, 1); - } - - var length = '', n, msg; - - for (var i = 0, l = data.length; i < l; i++) { - var chr = data.charAt(i); - - if (chr !== ':') { - length += chr; - continue; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; } - - if (length === '' || (length != (n = Number(length)))) { - // parser error - ignoring payload - return callback(err, 0, 1); + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; } - - msg = data.substr(i + 1, n); - - if (length != msg.length) { - // parser error - ignoring payload - return callback(err, 0, 1); + if (queue.length) { + drainQueue(); } +} - if (msg.length) { - packet = exports.decodePacket(msg, binaryType, false); - - if (err.type === packet.type && err.data === packet.data) { - // parser error in individual packet - ignoring payload - return callback(err, 0, 1); - } - - var ret = callback(packet, i + n, l); - if (false === ret) return; +function drainQueue() { + if (draining) { + return; } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - // advance cursor - i += n; - length = ''; - } - - if (length !== '') { - // parser error - ignoring payload - return callback(err, 0, 1); - } - -}; - -/** - * Encodes multiple messages (payload) as binary. - * - * <1 = binary, 0 = string>[...] - * - * Example: - * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers - * - * @param {Array} packets - * @return {ArrayBuffer} encoded payload - * @api private - */ - -exports.encodePayloadAsArrayBuffer = function(packets, callback) { - if (!packets.length) { - return callback(new ArrayBuffer(0)); - } - - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, true, true, function(data) { - return doneCallback(null, data); - }); - } - - map(packets, encodeOne, function(err, encodedPackets) { - var totalLength = encodedPackets.reduce(function(acc, p) { - var len; - if (typeof p === 'string'){ - len = p.length; - } else { - len = p.byteLength; - } - return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 - }, 0); - - var resultArray = new Uint8Array(totalLength); - - var bufferIndex = 0; - encodedPackets.forEach(function(p) { - var isString = typeof p === 'string'; - var ab = p; - if (isString) { - var view = new Uint8Array(p.length); - for (var i = 0; i < p.length; i++) { - view[i] = p.charCodeAt(i); + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } } - ab = view.buffer; - } - - if (isString) { // not true binary - resultArray[bufferIndex++] = 0; - } else { // true binary - resultArray[bufferIndex++] = 1; - } - - var lenStr = ab.byteLength.toString(); - for (var i = 0; i < lenStr.length; i++) { - resultArray[bufferIndex++] = parseInt(lenStr[i]); - } - resultArray[bufferIndex++] = 255; - - var view = new Uint8Array(ab); - for (var i = 0; i < view.length; i++) { - resultArray[bufferIndex++] = view[i]; - } - }); - - return callback(resultArray.buffer); - }); -}; - -/** - * Encode as Blob - */ + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} -exports.encodePayloadAsBlob = function(packets, callback) { - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, true, true, function(encoded) { - var binaryIdentifier = new Uint8Array(1); - binaryIdentifier[0] = 1; - if (typeof encoded === 'string') { - var view = new Uint8Array(encoded.length); - for (var i = 0; i < encoded.length; i++) { - view[i] = encoded.charCodeAt(i); +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; } - encoded = view.buffer; - binaryIdentifier[0] = 0; - } - - var len = (encoded instanceof ArrayBuffer) - ? encoded.byteLength - : encoded.size; - - var lenStr = len.toString(); - var lengthAry = new Uint8Array(lenStr.length + 1); - for (var i = 0; i < lenStr.length; i++) { - lengthAry[i] = parseInt(lenStr[i]); - } - lengthAry[lenStr.length] = 255; - - if (Blob) { - var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); - doneCallback(null, blob); - } - }); - } - - map(packets, encodeOne, function(err, results) { - return callback(new Blob(results)); - }); + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } }; -/* - * Decodes data when a payload is maybe expected. Strings are decoded by - * interpreting each byte as a key code for entries marked to start with 0. See - * description of encodePayloadAsBinary - * - * @param {ArrayBuffer} data, callback method - * @api public - */ - -exports.decodePayloadAsBinary = function (data, binaryType, callback) { - if (typeof binaryType === 'function') { - callback = binaryType; - binaryType = null; - } - - var bufferTail = data; - var buffers = []; - - while (bufferTail.byteLength > 0) { - var tailArray = new Uint8Array(bufferTail); - var isString = tailArray[0] === 0; - var msgLength = ''; - - for (var i = 1; ; i++) { - if (tailArray[i] === 255) break; - - // 310 = char length of Number.MAX_VALUE - if (msgLength.length > 310) { - return callback(err, 0, 1); - } +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; - msgLength += tailArray[i]; - } +function noop() {} - bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); - msgLength = parseInt(msgLength); +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; - var msg = sliceBuffer(bufferTail, 0, msgLength); - if (isString) { - try { - msg = String.fromCharCode.apply(null, new Uint8Array(msg)); - } catch (e) { - // iPhone Safari doesn't let you apply to typed arrays - var typed = new Uint8Array(msg); - msg = ''; - for (var i = 0; i < typed.length; i++) { - msg += String.fromCharCode(typed[i]); - } - } - } +process.listeners = function (name) { return [] } - buffers.push(msg); - bufferTail = sliceBuffer(bufferTail, msgLength); - } +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - var total = buffers.length; - buffers.forEach(function(buffer, i) { - callback(exports.decodePacket(buffer, binaryType, true), i, total); - }); +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); }; +process.umask = function() { return 0; }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), -/* 26 */ +/* 23 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* @@ -4219,7 +3235,7 @@ var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_ (function(global, factory) { /* AMD */ if (true) - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(212)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(171)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -7946,7 +6962,7 @@ var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_ /***/ }), -/* 27 */ +/* 24 */ /***/ (function(module, exports, __webpack_require__) { var Buffer = __webpack_require__(0).Buffer @@ -8033,12 +7049,12 @@ module.exports = Hash /***/ }), -/* 28 */ +/* 25 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) -var $keys = __webpack_require__(81); -var enumBugKeys = __webpack_require__(57); +var $keys = __webpack_require__(72); +var enumBugKeys = __webpack_require__(52); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); @@ -8046,7 +7062,7 @@ module.exports = Object.keys || function keys(O) { /***/ }), -/* 29 */ +/* 26 */ /***/ (function(module, exports) { var toString = {}.toString; @@ -8057,20 +7073,20 @@ module.exports = function (it) { /***/ }), -/* 30 */ +/* 27 */ /***/ (function(module, exports) { module.exports = true; /***/ }), -/* 31 */ +/* 28 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(147), __esModule: true }; +module.exports = { "default": __webpack_require__(126), __esModule: true }; /***/ }), -/* 32 */ +/* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -8078,11 +7094,11 @@ module.exports = { "default": __webpack_require__(147), __esModule: true }; exports.__esModule = true; -var _iterator = __webpack_require__(199); +var _iterator = __webpack_require__(155); var _iterator2 = _interopRequireDefault(_iterator); -var _symbol = __webpack_require__(201); +var _symbol = __webpack_require__(157); var _symbol2 = _interopRequireDefault(_symbol); @@ -8097,7 +7113,7 @@ exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.d }; /***/ }), -/* 33 */ +/* 30 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {module.exports = function xor (a, b) { @@ -8114,7 +7130,7 @@ exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.d /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) /***/ }), -/* 34 */ +/* 31 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors. @@ -8228,7 +7244,7 @@ function objectToString(o) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) /***/ }), -/* 35 */ +/* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -8238,13 +7254,13 @@ var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = [ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -var assert = __webpack_require__(4); -var ecurve = __webpack_require__(75); -var BigInteger = __webpack_require__(10); +var assert = __webpack_require__(3); +var ecurve = __webpack_require__(66); +var BigInteger = __webpack_require__(9); var secp256k1 = ecurve.getCurveByName('secp256k1'); -var hash = __webpack_require__(20); -var keyUtils = __webpack_require__(36); +var hash = __webpack_require__(18); +var keyUtils = __webpack_require__(33); var G = secp256k1.G; var n = secp256k1.n; @@ -8416,7 +7432,7 @@ PublicKey.fromStringHex = function (hex) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) /***/ }), -/* 36 */ +/* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -8424,11 +7440,11 @@ PublicKey.fromStringHex = function (hex) { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -var base58 = __webpack_require__(248); -var assert = __webpack_require__(4); -var randomBytes = __webpack_require__(111); +var base58 = __webpack_require__(207); +var assert = __webpack_require__(3); +var randomBytes = __webpack_require__(90); -var hash = __webpack_require__(20); +var hash = __webpack_require__(18); module.exports = { random32ByteBuffer: random32ByteBuffer, @@ -8690,17 +7706,17 @@ function checkDecode(keyString) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) /***/ }), -/* 37 */ +/* 34 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(142), __esModule: true }; +module.exports = { "default": __webpack_require__(121), __esModule: true }; /***/ }), -/* 38 */ +/* 35 */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding -var aFunction = __webpack_require__(39); +var aFunction = __webpack_require__(36); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; @@ -8722,7 +7738,7 @@ module.exports = function (fn, that, length) { /***/ }), -/* 39 */ +/* 36 */ /***/ (function(module, exports) { module.exports = function (it) { @@ -8732,7 +7748,7 @@ module.exports = function (it) { /***/ }), -/* 40 */ +/* 37 */ /***/ (function(module, exports) { module.exports = function (bitmap, value) { @@ -8746,7 +7762,7 @@ module.exports = function (bitmap, value) { /***/ }), -/* 41 */ +/* 38 */ /***/ (function(module, exports) { var id = 0; @@ -8757,22 +7773,22 @@ module.exports = function (key) { /***/ }), -/* 42 */ +/* 39 */ /***/ (function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }), -/* 43 */ +/* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $at = __webpack_require__(148)(true); +var $at = __webpack_require__(127)(true); // 21.1.3.27 String.prototype[@@iterator]() -__webpack_require__(85)(String, 'String', function (iterated) { +__webpack_require__(76)(String, 'String', function (iterated) { this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() @@ -8788,12 +7804,12 @@ __webpack_require__(85)(String, 'String', function (iterated) { /***/ }), -/* 44 */ +/* 41 */ /***/ (function(module, exports, __webpack_require__) { -var def = __webpack_require__(13).f; -var has = __webpack_require__(16); -var TAG = __webpack_require__(7)('toStringTag'); +var def = __webpack_require__(12).f; +var has = __webpack_require__(15); +var TAG = __webpack_require__(6)('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); @@ -8801,14 +7817,14 @@ module.exports = function (it, tag, stat) { /***/ }), -/* 45 */ +/* 42 */ /***/ (function(module, exports, __webpack_require__) { -__webpack_require__(152); -var global = __webpack_require__(6); -var hide = __webpack_require__(12); -var Iterators = __webpack_require__(23); -var TO_STRING_TAG = __webpack_require__(7)('toStringTag'); +__webpack_require__(131); +var global = __webpack_require__(5); +var hide = __webpack_require__(11); +var Iterators = __webpack_require__(21); +var TO_STRING_TAG = __webpack_require__(6)('toStringTag'); var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + @@ -8826,62 +7842,7 @@ for (var i = 0; i < DOMIterables.length; i++) { /***/ }), -/* 46 */ -/***/ (function(module, exports) { - -/** - * Compiles a querystring - * Returns string representation of the object - * - * @param {Object} - * @api private - */ - -exports.encode = function (obj) { - var str = ''; - - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - if (str.length) str += '&'; - str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); - } - } - - return str; -}; - -/** - * Parses a simple querystring into an object - * - * @param {String} qs - * @api private - */ - -exports.decode = function(qs){ - var qry = {}; - var pairs = qs.split('&'); - for (var i = 0, l = pairs.length; i < l; i++) { - var pair = pairs[i].split('='); - qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); - } - return qry; -}; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports) { - - -module.exports = function(a, b){ - var fn = function(){}; - fn.prototype = b.prototype; - a.prototype = new fn; - a.prototype.constructor = a; -}; - -/***/ }), -/* 48 */ +/* 43 */ /***/ (function(module, exports, __webpack_require__) { // based on the aes implimentation in triple sec @@ -9115,7 +8076,7 @@ module.exports.AES = AES /***/ }), -/* 49 */ +/* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -9164,10 +8125,10 @@ function nextTick(fn, arg1, arg2, arg3) { } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22))) /***/ }), -/* 50 */ +/* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -9179,17 +8140,17 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } -var ecurve = __webpack_require__(75); +var ecurve = __webpack_require__(66); var Point = ecurve.Point; var secp256k1 = ecurve.getCurveByName('secp256k1'); -var BigInteger = __webpack_require__(10); -var assert = __webpack_require__(4); +var BigInteger = __webpack_require__(9); +var assert = __webpack_require__(3); -var hash = __webpack_require__(20); -var PublicKey = __webpack_require__(35); -var keyUtils = __webpack_require__(36); -var createHash = __webpack_require__(76); -var promiseAsync = __webpack_require__(250); +var hash = __webpack_require__(18); +var PublicKey = __webpack_require__(32); +var keyUtils = __webpack_require__(33); +var createHash = __webpack_require__(67); +var promiseAsync = __webpack_require__(209); var G = secp256k1.G; var n = secp256k1.n; @@ -9505,11 +8466,11 @@ var doesNotThrow = function doesNotThrow(cb, msg) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) /***/ }), -/* 51 */ +/* 46 */ /***/ (function(module, exports, __webpack_require__) { -var isObject = __webpack_require__(14); -var document = __webpack_require__(6).document; +var isObject = __webpack_require__(13); +var document = __webpack_require__(5).document; // typeof document.createElement is 'object' in old IE var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { @@ -9518,11 +8479,11 @@ module.exports = function (it) { /***/ }), -/* 52 */ +/* 47 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) -var isObject = __webpack_require__(14); +var isObject = __webpack_require__(13); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (it, S) { @@ -9536,7 +8497,7 @@ module.exports = function (it, S) { /***/ }), -/* 53 */ +/* 48 */ /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) @@ -9547,7 +8508,7 @@ module.exports = function (it) { /***/ }), -/* 54 */ +/* 49 */ /***/ (function(module, exports) { // 7.1.4 ToInteger @@ -9559,22 +8520,22 @@ module.exports = function (it) { /***/ }), -/* 55 */ +/* 50 */ /***/ (function(module, exports, __webpack_require__) { -var shared = __webpack_require__(56)('keys'); -var uid = __webpack_require__(41); +var shared = __webpack_require__(51)('keys'); +var uid = __webpack_require__(38); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), -/* 56 */ +/* 51 */ /***/ (function(module, exports, __webpack_require__) { -var core = __webpack_require__(5); -var global = __webpack_require__(6); +var core = __webpack_require__(4); +var global = __webpack_require__(5); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); @@ -9582,13 +8543,13 @@ var store = global[SHARED] || (global[SHARED] = {}); return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: core.version, - mode: __webpack_require__(30) ? 'pure' : 'global', + mode: __webpack_require__(27) ? 'pure' : 'global', copyright: '© 2018 Denis Pushkarev (zloirock.ru)' }); /***/ }), -/* 57 */ +/* 52 */ /***/ (function(module, exports) { // IE 8- don't enum bug keys @@ -9598,30 +8559,30 @@ module.exports = ( /***/ }), -/* 58 */ +/* 53 */ /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), -/* 59 */ +/* 54 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) -var defined = __webpack_require__(53); +var defined = __webpack_require__(48); module.exports = function (it) { return Object(defined(it)); }; /***/ }), -/* 60 */ +/* 55 */ /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() -var cof = __webpack_require__(29); -var TAG = __webpack_require__(7)('toStringTag'); +var cof = __webpack_require__(26); +var TAG = __webpack_require__(6)('toStringTag'); // ES3 wrong here var ARG = cof(function () { return arguments; }()) == 'Arguments'; @@ -9645,13 +8606,13 @@ module.exports = function (it) { /***/ }), -/* 61 */ +/* 56 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 25.4.1.5 NewPromiseCapability(C) -var aFunction = __webpack_require__(39); +var aFunction = __webpack_require__(36); function PromiseCapability(C) { var resolve, reject; @@ -9670,7 +8631,7 @@ module.exports.f = function (C) { /***/ }), -/* 62 */ +/* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -9678,7 +8639,7 @@ module.exports.f = function (C) { exports.__esModule = true; -var _promise = __webpack_require__(31); +var _promise = __webpack_require__(28); var _promise2 = _interopRequireDefault(_promise); @@ -9714,662 +8675,21 @@ exports.default = function (fn) { }; /***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * Module dependencies. - */ - -var debug = __webpack_require__(9)('socket.io-parser'); -var Emitter = __webpack_require__(24); -var binary = __webpack_require__(173); -var isArray = __webpack_require__(64); -var isBuf = __webpack_require__(97); - -/** - * Protocol version. - * - * @api public - */ - -exports.protocol = 4; - -/** - * Packet types. - * - * @api public - */ - -exports.types = [ - 'CONNECT', - 'DISCONNECT', - 'EVENT', - 'ACK', - 'ERROR', - 'BINARY_EVENT', - 'BINARY_ACK' -]; - -/** - * Packet type `connect`. - * - * @api public - */ - -exports.CONNECT = 0; - -/** - * Packet type `disconnect`. - * - * @api public - */ - -exports.DISCONNECT = 1; - -/** - * Packet type `event`. - * - * @api public - */ - -exports.EVENT = 2; - -/** - * Packet type `ack`. - * - * @api public - */ - -exports.ACK = 3; - -/** - * Packet type `error`. - * - * @api public - */ - -exports.ERROR = 4; - -/** - * Packet type 'binary event' - * - * @api public - */ - -exports.BINARY_EVENT = 5; - -/** - * Packet type `binary ack`. For acks with binary arguments. - * - * @api public - */ - -exports.BINARY_ACK = 6; - -/** - * Encoder constructor. - * - * @api public - */ - -exports.Encoder = Encoder; - -/** - * Decoder constructor. - * - * @api public - */ - -exports.Decoder = Decoder; - -/** - * A socket.io Encoder instance - * - * @api public - */ - -function Encoder() {} - -var ERROR_PACKET = exports.ERROR + '"encode error"'; - -/** - * Encode a packet as a single string if non-binary, or as a - * buffer sequence, depending on packet type. - * - * @param {Object} obj - packet object - * @param {Function} callback - function to handle encodings (likely engine.write) - * @return Calls callback with Array of encodings - * @api public - */ - -Encoder.prototype.encode = function(obj, callback){ - debug('encoding packet %j', obj); - - if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { - encodeAsBinary(obj, callback); - } else { - var encoding = encodeAsString(obj); - callback([encoding]); - } -}; - -/** - * Encode packet as string. - * - * @param {Object} packet - * @return {String} encoded - * @api private - */ - -function encodeAsString(obj) { - - // first is type - var str = '' + obj.type; - - // attachments if we have them - if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { - str += obj.attachments + '-'; - } - - // if we have a namespace other than `/` - // we append it followed by a comma `,` - if (obj.nsp && '/' !== obj.nsp) { - str += obj.nsp + ','; - } - - // immediately followed by the id - if (null != obj.id) { - str += obj.id; - } - - // json data - if (null != obj.data) { - var payload = tryStringify(obj.data); - if (payload !== false) { - str += payload; - } else { - return ERROR_PACKET; - } - } - - debug('encoded %j as %s', obj, str); - return str; -} - -function tryStringify(str) { - try { - return JSON.stringify(str); - } catch(e){ - return false; - } -} - -/** - * Encode packet as 'buffer sequence' by removing blobs, and - * deconstructing packet into object with placeholders and - * a list of buffers. - * - * @param {Object} packet - * @return {Buffer} encoded - * @api private - */ - -function encodeAsBinary(obj, callback) { - - function writeEncoding(bloblessData) { - var deconstruction = binary.deconstructPacket(bloblessData); - var pack = encodeAsString(deconstruction.packet); - var buffers = deconstruction.buffers; - - buffers.unshift(pack); // add packet info to beginning of data list - callback(buffers); // write all the buffers - } - - binary.removeBlobs(obj, writeEncoding); -} - -/** - * A socket.io Decoder instance - * - * @return {Object} decoder - * @api public - */ - -function Decoder() { - this.reconstructor = null; -} - -/** - * Mix in `Emitter` with Decoder. - */ - -Emitter(Decoder.prototype); - -/** - * Decodes an ecoded packet string into packet JSON. - * - * @param {String} obj - encoded packet - * @return {Object} packet - * @api public - */ - -Decoder.prototype.add = function(obj) { - var packet; - if (typeof obj === 'string') { - packet = decodeString(obj); - if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json - this.reconstructor = new BinaryReconstructor(packet); - - // no attachments, labeled binary but no binary data to follow - if (this.reconstructor.reconPack.attachments === 0) { - this.emit('decoded', packet); - } - } else { // non-binary full packet - this.emit('decoded', packet); - } - } - else if (isBuf(obj) || obj.base64) { // raw binary data - if (!this.reconstructor) { - throw new Error('got binary data when not reconstructing a packet'); - } else { - packet = this.reconstructor.takeBinaryData(obj); - if (packet) { // received final buffer - this.reconstructor = null; - this.emit('decoded', packet); - } - } - } - else { - throw new Error('Unknown type: ' + obj); - } -}; - -/** - * Decode a packet String (JSON data) - * - * @param {String} str - * @return {Object} packet - * @api private - */ - -function decodeString(str) { - var i = 0; - // look up type - var p = { - type: Number(str.charAt(0)) - }; - - if (null == exports.types[p.type]) { - return error('unknown packet type ' + p.type); - } - - // look up attachments if type binary - if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) { - var buf = ''; - while (str.charAt(++i) !== '-') { - buf += str.charAt(i); - if (i == str.length) break; - } - if (buf != Number(buf) || str.charAt(i) !== '-') { - throw new Error('Illegal attachments'); - } - p.attachments = Number(buf); - } - - // look up namespace (if any) - if ('/' === str.charAt(i + 1)) { - p.nsp = ''; - while (++i) { - var c = str.charAt(i); - if (',' === c) break; - p.nsp += c; - if (i === str.length) break; - } - } else { - p.nsp = '/'; - } - - // look up id - var next = str.charAt(i + 1); - if ('' !== next && Number(next) == next) { - p.id = ''; - while (++i) { - var c = str.charAt(i); - if (null == c || Number(c) != c) { - --i; - break; - } - p.id += str.charAt(i); - if (i === str.length) break; - } - p.id = Number(p.id); - } - - // look up json data - if (str.charAt(++i)) { - var payload = tryParse(str.substr(i)); - var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload)); - if (isPayloadValid) { - p.data = payload; - } else { - return error('invalid payload'); - } - } - - debug('decoded %s as %j', str, p); - return p; -} - -function tryParse(str) { - try { - return JSON.parse(str); - } catch(e){ - return false; - } -} - -/** - * Deallocates a parser's resources - * - * @api public - */ - -Decoder.prototype.destroy = function() { - if (this.reconstructor) { - this.reconstructor.finishedReconstruction(); - } -}; - -/** - * A manager of a binary event's 'buffer sequence'. Should - * be constructed whenever a packet of type BINARY_EVENT is - * decoded. - * - * @param {Object} packet - * @return {BinaryReconstructor} initialized reconstructor - * @api private - */ - -function BinaryReconstructor(packet) { - this.reconPack = packet; - this.buffers = []; -} - -/** - * Method to be called when binary data received from connection - * after a BINARY_EVENT packet. - * - * @param {Buffer | ArrayBuffer} binData - the raw binary data received - * @return {null | Object} returns null if more binary data is expected or - * a reconstructed packet object if all buffers have been received. - * @api private - */ - -BinaryReconstructor.prototype.takeBinaryData = function(binData) { - this.buffers.push(binData); - if (this.buffers.length === this.reconPack.attachments) { // done with buffer list - var packet = binary.reconstructPacket(this.reconPack, this.buffers); - this.finishedReconstruction(); - return packet; - } - return null; -}; - -/** - * Cleans up binary packet reconstruction variables. - * - * @api private - */ - -BinaryReconstructor.prototype.finishedReconstruction = function() { - this.reconPack = null; - this.buffers = []; -}; - -function error(msg) { - return { - type: exports.ERROR, - data: 'parser error: ' + msg - }; -} - - -/***/ }), -/* 64 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {// browser shim for xmlhttprequest module - -var hasCORS = __webpack_require__(176); - -module.exports = function (opts) { - var xdomain = opts.xdomain; - - // scheme must be same when usign XDomainRequest - // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx - var xscheme = opts.xscheme; - - // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default. - // https://github.com/Automattic/engine.io-client/pull/217 - var enablesXDR = opts.enablesXDR; - - // XMLHttpRequest can be disabled on IE - try { - if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { - return new XMLHttpRequest(); - } - } catch (e) { } - - // Use XDomainRequest for IE8 if enablesXDR is true - // because loading bar keeps flashing when using jsonp-polling - // https://github.com/yujiosaka/socke.io-ie8-loading-example - try { - if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) { - return new XDomainRequest(); - } - } catch (e) { } - - if (!xdomain) { - try { - return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP'); - } catch (e) { } - } -}; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * Module dependencies. - */ - -var parser = __webpack_require__(25); -var Emitter = __webpack_require__(24); - -/** - * Module exports. - */ - -module.exports = Transport; - -/** - * Transport abstract constructor. - * - * @param {Object} options. - * @api private - */ - -function Transport (opts) { - this.path = opts.path; - this.hostname = opts.hostname; - this.port = opts.port; - this.secure = opts.secure; - this.query = opts.query; - this.timestampParam = opts.timestampParam; - this.timestampRequests = opts.timestampRequests; - this.readyState = ''; - this.agent = opts.agent || false; - this.socket = opts.socket; - this.enablesXDR = opts.enablesXDR; - - // SSL options for Node.js client - this.pfx = opts.pfx; - this.key = opts.key; - this.passphrase = opts.passphrase; - this.cert = opts.cert; - this.ca = opts.ca; - this.ciphers = opts.ciphers; - this.rejectUnauthorized = opts.rejectUnauthorized; - this.forceNode = opts.forceNode; - - // other options for Node.js client - this.extraHeaders = opts.extraHeaders; - this.localAddress = opts.localAddress; -} - -/** - * Mix in `Emitter`. - */ - -Emitter(Transport.prototype); - -/** - * Emits an error. - * - * @param {String} str - * @return {Transport} for chaining - * @api public - */ - -Transport.prototype.onError = function (msg, desc) { - var err = new Error(msg); - err.type = 'TransportError'; - err.description = desc; - this.emit('error', err); - return this; -}; - -/** - * Opens the transport. - * - * @api public - */ - -Transport.prototype.open = function () { - if ('closed' === this.readyState || '' === this.readyState) { - this.readyState = 'opening'; - this.doOpen(); - } - - return this; -}; - -/** - * Closes the transport. - * - * @api private - */ - -Transport.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.doClose(); - this.onClose(); - } - - return this; -}; - -/** - * Sends multiple packets. - * - * @param {Array} packets - * @api private - */ - -Transport.prototype.send = function (packets) { - if ('open' === this.readyState) { - this.write(packets); - } else { - throw new Error('Transport not open'); - } -}; - -/** - * Called upon open - * - * @api private - */ - -Transport.prototype.onOpen = function () { - this.readyState = 'open'; - this.writable = true; - this.emit('open'); -}; - -/** - * Called with data. - * - * @param {String} data - * @api private - */ - -Transport.prototype.onData = function (data) { - var packet = parser.decodePacket(data, this.socket.binaryType); - this.onPacket(packet); -}; - -/** - * Called with a decoded packet. - */ - -Transport.prototype.onPacket = function (packet) { - this.emit('packet', packet); -}; - -/** - * Called upon close. - * - * @api private - */ - -Transport.prototype.onClose = function () { - this.readyState = 'closed'; - this.emit('close'); -}; - - -/***/ }), -/* 67 */ +/* 58 */ /***/ (function(module, exports, __webpack_require__) { -exports.f = __webpack_require__(7); +exports.f = __webpack_require__(6); /***/ }), -/* 68 */ +/* 59 */ /***/ (function(module, exports, __webpack_require__) { -var global = __webpack_require__(6); -var core = __webpack_require__(5); -var LIBRARY = __webpack_require__(30); -var wksExt = __webpack_require__(67); -var defineProperty = __webpack_require__(13).f; +var global = __webpack_require__(5); +var core = __webpack_require__(4); +var LIBRARY = __webpack_require__(27); +var wksExt = __webpack_require__(58); +var defineProperty = __webpack_require__(12).f; module.exports = function (name) { var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); @@ -10377,21 +8697,21 @@ module.exports = function (name) { /***/ }), -/* 69 */ +/* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var commonApi = __webpack_require__(211); -var objectApi = __webpack_require__(253); +var commonApi = __webpack_require__(167); +var objectApi = __webpack_require__(212); var ecc = Object.assign({}, commonApi, objectApi); module.exports = ecc; /***/ }), -/* 70 */ +/* 61 */ /***/ (function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. @@ -10699,20 +9019,20 @@ function isUndefined(arg) { /***/ }), -/* 71 */ +/* 62 */ /***/ (function(module, exports, __webpack_require__) { -exports = module.exports = __webpack_require__(118); +exports = module.exports = __webpack_require__(97); exports.Stream = exports; exports.Readable = exports; -exports.Writable = __webpack_require__(72); -exports.Duplex = __webpack_require__(19); -exports.Transform = __webpack_require__(121); -exports.PassThrough = __webpack_require__(228); +exports.Writable = __webpack_require__(63); +exports.Duplex = __webpack_require__(17); +exports.Transform = __webpack_require__(100); +exports.PassThrough = __webpack_require__(187); /***/ }), -/* 72 */ +/* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10745,7 +9065,7 @@ exports.PassThrough = __webpack_require__(228); /**/ -var pna = __webpack_require__(49); +var pna = __webpack_require__(44); /**/ module.exports = Writable; @@ -10782,18 +9102,18 @@ var Duplex; Writable.WritableState = WritableState; /**/ -var util = __webpack_require__(34); +var util = __webpack_require__(31); util.inherits = __webpack_require__(1); /**/ /**/ var internalUtil = { - deprecate: __webpack_require__(227) + deprecate: __webpack_require__(186) }; /**/ /**/ -var Stream = __webpack_require__(119); +var Stream = __webpack_require__(98); /**/ /**/ @@ -10809,14 +9129,14 @@ function _isUint8Array(obj) { /**/ -var destroyImpl = __webpack_require__(120); +var destroyImpl = __webpack_require__(99); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(19); + Duplex = Duplex || __webpack_require__(17); options = options || {}; @@ -10966,7 +9286,7 @@ if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.protot } function Writable(options) { - Duplex = Duplex || __webpack_require__(19); + Duplex = Duplex || __webpack_require__(17); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` @@ -11403,10 +9723,10 @@ Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17), __webpack_require__(225).setImmediate, __webpack_require__(3))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22), __webpack_require__(184).setImmediate, __webpack_require__(7))) /***/ }), -/* 73 */ +/* 64 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -11708,13 +10028,13 @@ function simpleEnd(buf) { } /***/ }), -/* 74 */ +/* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) { var inherits = __webpack_require__(1) -var HashBase = __webpack_require__(124) +var HashBase = __webpack_require__(103) var ARRAY16 = new Array(16) @@ -11861,13 +10181,13 @@ module.exports = MD5 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) /***/ }), -/* 75 */ +/* 66 */ /***/ (function(module, exports, __webpack_require__) { -var Point = __webpack_require__(125) -var Curve = __webpack_require__(127) +var Point = __webpack_require__(104) +var Curve = __webpack_require__(106) -var getCurveByName = __webpack_require__(239) +var getCurveByName = __webpack_require__(198) module.exports = { Curve: Curve, @@ -11877,16 +10197,16 @@ module.exports = { /***/ }), -/* 76 */ +/* 67 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var inherits = __webpack_require__(1) -var MD5 = __webpack_require__(74) -var RIPEMD160 = __webpack_require__(128) -var sha = __webpack_require__(129) -var Base = __webpack_require__(18) +var MD5 = __webpack_require__(65) +var RIPEMD160 = __webpack_require__(107) +var sha = __webpack_require__(108) +var Base = __webpack_require__(16) function Hash (hash) { Base.call(this, 'digest') @@ -11914,7 +10234,7 @@ module.exports = function createHash (alg) { /***/ }), -/* 77 */ +/* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -11922,9 +10242,9 @@ module.exports = function createHash (alg) { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -var Types = __webpack_require__(254); -var Fcbuffer = __webpack_require__(258); -var assert = __webpack_require__(4); +var Types = __webpack_require__(213); +var Fcbuffer = __webpack_require__(218); +var assert = __webpack_require__(3); var create = Fcbuffer.create; @@ -12055,33 +10375,33 @@ module.exports.toBuffer = Fcbuffer.toBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) /***/ }), -/* 78 */ +/* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) { -var _slicedToArray2 = __webpack_require__(79); +var _slicedToArray2 = __webpack_require__(70); var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); -var _typeof2 = __webpack_require__(32); +var _typeof2 = __webpack_require__(29); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _require = __webpack_require__(69), +var _require = __webpack_require__(60), Signature = _require.Signature, PublicKey = _require.PublicKey; -var Fcbuffer = __webpack_require__(77); -var ByteBuffer = __webpack_require__(26); -var assert = __webpack_require__(4); +var Fcbuffer = __webpack_require__(68); +var ByteBuffer = __webpack_require__(23); +var assert = __webpack_require__(3); -var json = { schema: __webpack_require__(137) }; +var json = { schema: __webpack_require__(116) }; -var _require2 = __webpack_require__(138), +var _require2 = __webpack_require__(117), isName = _require2.isName, encodeName = _require2.encodeName, decodeName = _require2.decodeName, @@ -12859,7 +11179,7 @@ var actionDataOverride = function actionDataOverride(structLookup, forceActionDa /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) /***/ }), -/* 79 */ +/* 70 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -12867,11 +11187,11 @@ var actionDataOverride = function actionDataOverride(structLookup, forceActionDa exports.__esModule = true; -var _isIterable2 = __webpack_require__(273); +var _isIterable2 = __webpack_require__(233); var _isIterable3 = _interopRequireDefault(_isIterable2); -var _getIterator2 = __webpack_require__(276); +var _getIterator2 = __webpack_require__(236); var _getIterator3 = _interopRequireDefault(_getIterator2); @@ -12916,22 +11236,22 @@ exports.default = function () { }(); /***/ }), -/* 80 */ +/* 71 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = !__webpack_require__(15) && !__webpack_require__(21)(function () { - return Object.defineProperty(__webpack_require__(51)('div'), 'a', { get: function () { return 7; } }).a != 7; +module.exports = !__webpack_require__(14) && !__webpack_require__(19)(function () { + return Object.defineProperty(__webpack_require__(46)('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), -/* 81 */ +/* 72 */ /***/ (function(module, exports, __webpack_require__) { -var has = __webpack_require__(16); -var toIObject = __webpack_require__(22); -var arrayIndexOf = __webpack_require__(145)(false); -var IE_PROTO = __webpack_require__(55)('IE_PROTO'); +var has = __webpack_require__(15); +var toIObject = __webpack_require__(20); +var arrayIndexOf = __webpack_require__(124)(false); +var IE_PROTO = __webpack_require__(50)('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); @@ -12948,11 +11268,11 @@ module.exports = function (object, names) { /***/ }), -/* 82 */ +/* 73 */ /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings -var cof = __webpack_require__(29); +var cof = __webpack_require__(26); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); @@ -12960,11 +11280,11 @@ module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { /***/ }), -/* 83 */ +/* 74 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength -var toInteger = __webpack_require__(54); +var toInteger = __webpack_require__(49); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 @@ -12972,26 +11292,26 @@ module.exports = function (it) { /***/ }), -/* 84 */ +/* 75 */ /***/ (function(module, exports) { /***/ }), -/* 85 */ +/* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var LIBRARY = __webpack_require__(30); -var $export = __webpack_require__(11); -var redefine = __webpack_require__(86); -var hide = __webpack_require__(12); -var Iterators = __webpack_require__(23); -var $iterCreate = __webpack_require__(149); -var setToStringTag = __webpack_require__(44); -var getPrototypeOf = __webpack_require__(151); -var ITERATOR = __webpack_require__(7)('iterator'); +var LIBRARY = __webpack_require__(27); +var $export = __webpack_require__(10); +var redefine = __webpack_require__(77); +var hide = __webpack_require__(11); +var Iterators = __webpack_require__(21); +var $iterCreate = __webpack_require__(128); +var setToStringTag = __webpack_require__(41); +var getPrototypeOf = __webpack_require__(130); +var ITERATOR = __webpack_require__(6)('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; @@ -13054,34 +11374,34 @@ module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE /***/ }), -/* 86 */ +/* 77 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(12); +module.exports = __webpack_require__(11); /***/ }), -/* 87 */ +/* 78 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(8); -var dPs = __webpack_require__(150); -var enumBugKeys = __webpack_require__(57); -var IE_PROTO = __webpack_require__(55)('IE_PROTO'); +var dPs = __webpack_require__(129); +var enumBugKeys = __webpack_require__(52); +var IE_PROTO = __webpack_require__(50)('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(51)('iframe'); + var iframe = __webpack_require__(46)('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; - __webpack_require__(88).appendChild(iframe); + __webpack_require__(79).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); @@ -13108,21 +11428,21 @@ module.exports = Object.create || function create(O, Properties) { /***/ }), -/* 88 */ +/* 79 */ /***/ (function(module, exports, __webpack_require__) { -var document = __webpack_require__(6).document; +var document = __webpack_require__(5).document; module.exports = document && document.documentElement; /***/ }), -/* 89 */ +/* 80 */ /***/ (function(module, exports, __webpack_require__) { -var classof = __webpack_require__(60); -var ITERATOR = __webpack_require__(7)('iterator'); -var Iterators = __webpack_require__(23); -module.exports = __webpack_require__(5).getIteratorMethod = function (it) { +var classof = __webpack_require__(55); +var ITERATOR = __webpack_require__(6)('iterator'); +var Iterators = __webpack_require__(21); +module.exports = __webpack_require__(4).getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; @@ -13130,13 +11450,13 @@ module.exports = __webpack_require__(5).getIteratorMethod = function (it) { /***/ }), -/* 90 */ +/* 81 */ /***/ (function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(8); -var aFunction = __webpack_require__(39); -var SPECIES = __webpack_require__(7)('species'); +var aFunction = __webpack_require__(36); +var SPECIES = __webpack_require__(6)('species'); module.exports = function (O, D) { var C = anObject(O).constructor; var S; @@ -13145,14 +11465,14 @@ module.exports = function (O, D) { /***/ }), -/* 91 */ +/* 82 */ /***/ (function(module, exports, __webpack_require__) { -var ctx = __webpack_require__(38); -var invoke = __webpack_require__(160); -var html = __webpack_require__(88); -var cel = __webpack_require__(51); -var global = __webpack_require__(6); +var ctx = __webpack_require__(35); +var invoke = __webpack_require__(139); +var html = __webpack_require__(79); +var cel = __webpack_require__(46); +var global = __webpack_require__(5); var process = global.process; var setTask = global.setImmediate; var clearTask = global.clearImmediate; @@ -13191,7 +11511,7 @@ if (!setTask || !clearTask) { delete queue[id]; }; // Node.js 0.8- - if (__webpack_require__(29)(process) == 'process') { + if (__webpack_require__(26)(process) == 'process') { defer = function (id) { process.nextTick(ctx(run, id, 1)); }; @@ -13235,7 +11555,7 @@ module.exports = { /***/ }), -/* 92 */ +/* 83 */ /***/ (function(module, exports) { module.exports = function (exec) { @@ -13248,12 +11568,12 @@ module.exports = function (exec) { /***/ }), -/* 93 */ +/* 84 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(8); -var isObject = __webpack_require__(14); -var newPromiseCapability = __webpack_require__(61); +var isObject = __webpack_require__(13); +var newPromiseCapability = __webpack_require__(56); module.exports = function (C, x) { anObject(C); @@ -13266,7 +11586,7 @@ module.exports = function (C, x) { /***/ }), -/* 94 */ +/* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -13276,27 +11596,27 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _assign = __webpack_require__(37); +var _assign = __webpack_require__(34); var _assign2 = _interopRequireDefault(_assign); -var _promise = __webpack_require__(31); +var _promise = __webpack_require__(28); var _promise2 = _interopRequireDefault(_promise); -var _socket = __webpack_require__(169); +var _stringify = __webpack_require__(86); -var _socket2 = _interopRequireDefault(_socket); +var _stringify2 = _interopRequireDefault(_stringify); -var _StorageService = __webpack_require__(192); +var _StorageService = __webpack_require__(148); var _StorageService2 = _interopRequireDefault(_StorageService); -var _getRandomValues = __webpack_require__(193); +var _getRandomValues = __webpack_require__(149); var _getRandomValues2 = _interopRequireDefault(_getRandomValues); -var _eosjs = __webpack_require__(196); +var _eosjs = __webpack_require__(152); var _eosjs2 = _interopRequireDefault(_eosjs); @@ -13345,11 +11665,15 @@ const getOrigin = () => { let appkey = _StorageService2.default.getAppKey(); if (!appkey) appkey = 'appkey:' + random(); +const send = (type = null, data = null) => { + if (type === null && data === null) socket.send('40/scatter');else socket.send('42/scatter,' + (0, _stringify2.default)([type, data])); +}; + let pairingPromise = null; const pair = (passthrough = false) => { return new _promise2.default((resolve, reject) => { pairingPromise = { resolve, reject }; - socket.emit('pair', { data: { appkey, origin: getOrigin(), passthrough }, plugin }); + send('pair', { data: { appkey, origin: getOrigin(), passthrough }, plugin }); }); }; @@ -13373,70 +11697,77 @@ class SocketService { reconnectOnAbnormalDisconnection(); }, this.timeout)), new _promise2.default((resolve, reject) => { - console.log('connecting to', host); - // socket = io.connect(`${host}/scatter`, { secure:true, reconnection: false, rejectUnauthorized : false, transports: ['websocket', 'polling', 'flashsocket'] }); - socket = new WebSocket(`ws://${host}/socket.io/?EIO=3&transport=websocket`); + socket.onclose = x => { + resolve(false); + }; + + socket.onerror = err => { + console.error('err', err); + resolve(false); + }; + socket.onopen = x => { - console.log('connected'); + send(); clearTimeout(reconnectionTimeout); connected = true; pair(true).then(() => { + console.log('then pair', connected); resolve(true); }); - // socket.send('42/scatter,' + JSON.stringify(['connected'])); }; socket.onmessage = msg => { - console.log('msg', msg); - // socket.send('42' + JSON.stringify(['hello', 'there'])); + // Handshaking/Upgrading + if (msg.data.indexOf('42/scatter') === -1) return false; + + // Real message + const [type, data] = JSON.parse(msg.data.replace('42/scatter,', '')); + + switch (type) { + case 'paired': + return msg_paired(data); + case 'rekey': + return msg_rekey(); + case 'api': + return msg_api(data); + } + }; + + const msg_paired = result => { + console.log('paired', result); + paired = result; + + if (paired) { + const savedKey = _StorageService2.default.getAppKey(); + const hashed = appkey.indexOf('appkey:') > -1 ? ecc.sha256(appkey) : appkey; + + if (!savedKey || savedKey !== hashed) { + _StorageService2.default.setAppKey(hashed); + appkey = _StorageService2.default.getAppKey(); + } + } + + pairingPromise.resolve(result); + }; + + const msg_rekey = () => { + appkey = 'appkey:' + random(); + send('rekeyed', { data: { appkey, origin: getOrigin() }, plugin }); + }; + + const msg_api = result => { + const openRequest = openRequests.find(x => x.id === result.id); + if (!openRequest) return; + if (typeof result.result === 'object' && result.result !== null && result.result.hasOwnProperty('isError')) openRequest.reject(result.result);else openRequest.resolve(result.result); }; - // - // socket.on('connected', () => { - // console.log('connected'); - // clearTimeout(reconnectionTimeout); - // connected = true; - // pair(true).then(() => { - // resolve(true); - // }) - // }); - // - // socket.on('paired', result => { - // paired = result; - // - // if(paired) { - // const savedKey = StorageService.getAppKey(); - // const hashed = appkey.indexOf('appkey:') > -1 ? ecc.sha256(appkey) : appkey; - // - // if (!savedKey || savedKey !== hashed) { - // StorageService.setAppKey(hashed); - // appkey = StorageService.getAppKey(); - // } - // } - // - // pairingPromise.resolve(result); - // }); - // - // socket.on('rekey', () => { - // appkey = 'appkey:'+random(); - // socket.emit('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin}); - // }); // // socket.on('event', event => { // console.log('event', event); // }); // - // socket.on('api', result => { - // const openRequest = openRequests.find(x => x.id === result.id); - // if(!openRequest) return; - // if(typeof result.result === 'object' - // && result.result !== null - // && result.result.hasOwnProperty('isError')) openRequest.reject(result.result); - // else openRequest.resolve(result.result); - // }); - // // socket.on('disconnect', () => { // console.log('Disconnected') // connected = false; @@ -13490,7 +11821,7 @@ class SocketService { if (request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) request.payload.origin = getOrigin(); openRequests.push((0, _assign2.default)(request, { resolve, reject })); - socket.emit('api', { data: request, plugin }); + send('api', { data: request, plugin }); }); }); } @@ -13499,2258 +11830,1713 @@ class SocketService { exports.default = SocketService; /***/ }), -/* 95 */ +/* 86 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(168), __esModule: true }; +module.exports = { "default": __webpack_require__(147), __esModule: true }; /***/ }), -/* 96 */ -/***/ (function(module, exports) { +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Parses an URI - * - * @author Steven Levithan (MIT license) - * @api private - */ - -var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; - -var parts = [ - 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' -]; - -module.exports = function parseuri(str) { - var src = str, - b = str.indexOf('['), - e = str.indexOf(']'); - - if (b != -1 && e != -1) { - str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); - } - - var m = re.exec(str || ''), - uri = {}, - i = 14; - - while (i--) { - uri[parts[i]] = m[i] || ''; - } - - if (b != -1 && e != -1) { - uri.source = src; - uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); - uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); - uri.ipv6uri = true; - } - - return uri; -}; +module.exports = __webpack_require__(153); /***/ }), -/* 97 */ +/* 88 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(global) { -module.exports = isBuf; - -var withNativeBuffer = typeof global.Buffer === 'function' && typeof global.Buffer.isBuffer === 'function'; -var withNativeArrayBuffer = typeof global.ArrayBuffer === 'function'; - -var isView = (function () { - if (withNativeArrayBuffer && typeof global.ArrayBuffer.isView === 'function') { - return global.ArrayBuffer.isView; - } else { - return function (obj) { return obj.buffer instanceof global.ArrayBuffer; }; - } -})(); - -/** - * Returns true if obj is a buffer or an arraybuffer. - * - * @api private - */ +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) +var $keys = __webpack_require__(72); +var hiddenKeys = __webpack_require__(52).concat('length', 'prototype'); -function isBuf(obj) { - return (withNativeBuffer && global.Buffer.isBuffer(obj)) || - (withNativeArrayBuffer && (obj instanceof global.ArrayBuffer || isView(obj))); -} +exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return $keys(O, hiddenKeys); +}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), -/* 98 */ +/* 89 */ /***/ (function(module, exports, __webpack_require__) { +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { -/** - * Module dependencies. - */ +var randomBytes = __webpack_require__(90); +var ByteBuffer = __webpack_require__(23); +var crypto = __webpack_require__(172); +var assert = __webpack_require__(3); +var PublicKey = __webpack_require__(32); +var PrivateKey = __webpack_require__(45); +var hash = __webpack_require__(18); -var eio = __webpack_require__(174); -var Socket = __webpack_require__(105); -var Emitter = __webpack_require__(24); -var parser = __webpack_require__(63); -var on = __webpack_require__(106); -var bind = __webpack_require__(107); -var debug = __webpack_require__(9)('socket.io-client:manager'); -var indexOf = __webpack_require__(104); -var Backoff = __webpack_require__(191); +var Long = ByteBuffer.Long; -/** - * IE6+ hasOwnProperty - */ +module.exports = { + encrypt: encrypt, + decrypt: decrypt + + /** + Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem + + @throws {Error|TypeError} - "Invalid Key, ..." + + @arg {PrivateKey} private_key - required and used for decryption + @arg {PublicKey} public_key - required and used to calcualte the shared secret + @arg {string} [nonce = uniqueNonce()] - assigned a random unique uint64 + + @return {object} + @property {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys. + @property {Buffer} message - Plain text message + @property {number} checksum - shared secret checksum + */ +};function encrypt(private_key, public_key, message) { + var nonce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : uniqueNonce(); -var has = Object.prototype.hasOwnProperty; + return crypt(private_key, public_key, nonce, message); +} /** - * Module exports - */ + Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem -module.exports = Manager; + @arg {PrivateKey} private_key - required and used for decryption + @arg {PublicKey} public_key - required and used to calcualte the shared secret + @arg {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys. + @arg {Buffer} message - Encrypted or plain text message + @arg {number} checksum - shared secret checksum -/** - * `Manager` constructor. - * - * @param {String} engine instance or engine uri/opts - * @param {Object} options - * @api public - */ + @throws {Error|TypeError} - "Invalid Key, ..." -function Manager (uri, opts) { - if (!(this instanceof Manager)) return new Manager(uri, opts); - if (uri && ('object' === typeof uri)) { - opts = uri; - uri = undefined; - } - opts = opts || {}; - - opts.path = opts.path || '/socket.io'; - this.nsps = {}; - this.subs = []; - this.opts = opts; - this.reconnection(opts.reconnection !== false); - this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); - this.reconnectionDelay(opts.reconnectionDelay || 1000); - this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); - this.randomizationFactor(opts.randomizationFactor || 0.5); - this.backoff = new Backoff({ - min: this.reconnectionDelay(), - max: this.reconnectionDelayMax(), - jitter: this.randomizationFactor() - }); - this.timeout(null == opts.timeout ? 20000 : opts.timeout); - this.readyState = 'closed'; - this.uri = uri; - this.connecting = []; - this.lastPing = null; - this.encoding = false; - this.packetBuffer = []; - var _parser = opts.parser || parser; - this.encoder = new _parser.Encoder(); - this.decoder = new _parser.Decoder(); - this.autoConnect = opts.autoConnect !== false; - if (this.autoConnect) this.open(); + @return {Buffer} - message +*/ +function decrypt(private_key, public_key, nonce, message, checksum) { + return crypt(private_key, public_key, nonce, message, checksum).message; } /** - * Propagate given event to sockets and emit on `this` - * - * @api private - */ + @arg {Buffer} message - Encrypted or plain text message (see checksum) + @arg {number} checksum - shared secret checksum (null to encrypt, non-null to decrypt) + @private +*/ +function crypt(private_key, public_key, nonce, message, checksum) { + private_key = PrivateKey(private_key); + if (!private_key) throw new TypeError('private_key is required'); -Manager.prototype.emitAll = function () { - this.emit.apply(this, arguments); - for (var nsp in this.nsps) { - if (has.call(this.nsps, nsp)) { - this.nsps[nsp].emit.apply(this.nsps[nsp], arguments); - } - } -}; + public_key = PublicKey(public_key); + if (!public_key) throw new TypeError('public_key is required'); -/** - * Update `socket.id` of all sockets - * - * @api private - */ + nonce = toLongObj(nonce); + if (!nonce) throw new TypeError('nonce is required'); -Manager.prototype.updateSocketIds = function () { - for (var nsp in this.nsps) { - if (has.call(this.nsps, nsp)) { - this.nsps[nsp].id = this.generateId(nsp); + if (!Buffer.isBuffer(message)) { + if (typeof message !== 'string') throw new TypeError('message should be buffer or string'); + message = new Buffer(message, 'binary'); } - } -}; - -/** - * generate `socket.id` for the given `nsp` - * - * @param {String} nsp - * @return {String} - * @api private - */ + if (checksum && typeof checksum !== 'number') throw new TypeError('checksum should be a number'); -Manager.prototype.generateId = function (nsp) { - return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id; -}; + var S = private_key.getSharedSecret(public_key); + var ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); + ebuf.writeUint64(nonce); + ebuf.append(S.toString('binary'), 'binary'); + ebuf = new Buffer(ebuf.copy(0, ebuf.offset).toBinary(), 'binary'); + var encryption_key = hash.sha512(ebuf); -/** - * Mix in `Emitter`. - */ + // D E B U G + // console.log('crypt', { + // priv_to_pub: private_key.toPublic().toString(), + // pub: public_key.toString(), + // nonce: nonce.toString(), + // message: message.length, + // checksum, + // S: S.toString('hex'), + // encryption_key: encryption_key.toString('hex'), + // }) -Emitter(Manager.prototype); + var iv = encryption_key.slice(32, 48); + var key = encryption_key.slice(0, 32); -/** - * Sets the `reconnection` config. - * - * @param {Boolean} true/false if it should automatically reconnect - * @return {Manager} self or value - * @api public - */ + // check is first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits. + var check = hash.sha256(encryption_key); + check = check.slice(0, 4); + var cbuf = ByteBuffer.fromBinary(check.toString('binary'), ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); + check = cbuf.readUint32(); -Manager.prototype.reconnection = function (v) { - if (!arguments.length) return this._reconnection; - this._reconnection = !!v; - return this; -}; + if (checksum) { + if (check !== checksum) throw new Error('Invalid key'); + message = cryptoJsDecrypt(message, key, iv); + } else { + message = cryptoJsEncrypt(message, key, iv); + } + return { nonce: nonce, message: message, checksum: check }; +} -/** - * Sets the reconnection attempts config. - * - * @param {Number} max reconnection attempts before giving up - * @return {Manager} self or value - * @api public - */ +/** This method does not use a checksum, the returned data must be validated some other way. -Manager.prototype.reconnectionAttempts = function (v) { - if (!arguments.length) return this._reconnectionAttempts; - this._reconnectionAttempts = v; - return this; -}; + @arg {string|Buffer} message - ciphertext binary format + @arg {string|Buffer} key - 256bit + @arg {string|Buffer} iv - 128bit -/** - * Sets the delay between reconnections. - * - * @param {Number} delay - * @return {Manager} self or value - * @api public - */ + @return {Buffer} +*/ +function cryptoJsDecrypt(message, key, iv) { + assert(message, "Missing cipher text"); + message = toBinaryBuffer(message); + var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); + // decipher.setAutoPadding(true) + message = Buffer.concat([decipher.update(message), decipher.final()]); + return message; +} -Manager.prototype.reconnectionDelay = function (v) { - if (!arguments.length) return this._reconnectionDelay; - this._reconnectionDelay = v; - this.backoff && this.backoff.setMin(v); - return this; -}; +/** This method does not use a checksum, the returned data must be validated some other way. + @arg {string|Buffer} message - plaintext binary format + @arg {string|Buffer} key - 256bit + @arg {string|Buffer} iv - 128bit -Manager.prototype.randomizationFactor = function (v) { - if (!arguments.length) return this._randomizationFactor; - this._randomizationFactor = v; - this.backoff && this.backoff.setJitter(v); - return this; -}; + @return {Buffer} +*/ +function cryptoJsEncrypt(message, key, iv) { + assert(message, "Missing plain text"); + message = toBinaryBuffer(message); + var cipher = crypto.createCipheriv('aes-256-cbc', key, iv); + // cipher.setAutoPadding(true) + message = Buffer.concat([cipher.update(message), cipher.final()]); + return message; +} -/** - * Sets the maximum delay between reconnections. - * - * @param {Number} delay - * @return {Manager} self or value - * @api public - */ +/** @return {string} unique 64 bit unsigned number string. Being time based, this is careful to never choose the same nonce twice. This value could be recorded in the blockchain for a long time. +*/ +function uniqueNonce() { + if (unique_nonce_entropy === null) { + var b = new Uint8Array(randomBytes(2)); + unique_nonce_entropy = parseInt(b[0] << 8 | b[1], 10); + } + var long = Long.fromNumber(Date.now()); + var entropy = ++unique_nonce_entropy % 0xFFFF; + // console.log('uniqueNonce date\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) + // console.log('uniqueNonce entropy\t', ByteBuffer.allocate(8).writeUint64(Long.fromNumber(entropy)).toHex(0)) + long = long.shiftLeft(16).or(Long.fromNumber(entropy)); + // console.log('uniqueNonce final\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) + return long.toString(); +} +var unique_nonce_entropy = null; +// for(let i=1; i < 10; i++) key.uniqueNonce() -Manager.prototype.reconnectionDelayMax = function (v) { - if (!arguments.length) return this._reconnectionDelayMax; - this._reconnectionDelayMax = v; - this.backoff && this.backoff.setMax(v); - return this; +var toLongObj = function toLongObj(o) { + return o ? Long.isLong(o) ? o : Long.fromString(o) : o; }; - -/** - * Sets the connection timeout. `false` to disable - * - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.timeout = function (v) { - if (!arguments.length) return this._timeout; - this._timeout = v; - return this; +var toBinaryBuffer = function toBinaryBuffer(o) { + return o ? Buffer.isBuffer(o) ? o : new Buffer(o, 'binary') : o; }; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) -/** - * Starts trying to reconnect if reconnection is enabled and we have not - * started reconnecting yet - * - * @api private - */ - -Manager.prototype.maybeReconnectOnOpen = function () { - // Only try to reconnect if it's the first time we're connecting - if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) { - // keeps reconnection from firing twice for the same reconnection loop - this.reconnect(); - } -}; +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Sets the current transport `socket`. - * - * @param {Function} optional, callback - * @return {Manager} self - * @api public - */ +"use strict"; +/* WEBPACK VAR INJECTION */(function(global, process) { -Manager.prototype.open = -Manager.prototype.connect = function (fn, opts) { - debug('readyState %s', this.readyState); - if (~this.readyState.indexOf('open')) return this; - - debug('opening %s', this.uri); - this.engine = eio(this.uri, this.opts); - var socket = this.engine; - var self = this; - this.readyState = 'opening'; - this.skipReconnect = false; - - // emit `open` - var openSub = on(socket, 'open', function () { - self.onopen(); - fn && fn(); - }); +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} - // emit `connect_error` - var errorSub = on(socket, 'error', function (data) { - debug('connect_error'); - self.cleanup(); - self.readyState = 'closed'; - self.emitAll('connect_error', data); - if (fn) { - var err = new Error('Connection error'); - err.data = data; - fn(err); - } else { - // Only do this if there is no fn to handle the error - self.maybeReconnectOnOpen(); - } - }); +var Buffer = __webpack_require__(0).Buffer +var crypto = global.crypto || global.msCrypto - // emit `connect_timeout` - if (false !== this._timeout) { - var timeout = this._timeout; - debug('connect attempt will timeout after %d', timeout); +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} - // set timer - var timer = setTimeout(function () { - debug('connect attempt timed out after %d', timeout); - openSub.destroy(); - socket.close(); - socket.emit('error', 'timeout'); - self.emitAll('connect_timeout', timeout); - }, timeout); +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > 65536) throw new Error('requested too many random bytes') + // in case browserify isn't using the Uint8Array version + var rawBytes = new global.Uint8Array(size) - this.subs.push({ - destroy: function () { - clearTimeout(timer); - } - }); + // This will not work in older browsers. + // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + if (size > 0) { // getRandomValues fails on IE if size == 0 + crypto.getRandomValues(rawBytes) } - this.subs.push(openSub); - this.subs.push(errorSub); - - return this; -}; - -/** - * Called upon transport open. - * - * @api private - */ - -Manager.prototype.onopen = function () { - debug('open'); - - // clear old subs - this.cleanup(); + // XXX: phantomjs doesn't like a buffer being passed here + var bytes = Buffer.from(rawBytes.buffer) - // mark as open - this.readyState = 'open'; - this.emit('open'); + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } - // add new subs - var socket = this.engine; - this.subs.push(on(socket, 'data', bind(this, 'ondata'))); - this.subs.push(on(socket, 'ping', bind(this, 'onping'))); - this.subs.push(on(socket, 'pong', bind(this, 'onpong'))); - this.subs.push(on(socket, 'error', bind(this, 'onerror'))); - this.subs.push(on(socket, 'close', bind(this, 'onclose'))); - this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); -}; + return bytes +} -/** - * Called upon a ping. - * - * @api private - */ +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), __webpack_require__(22))) -Manager.prototype.onping = function () { - this.lastPing = new Date(); - this.emitAll('ping'); -}; +/***/ }), +/* 91 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Called upon a packet. - * - * @api private - */ +var modeModules = { + ECB: __webpack_require__(174), + CBC: __webpack_require__(175), + CFB: __webpack_require__(176), + CFB8: __webpack_require__(177), + CFB1: __webpack_require__(178), + OFB: __webpack_require__(179), + CTR: __webpack_require__(92), + GCM: __webpack_require__(92) +} -Manager.prototype.onpong = function () { - this.emitAll('pong', new Date() - this.lastPing); -}; +var modes = __webpack_require__(94) -/** - * Called with data. - * - * @api private - */ +for (var key in modes) { + modes[key].module = modeModules[modes[key].mode] +} -Manager.prototype.ondata = function (data) { - this.decoder.add(data); -}; +module.exports = modes -/** - * Called when parser fully decodes a packet. - * - * @api private - */ -Manager.prototype.ondecoded = function (packet) { - this.emit('packet', packet); -}; +/***/ }), +/* 92 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Called upon socket error. - * - * @api private - */ +var xor = __webpack_require__(30) +var Buffer = __webpack_require__(0).Buffer +var incr32 = __webpack_require__(93) -Manager.prototype.onerror = function (err) { - debug('error', err); - this.emitAll('error', err); -}; +function getBlock (self) { + var out = self._cipher.encryptBlockRaw(self._prev) + incr32(self._prev) + return out +} -/** - * Creates a new socket for the given `nsp`. - * - * @return {Socket} - * @api public - */ +var blockSize = 16 +exports.encrypt = function (self, chunk) { + var chunkNum = Math.ceil(chunk.length / blockSize) + var start = self._cache.length + self._cache = Buffer.concat([ + self._cache, + Buffer.allocUnsafe(chunkNum * blockSize) + ]) + for (var i = 0; i < chunkNum; i++) { + var out = getBlock(self) + var offset = start + i * blockSize + self._cache.writeUInt32BE(out[0], offset + 0) + self._cache.writeUInt32BE(out[1], offset + 4) + self._cache.writeUInt32BE(out[2], offset + 8) + self._cache.writeUInt32BE(out[3], offset + 12) + } + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} -Manager.prototype.socket = function (nsp, opts) { - var socket = this.nsps[nsp]; - if (!socket) { - socket = new Socket(this, nsp, opts); - this.nsps[nsp] = socket; - var self = this; - socket.on('connecting', onConnecting); - socket.on('connect', function () { - socket.id = self.generateId(nsp); - }); - if (this.autoConnect) { - // manually call here since connecting event is fired before listening - onConnecting(); - } - } +/***/ }), +/* 93 */ +/***/ (function(module, exports) { - function onConnecting () { - if (!~indexOf(self.connecting, socket)) { - self.connecting.push(socket); +function incr32 (iv) { + var len = iv.length + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break } } +} +module.exports = incr32 - return socket; -}; - -/** - * Called upon a socket close. - * - * @param {Socket} socket - */ - -Manager.prototype.destroy = function (socket) { - var index = indexOf(this.connecting, socket); - if (~index) this.connecting.splice(index, 1); - if (this.connecting.length) return; - this.close(); -}; +/***/ }), +/* 94 */ +/***/ (function(module, exports) { -/** - * Writes a packet. - * - * @param {Object} packet - * @api private - */ +module.exports = {"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}} -Manager.prototype.packet = function (packet) { - debug('writing packet %j', packet); - var self = this; - if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query; +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { - if (!self.encoding) { - // encode, then write to engine with result - self.encoding = true; - this.encoder.encode(packet, function (encodedPackets) { - for (var i = 0; i < encodedPackets.length; i++) { - self.engine.write(encodedPackets[i], packet.options); - } - self.encoding = false; - self.processPacketQueue(); - }); - } else { // add packet to the queue - self.packetBuffer.push(packet); - } -}; +var aes = __webpack_require__(43) +var Buffer = __webpack_require__(0).Buffer +var Transform = __webpack_require__(16) +var inherits = __webpack_require__(1) +var GHASH = __webpack_require__(192) +var xor = __webpack_require__(30) +var incr32 = __webpack_require__(93) -/** - * If packet buffer is non-empty, begins encoding the - * next packet in line. - * - * @api private - */ +function xorTest (a, b) { + var out = 0 + if (a.length !== b.length) out++ -Manager.prototype.processPacketQueue = function () { - if (this.packetBuffer.length > 0 && !this.encoding) { - var pack = this.packetBuffer.shift(); - this.packet(pack); + var len = Math.min(a.length, b.length) + for (var i = 0; i < len; ++i) { + out += (a[i] ^ b[i]) } -}; - -/** - * Clean up transport subscriptions and packet buffer. - * - * @api private - */ -Manager.prototype.cleanup = function () { - debug('cleanup'); + return out +} - var subsLength = this.subs.length; - for (var i = 0; i < subsLength; i++) { - var sub = this.subs.shift(); - sub.destroy(); +function calcIv (self, iv, ck) { + if (iv.length === 12) { + self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) + return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) } - - this.packetBuffer = []; - this.encoding = false; - this.lastPing = null; - - this.decoder.destroy(); -}; - -/** - * Close the current socket. - * - * @api private - */ - -Manager.prototype.close = -Manager.prototype.disconnect = function () { - debug('disconnect'); - this.skipReconnect = true; - this.reconnecting = false; - if ('opening' === this.readyState) { - // `onclose` will not fire because - // an open event never happened - this.cleanup(); - } - this.backoff.reset(); - this.readyState = 'closed'; - if (this.engine) this.engine.close(); -}; - -/** - * Called upon engine close. - * - * @api private - */ - -Manager.prototype.onclose = function (reason) { - debug('onclose'); - - this.cleanup(); - this.backoff.reset(); - this.readyState = 'closed'; - this.emit('close', reason); - - if (this._reconnection && !this.skipReconnect) { - this.reconnect(); - } -}; - -/** - * Attempt a reconnection. - * - * @api private - */ - -Manager.prototype.reconnect = function () { - if (this.reconnecting || this.skipReconnect) return this; - - var self = this; - - if (this.backoff.attempts >= this._reconnectionAttempts) { - debug('reconnect failed'); - this.backoff.reset(); - this.emitAll('reconnect_failed'); - this.reconnecting = false; - } else { - var delay = this.backoff.duration(); - debug('will wait %dms before reconnect attempt', delay); - - this.reconnecting = true; - var timer = setTimeout(function () { - if (self.skipReconnect) return; - - debug('attempting reconnect'); - self.emitAll('reconnect_attempt', self.backoff.attempts); - self.emitAll('reconnecting', self.backoff.attempts); - - // check again for the case socket closed in above events - if (self.skipReconnect) return; - - self.open(function (err) { - if (err) { - debug('reconnect attempt error'); - self.reconnecting = false; - self.reconnect(); - self.emitAll('reconnect_error', err.data); - } else { - debug('reconnect success'); - self.onreconnect(); - } - }); - }, delay); - - this.subs.push({ - destroy: function () { - clearTimeout(timer); - } - }); + var ghash = new GHASH(ck) + var len = iv.length + var toPad = len % 16 + ghash.update(iv) + if (toPad) { + toPad = 16 - toPad + ghash.update(Buffer.alloc(toPad, 0)) } -}; - -/** - * Called upon successful reconnect. - * - * @api private - */ - -Manager.prototype.onreconnect = function () { - var attempt = this.backoff.attempts; - this.reconnecting = false; - this.backoff.reset(); - this.updateSocketIds(); - this.emitAll('reconnect', attempt); -}; - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies - */ - -var XMLHttpRequest = __webpack_require__(65); -var XHR = __webpack_require__(177); -var JSONP = __webpack_require__(187); -var websocket = __webpack_require__(188); + ghash.update(Buffer.alloc(8, 0)) + var ivBits = len * 8 + var tail = Buffer.alloc(8) + tail.writeUIntBE(ivBits, 0, 8) + ghash.update(tail) + self._finID = ghash.state + var out = Buffer.from(self._finID) + incr32(out) + return out +} +function StreamCipher (mode, key, iv, decrypt) { + Transform.call(this) -/** - * Export transports. - */ + var h = Buffer.alloc(4, 0) -exports.polling = polling; -exports.websocket = websocket; + this._cipher = new aes.AES(key) + var ck = this._cipher.encryptBlock(h) + this._ghash = new GHASH(ck) + iv = calcIv(this, iv, ck) -/** - * Polling transport polymorphic constructor. - * Decides on xhr vs jsonp based on feature detection. - * - * @api private - */ + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) + this._decrypt = decrypt + this._alen = 0 + this._len = 0 + this._mode = mode -function polling (opts) { - var xhr; - var xd = false; - var xs = false; - var jsonp = false !== opts.jsonp; + this._authTag = null + this._called = false +} - if (global.location) { - var isSSL = 'https:' === location.protocol; - var port = location.port; +inherits(StreamCipher, Transform) - // some user agents have empty `location.port` - if (!port) { - port = isSSL ? 443 : 80; +StreamCipher.prototype._update = function (chunk) { + if (!this._called && this._alen) { + var rump = 16 - (this._alen % 16) + if (rump < 16) { + rump = Buffer.alloc(rump, 0) + this._ghash.update(rump) } - - xd = opts.hostname !== location.hostname || port !== opts.port; - xs = opts.secure !== isSSL; } - opts.xdomain = xd; - opts.xscheme = xs; - xhr = new XMLHttpRequest(opts); - - if ('open' in xhr && !opts.forceJSONP) { - return new XHR(opts); + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) } else { - if (!jsonp) throw new Error('JSONP disabled'); - return new JSONP(opts); + this._ghash.update(out) } + this._len += chunk.length + return out } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { +StreamCipher.prototype._final = function () { + if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') -/** - * Module dependencies. - */ + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) + if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') -var Transport = __webpack_require__(66); -var parseqs = __webpack_require__(46); -var parser = __webpack_require__(25); -var inherit = __webpack_require__(47); -var yeast = __webpack_require__(103); -var debug = __webpack_require__(9)('engine.io-client:polling'); + this._authTag = tag + this._cipher.scrub() +} -/** - * Module exports. - */ +StreamCipher.prototype.getAuthTag = function getAuthTag () { + if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') -module.exports = Polling; + return this._authTag +} -/** - * Is XHR2 supported? - */ +StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { + if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') -var hasXHR2 = (function () { - var XMLHttpRequest = __webpack_require__(65); - var xhr = new XMLHttpRequest({ xdomain: false }); - return null != xhr.responseType; -})(); + this._authTag = tag +} -/** - * Polling interface. - * - * @param {Object} opts - * @api private - */ +StreamCipher.prototype.setAAD = function setAAD (buf) { + if (this._called) throw new Error('Attempting to set AAD in unsupported state') -function Polling (opts) { - var forceBase64 = (opts && opts.forceBase64); - if (!hasXHR2 || forceBase64) { - this.supportsBinary = false; - } - Transport.call(this, opts); + this._ghash.update(buf) + this._alen += buf.length } -/** - * Inherits from Transport. - */ +module.exports = StreamCipher -inherit(Polling, Transport); -/** - * Transport name. - */ +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { -Polling.prototype.name = 'polling'; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -/** - * Opens the socket (triggers polling). We write a PING message to determine - * when the transport is open. - * - * @api private - */ +module.exports = Stream; -Polling.prototype.doOpen = function () { - this.poll(); -}; +var EE = __webpack_require__(61).EventEmitter; +var inherits = __webpack_require__(1); -/** - * Pauses polling. - * - * @param {Function} callback upon buffers are flushed and transport is paused - * @api private - */ +inherits(Stream, EE); +Stream.Readable = __webpack_require__(62); +Stream.Writable = __webpack_require__(188); +Stream.Duplex = __webpack_require__(189); +Stream.Transform = __webpack_require__(190); +Stream.PassThrough = __webpack_require__(191); -Polling.prototype.pause = function (onPause) { - var self = this; +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; - this.readyState = 'pausing'; - function pause () { - debug('paused'); - self.readyState = 'paused'; - onPause(); - } - if (this.polling || !this.writable) { - var total = 0; +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. - if (this.polling) { - debug('we are currently polling - waiting to pause'); - total++; - this.once('pollComplete', function () { - debug('pre-pause polling complete'); - --total || pause(); - }); - } +function Stream() { + EE.call(this); +} - if (!this.writable) { - debug('we are currently writing - waiting to pause'); - total++; - this.once('drain', function () { - debug('pre-pause writing complete'); - --total || pause(); - }); +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } } - } else { - pause(); } -}; - -/** - * Starts polling cycle. - * - * @api public - */ - -Polling.prototype.poll = function () { - debug('polling'); - this.polling = true; - this.doPoll(); - this.emit('poll'); -}; - -/** - * Overloads onData to detect payloads. - * - * @api private - */ -Polling.prototype.onData = function (data) { - var self = this; - debug('polling got data %s', data); - var callback = function (packet, index, total) { - // if its the first message we consider the transport open - if ('opening' === self.readyState) { - self.onOpen(); - } + source.on('data', ondata); - // if its a close packet, we close the ongoing requests - if ('close' === packet.type) { - self.onClose(); - return false; + function ondrain() { + if (source.readable && source.resume) { + source.resume(); } + } - // otherwise bypass onData and handle the message - self.onPacket(packet); - }; + dest.on('drain', ondrain); - // decode payload - parser.decodePayload(data, this.socket.binaryType, callback); + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } - // if an event did not trigger closing - if ('closed' !== this.readyState) { - // if we got data we're not polling - this.polling = false; - this.emit('pollComplete'); + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - if ('open' === this.readyState) { - this.poll(); - } else { - debug('ignoring poll - transport state "%s"', this.readyState); - } + dest.end(); } -}; -/** - * For polling, send a close packet. - * - * @api private - */ -Polling.prototype.doClose = function () { - var self = this; + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - function close () { - debug('writing close packet'); - self.write([{ type: 'close' }]); + if (typeof dest.destroy === 'function') dest.destroy(); } - if ('open' === this.readyState) { - debug('transport open - closing'); - close(); - } else { - // in case we're trying to close while - // handshaking is in progress (GH-164) - debug('transport not open - deferring close'); - this.once('open', close); + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } } -}; - -/** - * Writes a packets payload. - * - * @param {Array} data packets - * @param {Function} drain callback - * @api private - */ -Polling.prototype.write = function (packets) { - var self = this; - this.writable = false; - var callbackfn = function () { - self.writable = true; - self.emit('drain'); - }; + source.on('error', onerror); + dest.on('error', onerror); - parser.encodePayload(packets, this.supportsBinary, function (data) { - self.doWrite(data, callbackfn); - }); -}; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); -/** - * Generates uri for connection. - * - * @api private - */ + source.removeListener('end', onend); + source.removeListener('close', onclose); -Polling.prototype.uri = function () { - var query = this.query || {}; - var schema = this.secure ? 'https' : 'http'; - var port = ''; + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - // cache busting is forced - if (false !== this.timestampRequests) { - query[this.timestampParam] = yeast(); - } + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - if (!this.supportsBinary && !query.sid) { - query.b64 = 1; + dest.removeListener('close', cleanup); } - query = parseqs.encode(query); + source.on('end', cleanup); + source.on('close', cleanup); - // avoid port if default for schema - if (this.port && (('https' === schema && Number(this.port) !== 443) || - ('http' === schema && Number(this.port) !== 80))) { - port = ':' + this.port; - } + dest.on('close', cleanup); - // prepend ? to query - if (query.length) { - query = '?' + query; - } + dest.emit('pipe', source); - var ipv6 = this.hostname.indexOf(':') !== -1; - return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; }; /***/ }), -/* 101 */ +/* 97 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(Buffer) {/* global Blob File */ +"use strict"; +/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -/* - * Module requirements. - */ -var isArray = __webpack_require__(64); -var toString = Object.prototype.toString; -var withNativeBlob = typeof Blob === 'function' || - typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]'; -var withNativeFile = typeof File === 'function' || - typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]'; +/**/ -/** - * Module exports. - */ +var pna = __webpack_require__(44); +/**/ -module.exports = hasBinary; +module.exports = Readable; -/** - * Checks for binary data. - * - * Supports Buffer, ArrayBuffer, Blob and File. - * - * @param {Object} anything - * @api public - */ +/**/ +var isArray = __webpack_require__(180); +/**/ -function hasBinary (obj) { - if (!obj || typeof obj !== 'object') { - return false; - } +/**/ +var Duplex; +/**/ - if (isArray(obj)) { - for (var i = 0, l = obj.length; i < l; i++) { - if (hasBinary(obj[i])) { - return true; - } - } - return false; - } +Readable.ReadableState = ReadableState; - if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) || - (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) || - (withNativeBlob && obj instanceof Blob) || - (withNativeFile && obj instanceof File) - ) { - return true; - } +/**/ +var EE = __webpack_require__(61).EventEmitter; - // see: https://github.com/Automattic/has-binary/pull/4 - if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) { - return hasBinary(obj.toJSON(), true); - } +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { - return true; - } - } +/**/ +var Stream = __webpack_require__(98); +/**/ - return false; +/**/ + +var Buffer = __webpack_require__(0).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) +/**/ -/***/ }), -/* 102 */ -/***/ (function(module, exports) { +/**/ +var util = __webpack_require__(31); +util.inherits = __webpack_require__(1); +/**/ -module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - if(!module.children) module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - get: function() { - return module.l; - } - }); - Object.defineProperty(module, "id", { - enumerable: true, - get: function() { - return module.i; - } - }); - module.webpackPolyfill = 1; - } - return module; -}; +/**/ +var debugUtil = __webpack_require__(181); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ +var BufferList = __webpack_require__(182); +var destroyImpl = __webpack_require__(99); +var StringDecoder; -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { +util.inherits(Readable, Stream); -"use strict"; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); -var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') - , length = 64 - , map = {} - , seed = 0 - , i = 0 - , prev; + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} -/** - * Return a string representing the specified number. - * - * @param {Number} num The number to convert. - * @returns {String} The string representation of the number. - * @api public - */ -function encode(num) { - var encoded = ''; +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(17); - do { - encoded = alphabet[num % length] + encoded; - num = Math.floor(num / length); - } while (num > 0); + options = options || {}; - return encoded; -} + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; -/** - * Return the integer value specified by the given string. - * - * @param {String} str The string to convert. - * @returns {Number} The integer value represented by the string. - * @api public - */ -function decode(str) { - var decoded = 0; + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - for (i = 0; i < str.length; i++) { - decoded = decoded * length + map[str.charAt(i)]; - } + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - return decoded; -} + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; -/** - * Yeast: A tiny growing id generator. - * - * @returns {String} A unique id. - * @api public - */ -function yeast() { - var now = encode(+new Date()); + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - if (now !== prev) return seed = 0, prev = now; - return now +'.'+ encode(seed++); -} + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); -// -// Map each character to its index. -// -for (; i < length; i++) map[alphabet[i]] = i; + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; -// -// Expose the `yeast`, `encode` and `decode` functions. -// -yeast.encode = encode; -yeast.decode = decode; -module.exports = yeast; + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + // has it been destroyed + this.destroyed = false; -/***/ }), -/* 104 */ -/***/ (function(module, exports) { + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; -var indexOf = [].indexOf; + // if true, a maybeReadMore has been scheduled + this.readingMore = false; -module.exports = function(arr, obj){ - if (indexOf) return arr.indexOf(obj); - for (var i = 0; i < arr.length; ++i) { - if (arr[i] === obj) return i; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(64).StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; } - return -1; -}; - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { +} +function Readable(options) { + Duplex = Duplex || __webpack_require__(17); -/** - * Module dependencies. - */ + if (!(this instanceof Readable)) return new Readable(options); -var parser = __webpack_require__(63); -var Emitter = __webpack_require__(24); -var toArray = __webpack_require__(190); -var on = __webpack_require__(106); -var bind = __webpack_require__(107); -var debug = __webpack_require__(9)('socket.io-client:socket'); -var parseqs = __webpack_require__(46); -var hasBin = __webpack_require__(101); + this._readableState = new ReadableState(options, this); -/** - * Module exports. - */ - -module.exports = exports = Socket; - -/** - * Internal events (blacklisted). - * These events can't be emitted by the user. - * - * @api private - */ - -var events = { - connect: 1, - connect_error: 1, - connect_timeout: 1, - connecting: 1, - disconnect: 1, - error: 1, - reconnect: 1, - reconnect_attempt: 1, - reconnect_failed: 1, - reconnect_error: 1, - reconnecting: 1, - ping: 1, - pong: 1 -}; - -/** - * Shortcut to `Emitter#emit`. - */ - -var emit = Emitter.prototype.emit; + // legacy + this.readable = true; -/** - * `Socket` constructor. - * - * @api public - */ + if (options) { + if (typeof options.read === 'function') this._read = options.read; -function Socket (io, nsp, opts) { - this.io = io; - this.nsp = nsp; - this.json = this; // compat - this.ids = 0; - this.acks = {}; - this.receiveBuffer = []; - this.sendBuffer = []; - this.connected = false; - this.disconnected = true; - this.flags = {}; - if (opts && opts.query) { - this.query = opts.query; + if (typeof options.destroy === 'function') this._destroy = options.destroy; } - if (this.io.autoConnect) this.open(); -} - -/** - * Mix in `Emitter`. - */ -Emitter(Socket.prototype); + Stream.call(this); +} -/** - * Subscribe to open, close and packet events - * - * @api private - */ +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } -Socket.prototype.subEvents = function () { - if (this.subs) return; + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); - var io = this.io; - this.subs = [ - on(io, 'open', bind(this, 'onopen')), - on(io, 'packet', bind(this, 'onpacket')), - on(io, 'close', bind(this, 'onclose')) - ]; +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); }; -/** - * "Opens" the socket. - * - * @api public - */ +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; -Socket.prototype.open = -Socket.prototype.connect = function () { - if (this.connected) return this; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } - this.subEvents(); - this.io.open(); // ensure open - if ('open' === this.io.readyState) this.onopen(); - this.emit('connecting'); - return this; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; -/** - * Sends a `message` event. - * - * @return {Socket} self - * @api public - */ - -Socket.prototype.send = function () { - var args = toArray(arguments); - args.unshift('message'); - this.emit.apply(this, args); - return this; +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); }; -/** - * Override `emit`. - * If the event is in `events`, it's emitted normally. - * - * @param {String} event name - * @return {Socket} self - * @api public - */ +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } -Socket.prototype.emit = function (ev) { - if (events.hasOwnProperty(ev)) { - emit.apply(this, arguments); - return this; + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } } - var args = toArray(arguments); - var packet = { - type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT, - data: args - }; + return needMoreData(state); +} - packet.options = {}; - packet.options.compress = !this.flags || false !== this.flags.compress; +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - // event ack callback - if ('function' === typeof args[args.length - 1]) { - debug('emitting packet with ack id %d', this.ids); - this.acks[this.ids] = args.pop(); - packet.id = this.ids++; + if (state.needReadable) emitReadable(stream); } + maybeReadMore(stream, state); +} - if (this.connected) { - this.packet(packet); - } else { - this.sendBuffer.push(packet); +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } + return er; +} - this.flags = {}; +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} - return this; +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; }; -/** - * Sends a packet. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.packet = function (packet) { - packet.nsp = this.nsp; - this.io.packet(packet); +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(64).StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; }; -/** - * Called upon engine `open`. - * - * @api private - */ - -Socket.prototype.onopen = function () { - debug('transport is open - connecting'); - - // write connect packet if necessary - if ('/' !== this.nsp) { - if (this.query) { - var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query; - debug('sending connect packet with query %s', query); - this.packet({type: parser.CONNECT, query: query}); - } else { - this.packet({type: parser.CONNECT}); - } +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } -}; - -/** - * Called upon engine `close`. - * - * @param {String} reason - * @api private - */ - -Socket.prototype.onclose = function (reason) { - debug('close (%s)', reason); - this.connected = false; - this.disconnected = true; - delete this.id; - this.emit('disconnect', reason); -}; - -/** - * Called with socket packet. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.onpacket = function (packet) { - var sameNamespace = packet.nsp === this.nsp; - var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/'; - - if (!sameNamespace && !rootNamespaceError) return; - - switch (packet.type) { - case parser.CONNECT: - this.onconnect(); - break; + return n; +} - case parser.EVENT: - this.onevent(packet); - break; +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} - case parser.BINARY_EVENT: - this.onevent(packet); - break; +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; - case parser.ACK: - this.onack(packet); - break; + if (n !== 0) state.emittedReadable = false; - case parser.BINARY_ACK: - this.onack(packet); - break; + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } - case parser.DISCONNECT: - this.ondisconnect(); - break; + n = howMuchToRead(n, state); - case parser.ERROR: - this.emit('error', packet.data); - break; + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; } -}; -/** - * Called upon a server event. - * - * @param {Object} packet - * @api private - */ + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. -Socket.prototype.onevent = function (packet) { - var args = packet.data || []; - debug('emitting event %j', args); + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); - if (null != packet.id) { - debug('attaching ack callback to event'); - args.push(this.ack(packet.id)); + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); } - if (this.connected) { - emit.apply(this, args); - } else { - this.receiveBuffer.push(args); + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); } -}; - -/** - * Produces an ack callback to emit with an event. - * - * @api private - */ - -Socket.prototype.ack = function (id) { - var self = this; - var sent = false; - return function () { - // prevent double callbacks - if (sent) return; - sent = true; - var args = toArray(arguments); - debug('sending ack %j', args); - - self.packet({ - type: hasBin(args) ? parser.BINARY_ACK : parser.ACK, - id: id, - data: args - }); - }; -}; -/** - * Called upon a server acknowlegement. - * - * @param {Object} packet - * @api private - */ + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; -Socket.prototype.onack = function (packet) { - var ack = this.acks[packet.id]; - if ('function' === typeof ack) { - debug('calling ack %s with %j', packet.id, packet.data); - ack.apply(this, packet.data); - delete this.acks[packet.id]; + if (ret === null) { + state.needReadable = true; + n = 0; } else { - debug('bad ack %s', packet.id); + state.length -= n; } -}; - -/** - * Called upon server connect. - * - * @api private - */ -Socket.prototype.onconnect = function () { - this.connected = true; - this.disconnected = false; - this.emit('connect'); - this.emitBuffered(); -}; - -/** - * Emit buffered events (received and emitted). - * - * @api private - */ - -Socket.prototype.emitBuffered = function () { - var i; - for (i = 0; i < this.receiveBuffer.length; i++) { - emit.apply(this, this.receiveBuffer[i]); - } - this.receiveBuffer = []; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - for (i = 0; i < this.sendBuffer.length; i++) { - this.packet(this.sendBuffer[i]); + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); } - this.sendBuffer = []; -}; -/** - * Called upon server disconnect. - * - * @api private - */ + if (ret !== null) this.emit('data', ret); -Socket.prototype.ondisconnect = function () { - debug('server disconnect (%s)', this.nsp); - this.destroy(); - this.onclose('io server disconnect'); + return ret; }; -/** - * Called upon forced client/server side disconnections, - * this method ensures the manager stops tracking us and - * that reconnections don't get triggered for this. - * - * @api private. - */ - -Socket.prototype.destroy = function () { - if (this.subs) { - // clean subscriptions to avoid reconnections - for (var i = 0; i < this.subs.length; i++) { - this.subs[i].destroy(); +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } - this.subs = null; } + state.ended = true; - this.io.destroy(this); -}; - -/** - * Disconnects the socket manually. - * - * @return {Socket} self - * @api public - */ + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} -Socket.prototype.close = -Socket.prototype.disconnect = function () { - if (this.connected) { - debug('performing disconnect (%s)', this.nsp); - this.packet({ type: parser.DISCONNECT }); +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } +} - // remove socket from pool - this.destroy(); +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} - if (this.connected) { - // fire events - this.onclose('io client disconnect'); +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); } - return this; -}; - -/** - * Sets the compress flag. - * - * @param {Boolean} if `true`, compresses the sending data - * @return {Socket} self - * @api public - */ - -Socket.prototype.compress = function (compress) { - this.flags.compress = compress; - return this; -}; +} -/** - * Sets the binary flag - * - * @param {Boolean} whether the emitted data contains binary - * @return {Socket} self - * @api public - */ +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} -Socket.prototype.binary = function (binary) { - this.flags.binary = binary; - return this; +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); }; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; -/***/ }), -/* 106 */ -/***/ (function(module, exports) { - - -/** - * Module exports. - */ + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); -module.exports = on; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; -/** - * Helper for subscriptions. - * - * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` - * @param {String} event name - * @param {Function} callback - * @api public - */ + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); -function on (obj, ev, fn) { - obj.on(ev, fn); - return { - destroy: function () { - obj.removeListener(ev, fn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } - }; -} + } + function onend() { + debug('onend'); + dest.end(); + } -/***/ }), -/* 107 */ -/***/ (function(module, exports) { + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); -/** - * Slice reference. - */ + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); -var slice = [].slice; + cleanedUp = true; -/** - * Bind `obj` to `fn`. - * - * @param {Object} obj - * @param {Function|String} fn or string - * @return {Function} - * @api public - */ + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } -module.exports = function(obj, fn){ - if ('string' == typeof fn) fn = obj[fn]; - if ('function' != typeof fn) throw new Error('bind() requires a function'); - var args = slice.call(arguments, 2); - return function(){ - return fn.apply(obj, args.concat(slice.call(arguments))); + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } } -}; + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); -module.exports = __webpack_require__(197); + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { + // tell the dest that it's being piped to + dest.emit('pipe', src); -// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) -var $keys = __webpack_require__(81); -var hiddenKeys = __webpack_require__(57).concat('length', 'prototype'); + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } -exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return $keys(O, hiddenKeys); + return dest; }; - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var randomBytes = __webpack_require__(111); -var ByteBuffer = __webpack_require__(26); -var crypto = __webpack_require__(213); -var assert = __webpack_require__(4); -var PublicKey = __webpack_require__(35); -var PrivateKey = __webpack_require__(50); -var hash = __webpack_require__(20); - -var Long = ByteBuffer.Long; - -module.exports = { - encrypt: encrypt, - decrypt: decrypt - - /** - Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem - - @throws {Error|TypeError} - "Invalid Key, ..." - - @arg {PrivateKey} private_key - required and used for decryption - @arg {PublicKey} public_key - required and used to calcualte the shared secret - @arg {string} [nonce = uniqueNonce()] - assigned a random unique uint64 - - @return {object} - @property {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys. - @property {Buffer} message - Plain text message - @property {number} checksum - shared secret checksum - */ -};function encrypt(private_key, public_key, message) { - var nonce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : uniqueNonce(); - - return crypt(private_key, public_key, nonce, message); -} - -/** - Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem - - @arg {PrivateKey} private_key - required and used for decryption - @arg {PublicKey} public_key - required and used to calcualte the shared secret - @arg {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys. - @arg {Buffer} message - Encrypted or plain text message - @arg {number} checksum - shared secret checksum - - @throws {Error|TypeError} - "Invalid Key, ..." - - @return {Buffer} - message -*/ -function decrypt(private_key, public_key, nonce, message, checksum) { - return crypt(private_key, public_key, nonce, message, checksum).message; +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; } -/** - @arg {Buffer} message - Encrypted or plain text message (see checksum) - @arg {number} checksum - shared secret checksum (null to encrypt, non-null to decrypt) - @private -*/ -function crypt(private_key, public_key, nonce, message, checksum) { - private_key = PrivateKey(private_key); - if (!private_key) throw new TypeError('private_key is required'); - - public_key = PublicKey(public_key); - if (!public_key) throw new TypeError('public_key is required'); +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; - nonce = toLongObj(nonce); - if (!nonce) throw new TypeError('nonce is required'); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - if (!Buffer.isBuffer(message)) { - if (typeof message !== 'string') throw new TypeError('message should be buffer or string'); - message = new Buffer(message, 'binary'); - } - if (checksum && typeof checksum !== 'number') throw new TypeError('checksum should be a number'); + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - var S = private_key.getSharedSecret(public_key); - var ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); - ebuf.writeUint64(nonce); - ebuf.append(S.toString('binary'), 'binary'); - ebuf = new Buffer(ebuf.copy(0, ebuf.offset).toBinary(), 'binary'); - var encryption_key = hash.sha512(ebuf); + if (!dest) dest = state.pipes; - // D E B U G - // console.log('crypt', { - // priv_to_pub: private_key.toPublic().toString(), - // pub: public_key.toString(), - // nonce: nonce.toString(), - // message: message.length, - // checksum, - // S: S.toString('hex'), - // encryption_key: encryption_key.toString('hex'), - // }) + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } - var iv = encryption_key.slice(32, 48); - var key = encryption_key.slice(0, 32); + // slow case. multiple pipe destinations. - // check is first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits. - var check = hash.sha256(encryption_key); - check = check.slice(0, 4); - var cbuf = ByteBuffer.fromBinary(check.toString('binary'), ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); - check = cbuf.readUint32(); + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - if (checksum) { - if (check !== checksum) throw new Error('Invalid key'); - message = cryptoJsDecrypt(message, key, iv); - } else { - message = cryptoJsEncrypt(message, key, iv); - } - return { nonce: nonce, message: message, checksum: check }; -} + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } -/** This method does not use a checksum, the returned data must be validated some other way. + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; - @arg {string|Buffer} message - ciphertext binary format - @arg {string|Buffer} key - 256bit - @arg {string|Buffer} iv - 128bit + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - @return {Buffer} -*/ -function cryptoJsDecrypt(message, key, iv) { - assert(message, "Missing cipher text"); - message = toBinaryBuffer(message); - var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); - // decipher.setAutoPadding(true) - message = Buffer.concat([decipher.update(message), decipher.final()]); - return message; -} + dest.emit('unpipe', this, unpipeInfo); -/** This method does not use a checksum, the returned data must be validated some other way. - @arg {string|Buffer} message - plaintext binary format - @arg {string|Buffer} key - 256bit - @arg {string|Buffer} iv - 128bit + return this; +}; - @return {Buffer} -*/ -function cryptoJsEncrypt(message, key, iv) { - assert(message, "Missing plain text"); - message = toBinaryBuffer(message); - var cipher = crypto.createCipheriv('aes-256-cbc', key, iv); - // cipher.setAutoPadding(true) - message = Buffer.concat([cipher.update(message), cipher.final()]); - return message; -} +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); -/** @return {string} unique 64 bit unsigned number string. Being time based, this is careful to never choose the same nonce twice. This value could be recorded in the blockchain for a long time. -*/ -function uniqueNonce() { - if (unique_nonce_entropy === null) { - var b = new Uint8Array(randomBytes(2)); - unique_nonce_entropy = parseInt(b[0] << 8 | b[1], 10); + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } } - var long = Long.fromNumber(Date.now()); - var entropy = ++unique_nonce_entropy % 0xFFFF; - // console.log('uniqueNonce date\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) - // console.log('uniqueNonce entropy\t', ByteBuffer.allocate(8).writeUint64(Long.fromNumber(entropy)).toHex(0)) - long = long.shiftLeft(16).or(Long.fromNumber(entropy)); - // console.log('uniqueNonce final\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) - return long.toString(); -} -var unique_nonce_entropy = null; -// for(let i=1; i < 10; i++) key.uniqueNonce() + } -var toLongObj = function toLongObj(o) { - return o ? Long.isLong(o) ? o : Long.fromString(o) : o; -}; -var toBinaryBuffer = function toBinaryBuffer(o) { - return o ? Buffer.isBuffer(o) ? o : new Buffer(o, 'binary') : o; + return res; }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global, process) { +Readable.prototype.addListener = Readable.prototype.on; -function oldBrowser () { - throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); } -var Buffer = __webpack_require__(0).Buffer -var crypto = global.crypto || global.msCrypto +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; -if (crypto && crypto.getRandomValues) { - module.exports = randomBytes -} else { - module.exports = oldBrowser +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } } -function randomBytes (size, cb) { - // phantomjs needs to throw - if (size > 65536) throw new Error('requested too many random bytes') - // in case browserify isn't using the Uint8Array version - var rawBytes = new global.Uint8Array(size) - - // This will not work in older browsers. - // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues - if (size > 0) { // getRandomValues fails on IE if size == 0 - crypto.getRandomValues(rawBytes) +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); } - // XXX: phantomjs doesn't like a buffer being passed here - var bytes = Buffer.from(rawBytes.buffer) + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} - if (typeof cb === 'function') { - return process.nextTick(function () { - cb(null, bytes) - }) +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); } + return this; +}; - return bytes +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(17))) - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - -var modeModules = { - ECB: __webpack_require__(215), - CBC: __webpack_require__(216), - CFB: __webpack_require__(217), - CFB8: __webpack_require__(218), - CFB1: __webpack_require__(219), - OFB: __webpack_require__(220), - CTR: __webpack_require__(113), - GCM: __webpack_require__(113) -} +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; -var modes = __webpack_require__(115) + var state = this._readableState; + var paused = false; -for (var key in modes) { - modes[key].module = modeModules[modes[key].mode] -} + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } -module.exports = modes + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; -var xor = __webpack_require__(33) -var Buffer = __webpack_require__(0).Buffer -var incr32 = __webpack_require__(114) + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); -function getBlock (self) { - var out = self._cipher.encryptBlockRaw(self._prev) - incr32(self._prev) - return out -} + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } -var blockSize = 16 -exports.encrypt = function (self, chunk) { - var chunkNum = Math.ceil(chunk.length / blockSize) - var start = self._cache.length - self._cache = Buffer.concat([ - self._cache, - Buffer.allocUnsafe(chunkNum * blockSize) - ]) - for (var i = 0; i < chunkNum; i++) { - var out = getBlock(self) - var offset = start + i * blockSize - self._cache.writeUInt32BE(out[0], offset + 0) - self._cache.writeUInt32BE(out[1], offset + 4) - self._cache.writeUInt32BE(out[2], offset + 8) - self._cache.writeUInt32BE(out[3], offset + 12) + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } - var pad = self._cache.slice(0, chunk.length) - self._cache = self._cache.slice(chunk.length) - return xor(chunk, pad) -} + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; -/***/ }), -/* 114 */ -/***/ (function(module, exports) { + return this; +}; -function incr32 (iv) { - var len = iv.length - var item - while (len--) { - item = iv.readUInt8(len) - if (item === 255) { - iv.writeUInt8(0, len) - } else { - item++ - iv.writeUInt8(item, len) - break - } +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; } -} -module.exports = incr32 - +}); -/***/ }), -/* 115 */ -/***/ (function(module, exports) { +// exposed for testing purposes only. +Readable._fromList = fromList; -module.exports = {"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}} +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } -var aes = __webpack_require__(48) -var Buffer = __webpack_require__(0).Buffer -var Transform = __webpack_require__(18) -var inherits = __webpack_require__(1) -var GHASH = __webpack_require__(233) -var xor = __webpack_require__(33) -var incr32 = __webpack_require__(114) + return ret; +} -function xorTest (a, b) { - var out = 0 - if (a.length !== b.length) out++ - - var len = Math.min(a.length, b.length) - for (var i = 0; i < len; ++i) { - out += (a[i] ^ b[i]) +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } - - return out + return ret; } -function calcIv (self, iv, ck) { - if (iv.length === 12) { - self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) - return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) - } - var ghash = new GHASH(ck) - var len = iv.length - var toPad = len % 16 - ghash.update(iv) - if (toPad) { - toPad = 16 - toPad - ghash.update(Buffer.alloc(toPad, 0)) +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; } - ghash.update(Buffer.alloc(8, 0)) - var ivBits = len * 8 - var tail = Buffer.alloc(8) - tail.writeUIntBE(ivBits, 0, 8) - ghash.update(tail) - self._finID = ghash.state - var out = Buffer.from(self._finID) - incr32(out) - return out -} -function StreamCipher (mode, key, iv, decrypt) { - Transform.call(this) - - var h = Buffer.alloc(4, 0) - - this._cipher = new aes.AES(key) - var ck = this._cipher.encryptBlock(h) - this._ghash = new GHASH(ck) - iv = calcIv(this, iv, ck) - - this._prev = Buffer.from(iv) - this._cache = Buffer.allocUnsafe(0) - this._secCache = Buffer.allocUnsafe(0) - this._decrypt = decrypt - this._alen = 0 - this._len = 0 - this._mode = mode - - this._authTag = null - this._called = false + list.length -= c; + return ret; } -inherits(StreamCipher, Transform) - -StreamCipher.prototype._update = function (chunk) { - if (!this._called && this._alen) { - var rump = 16 - (this._alen % 16) - if (rump < 16) { - rump = Buffer.alloc(rump, 0) - this._ghash.update(rump) +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; } + ++c; } - - this._called = true - var out = this._mode.encrypt(this, chunk) - if (this._decrypt) { - this._ghash.update(chunk) - } else { - this._ghash.update(out) - } - this._len += chunk.length - return out + list.length -= c; + return ret; } -StreamCipher.prototype._final = function () { - if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') - - var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) - if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') - - this._authTag = tag - this._cipher.scrub() -} +function endReadable(stream) { + var state = stream._readableState; -StreamCipher.prototype.getAuthTag = function getAuthTag () { - if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - return this._authTag + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } } -StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { - if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') - - this._authTag = tag +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } } -StreamCipher.prototype.setAAD = function setAAD (buf) { - if (this._called) throw new Error('Attempting to set AAD in unsupported state') - - this._ghash.update(buf) - this._alen += buf.length +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; } - -module.exports = StreamCipher - +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), __webpack_require__(22))) /***/ }), -/* 117 */ +/* 98 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Stream; - -var EE = __webpack_require__(70).EventEmitter; -var inherits = __webpack_require__(1); - -inherits(Stream, EE); -Stream.Readable = __webpack_require__(71); -Stream.Writable = __webpack_require__(229); -Stream.Duplex = __webpack_require__(230); -Stream.Transform = __webpack_require__(231); -Stream.PassThrough = __webpack_require__(232); +module.exports = __webpack_require__(61).EventEmitter; -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. -function Stream() { - EE.call(this); -} +/**/ -Stream.prototype.pipe = function(dest, options) { - var source = this; +var pna = __webpack_require__(44); +/**/ - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; - source.on('data', ondata); + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - function ondrain() { - if (source.readable && source.resume) { - source.resume(); + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); } + return this; } - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - dest.end(); + if (this._readableState) { + this._readableState.destroyed = true; } - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; } - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + }); - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + return this; +} - dest.removeListener('close', cleanup); +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} - dest.emit('pipe', source); +function emitErrorNT(self, err) { + self.emit('error', err); +} - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; +module.exports = { + destroy: destroy, + undestroy: undestroy }; - /***/ }), -/* 118 */ +/* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. +// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the @@ -15771,9397 +13557,4920 @@ Stream.prototype.pipe = function(dest, options) { // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. -/**/ -var pna = __webpack_require__(49); -/**/ +module.exports = Transform; -module.exports = Readable; +var Duplex = __webpack_require__(17); /**/ -var isArray = __webpack_require__(221); +var util = __webpack_require__(31); +util.inherits = __webpack_require__(1); /**/ -/**/ -var Duplex; -/**/ +util.inherits(Transform, Duplex); -Readable.ReadableState = ReadableState; +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; -/**/ -var EE = __webpack_require__(70).EventEmitter; + var cb = ts.writecb; -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } -/**/ -var Stream = __webpack_require__(119); -/**/ + ts.writechunk = null; + ts.writecb = null; -/**/ + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); -var Buffer = __webpack_require__(0).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } } -/**/ +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); -/**/ -var util = __webpack_require__(34); -util.inherits = __webpack_require__(1); -/**/ + Duplex.call(this, options); -/**/ -var debugUtil = __webpack_require__(222); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; -var BufferList = __webpack_require__(223); -var destroyImpl = __webpack_require__(120); -var StringDecoder; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; -util.inherits(Readable, Stream); + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + if (typeof options.flush === 'function') this._flush = options.flush; + } - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); } -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(19); - - options = options || {}; +function prefinish() { + var _this = this; - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; - // has it been destroyed - this.destroyed = false; +function done(stream, er, data) { + if (er) return stream.emit('error', er); - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = __webpack_require__(73).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } + return stream.push(null); } -function Readable(options) { - Duplex = Duplex || __webpack_require__(19); +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { - if (!(this instanceof Readable)) return new Readable(options); +var aes = __webpack_require__(43) +var Buffer = __webpack_require__(0).Buffer +var Transform = __webpack_require__(16) +var inherits = __webpack_require__(1) - this._readableState = new ReadableState(options, this); +function StreamCipher (mode, key, iv, decrypt) { + Transform.call(this) - // legacy - this.readable = true; + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) + this._decrypt = decrypt + this._mode = mode +} - if (options) { - if (typeof options.read === 'function') this._read = options.read; +inherits(StreamCipher, Transform) - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } +StreamCipher.prototype._update = function (chunk) { + return this._mode.encrypt(this, chunk, this._decrypt) +} - Stream.call(this); +StreamCipher.prototype._final = function () { + this._cipher.scrub() } -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } +module.exports = StreamCipher - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; +var Buffer = __webpack_require__(0).Buffer +var MD5 = __webpack_require__(65) - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; +/* eslint-disable camelcase */ +function EVP_BytesToKey (password, salt, keyBits, ivLen) { + if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') + if (salt) { + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') + if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; + var keyLen = keyBits / 8 + var key = Buffer.alloc(keyLen) + var iv = Buffer.alloc(ivLen || 0) + var tmp = Buffer.alloc(0) -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; + while (keyLen > 0 || ivLen > 0) { + var hash = new MD5() + hash.update(tmp) + hash.update(password) + if (salt) hash.update(salt) + tmp = hash.digest() -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + var used = 0 - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; + if (keyLen > 0) { + var keyStart = key.length - keyLen + used = Math.min(keyLen, tmp.length) + tmp.copy(key, keyStart, 0, used) + keyLen -= used + } + + if (used < tmp.length && ivLen > 0) { + var ivStart = iv.length - ivLen + var length = Math.min(ivLen, tmp.length - used) + tmp.copy(iv, ivStart, used, used + length) + ivLen -= length } } - return needMoreData(state); + tmp.fill(0) + return { key: key, iv: iv } } -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); +module.exports = EVP_BytesToKey - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); +/***/ }), +/* 103 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var Buffer = __webpack_require__(0).Buffer +var Transform = __webpack_require__(96).Transform +var inherits = __webpack_require__(1) + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') } - return er; } -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} +function HashBase (blockSize) { + Transform.call(this) -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(73).StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; + this._finalized = false +} -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err } - return n; + + callback(error) } -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err } - return state.length; + + callback(error) } -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - if (n !== 0) state.emittedReadable = false; + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry } - n = howMuchToRead(n, state); + return this +} - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } + return digest +} - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } +module.exports = HashBase - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { - if (ret !== null) this.emit('data', ret); +var assert = __webpack_require__(3) +var Buffer = __webpack_require__(0).Buffer +var BigInteger = __webpack_require__(9) - return ret; -}; +var THREE = BigInteger.valueOf(3) -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; +function Point (curve, x, y, z) { + assert.notStrictEqual(z, undefined, 'Missing Z coordinate') - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} + this.curve = curve + this.x = x + this.y = y + this.z = z + this._zInv = null -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } + this.compressed = true } -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} +Object.defineProperty(Point.prototype, 'zInv', { + get: function () { + if (this._zInv === null) { + this._zInv = this.z.modInverse(this.curve.p) + } -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); + return this._zInv } -} +}) -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; +Object.defineProperty(Point.prototype, 'affineX', { + get: function () { + return this.x.multiply(this.zInv).mod(this.curve.p) } - state.readingMore = false; -} +}) -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; +Object.defineProperty(Point.prototype, 'affineY', { + get: function () { + return this.y.multiply(this.zInv).mod(this.curve.p) + } +}) -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; +Point.fromAffine = function (curve, x, y) { + return new Point(curve, x, y, BigInteger.ONE) +} - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); +Point.prototype.equals = function (other) { + if (other === this) return true + if (this.curve.isInfinity(this)) return this.curve.isInfinity(other) + if (this.curve.isInfinity(other)) return this.curve.isInfinity(this) - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + // u = Y2 * Z1 - Y1 * Z2 + var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p) - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + if (u.signum() !== 0) return false - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } + // v = X2 * Z1 - X1 * Z2 + var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p) - function onend() { - debug('onend'); - dest.end(); - } + return v.signum() === 0 +} - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); +Point.prototype.negate = function () { + var y = this.curve.p.subtract(this.y) - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); + return new Point(this.curve, this.x, y, this.z) +} - cleanedUp = true; +Point.prototype.add = function (b) { + if (this.curve.isInfinity(this)) return b + if (this.curve.isInfinity(b)) return this - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + var x1 = this.x + var y1 = this.y + var x2 = b.x + var y2 = b.y - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); + // u = Y2 * Z1 - Y1 * Z2 + var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p) + // v = X2 * Z1 - X1 * Z2 + var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p) + + if (v.signum() === 0) { + if (u.signum() === 0) { + return this.twice() // this == b, so double } - } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + return this.curve.infinity // this = -b, so infinity } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + var v2 = v.square() + var v3 = v2.multiply(v) + var x1v2 = x1.multiply(v2) + var zu2 = u.square().multiply(this.z) - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) + var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p) + // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 + var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p) + // z3 = v^3 * z1 * z2 + var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p) - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } + return new Point(this.curve, x3, y3, z3) +} - // tell the dest that it's being piped to - dest.emit('pipe', src); +Point.prototype.twice = function () { + if (this.curve.isInfinity(this)) return this + if (this.y.signum() === 0) return this.curve.infinity - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } + var x1 = this.x + var y1 = this.y - return dest; -}; + var y1z1 = y1.multiply(this.z).mod(this.curve.p) + var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p) + var a = this.curve.a -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} + // w = 3 * x1^2 + a * z1^2 + var w = x1.square().multiply(THREE) -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; + if (a.signum() !== 0) { + w = w.add(this.z.square().multiply(a)) + } - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + w = w.mod(this.curve.p) + // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) + var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p) + // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 + var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p) + // z3 = 8 * (y1 * z1)^3 + var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p) - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + return new Point(this.curve, x3, y3, z3) +} - if (!dest) dest = state.pipes; +// Simple NAF (Non-Adjacent Form) multiplication algorithm +// TODO: modularize the multiplication algorithm +Point.prototype.multiply = function (k) { + if (this.curve.isInfinity(this)) return this + if (k.signum() === 0) return this.curve.infinity - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } + var e = k + var h = e.multiply(THREE) - // slow case. multiple pipe destinations. + var neg = this.negate() + var R = this - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + for (var i = h.bitLength() - 2; i > 0; --i) { + var hBit = h.testBit(i) + var eBit = e.testBit(i) - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; - } + R = R.twice() - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; + if (hBit !== eBit) { + R = R.add(hBit ? this : neg) + } + } - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + return R +} - dest.emit('unpipe', this, unpipeInfo); +// Compute this*j + x*k (simultaneous multiplication) +Point.prototype.multiplyTwo = function (j, x, k) { + var i = Math.max(j.bitLength(), k.bitLength()) - 1 + var R = this.curve.infinity + var both = this.add(x) - return this; -}; + while (i >= 0) { + var jBit = j.testBit(i) + var kBit = k.testBit(i) -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); + R = R.twice() - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); + if (jBit) { + if (kBit) { + R = R.add(both) + } else { + R = R.add(this) } + } else if (kBit) { + R = R.add(x) } + --i } - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); + return R } -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; +Point.prototype.getEncoded = function (compressed) { + if (compressed == null) compressed = this.compressed + if (this.curve.isInfinity(this)) return Buffer.alloc(1, 0) // Infinity point encoded is simply '00' -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } -} + var x = this.affineX + var y = this.affineY + var byteLength = this.curve.pLength + var buffer -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } + // 0x02/0x03 | X + if (compressed) { + buffer = Buffer.allocUnsafe(1 + byteLength) + buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0) - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} + // 0x04 | X | Y + } else { + buffer = Buffer.allocUnsafe(1 + byteLength + byteLength) + buffer.writeUInt8(0x04, 0) -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); + y.toBuffer(byteLength).copy(buffer, 1 + byteLength) } - return this; -}; -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + x.toBuffer(byteLength).copy(buffer, 1) + + return buffer } -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; +Point.decodeFrom = function (curve, buffer) { + var type = buffer.readUInt8(0) + var compressed = (type !== 4) - var state = this._readableState; - var paused = false; + var byteLength = Math.floor((curve.p.bitLength() + 7) / 8) + var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength)) - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } + var Q + if (compressed) { + assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length') + assert(type === 0x02 || type === 0x03, 'Invalid sequence tag') - _this.push(null); - }); + var isOdd = (type === 0x03) + Q = curve.pointFromX(isOdd, x) + } else { + assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length') - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength)) + Q = Point.fromAffine(curve, x, y) + } - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + Q.compressed = compressed + return Q +} - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); +Point.prototype.toString = function () { + if (this.curve.isInfinity(this)) return '(INFINITY)' - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')' +} - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } +module.exports = Point - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - return this; -}; +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; +// (public) Constructor +function BigInteger(a, b, c) { + if (!(this instanceof BigInteger)) + return new BigInteger(a, b, c) + + if (a != null) { + if ("number" == typeof a) this.fromNumber(a, b, c) + else if (b == null && "string" != typeof a) this.fromString(a, 256) + else this.fromString(a, b) } -}); +} -// exposed for testing purposes only. -Readable._fromList = fromList; +var proto = BigInteger.prototype -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; +// duck-typed isBigInteger +proto.__bigi = __webpack_require__(196).version +BigInteger.isBigInteger = function (obj, check_ver) { + return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi) +} - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } +// Bits per digit +var dbits - return ret; -} +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c + c = Math.floor(v / 0x4000000) + w[j++] = v & 0x3ffffff } - return ret; + return c } - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i, x, w, j, c, n) { + var xl = x & 0x7fff, + xh = x >> 15 + while (--n >= 0) { + var l = this[i] & 0x7fff + var h = this[i++] >> 15 + var m = xh * l + h * xl + l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff) + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30) + w[j++] = l & 0x3fffffff } - list.length -= c; - return ret; + return c } - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i, x, w, j, c, n) { + var xl = x & 0x3fff, + xh = x >> 14 + while (--n >= 0) { + var l = this[i] & 0x3fff + var h = this[i++] >> 14 + var m = xh * l + h * xl + l = xl * l + ((m & 0x3fff) << 14) + w[j] + c + c = (l >> 28) + (m >> 14) + xh * h + w[j++] = l & 0xfffffff } - list.length -= c; - return ret; + return c } -function endReadable(stream) { - var state = stream._readableState; +// wtf? +BigInteger.prototype.am = am1 +dbits = 26 - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); +BigInteger.prototype.DB = dbits +BigInteger.prototype.DM = ((1 << dbits) - 1) +var DV = BigInteger.prototype.DV = (1 << dbits) - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } -} +var BI_FP = 52 +BigInteger.prototype.FV = Math.pow(2, BI_FP) +BigInteger.prototype.F1 = BI_FP - dbits +BigInteger.prototype.F2 = 2 * dbits - BI_FP -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} +// Digit conversions +var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz" +var BI_RC = new Array() +var rr, vv +rr = "0".charCodeAt(0) +for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv +rr = "a".charCodeAt(0) +for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv +rr = "A".charCodeAt(0) +for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; +function int2char(n) { + return BI_RM.charAt(n) } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(17))) - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(70).EventEmitter; - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)] + return (c == null) ? -1 : c +} -/**/ +// (protected) copy this to r +function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r[i] = this[i] + r.t = this.t + r.s = this.s +} -var pna = __webpack_require__(49); -/**/ +// (protected) set from integer value x, -DV <= x < DV +function bnpFromInt(x) { + this.t = 1 + this.s = (x < 0) ? -1 : 0 + if (x > 0) this[0] = x + else if (x < -1) this[0] = x + DV + else this.t = 0 +} -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; +// return bigint initialized to value +function nbv(i) { + var r = new BigInteger() + r.fromInt(i) + return r +} - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; +// (protected) set from string and radix +function bnpFromString(s, b) { + var self = this - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - pna.nextTick(emitErrorNT, this, err); + var k + if (b == 16) k = 4 + else if (b == 8) k = 3 + else if (b == 256) k = 8; // byte array + else if (b == 2) k = 1 + else if (b == 32) k = 5 + else if (b == 4) k = 2 + else { + self.fromRadix(s, b) + return + } + self.t = 0 + self.s = 0 + var i = s.length, + mi = false, + sh = 0 + while (--i >= 0) { + var x = (k == 8) ? s[i] & 0xff : intAt(s, i) + if (x < 0) { + if (s.charAt(i) == "-") mi = true + continue } - return this; + mi = false + if (sh == 0) + self[self.t++] = x + else if (sh + k > self.DB) { + self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh + self[self.t++] = (x >> (self.DB - sh)) + } else + self[self.t - 1] |= x << sh + sh += k + if (sh >= self.DB) sh -= self.DB } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; + if (k == 8 && (s[0] & 0x80) != 0) { + self.s = -1 + if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh } + self.clamp() + if (mi) BigInteger.ZERO.subTo(self, self) +} - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } +// (protected) clamp off excess high words +function bnpClamp() { + var c = this.s & this.DM + while (this.t > 0 && this[this.t - 1] == c)--this.t +} - this._destroy(err || null, function (err) { - if (!cb && err) { - pna.nextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; +// (public) return string representation in given radix +function bnToString(b) { + var self = this + if (self.s < 0) return "-" + self.negate() + .toString(b) + var k + if (b == 16) k = 4 + else if (b == 8) k = 3 + else if (b == 2) k = 1 + else if (b == 32) k = 5 + else if (b == 4) k = 2 + else return self.toRadix(b) + var km = (1 << k) - 1, + d, m = false, + r = "", + i = self.t + var p = self.DB - (i * self.DB) % k + if (i-- > 0) { + if (p < self.DB && (d = self[i] >> p) > 0) { + m = true + r = int2char(d) + } + while (i >= 0) { + if (p < k) { + d = (self[i] & ((1 << p) - 1)) << (k - p) + d |= self[--i] >> (p += self.DB - k) + } else { + d = (self[i] >> (p -= k)) & km + if (p <= 0) { + p += self.DB + --i + } } - } else if (cb) { - cb(err); + if (d > 0) m = true + if (m) r += int2char(d) } - }); - - return this; -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; } + return m ? r : "0" } -function emitErrorNT(self, err) { - self.emit('error', err); +// (public) -this +function bnNegate() { + var r = new BigInteger() + BigInteger.ZERO.subTo(this, r) + return r } -module.exports = { - destroy: destroy, - undestroy: undestroy -}; - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - - - -module.exports = Transform; - -var Duplex = __webpack_require__(19); - -/**/ -var util = __webpack_require__(34); -util.inherits = __webpack_require__(1); -/**/ - -util.inherits(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; +// (public) |this| +function bnAbs() { + return (this.s < 0) ? this.negate() : this +} - var cb = ts.writecb; +// (public) return + if this > a, - if this < a, 0 if equal +function bnCompareTo(a) { + var r = this.s - a.s + if (r != 0) return r + var i = this.t + r = i - a.t + if (r != 0) return (this.s < 0) ? -r : r + while (--i >= 0) + if ((r = this[i] - a[i]) != 0) return r + return 0 +} - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); +// returns bit length of the integer x +function nbits(x) { + var r = 1, + t + if ((t = x >>> 16) != 0) { + x = t + r += 16 } - - ts.writechunk = null; - ts.writecb = null; - - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - - cb(er); - - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); + if ((t = x >> 8) != 0) { + x = t + r += 8 + } + if ((t = x >> 4) != 0) { + x = t + r += 4 + } + if ((t = x >> 2) != 0) { + x = t + r += 2 + } + if ((t = x >> 1) != 0) { + x = t + r += 1 } + return r } -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; +// (public) return the number of bits in "this" +function bnBitLength() { + if (this.t <= 0) return 0 + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) +} - if (typeof options.flush === 'function') this._flush = options.flush; - } +// (public) return the number of bytes in "this" +function bnByteLength() { + return this.bitLength() >> 3 +} - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); +// (protected) r = this << n*DB +function bnpDLShiftTo(n, r) { + var i + for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i] + for (i = n - 1; i >= 0; --i) r[i] = 0 + r.t = this.t + n + r.s = this.s } -function prefinish() { - var _this = this; +// (protected) r = this >> n*DB +function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r[i - n] = this[i] + r.t = Math.max(this.t - n, 0) + r.s = this.s +} - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); +// (protected) r = this << n +function bnpLShiftTo(n, r) { + var self = this + var bs = n % self.DB + var cbs = self.DB - bs + var bm = (1 << cbs) - 1 + var ds = Math.floor(n / self.DB), + c = (self.s << bs) & self.DM, + i + for (i = self.t - 1; i >= 0; --i) { + r[i + ds + 1] = (self[i] >> cbs) | c + c = (self[i] & bm) << bs } + for (i = ds - 1; i >= 0; --i) r[i] = 0 + r[ds] = c + r.t = self.t + ds + 1 + r.s = self.s + r.clamp() } -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); +// (protected) r = this >> n +function bnpRShiftTo(n, r) { + var self = this + r.s = self.s + var ds = Math.floor(n / self.DB) + if (ds >= self.t) { + r.t = 0 + return } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; + var bs = n % self.DB + var cbs = self.DB - bs + var bm = (1 << bs) - 1 + r[0] = self[ds] >> bs + for (var i = ds + 1; i < self.t; ++i) { + r[i - ds - 1] |= (self[i] & bm) << cbs + r[i - ds] = self[i] >> bs + } + if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs + r.t = self.t - ds + r.clamp() +} - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); +// (protected) r = this - a +function bnpSubTo(a, r) { + var self = this + var i = 0, + c = 0, + m = Math.min(a.t, self.t) + while (i < m) { + c += self[i] - a[i] + r[i++] = c & self.DM + c >>= self.DB + } + if (a.t < self.t) { + c -= a.s + while (i < self.t) { + c += self[i] + r[i++] = c & self.DM + c >>= self.DB + } + c += self.s } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + c += self.s + while (i < a.t) { + c -= a[i] + r[i++] = c & self.DM + c >>= self.DB + } + c -= a.s } -}; - -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; + r.s = (c < 0) ? -1 : 0 + if (c < -1) r[i++] = self.DV + c + else if (c > 0) r[i++] = c + r.t = i + r.clamp() +} - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; +// (protected) r = this * a, r != this,a (HAC 14.12) +// "this" should be the larger one if appropriate. +function bnpMultiplyTo(a, r) { + var x = this.abs(), + y = a.abs() + var i = x.t + r.t = i + y.t + while (--i >= 0) r[i] = 0 + for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t) + r.s = 0 + r.clamp() + if (this.s != a.s) BigInteger.ZERO.subTo(r, r) +} -function done(stream, er, data) { - if (er) return stream.emit('error', er); +// (protected) r = this^2, r != this (HAC 14.16) +function bnpSquareTo(r) { + var x = this.abs() + var i = r.t = 2 * x.t + while (--i >= 0) r[i] = 0 + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1) + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r[i + x.t] -= x.DV + r[i + x.t + 1] = 1 + } + } + if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1) + r.s = 0 + r.clamp() +} - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); +// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) +// r != q, this != m. q or r may be null. +function bnpDivRemTo(m, q, r) { + var self = this + var pm = m.abs() + if (pm.t <= 0) return + var pt = self.abs() + if (pt.t < pm.t) { + if (q != null) q.fromInt(0) + if (r != null) self.copyTo(r) + return + } + if (r == null) r = new BigInteger() + var y = new BigInteger(), + ts = self.s, + ms = m.s + var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y) + pt.lShiftTo(nsh, r) + } else { + pm.copyTo(y) + pt.copyTo(r) + } + var ys = y.t + var y0 = y[ys - 1] + if (y0 == 0) return + var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0) + var d1 = self.FV / yt, + d2 = (1 << self.F1) / yt, + e = 1 << self.F2 + var i = r.t, + j = i - ys, + t = (q == null) ? new BigInteger() : q + y.dlShiftTo(j, t) + if (r.compareTo(t) >= 0) { + r[r.t++] = 1 + r.subTo(t, r) + } + BigInteger.ONE.dlShiftTo(ys, t) + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) y[y.t++] = 0 + while (--j >= 0) { + // Estimate quotient digit + var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2) + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out + y.dlShiftTo(j, t) + r.subTo(t, r) + while (r[i] < --qd) r.subTo(t, r) + } + } + if (q != null) { + r.drShiftTo(ys, q) + if (ts != ms) BigInteger.ZERO.subTo(q, q) + } + r.t = ys + r.clamp() + if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder + if (ts < 0) BigInteger.ZERO.subTo(r, r) +} - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); +// (public) this mod a +function bnMod(a) { + var r = new BigInteger() + this.abs() + .divRemTo(a, null, r) + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r) + return r +} - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); +// Modular reduction using "classic" algorithm +function Classic(m) { + this.m = m +} - return stream.push(null); +function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m) + else return x } -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { +function cRevert(x) { + return x +} -var aes = __webpack_require__(48) -var Buffer = __webpack_require__(0).Buffer -var Transform = __webpack_require__(18) -var inherits = __webpack_require__(1) +function cReduce(x) { + x.divRemTo(this.m, null, x) +} -function StreamCipher (mode, key, iv, decrypt) { - Transform.call(this) +function cMulTo(x, y, r) { + x.multiplyTo(y, r) + this.reduce(r) +} - this._cipher = new aes.AES(key) - this._prev = Buffer.from(iv) - this._cache = Buffer.allocUnsafe(0) - this._secCache = Buffer.allocUnsafe(0) - this._decrypt = decrypt - this._mode = mode +function cSqrTo(x, r) { + x.squareTo(r) + this.reduce(r) } -inherits(StreamCipher, Transform) +Classic.prototype.convert = cConvert +Classic.prototype.revert = cRevert +Classic.prototype.reduce = cReduce +Classic.prototype.mulTo = cMulTo +Classic.prototype.sqrTo = cSqrTo -StreamCipher.prototype._update = function (chunk) { - return this._mode.encrypt(this, chunk, this._decrypt) +// (protected) return "-1/this % 2^DB"; useful for Mont. reduction +// justification: +// xy == 1 (mod m) +// xy = 1+km +// xy(2-xy) = (1+km)(1-km) +// x[y(2-xy)] = 1-k^2m^2 +// x[y(2-xy)] == 1 (mod m^2) +// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 +// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. +// JS multiply "overflows" differently from C/C++, so care is needed here. +function bnpInvDigit() { + if (this.t < 1) return 0 + var x = this[0] + if ((x & 1) == 0) return 0 + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y > 0) ? this.DV - y : -y } -StreamCipher.prototype._final = function () { - this._cipher.scrub() +// Montgomery reduction +function Montgomery(m) { + this.m = m + this.mp = m.invDigit() + this.mpl = this.mp & 0x7fff + this.mph = this.mp >> 15 + this.um = (1 << (m.DB - 15)) - 1 + this.mt2 = 2 * m.t } -module.exports = StreamCipher - - -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { +// xR mod m +function montConvert(x) { + var r = new BigInteger() + x.abs() + .dlShiftTo(this.m.t, r) + r.divRemTo(this.m, null, r) + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r) + return r +} -var Buffer = __webpack_require__(0).Buffer -var MD5 = __webpack_require__(74) +// x/R mod m +function montRevert(x) { + var r = new BigInteger() + x.copyTo(r) + this.reduce(r) + return r +} -/* eslint-disable camelcase */ -function EVP_BytesToKey (password, salt, keyBits, ivLen) { - if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') - if (salt) { - if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') - if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') +// x = x/R mod m (HAC 14.32) +function montReduce(x) { + while (x.t <= this.mt2) // pad x so am has enough room later + x[x.t++] = 0 + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff + var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM + // use am to combine the multiply-shift-add into one call + j = i + this.m.t + x[j] += this.m.am(0, u0, x, i, 0, this.m.t) + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV + x[++j]++ + } } + x.clamp() + x.drShiftTo(this.m.t, x) + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x) +} - var keyLen = keyBits / 8 - var key = Buffer.alloc(keyLen) - var iv = Buffer.alloc(ivLen || 0) - var tmp = Buffer.alloc(0) +// r = "x^2/R mod m"; x != r +function montSqrTo(x, r) { + x.squareTo(r) + this.reduce(r) +} - while (keyLen > 0 || ivLen > 0) { - var hash = new MD5() - hash.update(tmp) - hash.update(password) - if (salt) hash.update(salt) - tmp = hash.digest() +// r = "xy/R mod m"; x,y != r +function montMulTo(x, y, r) { + x.multiplyTo(y, r) + this.reduce(r) +} - var used = 0 +Montgomery.prototype.convert = montConvert +Montgomery.prototype.revert = montRevert +Montgomery.prototype.reduce = montReduce +Montgomery.prototype.mulTo = montMulTo +Montgomery.prototype.sqrTo = montSqrTo - if (keyLen > 0) { - var keyStart = key.length - keyLen - used = Math.min(keyLen, tmp.length) - tmp.copy(key, keyStart, 0, used) - keyLen -= used - } +// (protected) true iff this is even +function bnpIsEven() { + return ((this.t > 0) ? (this[0] & 1) : this.s) == 0 +} - if (used < tmp.length && ivLen > 0) { - var ivStart = iv.length - ivLen - var length = Math.min(ivLen, tmp.length - used) - tmp.copy(iv, ivStart, used, used + length) - ivLen -= length +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) +function bnpExp(e, z) { + if (e > 0xffffffff || e < 1) return BigInteger.ONE + var r = new BigInteger(), + r2 = new BigInteger(), + g = z.convert(this), + i = nbits(e) - 1 + g.copyTo(r) + while (--i >= 0) { + z.sqrTo(r, r2) + if ((e & (1 << i)) > 0) z.mulTo(r2, g, r) + else { + var t = r + r = r2 + r2 = t } } - - tmp.fill(0) - return { key: key, iv: iv } + return z.revert(r) } -module.exports = EVP_BytesToKey - - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { +// (public) this^e % m, 0 <= e < 2^32 +function bnModPowInt(e, m) { + var z + if (e < 256 || m.isEven()) z = new Classic(m) + else z = new Montgomery(m) + return this.exp(e, z) +} -"use strict"; +// protected +proto.copyTo = bnpCopyTo +proto.fromInt = bnpFromInt +proto.fromString = bnpFromString +proto.clamp = bnpClamp +proto.dlShiftTo = bnpDLShiftTo +proto.drShiftTo = bnpDRShiftTo +proto.lShiftTo = bnpLShiftTo +proto.rShiftTo = bnpRShiftTo +proto.subTo = bnpSubTo +proto.multiplyTo = bnpMultiplyTo +proto.squareTo = bnpSquareTo +proto.divRemTo = bnpDivRemTo +proto.invDigit = bnpInvDigit +proto.isEven = bnpIsEven +proto.exp = bnpExp -var Buffer = __webpack_require__(0).Buffer -var Transform = __webpack_require__(117).Transform -var inherits = __webpack_require__(1) +// public +proto.toString = bnToString +proto.negate = bnNegate +proto.abs = bnAbs +proto.compareTo = bnCompareTo +proto.bitLength = bnBitLength +proto.byteLength = bnByteLength +proto.mod = bnMod +proto.modPowInt = bnModPowInt -function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } +// (public) +function bnClone() { + var r = new BigInteger() + this.copyTo(r) + return r } -function HashBase (blockSize) { - Transform.call(this) - - this._block = Buffer.allocUnsafe(blockSize) - this._blockSize = blockSize - this._blockOffset = 0 - this._length = [0, 0, 0, 0] +// (public) return value as integer +function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this[0] - this.DV + else if (this.t == 0) return -1 + } else if (this.t == 1) return this[0] + else if (this.t == 0) return 0 + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0] +} - this._finalized = false +// (public) return value as byte +function bnByteValue() { + return (this.t == 0) ? this.s : (this[0] << 24) >> 24 } -inherits(HashBase, Transform) +// (public) return value as short (assumes DB>=16) +function bnShortValue() { + return (this.t == 0) ? this.s : (this[0] << 16) >> 16 +} -HashBase.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - this.update(chunk, encoding) - } catch (err) { - error = err - } +// (protected) return x s.t. r^x < DV +function bnpChunkSize(r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)) +} - callback(error) +// (public) 0 if this == 0, 1 if this > 0 +function bnSigNum() { + if (this.s < 0) return -1 + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0 + else return 1 } -HashBase.prototype._flush = function (callback) { - var error = null - try { - this.push(this.digest()) - } catch (err) { - error = err +// (protected) convert to radix string +function bnpToRadix(b) { + if (b == null) b = 10 + if (this.signum() == 0 || b < 2 || b > 36) return "0" + var cs = this.chunkSize(b) + var a = Math.pow(b, cs) + var d = nbv(a), + y = new BigInteger(), + z = new BigInteger(), + r = "" + this.divRemTo(d, y, z) + while (y.signum() > 0) { + r = (a + z.intValue()) + .toString(b) + .substr(1) + r + y.divRemTo(d, y, z) } - - callback(error) + return z.intValue() + .toString(b) + r } -HashBase.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data') - if (this._finalized) throw new Error('Digest already called') - if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - - // consume data - var block = this._block - var offset = 0 - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] - this._update() - this._blockOffset = 0 +// (protected) convert from radix string +function bnpFromRadix(s, b) { + var self = this + self.fromInt(0) + if (b == null) b = 10 + var cs = self.chunkSize(b) + var d = Math.pow(b, cs), + mi = false, + j = 0, + w = 0 + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i) + if (x < 0) { + if (s.charAt(i) == "-" && self.signum() == 0) mi = true + continue + } + w = b * w + x + if (++j >= cs) { + self.dMultiply(d) + self.dAddOffset(w, 0) + j = 0 + w = 0 + } } - while (offset < data.length) block[this._blockOffset++] = data[offset++] + if (j > 0) { + self.dMultiply(Math.pow(b, j)) + self.dAddOffset(w, 0) + } + if (mi) BigInteger.ZERO.subTo(self, self) +} - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry - carry = (this._length[j] / 0x0100000000) | 0 - if (carry > 0) this._length[j] -= 0x0100000000 * carry +// (protected) alternate constructor +function bnpFromNumber(a, b, c) { + var self = this + if ("number" == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) self.fromInt(1) + else { + self.fromNumber(a, c) + if (!self.testBit(a - 1)) // force MSB set + self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self) + if (self.isEven()) self.dAddOffset(1, 0); // force odd + while (!self.isProbablePrime(b)) { + self.dAddOffset(2, 0) + if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self) + } + } + } else { + // new BigInteger(int,RNG) + var x = new Array(), + t = a & 7 + x.length = (a >> 3) + 1 + b.nextBytes(x) + if (t > 0) x[0] &= ((1 << t) - 1) + else x[0] = 0 + self.fromString(x, 256) } +} - return this +// (public) convert to bigendian byte array +function bnToByteArray() { + var self = this + var i = self.t, + r = new Array() + r[0] = self.s + var p = self.DB - (i * self.DB) % 8, + d, k = 0 + if (i-- > 0) { + if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p) + r[k++] = d | (self.s << (self.DB - p)) + while (i >= 0) { + if (p < 8) { + d = (self[i] & ((1 << p) - 1)) << (8 - p) + d |= self[--i] >> (p += self.DB - 8) + } else { + d = (self[i] >> (p -= 8)) & 0xff + if (p <= 0) { + p += self.DB + --i + } + } + if ((d & 0x80) != 0) d |= -256 + if (k === 0 && (self.s & 0x80) != (d & 0x80))++k + if (k > 0 || d != self.s) r[k++] = d + } + } + return r } -HashBase.prototype._update = function () { - throw new Error('_update is not implemented') +function bnEquals(a) { + return (this.compareTo(a) == 0) } -HashBase.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true +function bnMin(a) { + return (this.compareTo(a) < 0) ? this : a +} - var digest = this._digest() - if (encoding !== undefined) digest = digest.toString(encoding) +function bnMax(a) { + return (this.compareTo(a) > 0) ? this : a +} - // reset state - this._block.fill(0) - this._blockOffset = 0 - for (var i = 0; i < 4; ++i) this._length[i] = 0 +// (protected) r = this op a (bitwise) +function bnpBitwiseTo(a, op, r) { + var self = this + var i, f, m = Math.min(a.t, self.t) + for (i = 0; i < m; ++i) r[i] = op(self[i], a[i]) + if (a.t < self.t) { + f = a.s & self.DM + for (i = m; i < self.t; ++i) r[i] = op(self[i], f) + r.t = self.t + } else { + f = self.s & self.DM + for (i = m; i < a.t; ++i) r[i] = op(f, a[i]) + r.t = a.t + } + r.s = op(self.s, a.s) + r.clamp() +} - return digest +// (public) this & a +function op_and(x, y) { + return x & y } -HashBase.prototype._digest = function () { - throw new Error('_digest is not implemented') +function bnAnd(a) { + var r = new BigInteger() + this.bitwiseTo(a, op_and, r) + return r } -module.exports = HashBase +// (public) this | a +function op_or(x, y) { + return x | y +} +function bnOr(a) { + var r = new BigInteger() + this.bitwiseTo(a, op_or, r) + return r +} -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { +// (public) this ^ a +function op_xor(x, y) { + return x ^ y +} -var assert = __webpack_require__(4) -var Buffer = __webpack_require__(0).Buffer -var BigInteger = __webpack_require__(10) +function bnXor(a) { + var r = new BigInteger() + this.bitwiseTo(a, op_xor, r) + return r +} -var THREE = BigInteger.valueOf(3) +// (public) this & ~a +function op_andnot(x, y) { + return x & ~y +} -function Point (curve, x, y, z) { - assert.notStrictEqual(z, undefined, 'Missing Z coordinate') +function bnAndNot(a) { + var r = new BigInteger() + this.bitwiseTo(a, op_andnot, r) + return r +} - this.curve = curve - this.x = x - this.y = y - this.z = z - this._zInv = null +// (public) ~this +function bnNot() { + var r = new BigInteger() + for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i] + r.t = this.t + r.s = ~this.s + return r +} - this.compressed = true +// (public) this << n +function bnShiftLeft(n) { + var r = new BigInteger() + if (n < 0) this.rShiftTo(-n, r) + else this.lShiftTo(n, r) + return r } -Object.defineProperty(Point.prototype, 'zInv', { - get: function () { - if (this._zInv === null) { - this._zInv = this.z.modInverse(this.curve.p) - } +// (public) this >> n +function bnShiftRight(n) { + var r = new BigInteger() + if (n < 0) this.lShiftTo(-n, r) + else this.rShiftTo(n, r) + return r +} - return this._zInv +// return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { + if (x == 0) return -1 + var r = 0 + if ((x & 0xffff) == 0) { + x >>= 16 + r += 16 } -}) - -Object.defineProperty(Point.prototype, 'affineX', { - get: function () { - return this.x.multiply(this.zInv).mod(this.curve.p) + if ((x & 0xff) == 0) { + x >>= 8 + r += 8 } -}) - -Object.defineProperty(Point.prototype, 'affineY', { - get: function () { - return this.y.multiply(this.zInv).mod(this.curve.p) + if ((x & 0xf) == 0) { + x >>= 4 + r += 4 } -}) - -Point.fromAffine = function (curve, x, y) { - return new Point(curve, x, y, BigInteger.ONE) + if ((x & 3) == 0) { + x >>= 2 + r += 2 + } + if ((x & 1) == 0)++r + return r } -Point.prototype.equals = function (other) { - if (other === this) return true - if (this.curve.isInfinity(this)) return this.curve.isInfinity(other) - if (this.curve.isInfinity(other)) return this.curve.isInfinity(this) - - // u = Y2 * Z1 - Y1 * Z2 - var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p) +// (public) returns index of lowest 1-bit (or -1 if none) +function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this[i] != 0) return i * this.DB + lbit(this[i]) + if (this.s < 0) return this.t * this.DB + return -1 +} - if (u.signum() !== 0) return false +// return number of 1 bits in x +function cbit(x) { + var r = 0 + while (x != 0) { + x &= x - 1 + ++r + } + return r +} - // v = X2 * Z1 - X1 * Z2 - var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p) +// (public) return number of set bits +function bnBitCount() { + var r = 0, + x = this.s & this.DM + for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x) + return r +} - return v.signum() === 0 +// (public) true iff nth bit is set +function bnTestBit(n) { + var j = Math.floor(n / this.DB) + if (j >= this.t) return (this.s != 0) + return ((this[j] & (1 << (n % this.DB))) != 0) } -Point.prototype.negate = function () { - var y = this.curve.p.subtract(this.y) +// (protected) this op (1<>= self.DB + } + if (a.t < self.t) { + c += a.s + while (i < self.t) { + c += self[i] + r[i++] = c & self.DM + c >>= self.DB } - - return this.curve.infinity // this = -b, so infinity + c += self.s + } else { + c += self.s + while (i < a.t) { + c += a[i] + r[i++] = c & self.DM + c >>= self.DB + } + c += a.s } + r.s = (c < 0) ? -1 : 0 + if (c > 0) r[i++] = c + else if (c < -1) r[i++] = self.DV + c + r.t = i + r.clamp() +} - var v2 = v.square() - var v3 = v2.multiply(v) - var x1v2 = x1.multiply(v2) - var zu2 = u.square().multiply(this.z) - - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p) - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p) - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p) - - return new Point(this.curve, x3, y3, z3) +// (public) this + a +function bnAdd(a) { + var r = new BigInteger() + this.addTo(a, r) + return r } -Point.prototype.twice = function () { - if (this.curve.isInfinity(this)) return this - if (this.y.signum() === 0) return this.curve.infinity +// (public) this - a +function bnSubtract(a) { + var r = new BigInteger() + this.subTo(a, r) + return r +} - var x1 = this.x - var y1 = this.y +// (public) this * a +function bnMultiply(a) { + var r = new BigInteger() + this.multiplyTo(a, r) + return r +} - var y1z1 = y1.multiply(this.z).mod(this.curve.p) - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p) - var a = this.curve.a +// (public) this^2 +function bnSquare() { + var r = new BigInteger() + this.squareTo(r) + return r +} - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE) +// (public) this / a +function bnDivide(a) { + var r = new BigInteger() + this.divRemTo(a, r, null) + return r +} - if (a.signum() !== 0) { - w = w.add(this.z.square().multiply(a)) - } +// (public) this % a +function bnRemainder(a) { + var r = new BigInteger() + this.divRemTo(a, null, r) + return r +} - w = w.mod(this.curve.p) - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p) - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p) - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p) +// (public) [this/a,this%a] +function bnDivideAndRemainder(a) { + var q = new BigInteger(), + r = new BigInteger() + this.divRemTo(a, q, r) + return new Array(q, r) +} - return new Point(this.curve, x3, y3, z3) +// (protected) this *= n, this >= 0, 1 < n < DV +function bnpDMultiply(n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t) + ++this.t + this.clamp() } -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -Point.prototype.multiply = function (k) { - if (this.curve.isInfinity(this)) return this - if (k.signum() === 0) return this.curve.infinity +// (protected) this += n << w words, this >= 0 +function bnpDAddOffset(n, w) { + if (n == 0) return + while (this.t <= w) this[this.t++] = 0 + this[w] += n + while (this[w] >= this.DV) { + this[w] -= this.DV + if (++w >= this.t) this[this.t++] = 0 + ++this[w] + } +} - var e = k - var h = e.multiply(THREE) +// A "null" reducer +function NullExp() {} - var neg = this.negate() - var R = this +function nNop(x) { + return x +} - for (var i = h.bitLength() - 2; i > 0; --i) { - var hBit = h.testBit(i) - var eBit = e.testBit(i) +function nMulTo(x, y, r) { + x.multiplyTo(y, r) +} - R = R.twice() +function nSqrTo(x, r) { + x.squareTo(r) +} - if (hBit !== eBit) { - R = R.add(hBit ? this : neg) - } - } +NullExp.prototype.convert = nNop +NullExp.prototype.revert = nNop +NullExp.prototype.mulTo = nMulTo +NullExp.prototype.sqrTo = nSqrTo - return R +// (public) this^e +function bnPow(e) { + return this.exp(e, new NullExp()) } -// Compute this*j + x*k (simultaneous multiplication) -Point.prototype.multiplyTwo = function (j, x, k) { - var i = Math.max(j.bitLength(), k.bitLength()) - 1 - var R = this.curve.infinity - var both = this.add(x) - - while (i >= 0) { - var jBit = j.testBit(i) - var kBit = k.testBit(i) - - R = R.twice() - - if (jBit) { - if (kBit) { - R = R.add(both) - } else { - R = R.add(this) - } - } else if (kBit) { - R = R.add(x) - } - --i - } - - return R -} - -Point.prototype.getEncoded = function (compressed) { - if (compressed == null) compressed = this.compressed - if (this.curve.isInfinity(this)) return Buffer.alloc(1, 0) // Infinity point encoded is simply '00' - - var x = this.affineX - var y = this.affineY - var byteLength = this.curve.pLength - var buffer - - // 0x02/0x03 | X - if (compressed) { - buffer = Buffer.allocUnsafe(1 + byteLength) - buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0) - - // 0x04 | X | Y - } else { - buffer = Buffer.allocUnsafe(1 + byteLength + byteLength) - buffer.writeUInt8(0x04, 0) - - y.toBuffer(byteLength).copy(buffer, 1 + byteLength) - } - - x.toBuffer(byteLength).copy(buffer, 1) - - return buffer +// (protected) r = lower n words of "this * a", a.t <= n +// "this" should be the larger one if appropriate. +function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n) + r.s = 0; // assumes a,this >= 0 + r.t = i + while (i > 0) r[--i] = 0 + var j + for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t) + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i) + r.clamp() } -Point.decodeFrom = function (curve, buffer) { - var type = buffer.readUInt8(0) - var compressed = (type !== 4) - - var byteLength = Math.floor((curve.p.bitLength() + 7) / 8) - var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength)) - - var Q - if (compressed) { - assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length') - assert(type === 0x02 || type === 0x03, 'Invalid sequence tag') - - var isOdd = (type === 0x03) - Q = curve.pointFromX(isOdd, x) - } else { - assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length') - - var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength)) - Q = Point.fromAffine(curve, x, y) - } - - Q.compressed = compressed - return Q +// (protected) r = "this * a" without lower n words, n > 0 +// "this" should be the larger one if appropriate. +function bnpMultiplyUpperTo(a, n, r) { + --n + var i = r.t = this.t + a.t - n + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) r[i] = 0 + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n) + r.clamp() + r.drShiftTo(1, r) } -Point.prototype.toString = function () { - if (this.curve.isInfinity(this)) return '(INFINITY)' - - return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')' +// Barrett modular reduction +function Barrett(m) { + // setup Barrett + this.r2 = new BigInteger() + this.q3 = new BigInteger() + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2) + this.mu = this.r2.divide(m) + this.m = m } -module.exports = Point - - -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { - -// (public) Constructor -function BigInteger(a, b, c) { - if (!(this instanceof BigInteger)) - return new BigInteger(a, b, c) - - if (a != null) { - if ("number" == typeof a) this.fromNumber(a, b, c) - else if (b == null && "string" != typeof a) this.fromString(a, 256) - else this.fromString(a, b) +function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m) + else if (x.compareTo(this.m) < 0) return x + else { + var r = new BigInteger() + x.copyTo(r) + this.reduce(r) + return r } } -var proto = BigInteger.prototype - -// duck-typed isBigInteger -proto.__bigi = __webpack_require__(237).version -BigInteger.isBigInteger = function (obj, check_ver) { - return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi) +function barrettRevert(x) { + return x } -// Bits per digit -var dbits - -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. - -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) -function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c - c = Math.floor(v / 0x4000000) - w[j++] = v & 0x3ffffff - } - return c -} -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) -function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15 - while (--n >= 0) { - var l = this[i] & 0x7fff - var h = this[i++] >> 15 - var m = xh * l + h * xl - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff) - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30) - w[j++] = l & 0x3fffffff - } - return c -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. -function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14 - while (--n >= 0) { - var l = this[i] & 0x3fff - var h = this[i++] >> 14 - var m = xh * l + h * xl - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c - c = (l >> 28) + (m >> 14) + xh * h - w[j++] = l & 0xfffffff +// x = x mod m (HAC 14.42) +function barrettReduce(x) { + var self = this + x.drShiftTo(self.m.t - 1, self.r2) + if (x.t > self.m.t + 1) { + x.t = self.m.t + 1 + x.clamp() } - return c -} - -// wtf? -BigInteger.prototype.am = am1 -dbits = 26 - -BigInteger.prototype.DB = dbits -BigInteger.prototype.DM = ((1 << dbits) - 1) -var DV = BigInteger.prototype.DV = (1 << dbits) - -var BI_FP = 52 -BigInteger.prototype.FV = Math.pow(2, BI_FP) -BigInteger.prototype.F1 = BI_FP - dbits -BigInteger.prototype.F2 = 2 * dbits - BI_FP - -// Digit conversions -var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz" -var BI_RC = new Array() -var rr, vv -rr = "0".charCodeAt(0) -for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv -rr = "a".charCodeAt(0) -for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv -rr = "A".charCodeAt(0) -for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv - -function int2char(n) { - return BI_RM.charAt(n) -} - -function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)] - return (c == null) ? -1 : c + self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3) + self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2) + while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1) + x.subTo(self.r2, x) + while (x.compareTo(self.m) >= 0) x.subTo(self.m, x) } -// (protected) copy this to r -function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i] - r.t = this.t - r.s = this.s +// r = x^2 mod m; x != r +function barrettSqrTo(x, r) { + x.squareTo(r) + this.reduce(r) } -// (protected) set from integer value x, -DV <= x < DV -function bnpFromInt(x) { - this.t = 1 - this.s = (x < 0) ? -1 : 0 - if (x > 0) this[0] = x - else if (x < -1) this[0] = x + DV - else this.t = 0 +// r = x*y mod m; x,y != r +function barrettMulTo(x, y, r) { + x.multiplyTo(y, r) + this.reduce(r) } -// return bigint initialized to value -function nbv(i) { - var r = new BigInteger() - r.fromInt(i) - return r -} +Barrett.prototype.convert = barrettConvert +Barrett.prototype.revert = barrettRevert +Barrett.prototype.reduce = barrettReduce +Barrett.prototype.mulTo = barrettMulTo +Barrett.prototype.sqrTo = barrettSqrTo -// (protected) set from string and radix -function bnpFromString(s, b) { - var self = this +// (public) this^e % m (HAC 14.85) +function bnModPow(e, m) { + var i = e.bitLength(), + k, r = nbv(1), + z + if (i <= 0) return r + else if (i < 18) k = 1 + else if (i < 48) k = 3 + else if (i < 144) k = 4 + else if (i < 768) k = 5 + else k = 6 + if (i < 8) + z = new Classic(m) + else if (m.isEven()) + z = new Barrett(m) + else + z = new Montgomery(m) - var k - if (b == 16) k = 4 - else if (b == 8) k = 3 - else if (b == 256) k = 8; // byte array - else if (b == 2) k = 1 - else if (b == 32) k = 5 - else if (b == 4) k = 2 - else { - self.fromRadix(s, b) - return - } - self.t = 0 - self.s = 0 - var i = s.length, - mi = false, - sh = 0 - while (--i >= 0) { - var x = (k == 8) ? s[i] & 0xff : intAt(s, i) - if (x < 0) { - if (s.charAt(i) == "-") mi = true - continue + // precomputation + var g = new Array(), + n = 3, + k1 = k - 1, + km = (1 << k) - 1 + g[1] = z.convert(this) + if (k > 1) { + var g2 = new BigInteger() + z.sqrTo(g[1], g2) + while (n <= km) { + g[n] = new BigInteger() + z.mulTo(g2, g[n - 2], g[n]) + n += 2 } - mi = false - if (sh == 0) - self[self.t++] = x - else if (sh + k > self.DB) { - self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh - self[self.t++] = (x >> (self.DB - sh)) - } else - self[self.t - 1] |= x << sh - sh += k - if (sh >= self.DB) sh -= self.DB - } - if (k == 8 && (s[0] & 0x80) != 0) { - self.s = -1 - if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh } - self.clamp() - if (mi) BigInteger.ZERO.subTo(self, self) -} -// (protected) clamp off excess high words -function bnpClamp() { - var c = this.s & this.DM - while (this.t > 0 && this[this.t - 1] == c)--this.t -} + var j = e.t - 1, + w, is1 = true, + r2 = new BigInteger(), + t + i = nbits(e[j]) - 1 + while (j >= 0) { + if (i >= k1) w = (e[j] >> (i - k1)) & km + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i) + if (j > 0) w |= e[j - 1] >> (this.DB + i - k1) + } -// (public) return string representation in given radix -function bnToString(b) { - var self = this - if (self.s < 0) return "-" + self.negate() - .toString(b) - var k - if (b == 16) k = 4 - else if (b == 8) k = 3 - else if (b == 2) k = 1 - else if (b == 32) k = 5 - else if (b == 4) k = 2 - else return self.toRadix(b) - var km = (1 << k) - 1, - d, m = false, - r = "", - i = self.t - var p = self.DB - (i * self.DB) % k - if (i-- > 0) { - if (p < self.DB && (d = self[i] >> p) > 0) { - m = true - r = int2char(d) + n = k + while ((w & 1) == 0) { + w >>= 1 + --n } - while (i >= 0) { - if (p < k) { - d = (self[i] & ((1 << p) - 1)) << (k - p) - d |= self[--i] >> (p += self.DB - k) - } else { - d = (self[i] >> (p -= k)) & km - if (p <= 0) { - p += self.DB - --i - } - } - if (d > 0) m = true - if (m) r += int2char(d) + if ((i -= n) < 0) { + i += this.DB + --j } - } - return m ? r : "0" -} - -// (public) -this -function bnNegate() { - var r = new BigInteger() - BigInteger.ZERO.subTo(this, r) - return r -} - -// (public) |this| -function bnAbs() { - return (this.s < 0) ? this.negate() : this -} - -// (public) return + if this > a, - if this < a, 0 if equal -function bnCompareTo(a) { - var r = this.s - a.s - if (r != 0) return r - var i = this.t - r = i - a.t - if (r != 0) return (this.s < 0) ? -r : r - while (--i >= 0) - if ((r = this[i] - a[i]) != 0) return r - return 0 -} - -// returns bit length of the integer x -function nbits(x) { - var r = 1, - t - if ((t = x >>> 16) != 0) { - x = t - r += 16 - } - if ((t = x >> 8) != 0) { - x = t - r += 8 - } - if ((t = x >> 4) != 0) { - x = t - r += 4 - } - if ((t = x >> 2) != 0) { - x = t - r += 2 - } - if ((t = x >> 1) != 0) { - x = t - r += 1 - } - return r -} - -// (public) return the number of bits in "this" -function bnBitLength() { - if (this.t <= 0) return 0 - return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) -} - -// (public) return the number of bytes in "this" -function bnByteLength() { - return this.bitLength() >> 3 -} - -// (protected) r = this << n*DB -function bnpDLShiftTo(n, r) { - var i - for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i] - for (i = n - 1; i >= 0; --i) r[i] = 0 - r.t = this.t + n - r.s = this.s -} - -// (protected) r = this >> n*DB -function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i] - r.t = Math.max(this.t - n, 0) - r.s = this.s -} - -// (protected) r = this << n -function bnpLShiftTo(n, r) { - var self = this - var bs = n % self.DB - var cbs = self.DB - bs - var bm = (1 << cbs) - 1 - var ds = Math.floor(n / self.DB), - c = (self.s << bs) & self.DM, - i - for (i = self.t - 1; i >= 0; --i) { - r[i + ds + 1] = (self[i] >> cbs) | c - c = (self[i] & bm) << bs - } - for (i = ds - 1; i >= 0; --i) r[i] = 0 - r[ds] = c - r.t = self.t + ds + 1 - r.s = self.s - r.clamp() -} - -// (protected) r = this >> n -function bnpRShiftTo(n, r) { - var self = this - r.s = self.s - var ds = Math.floor(n / self.DB) - if (ds >= self.t) { - r.t = 0 - return - } - var bs = n % self.DB - var cbs = self.DB - bs - var bm = (1 << bs) - 1 - r[0] = self[ds] >> bs - for (var i = ds + 1; i < self.t; ++i) { - r[i - ds - 1] |= (self[i] & bm) << cbs - r[i - ds] = self[i] >> bs - } - if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs - r.t = self.t - ds - r.clamp() -} - -// (protected) r = this - a -function bnpSubTo(a, r) { - var self = this - var i = 0, - c = 0, - m = Math.min(a.t, self.t) - while (i < m) { - c += self[i] - a[i] - r[i++] = c & self.DM - c >>= self.DB - } - if (a.t < self.t) { - c -= a.s - while (i < self.t) { - c += self[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += self.s - } else { - c += self.s - while (i < a.t) { - c -= a[i] - r[i++] = c & self.DM - c >>= self.DB - } - c -= a.s - } - r.s = (c < 0) ? -1 : 0 - if (c < -1) r[i++] = self.DV + c - else if (c > 0) r[i++] = c - r.t = i - r.clamp() -} - -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. -function bnpMultiplyTo(a, r) { - var x = this.abs(), - y = a.abs() - var i = x.t - r.t = i + y.t - while (--i >= 0) r[i] = 0 - for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t) - r.s = 0 - r.clamp() - if (this.s != a.s) BigInteger.ZERO.subTo(r, r) -} - -// (protected) r = this^2, r != this (HAC 14.16) -function bnpSquareTo(r) { - var x = this.abs() - var i = r.t = 2 * x.t - while (--i >= 0) r[i] = 0 - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1) - if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r[i + x.t] -= x.DV - r[i + x.t + 1] = 1 - } - } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1) - r.s = 0 - r.clamp() -} - -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. -function bnpDivRemTo(m, q, r) { - var self = this - var pm = m.abs() - if (pm.t <= 0) return - var pt = self.abs() - if (pt.t < pm.t) { - if (q != null) q.fromInt(0) - if (r != null) self.copyTo(r) - return - } - if (r == null) r = new BigInteger() - var y = new BigInteger(), - ts = self.s, - ms = m.s - var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y) - pt.lShiftTo(nsh, r) - } else { - pm.copyTo(y) - pt.copyTo(r) - } - var ys = y.t - var y0 = y[ys - 1] - if (y0 == 0) return - var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0) - var d1 = self.FV / yt, - d2 = (1 << self.F1) / yt, - e = 1 << self.F2 - var i = r.t, - j = i - ys, - t = (q == null) ? new BigInteger() : q - y.dlShiftTo(j, t) - if (r.compareTo(t) >= 0) { - r[r.t++] = 1 - r.subTo(t, r) - } - BigInteger.ONE.dlShiftTo(ys, t) - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) y[y.t++] = 0 - while (--j >= 0) { - // Estimate quotient digit - var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2) - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out - y.dlShiftTo(j, t) - r.subTo(t, r) - while (r[i] < --qd) r.subTo(t, r) - } - } - if (q != null) { - r.drShiftTo(ys, q) - if (ts != ms) BigInteger.ZERO.subTo(q, q) - } - r.t = ys - r.clamp() - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r) -} - -// (public) this mod a -function bnMod(a) { - var r = new BigInteger() - this.abs() - .divRemTo(a, null, r) - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r) - return r -} - -// Modular reduction using "classic" algorithm -function Classic(m) { - this.m = m -} - -function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m) - else return x -} - -function cRevert(x) { - return x -} - -function cReduce(x) { - x.divRemTo(this.m, null, x) -} - -function cMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -function cSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -Classic.prototype.convert = cConvert -Classic.prototype.revert = cRevert -Classic.prototype.reduce = cReduce -Classic.prototype.mulTo = cMulTo -Classic.prototype.sqrTo = cSqrTo - -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. -function bnpInvDigit() { - if (this.t < 1) return 0 - var x = this[0] - if ((x & 1) == 0) return 0 - var y = x & 3; // y == 1/x mod 2^2 - y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 - y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 - y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y > 0) ? this.DV - y : -y -} - -// Montgomery reduction -function Montgomery(m) { - this.m = m - this.mp = m.invDigit() - this.mpl = this.mp & 0x7fff - this.mph = this.mp >> 15 - this.um = (1 << (m.DB - 15)) - 1 - this.mt2 = 2 * m.t -} - -// xR mod m -function montConvert(x) { - var r = new BigInteger() - x.abs() - .dlShiftTo(this.m.t, r) - r.divRemTo(this.m, null, r) - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r) - return r -} - -// x/R mod m -function montRevert(x) { - var r = new BigInteger() - x.copyTo(r) - this.reduce(r) - return r -} - -// x = x/R mod m (HAC 14.32) -function montReduce(x) { - while (x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0 - for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff - var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM - // use am to combine the multiply-shift-add into one call - j = i + this.m.t - x[j] += this.m.am(0, u0, x, i, 0, this.m.t) - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV - x[++j]++ - } - } - x.clamp() - x.drShiftTo(this.m.t, x) - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x) -} - -// r = "x^2/R mod m"; x != r -function montSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -// r = "xy/R mod m"; x,y != r -function montMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -Montgomery.prototype.convert = montConvert -Montgomery.prototype.revert = montRevert -Montgomery.prototype.reduce = montReduce -Montgomery.prototype.mulTo = montMulTo -Montgomery.prototype.sqrTo = montSqrTo - -// (protected) true iff this is even -function bnpIsEven() { - return ((this.t > 0) ? (this[0] & 1) : this.s) == 0 -} - -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) -function bnpExp(e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE - var r = new BigInteger(), - r2 = new BigInteger(), - g = z.convert(this), - i = nbits(e) - 1 - g.copyTo(r) - while (--i >= 0) { - z.sqrTo(r, r2) - if ((e & (1 << i)) > 0) z.mulTo(r2, g, r) - else { - var t = r - r = r2 - r2 = t - } - } - return z.revert(r) -} - -// (public) this^e % m, 0 <= e < 2^32 -function bnModPowInt(e, m) { - var z - if (e < 256 || m.isEven()) z = new Classic(m) - else z = new Montgomery(m) - return this.exp(e, z) -} - -// protected -proto.copyTo = bnpCopyTo -proto.fromInt = bnpFromInt -proto.fromString = bnpFromString -proto.clamp = bnpClamp -proto.dlShiftTo = bnpDLShiftTo -proto.drShiftTo = bnpDRShiftTo -proto.lShiftTo = bnpLShiftTo -proto.rShiftTo = bnpRShiftTo -proto.subTo = bnpSubTo -proto.multiplyTo = bnpMultiplyTo -proto.squareTo = bnpSquareTo -proto.divRemTo = bnpDivRemTo -proto.invDigit = bnpInvDigit -proto.isEven = bnpIsEven -proto.exp = bnpExp - -// public -proto.toString = bnToString -proto.negate = bnNegate -proto.abs = bnAbs -proto.compareTo = bnCompareTo -proto.bitLength = bnBitLength -proto.byteLength = bnByteLength -proto.mod = bnMod -proto.modPowInt = bnModPowInt - -// (public) -function bnClone() { - var r = new BigInteger() - this.copyTo(r) - return r -} - -// (public) return value as integer -function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV - else if (this.t == 0) return -1 - } else if (this.t == 1) return this[0] - else if (this.t == 0) return 0 - // assumes 16 < DB < 32 - return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0] -} - -// (public) return value as byte -function bnByteValue() { - return (this.t == 0) ? this.s : (this[0] << 24) >> 24 -} - -// (public) return value as short (assumes DB>=16) -function bnShortValue() { - return (this.t == 0) ? this.s : (this[0] << 16) >> 16 -} - -// (protected) return x s.t. r^x < DV -function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)) -} - -// (public) 0 if this == 0, 1 if this > 0 -function bnSigNum() { - if (this.s < 0) return -1 - else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0 - else return 1 -} - -// (protected) convert to radix string -function bnpToRadix(b) { - if (b == null) b = 10 - if (this.signum() == 0 || b < 2 || b > 36) return "0" - var cs = this.chunkSize(b) - var a = Math.pow(b, cs) - var d = nbv(a), - y = new BigInteger(), - z = new BigInteger(), - r = "" - this.divRemTo(d, y, z) - while (y.signum() > 0) { - r = (a + z.intValue()) - .toString(b) - .substr(1) + r - y.divRemTo(d, y, z) - } - return z.intValue() - .toString(b) + r -} - -// (protected) convert from radix string -function bnpFromRadix(s, b) { - var self = this - self.fromInt(0) - if (b == null) b = 10 - var cs = self.chunkSize(b) - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0 - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i) - if (x < 0) { - if (s.charAt(i) == "-" && self.signum() == 0) mi = true - continue - } - w = b * w + x - if (++j >= cs) { - self.dMultiply(d) - self.dAddOffset(w, 0) - j = 0 - w = 0 - } - } - if (j > 0) { - self.dMultiply(Math.pow(b, j)) - self.dAddOffset(w, 0) - } - if (mi) BigInteger.ZERO.subTo(self, self) -} - -// (protected) alternate constructor -function bnpFromNumber(a, b, c) { - var self = this - if ("number" == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) self.fromInt(1) - else { - self.fromNumber(a, c) - if (!self.testBit(a - 1)) // force MSB set - self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self) - if (self.isEven()) self.dAddOffset(1, 0); // force odd - while (!self.isProbablePrime(b)) { - self.dAddOffset(2, 0) - if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self) + if (is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r) + is1 = false + } else { + while (n > 1) { + z.sqrTo(r, r2) + z.sqrTo(r2, r) + n -= 2 } - } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7 - x.length = (a >> 3) + 1 - b.nextBytes(x) - if (t > 0) x[0] &= ((1 << t) - 1) - else x[0] = 0 - self.fromString(x, 256) - } -} - -// (public) convert to bigendian byte array -function bnToByteArray() { - var self = this - var i = self.t, - r = new Array() - r[0] = self.s - var p = self.DB - (i * self.DB) % 8, - d, k = 0 - if (i-- > 0) { - if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p) - r[k++] = d | (self.s << (self.DB - p)) - while (i >= 0) { - if (p < 8) { - d = (self[i] & ((1 << p) - 1)) << (8 - p) - d |= self[--i] >> (p += self.DB - 8) - } else { - d = (self[i] >> (p -= 8)) & 0xff - if (p <= 0) { - p += self.DB - --i - } - } - if ((d & 0x80) != 0) d |= -256 - if (k === 0 && (self.s & 0x80) != (d & 0x80))++k - if (k > 0 || d != self.s) r[k++] = d - } - } - return r -} - -function bnEquals(a) { - return (this.compareTo(a) == 0) -} - -function bnMin(a) { - return (this.compareTo(a) < 0) ? this : a -} - -function bnMax(a) { - return (this.compareTo(a) > 0) ? this : a -} - -// (protected) r = this op a (bitwise) -function bnpBitwiseTo(a, op, r) { - var self = this - var i, f, m = Math.min(a.t, self.t) - for (i = 0; i < m; ++i) r[i] = op(self[i], a[i]) - if (a.t < self.t) { - f = a.s & self.DM - for (i = m; i < self.t; ++i) r[i] = op(self[i], f) - r.t = self.t - } else { - f = self.s & self.DM - for (i = m; i < a.t; ++i) r[i] = op(f, a[i]) - r.t = a.t - } - r.s = op(self.s, a.s) - r.clamp() -} - -// (public) this & a -function op_and(x, y) { - return x & y -} - -function bnAnd(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_and, r) - return r -} - -// (public) this | a -function op_or(x, y) { - return x | y -} - -function bnOr(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_or, r) - return r -} - -// (public) this ^ a -function op_xor(x, y) { - return x ^ y -} - -function bnXor(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_xor, r) - return r -} - -// (public) this & ~a -function op_andnot(x, y) { - return x & ~y -} - -function bnAndNot(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_andnot, r) - return r -} - -// (public) ~this -function bnNot() { - var r = new BigInteger() - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i] - r.t = this.t - r.s = ~this.s - return r -} - -// (public) this << n -function bnShiftLeft(n) { - var r = new BigInteger() - if (n < 0) this.rShiftTo(-n, r) - else this.lShiftTo(n, r) - return r -} - -// (public) this >> n -function bnShiftRight(n) { - var r = new BigInteger() - if (n < 0) this.lShiftTo(-n, r) - else this.rShiftTo(n, r) - return r -} - -// return index of lowest 1-bit in x, x < 2^31 -function lbit(x) { - if (x == 0) return -1 - var r = 0 - if ((x & 0xffff) == 0) { - x >>= 16 - r += 16 - } - if ((x & 0xff) == 0) { - x >>= 8 - r += 8 - } - if ((x & 0xf) == 0) { - x >>= 4 - r += 4 - } - if ((x & 3) == 0) { - x >>= 2 - r += 2 - } - if ((x & 1) == 0)++r - return r -} - -// (public) returns index of lowest 1-bit (or -1 if none) -function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]) - if (this.s < 0) return this.t * this.DB - return -1 -} - -// return number of 1 bits in x -function cbit(x) { - var r = 0 - while (x != 0) { - x &= x - 1 - ++r - } - return r -} - -// (public) return number of set bits -function bnBitCount() { - var r = 0, - x = this.s & this.DM - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x) - return r -} - -// (public) true iff nth bit is set -function bnTestBit(n) { - var j = Math.floor(n / this.DB) - if (j >= this.t) return (this.s != 0) - return ((this[j] & (1 << (n % this.DB))) != 0) -} - -// (protected) this op (1<>= self.DB - } - if (a.t < self.t) { - c += a.s - while (i < self.t) { - c += self[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += self.s - } else { - c += self.s - while (i < a.t) { - c += a[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += a.s - } - r.s = (c < 0) ? -1 : 0 - if (c > 0) r[i++] = c - else if (c < -1) r[i++] = self.DV + c - r.t = i - r.clamp() -} - -// (public) this + a -function bnAdd(a) { - var r = new BigInteger() - this.addTo(a, r) - return r -} - -// (public) this - a -function bnSubtract(a) { - var r = new BigInteger() - this.subTo(a, r) - return r -} - -// (public) this * a -function bnMultiply(a) { - var r = new BigInteger() - this.multiplyTo(a, r) - return r -} - -// (public) this^2 -function bnSquare() { - var r = new BigInteger() - this.squareTo(r) - return r -} - -// (public) this / a -function bnDivide(a) { - var r = new BigInteger() - this.divRemTo(a, r, null) - return r -} - -// (public) this % a -function bnRemainder(a) { - var r = new BigInteger() - this.divRemTo(a, null, r) - return r -} - -// (public) [this/a,this%a] -function bnDivideAndRemainder(a) { - var q = new BigInteger(), - r = new BigInteger() - this.divRemTo(a, q, r) - return new Array(q, r) -} - -// (protected) this *= n, this >= 0, 1 < n < DV -function bnpDMultiply(n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t) - ++this.t - this.clamp() -} - -// (protected) this += n << w words, this >= 0 -function bnpDAddOffset(n, w) { - if (n == 0) return - while (this.t <= w) this[this.t++] = 0 - this[w] += n - while (this[w] >= this.DV) { - this[w] -= this.DV - if (++w >= this.t) this[this.t++] = 0 - ++this[w] - } -} - -// A "null" reducer -function NullExp() {} - -function nNop(x) { - return x -} - -function nMulTo(x, y, r) { - x.multiplyTo(y, r) -} - -function nSqrTo(x, r) { - x.squareTo(r) -} - -NullExp.prototype.convert = nNop -NullExp.prototype.revert = nNop -NullExp.prototype.mulTo = nMulTo -NullExp.prototype.sqrTo = nSqrTo - -// (public) this^e -function bnPow(e) { - return this.exp(e, new NullExp()) -} - -// (protected) r = lower n words of "this * a", a.t <= n -// "this" should be the larger one if appropriate. -function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n) - r.s = 0; // assumes a,this >= 0 - r.t = i - while (i > 0) r[--i] = 0 - var j - for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t) - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i) - r.clamp() -} - -// (protected) r = "this * a" without lower n words, n > 0 -// "this" should be the larger one if appropriate. -function bnpMultiplyUpperTo(a, n, r) { - --n - var i = r.t = this.t + a.t - n - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) r[i] = 0 - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n) - r.clamp() - r.drShiftTo(1, r) -} - -// Barrett modular reduction -function Barrett(m) { - // setup Barrett - this.r2 = new BigInteger() - this.q3 = new BigInteger() - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2) - this.mu = this.r2.divide(m) - this.m = m -} - -function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m) - else if (x.compareTo(this.m) < 0) return x - else { - var r = new BigInteger() - x.copyTo(r) - this.reduce(r) - return r - } -} - -function barrettRevert(x) { - return x -} - -// x = x mod m (HAC 14.42) -function barrettReduce(x) { - var self = this - x.drShiftTo(self.m.t - 1, self.r2) - if (x.t > self.m.t + 1) { - x.t = self.m.t + 1 - x.clamp() - } - self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3) - self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2) - while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1) - x.subTo(self.r2, x) - while (x.compareTo(self.m) >= 0) x.subTo(self.m, x) -} - -// r = x^2 mod m; x != r -function barrettSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -// r = x*y mod m; x,y != r -function barrettMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -Barrett.prototype.convert = barrettConvert -Barrett.prototype.revert = barrettRevert -Barrett.prototype.reduce = barrettReduce -Barrett.prototype.mulTo = barrettMulTo -Barrett.prototype.sqrTo = barrettSqrTo - -// (public) this^e % m (HAC 14.85) -function bnModPow(e, m) { - var i = e.bitLength(), - k, r = nbv(1), - z - if (i <= 0) return r - else if (i < 18) k = 1 - else if (i < 48) k = 3 - else if (i < 144) k = 4 - else if (i < 768) k = 5 - else k = 6 - if (i < 8) - z = new Classic(m) - else if (m.isEven()) - z = new Barrett(m) - else - z = new Montgomery(m) - - // precomputation - var g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1 - g[1] = z.convert(this) - if (k > 1) { - var g2 = new BigInteger() - z.sqrTo(g[1], g2) - while (n <= km) { - g[n] = new BigInteger() - z.mulTo(g2, g[n - 2], g[n]) - n += 2 - } - } - - var j = e.t - 1, - w, is1 = true, - r2 = new BigInteger(), - t - i = nbits(e[j]) - 1 - while (j >= 0) { - if (i >= k1) w = (e[j] >> (i - k1)) & km - else { - w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i) - if (j > 0) w |= e[j - 1] >> (this.DB + i - k1) - } - - n = k - while ((w & 1) == 0) { - w >>= 1 - --n - } - if ((i -= n) < 0) { - i += this.DB - --j - } - if (is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r) - is1 = false - } else { - while (n > 1) { - z.sqrTo(r, r2) - z.sqrTo(r2, r) - n -= 2 - } - if (n > 0) z.sqrTo(r, r2) - else { - t = r - r = r2 - r2 = t + if (n > 0) z.sqrTo(r, r2) + else { + t = r + r = r2 + r2 = t } z.mulTo(r2, g[w], r) - } - - while (j >= 0 && (e[j] & (1 << i)) == 0) { - z.sqrTo(r, r2) - t = r - r = r2 - r2 = t - if (--i < 0) { - i = this.DB - 1 - --j - } - } - } - return z.revert(r) -} - -// (public) gcd(this,a) (HAC 14.54) -function bnGCD(a) { - var x = (this.s < 0) ? this.negate() : this.clone() - var y = (a.s < 0) ? a.negate() : a.clone() - if (x.compareTo(y) < 0) { - var t = x - x = y - y = t - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit() - if (g < 0) return x - if (i < g) g = i - if (g > 0) { - x.rShiftTo(g, x) - y.rShiftTo(g, y) - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x) - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y) - if (x.compareTo(y) >= 0) { - x.subTo(y, x) - x.rShiftTo(1, x) - } else { - y.subTo(x, y) - y.rShiftTo(1, y) - } - } - if (g > 0) y.lShiftTo(g, y) - return y -} - -// (protected) this % n, n < 2^26 -function bnpModInt(n) { - if (n <= 0) return 0 - var d = this.DV % n, - r = (this.s < 0) ? n - 1 : 0 - if (this.t > 0) - if (d == 0) r = this[0] % n - else - for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n - return r -} - -// (public) 1/this % m (HAC 14.61) -function bnModInverse(m) { - var ac = m.isEven() - if (this.signum() === 0) throw new Error('division by zero') - if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO - var u = m.clone(), - v = this.clone() - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1) - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u) - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a) - b.subTo(m, b) - } - a.rShiftTo(1, a) - } else if (!b.isEven()) b.subTo(m, b) - b.rShiftTo(1, b) - } - while (v.isEven()) { - v.rShiftTo(1, v) - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c) - d.subTo(m, d) - } - c.rShiftTo(1, c) - } else if (!d.isEven()) d.subTo(m, d) - d.rShiftTo(1, d) - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u) - if (ac) a.subTo(c, a) - b.subTo(d, b) - } else { - v.subTo(u, v) - if (ac) c.subTo(a, c) - d.subTo(b, d) - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO - while (d.compareTo(m) >= 0) d.subTo(m, d) - while (d.signum() < 0) d.addTo(m, d) - return d -} - -var lowprimes = [ - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, - 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, - 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, - 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, - 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, - 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 -] - -var lplim = (1 << 26) / lowprimes[lowprimes.length - 1] - -// (public) test primality with certainty >= 1-.5^t -function bnIsProbablePrime(t) { - var i, x = this.abs() - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true - return false - } - if (x.isEven()) return false - i = 1 - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1 - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++] - m = x.modInt(m) - while (i < j) if (m % lowprimes[i++] == 0) return false - } - return x.millerRabin(t) -} - -// (protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE) - var k = n1.getLowestSetBit() - if (k <= 0) return false - var r = n1.shiftRight(k) - t = (t + 1) >> 1 - if (t > lowprimes.length) t = lowprimes.length - var a = new BigInteger(null) - var j, bases = [] - for (var i = 0; i < t; ++i) { - for (;;) { - j = lowprimes[Math.floor(Math.random() * lowprimes.length)] - if (bases.indexOf(j) == -1) break - } - bases.push(j) - a.fromInt(j) - var y = a.modPow(r, this) - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1 - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this) - if (y.compareTo(BigInteger.ONE) == 0) return false - } - if (y.compareTo(n1) != 0) return false - } - } - return true -} - -// protected -proto.chunkSize = bnpChunkSize -proto.toRadix = bnpToRadix -proto.fromRadix = bnpFromRadix -proto.fromNumber = bnpFromNumber -proto.bitwiseTo = bnpBitwiseTo -proto.changeBit = bnpChangeBit -proto.addTo = bnpAddTo -proto.dMultiply = bnpDMultiply -proto.dAddOffset = bnpDAddOffset -proto.multiplyLowerTo = bnpMultiplyLowerTo -proto.multiplyUpperTo = bnpMultiplyUpperTo -proto.modInt = bnpModInt -proto.millerRabin = bnpMillerRabin - -// public -proto.clone = bnClone -proto.intValue = bnIntValue -proto.byteValue = bnByteValue -proto.shortValue = bnShortValue -proto.signum = bnSigNum -proto.toByteArray = bnToByteArray -proto.equals = bnEquals -proto.min = bnMin -proto.max = bnMax -proto.and = bnAnd -proto.or = bnOr -proto.xor = bnXor -proto.andNot = bnAndNot -proto.not = bnNot -proto.shiftLeft = bnShiftLeft -proto.shiftRight = bnShiftRight -proto.getLowestSetBit = bnGetLowestSetBit -proto.bitCount = bnBitCount -proto.testBit = bnTestBit -proto.setBit = bnSetBit -proto.clearBit = bnClearBit -proto.flipBit = bnFlipBit -proto.add = bnAdd -proto.subtract = bnSubtract -proto.multiply = bnMultiply -proto.divide = bnDivide -proto.remainder = bnRemainder -proto.divideAndRemainder = bnDivideAndRemainder -proto.modPow = bnModPow -proto.modInverse = bnModInverse -proto.pow = bnPow -proto.gcd = bnGCD -proto.isProbablePrime = bnIsProbablePrime - -// JSBN-specific extension -proto.square = bnSquare - -// constants -BigInteger.ZERO = nbv(0) -BigInteger.ONE = nbv(1) -BigInteger.valueOf = nbv - -module.exports = BigInteger - - -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - -var assert = __webpack_require__(4) -var BigInteger = __webpack_require__(10) - -var Point = __webpack_require__(125) - -function Curve (p, a, b, Gx, Gy, n, h) { - this.p = p - this.a = a - this.b = b - this.G = Point.fromAffine(this, Gx, Gy) - this.n = n - this.h = h - - this.infinity = new Point(this, null, null, BigInteger.ZERO) - - // result caching - this.pOverFour = p.add(BigInteger.ONE).shiftRight(2) - - // determine size of p in bytes - this.pLength = Math.floor((this.p.bitLength() + 7) / 8) -} - -Curve.prototype.pointFromX = function (isOdd, x) { - var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p) - var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves - - var y = beta - if (beta.isEven() ^ !isOdd) { - y = this.p.subtract(y) // -y % p - } - - return Point.fromAffine(this, x, y) -} - -Curve.prototype.isInfinity = function (Q) { - if (Q === this.infinity) return true - - return Q.z.signum() === 0 && Q.y.signum() !== 0 -} - -Curve.prototype.isOnCurve = function (Q) { - if (this.isInfinity(Q)) return true - - var x = Q.affineX - var y = Q.affineY - var a = this.a - var b = this.b - var p = this.p - - // Check that xQ and yQ are integers in the interval [0, p - 1] - if (x.signum() < 0 || x.compareTo(p) >= 0) return false - if (y.signum() < 0 || y.compareTo(p) >= 0) return false - - // and check that y^2 = x^3 + ax + b (mod p) - var lhs = y.square().mod(p) - var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p) - return lhs.equals(rhs) -} - -/** - * Validate an elliptic curve point. - * - * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive - */ -Curve.prototype.validate = function (Q) { - // Check Q != O - assert(!this.isInfinity(Q), 'Point is at infinity') - assert(this.isOnCurve(Q), 'Point is not on the curve') - - // Check nQ = O (where Q is a scalar multiple of G) - var nQ = Q.multiply(this.n) - assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G') - - return true -} - -module.exports = Curve - - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var Buffer = __webpack_require__(2).Buffer -var inherits = __webpack_require__(1) -var HashBase = __webpack_require__(124) - -var ARRAY16 = new Array(16) - -var zl = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -] - -var zr = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -] - -var sl = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -] - -var sr = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -] - -var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] -var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] - -function RIPEMD160 () { - HashBase.call(this, 64) - - // state - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 -} - -inherits(RIPEMD160, HashBase) - -RIPEMD160.prototype._update = function () { - var words = ARRAY16 - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) - - var al = this._a | 0 - var bl = this._b | 0 - var cl = this._c | 0 - var dl = this._d | 0 - var el = this._e | 0 - - var ar = this._a | 0 - var br = this._b | 0 - var cr = this._c | 0 - var dr = this._d | 0 - var er = this._e | 0 - - // computation - for (var i = 0; i < 80; i += 1) { - var tl - var tr - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) - } - - al = el - el = dl - dl = rotl(cl, 10) - cl = bl - bl = tl - - ar = er - er = dr - dr = rotl(cr, 10) - cr = br - br = tr - } - - // update state - var t = (this._b + cl + dr) | 0 - this._b = (this._c + dl + er) | 0 - this._c = (this._d + el + ar) | 0 - this._d = (this._e + al + br) | 0 - this._e = (this._a + bl + cr) | 0 - this._a = t -} - -RIPEMD160.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80 - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64) - this._update() - this._blockOffset = 0 - } - - this._block.fill(0, this._blockOffset, 56) - this._block.writeUInt32LE(this._length[0], 56) - this._block.writeUInt32LE(this._length[1], 60) - this._update() - - // produce result - var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) - buffer.writeInt32LE(this._a, 0) - buffer.writeInt32LE(this._b, 4) - buffer.writeInt32LE(this._c, 8) - buffer.writeInt32LE(this._d, 12) - buffer.writeInt32LE(this._e, 16) - return buffer -} - -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} - -function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 -} - -function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 -} - -function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 -} - -function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 -} - -function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 -} - -module.exports = RIPEMD160 - - -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { - -var exports = module.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase() - - var Algorithm = exports[algorithm] - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - - return new Algorithm() -} - -exports.sha = __webpack_require__(241) -exports.sha1 = __webpack_require__(242) -exports.sha224 = __webpack_require__(243) -exports.sha256 = __webpack_require__(130) -exports.sha384 = __webpack_require__(244) -exports.sha512 = __webpack_require__(131) - - -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - -var inherits = __webpack_require__(1) -var Hash = __webpack_require__(27) -var Buffer = __webpack_require__(0).Buffer - -var K = [ - 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, - 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, - 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, - 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, - 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, - 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, - 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, - 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, - 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, - 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, - 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, - 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, - 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, - 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, - 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, - 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 -] - -var W = new Array(64) - -function Sha256 () { - this.init() - - this._w = W // new Array(64) - - Hash.call(this, 64, 56) -} - -inherits(Sha256, Hash) - -Sha256.prototype.init = function () { - this._a = 0x6a09e667 - this._b = 0xbb67ae85 - this._c = 0x3c6ef372 - this._d = 0xa54ff53a - this._e = 0x510e527f - this._f = 0x9b05688c - this._g = 0x1f83d9ab - this._h = 0x5be0cd19 - - return this -} - -function ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) -} - -function sigma1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) -} - -function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) -} - -function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) -} - -Sha256.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - var f = this._f | 0 - var g = this._g | 0 - var h = this._h | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 - var T2 = (sigma0(a) + maj(a, b, c)) | 0 - - h = g - g = f - f = e - e = (d + T1) | 0 - d = c - c = b - b = a - a = (T1 + T2) | 0 - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 - this._f = (f + this._f) | 0 - this._g = (g + this._g) | 0 - this._h = (h + this._h) | 0 -} - -Sha256.prototype._hash = function () { - var H = Buffer.allocUnsafe(32) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - H.writeInt32BE(this._h, 28) - - return H -} - -module.exports = Sha256 - - -/***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { - -var inherits = __webpack_require__(1) -var Hash = __webpack_require__(27) -var Buffer = __webpack_require__(0).Buffer - -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -] - -var W = new Array(160) - -function Sha512 () { - this.init() - this._w = W - - Hash.call(this, 128, 112) -} - -inherits(Sha512, Hash) - -Sha512.prototype.init = function () { - this._ah = 0x6a09e667 - this._bh = 0xbb67ae85 - this._ch = 0x3c6ef372 - this._dh = 0xa54ff53a - this._eh = 0x510e527f - this._fh = 0x9b05688c - this._gh = 0x1f83d9ab - this._hh = 0x5be0cd19 - - this._al = 0xf3bcc908 - this._bl = 0x84caa73b - this._cl = 0xfe94f82b - this._dl = 0x5f1d36f1 - this._el = 0xade682d1 - this._fl = 0x2b3e6c1f - this._gl = 0xfb41bd6b - this._hl = 0x137e2179 - - return this -} - -function Ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) -} - -function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) -} - -function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) -} - -function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) -} - -function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) -} - -function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) -} - -function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 -} - -Sha512.prototype._update = function (M) { - var W = this._w - - var ah = this._ah | 0 - var bh = this._bh | 0 - var ch = this._ch | 0 - var dh = this._dh | 0 - var eh = this._eh | 0 - var fh = this._fh | 0 - var gh = this._gh | 0 - var hh = this._hh | 0 - - var al = this._al | 0 - var bl = this._bl | 0 - var cl = this._cl | 0 - var dl = this._dl | 0 - var el = this._el | 0 - var fl = this._fl | 0 - var gl = this._gl | 0 - var hl = this._hl | 0 - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4) - W[i + 1] = M.readInt32BE(i * 4 + 4) - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2] - var xl = W[i - 15 * 2 + 1] - var gamma0 = Gamma0(xh, xl) - var gamma0l = Gamma0l(xl, xh) - - xh = W[i - 2 * 2] - xl = W[i - 2 * 2 + 1] - var gamma1 = Gamma1(xh, xl) - var gamma1l = Gamma1l(xl, xh) - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2] - var Wi7l = W[i - 7 * 2 + 1] - - var Wi16h = W[i - 16 * 2] - var Wi16l = W[i - 16 * 2 + 1] - - var Wil = (gamma0l + Wi7l) | 0 - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 - Wil = (Wil + gamma1l) | 0 - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 - Wil = (Wil + Wi16l) | 0 - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 - - W[i] = Wih - W[i + 1] = Wil - } - - for (var j = 0; j < 160; j += 2) { - Wih = W[j] - Wil = W[j + 1] - - var majh = maj(ah, bh, ch) - var majl = maj(al, bl, cl) - - var sigma0h = sigma0(ah, al) - var sigma0l = sigma0(al, ah) - var sigma1h = sigma1(eh, el) - var sigma1l = sigma1(el, eh) - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j] - var Kil = K[j + 1] - - var chh = Ch(eh, fh, gh) - var chl = Ch(el, fl, gl) - - var t1l = (hl + sigma1l) | 0 - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 - t1l = (t1l + chl) | 0 - t1h = (t1h + chh + getCarry(t1l, chl)) | 0 - t1l = (t1l + Kil) | 0 - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 - t1l = (t1l + Wil) | 0 - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0 - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 - - hh = gh - hl = gl - gh = fh - gl = fl - fh = eh - fl = el - el = (dl + t1l) | 0 - eh = (dh + t1h + getCarry(el, dl)) | 0 - dh = ch - dl = cl - ch = bh - cl = bl - bh = ah - bl = al - al = (t1l + t2l) | 0 - ah = (t1h + t2h + getCarry(al, t1l)) | 0 - } - - this._al = (this._al + al) | 0 - this._bl = (this._bl + bl) | 0 - this._cl = (this._cl + cl) | 0 - this._dl = (this._dl + dl) | 0 - this._el = (this._el + el) | 0 - this._fl = (this._fl + fl) | 0 - this._gl = (this._gl + gl) | 0 - this._hl = (this._hl + hl) | 0 - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 -} - -Sha512.prototype._hash = function () { - var H = Buffer.allocUnsafe(64) - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } - - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - writeInt64BE(this._gh, this._gl, 48) - writeInt64BE(this._hh, this._hl, 56) - - return H -} - -module.exports = Sha512 - - -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var ecdsa = __webpack_require__(251); -var hash = __webpack_require__(20); -var curve = __webpack_require__(75).getCurveByName('secp256k1'); -var assert = __webpack_require__(4); -var BigInteger = __webpack_require__(10); -var keyUtils = __webpack_require__(36); -var PublicKey = __webpack_require__(35); -var PrivateKey = __webpack_require__(50); - -module.exports = Signature; - -function Signature(r, s, i) { - assert.equal(r != null, true, 'Missing parameter'); - assert.equal(s != null, true, 'Missing parameter'); - assert.equal(i != null, true, 'Missing parameter'); - - /** - Verify signed data. - @arg {String|Buffer} data - full data - @arg {pubkey|PublicKey} pubkey - EOSKey.. - @arg {String} [encoding = 'utf8'] - data encoding (if data is a string) - @return {boolean} - */ - function verify(data, pubkey) { - var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8'; - - if (typeof data === 'string') { - data = Buffer.from(data, encoding); - } - assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); - data = hash.sha256(data); - return verifyHash(data, pubkey); - } - - /** - Verify a buffer of exactally 32 bytes in size (sha256(text)) - @arg {String|Buffer} dataSha256 - 32 byte buffer or string - @arg {String|PublicKey} pubkey - EOSKey.. - @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) - @return {boolean} - */ - function verifyHash(dataSha256, pubkey) { - var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex'; - - if (typeof dataSha256 === 'string') { - dataSha256 = Buffer.from(dataSha256, encoding); - } - if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 bytes required"); - - var publicKey = PublicKey(pubkey); - assert(publicKey, 'pubkey required'); - - return ecdsa.verify(curve, dataSha256, { r: r, s: s }, publicKey.Q); - }; - - /** @deprecated - Verify hex data by converting to a buffer then hashing. - @return {boolean} - */ - function verifyHex(hex, pubkey) { - console.log('Deprecated: use verify(data, pubkey, "hex")'); - - var buf = Buffer.from(hex, 'hex'); - return verify(buf, pubkey); - }; - - /** - Recover the public key used to create this signature using full data. - @arg {String|Buffer} data - full data - @arg {String} [encoding = 'utf8'] - data encoding (if string) - @return {PublicKey} - */ - function recover(data) { - var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'utf8'; - - if (typeof data === 'string') { - data = Buffer.from(data, encoding); - } - assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); - data = hash.sha256(data); - - return recoverHash(data); - }; - - /** - @arg {String|Buffer} dataSha256 - sha256 hash 32 byte buffer or hex string - @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) - @return {PublicKey} - */ - function recoverHash(dataSha256) { - var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'hex'; - - if (typeof dataSha256 === 'string') { - dataSha256 = Buffer.from(dataSha256, encoding); - } - if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) { - throw new Error("dataSha256: 32 byte String or buffer requred"); - } - - var e = BigInteger.fromBuffer(dataSha256); - var i2 = i; - i2 -= 27; - i2 = i2 & 3; - var Q = ecdsa.recoverPubKey(curve, e, { r: r, s: s, i: i }, i2); - return PublicKey.fromPoint(Q); - }; - - function toBuffer() { - var buf; - buf = new Buffer(65); - buf.writeUInt8(i, 0); - r.toBuffer(32).copy(buf, 1); - s.toBuffer(32).copy(buf, 33); - return buf; - }; - - function toHex() { - return toBuffer().toString("hex"); - }; - - var signatureCache = void 0; - - function toString() { - if (signatureCache) { - return signatureCache; - } - signatureCache = 'SIG_K1_' + keyUtils.checkEncode(toBuffer(), 'K1'); - return signatureCache; - } - - return { - r: r, s: s, i: i, - toBuffer: toBuffer, - verify: verify, - verifyHash: verifyHash, - verifyHex: verifyHex, // deprecated - recover: recover, - recoverHash: recoverHash, - toHex: toHex, - toString: toString, - - /** @deprecated use verify (same arguments and return) */ - verifyBuffer: function verifyBuffer() { - console.log('Deprecated: use signature.verify instead (same arguments)'); - return verify.apply(undefined, arguments); - }, - - /** @deprecated use recover (same arguments and return) */ - recoverPublicKey: function recoverPublicKey() { - console.log('Deprecated: use signature.recover instead (same arguments)'); - return recover.apply(undefined, arguments); - }, - - /** @deprecated use recoverHash (same arguments and return) */ - recoverPublicKeyFromBuffer: function recoverPublicKeyFromBuffer() { - console.log('Deprecated: use signature.recoverHash instead (same arguments)'); - return recoverHash.apply(undefined, arguments); - } - }; -} - -/** - Hash and sign arbitrary data. - - @arg {string|Buffer} data - full data - @arg {wif|PrivateKey} privateKey - @arg {String} [encoding = 'utf8'] - data encoding (if string) - - @return {Signature} -*/ -Signature.sign = function (data, privateKey) { - var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8'; - - if (typeof data === 'string') { - data = Buffer.from(data, encoding); - } - assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); - data = hash.sha256(data); - return Signature.signHash(data, privateKey); -}; - -/** - Sign a buffer of exactally 32 bytes in size (sha256(text)) - - @arg {string|Buffer} dataSha256 - 32 byte buffer or string - @arg {wif|PrivateKey} privateKey - @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) - - @return {Signature} -*/ -Signature.signHash = function (dataSha256, privateKey) { - var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex'; - - if (typeof dataSha256 === 'string') { - dataSha256 = Buffer.from(dataSha256, encoding); - } - if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 byte buffer requred"); - - privateKey = PrivateKey(privateKey); - assert(privateKey, 'privateKey required'); - - var der, e, ecsignature, i, lenR, lenS, nonce; - i = null; - nonce = 0; - e = BigInteger.fromBuffer(dataSha256); - while (true) { - ecsignature = ecdsa.sign(curve, dataSha256, privateKey.d, nonce++); - der = ecsignature.toDER(); - lenR = der[3]; - lenS = der[5 + lenR]; - if (lenR === 32 && lenS === 32) { - i = ecdsa.calcPubKeyRecoveryParam(curve, e, ecsignature, privateKey.toPublic().Q); - i += 4; // compressed - i += 27; // compact // 24 or 27 :( forcing odd-y 2nd key candidate) - break; - } - if (nonce % 10 === 0) { - console.log("WARN: " + nonce + " attempts to find canonical signature"); - } - } - return Signature(ecsignature.r, ecsignature.s, i); -}; - -Signature.fromBuffer = function (buf) { - var i, r, s; - assert(Buffer.isBuffer(buf), 'Buffer is required'); - assert.equal(buf.length, 65, 'Invalid signature length'); - i = buf.readUInt8(0); - assert.equal(i - 27, i - 27 & 7, 'Invalid signature parameter'); - r = BigInteger.fromBuffer(buf.slice(1, 33)); - s = BigInteger.fromBuffer(buf.slice(33)); - return Signature(r, s, i); -}; - -Signature.fromHex = function (hex) { - return Signature.fromBuffer(Buffer.from(hex, "hex")); -}; - -/** - @arg {string} signature - like SIG_K1_base58signature.. - @return {Signature} or `null` (invalid) -*/ -Signature.fromString = function (signature) { - try { - return Signature.fromStringOrThrow(signature); - } catch (e) { - return null; - } -}; - -/** - @arg {string} signature - like SIG_K1_base58signature.. - @throws {Error} invalid - @return {Signature} -*/ -Signature.fromStringOrThrow = function (signature) { - assert.equal(typeof signature === 'undefined' ? 'undefined' : _typeof(signature), 'string', 'signature'); - var match = signature.match(/^SIG_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/); - assert(match != null && match.length === 3, 'Expecting signature like: SIG_K1_base58signature..'); - - var _match = _slicedToArray(match, 3), - keyType = _match[1], - keyString = _match[2]; - - assert.equal(keyType, 'K1', 'K1 signature expected'); - return Signature.fromBuffer(keyUtils.checkDecode(keyString, keyType)); -}; - -/** - @arg {String|Signature} o - hex string - @return {Signature} -*/ -Signature.from = function (o) { - var signature = o ? o.r && o.s && o.i ? o : typeof o === 'string' && o.length === 130 ? Signature.fromHex(o) : typeof o === 'string' && o.length !== 130 ? Signature.fromStringOrThrow(o) : Buffer.isBuffer(o) ? Signature.fromBuffer(o) : null : o; /*null or undefined*/ - - if (!signature) { - throw new TypeError('signature should be a hex string or buffer'); - } - return signature; -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -module.exports = function enforce(type, value) { - // Copied from https://github.com/bitcoinjs/bitcoinjs-lib - switch (type) { - case 'Array': - { - if (Array.isArray(value)) return; - break; - } - - case 'Boolean': - { - if (typeof value === 'boolean') return; - break; - } - - case 'Buffer': - { - if (Buffer.isBuffer(value)) return; - break; - } - - case 'Number': - { - if (typeof value === 'number') return; - break; - } - - case 'String': - { - if (typeof value === 'string') return; - break; - } - - default: - { - if (getName(value.constructor) === getName(type)) return; - } - } - - throw new TypeError('Expected ' + (getName(type) || type) + ', got ' + value); -}; - -function getName(fn) { - // Why not fn.name: https://kangax.github.io/compat-table/es6/#function_name_property - var match = fn.toString().match(/function (.*?)\(/); - return match ? match[1] : null; -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var api = __webpack_require__(260); -var apiGen = __webpack_require__(263); -var processArgs = __webpack_require__(136); - -var EosApi = function EosApi(config) { - return apiGen('v1', api, config); -}; - -Object.assign(EosApi, { - processArgs: processArgs, - api: api, - - /** @deprecated */ - Testnet: function Testnet(config) { - console.error('deprecated, change EosApi.Testnet(..) to just EosApi(..)'); - return EosApi(config); - }, - - /** @deprecated */ - Localnet: function Localnet(config) { - console.error('deprecated, change EosApi.Localnet(..) to just EosApi(..)'); - return EosApi(config); - } -}); - -module.exports = EosApi; - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - -// the whatwg-fetch polyfill installs the fetch() function -// on the global object (window or self) -// -// Return that as the export for use in Webpack, Browserify etc. -__webpack_require__(264); -module.exports = self.fetch.bind(self); - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -module.exports = processArgs; - -/** - @typedef {object} processedArgs - Normalized object containing arguments, and - a chained promise and a callback. - - @property {object} params - normalized args only, parameters by name, no extra options or callback. - - @property {object} options - non-null or non-undefined return value from invocation of - optionsFormatter(optionsParam). - - @property {function} callback -chained to optional callback provided in args. Resolves - or rejects returnPromise. - - @property {Promise} returnPromise - promise is returned when no callback is provided in - args[args.length - 1]. Undefined when a callback is provided. -*/ -/** - Convert args array or object into a normalized value object. Suppoorts extra - options and(or) callback parameters. - - Per the Promise API feature promisifyAll (see also sb-promisify), the callback - (if provided) must always be last. - - @arg {Array|object} args - User-provided parameter object or array of parameters - @arg {Array} defParams - Names for the parameters. - @arg {string} methodName - for error reporting - @arg {function} [optionsFormatter(extraParam) = null] - optional callback used if an - extra optional (non-callback) parameter is provided. - - - @return {processedArgs} processedArgs - @throws TypeError - when parameter count is not exact (after adjusting for - options and callback) - - @example api.processArgs(args, ['account'], 'contract', optionsFormatter) -*/ -function processArgs(args, defParams) { - var methodName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'method'; - var optionsFormatter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - - var params = {}; - var options = {}; - - var expectedArgCount = defParams.length; - - // Extra callback argument? Last per promisifyAll standard. - var callbackArg = void 0; - if (typeof args[args.length - 1] === 'function') { - callbackArg = args[args.length - 1]; - args = args.slice(0, args.length - 1); - } - - var callback = void 0; - var returnPromise = void 0; - if (callbackArg) { - callback = function callback(err, result) { - if (err) { - callbackArg(err); - } else { - callbackArg(null, result); - } - }; - } else { - returnPromise = new Promise(function (resolve, reject) { - callback = function callback(err, result) { - if (err) { - reject(err); - } else { - resolve(result); - } - }; - }); - } - - // Look for the options parameter (after potential callback was removed) - if (typeof optionsFormatter === 'function' && args.length > 0 && (_typeof(args[0]) === 'object' && args.length === 2 || args.length === expectedArgCount + 1)) { - //An extra options argument - options = optionsFormatter(args[args.length - 1]); - if (options != null) { - // It is valid, remove it to avoid parameter count an error below - args = args.slice(0, args.length - 1); - } - } - - // Parameteters (args) can be ordered or an object - if (args.length === 1 && _typeof(args[0]) === 'object') { - params = args[0]; - } else { - // give ordered paramaters names - - if (args.length > expectedArgCount) { - // console.log('typeof defParams[expectedArgCount]', args) - throw new TypeError(methodName + ' is expecting ' + expectedArgCount + ' parameters but ' + args.length + ' where provided'); - } - - // convert ordered parameters into a value object by parameter name - var pos = 0; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = defParams[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var defParam = _step.value; - - params[defParam] = args[pos]; - pos++; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - return { params: params, options: options, callback: callback, returnPromise: returnPromise }; -} - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var schema = Object.assign({}, __webpack_require__(279), __webpack_require__(280), __webpack_require__(281)); - -module.exports = schema; - -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var _slicedToArray2 = __webpack_require__(79); - -var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); - -var _typeof2 = __webpack_require__(32); - -var _typeof3 = _interopRequireDefault(_typeof2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var assert = __webpack_require__(4); - -var _require = __webpack_require__(26), - Long = _require.Long; - -module.exports = { - ULong: ULong, - isName: isName, - encodeName: encodeName, // encode human readable name to uint64 (number string) - decodeName: decodeName, // decode from uint64 to human readable - encodeNameHex: function encodeNameHex(name) { - return Long.fromString(encodeName(name), true).toString(16); - }, - decodeNameHex: function decodeNameHex(hex) { - var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - return decodeName(Long.fromString(hex, true, 16).toString(), littleEndian); - }, - DecimalString: DecimalString, - DecimalPad: DecimalPad, - DecimalImply: DecimalImply, - DecimalUnimply: DecimalUnimply, - printAsset: printAsset, - parseAsset: parseAsset - - /** @private */ -};var signed = function signed(fn) { - return function () {}; -}; - -function ULong(value) { - var unsigned = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var radix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10; - - if (typeof value === 'number') { - // Some JSON libs use numbers for values under 53 bits or strings for larger. - // Accomidate but double-check it.. - if (value > Number.MAX_SAFE_INTEGER) throw new TypeError('value parameter overflow'); - - value = Long.fromString(String(value), unsigned, radix); - } else if (typeof value === 'string') { - value = Long.fromString(value, unsigned, radix); - } else if (!Long.isLong(value)) { - throw new TypeError('value parameter is a requied Long, Number or String'); - } - return value; -} - -function isName(str, err) { - try { - encodeName(str); - return true; - } catch (error) { - if (err) { - err(error); - } - return false; - } -} - -var charmap = '.12345abcdefghijklmnopqrstuvwxyz'; -var charidx = function charidx(ch) { - var idx = charmap.indexOf(ch); - if (idx === -1) throw new TypeError('Invalid character: \'' + ch + '\''); - - return idx; -}; - -/** Original Name encode and decode logic is in github.com/eosio/eos native.hpp */ - -/** - Encode a name (a base32 string) to a number. - - For performance reasons, the blockchain uses the numerical encoding of strings - for very common types like account names. - - @see types.hpp string_to_name - - @arg {string} name - A string to encode, up to 12 characters long. - @arg {string} [littleEndian = true] - Little or Bigendian encoding - - @return {string} - compressed string (from name arg). A string is - always used because a number could exceed JavaScript's 52 bit limit. -*/ -function encodeName(name) { - var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - if (typeof name !== 'string') throw new TypeError('name parameter is a required string'); - - if (name.length > 12) throw new TypeError('A name can be up to 12 characters long'); - - var bitstr = ''; - for (var i = 0; i <= 12; i++) { - // process all 64 bits (even if name is short) - var c = i < name.length ? charidx(name[i]) : 0; - var bitlen = i < 12 ? 5 : 4; - var bits = Number(c).toString(2); - if (bits.length > bitlen) { - throw new TypeError('Invalid name ' + name); - } - bits = '0'.repeat(bitlen - bits.length) + bits; - bitstr += bits; - } - - var value = Long.fromString(bitstr, true, 2); - - // convert to LITTLE_ENDIAN - var leHex = ''; - var bytes = littleEndian ? value.toBytesLE() : value.toBytesBE(); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = bytes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var b = _step.value; - - var n = Number(b).toString(16); - leHex += (n.length === 1 ? '0' : '') + n; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - var ulName = Long.fromString(leHex, true, 16).toString(); - - // console.log('encodeName', name, value.toString(), ulName.toString(), JSON.stringify(bitstr.split(/(.....)/).slice(1))) - - return ulName.toString(); -} - -/** - @arg {Long|String|number} value uint64 - @arg {string} [littleEndian = true] - Little or Bigendian encoding - - @return {string} -*/ -function decodeName(value) { - var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - value = ULong(value); - - // convert from LITTLE_ENDIAN - var beHex = ''; - var bytes = littleEndian ? value.toBytesLE() : value.toBytesBE(); - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = bytes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var b = _step2.value; - - var n = Number(b).toString(16); - beHex += (n.length === 1 ? '0' : '') + n; - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - beHex += '0'.repeat(16 - beHex.length); - - var fiveBits = Long.fromNumber(0x1f, true); - var fourBits = Long.fromNumber(0x0f, true); - var beValue = Long.fromString(beHex, true, 16); - - var str = ''; - var tmp = beValue; - - for (var i = 0; i <= 12; i++) { - var c = charmap[tmp.and(i === 0 ? fourBits : fiveBits)]; - str = c + str; - tmp = tmp.shiftRight(i === 0 ? 4 : 5); - } - str = str.replace(/\.+$/, ''); // remove trailing dots (all of them) - - // console.log('decodeName', str, beValue.toString(), value.toString(), JSON.stringify(beValue.toString(2).split(/(.....)/).slice(1))) - - return str; -} - -/** - Normalize and validate decimal string (potentially large values). Should - avoid internationalization issues if possible but will be safe and - throw an error for an invalid number. - - Normalization removes extra zeros or decimal. - - @return {string} value -*/ -function DecimalString(value) { - assert(value != null, 'value is required'); - value = value === 'object' && value.toString ? value.toString() : String(value); - - var neg = /^-/.test(value); - if (neg) { - value = value.substring(1); - } - - if (value[0] === '.') { - value = '0' + value; - } - - var part = value.split('.'); - assert(part.length <= 2, 'invalid decimal ' + value); - assert(/^\d+(,?\d)*\d*$/.test(part[0]), 'invalid decimal ' + value); - - if (part.length === 2) { - assert(/^\d*$/.test(part[1]), 'invalid decimal ' + value); - part[1] = part[1].replace(/0+$/, ''); // remove suffixing zeros - if (part[1] === '') { - part.pop(); - } - } - - part[0] = part[0].replace(/^0*/, ''); // remove leading zeros - if (part[0] === '') { - part[0] = '0'; - } - return (neg ? '-' : '') + part.join('.'); -} - -/** - Ensure a fixed number of decimal places. Safe for large numbers. - - @see ./format.test.js - - @example DecimalPad(10.2, 3) === '10.200' - - @arg {number|string|object.toString} num - @arg {number} [precision = null] - number of decimal places. Null skips - padding suffix but still applies number format normalization. - @return {string} decimal part is added and zero padded to match precision -*/ -function DecimalPad(num, precision) { - var value = DecimalString(num); - if (precision == null) { - return value; - } - - assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); - - var part = value.split('.'); - - if (precision === 0 && part.length === 1) { - return part[0]; - } - - if (part.length === 1) { - return part[0] + '.' + '0'.repeat(precision); - } else { - var pad = precision - part[1].length; - assert(pad >= 0, 'decimal \'' + value + '\' exceeds precision ' + precision); - return part[0] + '.' + part[1] + '0'.repeat(pad); - } -} - -/** Ensures proper trailing zeros then removes decimal place. */ -function DecimalImply(value, precision) { - return DecimalPad(value, precision).replace('.', ''); -} - -/** - Put the decimal place back in its position and return the normalized number - string (with any unnecessary zeros or an unnecessary decimal removed). - - @arg {string|number|value.toString} value 10000 - @arg {number} precision 4 - @return {number} 1.0000 -*/ -function DecimalUnimply(value, precision) { - assert(value != null, 'value is required'); - value = value === 'object' && value.toString ? value.toString() : String(value); - var neg = /^-/.test(value); - if (neg) { - value = value.substring(1); - } - assert(/^\d+$/.test(value), 'invalid whole number ' + value); - assert(precision != null, 'precision required'); - assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); - - // Ensure minimum length - var pad = precision - value.length; - if (pad > 0) { - value = '' + '0'.repeat(pad) + value; - } - - var dotIdx = value.length - precision; - value = value.slice(0, dotIdx) + '.' + value.slice(dotIdx); - return (neg ? '-' : '') + DecimalPad(value, precision); // Normalize -} - -/** @private for now, support for asset strings is limited -*/ -function printAsset(_ref) { - var amount = _ref.amount, - precision = _ref.precision, - symbol = _ref.symbol, - contract = _ref.contract; - - assert.equal(typeof symbol === 'undefined' ? 'undefined' : (0, _typeof3.default)(symbol), 'string', 'symbol is a required string'); - - if (amount != null && precision != null) { - amount = DecimalPad(amount, precision); - } - - var join = function join(e1, e2) { - return e1 == null ? '' : e2 == null ? '' : e1 + e2; - }; - - if (amount != null) { - // the amount contains the precision - return join(amount, ' ') + symbol + join('@', contract); - } - - return join(precision, ',') + symbol + join('@', contract); -} - -/** - Attempts to parse all forms of the asset strings (symbol, asset, or extended - versions). If the provided string contains any additional or appears to have - invalid information an error is thrown. - - @return {object} {amount, precision, symbol, contract} - @throws AssertionError -*/ -function parseAsset(str) { - var _str$split = str.split(' '), - _str$split2 = (0, _slicedToArray3.default)(_str$split, 1), - amountRaw = _str$split2[0]; - - var amountMatch = amountRaw.match(/^(-?[0-9]+(\.[0-9]+)?)( |$)/); - var amount = amountMatch ? amountMatch[1] : null; - - var precisionMatch = str.match(/(^| )([0-9]+),([A-Z]+)(@|$)/); - var precisionSymbol = precisionMatch ? Number(precisionMatch[2]) : null; - var precisionAmount = amount ? (amount.split('.')[1] || '').length : null; - var precision = precisionSymbol != null ? precisionSymbol : precisionAmount; - - var symbolMatch = str.match(/(^| |,)([A-Z]+)(@|$)/); - var symbol = symbolMatch ? symbolMatch[2] : null; - - var _str$split3 = str.split('@'), - _str$split4 = (0, _slicedToArray3.default)(_str$split3, 2), - _str$split4$ = _str$split4[1], - contractRaw = _str$split4$ === undefined ? '' : _str$split4$; - - var contract = /^[a-z0-5]+(\.[a-z0-5]+)*$/.test(contractRaw) ? contractRaw : null; - - var check = printAsset({ amount: amount, precision: precision, symbol: symbol, contract: contract }); - - assert.equal(str, check, 'Invalid asset string: ' + str + ' !== ' + check); - - if (precision != null) { - assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); - } - if (symbol != null) { - assert(symbol.length <= 7, 'Asset symbol is 7 characters or less'); - } - if (contract != null) { - assert(contract.length <= 12, 'Contract is 12 characters or less'); - } - - return { amount: amount, precision: precision, symbol: symbol, contract: contract }; -} - -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -const BLOCKCHAIN_SUPPORT = exports.BLOCKCHAIN_SUPPORT = 'blockchain_support'; - -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.BlockchainsArray = exports.Blockchains = undefined; - -var _keys = __webpack_require__(287); - -var _keys2 = _interopRequireDefault(_keys); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const Blockchains = exports.Blockchains = { - EOS: 'eos', - ETH: 'eth' -}; - -const BlockchainsArray = exports.BlockchainsArray = (0, _keys2.default)(Blockchains).map(key => ({ key, value: Blockchains[key] })); - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _assign = __webpack_require__(37); - -var _assign2 = _interopRequireDefault(_assign); - -var _promise = __webpack_require__(31); - -var _promise2 = _interopRequireDefault(_promise); - -var _asyncToGenerator2 = __webpack_require__(62); - -var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); - -var _SocketService = __webpack_require__(94); - -var _SocketService2 = _interopRequireDefault(_SocketService); - -var _PluginRepository = __webpack_require__(284); - -var _PluginRepository2 = _interopRequireDefault(_PluginRepository); - -__webpack_require__(135); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -let origin; - -const throwNoAuth = () => { - if (!holder.scatter.isExtension && !_SocketService2.default.isConnected()) throw new Error('Connect and Authenticate first - scatter.connect( pluginName )'); -}; - -const checkForPlugin = (resolve, tries = 0) => { - if (tries > 20) return; - if (holder.scatter.isExtension) return resolve(true); - setTimeout(() => checkForPlugin(resolve, tries + 1), 100); -}; - -class Scatter { - - constructor() { - const noIdFunc = () => { - if (!this.identity) throw new Error('No Identity'); - }; - - _PluginRepository2.default.signatureProviders().map(sigProvider => { - this[sigProvider.name] = sigProvider.signatureProvider(noIdFunc); - }); - - this.isExtension = false; - this.identity = null; - } - - isInstalled() { - return (0, _asyncToGenerator3.default)(function* () { - return new _promise2.default(function (resolve) { - setTimeout(function () { - resolve(false); - }, 3000); - - _promise2.default.race([checkForPlugin(resolve), _SocketService2.default.ping().then(function (found) { - console.log('found', found); - if (found) resolve(true); - })]); - - // Tries to set up Desktop Connection - }); - })(); - } - - connect(pluginName, options) { - var _this = this; - - return (0, _asyncToGenerator3.default)(function* () { - return new _promise2.default(function (resolve) { - if (!pluginName || !pluginName.length) throw new Error("You must specify a name for this connection"); - - // Setting options defaults - options = (0, _assign2.default)({ initTimeout: 10000, linkTimeout: 30000 }, options); - - // Auto failer - setTimeout(function () { - resolve(false); - }, options.initTimeout); - - // Defaults to scatter extension if exists - checkForPlugin(resolve); - - // Tries to set up Desktop Connection - _SocketService2.default.init(pluginName, options.linkTimeout); - _SocketService2.default.link().then((() => { - var _ref = (0, _asyncToGenerator3.default)(function* (authenticated) { - if (!authenticated) return false; - _this.identity = yield _this.getIdentityFromPermissions(); - return resolve(true); - }); - - return function (_x) { - return _ref.apply(this, arguments); - }; - })()); - }); - })(); - } - - disconnect() { - return _SocketService2.default.disconnect(); - } - - isConnected() { - return _SocketService2.default.isConnected(); - } - - getVersion() { - return _SocketService2.default.sendApiRequest({ - type: 'getVersion', - payload: {} - }); - } - - getIdentity(requiredFields) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'getOrRequestIdentity', - payload: { - fields: requiredFields - } - }).then(id => { - if (id) this.identity = id; - return id; - }); - } - - getIdentityFromPermissions() { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'identityFromPermissions', - payload: {} - }).then(id => { - if (id) this.identity = id; - return id; - }); - } - - forgetIdentity() { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'forgetIdentity', - payload: {} - }).then(res => { - this.identity = null; - return res; - }); - } - - authenticate() { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'authenticate', - payload: {} - }); - } - - getArbitrarySignature(publicKey, data, whatfor = '', isHash = false) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'requestArbitrarySignature', - payload: { - publicKey, - data, - whatfor, - isHash - } - }); - } - - getPublicKey(blockchain) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'getPublicKey', - payload: { blockchain } - }); - } - - linkAccount(publicKey, account, network) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'linkAccount', - payload: { publicKey, account, network } - }); - } - - suggestNetwork(network) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'requestAddNetwork', - payload: { - network - } - }); - } - - requestSignature(payload) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'requestSignature', - payload - }); - } - - createTransaction(blockchain, actions, account, network) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'createTransaction', - payload: { - blockchain, - actions, - account, - network - } - }); - } -} - -class Holder { - constructor(_scatter) { - this.scatter = _scatter; - } -} - -let holder = new Holder(new Scatter()); -if (typeof window !== 'undefined') { - - // Catching extension instead of Desktop - if (typeof document !== 'undefined') { - const bindScatterClassic = () => { - holder.scatter = window.scatter; - holder.scatter.isExtension = true; - holder.scatter.connect = () => new _promise2.default(resolve => resolve(true)); - }; - - if (typeof window.scatter !== 'undefined') bindScatterClassic();else document.addEventListener('scatterLoaded', () => bindScatterClassic()); - } - - if (!holder.scatter.isExtension) window.scatter = holder.scatter; -} - -exports.default = holder; - -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { - -__webpack_require__(143); -module.exports = __webpack_require__(5).Object.assign; - - -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { - -// 19.1.3.1 Object.assign(target, source) -var $export = __webpack_require__(11); - -$export($export.S + $export.F, 'Object', { assign: __webpack_require__(144) }); - - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// 19.1.2.1 Object.assign(target, source, ...) -var getKeys = __webpack_require__(28); -var gOPS = __webpack_require__(58); -var pIE = __webpack_require__(42); -var toObject = __webpack_require__(59); -var IObject = __webpack_require__(82); -var $assign = Object.assign; - -// should work with symbols and should have deterministic property order (V8 bug) -module.exports = !$assign || __webpack_require__(21)(function () { - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var S = Symbol(); - var K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function (k) { B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; -}) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var aLen = arguments.length; - var index = 1; - var getSymbols = gOPS.f; - var isEnum = pIE.f; - while (aLen > index) { - var S = IObject(arguments[index++]); - var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; - } return T; -} : $assign; - - -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { - -// false -> Array#indexOf -// true -> Array#includes -var toIObject = __webpack_require__(22); -var toLength = __webpack_require__(83); -var toAbsoluteIndex = __webpack_require__(146); -module.exports = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) if (IS_INCLUDES || index in O) { - if (O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; -}; - - -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - -var toInteger = __webpack_require__(54); -var max = Math.max; -var min = Math.min; -module.exports = function (index, length) { - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); -}; - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - -__webpack_require__(84); -__webpack_require__(43); -__webpack_require__(45); -__webpack_require__(155); -__webpack_require__(166); -__webpack_require__(167); -module.exports = __webpack_require__(5).Promise; - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - -var toInteger = __webpack_require__(54); -var defined = __webpack_require__(53); -// true -> String#at -// false -> String#codePointAt -module.exports = function (TO_STRING) { - return function (that, pos) { - var s = String(defined(that)); - var i = toInteger(pos); - var l = s.length; - var a, b; - if (i < 0 || i >= l) return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; -}; - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var create = __webpack_require__(87); -var descriptor = __webpack_require__(40); -var setToStringTag = __webpack_require__(44); -var IteratorPrototype = {}; - -// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() -__webpack_require__(12)(IteratorPrototype, __webpack_require__(7)('iterator'), function () { return this; }); - -module.exports = function (Constructor, NAME, next) { - Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); - setToStringTag(Constructor, NAME + ' Iterator'); -}; - - -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - -var dP = __webpack_require__(13); -var anObject = __webpack_require__(8); -var getKeys = __webpack_require__(28); - -module.exports = __webpack_require__(15) ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = getKeys(Properties); - var length = keys.length; - var i = 0; - var P; - while (length > i) dP.f(O, P = keys[i++], Properties[P]); - return O; -}; - - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - -// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) -var has = __webpack_require__(16); -var toObject = __webpack_require__(59); -var IE_PROTO = __webpack_require__(55)('IE_PROTO'); -var ObjectProto = Object.prototype; - -module.exports = Object.getPrototypeOf || function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; -}; - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var addToUnscopables = __webpack_require__(153); -var step = __webpack_require__(154); -var Iterators = __webpack_require__(23); -var toIObject = __webpack_require__(22); - -// 22.1.3.4 Array.prototype.entries() -// 22.1.3.13 Array.prototype.keys() -// 22.1.3.29 Array.prototype.values() -// 22.1.3.30 Array.prototype[@@iterator]() -module.exports = __webpack_require__(85)(Array, 'Array', function (iterated, kind) { - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind -// 22.1.5.2.1 %ArrayIteratorPrototype%.next() -}, function () { - var O = this._t; - var kind = this._k; - var index = this._i++; - if (!O || index >= O.length) { - this._t = undefined; - return step(1); - } - if (kind == 'keys') return step(0, index); - if (kind == 'values') return step(0, O[index]); - return step(0, [index, O[index]]); -}, 'values'); - -// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) -Iterators.Arguments = Iterators.Array; - -addToUnscopables('keys'); -addToUnscopables('values'); -addToUnscopables('entries'); - - -/***/ }), -/* 153 */ -/***/ (function(module, exports) { - -module.exports = function () { /* empty */ }; - - -/***/ }), -/* 154 */ -/***/ (function(module, exports) { - -module.exports = function (done, value) { - return { value: value, done: !!done }; -}; - - -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var LIBRARY = __webpack_require__(30); -var global = __webpack_require__(6); -var ctx = __webpack_require__(38); -var classof = __webpack_require__(60); -var $export = __webpack_require__(11); -var isObject = __webpack_require__(14); -var aFunction = __webpack_require__(39); -var anInstance = __webpack_require__(156); -var forOf = __webpack_require__(157); -var speciesConstructor = __webpack_require__(90); -var task = __webpack_require__(91).set; -var microtask = __webpack_require__(161)(); -var newPromiseCapabilityModule = __webpack_require__(61); -var perform = __webpack_require__(92); -var userAgent = __webpack_require__(162); -var promiseResolve = __webpack_require__(93); -var PROMISE = 'Promise'; -var TypeError = global.TypeError; -var process = global.process; -var versions = process && process.versions; -var v8 = versions && versions.v8 || ''; -var $Promise = global[PROMISE]; -var isNode = classof(process) == 'process'; -var empty = function () { /* empty */ }; -var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; -var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; - -var USE_NATIVE = !!function () { - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1); - var FakePromise = (promise.constructor = {})[__webpack_require__(7)('species')] = function (exec) { - exec(empty, empty); - }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') - && promise.then(empty) instanceof FakePromise - // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // we can't detect it synchronously, so just check versions - && v8.indexOf('6.6') !== 0 - && userAgent.indexOf('Chrome/66') === -1; - } catch (e) { /* empty */ } -}(); - -// helpers -var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; -}; -var notify = function (promise, isReject) { - if (promise._n) return; - promise._n = true; - var chain = promise._c; - microtask(function () { - var value = promise._v; - var ok = promise._s == 1; - var i = 0; - var run = function (reaction) { - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (promise._h == 2) onHandleUnhandled(promise); - promise._h = 1; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // may throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (e) { - if (domain && !exited) domain.exit(); - reject(e); - } - }; - while (chain.length > i) run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if (isReject && !promise._h) onUnhandled(promise); - }); -}; -var onUnhandled = function (promise) { - task.call(global, function () { - var value = promise._v; - var unhandled = isUnhandled(promise); - var result, handler, console; - if (unhandled) { - result = perform(function () { - if (isNode) { - process.emit('unhandledRejection', value, promise); - } else if (handler = global.onunhandledrejection) { - handler({ promise: promise, reason: value }); - } else if ((console = global.console) && console.error) { - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if (unhandled && result.e) throw result.v; - }); -}; -var isUnhandled = function (promise) { - return promise._h !== 1 && (promise._a || promise._c).length === 0; -}; -var onHandleUnhandled = function (promise) { - task.call(global, function () { - var handler; - if (isNode) { - process.emit('rejectionHandled', promise); - } else if (handler = global.onrejectionhandled) { - handler({ promise: promise, reason: promise._v }); - } - }); -}; -var $reject = function (value) { - var promise = this; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if (!promise._a) promise._a = promise._c.slice(); - notify(promise, true); -}; -var $resolve = function (value) { - var promise = this; - var then; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { - microtask(function () { - var wrapper = { _w: promise, _d: false }; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch (e) { - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap - } -}; - -// constructor polyfill -if (!USE_NATIVE) { - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor) { - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch (err) { - $reject.call(this, err); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(163)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected) { - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if (this._a) this._a.push(reaction); - if (this._s) notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - newPromiseCapabilityModule.f = newPromiseCapability = function (C) { - return C === $Promise || C === Wrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; -} - -$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); -__webpack_require__(44)($Promise, PROMISE); -__webpack_require__(164)(PROMISE); -Wrapper = __webpack_require__(5)[PROMISE]; - -// statics -$export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r) { - var capability = newPromiseCapability(this); - var $$reject = capability.reject; - $$reject(r); - return capability.promise; - } -}); -$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x) { - return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); - } -}); -$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(165)(function (iter) { - $Promise.all(iter)['catch'](empty); -})), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var values = []; - var index = 0; - var remaining = 1; - forOf(iterable, false, function (promise) { - var $index = index++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.e) reject(result.v); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var reject = capability.reject; - var result = perform(function () { - forOf(iterable, false, function (promise) { - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if (result.e) reject(result.v); - return capability.promise; - } -}); - - -/***/ }), -/* 156 */ -/***/ (function(module, exports) { + } -module.exports = function (it, Constructor, name, forbiddenField) { - if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { - throw TypeError(name + ': incorrect invocation!'); - } return it; -}; + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2) + t = r + r = r2 + r2 = t + if (--i < 0) { + i = this.DB - 1 + --j + } + } + } + return z.revert(r) +} +// (public) gcd(this,a) (HAC 14.54) +function bnGCD(a) { + var x = (this.s < 0) ? this.negate() : this.clone() + var y = (a.s < 0) ? a.negate() : a.clone() + if (x.compareTo(y) < 0) { + var t = x + x = y + y = t + } + var i = x.getLowestSetBit(), + g = y.getLowestSetBit() + if (g < 0) return x + if (i < g) g = i + if (g > 0) { + x.rShiftTo(g, x) + y.rShiftTo(g, y) + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x) + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y) + if (x.compareTo(y) >= 0) { + x.subTo(y, x) + x.rShiftTo(1, x) + } else { + y.subTo(x, y) + y.rShiftTo(1, y) + } + } + if (g > 0) y.lShiftTo(g, y) + return y +} -/***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { +// (protected) this % n, n < 2^26 +function bnpModInt(n) { + if (n <= 0) return 0 + var d = this.DV % n, + r = (this.s < 0) ? n - 1 : 0 + if (this.t > 0) + if (d == 0) r = this[0] % n + else + for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n + return r +} -var ctx = __webpack_require__(38); -var call = __webpack_require__(158); -var isArrayIter = __webpack_require__(159); -var anObject = __webpack_require__(8); -var toLength = __webpack_require__(83); -var getIterFn = __webpack_require__(89); -var BREAK = {}; -var RETURN = {}; -var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { - var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); - var f = ctx(fn, that, entries ? 2 : 1); - var index = 0; - var length, step, iterator, result; - if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if (result === BREAK || result === RETURN) return result; - } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { - result = call(iterator, f, step.value, entries); - if (result === BREAK || result === RETURN) return result; +// (public) 1/this % m (HAC 14.61) +function bnModInverse(m) { + var ac = m.isEven() + if (this.signum() === 0) throw new Error('division by zero') + if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO + var u = m.clone(), + v = this.clone() + var a = nbv(1), + b = nbv(0), + c = nbv(0), + d = nbv(1) + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u) + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a) + b.subTo(m, b) + } + a.rShiftTo(1, a) + } else if (!b.isEven()) b.subTo(m, b) + b.rShiftTo(1, b) + } + while (v.isEven()) { + v.rShiftTo(1, v) + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c) + d.subTo(m, d) + } + c.rShiftTo(1, c) + } else if (!d.isEven()) d.subTo(m, d) + d.rShiftTo(1, d) + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u) + if (ac) a.subTo(c, a) + b.subTo(d, b) + } else { + v.subTo(u, v) + if (ac) c.subTo(a, c) + d.subTo(b, d) + } } -}; -exports.BREAK = BREAK; -exports.RETURN = RETURN; + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO + while (d.compareTo(m) >= 0) d.subTo(m, d) + while (d.signum() < 0) d.addTo(m, d) + return d +} +var lowprimes = [ + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, + 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, + 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, + 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, + 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, + 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, + 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, + 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, + 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, + 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 +] -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { +var lplim = (1 << 26) / lowprimes[lowprimes.length - 1] -// call something on iterator step with safe closing on error -var anObject = __webpack_require__(8); -module.exports = function (iterator, fn, value, entries) { - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (e) { - var ret = iterator['return']; - if (ret !== undefined) anObject(ret.call(iterator)); - throw e; +// (public) test primality with certainty >= 1-.5^t +function bnIsProbablePrime(t) { + var i, x = this.abs() + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x[0] == lowprimes[i]) return true + return false } -}; - + if (x.isEven()) return false + i = 1 + while (i < lowprimes.length) { + var m = lowprimes[i], + j = i + 1 + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++] + m = x.modInt(m) + while (i < j) if (m % lowprimes[i++] == 0) return false + } + return x.millerRabin(t) +} -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { +// (protected) true if probably prime (HAC 4.24, Miller-Rabin) +function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE) + var k = n1.getLowestSetBit() + if (k <= 0) return false + var r = n1.shiftRight(k) + t = (t + 1) >> 1 + if (t > lowprimes.length) t = lowprimes.length + var a = new BigInteger(null) + var j, bases = [] + for (var i = 0; i < t; ++i) { + for (;;) { + j = lowprimes[Math.floor(Math.random() * lowprimes.length)] + if (bases.indexOf(j) == -1) break + } + bases.push(j) + a.fromInt(j) + var y = a.modPow(r, this) + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1 + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this) + if (y.compareTo(BigInteger.ONE) == 0) return false + } + if (y.compareTo(n1) != 0) return false + } + } + return true +} -// check on default Array iterator -var Iterators = __webpack_require__(23); -var ITERATOR = __webpack_require__(7)('iterator'); -var ArrayProto = Array.prototype; +// protected +proto.chunkSize = bnpChunkSize +proto.toRadix = bnpToRadix +proto.fromRadix = bnpFromRadix +proto.fromNumber = bnpFromNumber +proto.bitwiseTo = bnpBitwiseTo +proto.changeBit = bnpChangeBit +proto.addTo = bnpAddTo +proto.dMultiply = bnpDMultiply +proto.dAddOffset = bnpDAddOffset +proto.multiplyLowerTo = bnpMultiplyLowerTo +proto.multiplyUpperTo = bnpMultiplyUpperTo +proto.modInt = bnpModInt +proto.millerRabin = bnpMillerRabin -module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); -}; +// public +proto.clone = bnClone +proto.intValue = bnIntValue +proto.byteValue = bnByteValue +proto.shortValue = bnShortValue +proto.signum = bnSigNum +proto.toByteArray = bnToByteArray +proto.equals = bnEquals +proto.min = bnMin +proto.max = bnMax +proto.and = bnAnd +proto.or = bnOr +proto.xor = bnXor +proto.andNot = bnAndNot +proto.not = bnNot +proto.shiftLeft = bnShiftLeft +proto.shiftRight = bnShiftRight +proto.getLowestSetBit = bnGetLowestSetBit +proto.bitCount = bnBitCount +proto.testBit = bnTestBit +proto.setBit = bnSetBit +proto.clearBit = bnClearBit +proto.flipBit = bnFlipBit +proto.add = bnAdd +proto.subtract = bnSubtract +proto.multiply = bnMultiply +proto.divide = bnDivide +proto.remainder = bnRemainder +proto.divideAndRemainder = bnDivideAndRemainder +proto.modPow = bnModPow +proto.modInverse = bnModInverse +proto.pow = bnPow +proto.gcd = bnGCD +proto.isProbablePrime = bnIsProbablePrime +// JSBN-specific extension +proto.square = bnSquare -/***/ }), -/* 160 */ -/***/ (function(module, exports) { +// constants +BigInteger.ZERO = nbv(0) +BigInteger.ONE = nbv(1) +BigInteger.valueOf = nbv -// fast apply, http://jsperf.lnkit.com/fast-apply/5 -module.exports = function (fn, args, that) { - var un = that === undefined; - switch (args.length) { - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); -}; +module.exports = BigInteger /***/ }), -/* 161 */ +/* 106 */ /***/ (function(module, exports, __webpack_require__) { -var global = __webpack_require__(6); -var macrotask = __webpack_require__(91).set; -var Observer = global.MutationObserver || global.WebKitMutationObserver; -var process = global.process; -var Promise = global.Promise; -var isNode = __webpack_require__(29)(process) == 'process'; - -module.exports = function () { - var head, last, notify; - - var flush = function () { - var parent, fn; - if (isNode && (parent = process.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (e) { - if (head) notify(); - else last = undefined; - throw e; - } - } last = undefined; - if (parent) parent.enter(); - }; - - // Node.js - if (isNode) { - notify = function () { - process.nextTick(flush); - }; - // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 - } else if (Observer && !(global.navigator && global.navigator.standalone)) { - var toggle = true; - var node = document.createTextNode(''); - new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - var promise = Promise.resolve(undefined); - notify = function () { - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } +var assert = __webpack_require__(3) +var BigInteger = __webpack_require__(9) - return function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; -}; +var Point = __webpack_require__(104) +function Curve (p, a, b, Gx, Gy, n, h) { + this.p = p + this.a = a + this.b = b + this.G = Point.fromAffine(this, Gx, Gy) + this.n = n + this.h = h -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { + this.infinity = new Point(this, null, null, BigInteger.ZERO) -var global = __webpack_require__(6); -var navigator = global.navigator; + // result caching + this.pOverFour = p.add(BigInteger.ONE).shiftRight(2) -module.exports = navigator && navigator.userAgent || ''; + // determine size of p in bytes + this.pLength = Math.floor((this.p.bitLength() + 7) / 8) +} +Curve.prototype.pointFromX = function (isOdd, x) { + var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p) + var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { + var y = beta + if (beta.isEven() ^ !isOdd) { + y = this.p.subtract(y) // -y % p + } -var hide = __webpack_require__(12); -module.exports = function (target, src, safe) { - for (var key in src) { - if (safe && target[key]) target[key] = src[key]; - else hide(target, key, src[key]); - } return target; -}; + return Point.fromAffine(this, x, y) +} +Curve.prototype.isInfinity = function (Q) { + if (Q === this.infinity) return true -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { + return Q.z.signum() === 0 && Q.y.signum() !== 0 +} -"use strict"; +Curve.prototype.isOnCurve = function (Q) { + if (this.isInfinity(Q)) return true -var global = __webpack_require__(6); -var core = __webpack_require__(5); -var dP = __webpack_require__(13); -var DESCRIPTORS = __webpack_require__(15); -var SPECIES = __webpack_require__(7)('species'); + var x = Q.affineX + var y = Q.affineY + var a = this.a + var b = this.b + var p = this.p -module.exports = function (KEY) { - var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; - if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { - configurable: true, - get: function () { return this; } - }); -}; + // Check that xQ and yQ are integers in the interval [0, p - 1] + if (x.signum() < 0 || x.compareTo(p) >= 0) return false + if (y.signum() < 0 || y.compareTo(p) >= 0) return false + // and check that y^2 = x^3 + ax + b (mod p) + var lhs = y.square().mod(p) + var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p) + return lhs.equals(rhs) +} -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Validate an elliptic curve point. + * + * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive + */ +Curve.prototype.validate = function (Q) { + // Check Q != O + assert(!this.isInfinity(Q), 'Point is at infinity') + assert(this.isOnCurve(Q), 'Point is not on the curve') -var ITERATOR = __webpack_require__(7)('iterator'); -var SAFE_CLOSING = false; + // Check nQ = O (where Q is a scalar multiple of G) + var nQ = Q.multiply(this.n) + assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G') -try { - var riter = [7][ITERATOR](); - riter['return'] = function () { SAFE_CLOSING = true; }; - // eslint-disable-next-line no-throw-literal - Array.from(riter, function () { throw 2; }); -} catch (e) { /* empty */ } + return true +} -module.exports = function (exec, skipClosing) { - if (!skipClosing && !SAFE_CLOSING) return false; - var safe = false; - try { - var arr = [7]; - var iter = arr[ITERATOR](); - iter.next = function () { return { done: safe = true }; }; - arr[ITERATOR] = function () { return iter; }; - exec(arr); - } catch (e) { /* empty */ } - return safe; -}; +module.exports = Curve /***/ }), -/* 166 */ +/* 107 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// https://github.com/tc39/proposal-promise-finally - -var $export = __webpack_require__(11); -var core = __webpack_require__(5); -var global = __webpack_require__(6); -var speciesConstructor = __webpack_require__(90); -var promiseResolve = __webpack_require__(93); - -$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { - var C = speciesConstructor(this, core.Promise || global.Promise); - var isFunction = typeof onFinally == 'function'; - return this.then( - isFunction ? function (x) { - return promiseResolve(C, onFinally()).then(function () { return x; }); - } : onFinally, - isFunction ? function (e) { - return promiseResolve(C, onFinally()).then(function () { throw e; }); - } : onFinally - ); -} }); +var Buffer = __webpack_require__(2).Buffer +var inherits = __webpack_require__(1) +var HashBase = __webpack_require__(103) -/***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +var ARRAY16 = new Array(16) -// https://github.com/tc39/proposal-promise-try -var $export = __webpack_require__(11); -var newPromiseCapability = __webpack_require__(61); -var perform = __webpack_require__(92); +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] -$export($export.S, 'Promise', { 'try': function (callbackfn) { - var promiseCapability = newPromiseCapability.f(this); - var result = perform(callbackfn); - (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); - return promiseCapability.promise; -} }); +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] -var core = __webpack_require__(5); -var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify }); -module.exports = function stringify(it) { // eslint-disable-line no-unused-vars - return $JSON.stringify.apply($JSON, arguments); -}; +var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] +var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] +function RIPEMD160 () { + HashBase.call(this, 64) -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 +} +inherits(RIPEMD160, HashBase) -/** - * Module dependencies. - */ +RIPEMD160.prototype._update = function () { + var words = ARRAY16 + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) -var url = __webpack_require__(170); -var parser = __webpack_require__(63); -var Manager = __webpack_require__(98); -var debug = __webpack_require__(9)('socket.io-client'); + var al = this._a | 0 + var bl = this._b | 0 + var cl = this._c | 0 + var dl = this._d | 0 + var el = this._e | 0 -/** - * Module exports. - */ + var ar = this._a | 0 + var br = this._b | 0 + var cr = this._c | 0 + var dr = this._d | 0 + var er = this._e | 0 -module.exports = exports = lookup; + // computation + for (var i = 0; i < 80; i += 1) { + var tl + var tr + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) + } -/** - * Managers cache. - */ + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = tl -var cache = exports.managers = {}; + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = tr + } -/** - * Looks up an existing `Manager` for multiplexing. - * If the user summons: - * - * `io('http://localhost/a');` - * `io('http://localhost/b');` - * - * We reuse the existing instance based on same scheme/port/host, - * and we initialize sockets for each namespace. - * - * @api public - */ + // update state + var t = (this._b + cl + dr) | 0 + this._b = (this._c + dl + er) | 0 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t +} -function lookup (uri, opts) { - if (typeof uri === 'object') { - opts = uri; - uri = undefined; +RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 } - opts = opts || {}; - - var parsed = url(uri); - var source = parsed.source; - var id = parsed.id; - var path = parsed.path; - var sameNamespace = cache[id] && path in cache[id].nsps; - var newConnection = opts.forceNew || opts['force new connection'] || - false === opts.multiplex || sameNamespace; + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() - var io; + // produce result + var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer +} - if (newConnection) { - debug('ignoring socket cache for %s', source); - io = Manager(source, opts); - } else { - if (!cache[id]) { - debug('new io instance for %s', source); - cache[id] = Manager(source, opts); - } - io = cache[id]; - } - if (parsed.query && !opts.query) { - opts.query = parsed.query; - } - return io.socket(parsed.path, opts); +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) } -/** - * Protocol version. - * - * @api public - */ +function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 +} -exports.protocol = parser.protocol; +function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 +} -/** - * `connect`. - * - * @param {String} uri - * @api public - */ +function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 +} -exports.connect = lookup; +function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 +} -/** - * Expose constructors for standalone build. - * - * @api public - */ +function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 +} -exports.Manager = __webpack_require__(98); -exports.Socket = __webpack_require__(105); +module.exports = RIPEMD160 /***/ }), -/* 170 */ +/* 108 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(global) { -/** - * Module dependencies. - */ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() -var parseuri = __webpack_require__(96); -var debug = __webpack_require__(9)('socket.io-client:url'); + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') -/** - * Module exports. - */ + return new Algorithm() +} + +exports.sha = __webpack_require__(200) +exports.sha1 = __webpack_require__(201) +exports.sha224 = __webpack_require__(202) +exports.sha256 = __webpack_require__(109) +exports.sha384 = __webpack_require__(203) +exports.sha512 = __webpack_require__(110) -module.exports = url; + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { /** - * URL parser. + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * - * @param {String} url - * @param {Object} An object meant to mimic window.location. - * Defaults to window.location. - * @api public */ -function url (uri, loc) { - var obj = uri; - - // default to window.location - loc = loc || global.location; - if (null == uri) uri = loc.protocol + '//' + loc.host; +var inherits = __webpack_require__(1) +var Hash = __webpack_require__(24) +var Buffer = __webpack_require__(0).Buffer - // relative path support - if ('string' === typeof uri) { - if ('/' === uri.charAt(0)) { - if ('/' === uri.charAt(1)) { - uri = loc.protocol + uri; - } else { - uri = loc.host + uri; - } - } +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] - if (!/^(https?|wss?):\/\//.test(uri)) { - debug('protocol-less url %s', uri); - if ('undefined' !== typeof loc) { - uri = loc.protocol + '//' + uri; - } else { - uri = 'https://' + uri; - } - } +var W = new Array(64) - // parse - debug('parse %s', uri); - obj = parseuri(uri); - } +function Sha256 () { + this.init() - // make sure we treat `localhost:80` and `localhost` equally - if (!obj.port) { - if (/^(http|ws)$/.test(obj.protocol)) { - obj.port = '80'; - } else if (/^(http|ws)s$/.test(obj.protocol)) { - obj.port = '443'; - } - } + this._w = W // new Array(64) - obj.path = obj.path || '/'; + Hash.call(this, 64, 56) +} - var ipv6 = obj.host.indexOf(':') !== -1; - var host = ipv6 ? '[' + obj.host + ']' : obj.host; +inherits(Sha256, Hash) - // define unique id - obj.id = obj.protocol + '://' + host + ':' + obj.port; - // define href - obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port)); +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 - return obj; + return this } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { - +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __webpack_require__(172); +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} -/** - * Active `debug` instances. - */ -exports.instances = []; +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} -/** - * The currently active debug mode names, and names to skip. - */ +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} -exports.names = []; -exports.skips = []; +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ +Sha256.prototype._update = function (M) { + var W = this._w -exports.formatters = {}; + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 -function selectColor(namespace) { - var hash = 0, i; + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 } - return exports.colors[Math.abs(hash) % exports.colors.length]; + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - var prevTime; +Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) - function debug() { - // disabled? - if (!debug.enabled) return; + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) - var self = debug; + return H +} - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +module.exports = Sha256 - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - args[0] = exports.coerce(args[0]); +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } +var inherits = __webpack_require__(1) +var Hash = __webpack_require__(24) +var Buffer = __webpack_require__(0).Buffer - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +var W = new Array(160) - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); +function Sha512 () { + this.init() + this._w = W - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + Hash.call(this, 128, 112) +} - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; +inherits(Sha512, Hash) - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 - exports.instances.push(debug); + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 - return debug; + return this } -function destroy () { - var index = exports.instances.indexOf(this); - if (index !== -1) { - exports.instances.splice(index, 1); - return true; - } else { - return false; - } +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) } -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } - - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); - } +function maj (x, y, z) { + return (x & y) | (z & (x | y)) } -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) } -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) } -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) } +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} -/***/ }), -/* 172 */ -/***/ (function(module, exports) { +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} -/** - * Helpers. - */ +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ +Sha512.prototype._update = function (M) { + var W = this._w -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] -/** - * Pluralization helper. - */ + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; + W[i] = Wih + W[i + 1] = Wil } - return Math.ceil(ms / n) + ' ' + name + 's'; -} + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/*global Blob,File*/ + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) -/** - * Module requirements - */ + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) -var isArray = __webpack_require__(64); -var isBuf = __webpack_require__(97); -var toString = Object.prototype.toString; -var withNativeBlob = typeof global.Blob === 'function' || toString.call(global.Blob) === '[object BlobConstructor]'; -var withNativeFile = typeof global.File === 'function' || toString.call(global.File) === '[object FileConstructor]'; + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] -/** - * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. - * Anything with blobs or files should be fed through removeBlobs before coming - * here. - * - * @param {Object} packet - socket.io event packet - * @return {Object} with deconstructed packet and list of buffers - * @api public - */ + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) -exports.deconstructPacket = function(packet) { - var buffers = []; - var packetData = packet.data; - var pack = packet; - pack.data = _deconstructPacket(packetData, buffers); - pack.attachments = buffers.length; // number of binary 'attachments' - return {packet: pack, buffers: buffers}; -}; + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 -function _deconstructPacket(data, buffers) { - if (!data) return data; + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 - if (isBuf(data)) { - var placeholder = { _placeholder: true, num: buffers.length }; - buffers.push(data); - return placeholder; - } else if (isArray(data)) { - var newData = new Array(data.length); - for (var i = 0; i < data.length; i++) { - newData[i] = _deconstructPacket(data[i], buffers); - } - return newData; - } else if (typeof data === 'object' && !(data instanceof Date)) { - var newData = {}; - for (var key in data) { - newData[key] = _deconstructPacket(data[key], buffers); - } - return newData; + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 } - return data; -} -/** - * Reconstructs a binary packet from its placeholder packet and buffers - * - * @param {Object} packet - event packet with placeholders - * @param {Array} buffers - binary buffers to put in placeholder positions - * @return {Object} reconstructed packet - * @api public - */ + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 -exports.reconstructPacket = function(packet, buffers) { - packet.data = _reconstructPacket(packet.data, buffers); - packet.attachments = undefined; // no longer useful - return packet; -}; + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} -function _reconstructPacket(data, buffers) { - if (!data) return data; +Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) - if (data && data._placeholder) { - return buffers[data.num]; // appropriate buffer (should be natural order anyway) - } else if (isArray(data)) { - for (var i = 0; i < data.length; i++) { - data[i] = _reconstructPacket(data[i], buffers); - } - } else if (typeof data === 'object') { - for (var key in data) { - data[key] = _reconstructPacket(data[key], buffers); - } + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) } - return data; -} - -/** - * Asynchronously removes Blobs or Files from data via - * FileReader's readAsArrayBuffer method. Used before encoding - * data as msgpack. Calls callback with the blobless data. - * - * @param {Object} data - * @param {Function} callback - * @api private - */ + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) -exports.removeBlobs = function(data, callback) { - function _removeBlobs(obj, curKey, containingObject) { - if (!obj) return obj; + return H +} - // convert any blob - if ((withNativeBlob && obj instanceof Blob) || - (withNativeFile && obj instanceof File)) { - pendingBlobs++; +module.exports = Sha512 - // async filereader - var fileReader = new FileReader(); - fileReader.onload = function() { // this.result == arraybuffer - if (containingObject) { - containingObject[curKey] = this.result; - } - else { - bloblessData = this.result; - } - // if nothing pending its callback time - if(! --pendingBlobs) { - callback(bloblessData); - } - }; +/***/ }), +/* 111 */ +/***/ (function(module, exports, __webpack_require__) { - fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer - } else if (isArray(obj)) { // handle array - for (var i = 0; i < obj.length; i++) { - _removeBlobs(obj[i], i, obj); - } - } else if (typeof obj === 'object' && !isBuf(obj)) { // and object - for (var key in obj) { - _removeBlobs(obj[key], key, obj); - } - } - } +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { - var pendingBlobs = 0; - var bloblessData = data; - _removeBlobs(bloblessData); - if (!pendingBlobs) { - callback(bloblessData); - } -}; +var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { +var ecdsa = __webpack_require__(210); +var hash = __webpack_require__(18); +var curve = __webpack_require__(66).getCurveByName('secp256k1'); +var assert = __webpack_require__(3); +var BigInteger = __webpack_require__(9); +var keyUtils = __webpack_require__(33); +var PublicKey = __webpack_require__(32); +var PrivateKey = __webpack_require__(45); +module.exports = Signature; -module.exports = __webpack_require__(175); +function Signature(r, s, i) { + assert.equal(r != null, true, 'Missing parameter'); + assert.equal(s != null, true, 'Missing parameter'); + assert.equal(i != null, true, 'Missing parameter'); -/** - * Exports parser - * - * @api public - * - */ -module.exports.parser = __webpack_require__(25); + /** + Verify signed data. + @arg {String|Buffer} data - full data + @arg {pubkey|PublicKey} pubkey - EOSKey.. + @arg {String} [encoding = 'utf8'] - data encoding (if data is a string) + @return {boolean} + */ + function verify(data, pubkey) { + var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8'; + if (typeof data === 'string') { + data = Buffer.from(data, encoding); + } + assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); + data = hash.sha256(data); + return verifyHash(data, pubkey); + } -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { + /** + Verify a buffer of exactally 32 bytes in size (sha256(text)) + @arg {String|Buffer} dataSha256 - 32 byte buffer or string + @arg {String|PublicKey} pubkey - EOSKey.. + @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) + @return {boolean} + */ + function verifyHash(dataSha256, pubkey) { + var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex'; -/* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - */ + if (typeof dataSha256 === 'string') { + dataSha256 = Buffer.from(dataSha256, encoding); + } + if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 bytes required"); -var transports = __webpack_require__(99); -var Emitter = __webpack_require__(24); -var debug = __webpack_require__(9)('engine.io-client:socket'); -var index = __webpack_require__(104); -var parser = __webpack_require__(25); -var parseuri = __webpack_require__(96); -var parseqs = __webpack_require__(46); + var publicKey = PublicKey(pubkey); + assert(publicKey, 'pubkey required'); -/** - * Module exports. - */ + return ecdsa.verify(curve, dataSha256, { r: r, s: s }, publicKey.Q); + }; -module.exports = Socket; + /** @deprecated + Verify hex data by converting to a buffer then hashing. + @return {boolean} + */ + function verifyHex(hex, pubkey) { + console.log('Deprecated: use verify(data, pubkey, "hex")'); -/** - * Socket constructor. - * - * @param {String|Object} uri or options - * @param {Object} options - * @api public - */ + var buf = Buffer.from(hex, 'hex'); + return verify(buf, pubkey); + }; -function Socket (uri, opts) { - if (!(this instanceof Socket)) return new Socket(uri, opts); + /** + Recover the public key used to create this signature using full data. + @arg {String|Buffer} data - full data + @arg {String} [encoding = 'utf8'] - data encoding (if string) + @return {PublicKey} + */ + function recover(data) { + var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'utf8'; - opts = opts || {}; + if (typeof data === 'string') { + data = Buffer.from(data, encoding); + } + assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); + data = hash.sha256(data); - if (uri && 'object' === typeof uri) { - opts = uri; - uri = null; - } + return recoverHash(data); + }; - if (uri) { - uri = parseuri(uri); - opts.hostname = uri.host; - opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; - opts.port = uri.port; - if (uri.query) opts.query = uri.query; - } else if (opts.host) { - opts.hostname = parseuri(opts.host).host; - } + /** + @arg {String|Buffer} dataSha256 - sha256 hash 32 byte buffer or hex string + @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) + @return {PublicKey} + */ + function recoverHash(dataSha256) { + var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'hex'; - this.secure = null != opts.secure ? opts.secure - : (global.location && 'https:' === location.protocol); + if (typeof dataSha256 === 'string') { + dataSha256 = Buffer.from(dataSha256, encoding); + } + if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) { + throw new Error("dataSha256: 32 byte String or buffer requred"); + } - if (opts.hostname && !opts.port) { - // if no port is specified manually, use the protocol default - opts.port = this.secure ? '443' : '80'; - } + var e = BigInteger.fromBuffer(dataSha256); + var i2 = i; + i2 -= 27; + i2 = i2 & 3; + var Q = ecdsa.recoverPubKey(curve, e, { r: r, s: s, i: i }, i2); + return PublicKey.fromPoint(Q); + }; - this.agent = opts.agent || false; - this.hostname = opts.hostname || - (global.location ? location.hostname : 'localhost'); - this.port = opts.port || (global.location && location.port - ? location.port - : (this.secure ? 443 : 80)); - this.query = opts.query || {}; - if ('string' === typeof this.query) this.query = parseqs.decode(this.query); - this.upgrade = false !== opts.upgrade; - this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; - this.forceJSONP = !!opts.forceJSONP; - this.jsonp = false !== opts.jsonp; - this.forceBase64 = !!opts.forceBase64; - this.enablesXDR = !!opts.enablesXDR; - this.timestampParam = opts.timestampParam || 't'; - this.timestampRequests = opts.timestampRequests; - this.transports = opts.transports || ['polling', 'websocket']; - this.transportOptions = opts.transportOptions || {}; - this.readyState = ''; - this.writeBuffer = []; - this.prevBufferLen = 0; - this.policyPort = opts.policyPort || 843; - this.rememberUpgrade = opts.rememberUpgrade || false; - this.binaryType = null; - this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; - this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; + function toBuffer() { + var buf; + buf = new Buffer(65); + buf.writeUInt8(i, 0); + r.toBuffer(32).copy(buf, 1); + s.toBuffer(32).copy(buf, 33); + return buf; + }; - if (true === this.perMessageDeflate) this.perMessageDeflate = {}; - if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { - this.perMessageDeflate.threshold = 1024; - } + function toHex() { + return toBuffer().toString("hex"); + }; - // SSL options for Node.js client - this.pfx = opts.pfx || null; - this.key = opts.key || null; - this.passphrase = opts.passphrase || null; - this.cert = opts.cert || null; - this.ca = opts.ca || null; - this.ciphers = opts.ciphers || null; - this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized; - this.forceNode = !!opts.forceNode; + var signatureCache = void 0; - // other options for Node.js client - var freeGlobal = typeof global === 'object' && global; - if (freeGlobal.global === freeGlobal) { - if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { - this.extraHeaders = opts.extraHeaders; + function toString() { + if (signatureCache) { + return signatureCache; + } + signatureCache = 'SIG_K1_' + keyUtils.checkEncode(toBuffer(), 'K1'); + return signatureCache; } - if (opts.localAddress) { - this.localAddress = opts.localAddress; - } - } + return { + r: r, s: s, i: i, + toBuffer: toBuffer, + verify: verify, + verifyHash: verifyHash, + verifyHex: verifyHex, // deprecated + recover: recover, + recoverHash: recoverHash, + toHex: toHex, + toString: toString, - // set on handshake - this.id = null; - this.upgrades = null; - this.pingInterval = null; - this.pingTimeout = null; + /** @deprecated use verify (same arguments and return) */ + verifyBuffer: function verifyBuffer() { + console.log('Deprecated: use signature.verify instead (same arguments)'); + return verify.apply(undefined, arguments); + }, - // set on heartbeat - this.pingIntervalTimer = null; - this.pingTimeoutTimer = null; + /** @deprecated use recover (same arguments and return) */ + recoverPublicKey: function recoverPublicKey() { + console.log('Deprecated: use signature.recover instead (same arguments)'); + return recover.apply(undefined, arguments); + }, - this.open(); + /** @deprecated use recoverHash (same arguments and return) */ + recoverPublicKeyFromBuffer: function recoverPublicKeyFromBuffer() { + console.log('Deprecated: use signature.recoverHash instead (same arguments)'); + return recoverHash.apply(undefined, arguments); + } + }; } -Socket.priorWebsocketSuccess = false; - /** - * Mix in `Emitter`. - */ + Hash and sign arbitrary data. -Emitter(Socket.prototype); + @arg {string|Buffer} data - full data + @arg {wif|PrivateKey} privateKey + @arg {String} [encoding = 'utf8'] - data encoding (if string) -/** - * Protocol version. - * - * @api public - */ + @return {Signature} +*/ +Signature.sign = function (data, privateKey) { + var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8'; -Socket.protocol = parser.protocol; // this is an int + if (typeof data === 'string') { + data = Buffer.from(data, encoding); + } + assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); + data = hash.sha256(data); + return Signature.signHash(data, privateKey); +}; /** - * Expose deps for legacy compatibility - * and standalone browser access. - */ + Sign a buffer of exactally 32 bytes in size (sha256(text)) -Socket.Socket = Socket; -Socket.Transport = __webpack_require__(66); -Socket.transports = __webpack_require__(99); -Socket.parser = __webpack_require__(25); + @arg {string|Buffer} dataSha256 - 32 byte buffer or string + @arg {wif|PrivateKey} privateKey + @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) -/** - * Creates transport of the given type. - * - * @param {String} transport name - * @return {Transport} - * @api private - */ + @return {Signature} +*/ +Signature.signHash = function (dataSha256, privateKey) { + var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex'; -Socket.prototype.createTransport = function (name) { - debug('creating transport "%s"', name); - var query = clone(this.query); - - // append engine.io protocol identifier - query.EIO = parser.protocol; - - // transport name - query.transport = name; - - // per-transport options - var options = this.transportOptions[name] || {}; - - // session id if we already have one - if (this.id) query.sid = this.id; - - var transport = new transports[name]({ - query: query, - socket: this, - agent: options.agent || this.agent, - hostname: options.hostname || this.hostname, - port: options.port || this.port, - secure: options.secure || this.secure, - path: options.path || this.path, - forceJSONP: options.forceJSONP || this.forceJSONP, - jsonp: options.jsonp || this.jsonp, - forceBase64: options.forceBase64 || this.forceBase64, - enablesXDR: options.enablesXDR || this.enablesXDR, - timestampRequests: options.timestampRequests || this.timestampRequests, - timestampParam: options.timestampParam || this.timestampParam, - policyPort: options.policyPort || this.policyPort, - pfx: options.pfx || this.pfx, - key: options.key || this.key, - passphrase: options.passphrase || this.passphrase, - cert: options.cert || this.cert, - ca: options.ca || this.ca, - ciphers: options.ciphers || this.ciphers, - rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized, - perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate, - extraHeaders: options.extraHeaders || this.extraHeaders, - forceNode: options.forceNode || this.forceNode, - localAddress: options.localAddress || this.localAddress, - requestTimeout: options.requestTimeout || this.requestTimeout, - protocols: options.protocols || void (0) - }); + if (typeof dataSha256 === 'string') { + dataSha256 = Buffer.from(dataSha256, encoding); + } + if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 byte buffer requred"); - return transport; -}; + privateKey = PrivateKey(privateKey); + assert(privateKey, 'privateKey required'); -function clone (obj) { - var o = {}; - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - o[i] = obj[i]; + var der, e, ecsignature, i, lenR, lenS, nonce; + i = null; + nonce = 0; + e = BigInteger.fromBuffer(dataSha256); + while (true) { + ecsignature = ecdsa.sign(curve, dataSha256, privateKey.d, nonce++); + der = ecsignature.toDER(); + lenR = der[3]; + lenS = der[5 + lenR]; + if (lenR === 32 && lenS === 32) { + i = ecdsa.calcPubKeyRecoveryParam(curve, e, ecsignature, privateKey.toPublic().Q); + i += 4; // compressed + i += 27; // compact // 24 or 27 :( forcing odd-y 2nd key candidate) + break; + } + if (nonce % 10 === 0) { + console.log("WARN: " + nonce + " attempts to find canonical signature"); + } } - } - return o; -} - -/** - * Initializes transport to use and starts probe. - * - * @api private - */ -Socket.prototype.open = function () { - var transport; - if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { - transport = 'websocket'; - } else if (0 === this.transports.length) { - // Emit error on next tick so it can be listened to - var self = this; - setTimeout(function () { - self.emit('error', 'No transports available'); - }, 0); - return; - } else { - transport = this.transports[0]; - } - this.readyState = 'opening'; + return Signature(ecsignature.r, ecsignature.s, i); +}; - // Retry with the next transport if the transport is disabled (jsonp: false) - try { - transport = this.createTransport(transport); - } catch (e) { - this.transports.shift(); - this.open(); - return; - } +Signature.fromBuffer = function (buf) { + var i, r, s; + assert(Buffer.isBuffer(buf), 'Buffer is required'); + assert.equal(buf.length, 65, 'Invalid signature length'); + i = buf.readUInt8(0); + assert.equal(i - 27, i - 27 & 7, 'Invalid signature parameter'); + r = BigInteger.fromBuffer(buf.slice(1, 33)); + s = BigInteger.fromBuffer(buf.slice(33)); + return Signature(r, s, i); +}; - transport.open(); - this.setTransport(transport); +Signature.fromHex = function (hex) { + return Signature.fromBuffer(Buffer.from(hex, "hex")); }; /** - * Sets the current transport. Disables the existing one (if any). - * - * @api private - */ - -Socket.prototype.setTransport = function (transport) { - debug('setting transport %s', transport.name); - var self = this; - - if (this.transport) { - debug('clearing existing transport %s', this.transport.name); - this.transport.removeAllListeners(); - } - - // set up transport - this.transport = transport; - - // set up transport listeners - transport - .on('drain', function () { - self.onDrain(); - }) - .on('packet', function (packet) { - self.onPacket(packet); - }) - .on('error', function (e) { - self.onError(e); - }) - .on('close', function () { - self.onClose('transport close'); - }); + @arg {string} signature - like SIG_K1_base58signature.. + @return {Signature} or `null` (invalid) +*/ +Signature.fromString = function (signature) { + try { + return Signature.fromStringOrThrow(signature); + } catch (e) { + return null; + } }; /** - * Probes a transport. - * - * @param {String} transport name - * @api private - */ - -Socket.prototype.probe = function (name) { - debug('probing transport "%s"', name); - var transport = this.createTransport(name, { probe: 1 }); - var failed = false; - var self = this; - - Socket.priorWebsocketSuccess = false; - - function onTransportOpen () { - if (self.onlyBinaryUpgrades) { - var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; - failed = failed || upgradeLosesBinary; - } - if (failed) return; - - debug('probe transport "%s" opened', name); - transport.send([{ type: 'ping', data: 'probe' }]); - transport.once('packet', function (msg) { - if (failed) return; - if ('pong' === msg.type && 'probe' === msg.data) { - debug('probe transport "%s" pong', name); - self.upgrading = true; - self.emit('upgrading', transport); - if (!transport) return; - Socket.priorWebsocketSuccess = 'websocket' === transport.name; - - debug('pausing current transport "%s"', self.transport.name); - self.transport.pause(function () { - if (failed) return; - if ('closed' === self.readyState) return; - debug('changing transport and sending upgrade packet'); - - cleanup(); - - self.setTransport(transport); - transport.send([{ type: 'upgrade' }]); - self.emit('upgrade', transport); - transport = null; - self.upgrading = false; - self.flush(); - }); - } else { - debug('probe transport "%s" failed', name); - var err = new Error('probe error'); - err.transport = transport.name; - self.emit('upgradeError', err); - } - }); - } + @arg {string} signature - like SIG_K1_base58signature.. + @throws {Error} invalid + @return {Signature} +*/ +Signature.fromStringOrThrow = function (signature) { + assert.equal(typeof signature === 'undefined' ? 'undefined' : _typeof(signature), 'string', 'signature'); + var match = signature.match(/^SIG_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/); + assert(match != null && match.length === 3, 'Expecting signature like: SIG_K1_base58signature..'); - function freezeTransport () { - if (failed) return; + var _match = _slicedToArray(match, 3), + keyType = _match[1], + keyString = _match[2]; - // Any callback called by transport should be ignored since now - failed = true; + assert.equal(keyType, 'K1', 'K1 signature expected'); + return Signature.fromBuffer(keyUtils.checkDecode(keyString, keyType)); +}; - cleanup(); +/** + @arg {String|Signature} o - hex string + @return {Signature} +*/ +Signature.from = function (o) { + var signature = o ? o.r && o.s && o.i ? o : typeof o === 'string' && o.length === 130 ? Signature.fromHex(o) : typeof o === 'string' && o.length !== 130 ? Signature.fromStringOrThrow(o) : Buffer.isBuffer(o) ? Signature.fromBuffer(o) : null : o; /*null or undefined*/ - transport.close(); - transport = null; - } + if (!signature) { + throw new TypeError('signature should be a hex string or buffer'); + } + return signature; +}; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - // Handle any error that happens while probing - function onerror (err) { - var error = new Error('probe error: ' + err); - error.transport = transport.name; +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { - freezeTransport(); +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { - debug('probe transport "%s" failed because of error: %s', name, err); +module.exports = function enforce(type, value) { + // Copied from https://github.com/bitcoinjs/bitcoinjs-lib + switch (type) { + case 'Array': + { + if (Array.isArray(value)) return; + break; + } - self.emit('upgradeError', error); - } + case 'Boolean': + { + if (typeof value === 'boolean') return; + break; + } - function onTransportClose () { - onerror('transport closed'); - } + case 'Buffer': + { + if (Buffer.isBuffer(value)) return; + break; + } - // When the socket is closed while we're probing - function onclose () { - onerror('socket closed'); - } + case 'Number': + { + if (typeof value === 'number') return; + break; + } - // When the socket is upgraded while we're probing - function onupgrade (to) { - if (transport && to.name !== transport.name) { - debug('"%s" works - aborting "%s"', to.name, transport.name); - freezeTransport(); - } - } + case 'String': + { + if (typeof value === 'string') return; + break; + } - // Remove all listeners on the transport and on self - function cleanup () { - transport.removeListener('open', onTransportOpen); - transport.removeListener('error', onerror); - transport.removeListener('close', onTransportClose); - self.removeListener('close', onclose); - self.removeListener('upgrading', onupgrade); + default: + { + if (getName(value.constructor) === getName(type)) return; + } } - transport.once('open', onTransportOpen); - transport.once('error', onerror); - transport.once('close', onTransportClose); - - this.once('close', onclose); - this.once('upgrading', onupgrade); - - transport.open(); + throw new TypeError('Expected ' + (getName(type) || type) + ', got ' + value); }; -/** - * Called when connection is deemed open. - * - * @api public - */ - -Socket.prototype.onOpen = function () { - debug('socket open'); - this.readyState = 'open'; - Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; - this.emit('open'); - this.flush(); - - // we check for `readyState` in case an `open` - // listener already closed the socket - if ('open' === this.readyState && this.upgrade && this.transport.pause) { - debug('starting upgrade probes'); - for (var i = 0, l = this.upgrades.length; i < l; i++) { - this.probe(this.upgrades[i]); - } - } -}; +function getName(fn) { + // Why not fn.name: https://kangax.github.io/compat-table/es6/#function_name_property + var match = fn.toString().match(/function (.*?)\(/); + return match ? match[1] : null; +} +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) -/** - * Handles a packet. - * - * @api private - */ +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { -Socket.prototype.onPacket = function (packet) { - if ('opening' === this.readyState || 'open' === this.readyState || - 'closing' === this.readyState) { - debug('socket receive: type "%s", data "%s"', packet.type, packet.data); +"use strict"; - this.emit('packet', packet); - // Socket is live - any packet counts - this.emit('heartbeat'); +var api = __webpack_require__(220); +var apiGen = __webpack_require__(223); +var processArgs = __webpack_require__(115); - switch (packet.type) { - case 'open': - this.onHandshake(JSON.parse(packet.data)); - break; +var EosApi = function EosApi(config) { + return apiGen('v1', api, config); +}; - case 'pong': - this.setPing(); - this.emit('pong'); - break; +Object.assign(EosApi, { + processArgs: processArgs, + api: api, - case 'error': - var err = new Error('server error'); - err.code = packet.data; - this.onError(err); - break; + /** @deprecated */ + Testnet: function Testnet(config) { + console.error('deprecated, change EosApi.Testnet(..) to just EosApi(..)'); + return EosApi(config); + }, - case 'message': - this.emit('data', packet.data); - this.emit('message', packet.data); - break; - } - } else { - debug('packet received with socket readyState "%s"', this.readyState); + /** @deprecated */ + Localnet: function Localnet(config) { + console.error('deprecated, change EosApi.Localnet(..) to just EosApi(..)'); + return EosApi(config); } -}; +}); -/** - * Called upon handshake completion. - * - * @param {Object} handshake obj - * @api private - */ +module.exports = EosApi; -Socket.prototype.onHandshake = function (data) { - this.emit('handshake', data); - this.id = data.sid; - this.transport.query.sid = data.sid; - this.upgrades = this.filterUpgrades(data.upgrades); - this.pingInterval = data.pingInterval; - this.pingTimeout = data.pingTimeout; - this.onOpen(); - // In case open handler closes socket - if ('closed' === this.readyState) return; - this.setPing(); +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { - // Prolong liveness of socket on heartbeat - this.removeListener('heartbeat', this.onHeartbeat); - this.on('heartbeat', this.onHeartbeat); -}; +// the whatwg-fetch polyfill installs the fetch() function +// on the global object (window or self) +// +// Return that as the export for use in Webpack, Browserify etc. +__webpack_require__(224); +module.exports = self.fetch.bind(self); -/** - * Resets ping timeout. - * - * @api private - */ -Socket.prototype.onHeartbeat = function (timeout) { - clearTimeout(this.pingTimeoutTimer); - var self = this; - self.pingTimeoutTimer = setTimeout(function () { - if ('closed' === self.readyState) return; - self.onClose('ping timeout'); - }, timeout || (self.pingInterval + self.pingTimeout)); -}; +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Pings server every `this.pingInterval` and expects response - * within `this.pingTimeout` or closes connection. - * - * @api private - */ +"use strict"; -Socket.prototype.setPing = function () { - var self = this; - clearTimeout(self.pingIntervalTimer); - self.pingIntervalTimer = setTimeout(function () { - debug('writing ping packet - expecting pong within %sms', self.pingTimeout); - self.ping(); - self.onHeartbeat(self.pingTimeout); - }, self.pingInterval); -}; -/** -* Sends a ping packet. -* -* @api private -*/ +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; -Socket.prototype.ping = function () { - var self = this; - this.sendPacket('ping', function () { - self.emit('ping'); - }); -}; +module.exports = processArgs; /** - * Called on `drain` event - * - * @api private - */ + @typedef {object} processedArgs - Normalized object containing arguments, and + a chained promise and a callback. -Socket.prototype.onDrain = function () { - this.writeBuffer.splice(0, this.prevBufferLen); + @property {object} params - normalized args only, parameters by name, no extra options or callback. - // setting prevBufferLen = 0 is very important - // for example, when upgrading, upgrade packet is sent over, - // and a nonzero prevBufferLen could cause problems on `drain` - this.prevBufferLen = 0; + @property {object} options - non-null or non-undefined return value from invocation of + optionsFormatter(optionsParam). - if (0 === this.writeBuffer.length) { - this.emit('drain'); - } else { - this.flush(); - } -}; + @property {function} callback -chained to optional callback provided in args. Resolves + or rejects returnPromise. + @property {Promise} returnPromise - promise is returned when no callback is provided in + args[args.length - 1]. Undefined when a callback is provided. +*/ /** - * Flush write buffers. - * - * @api private - */ + Convert args array or object into a normalized value object. Suppoorts extra + options and(or) callback parameters. -Socket.prototype.flush = function () { - if ('closed' !== this.readyState && this.transport.writable && - !this.upgrading && this.writeBuffer.length) { - debug('flushing %d packets in socket', this.writeBuffer.length); - this.transport.send(this.writeBuffer); - // keep track of current length of writeBuffer - // splice writeBuffer and callbackBuffer on `drain` - this.prevBufferLen = this.writeBuffer.length; - this.emit('flush'); - } -}; + Per the Promise API feature promisifyAll (see also sb-promisify), the callback + (if provided) must always be last. -/** - * Sends a message. - * - * @param {String} message. - * @param {Function} callback function. - * @param {Object} options. - * @return {Socket} for chaining. - * @api public - */ + @arg {Array|object} args - User-provided parameter object or array of parameters + @arg {Array} defParams - Names for the parameters. + @arg {string} methodName - for error reporting + @arg {function} [optionsFormatter(extraParam) = null] - optional callback used if an + extra optional (non-callback) parameter is provided. -Socket.prototype.write = -Socket.prototype.send = function (msg, options, fn) { - this.sendPacket('message', msg, options, fn); - return this; -}; -/** - * Sends a packet. - * - * @param {String} packet type. - * @param {String} data. - * @param {Object} options. - * @param {Function} callback function. - * @api private - */ + @return {processedArgs} processedArgs + @throws TypeError - when parameter count is not exact (after adjusting for + options and callback) -Socket.prototype.sendPacket = function (type, data, options, fn) { - if ('function' === typeof data) { - fn = data; - data = undefined; - } + @example api.processArgs(args, ['account'], 'contract', optionsFormatter) +*/ +function processArgs(args, defParams) { + var methodName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'method'; + var optionsFormatter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + + var params = {}; + var options = {}; + + var expectedArgCount = defParams.length; - if ('function' === typeof options) { - fn = options; - options = null; + // Extra callback argument? Last per promisifyAll standard. + var callbackArg = void 0; + if (typeof args[args.length - 1] === 'function') { + callbackArg = args[args.length - 1]; + args = args.slice(0, args.length - 1); } - if ('closing' === this.readyState || 'closed' === this.readyState) { - return; + var callback = void 0; + var returnPromise = void 0; + if (callbackArg) { + callback = function callback(err, result) { + if (err) { + callbackArg(err); + } else { + callbackArg(null, result); + } + }; + } else { + returnPromise = new Promise(function (resolve, reject) { + callback = function callback(err, result) { + if (err) { + reject(err); + } else { + resolve(result); + } + }; + }); } - options = options || {}; - options.compress = false !== options.compress; + // Look for the options parameter (after potential callback was removed) + if (typeof optionsFormatter === 'function' && args.length > 0 && (_typeof(args[0]) === 'object' && args.length === 2 || args.length === expectedArgCount + 1)) { + //An extra options argument + options = optionsFormatter(args[args.length - 1]); + if (options != null) { + // It is valid, remove it to avoid parameter count an error below + args = args.slice(0, args.length - 1); + } + } - var packet = { - type: type, - data: data, - options: options - }; - this.emit('packetCreate', packet); - this.writeBuffer.push(packet); - if (fn) this.once('flush', fn); - this.flush(); -}; + // Parameteters (args) can be ordered or an object + if (args.length === 1 && _typeof(args[0]) === 'object') { + params = args[0]; + } else { + // give ordered paramaters names -/** - * Closes the connection. - * - * @api private - */ + if (args.length > expectedArgCount) { + // console.log('typeof defParams[expectedArgCount]', args) + throw new TypeError(methodName + ' is expecting ' + expectedArgCount + ' parameters but ' + args.length + ' where provided'); + } -Socket.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.readyState = 'closing'; + // convert ordered parameters into a value object by parameter name + var pos = 0; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - var self = this; + try { + for (var _iterator = defParams[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var defParam = _step.value; - if (this.writeBuffer.length) { - this.once('drain', function () { - if (this.upgrading) { - waitForUpgrade(); - } else { - close(); + params[defParam] = args[pos]; + pos++; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); } - }); - } else if (this.upgrading) { - waitForUpgrade(); - } else { - close(); + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } } } + return { params: params, options: options, callback: callback, returnPromise: returnPromise }; +} - function close () { - self.onClose('forced close'); - debug('socket closing - telling transport to close'); - self.transport.close(); - } - - function cleanupAndClose () { - self.removeListener('upgrade', cleanupAndClose); - self.removeListener('upgradeError', cleanupAndClose); - close(); - } +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { - function waitForUpgrade () { - // wait for upgrade to finish since we can't send packets while pausing a transport - self.once('upgrade', cleanupAndClose); - self.once('upgradeError', cleanupAndClose); - } +"use strict"; - return this; -}; -/** - * Called upon transport error - * - * @api private - */ +var schema = Object.assign({}, __webpack_require__(239), __webpack_require__(240), __webpack_require__(241)); -Socket.prototype.onError = function (err) { - debug('socket error %j', err); - Socket.priorWebsocketSuccess = false; - this.emit('error', err); - this.onClose('transport error', err); -}; +module.exports = schema; -/** - * Called upon transport close. - * - * @api private - */ +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { -Socket.prototype.onClose = function (reason, desc) { - if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { - debug('socket close with reason: "%s"', reason); - var self = this; +"use strict"; - // clear timers - clearTimeout(this.pingIntervalTimer); - clearTimeout(this.pingTimeoutTimer); - // stop event from firing again for transport - this.transport.removeAllListeners('close'); +var _slicedToArray2 = __webpack_require__(70); - // ensure transport won't stay open - this.transport.close(); +var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); - // ignore further transport communication - this.transport.removeAllListeners(); +var _typeof2 = __webpack_require__(29); - // set ready state - this.readyState = 'closed'; +var _typeof3 = _interopRequireDefault(_typeof2); - // clear session id - this.id = null; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // emit close event - this.emit('close', reason, desc); +var assert = __webpack_require__(3); - // clean buffers after, so users can still - // grab the buffers on `close` event - self.writeBuffer = []; - self.prevBufferLen = 0; - } -}; +var _require = __webpack_require__(23), + Long = _require.Long; -/** - * Filters upgrades, returning only those matching client transports. - * - * @param {Array} server upgrades - * @api private - * - */ +module.exports = { + ULong: ULong, + isName: isName, + encodeName: encodeName, // encode human readable name to uint64 (number string) + decodeName: decodeName, // decode from uint64 to human readable + encodeNameHex: function encodeNameHex(name) { + return Long.fromString(encodeName(name), true).toString(16); + }, + decodeNameHex: function decodeNameHex(hex) { + var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + return decodeName(Long.fromString(hex, true, 16).toString(), littleEndian); + }, + DecimalString: DecimalString, + DecimalPad: DecimalPad, + DecimalImply: DecimalImply, + DecimalUnimply: DecimalUnimply, + printAsset: printAsset, + parseAsset: parseAsset -Socket.prototype.filterUpgrades = function (upgrades) { - var filteredUpgrades = []; - for (var i = 0, j = upgrades.length; i < j; i++) { - if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); - } - return filteredUpgrades; + /** @private */ +};var signed = function signed(fn) { + return function () {}; }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 176 */ -/***/ (function(module, exports) { - +function ULong(value) { + var unsigned = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + var radix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10; -/** - * Module exports. - * - * Logic borrowed from Modernizr: - * - * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js - */ + if (typeof value === 'number') { + // Some JSON libs use numbers for values under 53 bits or strings for larger. + // Accomidate but double-check it.. + if (value > Number.MAX_SAFE_INTEGER) throw new TypeError('value parameter overflow'); -try { - module.exports = typeof XMLHttpRequest !== 'undefined' && - 'withCredentials' in new XMLHttpRequest(); -} catch (err) { - // if XMLHttp support is disabled in IE then it will throw - // when trying to create - module.exports = false; + value = Long.fromString(String(value), unsigned, radix); + } else if (typeof value === 'string') { + value = Long.fromString(value, unsigned, radix); + } else if (!Long.isLong(value)) { + throw new TypeError('value parameter is a requied Long, Number or String'); + } + return value; } +function isName(str, err) { + try { + encodeName(str); + return true; + } catch (error) { + if (err) { + err(error); + } + return false; + } +} -/***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { +var charmap = '.12345abcdefghijklmnopqrstuvwxyz'; +var charidx = function charidx(ch) { + var idx = charmap.indexOf(ch); + if (idx === -1) throw new TypeError('Invalid character: \'' + ch + '\''); -/* WEBPACK VAR INJECTION */(function(global) {/** - * Module requirements. - */ + return idx; +}; -var XMLHttpRequest = __webpack_require__(65); -var Polling = __webpack_require__(100); -var Emitter = __webpack_require__(24); -var inherit = __webpack_require__(47); -var debug = __webpack_require__(9)('engine.io-client:polling-xhr'); +/** Original Name encode and decode logic is in github.com/eosio/eos native.hpp */ /** - * Module exports. - */ + Encode a name (a base32 string) to a number. -module.exports = XHR; -module.exports.Request = Request; + For performance reasons, the blockchain uses the numerical encoding of strings + for very common types like account names. -/** - * Empty function - */ + @see types.hpp string_to_name -function empty () {} + @arg {string} name - A string to encode, up to 12 characters long. + @arg {string} [littleEndian = true] - Little or Bigendian encoding -/** - * XHR Polling constructor. - * - * @param {Object} opts - * @api public - */ + @return {string} - compressed string (from name arg). A string is + always used because a number could exceed JavaScript's 52 bit limit. +*/ +function encodeName(name) { + var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; -function XHR (opts) { - Polling.call(this, opts); - this.requestTimeout = opts.requestTimeout; - this.extraHeaders = opts.extraHeaders; + if (typeof name !== 'string') throw new TypeError('name parameter is a required string'); - if (global.location) { - var isSSL = 'https:' === location.protocol; - var port = location.port; + if (name.length > 12) throw new TypeError('A name can be up to 12 characters long'); - // some user agents have empty `location.port` - if (!port) { - port = isSSL ? 443 : 80; + var bitstr = ''; + for (var i = 0; i <= 12; i++) { + // process all 64 bits (even if name is short) + var c = i < name.length ? charidx(name[i]) : 0; + var bitlen = i < 12 ? 5 : 4; + var bits = Number(c).toString(2); + if (bits.length > bitlen) { + throw new TypeError('Invalid name ' + name); } - - this.xd = opts.hostname !== global.location.hostname || - port !== opts.port; - this.xs = opts.secure !== isSSL; + bits = '0'.repeat(bitlen - bits.length) + bits; + bitstr += bits; } -} - -/** - * Inherits from Polling. - */ -inherit(XHR, Polling); - -/** - * XHR supports binary - */ + var value = Long.fromString(bitstr, true, 2); -XHR.prototype.supportsBinary = true; + // convert to LITTLE_ENDIAN + var leHex = ''; + var bytes = littleEndian ? value.toBytesLE() : value.toBytesBE(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; -/** - * Creates a request. - * - * @param {String} method - * @api private - */ + try { + for (var _iterator = bytes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var b = _step.value; -XHR.prototype.request = function (opts) { - opts = opts || {}; - opts.uri = this.uri(); - opts.xd = this.xd; - opts.xs = this.xs; - opts.agent = this.agent || false; - opts.supportsBinary = this.supportsBinary; - opts.enablesXDR = this.enablesXDR; + var n = Number(b).toString(16); + leHex += (n.length === 1 ? '0' : '') + n; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } - // SSL options for Node.js client - opts.pfx = this.pfx; - opts.key = this.key; - opts.passphrase = this.passphrase; - opts.cert = this.cert; - opts.ca = this.ca; - opts.ciphers = this.ciphers; - opts.rejectUnauthorized = this.rejectUnauthorized; - opts.requestTimeout = this.requestTimeout; + var ulName = Long.fromString(leHex, true, 16).toString(); - // other options for Node.js client - opts.extraHeaders = this.extraHeaders; + // console.log('encodeName', name, value.toString(), ulName.toString(), JSON.stringify(bitstr.split(/(.....)/).slice(1))) - return new Request(opts); -}; + return ulName.toString(); +} /** - * Sends data. - * - * @param {String} data to send. - * @param {Function} called upon flush. - * @api private - */ + @arg {Long|String|number} value uint64 + @arg {string} [littleEndian = true] - Little or Bigendian encoding -XHR.prototype.doWrite = function (data, fn) { - var isBinary = typeof data !== 'string' && data !== undefined; - var req = this.request({ method: 'POST', data: data, isBinary: isBinary }); - var self = this; - req.on('success', fn); - req.on('error', function (err) { - self.onError('xhr post error', err); - }); - this.sendXhr = req; -}; + @return {string} +*/ +function decodeName(value) { + var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; -/** - * Starts a poll cycle. - * - * @api private - */ + value = ULong(value); -XHR.prototype.doPoll = function () { - debug('xhr poll'); - var req = this.request(); - var self = this; - req.on('data', function (data) { - self.onData(data); - }); - req.on('error', function (err) { - self.onError('xhr poll error', err); - }); - this.pollXhr = req; -}; + // convert from LITTLE_ENDIAN + var beHex = ''; + var bytes = littleEndian ? value.toBytesLE() : value.toBytesBE(); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; -/** - * Request constructor - * - * @param {Object} options - * @api public - */ + try { + for (var _iterator2 = bytes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var b = _step2.value; -function Request (opts) { - this.method = opts.method || 'GET'; - this.uri = opts.uri; - this.xd = !!opts.xd; - this.xs = !!opts.xs; - this.async = false !== opts.async; - this.data = undefined !== opts.data ? opts.data : null; - this.agent = opts.agent; - this.isBinary = opts.isBinary; - this.supportsBinary = opts.supportsBinary; - this.enablesXDR = opts.enablesXDR; - this.requestTimeout = opts.requestTimeout; - - // SSL options for Node.js client - this.pfx = opts.pfx; - this.key = opts.key; - this.passphrase = opts.passphrase; - this.cert = opts.cert; - this.ca = opts.ca; - this.ciphers = opts.ciphers; - this.rejectUnauthorized = opts.rejectUnauthorized; - - // other options for Node.js client - this.extraHeaders = opts.extraHeaders; - - this.create(); -} + var n = Number(b).toString(16); + beHex += (n.length === 1 ? '0' : '') + n; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } -/** - * Mix in `Emitter`. - */ + beHex += '0'.repeat(16 - beHex.length); -Emitter(Request.prototype); + var fiveBits = Long.fromNumber(0x1f, true); + var fourBits = Long.fromNumber(0x0f, true); + var beValue = Long.fromString(beHex, true, 16); -/** - * Creates the XHR object and sends the request. - * - * @api private - */ + var str = ''; + var tmp = beValue; -Request.prototype.create = function () { - var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR }; + for (var i = 0; i <= 12; i++) { + var c = charmap[tmp.and(i === 0 ? fourBits : fiveBits)]; + str = c + str; + tmp = tmp.shiftRight(i === 0 ? 4 : 5); + } + str = str.replace(/\.+$/, ''); // remove trailing dots (all of them) - // SSL options for Node.js client - opts.pfx = this.pfx; - opts.key = this.key; - opts.passphrase = this.passphrase; - opts.cert = this.cert; - opts.ca = this.ca; - opts.ciphers = this.ciphers; - opts.rejectUnauthorized = this.rejectUnauthorized; + // console.log('decodeName', str, beValue.toString(), value.toString(), JSON.stringify(beValue.toString(2).split(/(.....)/).slice(1))) - var xhr = this.xhr = new XMLHttpRequest(opts); - var self = this; + return str; +} - try { - debug('xhr open %s: %s', this.method, this.uri); - xhr.open(this.method, this.uri, this.async); - try { - if (this.extraHeaders) { - xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); - for (var i in this.extraHeaders) { - if (this.extraHeaders.hasOwnProperty(i)) { - xhr.setRequestHeader(i, this.extraHeaders[i]); - } - } - } - } catch (e) {} +/** + Normalize and validate decimal string (potentially large values). Should + avoid internationalization issues if possible but will be safe and + throw an error for an invalid number. - if ('POST' === this.method) { - try { - if (this.isBinary) { - xhr.setRequestHeader('Content-type', 'application/octet-stream'); - } else { - xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); - } - } catch (e) {} - } + Normalization removes extra zeros or decimal. - try { - xhr.setRequestHeader('Accept', '*/*'); - } catch (e) {} + @return {string} value +*/ +function DecimalString(value) { + assert(value != null, 'value is required'); + value = value === 'object' && value.toString ? value.toString() : String(value); - // ie6 check - if ('withCredentials' in xhr) { - xhr.withCredentials = true; - } + var neg = /^-/.test(value); + if (neg) { + value = value.substring(1); + } - if (this.requestTimeout) { - xhr.timeout = this.requestTimeout; - } + if (value[0] === '.') { + value = '0' + value; + } - if (this.hasXDR()) { - xhr.onload = function () { - self.onLoad(); - }; - xhr.onerror = function () { - self.onError(xhr.responseText); - }; - } else { - xhr.onreadystatechange = function () { - if (xhr.readyState === 2) { - try { - var contentType = xhr.getResponseHeader('Content-Type'); - if (self.supportsBinary && contentType === 'application/octet-stream') { - xhr.responseType = 'arraybuffer'; - } - } catch (e) {} - } - if (4 !== xhr.readyState) return; - if (200 === xhr.status || 1223 === xhr.status) { - self.onLoad(); - } else { - // make sure the `error` event handler that's user-set - // does not throw in the same tick and gets caught here - setTimeout(function () { - self.onError(xhr.status); - }, 0); - } - }; - } + var part = value.split('.'); + assert(part.length <= 2, 'invalid decimal ' + value); + assert(/^\d+(,?\d)*\d*$/.test(part[0]), 'invalid decimal ' + value); - debug('xhr data %s', this.data); - xhr.send(this.data); - } catch (e) { - // Need to defer since .create() is called directly fhrom the constructor - // and thus the 'error' event can only be only bound *after* this exception - // occurs. Therefore, also, we cannot throw here at all. - setTimeout(function () { - self.onError(e); - }, 0); - return; + if (part.length === 2) { + assert(/^\d*$/.test(part[1]), 'invalid decimal ' + value); + part[1] = part[1].replace(/0+$/, ''); // remove suffixing zeros + if (part[1] === '') { + part.pop(); + } } - if (global.document) { - this.index = Request.requestsCount++; - Request.requests[this.index] = this; + part[0] = part[0].replace(/^0*/, ''); // remove leading zeros + if (part[0] === '') { + part[0] = '0'; } -}; + return (neg ? '-' : '') + part.join('.'); +} /** - * Called upon successful response. - * - * @api private - */ + Ensure a fixed number of decimal places. Safe for large numbers. + + @see ./format.test.js + + @example DecimalPad(10.2, 3) === '10.200' + + @arg {number|string|object.toString} num + @arg {number} [precision = null] - number of decimal places. Null skips + padding suffix but still applies number format normalization. + @return {string} decimal part is added and zero padded to match precision +*/ +function DecimalPad(num, precision) { + var value = DecimalString(num); + if (precision == null) { + return value; + } -Request.prototype.onSuccess = function () { - this.emit('success'); - this.cleanup(); -}; + assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); -/** - * Called if we have data. - * - * @api private - */ + var part = value.split('.'); -Request.prototype.onData = function (data) { - this.emit('data', data); - this.onSuccess(); -}; + if (precision === 0 && part.length === 1) { + return part[0]; + } -/** - * Called upon error. - * - * @api private - */ + if (part.length === 1) { + return part[0] + '.' + '0'.repeat(precision); + } else { + var pad = precision - part[1].length; + assert(pad >= 0, 'decimal \'' + value + '\' exceeds precision ' + precision); + return part[0] + '.' + part[1] + '0'.repeat(pad); + } +} -Request.prototype.onError = function (err) { - this.emit('error', err); - this.cleanup(true); -}; +/** Ensures proper trailing zeros then removes decimal place. */ +function DecimalImply(value, precision) { + return DecimalPad(value, precision).replace('.', ''); +} /** - * Cleans up house. - * - * @api private - */ + Put the decimal place back in its position and return the normalized number + string (with any unnecessary zeros or an unnecessary decimal removed). -Request.prototype.cleanup = function (fromError) { - if ('undefined' === typeof this.xhr || null === this.xhr) { - return; - } - // xmlhttprequest - if (this.hasXDR()) { - this.xhr.onload = this.xhr.onerror = empty; - } else { - this.xhr.onreadystatechange = empty; + @arg {string|number|value.toString} value 10000 + @arg {number} precision 4 + @return {number} 1.0000 +*/ +function DecimalUnimply(value, precision) { + assert(value != null, 'value is required'); + value = value === 'object' && value.toString ? value.toString() : String(value); + var neg = /^-/.test(value); + if (neg) { + value = value.substring(1); } + assert(/^\d+$/.test(value), 'invalid whole number ' + value); + assert(precision != null, 'precision required'); + assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); - if (fromError) { - try { - this.xhr.abort(); - } catch (e) {} + // Ensure minimum length + var pad = precision - value.length; + if (pad > 0) { + value = '' + '0'.repeat(pad) + value; } - if (global.document) { - delete Request.requests[this.index]; - } + var dotIdx = value.length - precision; + value = value.slice(0, dotIdx) + '.' + value.slice(dotIdx); + return (neg ? '-' : '') + DecimalPad(value, precision); // Normalize +} - this.xhr = null; -}; +/** @private for now, support for asset strings is limited +*/ +function printAsset(_ref) { + var amount = _ref.amount, + precision = _ref.precision, + symbol = _ref.symbol, + contract = _ref.contract; -/** - * Called upon load. - * - * @api private - */ + assert.equal(typeof symbol === 'undefined' ? 'undefined' : (0, _typeof3.default)(symbol), 'string', 'symbol is a required string'); -Request.prototype.onLoad = function () { - var data; - try { - var contentType; - try { - contentType = this.xhr.getResponseHeader('Content-Type'); - } catch (e) {} - if (contentType === 'application/octet-stream') { - data = this.xhr.response || this.xhr.responseText; - } else { - data = this.xhr.responseText; - } - } catch (e) { - this.onError(e); - } - if (null != data) { - this.onData(data); + if (amount != null && precision != null) { + amount = DecimalPad(amount, precision); } -}; - -/** - * Check if it has XDomainRequest. - * - * @api private - */ -Request.prototype.hasXDR = function () { - return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR; -}; + var join = function join(e1, e2) { + return e1 == null ? '' : e2 == null ? '' : e1 + e2; + }; -/** - * Aborts the request. - * - * @api public - */ + if (amount != null) { + // the amount contains the precision + return join(amount, ' ') + symbol + join('@', contract); + } -Request.prototype.abort = function () { - this.cleanup(); -}; + return join(precision, ',') + symbol + join('@', contract); +} /** - * Aborts pending requests when unloading the window. This is needed to prevent - * memory leaks (e.g. when using IE) and to ensure that no spurious error is - * emitted. - */ + Attempts to parse all forms of the asset strings (symbol, asset, or extended + versions). If the provided string contains any additional or appears to have + invalid information an error is thrown. -Request.requestsCount = 0; -Request.requests = {}; + @return {object} {amount, precision, symbol, contract} + @throws AssertionError +*/ +function parseAsset(str) { + var _str$split = str.split(' '), + _str$split2 = (0, _slicedToArray3.default)(_str$split, 1), + amountRaw = _str$split2[0]; -if (global.document) { - if (global.attachEvent) { - global.attachEvent('onunload', unloadHandler); - } else if (global.addEventListener) { - global.addEventListener('beforeunload', unloadHandler, false); - } -} + var amountMatch = amountRaw.match(/^(-?[0-9]+(\.[0-9]+)?)( |$)/); + var amount = amountMatch ? amountMatch[1] : null; -function unloadHandler () { - for (var i in Request.requests) { - if (Request.requests.hasOwnProperty(i)) { - Request.requests[i].abort(); - } - } -} + var precisionMatch = str.match(/(^| )([0-9]+),([A-Z]+)(@|$)/); + var precisionSymbol = precisionMatch ? Number(precisionMatch[2]) : null; + var precisionAmount = amount ? (amount.split('.')[1] || '').length : null; + var precision = precisionSymbol != null ? precisionSymbol : precisionAmount; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) + var symbolMatch = str.match(/(^| |,)([A-Z]+)(@|$)/); + var symbol = symbolMatch ? symbolMatch[2] : null; -/***/ }), -/* 178 */ -/***/ (function(module, exports) { + var _str$split3 = str.split('@'), + _str$split4 = (0, _slicedToArray3.default)(_str$split3, 2), + _str$split4$ = _str$split4[1], + contractRaw = _str$split4$ === undefined ? '' : _str$split4$; + var contract = /^[a-z0-5]+(\.[a-z0-5]+)*$/.test(contractRaw) ? contractRaw : null; -/** - * Gets the keys for an object. - * - * @return {Array} keys - * @api private - */ + var check = printAsset({ amount: amount, precision: precision, symbol: symbol, contract: contract }); -module.exports = Object.keys || function keys (obj){ - var arr = []; - var has = Object.prototype.hasOwnProperty; + assert.equal(str, check, 'Invalid asset string: ' + str + ' !== ' + check); - for (var i in obj) { - if (has.call(obj, i)) { - arr.push(i); - } + if (precision != null) { + assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); + } + if (symbol != null) { + assert(symbol.length <= 7, 'Asset symbol is 7 characters or less'); + } + if (contract != null) { + assert(contract.length <= 12, 'Contract is 12 characters or less'); } - return arr; -}; + return { amount: amount, precision: precision, symbol: symbol, contract: contract }; +} /***/ }), -/* 179 */ +/* 118 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray +Object.defineProperty(exports, "__esModule", { + value: true +}); +const BLOCKCHAIN_SUPPORT = exports.BLOCKCHAIN_SUPPORT = 'blockchain_support'; -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} +"use strict"; -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 -function getLens (b64) { - var len = b64.length +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BlockchainsArray = exports.Blockchains = undefined; - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } +var _keys = __webpack_require__(247); - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len +var _keys2 = _interopRequireDefault(_keys); - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return [validLen, placeHoldersLen] -} +const Blockchains = exports.Blockchains = { + EOS: 'eos', + ETH: 'eth' +}; -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} +const BlockchainsArray = exports.BlockchainsArray = (0, _keys2.default)(Blockchains).map(key => ({ key, value: Blockchains[key] })); -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} +/***/ }), +/* 120 */ +/***/ (function(module, exports, __webpack_require__) { -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] +"use strict"; - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - var curByte = 0 +Object.defineProperty(exports, "__esModule", { + value: true +}); - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen +var _assign = __webpack_require__(34); - for (var i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } +var _assign2 = _interopRequireDefault(_assign); - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } +var _promise = __webpack_require__(28); - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } +var _promise2 = _interopRequireDefault(_promise); - return arr -} +var _asyncToGenerator2 = __webpack_require__(57); -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} +var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} +var _SocketService = __webpack_require__(85); -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 +var _SocketService2 = _interopRequireDefault(_SocketService); - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } +var _PluginRepository = __webpack_require__(244); - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } +var _PluginRepository2 = _interopRequireDefault(_PluginRepository); - return parts.join('') -} +__webpack_require__(114); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 180 */ -/***/ (function(module, exports) { +let origin; -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] +const throwNoAuth = () => { + if (!holder.scatter.isExtension && !_SocketService2.default.isConnected()) throw new Error('Connect and Authenticate first - scatter.connect( pluginName )'); +}; - i += d +const checkForPlugin = (resolve, tries = 0) => { + if (tries > 20) return; + if (holder.scatter.isExtension) return resolve(true); + setTimeout(() => checkForPlugin(resolve, tries + 1), 100); +}; - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} +class Scatter { - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + constructor() { + const noIdFunc = () => { + if (!this.identity) throw new Error('No Identity'); + }; - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} + _PluginRepository2.default.signatureProviders().map(sigProvider => { + this[sigProvider.name] = sigProvider.signatureProvider(noIdFunc); + }); -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + this.isExtension = false; + this.identity = null; + } - value = Math.abs(value) + isInstalled() { + return (0, _asyncToGenerator3.default)(function* () { + return new _promise2.default(function (resolve) { + setTimeout(function () { + resolve(false); + }, 3000); - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } + _promise2.default.race([checkForPlugin(resolve), _SocketService2.default.ping().then(function (found) { + console.log('found', found); + if (found) resolve(true); + })]); - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 + // Tries to set up Desktop Connection + }); + })(); } - } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + connect(pluginName, options) { + var _this = this; - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + return (0, _asyncToGenerator3.default)(function* () { + return new _promise2.default(function (resolve) { + if (!pluginName || !pluginName.length) throw new Error("You must specify a name for this connection"); - buffer[offset + i - d] |= s * 128 -} + // Setting options defaults + options = (0, _assign2.default)({ initTimeout: 10000, linkTimeout: 30000 }, options); + // Auto failer + setTimeout(function () { + resolve(false); + }, options.initTimeout); -/***/ }), -/* 181 */ -/***/ (function(module, exports) { + // Defaults to scatter extension if exists + checkForPlugin(resolve); -var toString = {}.toString; + // Tries to set up Desktop Connection + _SocketService2.default.init(pluginName, options.linkTimeout); + _SocketService2.default.link().then((() => { + var _ref = (0, _asyncToGenerator3.default)(function* (authenticated) { + if (!authenticated) return false; + _this.identity = yield _this.getIdentityFromPermissions(); + return resolve(true); + }); -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; + return function (_x) { + return _ref.apply(this, arguments); + }; + })()); + }); + })(); + } + disconnect() { + return _SocketService2.default.disconnect(); + } -/***/ }), -/* 182 */ -/***/ (function(module, exports) { + isConnected() { + return _SocketService2.default.isConnected(); + } -/** - * An abstraction for slicing an arraybuffer even when - * ArrayBuffer.prototype.slice is not supported - * - * @api public - */ + getVersion() { + return _SocketService2.default.sendApiRequest({ + type: 'getVersion', + payload: {} + }); + } + + getIdentity(requiredFields) { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'getOrRequestIdentity', + payload: { + fields: requiredFields + } + }).then(id => { + if (id) this.identity = id; + return id; + }); + } + + getIdentityFromPermissions() { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'identityFromPermissions', + payload: {} + }).then(id => { + if (id) this.identity = id; + return id; + }); + } -module.exports = function(arraybuffer, start, end) { - var bytes = arraybuffer.byteLength; - start = start || 0; - end = end || bytes; + forgetIdentity() { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'forgetIdentity', + payload: {} + }).then(res => { + this.identity = null; + return res; + }); + } - if (arraybuffer.slice) { return arraybuffer.slice(start, end); } + authenticate() { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'authenticate', + payload: {} + }); + } - if (start < 0) { start += bytes; } - if (end < 0) { end += bytes; } - if (end > bytes) { end = bytes; } + getArbitrarySignature(publicKey, data, whatfor = '', isHash = false) { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'requestArbitrarySignature', + payload: { + publicKey, + data, + whatfor, + isHash + } + }); + } - if (start >= bytes || start >= end || bytes === 0) { - return new ArrayBuffer(0); - } + getPublicKey(blockchain) { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'getPublicKey', + payload: { blockchain } + }); + } - var abv = new Uint8Array(arraybuffer); - var result = new Uint8Array(end - start); - for (var i = start, ii = 0; i < end; i++, ii++) { - result[ii] = abv[i]; - } - return result.buffer; -}; + linkAccount(publicKey, account, network) { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'linkAccount', + payload: { publicKey, account, network } + }); + } + suggestNetwork(network) { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'requestAddNetwork', + payload: { + network + } + }); + } -/***/ }), -/* 183 */ -/***/ (function(module, exports) { + requestSignature(payload) { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'requestSignature', + payload + }); + } -module.exports = after + createTransaction(blockchain, actions, account, network) { + throwNoAuth(); + return _SocketService2.default.sendApiRequest({ + type: 'createTransaction', + payload: { + blockchain, + actions, + account, + network + } + }); + } +} -function after(count, callback, err_cb) { - var bail = false - err_cb = err_cb || noop - proxy.count = count +class Holder { + constructor(_scatter) { + this.scatter = _scatter; + } +} - return (count === 0) ? callback() : proxy +let holder = new Holder(new Scatter()); +if (typeof window !== 'undefined') { - function proxy(err, result) { - if (proxy.count <= 0) { - throw new Error('after called too many times') - } - --proxy.count + // Catching extension instead of Desktop + if (typeof document !== 'undefined') { + const bindScatterClassic = () => { + holder.scatter = window.scatter; + holder.scatter.isExtension = true; + holder.scatter.connect = () => new _promise2.default(resolve => resolve(true)); + }; - // after first error, rest are passed to err_cb - if (err) { - bail = true - callback(err) - // future error callbacks will go to error handler - callback = err_cb - } else if (proxy.count === 0 && !bail) { - callback(null, result) - } + if (typeof window.scatter !== 'undefined') bindScatterClassic();else document.addEventListener('scatterLoaded', () => bindScatterClassic()); } -} -function noop() {} + if (!holder.scatter.isExtension) window.scatter = holder.scatter; +} +exports.default = holder; /***/ }), -/* 184 */ +/* 121 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/utf8js v2.1.2 by @mathias */ -;(function(root) { - - // Detect free variables `exports` - var freeExports = typeof exports == 'object' && exports; - - // Detect free variable `module` - var freeModule = typeof module == 'object' && module && - module.exports == freeExports && module; - - // Detect free variable `global`, from Node.js or Browserified code, - // and use it as `root` - var freeGlobal = typeof global == 'object' && global; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - root = freeGlobal; - } - - /*--------------------------------------------------------------------------*/ - - var stringFromCharCode = String.fromCharCode; - - // Taken from https://mths.be/punycode - function ucs2decode(string) { - var output = []; - var counter = 0; - var length = string.length; - var value; - var extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - // Taken from https://mths.be/punycode - function ucs2encode(array) { - var length = array.length; - var index = -1; - var value; - var output = ''; - while (++index < length) { - value = array[index]; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - } - return output; - } - - function checkScalarValue(codePoint, strict) { - if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { - if (strict) { - throw Error( - 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + - ' is not a scalar value' - ); - } - return false; - } - return true; - } - /*--------------------------------------------------------------------------*/ - - function createByte(codePoint, shift) { - return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); - } - - function encodeCodePoint(codePoint, strict) { - if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence - return stringFromCharCode(codePoint); - } - var symbol = ''; - if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence - symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); - } - else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence - if (!checkScalarValue(codePoint, strict)) { - codePoint = 0xFFFD; - } - symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); - symbol += createByte(codePoint, 6); - } - else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence - symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); - symbol += createByte(codePoint, 12); - symbol += createByte(codePoint, 6); - } - symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); - return symbol; - } - - function utf8encode(string, opts) { - opts = opts || {}; - var strict = false !== opts.strict; - - var codePoints = ucs2decode(string); - var length = codePoints.length; - var index = -1; - var codePoint; - var byteString = ''; - while (++index < length) { - codePoint = codePoints[index]; - byteString += encodeCodePoint(codePoint, strict); - } - return byteString; - } - - /*--------------------------------------------------------------------------*/ - - function readContinuationByte() { - if (byteIndex >= byteCount) { - throw Error('Invalid byte index'); - } - - var continuationByte = byteArray[byteIndex] & 0xFF; - byteIndex++; - - if ((continuationByte & 0xC0) == 0x80) { - return continuationByte & 0x3F; - } - - // If we end up here, it’s not a continuation byte - throw Error('Invalid continuation byte'); - } - - function decodeSymbol(strict) { - var byte1; - var byte2; - var byte3; - var byte4; - var codePoint; - - if (byteIndex > byteCount) { - throw Error('Invalid byte index'); - } - - if (byteIndex == byteCount) { - return false; - } - - // Read first byte - byte1 = byteArray[byteIndex] & 0xFF; - byteIndex++; - - // 1-byte sequence (no continuation bytes) - if ((byte1 & 0x80) == 0) { - return byte1; - } - - // 2-byte sequence - if ((byte1 & 0xE0) == 0xC0) { - byte2 = readContinuationByte(); - codePoint = ((byte1 & 0x1F) << 6) | byte2; - if (codePoint >= 0x80) { - return codePoint; - } else { - throw Error('Invalid continuation byte'); - } - } - - // 3-byte sequence (may include unpaired surrogates) - if ((byte1 & 0xF0) == 0xE0) { - byte2 = readContinuationByte(); - byte3 = readContinuationByte(); - codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; - if (codePoint >= 0x0800) { - return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD; - } else { - throw Error('Invalid continuation byte'); - } - } - - // 4-byte sequence - if ((byte1 & 0xF8) == 0xF0) { - byte2 = readContinuationByte(); - byte3 = readContinuationByte(); - byte4 = readContinuationByte(); - codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | - (byte3 << 0x06) | byte4; - if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { - return codePoint; - } - } - - throw Error('Invalid UTF-8 detected'); - } - - var byteArray; - var byteCount; - var byteIndex; - function utf8decode(byteString, opts) { - opts = opts || {}; - var strict = false !== opts.strict; - - byteArray = ucs2decode(byteString); - byteCount = byteArray.length; - byteIndex = 0; - var codePoints = []; - var tmp; - while ((tmp = decodeSymbol(strict)) !== false) { - codePoints.push(tmp); - } - return ucs2encode(codePoints); - } - - /*--------------------------------------------------------------------------*/ - - var utf8 = { - 'version': '2.1.2', - 'encode': utf8encode, - 'decode': utf8decode - }; - - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - true - ) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { - return utf8; - }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (freeExports && !freeExports.nodeType) { - if (freeModule) { // in Node.js or RingoJS v0.8.0+ - freeModule.exports = utf8; - } else { // in Narwhal or RingoJS v0.7.0- - var object = {}; - var hasOwnProperty = object.hasOwnProperty; - for (var key in utf8) { - hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); - } - } - } else { // in Rhino or a web browser - root.utf8 = utf8; - } - -}(this)); - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(102)(module), __webpack_require__(3))) - -/***/ }), -/* 185 */ -/***/ (function(module, exports) { - -/* - * base64-arraybuffer - * https://github.com/niklasvh/base64-arraybuffer - * - * Copyright (c) 2012 Niklas von Hertzen - * Licensed under the MIT license. - */ -(function(){ - "use strict"; +__webpack_require__(122); +module.exports = __webpack_require__(4).Object.assign; - var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - // Use a lookup table to find the index. - var lookup = new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup[chars.charCodeAt(i)] = i; - } +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { - exports.encode = function(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), - i, len = bytes.length, base64 = ""; +// 19.1.3.1 Object.assign(target, source) +var $export = __webpack_require__(10); - for (i = 0; i < len; i+=3) { - base64 += chars[bytes[i] >> 2]; - base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; - base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; - base64 += chars[bytes[i + 2] & 63]; - } +$export($export.S + $export.F, 'Object', { assign: __webpack_require__(123) }); - if ((len % 3) === 2) { - base64 = base64.substring(0, base64.length - 1) + "="; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + "=="; - } - return base64; - }; +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { - exports.decode = function(base64) { - var bufferLength = base64.length * 0.75, - len = base64.length, i, p = 0, - encoded1, encoded2, encoded3, encoded4; +"use strict"; - if (base64[base64.length - 1] === "=") { - bufferLength--; - if (base64[base64.length - 2] === "=") { - bufferLength--; - } - } +// 19.1.2.1 Object.assign(target, source, ...) +var getKeys = __webpack_require__(25); +var gOPS = __webpack_require__(53); +var pIE = __webpack_require__(39); +var toObject = __webpack_require__(54); +var IObject = __webpack_require__(73); +var $assign = Object.assign; - var arraybuffer = new ArrayBuffer(bufferLength), - bytes = new Uint8Array(arraybuffer); +// should work with symbols and should have deterministic property order (V8 bug) +module.exports = !$assign || __webpack_require__(19)(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; +}) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = gOPS.f; + var isEnum = pIE.f; + while (aLen > index) { + var S = IObject(arguments[index++]); + var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; +} : $assign; - for (i = 0; i < len; i+=4) { - encoded1 = lookup[base64.charCodeAt(i)]; - encoded2 = lookup[base64.charCodeAt(i+1)]; - encoded3 = lookup[base64.charCodeAt(i+2)]; - encoded4 = lookup[base64.charCodeAt(i+3)]; - bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { - return arraybuffer; +// false -> Array#indexOf +// true -> Array#includes +var toIObject = __webpack_require__(20); +var toLength = __webpack_require__(74); +var toAbsoluteIndex = __webpack_require__(125); +module.exports = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; }; -})(); +}; /***/ }), -/* 186 */ +/* 125 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(global) {/** - * Create a blob builder even when vendor prefixes exist - */ +var toInteger = __webpack_require__(49); +var max = Math.max; +var min = Math.min; +module.exports = function (index, length) { + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); +}; -var BlobBuilder = global.BlobBuilder - || global.WebKitBlobBuilder - || global.MSBlobBuilder - || global.MozBlobBuilder; -/** - * Check if Blob constructor is supported - */ +/***/ }), +/* 126 */ +/***/ (function(module, exports, __webpack_require__) { -var blobSupported = (function() { - try { - var a = new Blob(['hi']); - return a.size === 2; - } catch(e) { - return false; - } -})(); +__webpack_require__(75); +__webpack_require__(40); +__webpack_require__(42); +__webpack_require__(134); +__webpack_require__(145); +__webpack_require__(146); +module.exports = __webpack_require__(4).Promise; -/** - * Check if Blob constructor supports ArrayBufferViews - * Fails in Safari 6, so we need to map to ArrayBuffers there. - */ -var blobSupportsArrayBufferView = blobSupported && (function() { - try { - var b = new Blob([new Uint8Array([1,2])]); - return b.size === 2; - } catch(e) { - return false; - } -})(); +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Check if BlobBuilder is supported - */ +var toInteger = __webpack_require__(49); +var defined = __webpack_require__(48); +// true -> String#at +// false -> String#codePointAt +module.exports = function (TO_STRING) { + return function (that, pos) { + var s = String(defined(that)); + var i = toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; -var blobBuilderSupported = BlobBuilder - && BlobBuilder.prototype.append - && BlobBuilder.prototype.getBlob; -/** - * Helper function that maps ArrayBufferViews to ArrayBuffers - * Used by BlobBuilder constructor and old browsers that didn't - * support it in the Blob constructor. - */ +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { -function mapArrayBufferViews(ary) { - for (var i = 0; i < ary.length; i++) { - var chunk = ary[i]; - if (chunk.buffer instanceof ArrayBuffer) { - var buf = chunk.buffer; +"use strict"; - // if this is a subarray, make a copy so we only - // include the subarray region from the underlying buffer - if (chunk.byteLength !== buf.byteLength) { - var copy = new Uint8Array(chunk.byteLength); - copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); - buf = copy.buffer; - } +var create = __webpack_require__(78); +var descriptor = __webpack_require__(37); +var setToStringTag = __webpack_require__(41); +var IteratorPrototype = {}; - ary[i] = buf; - } - } -} +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +__webpack_require__(11)(IteratorPrototype, __webpack_require__(6)('iterator'), function () { return this; }); -function BlobBuilderConstructor(ary, options) { - options = options || {}; +module.exports = function (Constructor, NAME, next) { + Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); + setToStringTag(Constructor, NAME + ' Iterator'); +}; - var bb = new BlobBuilder(); - mapArrayBufferViews(ary); - for (var i = 0; i < ary.length; i++) { - bb.append(ary[i]); - } +/***/ }), +/* 129 */ +/***/ (function(module, exports, __webpack_require__) { - return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); -}; +var dP = __webpack_require__(12); +var anObject = __webpack_require__(8); +var getKeys = __webpack_require__(25); -function BlobConstructor(ary, options) { - mapArrayBufferViews(ary); - return new Blob(ary, options || {}); +module.exports = __webpack_require__(14) ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = getKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) dP.f(O, P = keys[i++], Properties[P]); + return O; }; -module.exports = (function() { - if (blobSupported) { - return blobSupportsArrayBufferView ? global.Blob : BlobConstructor; - } else if (blobBuilderSupported) { - return BlobBuilderConstructor; - } else { - return undefined; - } -})(); - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), -/* 187 */ +/* 130 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(global) { -/** - * Module requirements. - */ +// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) +var has = __webpack_require__(15); +var toObject = __webpack_require__(54); +var IE_PROTO = __webpack_require__(50)('IE_PROTO'); +var ObjectProto = Object.prototype; -var Polling = __webpack_require__(100); -var inherit = __webpack_require__(47); +module.exports = Object.getPrototypeOf || function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; +}; -/** - * Module exports. - */ -module.exports = JSONPPolling; +/***/ }), +/* 131 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Cached regular expressions. - */ +"use strict"; -var rNewline = /\n/g; -var rEscapedNewline = /\\n/g; +var addToUnscopables = __webpack_require__(132); +var step = __webpack_require__(133); +var Iterators = __webpack_require__(21); +var toIObject = __webpack_require__(20); -/** - * Global JSONP callbacks. - */ +// 22.1.3.4 Array.prototype.entries() +// 22.1.3.13 Array.prototype.keys() +// 22.1.3.29 Array.prototype.values() +// 22.1.3.30 Array.prototype[@@iterator]() +module.exports = __webpack_require__(76)(Array, 'Array', function (iterated, kind) { + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind +// 22.1.5.2.1 %ArrayIteratorPrototype%.next() +}, function () { + var O = this._t; + var kind = this._k; + var index = this._i++; + if (!O || index >= O.length) { + this._t = undefined; + return step(1); + } + if (kind == 'keys') return step(0, index); + if (kind == 'values') return step(0, O[index]); + return step(0, [index, O[index]]); +}, 'values'); -var callbacks; +// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) +Iterators.Arguments = Iterators.Array; -/** - * Noop. - */ +addToUnscopables('keys'); +addToUnscopables('values'); +addToUnscopables('entries'); -function empty () { } -/** - * JSONP Polling constructor. - * - * @param {Object} opts. - * @api public - */ +/***/ }), +/* 132 */ +/***/ (function(module, exports) { -function JSONPPolling (opts) { - Polling.call(this, opts); +module.exports = function () { /* empty */ }; - this.query = this.query || {}; - // define global callbacks array if not present - // we do this here (lazily) to avoid unneeded global pollution - if (!callbacks) { - // we need to consider multiple engines in the same page - if (!global.___eio) global.___eio = []; - callbacks = global.___eio; - } +/***/ }), +/* 133 */ +/***/ (function(module, exports) { - // callback identifier - this.index = callbacks.length; +module.exports = function (done, value) { + return { value: value, done: !!done }; +}; - // add callback to jsonp global - var self = this; - callbacks.push(function (msg) { - self.onData(msg); - }); - // append to query string - this.query.j = this.index; +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { - // prevent spurious errors from being emitted when the window is unloaded - if (global.document && global.addEventListener) { - global.addEventListener('beforeunload', function () { - if (self.script) self.script.onerror = empty; - }, false); - } -} +"use strict"; -/** - * Inherits from Polling. - */ +var LIBRARY = __webpack_require__(27); +var global = __webpack_require__(5); +var ctx = __webpack_require__(35); +var classof = __webpack_require__(55); +var $export = __webpack_require__(10); +var isObject = __webpack_require__(13); +var aFunction = __webpack_require__(36); +var anInstance = __webpack_require__(135); +var forOf = __webpack_require__(136); +var speciesConstructor = __webpack_require__(81); +var task = __webpack_require__(82).set; +var microtask = __webpack_require__(140)(); +var newPromiseCapabilityModule = __webpack_require__(56); +var perform = __webpack_require__(83); +var userAgent = __webpack_require__(141); +var promiseResolve = __webpack_require__(84); +var PROMISE = 'Promise'; +var TypeError = global.TypeError; +var process = global.process; +var versions = process && process.versions; +var v8 = versions && versions.v8 || ''; +var $Promise = global[PROMISE]; +var isNode = classof(process) == 'process'; +var empty = function () { /* empty */ }; +var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; +var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; -inherit(JSONPPolling, Polling); +var USE_NATIVE = !!function () { + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1); + var FakePromise = (promise.constructor = {})[__webpack_require__(6)('species')] = function (exec) { + exec(empty, empty); + }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode || typeof PromiseRejectionEvent == 'function') + && promise.then(empty) instanceof FakePromise + // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables + // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 + // we can't detect it synchronously, so just check versions + && v8.indexOf('6.6') !== 0 + && userAgent.indexOf('Chrome/66') === -1; + } catch (e) { /* empty */ } +}(); -/* - * JSONP only supports binary as base64 encoded strings - */ +// helpers +var isThenable = function (it) { + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; +}; +var notify = function (promise, isReject) { + if (promise._n) return; + promise._n = true; + var chain = promise._c; + microtask(function () { + var value = promise._v; + var ok = promise._s == 1; + var i = 0; + var run = function (reaction) { + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then, exited; + try { + if (handler) { + if (!ok) { + if (promise._h == 2) onHandleUnhandled(promise); + promise._h = 1; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); // may throw + if (domain) { + domain.exit(); + exited = true; + } + } + if (result === reaction.promise) { + reject(TypeError('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (e) { + if (domain && !exited) domain.exit(); + reject(e); + } + }; + while (chain.length > i) run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if (isReject && !promise._h) onUnhandled(promise); + }); +}; +var onUnhandled = function (promise) { + task.call(global, function () { + var value = promise._v; + var unhandled = isUnhandled(promise); + var result, handler, console; + if (unhandled) { + result = perform(function () { + if (isNode) { + process.emit('unhandledRejection', value, promise); + } else if (handler = global.onunhandledrejection) { + handler({ promise: promise, reason: value }); + } else if ((console = global.console) && console.error) { + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if (unhandled && result.e) throw result.v; + }); +}; +var isUnhandled = function (promise) { + return promise._h !== 1 && (promise._a || promise._c).length === 0; +}; +var onHandleUnhandled = function (promise) { + task.call(global, function () { + var handler; + if (isNode) { + process.emit('rejectionHandled', promise); + } else if (handler = global.onrejectionhandled) { + handler({ promise: promise, reason: promise._v }); + } + }); +}; +var $reject = function (value) { + var promise = this; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if (!promise._a) promise._a = promise._c.slice(); + notify(promise, true); +}; +var $resolve = function (value) { + var promise = this; + var then; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if (promise === value) throw TypeError("Promise can't be resolved itself"); + if (then = isThenable(value)) { + microtask(function () { + var wrapper = { _w: promise, _d: false }; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch (e) { + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch (e) { + $reject.call({ _w: promise, _d: false }, e); // wrap + } +}; -JSONPPolling.prototype.supportsBinary = false; +// constructor polyfill +if (!USE_NATIVE) { + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor) { + anInstance(this, $Promise, PROMISE, '_h'); + aFunction(executor); + Internal.call(this); + try { + executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + } catch (err) { + $reject.call(this, err); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = __webpack_require__(142)($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected) { + var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode ? process.domain : undefined; + this._c.push(reaction); + if (this._a) this._a.push(reaction); + if (this._s) notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + this.promise = promise; + this.resolve = ctx($resolve, promise, 1); + this.reject = ctx($reject, promise, 1); + }; + newPromiseCapabilityModule.f = newPromiseCapability = function (C) { + return C === $Promise || C === Wrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; +} -/** - * Closes the socket. - * - * @api private - */ +$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); +__webpack_require__(41)($Promise, PROMISE); +__webpack_require__(143)(PROMISE); +Wrapper = __webpack_require__(4)[PROMISE]; -JSONPPolling.prototype.doClose = function () { - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; +// statics +$export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r) { + var capability = newPromiseCapability(this); + var $$reject = capability.reject; + $$reject(r); + return capability.promise; } - - if (this.form) { - this.form.parentNode.removeChild(this.form); - this.form = null; - this.iframe = null; +}); +$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x) { + return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); } - - Polling.prototype.doClose.call(this); -}; - -/** - * Starts a poll cycle. - * - * @api private - */ - -JSONPPolling.prototype.doPoll = function () { - var self = this; - var script = document.createElement('script'); - - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; +}); +$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(144)(function (iter) { + $Promise.all(iter)['catch'](empty); +})), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var values = []; + var index = 0; + var remaining = 1; + forOf(iterable, false, function (promise) { + var $index = index++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.e) reject(result.v); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = perform(function () { + forOf(iterable, false, function (promise) { + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if (result.e) reject(result.v); + return capability.promise; } +}); - script.async = true; - script.src = this.uri(); - script.onerror = function (e) { - self.onError('jsonp poll error', e); - }; - - var insertAt = document.getElementsByTagName('script')[0]; - if (insertAt) { - insertAt.parentNode.insertBefore(script, insertAt); - } else { - (document.head || document.body).appendChild(script); - } - this.script = script; - var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); +/***/ }), +/* 135 */ +/***/ (function(module, exports) { - if (isUAgecko) { - setTimeout(function () { - var iframe = document.createElement('iframe'); - document.body.appendChild(iframe); - document.body.removeChild(iframe); - }, 100); - } +module.exports = function (it, Constructor, name, forbiddenField) { + if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { + throw TypeError(name + ': incorrect invocation!'); + } return it; }; -/** - * Writes with a hidden iframe. - * - * @param {String} data to send - * @param {Function} called upon flush. - * @api private - */ - -JSONPPolling.prototype.doWrite = function (data, fn) { - var self = this; - - if (!this.form) { - var form = document.createElement('form'); - var area = document.createElement('textarea'); - var id = this.iframeId = 'eio_iframe_' + this.index; - var iframe; - form.className = 'socketio'; - form.style.position = 'absolute'; - form.style.top = '-1000px'; - form.style.left = '-1000px'; - form.target = id; - form.method = 'POST'; - form.setAttribute('accept-charset', 'utf-8'); - area.name = 'd'; - form.appendChild(area); - document.body.appendChild(form); - - this.form = form; - this.area = area; - } - - this.form.action = this.uri(); - - function complete () { - initIframe(); - fn(); - } - - function initIframe () { - if (self.iframe) { - try { - self.form.removeChild(self.iframe); - } catch (e) { - self.onError('jsonp polling iframe removal error', e); - } - } - - try { - // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) - var html = '