text: (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g._bcvault = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  // 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; };
  
  },{}],2:[function(require,module,exports){
  "use strict";
  var a = require("./lib/bcapi");
  var b = require("./lib/types");
  module.exports = Object.assign(new a.BCJS(), a, b);
  
  },{"./lib/bcapi":3,"./lib/types":4}],3:[function(require,module,exports){
  "use strict";
  var __assign = (this && this.__assign) || function () {
      __assign = Object.assign || function(t) {
          for (var s, i = 1, n = arguments.length; i < n; i++) {
              s = arguments[i];
              for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                  t[p] = s[p];
          }
          return t;
      };
      return __assign.apply(this, arguments);
  };
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  var __generator = (this && this.__generator) || function (thisArg, body) {
      var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
      function verb(n) { return function (v) { return step([n, v]); }; }
      function step(op) {
          if (f) throw new TypeError("Generator is already executing.");
          while (_) try {
              if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
              if (y = 0, t) op = [op[0] & 2, t.value];
              switch (op[0]) {
                  case 0: case 1: t = op; break;
                  case 4: _.label++; return { value: op[1], done: false };
                  case 5: _.label++; y = op[1]; op = [0]; continue;
                  case 7: op = _.ops.pop(); _.trys.pop(); continue;
                  default:
                      if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                      if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                      if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                      if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                      if (t[2]) _.ops.pop();
                      _.trys.pop(); continue;
              }
              op = body.call(thisArg, _);
          } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
          if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
      }
  };
  var __values = (this && this.__values) || function(o) {
      var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
      if (m) return m.call(o);
      if (o && typeof o.length === "number") return {
          next: function () {
              if (o && i >= o.length) o = void 0;
              return { value: o && o[i++], done: !o };
          }
      };
      throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  };
  var __read = (this && this.__read) || function (o, n) {
      var m = typeof Symbol === "function" && o[Symbol.iterator];
      if (!m) return o;
      var i = m.call(o), r, ar = [], e;
      try {
          while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
      }
      catch (error) { e = { error: error }; }
      finally {
          try {
              if (r && !r.done && (m = i["return"])) m.call(i);
          }
          finally { if (e) throw e.error; }
      }
      return ar;
  };
  var __spread = (this && this.__spread) || function () {
      for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
      return ar;
  };
  exports.__esModule = true;
  exports.BCJS = void 0;
  var axios_1 = require("axios");
  var types_1 = require("./types");
  var es6_promise_1 = require("es6-promise");
  es6_promise_1.polyfill();
  var BCJS = /** @class */ (function () {
      /**
       * The BCJS constructor.
       * @param authWindowHandler Setting this parameter is not needed in the browser, but is required for NodeJS. This is a function which must submit a device or wallet password to the daemon for use in the next call.
       * See showAuthPopup and the popup for implementation ideas. A function of this type must be specified in the constructor of BCJS in node, but in the browser it is ignored/optional.
       * The call you are expected to make can be found in the source of:
       * https://localhost.bc-vault.com:1991/PasswordInput?channelID=1&channelPasswordType=global
       *
       * If the call was not successful, reject the promise. If it was, resolve it with no value.
       *
       * The `preAuthReference` object is passed from the `preAuthWindowHandler` called previously.
       *
       * @param preAuthWindowHandler This is a function which is called prior to `authWindowHandler` and prepares it for use. In the browser this function is used to prime a popup window.
       *
       * If the call was not successful, reject the promise. If it was, resolve it with a value you expect to be passed to `authWindowHandler`.
       *
       * This function is completely optional and can be left undefined.
       *
       */
      function BCJS(authWindowHandler, preAuthWindowHandler) {
          /** Is BCData object polling already taking place? */ //
          this.isPolling = false;
          /** Set Logging verbosity */
          this.logLevel = types_1.LogLevel.debug;
          /** Use cookies for session management. If set to false no cookies will be set and the session will be lost when 'authToken' is unloaded. It will need to be manually specified. It will be automatically refreshed if a request fails due to a token error. */
          this.authTokenUseCookies = true;
          /** How long each auth grant will last in seconds since the last request. */
          this.authTokenExpireSeconds = 3600;
          /** The path to match the auth-token against. This is a security feature and allows you to fine tune access. Default is: undefined (don't check the full path, note: specifying this may require you to allow https://www.w3.org/TR/referrer-policy/#referrer-policy-origin-when-cross-origin on your webpage depending on which browsers you target) */
          this.authTokenMatchPath = undefined;
          /** The current state of the daemon, updated either manually or on device connect/disconnect after calling startObjectPolling  */
          this.BCData = { devices: [] };
          this.API_VERSION = 5;
          this.lastSeenDevices = [];
          this.listeners = [];
          this.lastPushedStatus = types_1.BCDataRefreshStatusCode.Ready;
          if (typeof (window) === 'undefined') {
              // is nodejs, authWindowHandler MUST be specified!
              if (typeof (authWindowHandler) !== 'function') {
                  throw new Error('authWindowHandler MUST be of type function for BCJS constructor in NodeJS');
              }
              else {
                  this.authHandler = authWindowHandler;
              }
          }
          if (typeof (preAuthWindowHandler) !== 'function' && typeof (preAuthWindowHandler) !== 'undefined') {
              throw new Error('type of preAuthWindowHandler must be either undefined or function');
          }
          if (typeof (preAuthWindowHandler) === 'function' && !authWindowHandler) {
              throw new Error('AuthWindowHandler must be specified if using preAuthWindowHandler.');
          }
          this.preAuthHandler = preAuthWindowHandler;
      }
      /**
        Starts polling daemon for changes and updates BCData object
        ### Example (es3)
        ```js
          bc.startObjectPolling(150);
          //=> bc.BCData will now be updated if the getDevices array changes
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
          bc.startObjectPolling(150);
          //=> bc.BCData will now be updated if the getDevices array changes
        ```
  
  
      @param deviceInterval how many milliseconds to wait between getDevices pings to daemon
      @throws        Will throw "Already polling" if polling is already taking place.
       */
      BCJS.prototype.startObjectPolling = function (deviceInterval) {
          if (deviceInterval === void 0) { deviceInterval = 150; }
          if (this.isPolling)
              throw Error("Already polling!");
          this.isPolling = true;
          // pollBCObject(fullInterval);
          this.pollDevicesChanged(deviceInterval);
      };
      /**
        Stops polling daemon for changes
        ### Example (es3)
        ```js
          bc.startObjectPolling(150);
          bc.stopObjectPolling();
          //=> bc.BCData will now not be updated if the getDevices array changes
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
          bc.startObjectPolling(150);
          bc.stopObjectPolling();
          //=> bc.BCData will now not be updated if the getDevices array changes
        ```
       */
      BCJS.prototype.stopObjectPolling = function () {
          if (!this.isPolling) {
              throw new Error("Not polling!");
          }
          this.isPolling = false;
          clearTimeout(this.timeoutRef);
      };
      /**
        Triggers a manual update to BCData.
        ### Example (es3)
        ```js
        console.log(JSON.stringify(bc.BCData));//Old
        bc.triggerManualUpdate().then(function(){
          console.log(JSON.stringify(bc.BCData));//Updated
        });
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
          console.log(JSON.stringify(bc.BCData));//Old
          await bc.triggerManualUpdate();
          console.log(JSON.stringify(bc.BCData));//Updated
        ```
  
  
      @param fullUpdate Force an update or only update data if a new device connects or disconnects.
      @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
      @throws        Will throw an AxiosError if the request itself failed or if status code != 200
       */
      BCJS.prototype.triggerManualUpdate = function (fullUpdate) {
          if (fullUpdate === void 0) { fullUpdate = true; }
          return __awaiter(this, void 0, void 0, function () {
              var devArray, devs, devArray_1, devArray_1_1, deviceID, activeTypes, e_1, userData, _a, _b, usrDataHex, deviceUID, _c, _d, _e, e_2_1, devices;
              var e_2, _f, _g, _h;
              return __generator(this, function (_j) {
                  switch (_j.label) {
                      case 0:
                          if (!fullUpdate) return [3 /*break*/, 26];
                          return [4 /*yield*/, this.getDevices()];
                      case 1:
                          devArray = _j.sent();
                          devs = [];
                          this.FireAllStatusListeners(1);
                          _j.label = 2;
                      case 2:
                          _j.trys.push([2, 23, 24, 25]);
                          devArray_1 = __values(devArray), devArray_1_1 = devArray_1.next();
                          _j.label = 3;
                      case 3:
                          if (!!devArray_1_1.done) return [3 /*break*/, 22];
                          deviceID = devArray_1_1.value;
                          activeTypes = void 0;
                          _j.label = 4;
                      case 4:
                          _j.trys.push([4, 6, , 11]);
                          return [4 /*yield*/, this.getActiveWalletTypes(deviceID)];
                      case 5:
                          activeTypes = _j.sent();
                          return [3 /*break*/, 11];
                      case 6:
                          e_1 = _j.sent();
                          if (!(e_1.BCHttpResponse !== undefined)) return [3 /*break*/, 10];
                          return [4 /*yield*/, this.getWalletUserData(deviceID, types_1.WalletType.none, "", false)];
                      case 7:
                          userData = _j.sent();
                          _b = (_a = devs).push;
                          _g = {
                              id: deviceID,
                              space: { available: 1, complete: 1 }
                          };
                          return [4 /*yield*/, this.getFirmwareVersion(deviceID)];
                      case 8:
                          _g.firmware = _j.sent(),
                              _g.userData = this.parseHex(userData),
                              _g.userDataRaw = userData;
                          return [4 /*yield*/, this.getSupportedWalletTypes(deviceID)];
                      case 9:
                          _b.apply(_a, [(_g.supportedTypes = _j.sent(),
                                  _g.activeTypes = [],
                                  _g.activeWallets = [],
                                  _g.locked = true,
                                  _g)]);
                          return [3 /*break*/, 21];
                      case 10: throw e_1;
                      case 11: return [4 /*yield*/, this.getWalletUserData(deviceID, types_1.WalletType.none, "", false)];
                      case 12:
                          usrDataHex = _j.sent();
                          deviceUID = void 0;
                          _j.label = 13;
                      case 13:
                          _j.trys.push([13, 15, , 16]);
                          return [4 /*yield*/, this.getDeviceUID(deviceID)];
                      case 14:
                          deviceUID = _j.sent();
                          return [3 /*break*/, 16];
                      case 15:
                          _c = _j.sent();
                          deviceUID = undefined;
                          return [3 /*break*/, 16];
                      case 16:
                          _e = (_d = devs).push;
                          _h = {
                              id: deviceID,
                              UID: deviceUID
                          };
                          return [4 /*yield*/, this.getAvailableSpace(deviceID)];
                      case 17:
                          _h.space = _j.sent();
                          return [4 /*yield*/, this.getFirmwareVersion(deviceID)];
                      case 18:
                          _h.firmware = _j.sent();
                          return [4 /*yield*/, this.getSupportedWalletTypes(deviceID)];
                      case 19:
                          _h.supportedTypes = _j.sent(),
                              _h.userData = this.parseHex(usrDataHex),
                              _h.userDataRaw = usrDataHex,
                              _h.activeTypes = activeTypes;
                          return [4 /*yield*/, this.getWallets(deviceID, activeTypes)];
                      case 20:
                          _e.apply(_d, [(_h.activeWallets = _j.sent(),
                                  _h.locked = false,
                                  _h)]);
                          _j.label = 21;
                      case 21:
                          devArray_1_1 = devArray_1.next();
                          return [3 /*break*/, 3];
                      case 22: return [3 /*break*/, 25];
                      case 23:
                          e_2_1 = _j.sent();
                          e_2 = { error: e_2_1 };
                          return [3 /*break*/, 25];
                      case 24:
                          try {
                              if (devArray_1_1 && !devArray_1_1.done && (_f = devArray_1["return"])) _f.call(devArray_1);
                          }
                          finally { if (e_2) throw e_2.error; }
                          return [7 /*endfinally*/];
                      case 25:
                          this.BCData = { devices: devs };
                          this.FireAllStatusListeners(0);
                          return [3 /*break*/, 29];
                      case 26:
                          devices = void 0;
                          return [4 /*yield*/, this.getDevices()];
                      case 27:
                          devices = _j.sent();
                          if (!(!this.arraysEqual(devices, this.lastSeenDevices) || this.lastPushedStatus === types_1.BCDataRefreshStatusCode.ConnectionError)) return [3 /*break*/, 29];
                          this.lastSeenDevices = devices;
                          return [4 /*yield*/, this.triggerManualUpdate(true)];
                      case 28:
                          _j.sent();
                          _j.label = 29;
                      case 29: return [2 /*return*/];
                  }
              });
          });
      };
      /**
        Adds a status changed listener for updates to the BCData object
        ### Example (es3)
        ```js
          bc.AddBCDataChangedListener(console.log);
          bc.triggerManualUpdate();
          // => 1
          // => 0
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
          bc.AddBCDataChangedListener(console.log);
          bc.triggerManualUpdate();
          // => 1
          // => 0
        ```
  
  
       */
      BCJS.prototype.AddBCDataChangedListener = function (func) {
          this.listeners.push(func);
      };
      /**
        Returns WalletTypeInfo(name, ticker, etc...) for a specified WalletType if it exists
        ### Example (es3)
        ```js
          console.log(JSON.stringify(bc.getWalletTypeInfo(1)));
          // => {"type":"BcCash01","name":"Bitcoin Cash","ticker":"BCH"}
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
          console.log(JSON.stringify(bc.getWalletTypeInfo(1)));
          // => {"type":"BcCash01","name":"Bitcoin Cash","ticker":"BCH"}
        ```
  
  
       */
      BCJS.prototype.getWalletTypeInfo = function (id) {
          return types_1.typeInfoMap.find(function (x) { return x.type === id; });
      };
      /**
        Gets the currently connected devices.
        ### Example (es3)
        ```js
        bc.getDevices().then(console.log)
        // => [1,2]
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getDevices())
        // => [1,2]
        ```
  
  
      @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
      @throws        Will throw an AxiosError if the request itself failed or if status code != 200
      @returns       An array of Device IDs of currently connected devices
       */
      BCJS.prototype.getDevices = function () {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.Devices)];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
        Gets the firmware version of a specific device.
        ### Example (es3)
        ```js
        bc.getFirmwareVersion(1).then(console.log)
        // => {"major":1,"minor":0,"revision":1,"date":{"day":17,"month":10,"year":2017},"apiVersion":{"major":1,"minor":0}}
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getFirmwareVersion(1))
        // => {"major":1,"minor":0,"revision":1,"date":{"day":17,"month":10,"year":2017},"apiVersion":{"major":1,"minor":0}}
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       An object containing requested data
       */
      BCJS.prototype.getFirmwareVersion = function (device) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.FirmwareVersion, { device: device })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
        Gets the balance in currency-specific minimum units for the specified wallet from a web-service.
        ### Example (es3)
        ```js
        bc.getWalletBalance("BitCoin1","1PekCrsopzENYBa82YpmmBtJcsNgu4PqEV").then(console.log)
        // => {"errorCode": 36864,"data": "0"}
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getWalletBalance("BitCoin1","1PekCrsopzENYBa82YpmmBtJcsNgu4PqEV"))
        // => {"errorCode": 36864,"data": "0"}
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       An object containing requested data
       */
      BCJS.prototype.getWalletBalance = function (type, sourcePublicID) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.GetWalletBalance, { walletTypeString: type, sourcePublicID: sourcePublicID })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
        Gets the available space on a specific device
        ### Example (es3)
        ```js
        bc.getAvailableSpace(1).then(console.log)
        // => {"available":4294967295,"complete":4294967295}
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getAvailableSpace(1))
        // => {"available":4294967295,"complete":4294967295}
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       An object containing requested data, all numbers are in BYTES
       */
      BCJS.prototype.getAvailableSpace = function (device) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.AvailableSpace, { device: device })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
        Gets an ID unique to each device. Will not persist device wipes and will change according to the HTTP Origin. This ID will persist reboots and requires global-pin authorization.
        ### Example (es3)
        ```js
        bc.getDeviceUID(1).then(console.log)
        // => "0x9d8e1b33b93d7c27fb4fc17857e22fb529937947152ca7af441095949b20ba02"
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getDeviceUID(1))
        // => "0x9d8e1b33b93d7c27fb4fc17857e22fb529937947152ca7af441095949b20ba02"
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       The unique ID
       */
      BCJS.prototype.getDeviceUID = function (device) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr, e_3, err;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          _a.trys.push([0, 2, , 3]);
                          return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.DeviceUID, { device: device })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [3 /*break*/, 3];
                      case 2:
                          e_3 = _a.sent();
                          if (e_3.HttpResponse !== undefined) {
                              err = new types_1.DaemonError({
                                  daemonError: 4,
                                  parseError: "Command not found"
                              });
                              throw err;
                          }
                          throw e_3;
                      case 3: return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
        Gets the supported WalletTypes on a specific device
        ### Example (es3)
        ```js
        bc.getSupportedWalletTypes("BitCoin1").then(console.log)
        // => [  "BitCoin1",  "BcCash01",  "Ethereum",  "LiteCoi1",  "Dash0001", ...]
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getSupportedWalletTypes(1))
        // => [  "BitCoin1",  "BcCash01",  "Ethereum",  "LiteCoi1",  "Dash0001", ...]
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       An array containing requested data
       */
      BCJS.prototype.getSupportedWalletTypes = function (device) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.WalletTypes, { device: device })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
        Gets a list of WalletTypes that are actually used on a specific device(have at least one wallet)
        ### Example (es3)
        ```js
        bc.getActiveWalletTypes(1).then(console.log)
        // => ["BitCoin1","Ethereum"]
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getActiveWalletTypes(1))
        // => ["BitCoin1","Ethereum"]
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       An array containing requested data
       */
      BCJS.prototype.getActiveWalletTypes = function (device) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.SavedWalletTypes, { device: device })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
       * @deprecated since 1.3.2, use getBatchWalletDetails instead
        Gets an array(string) of public keys of a specific WalletTypes on a device
        ### Example (es5 (old browsers))
        ```js
        bc.getWalletsOfType(1,"BitCoin1").then(console.log)
        // => ["1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc"]
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getWalletsOfType(1,"BitCoin1"))
        // => ["1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc"]
        ```
        @param device  DeviceID obtained from getDevices
        @param type    WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       An array containing requested data
       */
      BCJS.prototype.getWalletsOfType = function (device, type) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.WalletsOfType, { device: device, walletTypeString: type })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
        Gets the requested data about wallets stored on the device. Details to query can be specified through the final parameter, which is set to query all details by default. Anything not queried will be filled with the empty value of that type, ie '' for strings and 0 for numbers.
        ### Example (es3)
        ```js
        bc.getBatchWalletDetails(1,"BitCoin1").then(console.log)
        // => an array of type WalletBatchDataResponse
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getBatchWalletDetails(1,"BitCoin1"))
        // => an array of type WalletBatchDataResponse
        ```
  
  
        @param device           DeviceID obtained from getDevices
        @param walletTypes      WalletTypes obtained from getActiveWalletTypes or getSupportedWalletTypes
        @param walletDetails    Query details flags, can be combined with binary OR
        @throws                 Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws                 Will throw an AxiosError if the request itself failed or if status code != 200
        @returns                An array containing requested data
       */
      BCJS.prototype.getBatchWalletDetails = function (device, walletTypes, walletDetails) {
          if (walletDetails === void 0) { walletDetails = types_1.WalletDetailsQuery.all; }
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              var _this = this;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          if (walletTypes.length === 0) {
                              return [2 /*return*/, []];
                          }
                          return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.WalletsOfTypes, { device: device, walletTypes: walletTypes, walletDetails: walletDetails })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          httpr.body.data = httpr.body.data.map(function (x) {
                              return __assign(__assign({}, x), { userDataRaw: x.userData, userData: _this.parseHex(x.userData) });
                          });
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
       * @deprecated since 1.3.2, use getBatchWalletDetails instead
        Gets the user data associated with a publicAddress on this device
        ### Example (es3)
        ```js
        bc.getWalletUserData(1,"BitCoin1","1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc",true).then(console.log)
        // => "This is my mining wallet!"
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        console.log(await bc.getWalletUserData(1,"BitCoin1","1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc",true))
        // => "This is my mining wallet!"
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @param type    WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @param publicAddress publicAddress obtained from getWalletsOfType
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       The UserData
       */
      BCJS.prototype.getWalletUserData = function (device, type, publicAddress, shouldParseHex) {
          if (shouldParseHex === void 0) { shouldParseHex = true; }
          return __awaiter(this, void 0, void 0, function () {
              var httpr, responseString;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.WalletUserData, { device: device, walletTypeString: type, sourcePublicID: publicAddress })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          responseString = httpr.body.data;
                          if (shouldParseHex) {
                              responseString = this.parseHex(responseString);
                          }
                          return [2 /*return*/, responseString];
                  }
              });
          });
      };
      /**
        Copies a wallet private key to another walletType (in case of a fork etc.)
        ### Example (es3)
        ```js
        bc.CopyWalletToType(1,"BitCoin1","BcCash01","1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc").then(console.log)
        // => "true"
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        await bc.CopyWalletToType(1,"BitCoin1","BcCash01","1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc")
        // => true
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @param type    WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @param newType WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @param publicAddress publicAddress obtained from getWalletsOfType
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       true if operation was successful, otherwise will throw
       */
      BCJS.prototype.CopyWalletToType = function (device, oldType, newType, publicAddress) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr, id;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getSecureWindowResponse(types_1.PasswordType.WalletPassword)];
                      case 1:
                          id = _a.sent();
                          return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.CopyWalletToType, { device: device, walletTypeString: oldType, newWalletTypeString: newType, sourcePublicID: publicAddress, password: id })];
                      case 2:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, true];
                  }
              });
          });
      };
      /**
        Check if address is valid for a specific WalletType
        ### Example (es3)
        ```js
        bc.getIsAddressValid(1,"BitCoin1","1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc").then(console.log)
        // => "true"
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        await bc.getIsAddressValid(1,"BitCoin1","1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc")
        // => true
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @param type    WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @param publicAddress publicAddress obtained from getWalletsOfType
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       true if address is valid
       */
      BCJS.prototype.getIsAddressValid = function (device, type, publicAddress) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.IsAddressValid, { device: device, walletTypeString: type, address: publicAddress })];
                      case 1:
                          httpr = _a.sent();
                          return [2 /*return*/, httpr.body.errorCode === 0x9000];
                  }
              });
          });
      };
      /**
        Displays address on device for verification
        @deprecated You should not use this function as it is not supported on newer firmwares.
        ### Example (es3)
        ```js
        bc.DisplayAddressOnDevice(1,"BitCoin1","1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc").then(console.log)
        // => "true"
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        await bc.DisplayAddressOnDevice(1,"BitCoin1","1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc")
        // => true
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @param type    WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @param publicAddress publicAddress obtained from getWalletsOfType
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       true if display was successful, otherwise will throw
       */
      BCJS.prototype.DisplayAddressOnDevice = function (device, type, publicAddress) {
          return __awaiter(this, void 0, void 0, function () {
              var httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.DisplayAddress, { device: device, walletTypeString: type, publicID: publicAddress })];
                      case 1:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, true];
                  }
              });
          });
      };
      /**
        Generates a new wallet on the device
        ### Example (es3)
        ```js
        bc.GenerateWallet(1,"BitCoin1").then(console.log)
        // => "true"
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        await bc.GenerateWallet(1,"BitCoin1")
        // => true
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @param type    WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       the public key of the new wallet
       */
      BCJS.prototype.GenerateWallet = function (device, type) {
          return __awaiter(this, void 0, void 0, function () {
              var id, httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getSecureWindowResponse(types_1.PasswordType.WalletPassword)];
                      case 1:
                          id = _a.sent();
                          return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.GenerateWallet, { device: device, walletTypeString: type, password: id })];
                      case 2:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          return [2 /*return*/, httpr.body.data];
                  }
              });
          });
      };
      /**
        Prompt the user to unlock the device
        ### Example (es3)
        ```js
        bc.EnterGlobalPin(1).then(console.log)
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        await bc.EnterGlobalPin(1)
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
       */
      BCJS.prototype.EnterGlobalPin = function (device, passwordType) {
          if (passwordType === void 0) { passwordType = types_1.PasswordType.GlobalPassword; }
          return __awaiter(this, void 0, void 0, function () {
              var id, httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getSecureWindowResponse(passwordType)];
                      case 1:
                          id = _a.sent();
                          this.log("Got pin popup:" + id);
                          return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.EnterGlobalPin, { device: device, password: id })];
                      case 2:
                          httpr = _a.sent();
                          this.assertIsBCHttpResponse(httpr);
                          this.triggerManualUpdate();
                          return [2 /*return*/];
                  }
              });
          });
      };
      /**
        Generates a new transaction on the device
        ### Example (es3)
        ```js
        var trxOptions = {from:"1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc",to:"1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc",feeCount:0,feePrice:"50000",amount:"500000000"};
        bc.GenerateTransaction(1,"BitCoin1",trxOptions).then(console.log)
        // generates a transaction of type bitCoinCash which uses 0.00050000 BCH as fee and sends 5 BCH back to the same address
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        var trxOptions = {from:"1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc",to:"1271DpdZ7iM6sXRasvjAQ6Hg2zw8bS3ADc",feeCount:0,feePrice:"50000",amount:"500000000"};
        await bc.GenerateTransaction(1,"BitCoin1",trxOptions)
        // generates a transaction of type bitCoinCash which uses 0.00050000 BCH as fee and sends 5 BCH back to the same address
        ```
  
  
        @param device    DeviceID obtained from getDevices
        @param type      WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @param data      Transaction data object
        @param broadcast Whether to broadcast the transaction to the blockchain automatically
        @throws          Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws          Will throw an AxiosError if the request itself failed or if status code != 200
        @returns         The raw transaction hex prefixed with '0x' if operation was successful, otherwise will throw
       */
      BCJS.prototype.GenerateTransaction = function (device, type, data, broadcast) {
          return __awaiter(this, void 0, void 0, function () {
              var apiVersion, id, httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getVersion()];
                      case 1:
                          apiVersion = _a.sent();
                          if (data.contractData !== undefined) {
                              // check compatibility
                              if (apiVersion < 4) {
                                  throw new Error("Unsupported parameter: contract data. Update daemon.");
                              }
                          }
                          if (data.memo) {
                              if (apiVersion < 5) {
                                  throw new Error("Unsupported parameter: memo. Update daemon.");
                              }
                          }
                          if (data.advanced && data.advanced.eth && data.advanced.eth.chainID !== undefined) {
                              if (apiVersion < 5) {
                                  throw new Error("Unsupported parameter: advanced.eth.chainID. Update daemon.");
                              }
                          }
                          if (!data.feeCount) {
                              data.feeCount = 0;
                          }
                          return [4 /*yield*/, this.getSecureWindowResponse(types_1.PasswordType.WalletPassword)];
                      case 2:
                          id = _a.sent();
                          this.log("Got auth id:" + id, types_1.LogLevel.debug);
                          this.log("Sending object:" + JSON.stringify({ device: device, walletTypeString: type, transaction: data, password: id }), types_1.LogLevel.debug);
                          return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.GenerateTransaction, { device: device, walletTypeString: type, transaction: data, password: id, broadcast: broadcast })];
                      case 3:
                          httpr = _a.sent();
                          this.log(httpr.body, types_1.LogLevel.debug);
                          this.assertIsBCHttpResponse(httpr);
                          // i know.
                          // tslint:disable-next-line: no-string-literal
                          return [2 /*return*/, httpr.body["data"]];
                  }
              });
          });
      };
      /**
        Signs data on the device
        ### Example (es3)
        ```js
        bc.SignData(1,bc.WalletType.ethereum,"0x9283099a29556fcf8fff5b2cea2d4f67cb7a7a8b","0x4920616d20627574206120737461636b2065786368616e676520706f7374").then(console.log)
        // => "0x..."
        ```
  
        ### Example (es6 (node and most browsers))
        ```js
        await bc.SignData(1,bc.WalletType.ethereum,"0x9283099a29556fcf8fff5b2cea2d4f67cb7a7a8b","0x4920616d20627574206120737461636b2065786368616e676520706f7374")
        // => "0x..."
        ```
  
  
        @param device  DeviceID obtained from getDevices
        @param type    WalletType obtained from getActiveWalletTypes or getSupportedWalletTypes
        @param publicAddress publicAddress obtained from getWalletsOfType
        @param data    Message data as a hex string prefixed with 0x
        @throws        Will throw a DaemonError if the status code of the request was rejected by the server for any reason
        @throws        Will throw an AxiosError if the request itself failed or if status code != 200
        @returns       The raw signed message hex prefixed with '0x' if operation was successful, otherwise will throw
       */
      BCJS.prototype.SignData = function (device, type, publicAddress, data) {
          return __awaiter(this, void 0, void 0, function () {
              var id, httpr;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.getSecureWindowResponse(types_1.PasswordType.WalletPassword)];
                      case 1:
                          id = _a.sent();
                          this.log("Got auth id:" + id, types_1.LogLevel.debug);
                          this.log("Sending object:" + JSON.stringify({ device: device, walletTypeString: type, sourcePublicID: publicAddress, srcData: data, password: id }), types_1.LogLevel.debug);
                          return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.SignData, { device: device, walletTypeString: type, sourcePublicID: publicAddress, srcData: data, password: id })];
                      case 2:
                          httpr = _a.sent();
                          this.log("Response body:" + httpr.body, types_1.LogLevel.debug);
                          this.assertIsBCHttpResponse(httpr);
                          // i know.
                          // tslint:disable-next-line: no-string-literal
                          return [2 /*return*/, httpr.body["data"]];
                  }
              });
          });
      };
      BCJS.prototype.web3_GetAccounts = function (cb) {
          return __awaiter(this, void 0, void 0, function () {
              var devices, wallets, e_4, wallets, e_5;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          _a.trys.push([0, 9, , 10]);
                          return [4 /*yield*/, this.getDevices()];
                      case 1:
                          devices = _a.sent();
                          if (devices.length === 0) {
                              cb("No BC Vault connected");
                              return [2 /*return*/];
                          }
                          _a.label = 2;
                      case 2:
                          _a.trys.push([2, 4, , 8]);
                          return [4 /*yield*/, this.getWalletsOfType(devices[0], types_1.WalletType.ethereum)];
                      case 3:
                          wallets = _a.sent();
                          cb(null, wallets.map(function (x) { return "0x" + x; }));
                          return [3 /*break*/, 8];
                      case 4:
                          e_4 = _a.sent();
                          if (!(e_4.BCHttpResponse !== undefined)) return [3 /*break*/, 7];
                          // unlock BC Vault!
                          return [4 /*yield*/, this.EnterGlobalPin(devices[0], types_1.PasswordType.GlobalPassword)];
                      case 5:
                          // unlock BC Vault!
                          _a.sent();
                          return [4 /*yield*/, this.getWalletsOfType(devices[0], types_1.WalletType.ethereum)];
                      case 6:
                          wallets = _a.sent();
                          return [2 /*return*/, cb(null, wallets.map(function (x) { return "0x" + x; }))];
                      case 7: return [3 /*break*/, 8];
                      case 8: return [3 /*break*/, 10];
                      case 9:
                          e_5 = _a.sent();
                          cb(e_5, null);
                          return [3 /*break*/, 10];
                      case 10: return [2 /*return*/];
                  }
              });
          });
      };
      BCJS.prototype.web3_signTransaction = function (txParams, cb) {
          return __awaiter(this, void 0, void 0, function () {
              var devices, txHex, e_6;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          _a.trys.push([0, 3, , 4]);
                          return [4 /*yield*/, this.getDevices()];
                      case 1:
                          devices = _a.sent();
                          if (devices.length === 0) {
                              cb("No BC Vault connected");
                              return [2 /*return*/];
                          }
                          txParams.feePrice = txParams.gasPrice;
                          txParams.feeCount = txParams.gas;
                          txParams.amount = txParams.value;
                          txParams.from = this.toEtherCase(this.strip0x(txParams.from));
                          return [4 /*yield*/, this.GenerateTransaction(devices[devices.length - 1], types_1.WalletType.ethereum, txParams)];
                      case 2:
                          txHex = _a.sent();
                          cb(null, txHex);
                          return [3 /*break*/, 4];
                      case 3:
                          e_6 = _a.sent();
                          cb(e_6, null);
                          return [3 /*break*/, 4];
                      case 4: return [2 /*return*/];
                  }
              });
          });
      };
      BCJS.prototype.web3_signPersonalMessage = function (msgParams, cb) {
          return __awaiter(this, void 0, void 0, function () {
              var devices, signedMessage, e_7;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          _a.trys.push([0, 3, , 4]);
                          return [4 /*yield*/, this.getDevices()];
                      case 1:
                          devices = _a.sent();
                          if (devices.length === 0) {
                              cb("No BC Vault connected");
                              return [2 /*return*/];
                          }
                          msgParams.from = this.toEtherCase(this.strip0x(msgParams.from));
                          return [4 /*yield*/, this.SignData(devices[devices.length - 1], types_1.WalletType.ethereum, msgParams.from, msgParams.data)];
                      case 2:
                          signedMessage = _a.sent();
                          cb(null, signedMessage);
                          return [3 /*break*/, 4];
                      case 3:
                          e_7 = _a.sent();
                          cb(e_7, null);
                          return [3 /*break*/, 4];
                      case 4: return [2 /*return*/];
                  }
              });
          });
      };
      BCJS.prototype.strip0x = function (str) {
          if (str.startsWith('0x')) {
              return str.substr(2);
          }
          return str;
      };
      BCJS.prototype.toEtherCase = function (inputString) {
          return inputString.toUpperCase();
      };
      BCJS.prototype.parseHex = function (str) {
          var out = str;
          if (out.length % 2 === 0) {
              out = out.substr(2); // remove 0x
              var responseStringArray = __spread(out);
              var byteArrayStr = [];
              for (var i = 0; i < responseStringArray.length; i += 2) {
                  byteArrayStr.push(parseInt(responseStringArray[i] + responseStringArray[i + 1], 16));
              }
              out = String.fromCharCode.apply(String, __spread(byteArrayStr));
          }
          return out;
      };
      BCJS.prototype.getServerURL = function () {
          return 'https://localhost:1991';
      };
      BCJS.prototype.getNewSession = function () {
          return __awaiter(this, void 0, void 0, function () {
              var scp, axiosConfig, response;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          scp = {
                              sessionType: this.authTokenUseCookies ? types_1.SessionAuthType.any : types_1.SessionAuthType.token,
                              expireSeconds: this.authTokenExpireSeconds,
                              matchPath: this.authTokenMatchPath,
                              versionNumber: this.API_VERSION
                          };
                          axiosConfig = {
                              baseURL: this.getServerURL(),
                              method: "POST",
                              url: 'SetBCSessionParams',
                              withCredentials: true,
                              data: scp,
                              headers: { "Api-Version": this.API_VERSION }
                          };
                          if (typeof (window) === 'undefined') {
                              axiosConfig.headers.Origin = "https://localhost";
                              axiosConfig.headers.Referer = "https://localhost";
                          }
                          return [4 /*yield*/, axios_1["default"](axiosConfig)];
                      case 1:
                          response = _a.sent();
                          return [2 /*return*/, response.data.d_token];
                  }
              });
          });
      };
      BCJS.prototype.getVersion = function () {
          return __awaiter(this, void 0, void 0, function () {
              var response;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          if (!(this.REMOTE_API_VERSION === undefined)) return [3 /*break*/, 2];
                          this.log('Getting remote version...', types_1.LogLevel.verbose);
                          return [4 /*yield*/, axios_1["default"](this.getServerURL() + '/version')];
                      case 1:
                          response = _a.sent();
                          this.REMOTE_API_VERSION = parseInt(response.data, 10);
                          this.log('Got remote version:' + this.REMOTE_API_VERSION, types_1.LogLevel.verbose);
                          _a.label = 2;
                      case 2: return [2 /*return*/, this.REMOTE_API_VERSION];
                  }
              });
          });
      };
      BCJS.prototype.getResponsePromised = function (endpoint, data) {
          var _this = this;
          var dataWithToken = __assign(__assign({}, (data || {})), { d_token: this.authToken });
          return new Promise(function (res, rej) { return __awaiter(_this, void 0, void 0, function () {
              var methodCheck, e_8, options, responseFunction;
              var _this = this;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          if (!(this.endpointAllowsCredentials === undefined)) return [3 /*break*/, 4];
                          _a.label = 1;
                      case 1:
                          _a.trys.push([1, 3, , 4]);
                          return [4 /*yield*/, axios_1["default"]({ baseURL: this.getServerURL(), data: "{}", method: "POST", url: "/Devices" })];
                      case 2:
                          methodCheck = _a.sent();
                          this.endpointAllowsCredentials = methodCheck.data.daemonError === types_1.DaemonErrorCodes.sessionError;
                          return [3 /*break*/, 4];
                      case 3:
                          e_8 = _a.sent();
                          this.log("Daemon offline during initialization.", types_1.LogLevel.debug);
                          return [2 /*return*/, rej(new types_1.DaemonError(e_8))];
                      case 4:
                          options = {
                              baseURL: this.getServerURL(),
                              data: JSON.stringify(dataWithToken),
                              method: "POST",
                              url: endpoint,
                              headers: {}
                          };
                          if (this.endpointAllowsCredentials && this.authTokenUseCookies) {
                              options.withCredentials = true;
                              options.headers["Api-Version"] = this.API_VERSION;
                          }
                          if (typeof (window) === 'undefined') {
                              options.headers.Origin = "https://localhost";
                              options.headers.Referer = "https://localhost";
                          }
                          this.log("getResponsePromised - " + endpoint + " - " + options.data);
                          responseFunction = function (response) { return __awaiter(_this, void 0, void 0, function () {
                              var htpr, _a;
                              var _this = this;
                              return __generator(this, function (_b) {
                                  switch (_b.label) {
                                      case 0:
                                          htpr = { status: response.status, body: response.data };
                                          if (!(response.data.daemonError === types_1.DaemonErrorCodes.sessionError)) return [3 /*break*/, 2];
                                          this.log("Creating new session.", types_1.LogLevel.debug);
                                          _a = this;
                                          return [4 /*yield*/, this.getNewSession()];
                                      case 1:
                                          _a.authToken = _b.sent();
                                          this.log("New session created: " + this.authToken, types_1.LogLevel.debug);
                                          options.data = JSON.stringify(__assign(__assign({}, dataWithToken), { d_token: this.authToken }));
                                          axios_1["default"](options).then(function (authenticatedResponse) {
                                              if (authenticatedResponse.data.daemonError) {
                                                  return rej(new types_1.DaemonError(authenticatedResponse.data));
                                              }
                                              else {
                                                  return res({ status: authenticatedResponse.status, body: authenticatedResponse.data });
                                              }
                                          })["catch"](function (e) {
                                              _this.log("Daemon request failed: " + JSON.stringify(e), types_1.LogLevel.warning);
                                              rej(new types_1.DaemonError(e));
                                          });
                                          return [2 /*return*/];
                                      case 2:
                                          res(htpr);
                                          return [2 /*return*/];
                                  }
                              });
                          }); };
                          axios_1["default"](options).then(responseFunction)["catch"](function (e) {
                              _this.log("Daemon request failed: " + JSON.stringify(e), types_1.LogLevel.warning);
                              rej(new types_1.DaemonError(e));
                          });
                          return [2 /*return*/];
                  }
              });
          }); });
      };
      BCJS.prototype.assertIsBCHttpResponse = function (httpr) {
          if (httpr.body.errorCode !== 0x9000) {
              throw new types_1.DaemonError(httpr.body);
          }
      };
      BCJS.prototype.log = function (msg, level) {
          if (level === void 0) { level = types_1.LogLevel.verbose; }
          if (this.logLevel <= level) {
              console.log('[' + new Date(Date.now()).toLocaleTimeString() + ']: ' + msg);
          }
      };
      BCJS.prototype.getWallets = function (deviceID, activeTypes) {
          return __awaiter(this, void 0, void 0, function () {
              var ret, response, response_1, response_1_1, detailItem;
              var e_9, _a;
              return __generator(this, function (_b) {
                  switch (_b.label) {
                      case 0:
                          ret = [];
                          if (activeTypes.length === 0) {
                              return [2 /*return*/, []];
                          }
                          return [4 /*yield*/, this.getBatchWalletDetails(deviceID, activeTypes)];
                      case 1:
                          response = _b.sent();
                          try {
                              for (response_1 = __values(response), response_1_1 = response_1.next(); !response_1_1.done; response_1_1 = response_1.next()) {
                                  detailItem = response_1_1.value;
                                  ret.push({
                                      publicKey: detailItem.address,
                                      userData: detailItem.userData,
                                      userDataRaw: detailItem.userDataRaw,
                                      extraData: detailItem.extraData,
                                      walletType: detailItem.type
                                  });
                              }
                          }
                          catch (e_9_1) { e_9 = { error: e_9_1 }; }
                          finally {
                              try {
                                  if (response_1_1 && !response_1_1.done && (_a = response_1["return"])) _a.call(response_1);
                              }
                              finally { if (e_9) throw e_9.error; }
                          }
                          return [2 /*return*/, ret];
                  }
              });
          });
      };
      BCJS.prototype.arraysEqual = function (a, b) {
          var equal = a.length === b.length;
          for (var i = 0; i < a.length && equal; i++) {
              equal = a[i] === b[i];
          }
          return equal;
      };
      BCJS.prototype.pollDevicesChanged = function (interval) {
          var _this = this;
          this.timeoutRef = setTimeout(function () { return _this.pollDevicesChanged(interval); }, interval);
          return new Promise(function (res) { return __awaiter(_this, void 0, void 0, function () {
              var e_10;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          _a.trys.push([0, 2, , 3]);
                          return [4 /*yield*/, this.triggerManualUpdate(false)];
                      case 1:
                          _a.sent();
                          res();
                          return [3 /*break*/, 3];
                      case 2:
                          e_10 = _a.sent();
                          this.FireAllStatusListeners(-1);
                          console.error(e_10);
                          return [3 /*break*/, 3];
                      case 3: return [2 /*return*/];
                  }
              });
          }); });
      };
      BCJS.prototype.FireAllStatusListeners = function (args) {
          var e_11, _a;
          this.lastPushedStatus = args;
          try {
              for (var _b = __values(this.listeners), _c = _b.next(); !_c.done; _c = _b.next()) {
                  var listener = _c.value;
                  listener.call(null, args);
              }
          }
          catch (e_11_1) { e_11 = { error: e_11_1 }; }
          finally {
              try {
                  if (_c && !_c.done && (_a = _b["return"])) _a.call(_b);
              }
              finally { if (e_11) throw e_11.error; }
          }
      };
      BCJS.prototype.showAuthPopup = function (id, passwordType, popupReference) {
          var _this = this;
          return new Promise(function (res) { return __awaiter(_this, void 0, void 0, function () {
              var isIE, timer_1;
              return __generator(this, function (_a) {
                  isIE = window.ActiveXObject || "ActiveXObject" in window;
                  if (isIE) {
                      window.showModalDialog(this.getServerURL() + "/PasswordInput?channelID=" + id + "&channelPasswordType=" + passwordType);
                      parent.postMessage("OKAY", "*");
                      res();
                  }
                  else {
                      popupReference.location.href = this.getServerURL() + "/PasswordInput?channelID=" + id + "&channelPasswordType=" + passwordType;
                      timer_1 = setInterval(function () {
                          if (popupReference.closed) {
                              clearInterval(timer_1);
                              res();
                          }
                      }, 500);
                  }
                  return [2 /*return*/];
              });
          }); });
      };
      BCJS.prototype.getSecureWindowResponse = function (passwordType) {
          return __awaiter(this, void 0, void 0, function () {
              var preAuthObj, isIE, x, id;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          if (this.preAuthHandler === undefined) {
                              isIE = window.ActiveXObject || "ActiveXObject" in window;
                              if (window && !isIE) {
                                  preAuthObj = window.open('127.0.0.1', '_blank', 'location=yes,menubar=yes,resizable=no,scrollbars=no,status=no,toolbar=no,centerscreen=yes,width=750,height=500');
                                  if (preAuthObj === null) {
                                      throw new types_1.DaemonError(types_1.JSErrorCode.popupCreateFailed, 'Could not create popup!');
                                  }
                              }
                          }
                          else {
                              preAuthObj = this.preAuthHandler(passwordType);
                          }
                          return [4 /*yield*/, this.getResponsePromised(types_1.Endpoint.GetAuthID)];
                      case 1:
                          x = _a.sent();
                          id = x.body;
                          if (!(this.authHandler === undefined)) return [3 /*break*/, 3];
                          return [4 /*yield*/, this.showAuthPopup(id, passwordType, preAuthObj)];
                      case 2:
                          _a.sent();
                          return [3 /*break*/, 5];
                      case 3: return [4 /*yield*/, this.authHandler(id, passwordType, preAuthObj)];
                      case 4:
                          _a.sent();
                          _a.label = 5;
                      case 5: return [2 /*return*/, id];
                  }
              });
          });
      };
      return BCJS;
  }());
  exports.BCJS = BCJS;
  
  },{"./types":4,"axios":5,"es6-promise":32}],4:[function(require,module,exports){
  "use strict";
  var __extends = (this && this.__extends) || (function () {
      var extendStatics = function (d, b) {
          extendStatics = Object.setPrototypeOf ||
              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
              function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
          return extendStatics(d, b);
      };
      return function (d, b) {
          extendStatics(d, b);
          function __() { this.constructor = d; }
          d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
      };
  })();
  exports.__esModule = true;
  exports.WalletDetailsQuery = exports.JSErrorCode = exports.DaemonErrorCodes = exports.SessionAuthType = exports.PasswordType = exports.BCDataRefreshStatusCode = exports.typeInfoMap = exports.WalletType = exports.Endpoint = exports.DaemonError = exports.StellarCreateAccount = exports.AddressType = exports.LogLevel = void 0;
  var LogLevel;
  (function (LogLevel) {
      LogLevel[LogLevel["verbose"] = 1] = "verbose";
      LogLevel[LogLevel["debug"] = 2] = "debug";
      LogLevel[LogLevel["warning"] = 3] = "warning";
      LogLevel[LogLevel["error"] = 4] = "error";
  })(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
  /**
   * @description the type of address, segwit, legacy etc...
   */
  var AddressType;
  (function (AddressType) {
      AddressType[AddressType["All"] = 0] = "All";
      AddressType[AddressType["PKH"] = 1] = "PKH";
      AddressType[AddressType["PSH"] = 2] = "PSH";
      AddressType[AddressType["P2WPKH"] = 3] = "P2WPKH";
      AddressType[AddressType["B32"] = 4] = "B32";
      AddressType[AddressType["BCHNew"] = 5] = "BCHNew";
      AddressType[AddressType["EOSAccount"] = 6] = "EOSAccount";
      AddressType[AddressType["EOSOwner"] = 7] = "EOSOwner";
      AddressType[AddressType["EOSActive"] = 8] = "EOSActive";
      AddressType[AddressType["EOS"] = 9] = "EOS";
      AddressType[AddressType["EOSK1"] = 10] = "EOSK1";
      AddressType[AddressType["err"] = 11] = "err";
  })(AddressType = exports.AddressType || (exports.AddressType = {}));
  var StellarCreateAccount;
  (function (StellarCreateAccount) {
      StellarCreateAccount[StellarCreateAccount["No"] = 0] = "No";
      StellarCreateAccount[StellarCreateAccount["Yes"] = 1] = "Yes";
      StellarCreateAccount[StellarCreateAccount["FetchFromNetwork"] = 255] = "FetchFromNetwork";
  })(StellarCreateAccount = exports.StellarCreateAccount || (exports.StellarCreateAccount = {}));
  /**
   * @description The DaemonError class contains a BCHttpResponse, HttpResponse, DaemonHttpResponse, or , depending on where the failure was
   * @description HttpResponse !== undefined if the response code was != 200 or if the request itself failed
   * @description BCHttpResponse !== undefined if the request succeeded but the device returned an error code.
   */
  var DaemonError = /** @class */ (function (_super) {
      __extends(DaemonError, _super);
      // tslint:disable: no-string-literal
      function DaemonError(data, m) {
          if (m === void 0) { m = "DaemonError"; }
          var _this = _super.call(this, m) || this;
          // Set the prototype explicitly.
          Object.setPrototypeOf(_this, DaemonError.prototype);
          _this.name = "DaemonError";
          if (data['config'] !== undefined) {
              _this.HttpResponse = data;
              return _this;
          }
          if (data['errorCode'] !== undefined) {
              _this.BCHttpResponse = data;
              return _this;
          }
          if (data['daemonError'] !== undefined) {
              _this.DaemonHttpResponse = data;
              return _this;
          }
          if (typeof (data) === typeof (JSErrorCode.popupCreateFailed)) {
              _this.jsError = data;
              return _this;
          }
          throw new Error('Error could not be parsed, this should never happen.');
          return _this;
      }
      return DaemonError;
  }(Error));
  exports.DaemonError = DaemonError;
  var Endpoint;
  (function (Endpoint) {
      Endpoint["Devices"] = "Devices";
      Endpoint["FirmwareVersion"] = "FirmwareVersion";
      Endpoint["AvailableSpace"] = "AvailableSpace";
      Endpoint["WalletTypes"] = "WalletTypes";
      Endpoint["SavedWalletTypes"] = "SavedWalletTypes";
      Endpoint["WalletsOfType"] = "WalletsOfType";
      Endpoint["WalletsOfTypes"] = "WalletsOfTypes";
      Endpoint["GenerateWallet"] = "GenerateWallet";
      Endpoint["WalletUserData"] = "WalletUserData";
      Endpoint["GenerateTransaction"] = "GenerateTransaction";
      Endpoint["SignTransactionData"] = "SignTransactionData";
      Endpoint["CopyWalletToType"] = "CopyWalletToType";
      Endpoint["IsAddressValid"] = "IsAddressValid";
      Endpoint["EnterGlobalPin"] = "EnterGlobalPin";
      Endpoint["DisplayAddress"] = "DisplayAddress";
      Endpoint["PasswordInput"] = "PasswordInput";
      Endpoint["GetAuthID"] = "GetAuthID";
      Endpoint["GetWalletBalance"] = "WalletBalance";
      Endpoint["SignData"] = "SignData";
      Endpoint["DeviceUID"] = "DeviceUID";
  })(Endpoint = exports.Endpoint || (exports.Endpoint = {}));
  var WalletType;
  (function (WalletType) {
      WalletType[WalletType["none"] = 0] = "none";
      WalletType["bitCoin"] = "BitCoin1";
      WalletType["ethereum"] = "Ethereum";
      WalletType["ripple"] = "Ripple01";
      WalletType["stellar"] = "Stellar1";
      WalletType["eos"] = "Eos____1";
      WalletType["binanceCoin"] = "Bnb____1";
      WalletType["tron"] = "Tron___1";
      WalletType["bitCoinCash"] = "BcCash01";
      WalletType["bitcoinGold"] = "BcGold01";
      WalletType["liteCoin"] = "LiteCoi1";
      WalletType["dash"] = "Dash0001";
      WalletType["dogeCoin"] = "DogeCoi1";
      WalletType["groestlcoin"] = "Groestl1";
      WalletType["velas"] = "Velas__1";
      WalletType["cardano"] = "Cardano1";
      WalletType["erc20Salt"] = "E2Salt_1";
      WalletType["erc20Polymath"] = "E2Polym1";
      WalletType["erc200x"] = "E2_0X__1";
      WalletType["erc20Cindicator"] = "E2Cindi1";
      WalletType["erc20CargoX"] = "E2Cargo1";
      WalletType["erc20Viberate"] = "E2Viber1";
      WalletType["erc20Iconomi"] = "E2Icono1";
      WalletType["erc20DTR"] = "E2DynTR1";
      WalletType["erc20OriginTrail"] = "E2OriTr1";
      WalletType["erc20InsurePal"] = "E2InsuP1";
      WalletType["erc20Xaurum"] = "E2Xauru1";
      WalletType["erc20OmiseGo"] = "E2Omise1";
      WalletType["erc20WaltonChain"] = "E2WaltC1";
  })(WalletType = exports.WalletType || (exports.WalletType = {}));
  exports.typeInfoMap = [
      { type: WalletType.bitCoin, name: "Bitcoin", ticker: "BTC" },
      { type: WalletType.ethereum, name: "Ethereum", ticker: "ETH" },
      { type: WalletType.bitCoinCash, name: "Bitcoin Cash", ticker: "BCH" },
      { type: WalletType.liteCoin, name: "Litecoin", ticker: "LTC" },
      { type: WalletType.dash, name: "Dash", ticker: "DASH" },
      { type: WalletType.dogeCoin, name: "Dogecoin", ticker: "DOGE" },
      { type: WalletType.eos, name: "EOS", ticker: "EOS" },
      { type: WalletType.binanceCoin, name: "Binance", ticker: "BNB" },
      { type: WalletType.tron, name: "TRON", ticker: "TRX" },
      { type: WalletType.groestlcoin, name: "Groestlcoin", ticker: "GRS" },
      { type: WalletType.velas, name: "Velas", ticker: "VLX" },
      { type: WalletType.cardano, name: "Cardano", ticker: "ADA" },
      { type: WalletType.erc20Salt, name: "Salt", ticker: "SALT" },
      { type: WalletType.erc20Polymath, name: "Polymath", ticker: "POLY" },
      { type: WalletType.erc200x, name: "0X", ticker: "ZRX" },
      { type: WalletType.erc20Cindicator, name: "Cindicator", ticker: "CND" },
      { type: WalletType.erc20CargoX, name: "CargoX", ticker: "CXO" },
      { type: WalletType.erc20Viberate, name: "Viberate", ticker: "VIB" },
      { type: WalletType.erc20Iconomi, name: "Iconomi", ticker: "ICN" },
      { type: WalletType.erc20DTR, name: "Dynamic Trading Rights", ticker: "DTR" },
      { type: WalletType.erc20OriginTrail, name: "OriginTrail", ticker: "TRAC" },
      { type: WalletType.erc20InsurePal, name: "InsurePal", ticker: "IPL" },
      { type: WalletType.erc20Xaurum, name: "Xaurum", ticker: "XAURUM" },
      { type: WalletType.erc20OmiseGo, name: "OmiseGo", ticker: "OMG" },
      { type: WalletType.erc20WaltonChain, name: "WaltonChain", ticker: "WTC" },
      { type: WalletType.ripple, name: "Ripple", ticker: "XRP" },
      { type: WalletType.stellar, name: "Stellar", ticker: "XLM" },
  ];
  var BCDataRefreshStatusCode;
  (function (BCDataRefreshStatusCode) {
      BCDataRefreshStatusCode[BCDataRefreshStatusCode["ConnectionError"] = -1] = "ConnectionError";
      BCDataRefreshStatusCode[BCDataRefreshStatusCode["Ready"] = 0] = "Ready";
      BCDataRefreshStatusCode[BCDataRefreshStatusCode["Working"] = 1] = "Working";
  })(BCDataRefreshStatusCode = exports.BCDataRefreshStatusCode || (exports.BCDataRefreshStatusCode = {}));
  var PasswordType;
  (function (PasswordType) {
      PasswordType["WalletPassword"] = "wallet";
      PasswordType["GlobalPassword"] = "global";
  })(PasswordType = exports.PasswordType || (exports.PasswordType = {}));
  var SessionAuthType;
  (function (SessionAuthType) {
      SessionAuthType["token"] = "token";
      SessionAuthType["any"] = "any";
  })(SessionAuthType = exports.SessionAuthType || (exports.SessionAuthType = {}));
  var DaemonErrorCodes;
  (function (DaemonErrorCodes) {
      DaemonErrorCodes[DaemonErrorCodes["sessionError"] = 1] = "sessionError";
      DaemonErrorCodes[DaemonErrorCodes["parameterError"] = 2] = "parameterError";
      DaemonErrorCodes[DaemonErrorCodes["httpsInvalid"] = 3] = "httpsInvalid";
  })(DaemonErrorCodes = exports.DaemonErrorCodes || (exports.DaemonErrorCodes = {}));
  var JSErrorCode;
  (function (JSErrorCode) {
      JSErrorCode[JSErrorCode["popupCreateFailed"] = 1] = "popupCreateFailed";
  })(JSErrorCode = exports.JSErrorCode || (exports.JSErrorCode = {}));
  var WalletDetailsQuery;
  (function (WalletDetailsQuery) {
      WalletDetailsQuery[WalletDetailsQuery["none"] = 0] = "none";
      WalletDetailsQuery[WalletDetailsQuery["userData"] = 1] = "userData";
      WalletDetailsQuery[WalletDetailsQuery["extraData"] = 2] = "extraData";
      WalletDetailsQuery[WalletDetailsQuery["status"] = 4] = "status";
      WalletDetailsQuery[WalletDetailsQuery["all"] = 4294967295] = "all";
  })(WalletDetailsQuery = exports.WalletDetailsQuery || (exports.WalletDetailsQuery = {}));
  
  },{}],5:[function(require,module,exports){
  module.exports = require('./lib/axios');
  },{"./lib/axios":7}],6:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  var settle = require('./../core/settle');
  var cookies = require('./../helpers/cookies');
  var buildURL = require('./../helpers/buildURL');
  var buildFullPath = require('../core/buildFullPath');
  var parseHeaders = require('./../helpers/parseHeaders');
  var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
  var createError = require('../core/createError');
  
  module.exports = function xhrAdapter(config) {
    return new Promise(function dispatchXhrRequest(resolve, reject) {
      var requestData = config.data;
      var requestHeaders = config.headers;
  
      if (utils.isFormData(requestData)) {
        delete requestHeaders['Content-Type']; // Let the browser set it
      }
  
      var request = new XMLHttpRequest();
  
      // HTTP basic authentication
      if (config.auth) {
        var username = config.auth.username || '';
        var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
        requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
      }
  
      var fullPath = buildFullPath(config.baseURL, config.url);
      request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
  
      // Set the request timeout in MS
      request.timeout = config.timeout;
  
      // Listen for ready state
      request.onreadystatechange = function handleLoad() {
        if (!request || request.readyState !== 4) {
          return;
        }
  
        // The request errored out and we didn't get a response, this will be
        // handled by onerror instead
        // With one exception: request that using file: protocol, most browsers
        // will return status as 0 even though it's a successful request
        if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
          return;
        }
  
        // Prepare the response
        var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
        var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
        var response = {
          data: responseData,
          status: request.status,
          statusText: request.statusText,
          headers: responseHeaders,
          config: config,
          request: request
        };
  
        settle(resolve, reject, response);
  
        // Clean up request
        request = null;
      };
  
      // Handle browser request cancellation (as opposed to a manual cancellation)
      request.onabort = function handleAbort() {
        if (!request) {
          return;
        }
  
        reject(createError('Request aborted', config, 'ECONNABORTED', request));
  
        // Clean up request
        request = null;
      };
  
      // Handle low level network errors
      request.onerror = function handleError() {
        // Real errors are hidden from us by the browser
        // onerror should only fire if it's a network error
        reject(createError('Network Error', config, null, request));
  
        // Clean up request
        request = null;
      };
  
      // Handle timeout
      request.ontimeout = function handleTimeout() {
        var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
        if (config.timeoutErrorMessage) {
          timeoutErrorMessage = config.timeoutErrorMessage;
        }
        reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
          request));
  
        // Clean up request
        request = null;
      };
  
      // Add xsrf header
      // This is only done if running in a standard browser environment.
      // Specifically not if we're in a web worker, or react-native.
      if (utils.isStandardBrowserEnv()) {
        // Add xsrf header
        var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
          cookies.read(config.xsrfCookieName) :
          undefined;
  
        if (xsrfValue) {
          requestHeaders[config.xsrfHeaderName] = xsrfValue;
        }
      }
  
      // Add headers to the request
      if ('setRequestHeader' in request) {
        utils.forEach(requestHeaders, function setRequestHeader(val, key) {
          if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
            // Remove Content-Type if data is undefined
            delete requestHeaders[key];
          } else {
            // Otherwise add header to the request
            request.setRequestHeader(key, val);
          }
        });
      }
  
      // Add withCredentials to request if needed
      if (!utils.isUndefined(config.withCredentials)) {
        request.withCredentials = !!config.withCredentials;
      }
  
      // Add responseType to request if needed
      if (config.responseType) {
        try {
          request.responseType = config.responseType;
        } catch (e) {
          // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
          // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
          if (config.responseType !== 'json') {
            throw e;
          }
        }
      }
  
      // Handle progress if needed
      if (typeof config.onDownloadProgress === 'function') {
        request.addEventListener('progress', config.onDownloadProgress);
      }
  
      // Not all browsers support upload events
      if (typeof config.onUploadProgress === 'function' && request.upload) {
        request.upload.addEventListener('progress', config.onUploadProgress);
      }
  
      if (config.cancelToken) {
        // Handle cancellation
        config.cancelToken.promise.then(function onCanceled(cancel) {
          if (!request) {
            return;
          }
  
          request.abort();
          reject(cancel);
          // Clean up request
          request = null;
        });
      }
  
      if (!requestData) {
        requestData = null;
      }
  
      // Send the request
      request.send(requestData);
    });
  };
  
  },{"../core/buildFullPath":13,"../core/createError":14,"./../core/settle":18,"./../helpers/buildURL":22,"./../helpers/cookies":24,"./../helpers/isURLSameOrigin":27,"./../helpers/parseHeaders":29,"./../utils":31}],7:[function(require,module,exports){
  'use strict';
  
  var utils = require('./utils');
  var bind = require('./helpers/bind');
  var Axios = require('./core/Axios');
  var mergeConfig = require('./core/mergeConfig');
  var defaults = require('./defaults');
  
  /**
   * Create an instance of Axios
   *
   * @param {Object} defaultConfig The default config for the instance
   * @return {Axios} A new instance of Axios
   */
  function createInstance(defaultConfig) {
    var context = new Axios(defaultConfig);
    var instance = bind(Axios.prototype.request, context);
  
    // Copy axios.prototype to instance
    utils.extend(instance, Axios.prototype, context);
  
    // Copy context to instance
    utils.extend(instance, context);
  
    return instance;
  }
  
  // Create the default instance to be exported
  var axios = createInstance(defaults);
  
  // Expose Axios class to allow class inheritance
  axios.Axios = Axios;
  
  // Factory for creating new instances
  axios.create = function create(instanceConfig) {
    return createInstance(mergeConfig(axios.defaults, instanceConfig));
  };
  
  // Expose Cancel & CancelToken
  axios.Cancel = require('./cancel/Cancel');
  axios.CancelToken = require('./cancel/CancelToken');
  axios.isCancel = require('./cancel/isCancel');
  
  // Expose all/spread
  axios.all = function all(promises) {
    return Promise.all(promises);
  };
  axios.spread = require('./helpers/spread');
  
  // Expose isAxiosError
  axios.isAxiosError = require('./helpers/isAxiosError');
  
  module.exports = axios;
  
  // Allow use of default import syntax in TypeScript
  module.exports.default = axios;
  
  },{"./cancel/Cancel":8,"./cancel/CancelToken":9,"./cancel/isCancel":10,"./core/Axios":11,"./core/mergeConfig":17,"./defaults":20,"./helpers/bind":21,"./helpers/isAxiosError":26,"./helpers/spread":30,"./utils":31}],8:[function(require,module,exports){
  'use strict';
  
  /**
   * A `Cancel` is an object that is thrown when an operation is canceled.
   *
   * @class
   * @param {string=} message The message.
   */
  function Cancel(message) {
    this.message = message;
  }
  
  Cancel.prototype.toString = function toString() {
    return 'Cancel' + (this.message ? ': ' + this.message : '');
  };
  
  Cancel.prototype.__CANCEL__ = true;
  
  module.exports = Cancel;
  
  },{}],9:[function(require,module,exports){
  'use strict';
  
  var Cancel = require('./Cancel');
  
  /**
   * A `CancelToken` is an object that can be used to request cancellation of an operation.
   *
   * @class
   * @param {Function} executor The executor function.
   */
  function CancelToken(executor) {
    if (typeof executor !== 'function') {
      throw new TypeError('executor must be a function.');
    }
  
    var resolvePromise;
    this.promise = new Promise(function promiseExecutor(resolve) {
      resolvePromise = resolve;
    });
  
    var token = this;
    executor(function cancel(message) {
      if (token.reason) {
        // Cancellation has already been requested
        return;
      }
  
      token.reason = new Cancel(message);
      resolvePromise(token.reason);
    });
  }
  
  /**
   * Throws a `Cancel` if cancellation has been requested.
   */
  CancelToken.prototype.throwIfRequested = function throwIfRequested() {
    if (this.reason) {
      throw this.reason;
    }
  };
  
  /**
   * Returns an object that contains a new `CancelToken` and a function that, when called,
   * cancels the `CancelToken`.
   */
  CancelToken.source = function source() {
    var cancel;
    var token = new CancelToken(function executor(c) {
      cancel = c;
    });
    return {
      token: token,
      cancel: cancel
    };
  };
  
  module.exports = CancelToken;
  
  },{"./Cancel":8}],10:[function(require,module,exports){
  'use strict';
  
  module.exports = function isCancel(value) {
    return !!(value && value.__CANCEL__);
  };
  
  },{}],11:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  var buildURL = require('../helpers/buildURL');
  var InterceptorManager = require('./InterceptorManager');
  var dispatchRequest = require('./dispatchRequest');
  var mergeConfig = require('./mergeConfig');
  
  /**
   * Create a new instance of Axios
   *
   * @param {Object} instanceConfig The default config for the instance
   */
  function Axios(instanceConfig) {
    this.defaults = instanceConfig;
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }
  
  /**
   * Dispatch a request
   *
   * @param {Object} config The config specific for this request (merged with this.defaults)
   */
  Axios.prototype.request = function request(config) {
    /*eslint no-param-reassign:0*/
    // Allow for axios('example/url'[, config]) a la fetch API
    if (typeof config === 'string') {
      config = arguments[1] || {};
      config.url = arguments[0];
    } else {
      config = config || {};
    }
  
    config = mergeConfig(this.defaults, config);
  
    // Set config.method
    if (config.method) {
      config.method = config.method.toLowerCase();
    } else if (this.defaults.method) {
      config.method = this.defaults.method.toLowerCase();
    } else {
      config.method = 'get';
    }
  
    // Hook up interceptors middleware
    var chain = [dispatchRequest, undefined];
    var promise = Promise.resolve(config);
  
    this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
      chain.unshift(interceptor.fulfilled, interceptor.rejected);
    });
  
    this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
      chain.push(interceptor.fulfilled, interceptor.rejected);
    });
  
    while (chain.length) {
      promise = promise.then(chain.shift(), chain.shift());
    }
  
    return promise;
  };
  
  Axios.prototype.getUri = function getUri(config) {
    config = mergeConfig(this.defaults, config);
    return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
  };
  
  // Provide aliases for supported request methods
  utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
    /*eslint func-names:0*/
    Axios.prototype[method] = function(url, config) {
      return this.request(mergeConfig(config || {}, {
        method: method,
        url: url,
        data: (config || {}).data
      }));
    };
  });
  
  utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
    /*eslint func-names:0*/
    Axios.prototype[method] = function(url, data, config) {
      return this.request(mergeConfig(config || {}, {
        method: method,
        url: url,
        data: data
      }));
    };
  });
  
  module.exports = Axios;
  
  },{"../helpers/buildURL":22,"./../utils":31,"./InterceptorManager":12,"./dispatchRequest":15,"./mergeConfig":17}],12:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  function InterceptorManager() {
    this.handlers = [];
  }
  
  /**
   * Add a new interceptor to the stack
   *
   * @param {Function} fulfilled The function to handle `then` for a `Promise`
   * @param {Function} rejected The function to handle `reject` for a `Promise`
   *
   * @return {Number} An ID used to remove interceptor later
   */
  InterceptorManager.prototype.use = function use(fulfilled, rejected) {
    this.handlers.push({
      fulfilled: fulfilled,
      rejected: rejected
    });
    return this.handlers.length - 1;
  };
  
  /**
   * Remove an interceptor from the stack
   *
   * @param {Number} id The ID that was returned by `use`
   */
  InterceptorManager.prototype.eject = function eject(id) {
    if (this.handlers[id]) {
      this.handlers[id] = null;
    }
  };
  
  /**
   * Iterate over all the registered interceptors
   *
   * This method is particularly useful for skipping over any
   * interceptors that may have become `null` calling `eject`.
   *
   * @param {Function} fn The function to call for each interceptor
   */
  InterceptorManager.prototype.forEach = function forEach(fn) {
    utils.forEach(this.handlers, function forEachHandler(h) {
      if (h !== null) {
        fn(h);
      }
    });
  };
  
  module.exports = InterceptorManager;
  
  },{"./../utils":31}],13:[function(require,module,exports){
  'use strict';
  
  var isAbsoluteURL = require('../helpers/isAbsoluteURL');
  var combineURLs = require('../helpers/combineURLs');
  
  /**
   * Creates a new URL by combining the baseURL with the requestedURL,
   * only when the requestedURL is not already an absolute URL.
   * If the requestURL is absolute, this function returns the requestedURL untouched.
   *
   * @param {string} baseURL The base URL
   * @param {string} requestedURL Absolute or relative URL to combine
   * @returns {string} The combined full path
   */
  module.exports = function buildFullPath(baseURL, requestedURL) {
    if (baseURL && !isAbsoluteURL(requestedURL)) {
      return combineURLs(baseURL, requestedURL);
    }
    return requestedURL;
  };
  
  },{"../helpers/combineURLs":23,"../helpers/isAbsoluteURL":25}],14:[function(require,module,exports){
  'use strict';
  
  var enhanceError = require('./enhanceError');
  
  /**
   * Create an Error with the specified message, config, error code, request and response.
   *
   * @param {string} message The error message.
   * @param {Object} config The config.
   * @param {string} [code] The error code (for example, 'ECONNABORTED').
   * @param {Object} [request] The request.
   * @param {Object} [response] The response.
   * @returns {Error} The created error.
   */
  module.exports = function createError(message, config, code, request, response) {
    var error = new Error(message);
    return enhanceError(error, config, code, request, response);
  };
  
  },{"./enhanceError":16}],15:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  var transformData = require('./transformData');
  var isCancel = require('../cancel/isCancel');
  var defaults = require('../defaults');
  
  /**
   * Throws a `Cancel` if cancellation has been requested.
   */
  function throwIfCancellationRequested(config) {
    if (config.cancelToken) {
      config.cancelToken.throwIfRequested();
    }
  }
  
  /**
   * Dispatch a request to the server using the configured adapter.
   *
   * @param {object} config The config that is to be used for the request
   * @returns {Promise} The Promise to be fulfilled
   */
  module.exports = function dispatchRequest(config) {
    throwIfCancellationRequested(config);
  
    // Ensure headers exist
    config.headers = config.headers || {};
  
    // Transform request data
    config.data = transformData(
      config.data,
      config.headers,
      config.transformRequest
    );
  
    // Flatten headers
    config.headers = utils.merge(
      config.headers.common || {},
      config.headers[config.method] || {},
      config.headers
    );
  
    utils.forEach(
      ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
      function cleanHeaderConfig(method) {
        delete config.headers[method];
      }
    );
  
    var adapter = config.adapter || defaults.adapter;
  
    return adapter(config).then(function onAdapterResolution(response) {
      throwIfCancellationRequested(config);
  
      // Transform response data
      response.data = transformData(
        response.data,
        response.headers,
        config.transformResponse
      );
  
      return response;
    }, function onAdapterRejection(reason) {
      if (!isCancel(reason)) {
        throwIfCancellationRequested(config);
  
        // Transform response data
        if (reason && reason.response) {
          reason.response.data = transformData(
            reason.response.data,
            reason.response.headers,
            config.transformResponse
          );
        }
      }
  
      return Promise.reject(reason);
    });
  };
  
  },{"../cancel/isCancel":10,"../defaults":20,"./../utils":31,"./transformData":19}],16:[function(require,module,exports){
  'use strict';
  
  /**
   * Update an Error with the specified config, error code, and response.
   *
   * @param {Error} error The error to update.
   * @param {Object} config The config.
   * @param {string} [code] The error code (for example, 'ECONNABORTED').
   * @param {Object} [request] The request.
   * @param {Object} [response] The response.
   * @returns {Error} The error.
   */
  module.exports = function enhanceError(error, config, code, request, response) {
    error.config = config;
    if (code) {
      error.code = code;
    }
  
    error.request = request;
    error.response = response;
    error.isAxiosError = true;
  
    error.toJSON = function toJSON() {
      return {
        // Standard
        message: this.message,
        name: this.name,
        // Microsoft
        description: this.description,
        number: this.number,
        // Mozilla
        fileName: this.fileName,
        lineNumber: this.lineNumber,
        columnNumber: this.columnNumber,
        stack: this.stack,
        // Axios
        config: this.config,
        code: this.code
      };
    };
    return error;
  };
  
  },{}],17:[function(require,module,exports){
  'use strict';
  
  var utils = require('../utils');
  
  /**
   * Config-specific merge-function which creates a new config-object
   * by merging two configuration objects together.
   *
   * @param {Object} config1
   * @param {Object} config2
   * @returns {Object} New object resulting from merging config2 to config1
   */
  module.exports = function mergeConfig(config1, config2) {
    // eslint-disable-next-line no-param-reassign
    config2 = config2 || {};
    var config = {};
  
    var valueFromConfig2Keys = ['url', 'method', 'data'];
    var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
    var defaultToConfig2Keys = [
      'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
      'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
      'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
      'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
      'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
    ];
    var directMergeKeys = ['validateStatus'];
  
    function getMergedValue(target, source) {
      if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
        return utils.merge(target, source);
      } else if (utils.isPlainObject(source)) {
        return utils.merge({}, source);
      } else if (utils.isArray(source)) {
        return source.slice();
      }
      return source;
    }
  
    function mergeDeepProperties(prop) {
      if (!utils.isUndefined(config2[prop])) {
        config[prop] = getMergedValue(config1[prop], config2[prop]);
      } else if (!utils.isUndefined(config1[prop])) {
        config[prop] = getMergedValue(undefined, config1[prop]);
      }
    }
  
    utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
      if (!utils.isUndefined(config2[prop])) {
        config[prop] = getMergedValue(undefined, config2[prop]);
      }
    });
  
    utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
  
    utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
      if (!utils.isUndefined(config2[prop])) {
        config[prop] = getMergedValue(undefined, config2[prop]);
      } else if (!utils.isUndefined(config1[prop])) {
        config[prop] = getMergedValue(undefined, config1[prop]);
      }
    });
  
    utils.forEach(directMergeKeys, function merge(prop) {
      if (prop in config2) {
        config[prop] = getMergedValue(config1[prop], config2[prop]);
      } else if (prop in config1) {
        config[prop] = getMergedValue(undefined, config1[prop]);
      }
    });
  
    var axiosKeys = valueFromConfig2Keys
      .concat(mergeDeepPropertiesKeys)
      .concat(defaultToConfig2Keys)
      .concat(directMergeKeys);
  
    var otherKeys = Object
      .keys(config1)
      .concat(Object.keys(config2))
      .filter(function filterAxiosKeys(key) {
        return axiosKeys.indexOf(key) === -1;
      });
  
    utils.forEach(otherKeys, mergeDeepProperties);
  
    return config;
  };
  
  },{"../utils":31}],18:[function(require,module,exports){
  'use strict';
  
  var createError = require('./createError');
  
  /**
   * Resolve or reject a Promise based on response status.
   *
   * @param {Function} resolve A function that resolves the promise.
   * @param {Function} reject A function that rejects the promise.
   * @param {object} response The response.
   */
  module.exports = function settle(resolve, reject, response) {
    var validateStatus = response.config.validateStatus;
    if (!response.status || !validateStatus || validateStatus(response.status)) {
      resolve(response);
    } else {
      reject(createError(
        'Request failed with status code ' + response.status,
        response.config,
        null,
        response.request,
        response
      ));
    }
  };
  
  },{"./createError":14}],19:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  /**
   * Transform the data for a request or a response
   *
   * @param {Object|String} data The data to be transformed
   * @param {Array} headers The headers for the request or response
   * @param {Array|Function} fns A single function or Array of functions
   * @returns {*} The resulting transformed data
   */
  module.exports = function transformData(data, headers, fns) {
    /*eslint no-param-reassign:0*/
    utils.forEach(fns, function transform(fn) {
      data = fn(data, headers);
    });
  
    return data;
  };
  
  },{"./../utils":31}],20:[function(require,module,exports){
  (function (process){
  'use strict';
  
  var utils = require('./utils');
  var normalizeHeaderName = require('./helpers/normalizeHeaderName');
  
  var DEFAULT_CONTENT_TYPE = {
    'Content-Type': 'application/x-www-form-urlencoded'
  };
  
  function setContentTypeIfUnset(headers, value) {
    if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
      headers['Content-Type'] = value;
    }
  }
  
  function getDefaultAdapter() {
    var adapter;
    if (typeof XMLHttpRequest !== 'undefined') {
      // For browsers use XHR adapter
      adapter = require('./adapters/xhr');
    } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
      // For node use HTTP adapter
      adapter = require('./adapters/http');
    }
    return adapter;
  }
  
  var defaults = {
    adapter: getDefaultAdapter(),
  
    transformRequest: [function transformRequest(data, headers) {
      normalizeHeaderName(headers, 'Accept');
      normalizeHeaderName(headers, 'Content-Type');
      if (utils.isFormData(data) ||
        utils.isArrayBuffer(data) ||
        utils.isBuffer(data) ||
        utils.isStream(data) ||
        utils.isFile(data) ||
        utils.isBlob(data)
      ) {
        return data;
      }
      if (utils.isArrayBufferView(data)) {
        return data.buffer;
      }
      if (utils.isURLSearchParams(data)) {
        setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
        return data.toString();
      }
      if (utils.isObject(data)) {
        setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
        return JSON.stringify(data);
      }
      return data;
    }],
  
    transformResponse: [function transformResponse(data) {
      /*eslint no-param-reassign:0*/
      if (typeof data === 'string') {
        try {
          data = JSON.parse(data);
        } catch (e) { /* Ignore */ }
      }
      return data;
    }],
  
    /**
     * A timeout in milliseconds to abort a request. If set to 0 (default) a
     * timeout is not created.
     */
    timeout: 0,
  
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
  
    maxContentLength: -1,
    maxBodyLength: -1,
  
    validateStatus: function validateStatus(status) {
      return status >= 200 && status < 300;
    }
  };
  
  defaults.headers = {
    common: {
      'Accept': 'application/json, text/plain, */*'
    }
  };
  
  utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
    defaults.headers[method] = {};
  });
  
  utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
    defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  });
  
  module.exports = defaults;
  
  }).call(this,require('_process'))
  },{"./adapters/http":6,"./adapters/xhr":6,"./helpers/normalizeHeaderName":28,"./utils":31,"_process":1}],21:[function(require,module,exports){
  'use strict';
  
  module.exports = function bind(fn, thisArg) {
    return function wrap() {
      var args = new Array(arguments.length);
      for (var i = 0; i < args.length; i++) {
        args[i] = arguments[i];
      }
      return fn.apply(thisArg, args);
    };
  };
  
  },{}],22:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  function encode(val) {
    return encodeURIComponent(val).
      replace(/%3A/gi, ':').
      replace(/%24/g, '$').
      replace(/%2C/gi, ',').
      replace(/%20/g, '+').
      replace(/%5B/gi, '[').
      replace(/%5D/gi, ']');
  }
  
  /**
   * Build a URL by appending params to the end
   *
   * @param {string} url The base of the url (e.g., http://www.google.com)
   * @param {object} [params] The params to be appended
   * @returns {string} The formatted url
   */
  module.exports = function buildURL(url, params, paramsSerializer) {
    /*eslint no-param-reassign:0*/
    if (!params) {
      return url;
    }
  
    var serializedParams;
    if (paramsSerializer) {
      serializedParams = paramsSerializer(params);
    } else if (utils.isURLSearchParams(params)) {
      serializedParams = params.toString();
    } else {
      var parts = [];
  
      utils.forEach(params, function serialize(val, key) {
        if (val === null || typeof val === 'undefined') {
          return;
        }
  
        if (utils.isArray(val)) {
          key = key + '[]';
        } else {
          val = [val];
        }
  
        utils.forEach(val, function parseValue(v) {
          if (utils.isDate(v)) {
            v = v.toISOString();
          } else if (utils.isObject(v)) {
            v = JSON.stringify(v);
          }
          parts.push(encode(key) + '=' + encode(v));
        });
      });
  
      serializedParams = parts.join('&');
    }
  
    if (serializedParams) {
      var hashmarkIndex = url.indexOf('#');
      if (hashmarkIndex !== -1) {
        url = url.slice(0, hashmarkIndex);
      }
  
      url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
    }
  
    return url;
  };
  
  },{"./../utils":31}],23:[function(require,module,exports){
  'use strict';
  
  /**
   * Creates a new URL by combining the specified URLs
   *
   * @param {string} baseURL The base URL
   * @param {string} relativeURL The relative URL
   * @returns {string} The combined URL
   */
  module.exports = function combineURLs(baseURL, relativeURL) {
    return relativeURL
      ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
      : baseURL;
  };
  
  },{}],24:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  module.exports = (
    utils.isStandardBrowserEnv() ?
  
    // Standard browser envs support document.cookie
      (function standardBrowserEnv() {
        return {
          write: function write(name, value, expires, path, domain, secure) {
            var cookie = [];
            cookie.push(name + '=' + encodeURIComponent(value));
  
            if (utils.isNumber(expires)) {
              cookie.push('expires=' + new Date(expires).toGMTString());
            }
  
            if (utils.isString(path)) {
              cookie.push('path=' + path);
            }
  
            if (utils.isString(domain)) {
              cookie.push('domain=' + domain);
            }
  
            if (secure === true) {
              cookie.push('secure');
            }
  
            document.cookie = cookie.join('; ');
          },
  
          read: function read(name) {
            var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
            return (match ? decodeURIComponent(match[3]) : null);
          },
  
          remove: function remove(name) {
            this.write(name, '', Date.now() - 86400000);
          }
        };
      })() :
  
    // Non standard browser env (web workers, react-native) lack needed support.
      (function nonStandardBrowserEnv() {
        return {
          write: function write() {},
          read: function read() { return null; },
          remove: function remove() {}
        };
      })()
  );
  
  },{"./../utils":31}],25:[function(require,module,exports){
  'use strict';
  
  /**
   * Determines whether the specified URL is absolute
   *
   * @param {string} url The URL to test
   * @returns {boolean} True if the specified URL is absolute, otherwise false
   */
  module.exports = function isAbsoluteURL(url) {
    // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
    // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
    // by any combination of letters, digits, plus, period, or hyphen.
    return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
  };
  
  },{}],26:[function(require,module,exports){
  'use strict';
  
  /**
   * Determines whether the payload is an error thrown by Axios
   *
   * @param {*} payload The value to test
   * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
   */
  module.exports = function isAxiosError(payload) {
    return (typeof payload === 'object') && (payload.isAxiosError === true);
  };
  
  },{}],27:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  module.exports = (
    utils.isStandardBrowserEnv() ?
  
    // Standard browser envs have full support of the APIs needed to test
    // whether the request URL is of the same origin as current location.
      (function standardBrowserEnv() {
        var msie = /(msie|trident)/i.test(navigator.userAgent);
        var urlParsingNode = document.createElement('a');
        var originURL;
  
        /**
      * Parse a URL to discover it's components
      *
      * @param {String} url The URL to be parsed
      * @returns {Object}
      */
        function resolveURL(url) {
          var href = url;
  
          if (msie) {
          // IE needs attribute set twice to normalize properties
            urlParsingNode.setAttribute('href', href);
            href = urlParsingNode.href;
          }
  
          urlParsingNode.setAttribute('href', href);
  
          // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
          return {
            href: urlParsingNode.href,
            protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
            host: urlParsingNode.host,
            search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
            hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
            hostname: urlParsingNode.hostname,
            port: urlParsingNode.port,
            pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
              urlParsingNode.pathname :
              '/' + urlParsingNode.pathname
          };
        }
  
        originURL = resolveURL(window.location.href);
  
        /**
      * Determine if a URL shares the same origin as the current location
      *
      * @param {String} requestURL The URL to test
      * @returns {boolean} True if URL shares the same origin, otherwise false
      */
        return function isURLSameOrigin(requestURL) {
          var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
          return (parsed.protocol === originURL.protocol &&
              parsed.host === originURL.host);
        };
      })() :
  
    // Non standard browser envs (web workers, react-native) lack needed support.
      (function nonStandardBrowserEnv() {
        return function isURLSameOrigin() {
          return true;
        };
      })()
  );
  
  },{"./../utils":31}],28:[function(require,module,exports){
  'use strict';
  
  var utils = require('../utils');
  
  module.exports = function normalizeHeaderName(headers, normalizedName) {
    utils.forEach(headers, function processHeader(value, name) {
      if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
        headers[normalizedName] = value;
        delete headers[name];
      }
    });
  };
  
  },{"../utils":31}],29:[function(require,module,exports){
  'use strict';
  
  var utils = require('./../utils');
  
  // Headers whose duplicates are ignored by node
  // c.f. https://nodejs.org/api/http.html#http_message_headers
  var ignoreDuplicateOf = [
    'age', 'authorization', 'content-length', 'content-type', 'etag',
    'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
    'last-modified', 'location', 'max-forwards', 'proxy-authorization',
    'referer', 'retry-after', 'user-agent'
  ];
  
  /**
   * Parse headers into an object
   *
   * ```
   * Date: Wed, 27 Aug 2014 08:58:49 GMT
   * Content-Type: application/json
   * Connection: keep-alive
   * Transfer-Encoding: chunked
   * ```
   *
   * @param {String} headers Headers needing to be parsed
   * @returns {Object} Headers parsed into an object
   */
  module.exports = function parseHeaders(headers) {
    var parsed = {};
    var key;
    var val;
    var i;
  
    if (!headers) { return parsed; }
  
    utils.forEach(headers.split('\n'), function parser(line) {
      i = line.indexOf(':');
      key = utils.trim(line.substr(0, i)).toLowerCase();
      val = utils.trim(line.substr(i + 1));
  
      if (key) {
        if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
          return;
        }
        if (key === 'set-cookie') {
          parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
        } else {
          parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
        }
      }
    });
  
    return parsed;
  };
  
  },{"./../utils":31}],30:[function(require,module,exports){
  'use strict';
  
  /**
   * Syntactic sugar for invoking a function and expanding an array for arguments.
   *
   * Common use case would be to use `Function.prototype.apply`.
   *
   *  ```js
   *  function f(x, y, z) {}
   *  var args = [1, 2, 3];
   *  f.apply(null, args);
   *  ```
   *
   * With `spread` this example can be re-written.
   *
   *  ```js
   *  spread(function(x, y, z) {})([1, 2, 3]);
   *  ```
   *
   * @param {Function} callback
   * @returns {Function}
   */
  module.exports = function spread(callback) {
    return function wrap(arr) {
      return callback.apply(null, arr);
    };
  };
  
  },{}],31:[function(require,module,exports){
  'use strict';
  
  var bind = require('./helpers/bind');
  
  /*global toString:true*/
  
  // utils is a library of generic helper functions non-specific to axios
  
  var toString = Object.prototype.toString;
  
  /**
   * Determine if a value is an Array
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is an Array, otherwise false
   */
  function isArray(val) {
    return toString.call(val) === '[object Array]';
  }
  
  /**
   * Determine if a value is undefined
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if the value is undefined, otherwise false
   */
  function isUndefined(val) {
    return typeof val === 'undefined';
  }
  
  /**
   * Determine if a value is a Buffer
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Buffer, otherwise false
   */
  function isBuffer(val) {
    return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
      && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  }
  
  /**
   * Determine if a value is an ArrayBuffer
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is an ArrayBuffer, otherwise false
   */
  function isArrayBuffer(val) {
    return toString.call(val) === '[object ArrayBuffer]';
  }
  
  /**
   * Determine if a value is a FormData
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is an FormData, otherwise false
   */
  function isFormData(val) {
    return (typeof FormData !== 'undefined') && (val instanceof FormData);
  }
  
  /**
   * Determine if a value is a view on an ArrayBuffer
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
   */
  function isArrayBufferView(val) {
    var result;
    if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
      result = ArrayBuffer.isView(val);
    } else {
      result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
    }
    return result;
  }
  
  /**
   * Determine if a value is a String
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a String, otherwise false
   */
  function isString(val) {
    return typeof val === 'string';
  }
  
  /**
   * Determine if a value is a Number
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Number, otherwise false
   */
  function isNumber(val) {
    return typeof val === 'number';
  }
  
  /**
   * Determine if a value is an Object
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is an Object, otherwise false
   */
  function isObject(val) {
    return val !== null && typeof val === 'object';
  }
  
  /**
   * Determine if a value is a plain Object
   *
   * @param {Object} val The value to test
   * @return {boolean} True if value is a plain Object, otherwise false
   */
  function isPlainObject(val) {
    if (toString.call(val) !== '[object Object]') {
      return false;
    }
  
    var prototype = Object.getPrototypeOf(val);
    return prototype === null || prototype === Object.prototype;
  }
  
  /**
   * Determine if a value is a Date
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Date, otherwise false
   */
  function isDate(val) {
    return toString.call(val) === '[object Date]';
  }
  
  /**
   * Determine if a value is a File
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a File, otherwise false
   */
  function isFile(val) {
    return toString.call(val) === '[object File]';
  }
  
  /**
   * Determine if a value is a Blob
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Blob, otherwise false
   */
  function isBlob(val) {
    return toString.call(val) === '[object Blob]';
  }
  
  /**
   * Determine if a value is a Function
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Function, otherwise false
   */
  function isFunction(val) {
    return toString.call(val) === '[object Function]';
  }
  
  /**
   * Determine if a value is a Stream
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a Stream, otherwise false
   */
  function isStream(val) {
    return isObject(val) && isFunction(val.pipe);
  }
  
  /**
   * Determine if a value is a URLSearchParams object
   *
   * @param {Object} val The value to test
   * @returns {boolean} True if value is a URLSearchParams object, otherwise false
   */
  function isURLSearchParams(val) {
    return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
  }
  
  /**
   * Trim excess whitespace off the beginning and end of a string
   *
   * @param {String} str The String to trim
   * @returns {String} The String freed of excess whitespace
   */
  function trim(str) {
    return str.replace(/^\s*/, '').replace(/\s*$/, '');
  }
  
  /**
   * Determine if we're running in a standard browser environment
   *
   * This allows axios to run in a web worker, and react-native.
   * Both environments support XMLHttpRequest, but not fully standard globals.
   *
   * web workers:
   *  typeof window -> undefined
   *  typeof document -> undefined
   *
   * react-native:
   *  navigator.product -> 'ReactNative'
   * nativescript
   *  navigator.product -> 'NativeScript' or 'NS'
   */
  function isStandardBrowserEnv() {
    if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
                                             navigator.product === 'NativeScript' ||
                                             navigator.product === 'NS')) {
      return false;
    }
    return (
      typeof window !== 'undefined' &&
      typeof document !== 'undefined'
    );
  }
  
  /**
   * Iterate over an Array or an Object invoking a function for each item.
   *
   * If `obj` is an Array callback will be called passing
   * the value, index, and complete array for each item.
   *
   * If 'obj' is an Object callback will be called passing
   * the value, key, and complete object for each property.
   *
   * @param {Object|Array} obj The object to iterate
   * @param {Function} fn The callback to invoke for each item
   */
  function forEach(obj, fn) {
    // Don't bother if no value provided
    if (obj === null || typeof obj === 'undefined') {
      return;
    }
  
    // Force an array if not already something iterable
    if (typeof obj !== 'object') {
      /*eslint no-param-reassign:0*/
      obj = [obj];
    }
  
    if (isArray(obj)) {
      // Iterate over array values
      for (var i = 0, l = obj.length; i < l; i++) {
        fn.call(null, obj[i], i, obj);
      }
    } else {
      // Iterate over object keys
      for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          fn.call(null, obj[key], key, obj);
        }
      }
    }
  }
  
  /**
   * Accepts varargs expecting each argument to be an object, then
   * immutably merges the properties of each object and returns result.
   *
   * When multiple objects contain the same key the later object in
   * the arguments list will take precedence.
   *
   * Example:
   *
   * ```js
   * var result = merge({foo: 123}, {foo: 456});
   * console.log(result.foo); // outputs 456
   * ```
   *
   * @param {Object} obj1 Object to merge
   * @returns {Object} Result of all merge properties
   */
  function merge(/* obj1, obj2, obj3, ... */) {
    var result = {};
    function assignValue(val, key) {
      if (isPlainObject(result[key]) && isPlainObject(val)) {
        result[key] = merge(result[key], val);
      } else if (isPlainObject(val)) {
        result[key] = merge({}, val);
      } else if (isArray(val)) {
        result[key] = val.slice();
      } else {
        result[key] = val;
      }
    }
  
    for (var i = 0, l = arguments.length; i < l; i++) {
      forEach(arguments[i], assignValue);
    }
    return result;
  }
  
  /**
   * Extends object a by mutably adding to it the properties of object b.
   *
   * @param {Object} a The object to be extended
   * @param {Object} b The object to copy properties from
   * @param {Object} thisArg The object to bind function to
   * @return {Object} The resulting value of object a
   */
  function extend(a, b, thisArg) {
    forEach(b, function assignValue(val, key) {
      if (thisArg && typeof val === 'function') {
        a[key] = bind(val, thisArg);
      } else {
        a[key] = val;
      }
    });
    return a;
  }
  
  /**
   * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
   *
   * @param {string} content with BOM
   * @return {string} content value without BOM
   */
  function stripBOM(content) {
    if (content.charCodeAt(0) === 0xFEFF) {
      content = content.slice(1);
    }
    return content;
  }
  
  module.exports = {
    isArray: isArray,
    isArrayBuffer: isArrayBuffer,
    isBuffer: isBuffer,
    isFormData: isFormData,
    isArrayBufferView: isArrayBufferView,
    isString: isString,
    isNumber: isNumber,
    isObject: isObject,
    isPlainObject: isPlainObject,
    isUndefined: isUndefined,
    isDate: isDate,
    isFile: isFile,
    isBlob: isBlob,
    isFunction: isFunction,
    isStream: isStream,
    isURLSearchParams: isURLSearchParams,
    isStandardBrowserEnv: isStandardBrowserEnv,
    forEach: forEach,
    merge: merge,
    extend: extend,
    trim: trim,
    stripBOM: stripBOM
  };
  
  },{"./helpers/bind":21}],32:[function(require,module,exports){
  (function (process,global){
  /*!
   * @overview es6-promise - a tiny implementation of Promises/A+.
   * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
   * @license   Licensed under MIT license
   *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
   * @version   v4.2.8+1e68dce6
   */
  
  (function (global, factory) {
  	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  	typeof define === 'function' && define.amd ? define(factory) :
  	(global.ES6Promise = factory());
  }(this, (function () { 'use strict';
  
  function objectOrFunction(x) {
    var type = typeof x;
    return x !== null && (type === 'object' || type === 'function');
  }
  
  function isFunction(x) {
    return typeof x === 'function';
  }
  
  
  
  var _isArray = void 0;
  if (Array.isArray) {
    _isArray = Array.isArray;
  } else {
    _isArray = function (x) {
      return Object.prototype.toString.call(x) === '[object Array]';
    };
  }
  
  var isArray = _isArray;
  
  var len = 0;
  var vertxNext = void 0;
  var customSchedulerFn = void 0;
  
  var asap = function asap(callback, arg) {
    queue[len] = callback;
    queue[len + 1] = arg;
    len += 2;
    if (len === 2) {
      // If len is 2, that means that we need to schedule an async flush.
      // If additional callbacks are queued before the queue is flushed, they
      // will be processed by this flush that we are scheduling.
      if (customSchedulerFn) {
        customSchedulerFn(flush);
      } else {
        scheduleFlush();
      }
    }
  };
  
  function setScheduler(scheduleFn) {
    customSchedulerFn = scheduleFn;
  }
  
  function setAsap(asapFn) {
    asap = asapFn;
  }
  
  var browserWindow = typeof window !== 'undefined' ? window : undefined;
  var browserGlobal = browserWindow || {};
  var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  
  // test for web worker but not in IE10
  var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  
  // node
  function useNextTick() {
    // node version 0.10.x displays a deprecation warning when nextTick is used recursively
    // see https://github.com/cujojs/when/issues/410 for details
    return function () {
      return process.nextTick(flush);
    };
  }
  
  // vertx
  function useVertxTimer() {
    if (typeof vertxNext !== 'undefined') {
      return function () {
        vertxNext(flush);
      };
    }
  
    return useSetTimeout();
  }
  
  function useMutationObserver() {
    var iterations = 0;
    var observer = new BrowserMutationObserver(flush);
    var node = document.createTextNode('');
    observer.observe(node, { characterData: true });
  
    return function () {
      node.data = iterations = ++iterations % 2;
    };
  }
  
  // web worker
  function useMessageChannel() {
    var channel = new MessageChannel();
    channel.port1.onmessage = flush;
    return function () {
      return channel.port2.postMessage(0);
    };
  }
  
  function useSetTimeout() {
    // Store setTimeout reference so es6-promise will be unaffected by
    // other code modifying setTimeout (like sinon.useFakeTimers())
    var globalSetTimeout = setTimeout;
    return function () {
      return globalSetTimeout(flush, 1);
    };
  }
  
  var queue = new Array(1000);
  function flush() {
    for (var i = 0; i < len; i += 2) {
      var callback = queue[i];
      var arg = queue[i + 1];
  
      callback(arg);
  
      queue[i] = undefined;
      queue[i + 1] = undefined;
    }
  
    len = 0;
  }
  
  function attemptVertx() {
    try {
      var vertx = Function('return this')().require('vertx');
      vertxNext = vertx.runOnLoop || vertx.runOnContext;
      return useVertxTimer();
    } catch (e) {
      return useSetTimeout();
    }
  }
  
  var scheduleFlush = void 0;
  // Decide what async method to use to triggering processing of queued callbacks:
  if (isNode) {
    scheduleFlush = useNextTick();
  } else if (BrowserMutationObserver) {
    scheduleFlush = useMutationObserver();
  } else if (isWorker) {
    scheduleFlush = useMessageChannel();
  } else if (browserWindow === undefined && typeof require === 'function') {
    scheduleFlush = attemptVertx();
  } else {
    scheduleFlush = useSetTimeout();
  }
  
  function then(onFulfillment, onRejection) {
    var parent = this;
  
    var child = new this.constructor(noop);
  
    if (child[PROMISE_ID] === undefined) {
      makePromise(child);
    }
  
    var _state = parent._state;
  
  
    if (_state) {
      var callback = arguments[_state - 1];
      asap(function () {
        return invokeCallback(_state, child, callback, parent._result);
      });
    } else {
      subscribe(parent, child, onFulfillment, onRejection);
    }
  
    return child;
  }
  
  /**
    `Promise.resolve` returns a promise that will become resolved with the
    passed `value`. It is shorthand for the following:
  
    ```javascript
    let promise = new Promise(function(resolve, reject){
      resolve(1);
    });
  
    promise.then(function(value){
      // value === 1
    });
    ```
  
    Instead of writing the above, your code now simply becomes the following:
  
    ```javascript
    let promise = Promise.resolve(1);
  
    promise.then(function(value){
      // value === 1
    });
    ```
  
    @method resolve
    @static
    @param {Any} value value that the returned promise will be resolved with
    Useful for tooling.
    @return {Promise} a promise that will become fulfilled with the given
    `value`
  */
  function resolve$1(object) {
    /*jshint validthis:true */
    var Constructor = this;
  
    if (object && typeof object === 'object' && object.constructor === Constructor) {
      return object;
    }
  
    var promise = new Constructor(noop);
    resolve(promise, object);
    return promise;
  }
  
  var PROMISE_ID = Math.random().toString(36).substring(2);
  
  function noop() {}
  
  var PENDING = void 0;
  var FULFILLED = 1;
  var REJECTED = 2;
  
  function selfFulfillment() {
    return new TypeError("You cannot resolve a promise with itself");
  }
  
  function cannotReturnOwn() {
    return new TypeError('A promises callback cannot return that same promise.');
  }
  
  function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
    try {
      then$$1.call(value, fulfillmentHandler, rejectionHandler);
    } catch (e) {
      return e;
    }
  }
  
  function handleForeignThenable(promise, thenable, then$$1) {
    asap(function (promise) {
      var sealed = false;
      var error = tryThen(then$$1, thenable, function (value) {
        if (sealed) {
          return;
        }
        sealed = true;
        if (thenable !== value) {
          resolve(promise, value);
        } else {
          fulfill(promise, value);
        }
      }, function (reason) {
        if (sealed) {
          return;
        }
        sealed = true;
  
        reject(promise, reason);
      }, 'Settle: ' + (promise._label || ' unknown promise'));
  
      if (!sealed && error) {
        sealed = true;
        reject(promise, error);
      }
    }, promise);
  }
  
  function handleOwnThenable(promise, thenable) {
    if (thenable._state === FULFILLED) {
      fulfill(promise, thenable._result);
    } else if (thenable._state === REJECTED) {
      reject(promise, thenable._result);
    } else {
      subscribe(thenable, undefined, function (value) {
        return resolve(promise, value);
      }, function (reason) {
        return reject(promise, reason);
      });
    }
  }
  
  function handleMaybeThenable(promise, maybeThenable, then$$1) {
    if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
      handleOwnThenable(promise, maybeThenable);
    } else {
      if (then$$1 === undefined) {
        fulfill(promise, maybeThenable);
      } else if (isFunction(then$$1)) {
        handleForeignThenable(promise, maybeThenable, then$$1);
      } else {
        fulfill(promise, maybeThenable);
      }
    }
  }
  
  function resolve(promise, value) {
    if (promise === value) {
      reject(promise, selfFulfillment());
    } else if (objectOrFunction(value)) {
      var then$$1 = void 0;
      try {
        then$$1 = value.then;
      } catch (error) {
        reject(promise, error);
        return;
      }
      handleMaybeThenable(promise, value, then$$1);
    } else {
      fulfill(promise, value);
    }
  }
  
  function publishRejection(promise) {
    if (promise._onerror) {
      promise._onerror(promise._result);
    }
  
    publish(promise);
  }
  
  function fulfill(promise, value) {
    if (promise._state !== PENDING) {
      return;
    }
  
    promise._result = value;
    promise._state = FULFILLED;
  
    if (promise._subscribers.length !== 0) {
      asap(publish, promise);
    }
  }
  
  function reject(promise, reason) {
    if (promise._state !== PENDING) {
      return;
    }
    promise._state = REJECTED;
    promise._result = reason;
  
    asap(publishRejection, promise);
  }
  
  function subscribe(parent, child, onFulfillment, onRejection) {
    var _subscribers = parent._subscribers;
    var length = _subscribers.length;
  
  
    parent._onerror = null;
  
    _subscribers[length] = child;
    _subscribers[length + FULFILLED] = onFulfillment;
    _subscribers[length + REJECTED] = onRejection;
  
    if (length === 0 && parent._state) {
      asap(publish, parent);
    }
  }
  
  function publish(promise) {
    var subscribers = promise._subscribers;
    var settled = promise._state;
  
    if (subscribers.length === 0) {
      return;
    }
  
    var child = void 0,
        callback = void 0,
        detail = promise._result;
  
    for (var i = 0; i < subscribers.length; i += 3) {
      child = subscribers[i];
      callback = subscribers[i + settled];
  
      if (child) {
        invokeCallback(settled, child, callback, detail);
      } else {
        callback(detail);
      }
    }
  
    promise._subscribers.length = 0;
  }
  
  function invokeCallback(settled, promise, callback, detail) {
    var hasCallback = isFunction(callback),
        value = void 0,
        error = void 0,
        succeeded = true;
  
    if (hasCallback) {
      try {
        value = callback(detail);
      } catch (e) {
        succeeded = false;
        error = e;
      }
  
      if (promise === value) {
        reject(promise, cannotReturnOwn());
        return;
      }
    } else {
      value = detail;
    }
  
    if (promise._state !== PENDING) {
      // noop
    } else if (hasCallback && succeeded) {
      resolve(promise, value);
    } else if (succeeded === false) {
      reject(promise, error);
    } else if (settled === FULFILLED) {
      fulfill(promise, value);
    } else if (settled === REJECTED) {
      reject(promise, value);
    }
  }
  
  function initializePromise(promise, resolver) {
    try {
      resolver(function resolvePromise(value) {
        resolve(promise, value);
      }, function rejectPromise(reason) {
        reject(promise, reason);
      });
    } catch (e) {
      reject(promise, e);
    }
  }
  
  var id = 0;
  function nextId() {
    return id++;
  }
  
  function makePromise(promise) {
    promise[PROMISE_ID] = id++;
    promise._state = undefined;
    promise._result = undefined;
    promise._subscribers = [];
  }
  
  function validationError() {
    return new Error('Array Methods must be provided an Array');
  }
  
  var Enumerator = function () {
    function Enumerator(Constructor, input) {
      this._instanceConstructor = Constructor;
      this.promise = new Constructor(noop);
  
      if (!this.promise[PROMISE_ID]) {
        makePromise(this.promise);
      }
  
      if (isArray(input)) {
        this.length = input.length;
        this._remaining = input.length;
  
        this._result = new Array(this.length);
  
        if (this.length === 0) {
          fulfill(this.promise, this._result);
        } else {
          this.length = this.length || 0;
          this._enumerate(input);
          if (this._remaining === 0) {
            fulfill(this.promise, this._result);
          }
        }
      } else {
        reject(this.promise, validationError());
      }
    }
  
    Enumerator.prototype._enumerate = function _enumerate(input) {
      for (var i = 0; this._state === PENDING && i < input.length; i++) {
        this._eachEntry(input[i], i);
      }
    };
  
    Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
      var c = this._instanceConstructor;
      var resolve$$1 = c.resolve;
  
  
      if (resolve$$1 === resolve$1) {
        var _then = void 0;
        var error = void 0;
        var didError = false;
        try {
          _then = entry.then;
        } catch (e) {
          didError = true;
          error = e;
        }
  
        if (_then === then && entry._state !== PENDING) {
          this._settledAt(entry._state, i, entry._result);
        } else if (typeof _then !== 'function') {
          this._remaining--;
          this._result[i] = entry;
        } else if (c === Promise$1) {
          var promise = new c(noop);
          if (didError) {
            reject(promise, error);
          } else {
            handleMaybeThenable(promise, entry, _then);
          }
          this._willSettleAt(promise, i);
        } else {
          this._willSettleAt(new c(function (resolve$$1) {
            return resolve$$1(entry);
          }), i);
        }
      } else {
        this._willSettleAt(resolve$$1(entry), i);
      }
    };
  
    Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
      var promise = this.promise;
  
  
      if (promise._state === PENDING) {
        this._remaining--;
  
        if (state === REJECTED) {
          reject(promise, value);
        } else {
          this._result[i] = value;
        }
      }
  
      if (this._remaining === 0) {
        fulfill(promise, this._result);
      }
    };
  
    Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
      var enumerator = this;
  
      subscribe(promise, undefined, function (value) {
        return enumerator._settledAt(FULFILLED, i, value);
      }, function (reason) {
        return enumerator._settledAt(REJECTED, i, reason);
      });
    };
  
    return Enumerator;
  }();
  
  /**
    `Promise.all` accepts an array of promises, and returns a new promise which
    is fulfilled with an array of fulfillment values for the passed promises, or
    rejected with the reason of the first passed promise to be rejected. It casts all
    elements of the passed iterable to promises as it runs this algorithm.
  
    Example:
  
    ```javascript
    let promise1 = resolve(1);
    let promise2 = resolve(2);
    let promise3 = resolve(3);
    let promises = [ promise1, promise2, promise3 ];
  
    Promise.all(promises).then(function(array){
      // The array here would be [ 1, 2, 3 ];
    });
    ```
  
    If any of the `promises` given to `all` are rejected, the first promise
    that is rejected will be given as an argument to the returned promises's
    rejection handler. For example:
  
    Example:
  
    ```javascript
    let promise1 = resolve(1);
    let promise2 = reject(new Error("2"));
    let promise3 = reject(new Error("3"));
    let promises = [ promise1, promise2, promise3 ];
  
    Promise.all(promises).then(function(array){
      // Code here never runs because there are rejected promises!
    }, function(error) {
      // error.message === "2"
    });
    ```
  
    @method all
    @static
    @param {Array} entries array of promises
    @param {String} label optional string for labeling the promise.
    Useful for tooling.
    @return {Promise} promise that is fulfilled when all `promises` have been
    fulfilled, or rejected if any of them become rejected.
    @static
  */
  function all(entries) {
    return new Enumerator(this, entries).promise;
  }
  
  /**
    `Promise.race` returns a new promise which is settled in the same way as the
    first passed promise to settle.
  
    Example:
  
    ```javascript
    let promise1 = new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve('promise 1');
      }, 200);
    });
  
    let promise2 = new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve('promise 2');
      }, 100);
    });
  
    Promise.race([promise1, promise2]).then(function(result){
      // result === 'promise 2' because it was resolved before promise1
      // was resolved.
    });
    ```
  
    `Promise.race` is deterministic in that only the state of the first
    settled promise matters. For example, even if other promises given to the
    `promises` array argument are resolved, but the first settled promise has
    become rejected before the other promises became fulfilled, the returned
    promise will become rejected:
  
    ```javascript
    let promise1 = new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve('promise 1');
      }, 200);
    });
  
    let promise2 = new Promise(function(resolve, reject){
      setTimeout(function(){
        reject(new Error('promise 2'));
      }, 100);
    });
  
    Promise.race([promise1, promise2]).then(function(result){
      // Code here never runs
    }, function(reason){
      // reason.message === 'promise 2' because promise 2 became rejected before
      // promise 1 became fulfilled
    });
    ```
  
    An example real-world use case is implementing timeouts:
  
    ```javascript
    Promise.race([ajax('foo.json'), timeout(5000)])
    ```
  
    @method race
    @static
    @param {Array} promises array of promises to observe
    Useful for tooling.
    @return {Promise} a promise which settles in the same way as the first passed
    promise to settle.
  */
  function race(entries) {
    /*jshint validthis:true */
    var Constructor = this;
  
    if (!isArray(entries)) {
      return new Constructor(function (_, reject) {
        return reject(new TypeError('You must pass an array to race.'));
      });
    } else {
      return new Constructor(function (resolve, reject) {
        var length = entries.length;
        for (var i = 0; i < length; i++) {
          Constructor.resolve(entries[i]).then(resolve, reject);
        }
      });
    }
  }
  
  /**
    `Promise.reject` returns a promise rejected with the passed `reason`.
    It is shorthand for the following:
  
    ```javascript
    let promise = new Promise(function(resolve, reject){
      reject(new Error('WHOOPS'));
    });
  
    promise.then(function(value){
      // Code here doesn't run because the promise is rejected!
    }, function(reason){
      // reason.message === 'WHOOPS'
    });
    ```
  
    Instead of writing the above, your code now simply becomes the following:
  
    ```javascript
    let promise = Promise.reject(new Error('WHOOPS'));
  
    promise.then(function(value){
      // Code here doesn't run because the promise is rejected!
    }, function(reason){
      // reason.message === 'WHOOPS'
    });
    ```
  
    @method reject
    @static
    @param {Any} reason value that the returned promise will be rejected with.
    Useful for tooling.
    @return {Promise} a promise rejected with the given `reason`.
  */
  function reject$1(reason) {
    /*jshint validthis:true */
    var Constructor = this;
    var promise = new Constructor(noop);
    reject(promise, reason);
    return promise;
  }
  
  function needsResolver() {
    throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  }
  
  function needsNew() {
    throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  }
  
  /**
    Promise objects represent the eventual result of an asynchronous operation. The
    primary way of interacting with a promise is through its `then` method, which
    registers callbacks to receive either a promise's eventual value or the reason
    why the promise cannot be fulfilled.
  
    Terminology
    -----------
  
    - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
    - `thenable` is an object or function that defines a `then` method.
    - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
    - `exception` is a value that is thrown using the throw statement.
    - `reason` is a value that indicates why a promise was rejected.
    - `settled` the final resting state of a promise, fulfilled or rejected.
  
    A promise can be in one of three states: pending, fulfilled, or rejected.
  
    Promises that are fulfilled have a fulfillment value and are in the fulfilled
    state.  Promises that are rejected have a rejection reason and are in the
    rejected state.  A fulfillment value is never a thenable.
  
    Promises can also be said to *resolve* a value.  If this value is also a
    promise, then the original promise's settled state will match the value's
    settled state.  So a promise that *resolves* a promise that rejects will
    itself reject, and a promise that *resolves* a promise that fulfills will
    itself fulfill.
  
  
    Basic Usage:
    ------------
  
    ```js
    let promise = new Promise(function(resolve, reject) {
      // on success
      resolve(value);
  
      // on failure
      reject(reason);
    });
  
    promise.then(function(value) {
      // on fulfillment
    }, function(reason) {
      // on rejection
    });
    ```
  
    Advanced Usage:
    ---------------
  
    Promises shine when abstracting away asynchronous interactions such as
    `XMLHttpRequest`s.
  
    ```js
    function getJSON(url) {
      return new Promise(function(resolve, reject){
        let xhr = new XMLHttpRequest();
  
        xhr.open('GET', url);
        xhr.onreadystatechange = handler;
        xhr.responseType = 'json';
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.send();
  
        function handler() {
          if (this.readyState === this.DONE) {
            if (this.status === 200) {
              resolve(this.response);
            } else {
              reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
            }
          }
        };
      });
    }
  
    getJSON('/posts.json').then(function(json) {
      // on fulfillment
    }, function(reason) {
      // on rejection
    });
    ```
  
    Unlike callbacks, promises are great composable primitives.
  
    ```js
    Promise.all([
      getJSON('/posts'),
      getJSON('/comments')
    ]).then(function(values){
      values[0] // => postsJSON
      values[1] // => commentsJSON
  
      return values;
    });
    ```
  
    @class Promise
    @param {Function} resolver
    Useful for tooling.
    @constructor
  */
  
  var Promise$1 = function () {
    function Promise(resolver) {
      this[PROMISE_ID] = nextId();
      this._result = this._state = undefined;
      this._subscribers = [];
  
      if (noop !== resolver) {
        typeof resolver !== 'function' && needsResolver();
        this instanceof Promise ? initializePromise(this, resolver) : needsNew();
      }
    }
  
    /**
    The primary way of interacting with a promise is through its `then` method,
    which registers callbacks to receive either a promise's eventual value or the
    reason why the promise cannot be fulfilled.
     ```js
    findUser().then(function(user){
      // user is available
    }, function(reason){
      // user is unavailable, and you are given the reason why
    });
    ```
     Chaining
    --------
     The return value of `then` is itself a promise.  This second, 'downstream'
    promise is resolved with the return value of the first promise's fulfillment
    or rejection handler, or rejected if the handler throws an exception.
     ```js
    findUser().then(function (user) {
      return user.name;
    }, function (reason) {
      return 'default name';
    }).then(function (userName) {
      // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
      // will be `'default name'`
    });
     findUser().then(function (user) {
      throw new Error('Found user, but still unhappy');
    }, function (reason) {
      throw new Error('`findUser` rejected and we're unhappy');
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
      // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
    });
    ```
    If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
     ```js
    findUser().then(function (user) {
      throw new PedagogicalException('Upstream error');
    }).then(function (value) {
      // never reached
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // The `PedgagocialException` is propagated all the way down to here
    });
    ```
     Assimilation
    ------------
     Sometimes the value you want to propagate to a downstream promise can only be
    retrieved asynchronously. This can be achieved by returning a promise in the
    fulfillment or rejection handler. The downstream promise will then be pending
    until the returned promise is settled. This is called *assimilation*.
     ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // The user's comments are now available
    });
    ```
     If the assimliated promise rejects, then the downstream promise will also reject.
     ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // If `findCommentsByAuthor` fulfills, we'll have the value here
    }, function (reason) {
      // If `findCommentsByAuthor` rejects, we'll have the reason here
    });
    ```
     Simple Example
    --------------
     Synchronous Example
     ```javascript
    let result;
     try {
      result = findResult();
      // success
    } catch(reason) {
      // failure
    }
    ```
     Errback Example
     ```js
    findResult(function(result, err){
      if (err) {
        // failure
      } else {
        // success
      }
    });
    ```
     Promise Example;
     ```javascript
    findResult().then(function(result){
      // success
    }, function(reason){
      // failure
    });
    ```
     Advanced Example
    --------------
     Synchronous Example
     ```javascript
    let author, books;
     try {
      author = findAuthor();
      books  = findBooksByAuthor(author);
      // success
    } catch(reason) {
      // failure
    }
    ```
     Errback Example
     ```js
     function foundBooks(books) {
     }
     function failure(reason) {
     }
     findAuthor(function(author, err){
      if (err) {
        failure(err);
        // failure
      } else {
        try {
          findBoooksByAuthor(author, function(books, err) {
            if (err) {
              failure(err);
            } else {
              try {
                foundBooks(books);
              } catch(reason) {
                failure(reason);
              }
            }
          });
        } catch(error) {
          failure(err);
        }
        // success
      }
    });
    ```
     Promise Example;
     ```javascript
    findAuthor().
      then(findBooksByAuthor).
      then(function(books){
        // found books
    }).catch(function(reason){
      // something went wrong
    });
    ```
     @method then
    @param {Function} onFulfilled
    @param {Function} onRejected
    Useful for tooling.
    @return {Promise}
    */
  
    /**
    `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
    as the catch block of a try/catch statement.
    ```js
    function findAuthor(){
    throw new Error('couldn't find that author');
    }
    // synchronous
    try {
    findAuthor();
    } catch(reason) {
    // something went wrong
    }
    // async with promises
    findAuthor().catch(function(reason){
    // something went wrong
    });
    ```
    @method catch
    @param {Function} onRejection
    Useful for tooling.
    @return {Promise}
    */
  
  
    Promise.prototype.catch = function _catch(onRejection) {
      return this.then(null, onRejection);
    };
  
    /**
      `finally` will be invoked regardless of the promise's fate just as native
      try/catch/finally behaves
    
      Synchronous example:
    
      ```js
      findAuthor() {
        if (Math.random() > 0.5) {
          throw new Error();
        }
        return new Author();
      }
    
      try {
        return findAuthor(); // succeed or fail
      } catch(error) {
        return findOtherAuther();
      } finally {
        // always runs
        // doesn't affect the return value
      }
      ```
    
      Asynchronous example:
    
      ```js
      findAuthor().catch(function(reason){
        return findOtherAuther();
      }).finally(function(){
        // author was either found, or not
      });
      ```
    
      @method finally
      @param {Function} callback
      @return {Promise}
    */
  
  
    Promise.prototype.finally = function _finally(callback) {
      var promise = this;
      var constructor = promise.constructor;
  
      if (isFunction(callback)) {
        return promise.then(function (value) {
          return constructor.resolve(callback()).then(function () {
            return value;
          });
        }, function (reason) {
          return constructor.resolve(callback()).then(function () {
            throw reason;
          });
        });
      }
  
      return promise.then(callback, callback);
    };
  
    return Promise;
  }();
  
  Promise$1.prototype.then = then;
  Promise$1.all = all;
  Promise$1.race = race;
  Promise$1.resolve = resolve$1;
  Promise$1.reject = reject$1;
  Promise$1._setScheduler = setScheduler;
  Promise$1._setAsap = setAsap;
  Promise$1._asap = asap;
  
  /*global self*/
  function polyfill() {
    var local = void 0;
  
    if (typeof global !== 'undefined') {
      local = global;
    } else if (typeof self !== 'undefined') {
      local = self;
    } else {
      try {
        local = Function('return this')();
      } catch (e) {
        throw new Error('polyfill failed because global object is unavailable in this environment');
      }
    }
  
    var P = local.Promise;
  
    if (P) {
      var promiseToString = null;
      try {
        promiseToString = Object.prototype.toString.call(P.resolve());
      } catch (e) {
        // silently ignored
      }
  
      if (promiseToString === '[object Promise]' && !P.cast) {
        return;
      }
    }
  
    local.Promise = Promise$1;
  }
  
  // Strange compat..
  Promise$1.polyfill = polyfill;
  Promise$1.Promise = Promise$1;
  
  return Promise$1;
  
  })));
  
  
  
  
  
  }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  },{"_process":1}]},{},[2])(2)
  });
  