exports.id = 6652;
exports.ids = [6652];
exports.modules = {

/***/ 416826:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

// Copyright (c) 2012, Mark Cavage. All rights reserved.
// Copyright 2015 Joyent, Inc.

var assert = __webpack_require__(439491);
var Stream = (__webpack_require__(12781).Stream);
var util = __webpack_require__(473837);


///--- Globals

/* JSSTYLED */
var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;


///--- Internal

function _capitalize(str) {
    return (str.charAt(0).toUpperCase() + str.slice(1));
}

function _toss(name, expected, oper, arg, actual) {
    throw new assert.AssertionError({
        message: util.format('%s (%s) is required', name, expected),
        actual: (actual === undefined) ? typeof (arg) : actual(arg),
        expected: expected,
        operator: oper || '===',
        stackStartFunction: _toss.caller
    });
}

function _getClass(arg) {
    return (Object.prototype.toString.call(arg).slice(8, -1));
}

function noop() {
    // Why even bother with asserts?
}


///--- Exports

var types = {
    bool: {
        check: function (arg) { return typeof (arg) === 'boolean'; }
    },
    func: {
        check: function (arg) { return typeof (arg) === 'function'; }
    },
    string: {
        check: function (arg) { return typeof (arg) === 'string'; }
    },
    object: {
        check: function (arg) {
            return typeof (arg) === 'object' && arg !== null;
        }
    },
    number: {
        check: function (arg) {
            return typeof (arg) === 'number' && !isNaN(arg);
        }
    },
    finite: {
        check: function (arg) {
            return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
        }
    },
    buffer: {
        check: function (arg) { return Buffer.isBuffer(arg); },
        operator: 'Buffer.isBuffer'
    },
    array: {
        check: function (arg) { return Array.isArray(arg); },
        operator: 'Array.isArray'
    },
    stream: {
        check: function (arg) { return arg instanceof Stream; },
        operator: 'instanceof',
        actual: _getClass
    },
    date: {
        check: function (arg) { return arg instanceof Date; },
        operator: 'instanceof',
        actual: _getClass
    },
    regexp: {
        check: function (arg) { return arg instanceof RegExp; },
        operator: 'instanceof',
        actual: _getClass
    },
    uuid: {
        check: function (arg) {
            return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
        },
        operator: 'isUUID'
    }
};

function _setExports(ndebug) {
    var keys = Object.keys(types);
    var out;

    /* re-export standard assert */
    if (process.env.NODE_NDEBUG) {
        out = noop;
    } else {
        out = function (arg, msg) {
            if (!arg) {
                _toss(msg, 'true', arg);
            }
        };
    }

    /* standard checks */
    keys.forEach(function (k) {
        if (ndebug) {
            out[k] = noop;
            return;
        }
        var type = types[k];
        out[k] = function (arg, msg) {
            if (!type.check(arg)) {
                _toss(msg, k, type.operator, arg, type.actual);
            }
        };
    });

    /* optional checks */
    keys.forEach(function (k) {
        var name = 'optional' + _capitalize(k);
        if (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        out[name] = function (arg, msg) {
            if (arg === undefined || arg === null) {
                return;
            }
            if (!type.check(arg)) {
                _toss(msg, k, type.operator, arg, type.actual);
            }
        };
    });

    /* arrayOf checks */
    keys.forEach(function (k) {
        var name = 'arrayOf' + _capitalize(k);
        if (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        var expected = '[' + k + ']';
        out[name] = function (arg, msg) {
            if (!Array.isArray(arg)) {
                _toss(msg, expected, type.operator, arg, type.actual);
            }
            var i;
            for (i = 0; i < arg.length; i++) {
                if (!type.check(arg[i])) {
                    _toss(msg, expected, type.operator, arg, type.actual);
                }
            }
        };
    });

    /* optionalArrayOf checks */
    keys.forEach(function (k) {
        var name = 'optionalArrayOf' + _capitalize(k);
        if (ndebug) {
            out[name] = noop;
            return;
        }
        var type = types[k];
        var expected = '[' + k + ']';
        out[name] = function (arg, msg) {
            if (arg === undefined || arg === null) {
                return;
            }
            if (!Array.isArray(arg)) {
                _toss(msg, expected, type.operator, arg, type.actual);
            }
            var i;
            for (i = 0; i < arg.length; i++) {
                if (!type.check(arg[i])) {
                    _toss(msg, expected, type.operator, arg, type.actual);
                }
            }
        };
    });

    /* re-export built-in assertions */
    Object.keys(assert).forEach(function (k) {
        if (k === 'AssertionError') {
            out[k] = assert[k];
            return;
        }
        if (ndebug) {
            out[k] = noop;
            return;
        }
        out[k] = assert[k];
    });

    /* export ourselves (for unit tests _only_) */
    out._setExports = _setExports;

    return out;
}

module.exports = _setExports(process.env.NODE_NDEBUG);


/***/ }),

/***/ 751338:
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = guarded;

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var DEFAULT_CONFIG = {
  context: null,
  log: function log() {
    var _console;

    return (_console = console).error.apply(_console, arguments);
  }
};

function logError(log, err) {
  log(err.stack || err);

  for (var key in err) {
    if (key !== 'stack') {
      log("".concat(key, " = ").concat(err[key]));
    }
  }
} // returns a guarded version of a given async function.
// Errors are logged during synchronous or asynchronous execution


function guarded(asyncFn, config) {
  config = _objectSpread({}, DEFAULT_CONFIG, config || {});
  return function guardedFn() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return asyncFn.apply(config.context, args)["catch"](function (err) {
      logError(config.log, err);
      throw err;
    });
  };
}

module.exports = exports["default"];

/***/ }),

/***/ 752185:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
Object.defineProperty(exports, "guarded", ({
  enumerable: true,
  get: function get() {
    return _guarded2["default"];
  }
}));
Object.defineProperty(exports, "resilient", ({
  enumerable: true,
  get: function get() {
    return _resilient2["default"];
  }
}));
Object.defineProperty(exports, "resilientTimed", ({
  enumerable: true,
  get: function get() {
    return _resilientTimed2["default"];
  }
}));
Object.defineProperty(exports, "reuseInFlight", ({
  enumerable: true,
  get: function get() {
    return _reuseInFlight2["default"];
  }
}));
Object.defineProperty(exports, "throttled", ({
  enumerable: true,
  get: function get() {
    return _throttled2["default"];
  }
}));
Object.defineProperty(exports, "timed", ({
  enumerable: true,
  get: function get() {
    return _timed2["default"];
  }
}));

var _guarded2 = _interopRequireDefault(__webpack_require__(751338));

var _resilient2 = _interopRequireDefault(__webpack_require__(261756));

var _resilientTimed2 = _interopRequireDefault(__webpack_require__(107704));

var _reuseInFlight2 = _interopRequireDefault(__webpack_require__(921364));

var _throttled2 = _interopRequireDefault(__webpack_require__(991363));

var _timed2 = _interopRequireDefault(__webpack_require__(340397));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

/***/ }),

/***/ 261756:
/***/ ((module, exports, __webpack_require__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = resilient;

var _verror = __webpack_require__(386783);

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var DEFAULT_CONFIG = {
  task: 'promise resolution',
  attempts: 3,
  context: null
};

function resilient(asyncFn, config) {
  config = _objectSpread({}, DEFAULT_CONFIG, config || {});
  var maxAttempts = config.attempts;

  function resilientFn() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var errors = [];
    var currentAttempts = 0; // recursive "catcher"

    function statefulCatch(err) {
      if (currentAttempts >= config.attempts) {
        // give up
        throw new _verror.VError({
          name: 'ResilientPromiseFailed',
          //
          cause: new _verror.MultiError(errors),
          info: {
            task: config.task,
            maxAttempts: maxAttempts
          }
        }, "Resilient ".concat(config.task, " failed after ").concat(maxAttempts));
      } else {
        currentAttempts += 1;
        errors.push(err);
        return asyncFn.apply(config.context, args)["catch"](statefulCatch);
      }
    } // kick off the chain


    return asyncFn.apply(config.context, args)["catch"](statefulCatch);
  }

  return resilientFn;
}

module.exports = exports["default"];

/***/ }),

/***/ 107704:
/***/ ((module, exports, __webpack_require__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = resilientTimed;

var _resilient = _interopRequireDefault(__webpack_require__(261756));

var _timed = _interopRequireDefault(__webpack_require__(340397));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

// convenience composition of resilient, timed function - the function will time out
// after the given timeout, but will retry itself attempts times. The same
// config will be passed to both the timed and resilient functions.
function resilientTimed(asyncFn, config) {
  return (0, _resilient["default"])((0, _timed["default"])(asyncFn, config), config);
}

module.exports = exports["default"];

/***/ }),

/***/ 921364:
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = reuseInFlight;

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var DEFAULT_CONFIG = {
  createKey: function createKey(args) {
    return JSON.stringify(args);
  },
  ignoreSingleUndefined: false
}; // for a given Promise-generating function, track each execution by the stringified
// arguments. if the function is called again with the same arguments, then instead
// of generating a new promise, an existing in-flight promise is used instead. This
// prevents unnecessary repetition of async function calls while the same function
// is still in flight.

function reuseInFlight(asyncFn, config) {
  config = _objectSpread({}, DEFAULT_CONFIG, config || {});
  var inflight = {};
  return function debounced() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    if (config.ignoreSingleUndefined && args.length === 1 && args[0] === undefined) {
      console.warn('Ignoring single undefined arg (reuseInFlight)');
      args = [];
    }

    var key = config.createKey(args);

    if (!inflight.hasOwnProperty(key)) {
      // WE DO NOT AWAIT, we are storing the promise itself
      inflight[key] = asyncFn.apply(this, args).then(function (results) {
        // self invalidate
        delete inflight[key];
        return results;
      }, function (err) {
        // still self-invalidate, then rethrow
        delete inflight[key];
        throw err;
      });
    }

    return inflight[key];
  };
}

module.exports = exports["default"];

/***/ }),

/***/ 991363:
/***/ ((module, exports, __webpack_require__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = throttled;

var _simple = __webpack_require__(504914);

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var DEFAULT_CONFIG = {
  batchSize: 100,
  delay: 0,
  log: function log() {
    var _console;

    return (_console = console).log.apply(_console, arguments);
  }
}; // throttles the number of promises a promise generating function can execute. This is useful
// when you are firing off a large number of promises without waiting for them to be complete.
//
// the decorator maintains a count of the number of executions, and if the count hits a defined
// batch size, it blocks all subsequent promises until the current batch of promises complete.

function throttled(asyncFn, config) {
  var count = 0;
  var waitChain = Promise.resolve();
  var promiseQueue = [];
  config = _objectSpread({}, DEFAULT_CONFIG, config || {});
  return function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    if (count % config.batchSize === 0) {
      // replaces the current wait chain with a Promise
      // that waits for the current set of Promises to complete
      // first before allowing any more promises to execute
      //
      // awkward, because of the mutable aspect of promiseQueue
      // and count, we use an immediately executing function
      // block where they do not mutate.
      waitChain = function (queue, count) {
        return waitChain.then(function () {
          config.log("Completed ".concat(count));

          if (config.delay === 0) {
            return Promise.all(queue);
          } else {
            return Promise.all(queue).then(_simple.sleep.bind(null, config.delay));
          }
        });
      }(promiseQueue, count);

      promiseQueue = [];
    } // we always return the tail.


    var tail = waitChain.then(function () {
      return asyncFn.apply(void 0, args);
    });
    promiseQueue.push(tail);
    count += 1;
    return tail;
  };
}

module.exports = exports["default"];

/***/ }),

/***/ 340397:
/***/ ((module, exports, __webpack_require__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = timed;

var _simple = __webpack_require__(504914);

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var DEFAULT_CONFIG = {
  task: 'promise resolution',
  timeout: 1000,
  context: null
}; // decorates a promise generating function such that if it takes too long to
// complete, it will time out.

function timed(asyncFn, config) {
  config = _objectSpread({}, DEFAULT_CONFIG, config || {});
  return function timedFn() {
    var pacer = (0, _simple.sleep)(config.timeout).then(function () {
      return Promise.reject(new Error("".concat(config.task, " timed out")));
    });

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return Promise.race([asyncFn.apply(config.context, args), pacer]);
  };
}

module.exports = exports["default"];

/***/ }),

/***/ 260235:
/***/ ((module, exports, __webpack_require__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = execute;

var _guarded = _interopRequireDefault(__webpack_require__(751338));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function execute(fn) {
  var guardedFn = (0, _guarded["default"])(fn);

  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  return guardedFn.apply(void 0, args);
}

module.exports = exports["default"];

/***/ }),

/***/ 504914:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
Object.defineProperty(exports, "execute", ({
  enumerable: true,
  get: function get() {
    return _execute2["default"];
  }
}));
Object.defineProperty(exports, "sleep", ({
  enumerable: true,
  get: function get() {
    return _sleep2["default"];
  }
}));

var _execute2 = _interopRequireDefault(__webpack_require__(260235));

var _sleep2 = _interopRequireDefault(__webpack_require__(844991));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

/***/ }),

/***/ 844991:
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = sleep;

function sleep(duration) {
  return new Promise(function (ok) {
    return setTimeout(ok, duration);
  });
}

module.exports = exports["default"];

/***/ }),

/***/ 372007:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({ value: true }));

/**
 * The async/await utility for browsers and Node.js.
 *
 * (
 * [examples](https://github.com/hunterloftis/awaiting#examples) -
 * [github](https://github.com/hunterloftis/awaiting) -
 * [npm](https://www.npmjs.com/package/awaiting) -
 * [suggestions / bug reports](https://github.com/hunterloftis/awaiting/issues) -
 * [installation](https://github.com/hunterloftis/awaiting#installation) -
 * [motivation](https://github.com/hunterloftis/awaiting#motivation)
 * )
 *
 * **`$ yarn add awaiting`**
 *
 * **`$ npm install awaiting --save`**
 *
 * **`<script src='awaiting.js'>`**
 *
 * [![Build Status](https://travis-ci.org/hunterloftis/awaiting.svg?branch=master)](https://travis-ci.org/hunterloftis/awaiting)
 * [![Coverage Status](https://coveralls.io/repos/hunterloftis/awaiting/badge.svg?branch=master)](https://coveralls.io/r/hunterloftis/awaiting?branch=master)
 *
 * @license MIT
 * @file
 * @example
 *
 * const a = require('awaiting')
 * // ...
 * await a.delay(1000)
 */

/**
 * Iterable Error type
 *
 * Functions that operate on lists throw ErrorLists,
 * making it possible to inspect all of the Errors that may have been thrown.
 *
 * @class
 * @param {string} message top-level Error message
 * @returns {iterable.<Error>}
 * @example
 *
 * const err = new ErrorList('several errors')
 * err.add(new Error('first'))
 * err.add(new Error('second'))
 * console.log(err.message, err.get(1).message)
 * // => several errors second
 *
 * @example
 *
 * try {
 *   await a.list([ failing1, failing2, failing3 ])
 * }
 * catch (errorList) {
 *   for (let err of errorList) {
 *     console.error(err.stack)
 *   }
 * }
 */
function ErrorList (message) {
  this.name = 'ErrorList';
  this.message = message;
  this.stack = (new Error()).stack;
  this.errors = [];
  Object.defineProperty(this, 'length', {
    get: function () { return this.errors.length }
  });
}
ErrorList.prototype = Object.create(Error.prototype);
ErrorList.prototype.constructor = ErrorList;
ErrorList.prototype.add = function (err) {
  this.errors.push(err);
};
ErrorList.prototype.get = function (index) {
  return this.errors[index]
};
ErrorList.prototype[Symbol.iterator] = function* () {
  let i = 0;
  while (i < this.errors.length) {
    yield this.errors[i];
    i++;
  }
};

/**
 * Waits for `ms` milliseconds to pass.
 *
 * @param {number} ms the number of milliseconds to wait
 * @returns {promise}
 * @example
 *
 * const start = Date.now()
 * await a.delay(5000)
 * console.log(Date.now() - start)
 * // => 5000
 */
async function delay (ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

/**
 * Waits for `date`.
 *
 * @param {date} date the date at which to stop waiting
 * @returns {promise}
 * @example
 *
 * const nextYear = new Date(2018, 1)
 * await a.time(nextYear)
 * // => this will run until the end of 2017
 */
async function time (date) {
  const delta = Math.max(date.getTime() - Date.now(), 0);
  return await delay(delta)
}

/**
 * Waits for the value of `goal`, limited by the resolution of `limiter`.
 * Throws an Error if `limiter` finishes first or if either throws early.
 * If `limiter` is a number, limits by time in milliseconds
 *
 * @param {promise} goal the promise to execute
 * @param {number|promise} limiter milliseconds or promise to limit by
 * @returns {promise}
 * @example
 *
 * // throw if flowers.jpg can't be retrieved in < 5 seconds
 * await a.limit(fetch('flowers.jpg'), 5000)
 */
async function limit (goal, limiter) {
  return new Promise((resolve, reject) => {
    const limitFn = typeof limiter === 'number'
      ? delay(limiter)
      : limiter;
    let completed = false;
    goal
      .then(result => {
        if (complete()) return
        resolve(result);
      })
      .catch(err => {
        if (complete()) return
        reject(err);
      });
    limitFn
      .then(result => {
        if (complete()) return
        reject(new Error('limit exceeded'));
      })
      .catch(err => {
        if (complete()) return
        reject(err);
      });
    function complete () {
      if (completed) return true
      completed = true;
      return false
    }
  })
}

/**
 * Waits for `emitter` to emit an `eventName` event.
 *
 * @param {EventEmitter} emitter the object to listen on
 * @param {string} eventName the event to listen for
 * @returns {promise.<Array>} an array of the arguments passed to the `eventName` event
 * @example
 *
 * await a.event(server, 'listen')
 */
async function event (emitter, eventName) {
  return new Promise((resolve, reject) => {
    emitter.once(eventName, (...args) => {
      resolve([...args]);
    });
  })
}

/**
 * Calls a function `func` that takes arguments `args` and an `(err, result)` callback.
 * Waits for the callback result, throwing an Error if err is truthy.
 *
 * @param {function} fn a function that takes a callback
 * @param {...object} args arguments to pass to `fn`
 * @returns {promise} the result passed to the callback
 * @example
 *
 * const result = await a.callback(fs.readFile, 'foo.txt')
 * console.log(result)
 * // => 'the text of the file'
 */
async function callback (fn, ...args) {
  return new Promise((resolve, reject) => {
    fn(...args, (err, result) => {
      if (err) return reject(err)
      resolve(result);
    });
  })
}

/**
 * Wraps a node style function (see `callback`) into a new function, which instead of taking a callback
 * function, returns an async function (`Promise`). This `Promise` resolves if the first (error) argument of the
 * callback was called with a falsy value, rejects with the error otherwise. Takes the rest of the
 * arguments as the original function `fn`.
 *
 * @returns {function}
 * @example
 *
 * const fs = require('fs')
 * const readFile = a.awaited(fs.readFile)
 * const contents = await readFile('foo.txt', 'utf-8')
 */
function awaited (fn) {
  return async (...args) => callback(fn, ...args)
}

function throwOnRejection (err, promise) { throw err }
function swallowOnRejection (err, promise) {} // eslint-disable-line

/**
 * Waits for the first Promise in `list` to resolve.
 *
 * @param {array.<Promise>} list racing promises
 * @param {number} [ignore=0] number of rejections to ignore
 * @returns {promise}
 * @example
 *
 * const file = await a.single([ fetch(remoteFile), read(localFile) ])
 */
async function single (list, ignore = 0) {
  const results = await set(list, 1, ignore);
  return results[0]
}

/**
 * Waits for the first `count` Promises in `list` to resolve.
 *
 * @param {array.<Promise>} list racing promises
 * @param {number} [count=list.length] number of promises to wait for
 * @param {number} [ignore=0] number of rejections to ignore
 * @returns {promise.<Array>}
 * @example
 *
 * const [ first, second ] = await a.set([
 *   ping('ns1.example.com'),
 *   ping('ns2.example.com'),
 *   ping('ns3.example.com'),
 *   ping('ns4.example.com')
 * ], 2)
 * console.log(`fastest nameservers: ${first}, ${second}`)
 */

async function set (list, count = Infinity, ignore = 0) {
  return new Promise((resolve, reject) => {
    const goal = Math.min(list.length, count);
    const limit = Math.min(list.length - goal, ignore);
    const results = [];
    const failures = new ErrorList('too many failures');
    list.forEach(promise => promise.then(success).catch(error));

    function success (result) {
      if (failures.length > limit) return
      results.push(result);
      if (results.length === goal) {
        resolve(results);
      }
    }
    function error (err) {
      if (failures.length > limit) return
      if (results.length >= goal) return
      failures.add(err);
      // TODO: reject with an Iterable custom Error that includes all failures
      if (failures.length > limit) reject(failures);
    }
  })
}

/**
 * Waits for all Promises in `list` to resolve.
 *
 * Like `Promise.all` with the option to ignore some (or all) rejections.
 *
 * @param {array} list promises
 * @param {number} ignore rejections to ignore
 * @returns {promise.<Array>} promised results in order
 * @example
 *
 * const results = await a.list([ foo, bar, baz ])
 * console.log(results.length)
 * // => 3
 */
async function list (list, ignore = 0) {
  return new Promise((resolve, reject) => {
    const results = [];
    const failures = new ErrorList('too many failures');
    const complete = () => count + failures.length === list.length;
    let count = 0;
    list.forEach((promise, index) => {
      promise.then(success).catch(error);

      function success (result) {
        if (failures.length > ignore) return
        results[index] = result;
        count++;
        if (complete()) resolve(results);
      }
      function error (err) {
        if (failures.length > ignore) return
        results[index] = undefined;
        failures.add(err);
        if (failures.length > ignore) reject(failures);
        else if (complete()) resolve(results);
      }
    });
  })
}

/**
 * Waits for all Promises in the keys of `container` to resolve.
 *
 * @param {object} container
 * @param {number} ignore rejections to ignore
 * @returns {promise.<Object>} a new object with keys mapped to the resolved values
 * @example
 *
 * const results = await a.object({
 *   pictures: getPictures(),
 *   comments: getComments(),
 *   tweets: getTweets()
 * })
 * console.log(results.pictures, results.comments, results.tweets)
 */

async function object (container, ignore = 0) {
  const containsPromise = key => typeof container[key].then === 'function';
  const keys = Object.keys(container).filter(containsPromise);
  const promises = keys.map(key => container[key]);
  const results = await list(promises, ignore);
  const obj = Object.assign({}, container);
  results.forEach((result, index) => {
    const key = keys[index];
    obj[key] = result;
  });
  return obj
}

/**
 * Passes each item in `list` to the Promise-returning function `fn`,
 * running at most `concurrency` simultaneous promises.
 *
 * For cases where starting all Promises simultaneously is infeasible,
 * such as making a large number of requests to a server with rate-limiting.
 *
 * @param {array} list items to pass to each promise
 * @param {number} concurrency maximum concurrency
 * @param {function} fn takes an item and returns a Promise
 * @example
 *
 * // pull hundreds of pages from a site without getting blocked
 * const pages = await a.map(urls, 3, fetch)
 */
async function map (list, concurrency, fn) {
  return new Promise((resolve, reject) => {
    const results = [];
    let running = 0;
    let index = 0;

    update();

    function update () {
      if (index === list.length && running === 0) {
        return resolve(results)
      }
      while (running < concurrency && index < list.length) {
        fn(list[index]).then(success(index)).catch(error);
        index++;
        running++;
      }
    }
    function success (i) {
      return result => {
        running--;
        results[i] = result;
        update();
      }
    }
    function error (err) {
      running--;
      index = Infinity;
      reject(err);
    }
  })
}

/**
 * Waits for `promise` to reject, returning the Error object.
 * If `promise` resolves successfully, returns `undefined`.
 *
 * @param {promise}
 * @returns {promise.<Error>} the Error object, or undefined
 * @example
 *
 * test('throws "foo"', () => {
 *   const err = await a.failure(shouldThrow())
 *   assert.equal(err.message, 'foo')
 * })
 */
async function failure (promise) {
  return Promise.resolve()
    .then(() => promise)
    .then(() => undefined)
    .catch(err => err)
}

/**
 * Waits for the value of `promise`.
 * If `promise` throws an Error, returns `undefined`.
 *
 * @param {promise}
 * @returns {promise} the result, or undefined
 * @example
 *
 * const isNodeProject = await a.success(a.callback(fs.access, packageJSON))
 * if (isNodeProject) doSomething()
 */
async function success (promise) {
  return Promise.resolve()
    .then(() => promise)
    .catch(() => undefined) // eslint-disable-line
}

/**
 * Waits for `promise` to resolve or reject.
 * Returns either the resolved value, or the Error object.
 *
 * @param {promise}
 * @returns {promise} the result or error
 * @example
 *
 * $("#ajax-loader-animation").show()
 * await a.result(loadAjaxData())
 * $("#ajax-loader-animation").hide();
 */
async function result (promise) {
  return Promise.resolve()
    .then(() => promise)
    .catch(err => err)
}

/**
 * Provides a stack trace for unhandled rejections instead of the default message string.
 *
 * `throw` and `swallow` can be called multiple times but will only attach a single listener.
 *
 * @alias throw
 * @returns {undefined}
 * @example
 *
 * failingPromise()
 * // => (node:6051) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
 *
 * @example
 *
 * a.throw()
 * failingPromise()
 * // => /Users/hloftis/code/awaiting/lib/awaiting.js:308
 * // => function throwOnRejection (err, promise) { throw err }
 * // =>                                            ^
 * // => Error: fail
 * // =>    at fail (/Users/hloftis/code/awaiting/test/fixtures/rejection-throw.js:7:9)
 * // =>    at Object.<anonymous> (/Users/hloftis/code/awaiting/test/fixtures/rejection-throw.js:4:1)
 */
function throwRejections () {
  process.removeListener('unhandledRejection', throwOnRejection);
  process.removeListener('unhandledRejection', swallowOnRejection);
  process.on('unhandledRejection', throwOnRejection);
}

/**
 * Silently swallows unhandled rejections.
 *
 * This is an anti-pattern, but if you depend on a module that doesn't handle all of its rejections,
 * you'll get a lot of really annoying logs in current versions of node.
 * `swallow` will allow you to suppress them.
 *
 * `throw` and `swallow` can be called multiple times but will only attach a single listener.
 *
 * @alias swallow
 * @returns {undefined}
 * @example
 *
 * failingPromise()
 * // => (node:6051) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
 *
 * @example
 *
 * a.swallow()
 * failingPromise()
 * // (no output)
 */
function swallowRejections () {
  process.removeListener('unhandledRejection', throwOnRejection);
  process.removeListener('unhandledRejection', swallowOnRejection);
  process.on('unhandledRejection', swallowOnRejection);
}

exports.delay = delay;
exports.time = time;
exports.limit = limit;
exports.event = event;
exports.callback = callback;
exports.single = single;
exports.set = set;
exports.list = list;
exports.object = object;
exports.map = map;
exports.failure = failure;
exports.success = success;
exports.result = result;
exports.awaited = awaited;
exports.awaitable = awaited;
exports["throw"] = throwRejections;
exports.swallow = swallowRejections;
exports.ErrorList = ErrorList;


/***/ }),

/***/ 204993:
/***/ ((__unused_webpack_module, exports) => {

var __webpack_unused_export__;
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.

function isArray(arg) {
  if (Array.isArray) {
    return Array.isArray(arg);
  }
  return objectToString(arg) === '[object Array]';
}
__webpack_unused_export__ = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
__webpack_unused_export__ = isBoolean;

function isNull(arg) {
  return arg === null;
}
__webpack_unused_export__ = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
__webpack_unused_export__ = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
__webpack_unused_export__ = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
__webpack_unused_export__ = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
__webpack_unused_export__ = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
__webpack_unused_export__ = isUndefined;

function isRegExp(re) {
  return objectToString(re) === '[object RegExp]';
}
__webpack_unused_export__ = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
__webpack_unused_export__ = isObject;

function isDate(d) {
  return objectToString(d) === '[object Date]';
}
__webpack_unused_export__ = isDate;

function isError(e) {
  return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.VZ = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
__webpack_unused_export__ = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
__webpack_unused_export__ = isPrimitive;

__webpack_unused_export__ = Buffer.isBuffer;

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


/***/ }),

/***/ 893238:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

/*
 * extsprintf.js: extended POSIX-style sprintf
 */

var mod_assert = __webpack_require__(439491);
var mod_util = __webpack_require__(473837);

/*
 * Public interface
 */
exports.sprintf = jsSprintf;
exports.printf = jsPrintf;
exports.fprintf = jsFprintf;

/*
 * Stripped down version of s[n]printf(3c).  We make a best effort to throw an
 * exception when given a format string we don't understand, rather than
 * ignoring it, so that we won't break existing programs if/when we go implement
 * the rest of this.
 *
 * This implementation currently supports specifying
 *	- field alignment ('-' flag),
 * 	- zero-pad ('0' flag)
 *	- always show numeric sign ('+' flag),
 *	- field width
 *	- conversions for strings, decimal integers, and floats (numbers).
 *	- argument size specifiers.  These are all accepted but ignored, since
 *	  Javascript has no notion of the physical size of an argument.
 *
 * Everything else is currently unsupported, most notably precision, unsigned
 * numbers, non-decimal numbers, and characters.
 */
function jsSprintf(ofmt)
{
	var regex = [
	    '([^%]*)',				/* normal text */
	    '%',				/* start of format */
	    '([\'\\-+ #0]*?)',			/* flags (optional) */
	    '([1-9]\\d*)?',			/* width (optional) */
	    '(\\.([1-9]\\d*))?',		/* precision (optional) */
	    '[lhjztL]*?',			/* length mods (ignored) */
	    '([diouxXfFeEgGaAcCsSp%jr])'	/* conversion */
	].join('');

	var re = new RegExp(regex);

	/* variadic arguments used to fill in conversion specifiers */
	var args = Array.prototype.slice.call(arguments, 1);
	/* remaining format string */
	var fmt = ofmt;

	/* components of the current conversion specifier */
	var flags, width, precision, conversion;
	var left, pad, sign, arg, match;

	/* return value */
	var ret = '';

	/* current variadic argument (1-based) */
	var argn = 1;
	/* 0-based position in the format string that we've read */
	var posn = 0;
	/* 1-based position in the format string of the current conversion */
	var convposn;
	/* current conversion specifier */
	var curconv;

	mod_assert.equal('string', typeof (fmt),
	    'first argument must be a format string');

	while ((match = re.exec(fmt)) !== null) {
		ret += match[1];
		fmt = fmt.substring(match[0].length);

		/*
		 * Update flags related to the current conversion specifier's
		 * position so that we can report clear error messages.
		 */
		curconv = match[0].substring(match[1].length);
		convposn = posn + match[1].length + 1;
		posn += match[0].length;

		flags = match[2] || '';
		width = match[3] || 0;
		precision = match[4] || '';
		conversion = match[6];
		left = false;
		sign = false;
		pad = ' ';

		if (conversion == '%') {
			ret += '%';
			continue;
		}

		if (args.length === 0) {
			throw (jsError(ofmt, convposn, curconv,
			    'has no matching argument ' +
			    '(too few arguments passed)'));
		}

		arg = args.shift();
		argn++;

		if (flags.match(/[\' #]/)) {
			throw (jsError(ofmt, convposn, curconv,
			    'uses unsupported flags'));
		}

		if (precision.length > 0) {
			throw (jsError(ofmt, convposn, curconv,
			    'uses non-zero precision (not supported)'));
		}

		if (flags.match(/-/))
			left = true;

		if (flags.match(/0/))
			pad = '0';

		if (flags.match(/\+/))
			sign = true;

		switch (conversion) {
		case 's':
			if (arg === undefined || arg === null) {
				throw (jsError(ofmt, convposn, curconv,
				    'attempted to print undefined or null ' +
				    'as a string (argument ' + argn + ' to ' +
				    'sprintf)'));
			}
			ret += doPad(pad, width, left, arg.toString());
			break;

		case 'd':
			arg = Math.floor(arg);
			/*jsl:fallthru*/
		case 'f':
			sign = sign && arg > 0 ? '+' : '';
			ret += sign + doPad(pad, width, left,
			    arg.toString());
			break;

		case 'x':
			ret += doPad(pad, width, left, arg.toString(16));
			break;

		case 'j': /* non-standard */
			if (width === 0)
				width = 10;
			ret += mod_util.inspect(arg, false, width);
			break;

		case 'r': /* non-standard */
			ret += dumpException(arg);
			break;

		default:
			throw (jsError(ofmt, convposn, curconv,
			    'is not supported'));
		}
	}

	ret += fmt;
	return (ret);
}

function jsError(fmtstr, convposn, curconv, reason) {
	mod_assert.equal(typeof (fmtstr), 'string');
	mod_assert.equal(typeof (curconv), 'string');
	mod_assert.equal(typeof (convposn), 'number');
	mod_assert.equal(typeof (reason), 'string');
	return (new Error('format string "' + fmtstr +
	    '": conversion specifier "' + curconv + '" at character ' +
	    convposn + ' ' + reason));
}

function jsPrintf() {
	var args = Array.prototype.slice.call(arguments);
	args.unshift(process.stdout);
	jsFprintf.apply(null, args);
}

function jsFprintf(stream) {
	var args = Array.prototype.slice.call(arguments, 1);
	return (stream.write(jsSprintf.apply(this, args)));
}

function doPad(chr, width, left, str)
{
	var ret = str;

	while (ret.length < width) {
		if (left)
			ret += chr;
		else
			ret = chr + ret;
	}

	return (ret);
}

/*
 * This function dumps long stack traces for exceptions having a cause() method.
 * See node-verror for an example.
 */
function dumpException(ex)
{
	var ret;

	if (!(ex instanceof Error))
		throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));

	/* Note that V8 prepends "ex.stack" with ex.toString(). */
	ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;

	if (ex.cause && typeof (ex.cause) === 'function') {
		var cex = ex.cause();
		if (cex) {
			ret += '\nCaused by: ' + dumpException(cex);
		}
	}

	return (ret);
}


/***/ }),

/***/ 386783:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/*
 * verror.js: richer JavaScript errors
 */

var mod_assertplus = __webpack_require__(416826);
var mod_util = __webpack_require__(473837);

var mod_extsprintf = __webpack_require__(893238);
var mod_isError = (__webpack_require__(204993)/* .isError */ .VZ);
var sprintf = mod_extsprintf.sprintf;

/*
 * Public interface
 */

/* So you can 'var VError = require('verror')' */
module.exports = VError;
/* For compatibility */
VError.VError = VError;
/* Other exported classes */
VError.SError = SError;
VError.WError = WError;
VError.MultiError = MultiError;

/*
 * Common function used to parse constructor arguments for VError, WError, and
 * SError.  Named arguments to this function:
 *
 *     strict		force strict interpretation of sprintf arguments, even
 *     			if the options in "argv" don't say so
 *
 *     argv		error's constructor arguments, which are to be
 *     			interpreted as described in README.md.  For quick
 *     			reference, "argv" has one of the following forms:
 *
 *          [ sprintf_args... ]           (argv[0] is a string)
 *          [ cause, sprintf_args... ]    (argv[0] is an Error)
 *          [ options, sprintf_args... ]  (argv[0] is an object)
 *
 * This function normalizes these forms, producing an object with the following
 * properties:
 *
 *    options           equivalent to "options" in third form.  This will never
 *    			be a direct reference to what the caller passed in
 *    			(i.e., it may be a shallow copy), so it can be freely
 *    			modified.
 *
 *    shortmessage      result of sprintf(sprintf_args), taking options.strict
 *    			into account as described in README.md.
 */
function parseConstructorArguments(args)
{
	var argv, options, sprintf_args, shortmessage, k;

	mod_assertplus.object(args, 'args');
	mod_assertplus.bool(args.strict, 'args.strict');
	mod_assertplus.array(args.argv, 'args.argv');
	argv = args.argv;

	/*
	 * First, figure out which form of invocation we've been given.
	 */
	if (argv.length === 0) {
		options = {};
		sprintf_args = [];
	} else if (mod_isError(argv[0])) {
		options = { 'cause': argv[0] };
		sprintf_args = argv.slice(1);
	} else if (typeof (argv[0]) === 'object') {
		options = {};
		for (k in argv[0]) {
			options[k] = argv[0][k];
		}
		sprintf_args = argv.slice(1);
	} else {
		mod_assertplus.string(argv[0],
		    'first argument to VError, SError, or WError ' +
		    'constructor must be a string, object, or Error');
		options = {};
		sprintf_args = argv;
	}

	/*
	 * Now construct the error's message.
	 *
	 * extsprintf (which we invoke here with our caller's arguments in order
	 * to construct this Error's message) is strict in its interpretation of
	 * values to be processed by the "%s" specifier.  The value passed to
	 * extsprintf must actually be a string or something convertible to a
	 * String using .toString().  Passing other values (notably "null" and
	 * "undefined") is considered a programmer error.  The assumption is
	 * that if you actually want to print the string "null" or "undefined",
	 * then that's easy to do that when you're calling extsprintf; on the
	 * other hand, if you did NOT want that (i.e., there's actually a bug
	 * where the program assumes some variable is non-null and tries to
	 * print it, which might happen when constructing a packet or file in
	 * some specific format), then it's better to stop immediately than
	 * produce bogus output.
	 *
	 * However, sometimes the bug is only in the code calling VError, and a
	 * programmer might prefer to have the error message contain "null" or
	 * "undefined" rather than have the bug in the error path crash the
	 * program (making the first bug harder to identify).  For that reason,
	 * by default VError converts "null" or "undefined" arguments to their
	 * string representations and passes those to extsprintf.  Programmers
	 * desiring the strict behavior can use the SError class or pass the
	 * "strict" option to the VError constructor.
	 */
	mod_assertplus.object(options);
	if (!options.strict && !args.strict) {
		sprintf_args = sprintf_args.map(function (a) {
			return (a === null ? 'null' :
			    a === undefined ? 'undefined' : a);
		});
	}

	if (sprintf_args.length === 0) {
		shortmessage = '';
	} else {
		shortmessage = sprintf.apply(null, sprintf_args);
	}

	return ({
	    'options': options,
	    'shortmessage': shortmessage
	});
}

/*
 * See README.md for reference documentation.
 */
function VError()
{
	var args, obj, parsed, cause, ctor, message, k;

	args = Array.prototype.slice.call(arguments, 0);

	/*
	 * This is a regrettable pattern, but JavaScript's built-in Error class
	 * is defined to work this way, so we allow the constructor to be called
	 * without "new".
	 */
	if (!(this instanceof VError)) {
		obj = Object.create(VError.prototype);
		VError.apply(obj, arguments);
		return (obj);
	}

	/*
	 * For convenience and backwards compatibility, we support several
	 * different calling forms.  Normalize them here.
	 */
	parsed = parseConstructorArguments({
	    'argv': args,
	    'strict': false
	});

	/*
	 * If we've been given a name, apply it now.
	 */
	if (parsed.options.name) {
		mod_assertplus.string(parsed.options.name,
		    'error\'s "name" must be a string');
		this.name = parsed.options.name;
	}

	/*
	 * For debugging, we keep track of the original short message (attached
	 * this Error particularly) separately from the complete message (which
	 * includes the messages of our cause chain).
	 */
	this.jse_shortmsg = parsed.shortmessage;
	message = parsed.shortmessage;

	/*
	 * If we've been given a cause, record a reference to it and update our
	 * message appropriately.
	 */
	cause = parsed.options.cause;
	if (cause) {
		mod_assertplus.ok(mod_isError(cause), 'cause is not an Error');
		this.jse_cause = cause;

		if (!parsed.options.skipCauseMessage) {
			message += ': ' + cause.message;
		}
	}

	/*
	 * If we've been given an object with properties, shallow-copy that
	 * here.  We don't want to use a deep copy in case there are non-plain
	 * objects here, but we don't want to use the original object in case
	 * the caller modifies it later.
	 */
	this.jse_info = {};
	if (parsed.options.info) {
		for (k in parsed.options.info) {
			this.jse_info[k] = parsed.options.info[k];
		}
	}

	this.message = message;
	Error.call(this, message);

	if (Error.captureStackTrace) {
		ctor = parsed.options.constructorOpt || this.constructor;
		Error.captureStackTrace(this, ctor);
	}

	return (this);
}

mod_util.inherits(VError, Error);
VError.prototype.name = 'VError';

VError.prototype.toString = function ve_toString()
{
	var str = (this.hasOwnProperty('name') && this.name ||
		this.constructor.name || this.constructor.prototype.name);
	if (this.message)
		str += ': ' + this.message;

	return (str);
};

/*
 * This method is provided for compatibility.  New callers should use
 * VError.cause() instead.  That method also uses the saner `null` return value
 * when there is no cause.
 */
VError.prototype.cause = function ve_cause()
{
	var cause = VError.cause(this);
	return (cause === null ? undefined : cause);
};

/*
 * Static methods
 *
 * These class-level methods are provided so that callers can use them on
 * instances of Errors that are not VErrors.  New interfaces should be provided
 * only using static methods to eliminate the class of programming mistake where
 * people fail to check whether the Error object has the corresponding methods.
 */

VError.cause = function (err)
{
	mod_assertplus.ok(mod_isError(err), 'err must be an Error');
	return (mod_isError(err.jse_cause) ? err.jse_cause : null);
};

VError.info = function (err)
{
	var rv, cause, k;

	mod_assertplus.ok(mod_isError(err), 'err must be an Error');
	cause = VError.cause(err);
	if (cause !== null) {
		rv = VError.info(cause);
	} else {
		rv = {};
	}

	if (typeof (err.jse_info) == 'object' && err.jse_info !== null) {
		for (k in err.jse_info) {
			rv[k] = err.jse_info[k];
		}
	}

	return (rv);
};

VError.findCauseByName = function (err, name)
{
	var cause;

	mod_assertplus.ok(mod_isError(err), 'err must be an Error');
	mod_assertplus.string(name, 'name');
	mod_assertplus.ok(name.length > 0, 'name cannot be empty');

	for (cause = err; cause !== null; cause = VError.cause(cause)) {
		mod_assertplus.ok(mod_isError(cause));
		if (cause.name == name) {
			return (cause);
		}
	}

	return (null);
};

VError.hasCauseWithName = function (err, name)
{
	return (VError.findCauseByName(err, name) !== null);
};

VError.fullStack = function (err)
{
	mod_assertplus.ok(mod_isError(err), 'err must be an Error');

	var cause = VError.cause(err);

	if (cause) {
		return (err.stack + '\ncaused by: ' + VError.fullStack(cause));
	}

	return (err.stack);
};

VError.errorFromList = function (errors)
{
	mod_assertplus.arrayOfObject(errors, 'errors');

	if (errors.length === 0) {
		return (null);
	}

	errors.forEach(function (e) {
		mod_assertplus.ok(mod_isError(e));
	});

	if (errors.length == 1) {
		return (errors[0]);
	}

	return (new MultiError(errors));
};

VError.errorForEach = function (err, func)
{
	mod_assertplus.ok(mod_isError(err), 'err must be an Error');
	mod_assertplus.func(func, 'func');

	if (err instanceof MultiError) {
		err.errors().forEach(function iterError(e) { func(e); });
	} else {
		func(err);
	}
};


/*
 * SError is like VError, but stricter about types.  You cannot pass "null" or
 * "undefined" as string arguments to the formatter.
 */
function SError()
{
	var args, obj, parsed, options;

	args = Array.prototype.slice.call(arguments, 0);
	if (!(this instanceof SError)) {
		obj = Object.create(SError.prototype);
		SError.apply(obj, arguments);
		return (obj);
	}

	parsed = parseConstructorArguments({
	    'argv': args,
	    'strict': true
	});

	options = parsed.options;
	VError.call(this, options, '%s', parsed.shortmessage);

	return (this);
}

/*
 * We don't bother setting SError.prototype.name because once constructed,
 * SErrors are just like VErrors.
 */
mod_util.inherits(SError, VError);


/*
 * Represents a collection of errors for the purpose of consumers that generally
 * only deal with one error.  Callers can extract the individual errors
 * contained in this object, but may also just treat it as a normal single
 * error, in which case a summary message will be printed.
 */
function MultiError(errors)
{
	mod_assertplus.array(errors, 'list of errors');
	mod_assertplus.ok(errors.length > 0, 'must be at least one error');
	this.ase_errors = errors;

	VError.call(this, {
	    'cause': errors[0]
	}, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');
}

mod_util.inherits(MultiError, VError);
MultiError.prototype.name = 'MultiError';

MultiError.prototype.errors = function me_errors()
{
	return (this.ase_errors.slice(0));
};


/*
 * See README.md for reference details.
 */
function WError()
{
	var args, obj, parsed, options;

	args = Array.prototype.slice.call(arguments, 0);
	if (!(this instanceof WError)) {
		obj = Object.create(WError.prototype);
		WError.apply(obj, args);
		return (obj);
	}

	parsed = parseConstructorArguments({
	    'argv': args,
	    'strict': false
	});

	options = parsed.options;
	options['skipCauseMessage'] = true;
	VError.call(this, options, '%s', parsed.shortmessage);

	return (this);
}

mod_util.inherits(WError, VError);
WError.prototype.name = 'WError';

WError.prototype.toString = function we_toString()
{
	var str = (this.hasOwnProperty('name') && this.name ||
		this.constructor.name || this.constructor.prototype.name);
	if (this.message)
		str += ': ' + this.message;
	if (this.jse_cause && this.jse_cause.message)
		str += '; caused by ' + this.jse_cause.toString();

	return (str);
};

/*
 * For purely historical reasons, WError's cause() function allows you to set
 * the cause.
 */
WError.prototype.cause = function we_cause(c)
{
	if (mod_isError(c))
		this.jse_cause = c;

	return (this.jse_cause);
};


/***/ })

};
;