nova-ui/syncEvents.cjs

64403 lines
2.1 MiB

#!/usr/bin/env node
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 45);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) {
'use strict';
// Utils
function assert (val, msg) {
if (!val) throw new Error(msg || 'Assertion failed');
}
// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits (ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
// BN
function BN (number, base, endian) {
if (BN.isBN(number)) {
return number;
}
this.negative = 0;
this.words = null;
this.length = 0;
// Reduction context
this.red = null;
if (number !== null) {
if (base === 'le' || base === 'be') {
endian = base;
base = 10;
}
this._init(number || 0, base || 10, endian || 'be');
}
}
if (typeof module === 'object') {
module.exports = BN;
} else {
exports.BN = BN;
}
BN.BN = BN;
BN.wordSize = 26;
var Buffer;
try {
if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
Buffer = window.Buffer;
} else {
Buffer = __webpack_require__(24).Buffer;
}
} catch (e) {
}
BN.isBN = function isBN (num) {
if (num instanceof BN) {
return true;
}
return num !== null && typeof num === 'object' &&
num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
};
BN.max = function max (left, right) {
if (left.cmp(right) > 0) return left;
return right;
};
BN.min = function min (left, right) {
if (left.cmp(right) < 0) return left;
return right;
};
BN.prototype._init = function init (number, base, endian) {
if (typeof number === 'number') {
return this._initNumber(number, base, endian);
}
if (typeof number === 'object') {
return this._initArray(number, base, endian);
}
if (base === 'hex') {
base = 16;
}
assert(base === (base | 0) && base >= 2 && base <= 36);
number = number.toString().replace(/\s+/g, '');
var start = 0;
if (number[0] === '-') {
start++;
this.negative = 1;
}
if (start < number.length) {
if (base === 16) {
this._parseHex(number, start, endian);
} else {
this._parseBase(number, base, start);
if (endian === 'le') {
this._initArray(this.toArray(), base, endian);
}
}
}
};
BN.prototype._initNumber = function _initNumber (number, base, endian) {
if (number < 0) {
this.negative = 1;
number = -number;
}
if (number < 0x4000000) {
this.words = [number & 0x3ffffff];
this.length = 1;
} else if (number < 0x10000000000000) {
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff
];
this.length = 2;
} else {
assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff,
1
];
this.length = 3;
}
if (endian !== 'le') return;
// Reverse the bytes
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initArray = function _initArray (number, base, endian) {
// Perhaps a Uint8Array
assert(typeof number.length === 'number');
if (number.length <= 0) {
this.words = [0];
this.length = 1;
return this;
}
this.length = Math.ceil(number.length / 3);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
this.words[i] = 0;
}
var j, w;
var off = 0;
if (endian === 'be') {
for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
} else if (endian === 'le') {
for (i = 0, j = 0; i < number.length; i += 3) {
w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
}
return this._strip();
};
function parseHex4Bits (string, index) {
var c = string.charCodeAt(index);
// '0' - '9'
if (c >= 48 && c <= 57) {
return c - 48;
// 'A' - 'F'
} else if (c >= 65 && c <= 70) {
return c - 55;
// 'a' - 'f'
} else if (c >= 97 && c <= 102) {
return c - 87;
} else {
assert(false, 'Invalid character in ' + string);
}
}
function parseHexByte (string, lowerBound, index) {
var r = parseHex4Bits(string, index);
if (index - 1 >= lowerBound) {
r |= parseHex4Bits(string, index - 1) << 4;
}
return r;
}
BN.prototype._parseHex = function _parseHex (number, start, endian) {
// Create possibly bigger array to ensure that it fits the number
this.length = Math.ceil((number.length - start) / 6);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
this.words[i] = 0;
}
// 24-bits chunks
var off = 0;
var j = 0;
var w;
if (endian === 'be') {
for (i = number.length - 1; i >= start; i -= 2) {
w = parseHexByte(number, start, i) << off;
this.words[j] |= w & 0x3ffffff;
if (off >= 18) {
off -= 18;
j += 1;
this.words[j] |= w >>> 26;
} else {
off += 8;
}
}
} else {
var parseLength = number.length - start;
for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
w = parseHexByte(number, start, i) << off;
this.words[j] |= w & 0x3ffffff;
if (off >= 18) {
off -= 18;
j += 1;
this.words[j] |= w >>> 26;
} else {
off += 8;
}
}
}
this._strip();
};
function parseBase (str, start, end, mul) {
var r = 0;
var b = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r *= mul;
// 'a'
if (c >= 49) {
b = c - 49 + 0xa;
// 'A'
} else if (c >= 17) {
b = c - 17 + 0xa;
// '0' - '9'
} else {
b = c;
}
assert(c >= 0 && b < mul, 'Invalid character');
r += b;
}
return r;
}
BN.prototype._parseBase = function _parseBase (number, base, start) {
// Initialize as zero
this.words = [0];
this.length = 1;
// Find length of limb in base
for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
limbLen++;
}
limbLen--;
limbPow = (limbPow / base) | 0;
var total = number.length - start;
var mod = total % limbLen;
var end = Math.min(total, total - mod) + start;
var word = 0;
for (var i = start; i < end; i += limbLen) {
word = parseBase(number, i, i + limbLen, base);
this.imuln(limbPow);
if (this.words[0] + word < 0x4000000) {
this.words[0] += word;
} else {
this._iaddn(word);
}
}
if (mod !== 0) {
var pow = 1;
word = parseBase(number, i, number.length, base);
for (i = 0; i < mod; i++) {
pow *= base;
}
this.imuln(pow);
if (this.words[0] + word < 0x4000000) {
this.words[0] += word;
} else {
this._iaddn(word);
}
}
this._strip();
};
BN.prototype.copy = function copy (dest) {
dest.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
dest.words[i] = this.words[i];
}
dest.length = this.length;
dest.negative = this.negative;
dest.red = this.red;
};
function move (dest, src) {
dest.words = src.words;
dest.length = src.length;
dest.negative = src.negative;
dest.red = src.red;
}
BN.prototype._move = function _move (dest) {
move(dest, this);
};
BN.prototype.clone = function clone () {
var r = new BN(null);
this.copy(r);
return r;
};
BN.prototype._expand = function _expand (size) {
while (this.length < size) {
this.words[this.length++] = 0;
}
return this;
};
// Remove leading `0` from `this`
BN.prototype._strip = function strip () {
while (this.length > 1 && this.words[this.length - 1] === 0) {
this.length--;
}
return this._normSign();
};
BN.prototype._normSign = function _normSign () {
// -0 = 0
if (this.length === 1 && this.words[0] === 0) {
this.negative = 0;
}
return this;
};
// Check Symbol.for because not everywhere where Symbol defined
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {
try {
BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;
} catch (e) {
BN.prototype.inspect = inspect;
}
} else {
BN.prototype.inspect = inspect;
}
function inspect () {
return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
}
/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/
var zeros = [
'',
'0',
'00',
'000',
'0000',
'00000',
'000000',
'0000000',
'00000000',
'000000000',
'0000000000',
'00000000000',
'000000000000',
'0000000000000',
'00000000000000',
'000000000000000',
'0000000000000000',
'00000000000000000',
'000000000000000000',
'0000000000000000000',
'00000000000000000000',
'000000000000000000000',
'0000000000000000000000',
'00000000000000000000000',
'000000000000000000000000',
'0000000000000000000000000'
];
var groupSizes = [
0, 0,
25, 16, 12, 11, 10, 9, 8,
8, 7, 7, 7, 7, 6, 6,
6, 6, 6, 6, 6, 5, 5,
5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5
];
var groupBases = [
0, 0,
33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
];
BN.prototype.toString = function toString (base, padding) {
base = base || 10;
padding = padding | 0 || 1;
var out;
if (base === 16 || base === 'hex') {
out = '';
var off = 0;
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = this.words[i];
var word = (((w << off) | carry) & 0xffffff).toString(16);
carry = (w >>> (24 - off)) & 0xffffff;
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
if (carry !== 0 || i !== this.length - 1) {
out = zeros[6 - word.length] + word + out;
} else {
out = word + out;
}
}
if (carry !== 0) {
out = carry.toString(16) + out;
}
while (out.length % padding !== 0) {
out = '0' + out;
}
if (this.negative !== 0) {
out = '-' + out;
}
return out;
}
if (base === (base | 0) && base >= 2 && base <= 36) {
// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize = groupSizes[base];
// var groupBase = Math.pow(base, groupSize);
var groupBase = groupBases[base];
out = '';
var c = this.clone();
c.negative = 0;
while (!c.isZero()) {
var r = c.modrn(groupBase).toString(base);
c = c.idivn(groupBase);
if (!c.isZero()) {
out = zeros[groupSize - r.length] + r + out;
} else {
out = r + out;
}
}
if (this.isZero()) {
out = '0' + out;
}
while (out.length % padding !== 0) {
out = '0' + out;
}
if (this.negative !== 0) {
out = '-' + out;
}
return out;
}
assert(false, 'Base should be between 2 and 36');
};
BN.prototype.toNumber = function toNumber () {
var ret = this.words[0];
if (this.length === 2) {
ret += this.words[1] * 0x4000000;
} else if (this.length === 3 && this.words[2] === 0x01) {
// NOTE: at this stage it is known that the top bit is set
ret += 0x10000000000000 + (this.words[1] * 0x4000000);
} else if (this.length > 2) {
assert(false, 'Number can only safely store up to 53 bits');
}
return (this.negative !== 0) ? -ret : ret;
};
BN.prototype.toJSON = function toJSON () {
return this.toString(16, 2);
};
if (Buffer) {
BN.prototype.toBuffer = function toBuffer (endian, length) {
return this.toArrayLike(Buffer, endian, length);
};
}
BN.prototype.toArray = function toArray (endian, length) {
return this.toArrayLike(Array, endian, length);
};
var allocate = function allocate (ArrayType, size) {
if (ArrayType.allocUnsafe) {
return ArrayType.allocUnsafe(size);
}
return new ArrayType(size);
};
BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
this._strip();
var byteLength = this.byteLength();
var reqLength = length || Math.max(1, byteLength);
assert(byteLength <= reqLength, 'byte array longer than desired length');
assert(reqLength > 0, 'Requested array length <= 0');
var res = allocate(ArrayType, reqLength);
var postfix = endian === 'le' ? 'LE' : 'BE';
this['_toArrayLike' + postfix](res, byteLength);
return res;
};
BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {
var position = 0;
var carry = 0;
for (var i = 0, shift = 0; i < this.length; i++) {
var word = (this.words[i] << shift) | carry;
res[position++] = word & 0xff;
if (position < res.length) {
res[position++] = (word >> 8) & 0xff;
}
if (position < res.length) {
res[position++] = (word >> 16) & 0xff;
}
if (shift === 6) {
if (position < res.length) {
res[position++] = (word >> 24) & 0xff;
}
carry = 0;
shift = 0;
} else {
carry = word >>> 24;
shift += 2;
}
}
if (position < res.length) {
res[position++] = carry;
while (position < res.length) {
res[position++] = 0;
}
}
};
BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {
var position = res.length - 1;
var carry = 0;
for (var i = 0, shift = 0; i < this.length; i++) {
var word = (this.words[i] << shift) | carry;
res[position--] = word & 0xff;
if (position >= 0) {
res[position--] = (word >> 8) & 0xff;
}
if (position >= 0) {
res[position--] = (word >> 16) & 0xff;
}
if (shift === 6) {
if (position >= 0) {
res[position--] = (word >> 24) & 0xff;
}
carry = 0;
shift = 0;
} else {
carry = word >>> 24;
shift += 2;
}
}
if (position >= 0) {
res[position--] = carry;
while (position >= 0) {
res[position--] = 0;
}
}
};
if (Math.clz32) {
BN.prototype._countBits = function _countBits (w) {
return 32 - Math.clz32(w);
};
} else {
BN.prototype._countBits = function _countBits (w) {
var t = w;
var r = 0;
if (t >= 0x1000) {
r += 13;
t >>>= 13;
}
if (t >= 0x40) {
r += 7;
t >>>= 7;
}
if (t >= 0x8) {
r += 4;
t >>>= 4;
}
if (t >= 0x02) {
r += 2;
t >>>= 2;
}
return r + t;
};
}
BN.prototype._zeroBits = function _zeroBits (w) {
// Short-cut
if (w === 0) return 26;
var t = w;
var r = 0;
if ((t & 0x1fff) === 0) {
r += 13;
t >>>= 13;
}
if ((t & 0x7f) === 0) {
r += 7;
t >>>= 7;
}
if ((t & 0xf) === 0) {
r += 4;
t >>>= 4;
}
if ((t & 0x3) === 0) {
r += 2;
t >>>= 2;
}
if ((t & 0x1) === 0) {
r++;
}
return r;
};
// Return number of used bits in a BN
BN.prototype.bitLength = function bitLength () {
var w = this.words[this.length - 1];
var hi = this._countBits(w);
return (this.length - 1) * 26 + hi;
};
function toBitArray (num) {
var w = new Array(num.bitLength());
for (var bit = 0; bit < w.length; bit++) {
var off = (bit / 26) | 0;
var wbit = bit % 26;
w[bit] = (num.words[off] >>> wbit) & 0x01;
}
return w;
}
// Number of trailing zero bits
BN.prototype.zeroBits = function zeroBits () {
if (this.isZero()) return 0;
var r = 0;
for (var i = 0; i < this.length; i++) {
var b = this._zeroBits(this.words[i]);
r += b;
if (b !== 26) break;
}
return r;
};
BN.prototype.byteLength = function byteLength () {
return Math.ceil(this.bitLength() / 8);
};
BN.prototype.toTwos = function toTwos (width) {
if (this.negative !== 0) {
return this.abs().inotn(width).iaddn(1);
}
return this.clone();
};
BN.prototype.fromTwos = function fromTwos (width) {
if (this.testn(width - 1)) {
return this.notn(width).iaddn(1).ineg();
}
return this.clone();
};
BN.prototype.isNeg = function isNeg () {
return this.negative !== 0;
};
// Return negative clone of `this`
BN.prototype.neg = function neg () {
return this.clone().ineg();
};
BN.prototype.ineg = function ineg () {
if (!this.isZero()) {
this.negative ^= 1;
}
return this;
};
// Or `num` with `this` in-place
BN.prototype.iuor = function iuor (num) {
while (this.length < num.length) {
this.words[this.length++] = 0;
}
for (var i = 0; i < num.length; i++) {
this.words[i] = this.words[i] | num.words[i];
}
return this._strip();
};
BN.prototype.ior = function ior (num) {
assert((this.negative | num.negative) === 0);
return this.iuor(num);
};
// Or `num` with `this`
BN.prototype.or = function or (num) {
if (this.length > num.length) return this.clone().ior(num);
return num.clone().ior(this);
};
BN.prototype.uor = function uor (num) {
if (this.length > num.length) return this.clone().iuor(num);
return num.clone().iuor(this);
};
// And `num` with `this` in-place
BN.prototype.iuand = function iuand (num) {
// b = min-length(num, this)
var b;
if (this.length > num.length) {
b = num;
} else {
b = this;
}
for (var i = 0; i < b.length; i++) {
this.words[i] = this.words[i] & num.words[i];
}
this.length = b.length;
return this._strip();
};
BN.prototype.iand = function iand (num) {
assert((this.negative | num.negative) === 0);
return this.iuand(num);
};
// And `num` with `this`
BN.prototype.and = function and (num) {
if (this.length > num.length) return this.clone().iand(num);
return num.clone().iand(this);
};
BN.prototype.uand = function uand (num) {
if (this.length > num.length) return this.clone().iuand(num);
return num.clone().iuand(this);
};
// Xor `num` with `this` in-place
BN.prototype.iuxor = function iuxor (num) {
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
for (var i = 0; i < b.length; i++) {
this.words[i] = a.words[i] ^ b.words[i];
}
if (this !== a) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
this.length = a.length;
return this._strip();
};
BN.prototype.ixor = function ixor (num) {
assert((this.negative | num.negative) === 0);
return this.iuxor(num);
};
// Xor `num` with `this`
BN.prototype.xor = function xor (num) {
if (this.length > num.length) return this.clone().ixor(num);
return num.clone().ixor(this);
};
BN.prototype.uxor = function uxor (num) {
if (this.length > num.length) return this.clone().iuxor(num);
return num.clone().iuxor(this);
};
// Not ``this`` with ``width`` bitwidth
BN.prototype.inotn = function inotn (width) {
assert(typeof width === 'number' && width >= 0);
var bytesNeeded = Math.ceil(width / 26) | 0;
var bitsLeft = width % 26;
// Extend the buffer with leading zeroes
this._expand(bytesNeeded);
if (bitsLeft > 0) {
bytesNeeded--;
}
// Handle complete words
for (var i = 0; i < bytesNeeded; i++) {
this.words[i] = ~this.words[i] & 0x3ffffff;
}
// Handle the residue
if (bitsLeft > 0) {
this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
}
// And remove leading zeroes
return this._strip();
};
BN.prototype.notn = function notn (width) {
return this.clone().inotn(width);
};
// Set `bit` of `this`
BN.prototype.setn = function setn (bit, val) {
assert(typeof bit === 'number' && bit >= 0);
var off = (bit / 26) | 0;
var wbit = bit % 26;
this._expand(off + 1);
if (val) {
this.words[off] = this.words[off] | (1 << wbit);
} else {
this.words[off] = this.words[off] & ~(1 << wbit);
}
return this._strip();
};
// Add `num` to `this` in-place
BN.prototype.iadd = function iadd (num) {
var r;
// negative + positive
if (this.negative !== 0 && num.negative === 0) {
this.negative = 0;
r = this.isub(num);
this.negative ^= 1;
return this._normSign();
// positive + negative
} else if (this.negative === 0 && num.negative !== 0) {
num.negative = 0;
r = this.isub(num);
num.negative = 1;
return r._normSign();
}
// a.length > b.length
var a, b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
for (; carry !== 0 && i < a.length; i++) {
r = (a.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
this.length = a.length;
if (carry !== 0) {
this.words[this.length] = carry;
this.length++;
// Copy the rest of the words
} else if (a !== this) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
return this;
};
// Add `num` to `this`
BN.prototype.add = function add (num) {
var res;
if (num.negative !== 0 && this.negative === 0) {
num.negative = 0;
res = this.sub(num);
num.negative ^= 1;
return res;
} else if (num.negative === 0 && this.negative !== 0) {
this.negative = 0;
res = num.sub(this);
this.negative = 1;
return res;
}
if (this.length > num.length) return this.clone().iadd(num);
return num.clone().iadd(this);
};
// Subtract `num` from `this` in-place
BN.prototype.isub = function isub (num) {
// this - (-num) = this + num
if (num.negative !== 0) {
num.negative = 0;
var r = this.iadd(num);
num.negative = 1;
return r._normSign();
// -this - num = -(this + num)
} else if (this.negative !== 0) {
this.negative = 0;
this.iadd(num);
this.negative = 1;
return this._normSign();
}
// At this point both numbers are positive
var cmp = this.cmp(num);
// Optimization - zeroify
if (cmp === 0) {
this.negative = 0;
this.length = 1;
this.words[0] = 0;
return this;
}
// a > b
var a, b;
if (cmp > 0) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
for (; carry !== 0 && i < a.length; i++) {
r = (a.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
// Copy rest of the words
if (carry === 0 && i < a.length && a !== this) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
this.length = Math.max(this.length, i);
if (a !== this) {
this.negative = 1;
}
return this._strip();
};
// Subtract `num` from `this`
BN.prototype.sub = function sub (num) {
return this.clone().isub(num);
};
function smallMulTo (self, num, out) {
out.negative = num.negative ^ self.negative;
var len = (self.length + num.length) | 0;
out.length = len;
len = (len - 1) | 0;
// Peel one iteration (compiler can't do it, because of code complexity)
var a = self.words[0] | 0;
var b = num.words[0] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
var carry = (r / 0x4000000) | 0;
out.words[0] = lo;
for (var k = 1; k < len; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = carry >>> 26;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
var i = (k - j) | 0;
a = self.words[i] | 0;
b = num.words[j] | 0;
r = a * b + rword;
ncarry += (r / 0x4000000) | 0;
rword = r & 0x3ffffff;
}
out.words[k] = rword | 0;
carry = ncarry | 0;
}
if (carry !== 0) {
out.words[k] = carry | 0;
} else {
out.length--;
}
return out._strip();
}
// TODO(indutny): it may be reasonable to omit it for users who don't need
// to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
// multiplication (like elliptic secp256k1).
var comb10MulTo = function comb10MulTo (self, num, out) {
var a = self.words;
var b = num.words;
var o = out.words;
var c = 0;
var lo;
var mid;
var hi;
var a0 = a[0] | 0;
var al0 = a0 & 0x1fff;
var ah0 = a0 >>> 13;
var a1 = a[1] | 0;
var al1 = a1 & 0x1fff;
var ah1 = a1 >>> 13;
var a2 = a[2] | 0;
var al2 = a2 & 0x1fff;
var ah2 = a2 >>> 13;
var a3 = a[3] | 0;
var al3 = a3 & 0x1fff;
var ah3 = a3 >>> 13;
var a4 = a[4] | 0;
var al4 = a4 & 0x1fff;
var ah4 = a4 >>> 13;
var a5 = a[5] | 0;
var al5 = a5 & 0x1fff;
var ah5 = a5 >>> 13;
var a6 = a[6] | 0;
var al6 = a6 & 0x1fff;
var ah6 = a6 >>> 13;
var a7 = a[7] | 0;
var al7 = a7 & 0x1fff;
var ah7 = a7 >>> 13;
var a8 = a[8] | 0;
var al8 = a8 & 0x1fff;
var ah8 = a8 >>> 13;
var a9 = a[9] | 0;
var al9 = a9 & 0x1fff;
var ah9 = a9 >>> 13;
var b0 = b[0] | 0;
var bl0 = b0 & 0x1fff;
var bh0 = b0 >>> 13;
var b1 = b[1] | 0;
var bl1 = b1 & 0x1fff;
var bh1 = b1 >>> 13;
var b2 = b[2] | 0;
var bl2 = b2 & 0x1fff;
var bh2 = b2 >>> 13;
var b3 = b[3] | 0;
var bl3 = b3 & 0x1fff;
var bh3 = b3 >>> 13;
var b4 = b[4] | 0;
var bl4 = b4 & 0x1fff;
var bh4 = b4 >>> 13;
var b5 = b[5] | 0;
var bl5 = b5 & 0x1fff;
var bh5 = b5 >>> 13;
var b6 = b[6] | 0;
var bl6 = b6 & 0x1fff;
var bh6 = b6 >>> 13;
var b7 = b[7] | 0;
var bl7 = b7 & 0x1fff;
var bh7 = b7 >>> 13;
var b8 = b[8] | 0;
var bl8 = b8 & 0x1fff;
var bh8 = b8 >>> 13;
var b9 = b[9] | 0;
var bl9 = b9 & 0x1fff;
var bh9 = b9 >>> 13;
out.negative = self.negative ^ num.negative;
out.length = 19;
/* k = 0 */
lo = Math.imul(al0, bl0);
mid = Math.imul(al0, bh0);
mid = (mid + Math.imul(ah0, bl0)) | 0;
hi = Math.imul(ah0, bh0);
var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
w0 &= 0x3ffffff;
/* k = 1 */
lo = Math.imul(al1, bl0);
mid = Math.imul(al1, bh0);
mid = (mid + Math.imul(ah1, bl0)) | 0;
hi = Math.imul(ah1, bh0);
lo = (lo + Math.imul(al0, bl1)) | 0;
mid = (mid + Math.imul(al0, bh1)) | 0;
mid = (mid + Math.imul(ah0, bl1)) | 0;
hi = (hi + Math.imul(ah0, bh1)) | 0;
var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
w1 &= 0x3ffffff;
/* k = 2 */
lo = Math.imul(al2, bl0);
mid = Math.imul(al2, bh0);
mid = (mid + Math.imul(ah2, bl0)) | 0;
hi = Math.imul(ah2, bh0);
lo = (lo + Math.imul(al1, bl1)) | 0;
mid = (mid + Math.imul(al1, bh1)) | 0;
mid = (mid + Math.imul(ah1, bl1)) | 0;
hi = (hi + Math.imul(ah1, bh1)) | 0;
lo = (lo + Math.imul(al0, bl2)) | 0;
mid = (mid + Math.imul(al0, bh2)) | 0;
mid = (mid + Math.imul(ah0, bl2)) | 0;
hi = (hi + Math.imul(ah0, bh2)) | 0;
var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
w2 &= 0x3ffffff;
/* k = 3 */
lo = Math.imul(al3, bl0);
mid = Math.imul(al3, bh0);
mid = (mid + Math.imul(ah3, bl0)) | 0;
hi = Math.imul(ah3, bh0);
lo = (lo + Math.imul(al2, bl1)) | 0;
mid = (mid + Math.imul(al2, bh1)) | 0;
mid = (mid + Math.imul(ah2, bl1)) | 0;
hi = (hi + Math.imul(ah2, bh1)) | 0;
lo = (lo + Math.imul(al1, bl2)) | 0;
mid = (mid + Math.imul(al1, bh2)) | 0;
mid = (mid + Math.imul(ah1, bl2)) | 0;
hi = (hi + Math.imul(ah1, bh2)) | 0;
lo = (lo + Math.imul(al0, bl3)) | 0;
mid = (mid + Math.imul(al0, bh3)) | 0;
mid = (mid + Math.imul(ah0, bl3)) | 0;
hi = (hi + Math.imul(ah0, bh3)) | 0;
var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
w3 &= 0x3ffffff;
/* k = 4 */
lo = Math.imul(al4, bl0);
mid = Math.imul(al4, bh0);
mid = (mid + Math.imul(ah4, bl0)) | 0;
hi = Math.imul(ah4, bh0);
lo = (lo + Math.imul(al3, bl1)) | 0;
mid = (mid + Math.imul(al3, bh1)) | 0;
mid = (mid + Math.imul(ah3, bl1)) | 0;
hi = (hi + Math.imul(ah3, bh1)) | 0;
lo = (lo + Math.imul(al2, bl2)) | 0;
mid = (mid + Math.imul(al2, bh2)) | 0;
mid = (mid + Math.imul(ah2, bl2)) | 0;
hi = (hi + Math.imul(ah2, bh2)) | 0;
lo = (lo + Math.imul(al1, bl3)) | 0;
mid = (mid + Math.imul(al1, bh3)) | 0;
mid = (mid + Math.imul(ah1, bl3)) | 0;
hi = (hi + Math.imul(ah1, bh3)) | 0;
lo = (lo + Math.imul(al0, bl4)) | 0;
mid = (mid + Math.imul(al0, bh4)) | 0;
mid = (mid + Math.imul(ah0, bl4)) | 0;
hi = (hi + Math.imul(ah0, bh4)) | 0;
var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
w4 &= 0x3ffffff;
/* k = 5 */
lo = Math.imul(al5, bl0);
mid = Math.imul(al5, bh0);
mid = (mid + Math.imul(ah5, bl0)) | 0;
hi = Math.imul(ah5, bh0);
lo = (lo + Math.imul(al4, bl1)) | 0;
mid = (mid + Math.imul(al4, bh1)) | 0;
mid = (mid + Math.imul(ah4, bl1)) | 0;
hi = (hi + Math.imul(ah4, bh1)) | 0;
lo = (lo + Math.imul(al3, bl2)) | 0;
mid = (mid + Math.imul(al3, bh2)) | 0;
mid = (mid + Math.imul(ah3, bl2)) | 0;
hi = (hi + Math.imul(ah3, bh2)) | 0;
lo = (lo + Math.imul(al2, bl3)) | 0;
mid = (mid + Math.imul(al2, bh3)) | 0;
mid = (mid + Math.imul(ah2, bl3)) | 0;
hi = (hi + Math.imul(ah2, bh3)) | 0;
lo = (lo + Math.imul(al1, bl4)) | 0;
mid = (mid + Math.imul(al1, bh4)) | 0;
mid = (mid + Math.imul(ah1, bl4)) | 0;
hi = (hi + Math.imul(ah1, bh4)) | 0;
lo = (lo + Math.imul(al0, bl5)) | 0;
mid = (mid + Math.imul(al0, bh5)) | 0;
mid = (mid + Math.imul(ah0, bl5)) | 0;
hi = (hi + Math.imul(ah0, bh5)) | 0;
var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
w5 &= 0x3ffffff;
/* k = 6 */
lo = Math.imul(al6, bl0);
mid = Math.imul(al6, bh0);
mid = (mid + Math.imul(ah6, bl0)) | 0;
hi = Math.imul(ah6, bh0);
lo = (lo + Math.imul(al5, bl1)) | 0;
mid = (mid + Math.imul(al5, bh1)) | 0;
mid = (mid + Math.imul(ah5, bl1)) | 0;
hi = (hi + Math.imul(ah5, bh1)) | 0;
lo = (lo + Math.imul(al4, bl2)) | 0;
mid = (mid + Math.imul(al4, bh2)) | 0;
mid = (mid + Math.imul(ah4, bl2)) | 0;
hi = (hi + Math.imul(ah4, bh2)) | 0;
lo = (lo + Math.imul(al3, bl3)) | 0;
mid = (mid + Math.imul(al3, bh3)) | 0;
mid = (mid + Math.imul(ah3, bl3)) | 0;
hi = (hi + Math.imul(ah3, bh3)) | 0;
lo = (lo + Math.imul(al2, bl4)) | 0;
mid = (mid + Math.imul(al2, bh4)) | 0;
mid = (mid + Math.imul(ah2, bl4)) | 0;
hi = (hi + Math.imul(ah2, bh4)) | 0;
lo = (lo + Math.imul(al1, bl5)) | 0;
mid = (mid + Math.imul(al1, bh5)) | 0;
mid = (mid + Math.imul(ah1, bl5)) | 0;
hi = (hi + Math.imul(ah1, bh5)) | 0;
lo = (lo + Math.imul(al0, bl6)) | 0;
mid = (mid + Math.imul(al0, bh6)) | 0;
mid = (mid + Math.imul(ah0, bl6)) | 0;
hi = (hi + Math.imul(ah0, bh6)) | 0;
var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
w6 &= 0x3ffffff;
/* k = 7 */
lo = Math.imul(al7, bl0);
mid = Math.imul(al7, bh0);
mid = (mid + Math.imul(ah7, bl0)) | 0;
hi = Math.imul(ah7, bh0);
lo = (lo + Math.imul(al6, bl1)) | 0;
mid = (mid + Math.imul(al6, bh1)) | 0;
mid = (mid + Math.imul(ah6, bl1)) | 0;
hi = (hi + Math.imul(ah6, bh1)) | 0;
lo = (lo + Math.imul(al5, bl2)) | 0;
mid = (mid + Math.imul(al5, bh2)) | 0;
mid = (mid + Math.imul(ah5, bl2)) | 0;
hi = (hi + Math.imul(ah5, bh2)) | 0;
lo = (lo + Math.imul(al4, bl3)) | 0;
mid = (mid + Math.imul(al4, bh3)) | 0;
mid = (mid + Math.imul(ah4, bl3)) | 0;
hi = (hi + Math.imul(ah4, bh3)) | 0;
lo = (lo + Math.imul(al3, bl4)) | 0;
mid = (mid + Math.imul(al3, bh4)) | 0;
mid = (mid + Math.imul(ah3, bl4)) | 0;
hi = (hi + Math.imul(ah3, bh4)) | 0;
lo = (lo + Math.imul(al2, bl5)) | 0;
mid = (mid + Math.imul(al2, bh5)) | 0;
mid = (mid + Math.imul(ah2, bl5)) | 0;
hi = (hi + Math.imul(ah2, bh5)) | 0;
lo = (lo + Math.imul(al1, bl6)) | 0;
mid = (mid + Math.imul(al1, bh6)) | 0;
mid = (mid + Math.imul(ah1, bl6)) | 0;
hi = (hi + Math.imul(ah1, bh6)) | 0;
lo = (lo + Math.imul(al0, bl7)) | 0;
mid = (mid + Math.imul(al0, bh7)) | 0;
mid = (mid + Math.imul(ah0, bl7)) | 0;
hi = (hi + Math.imul(ah0, bh7)) | 0;
var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
w7 &= 0x3ffffff;
/* k = 8 */
lo = Math.imul(al8, bl0);
mid = Math.imul(al8, bh0);
mid = (mid + Math.imul(ah8, bl0)) | 0;
hi = Math.imul(ah8, bh0);
lo = (lo + Math.imul(al7, bl1)) | 0;
mid = (mid + Math.imul(al7, bh1)) | 0;
mid = (mid + Math.imul(ah7, bl1)) | 0;
hi = (hi + Math.imul(ah7, bh1)) | 0;
lo = (lo + Math.imul(al6, bl2)) | 0;
mid = (mid + Math.imul(al6, bh2)) | 0;
mid = (mid + Math.imul(ah6, bl2)) | 0;
hi = (hi + Math.imul(ah6, bh2)) | 0;
lo = (lo + Math.imul(al5, bl3)) | 0;
mid = (mid + Math.imul(al5, bh3)) | 0;
mid = (mid + Math.imul(ah5, bl3)) | 0;
hi = (hi + Math.imul(ah5, bh3)) | 0;
lo = (lo + Math.imul(al4, bl4)) | 0;
mid = (mid + Math.imul(al4, bh4)) | 0;
mid = (mid + Math.imul(ah4, bl4)) | 0;
hi = (hi + Math.imul(ah4, bh4)) | 0;
lo = (lo + Math.imul(al3, bl5)) | 0;
mid = (mid + Math.imul(al3, bh5)) | 0;
mid = (mid + Math.imul(ah3, bl5)) | 0;
hi = (hi + Math.imul(ah3, bh5)) | 0;
lo = (lo + Math.imul(al2, bl6)) | 0;
mid = (mid + Math.imul(al2, bh6)) | 0;
mid = (mid + Math.imul(ah2, bl6)) | 0;
hi = (hi + Math.imul(ah2, bh6)) | 0;
lo = (lo + Math.imul(al1, bl7)) | 0;
mid = (mid + Math.imul(al1, bh7)) | 0;
mid = (mid + Math.imul(ah1, bl7)) | 0;
hi = (hi + Math.imul(ah1, bh7)) | 0;
lo = (lo + Math.imul(al0, bl8)) | 0;
mid = (mid + Math.imul(al0, bh8)) | 0;
mid = (mid + Math.imul(ah0, bl8)) | 0;
hi = (hi + Math.imul(ah0, bh8)) | 0;
var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
w8 &= 0x3ffffff;
/* k = 9 */
lo = Math.imul(al9, bl0);
mid = Math.imul(al9, bh0);
mid = (mid + Math.imul(ah9, bl0)) | 0;
hi = Math.imul(ah9, bh0);
lo = (lo + Math.imul(al8, bl1)) | 0;
mid = (mid + Math.imul(al8, bh1)) | 0;
mid = (mid + Math.imul(ah8, bl1)) | 0;
hi = (hi + Math.imul(ah8, bh1)) | 0;
lo = (lo + Math.imul(al7, bl2)) | 0;
mid = (mid + Math.imul(al7, bh2)) | 0;
mid = (mid + Math.imul(ah7, bl2)) | 0;
hi = (hi + Math.imul(ah7, bh2)) | 0;
lo = (lo + Math.imul(al6, bl3)) | 0;
mid = (mid + Math.imul(al6, bh3)) | 0;
mid = (mid + Math.imul(ah6, bl3)) | 0;
hi = (hi + Math.imul(ah6, bh3)) | 0;
lo = (lo + Math.imul(al5, bl4)) | 0;
mid = (mid + Math.imul(al5, bh4)) | 0;
mid = (mid + Math.imul(ah5, bl4)) | 0;
hi = (hi + Math.imul(ah5, bh4)) | 0;
lo = (lo + Math.imul(al4, bl5)) | 0;
mid = (mid + Math.imul(al4, bh5)) | 0;
mid = (mid + Math.imul(ah4, bl5)) | 0;
hi = (hi + Math.imul(ah4, bh5)) | 0;
lo = (lo + Math.imul(al3, bl6)) | 0;
mid = (mid + Math.imul(al3, bh6)) | 0;
mid = (mid + Math.imul(ah3, bl6)) | 0;
hi = (hi + Math.imul(ah3, bh6)) | 0;
lo = (lo + Math.imul(al2, bl7)) | 0;
mid = (mid + Math.imul(al2, bh7)) | 0;
mid = (mid + Math.imul(ah2, bl7)) | 0;
hi = (hi + Math.imul(ah2, bh7)) | 0;
lo = (lo + Math.imul(al1, bl8)) | 0;
mid = (mid + Math.imul(al1, bh8)) | 0;
mid = (mid + Math.imul(ah1, bl8)) | 0;
hi = (hi + Math.imul(ah1, bh8)) | 0;
lo = (lo + Math.imul(al0, bl9)) | 0;
mid = (mid + Math.imul(al0, bh9)) | 0;
mid = (mid + Math.imul(ah0, bl9)) | 0;
hi = (hi + Math.imul(ah0, bh9)) | 0;
var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
w9 &= 0x3ffffff;
/* k = 10 */
lo = Math.imul(al9, bl1);
mid = Math.imul(al9, bh1);
mid = (mid + Math.imul(ah9, bl1)) | 0;
hi = Math.imul(ah9, bh1);
lo = (lo + Math.imul(al8, bl2)) | 0;
mid = (mid + Math.imul(al8, bh2)) | 0;
mid = (mid + Math.imul(ah8, bl2)) | 0;
hi = (hi + Math.imul(ah8, bh2)) | 0;
lo = (lo + Math.imul(al7, bl3)) | 0;
mid = (mid + Math.imul(al7, bh3)) | 0;
mid = (mid + Math.imul(ah7, bl3)) | 0;
hi = (hi + Math.imul(ah7, bh3)) | 0;
lo = (lo + Math.imul(al6, bl4)) | 0;
mid = (mid + Math.imul(al6, bh4)) | 0;
mid = (mid + Math.imul(ah6, bl4)) | 0;
hi = (hi + Math.imul(ah6, bh4)) | 0;
lo = (lo + Math.imul(al5, bl5)) | 0;
mid = (mid + Math.imul(al5, bh5)) | 0;
mid = (mid + Math.imul(ah5, bl5)) | 0;
hi = (hi + Math.imul(ah5, bh5)) | 0;
lo = (lo + Math.imul(al4, bl6)) | 0;
mid = (mid + Math.imul(al4, bh6)) | 0;
mid = (mid + Math.imul(ah4, bl6)) | 0;
hi = (hi + Math.imul(ah4, bh6)) | 0;
lo = (lo + Math.imul(al3, bl7)) | 0;
mid = (mid + Math.imul(al3, bh7)) | 0;
mid = (mid + Math.imul(ah3, bl7)) | 0;
hi = (hi + Math.imul(ah3, bh7)) | 0;
lo = (lo + Math.imul(al2, bl8)) | 0;
mid = (mid + Math.imul(al2, bh8)) | 0;
mid = (mid + Math.imul(ah2, bl8)) | 0;
hi = (hi + Math.imul(ah2, bh8)) | 0;
lo = (lo + Math.imul(al1, bl9)) | 0;
mid = (mid + Math.imul(al1, bh9)) | 0;
mid = (mid + Math.imul(ah1, bl9)) | 0;
hi = (hi + Math.imul(ah1, bh9)) | 0;
var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
w10 &= 0x3ffffff;
/* k = 11 */
lo = Math.imul(al9, bl2);
mid = Math.imul(al9, bh2);
mid = (mid + Math.imul(ah9, bl2)) | 0;
hi = Math.imul(ah9, bh2);
lo = (lo + Math.imul(al8, bl3)) | 0;
mid = (mid + Math.imul(al8, bh3)) | 0;
mid = (mid + Math.imul(ah8, bl3)) | 0;
hi = (hi + Math.imul(ah8, bh3)) | 0;
lo = (lo + Math.imul(al7, bl4)) | 0;
mid = (mid + Math.imul(al7, bh4)) | 0;
mid = (mid + Math.imul(ah7, bl4)) | 0;
hi = (hi + Math.imul(ah7, bh4)) | 0;
lo = (lo + Math.imul(al6, bl5)) | 0;
mid = (mid + Math.imul(al6, bh5)) | 0;
mid = (mid + Math.imul(ah6, bl5)) | 0;
hi = (hi + Math.imul(ah6, bh5)) | 0;
lo = (lo + Math.imul(al5, bl6)) | 0;
mid = (mid + Math.imul(al5, bh6)) | 0;
mid = (mid + Math.imul(ah5, bl6)) | 0;
hi = (hi + Math.imul(ah5, bh6)) | 0;
lo = (lo + Math.imul(al4, bl7)) | 0;
mid = (mid + Math.imul(al4, bh7)) | 0;
mid = (mid + Math.imul(ah4, bl7)) | 0;
hi = (hi + Math.imul(ah4, bh7)) | 0;
lo = (lo + Math.imul(al3, bl8)) | 0;
mid = (mid + Math.imul(al3, bh8)) | 0;
mid = (mid + Math.imul(ah3, bl8)) | 0;
hi = (hi + Math.imul(ah3, bh8)) | 0;
lo = (lo + Math.imul(al2, bl9)) | 0;
mid = (mid + Math.imul(al2, bh9)) | 0;
mid = (mid + Math.imul(ah2, bl9)) | 0;
hi = (hi + Math.imul(ah2, bh9)) | 0;
var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
w11 &= 0x3ffffff;
/* k = 12 */
lo = Math.imul(al9, bl3);
mid = Math.imul(al9, bh3);
mid = (mid + Math.imul(ah9, bl3)) | 0;
hi = Math.imul(ah9, bh3);
lo = (lo + Math.imul(al8, bl4)) | 0;
mid = (mid + Math.imul(al8, bh4)) | 0;
mid = (mid + Math.imul(ah8, bl4)) | 0;
hi = (hi + Math.imul(ah8, bh4)) | 0;
lo = (lo + Math.imul(al7, bl5)) | 0;
mid = (mid + Math.imul(al7, bh5)) | 0;
mid = (mid + Math.imul(ah7, bl5)) | 0;
hi = (hi + Math.imul(ah7, bh5)) | 0;
lo = (lo + Math.imul(al6, bl6)) | 0;
mid = (mid + Math.imul(al6, bh6)) | 0;
mid = (mid + Math.imul(ah6, bl6)) | 0;
hi = (hi + Math.imul(ah6, bh6)) | 0;
lo = (lo + Math.imul(al5, bl7)) | 0;
mid = (mid + Math.imul(al5, bh7)) | 0;
mid = (mid + Math.imul(ah5, bl7)) | 0;
hi = (hi + Math.imul(ah5, bh7)) | 0;
lo = (lo + Math.imul(al4, bl8)) | 0;
mid = (mid + Math.imul(al4, bh8)) | 0;
mid = (mid + Math.imul(ah4, bl8)) | 0;
hi = (hi + Math.imul(ah4, bh8)) | 0;
lo = (lo + Math.imul(al3, bl9)) | 0;
mid = (mid + Math.imul(al3, bh9)) | 0;
mid = (mid + Math.imul(ah3, bl9)) | 0;
hi = (hi + Math.imul(ah3, bh9)) | 0;
var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
w12 &= 0x3ffffff;
/* k = 13 */
lo = Math.imul(al9, bl4);
mid = Math.imul(al9, bh4);
mid = (mid + Math.imul(ah9, bl4)) | 0;
hi = Math.imul(ah9, bh4);
lo = (lo + Math.imul(al8, bl5)) | 0;
mid = (mid + Math.imul(al8, bh5)) | 0;
mid = (mid + Math.imul(ah8, bl5)) | 0;
hi = (hi + Math.imul(ah8, bh5)) | 0;
lo = (lo + Math.imul(al7, bl6)) | 0;
mid = (mid + Math.imul(al7, bh6)) | 0;
mid = (mid + Math.imul(ah7, bl6)) | 0;
hi = (hi + Math.imul(ah7, bh6)) | 0;
lo = (lo + Math.imul(al6, bl7)) | 0;
mid = (mid + Math.imul(al6, bh7)) | 0;
mid = (mid + Math.imul(ah6, bl7)) | 0;
hi = (hi + Math.imul(ah6, bh7)) | 0;
lo = (lo + Math.imul(al5, bl8)) | 0;
mid = (mid + Math.imul(al5, bh8)) | 0;
mid = (mid + Math.imul(ah5, bl8)) | 0;
hi = (hi + Math.imul(ah5, bh8)) | 0;
lo = (lo + Math.imul(al4, bl9)) | 0;
mid = (mid + Math.imul(al4, bh9)) | 0;
mid = (mid + Math.imul(ah4, bl9)) | 0;
hi = (hi + Math.imul(ah4, bh9)) | 0;
var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
w13 &= 0x3ffffff;
/* k = 14 */
lo = Math.imul(al9, bl5);
mid = Math.imul(al9, bh5);
mid = (mid + Math.imul(ah9, bl5)) | 0;
hi = Math.imul(ah9, bh5);
lo = (lo + Math.imul(al8, bl6)) | 0;
mid = (mid + Math.imul(al8, bh6)) | 0;
mid = (mid + Math.imul(ah8, bl6)) | 0;
hi = (hi + Math.imul(ah8, bh6)) | 0;
lo = (lo + Math.imul(al7, bl7)) | 0;
mid = (mid + Math.imul(al7, bh7)) | 0;
mid = (mid + Math.imul(ah7, bl7)) | 0;
hi = (hi + Math.imul(ah7, bh7)) | 0;
lo = (lo + Math.imul(al6, bl8)) | 0;
mid = (mid + Math.imul(al6, bh8)) | 0;
mid = (mid + Math.imul(ah6, bl8)) | 0;
hi = (hi + Math.imul(ah6, bh8)) | 0;
lo = (lo + Math.imul(al5, bl9)) | 0;
mid = (mid + Math.imul(al5, bh9)) | 0;
mid = (mid + Math.imul(ah5, bl9)) | 0;
hi = (hi + Math.imul(ah5, bh9)) | 0;
var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
w14 &= 0x3ffffff;
/* k = 15 */
lo = Math.imul(al9, bl6);
mid = Math.imul(al9, bh6);
mid = (mid + Math.imul(ah9, bl6)) | 0;
hi = Math.imul(ah9, bh6);
lo = (lo + Math.imul(al8, bl7)) | 0;
mid = (mid + Math.imul(al8, bh7)) | 0;
mid = (mid + Math.imul(ah8, bl7)) | 0;
hi = (hi + Math.imul(ah8, bh7)) | 0;
lo = (lo + Math.imul(al7, bl8)) | 0;
mid = (mid + Math.imul(al7, bh8)) | 0;
mid = (mid + Math.imul(ah7, bl8)) | 0;
hi = (hi + Math.imul(ah7, bh8)) | 0;
lo = (lo + Math.imul(al6, bl9)) | 0;
mid = (mid + Math.imul(al6, bh9)) | 0;
mid = (mid + Math.imul(ah6, bl9)) | 0;
hi = (hi + Math.imul(ah6, bh9)) | 0;
var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
w15 &= 0x3ffffff;
/* k = 16 */
lo = Math.imul(al9, bl7);
mid = Math.imul(al9, bh7);
mid = (mid + Math.imul(ah9, bl7)) | 0;
hi = Math.imul(ah9, bh7);
lo = (lo + Math.imul(al8, bl8)) | 0;
mid = (mid + Math.imul(al8, bh8)) | 0;
mid = (mid + Math.imul(ah8, bl8)) | 0;
hi = (hi + Math.imul(ah8, bh8)) | 0;
lo = (lo + Math.imul(al7, bl9)) | 0;
mid = (mid + Math.imul(al7, bh9)) | 0;
mid = (mid + Math.imul(ah7, bl9)) | 0;
hi = (hi + Math.imul(ah7, bh9)) | 0;
var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
w16 &= 0x3ffffff;
/* k = 17 */
lo = Math.imul(al9, bl8);
mid = Math.imul(al9, bh8);
mid = (mid + Math.imul(ah9, bl8)) | 0;
hi = Math.imul(ah9, bh8);
lo = (lo + Math.imul(al8, bl9)) | 0;
mid = (mid + Math.imul(al8, bh9)) | 0;
mid = (mid + Math.imul(ah8, bl9)) | 0;
hi = (hi + Math.imul(ah8, bh9)) | 0;
var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
w17 &= 0x3ffffff;
/* k = 18 */
lo = Math.imul(al9, bl9);
mid = Math.imul(al9, bh9);
mid = (mid + Math.imul(ah9, bl9)) | 0;
hi = Math.imul(ah9, bh9);
var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
w18 &= 0x3ffffff;
o[0] = w0;
o[1] = w1;
o[2] = w2;
o[3] = w3;
o[4] = w4;
o[5] = w5;
o[6] = w6;
o[7] = w7;
o[8] = w8;
o[9] = w9;
o[10] = w10;
o[11] = w11;
o[12] = w12;
o[13] = w13;
o[14] = w14;
o[15] = w15;
o[16] = w16;
o[17] = w17;
o[18] = w18;
if (c !== 0) {
o[19] = c;
out.length++;
}
return out;
};
// Polyfill comb
if (!Math.imul) {
comb10MulTo = smallMulTo;
}
function bigMulTo (self, num, out) {
out.negative = num.negative ^ self.negative;
out.length = self.length + num.length;
var carry = 0;
var hncarry = 0;
for (var k = 0; k < out.length - 1; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = hncarry;
hncarry = 0;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
var i = k - j;
var a = self.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
lo = (lo + rword) | 0;
rword = lo & 0x3ffffff;
ncarry = (ncarry + (lo >>> 26)) | 0;
hncarry += ncarry >>> 26;
ncarry &= 0x3ffffff;
}
out.words[k] = rword;
carry = ncarry;
ncarry = hncarry;
}
if (carry !== 0) {
out.words[k] = carry;
} else {
out.length--;
}
return out._strip();
}
function jumboMulTo (self, num, out) {
// Temporary disable, see https://github.com/indutny/bn.js/issues/211
// var fftm = new FFTM();
// return fftm.mulp(self, num, out);
return bigMulTo(self, num, out);
}
BN.prototype.mulTo = function mulTo (num, out) {
var res;
var len = this.length + num.length;
if (this.length === 10 && num.length === 10) {
res = comb10MulTo(this, num, out);
} else if (len < 63) {
res = smallMulTo(this, num, out);
} else if (len < 1024) {
res = bigMulTo(this, num, out);
} else {
res = jumboMulTo(this, num, out);
}
return res;
};
// Cooley-Tukey algorithm for FFT
// slightly revisited to rely on looping instead of recursion
function FFTM (x, y) {
this.x = x;
this.y = y;
}
FFTM.prototype.makeRBT = function makeRBT (N) {
var t = new Array(N);
var l = BN.prototype._countBits(N) - 1;
for (var i = 0; i < N; i++) {
t[i] = this.revBin(i, l, N);
}
return t;
};
// Returns binary-reversed representation of `x`
FFTM.prototype.revBin = function revBin (x, l, N) {
if (x === 0 || x === N - 1) return x;
var rb = 0;
for (var i = 0; i < l; i++) {
rb |= (x & 1) << (l - i - 1);
x >>= 1;
}
return rb;
};
// Performs "tweedling" phase, therefore 'emulating'
// behaviour of the recursive algorithm
FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
for (var i = 0; i < N; i++) {
rtws[i] = rws[rbt[i]];
itws[i] = iws[rbt[i]];
}
};
FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
this.permute(rbt, rws, iws, rtws, itws, N);
for (var s = 1; s < N; s <<= 1) {
var l = s << 1;
var rtwdf = Math.cos(2 * Math.PI / l);
var itwdf = Math.sin(2 * Math.PI / l);
for (var p = 0; p < N; p += l) {
var rtwdf_ = rtwdf;
var itwdf_ = itwdf;
for (var j = 0; j < s; j++) {
var re = rtws[p + j];
var ie = itws[p + j];
var ro = rtws[p + j + s];
var io = itws[p + j + s];
var rx = rtwdf_ * ro - itwdf_ * io;
io = rtwdf_ * io + itwdf_ * ro;
ro = rx;
rtws[p + j] = re + ro;
itws[p + j] = ie + io;
rtws[p + j + s] = re - ro;
itws[p + j + s] = ie - io;
/* jshint maxdepth : false */
if (j !== l) {
rx = rtwdf * rtwdf_ - itwdf * itwdf_;
itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
rtwdf_ = rx;
}
}
}
}
};
FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
var N = Math.max(m, n) | 1;
var odd = N & 1;
var i = 0;
for (N = N / 2 | 0; N; N = N >>> 1) {
i++;
}
return 1 << i + 1 + odd;
};
FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
if (N <= 1) return;
for (var i = 0; i < N / 2; i++) {
var t = rws[i];
rws[i] = rws[N - i - 1];
rws[N - i - 1] = t;
t = iws[i];
iws[i] = -iws[N - i - 1];
iws[N - i - 1] = -t;
}
};
FFTM.prototype.normalize13b = function normalize13b (ws, N) {
var carry = 0;
for (var i = 0; i < N / 2; i++) {
var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
Math.round(ws[2 * i] / N) +
carry;
ws[i] = w & 0x3ffffff;
if (w < 0x4000000) {
carry = 0;
} else {
carry = w / 0x4000000 | 0;
}
}
return ws;
};
FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
var carry = 0;
for (var i = 0; i < len; i++) {
carry = carry + (ws[i] | 0);
rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
}
// Pad with zeroes
for (i = 2 * len; i < N; ++i) {
rws[i] = 0;
}
assert(carry === 0);
assert((carry & ~0x1fff) === 0);
};
FFTM.prototype.stub = function stub (N) {
var ph = new Array(N);
for (var i = 0; i < N; i++) {
ph[i] = 0;
}
return ph;
};
FFTM.prototype.mulp = function mulp (x, y, out) {
var N = 2 * this.guessLen13b(x.length, y.length);
var rbt = this.makeRBT(N);
var _ = this.stub(N);
var rws = new Array(N);
var rwst = new Array(N);
var iwst = new Array(N);
var nrws = new Array(N);
var nrwst = new Array(N);
var niwst = new Array(N);
var rmws = out.words;
rmws.length = N;
this.convert13b(x.words, x.length, rws, N);
this.convert13b(y.words, y.length, nrws, N);
this.transform(rws, _, rwst, iwst, N, rbt);
this.transform(nrws, _, nrwst, niwst, N, rbt);
for (var i = 0; i < N; i++) {
var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
rwst[i] = rx;
}
this.conjugate(rwst, iwst, N);
this.transform(rwst, iwst, rmws, _, N, rbt);
this.conjugate(rmws, _, N);
this.normalize13b(rmws, N);
out.negative = x.negative ^ y.negative;
out.length = x.length + y.length;
return out._strip();
};
// Multiply `this` by `num`
BN.prototype.mul = function mul (num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return this.mulTo(num, out);
};
// Multiply employing FFT
BN.prototype.mulf = function mulf (num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return jumboMulTo(this, num, out);
};
// In-place Multiplication
BN.prototype.imul = function imul (num) {
return this.clone().mulTo(num, this);
};
BN.prototype.imuln = function imuln (num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(typeof num === 'number');
assert(num < 0x4000000);
// Carry
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = (this.words[i] | 0) * num;
var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
carry >>= 26;
carry += (w / 0x4000000) | 0;
// NOTE: lo is 27bit maximum
carry += lo >>> 26;
this.words[i] = lo & 0x3ffffff;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return isNegNum ? this.ineg() : this;
};
BN.prototype.muln = function muln (num) {
return this.clone().imuln(num);
};
// `this` * `this`
BN.prototype.sqr = function sqr () {
return this.mul(this);
};
// `this` * `this` in-place
BN.prototype.isqr = function isqr () {
return this.imul(this.clone());
};
// Math.pow(`this`, `num`)
BN.prototype.pow = function pow (num) {
var w = toBitArray(num);
if (w.length === 0) return new BN(1);
// Skip leading zeroes
var res = this;
for (var i = 0; i < w.length; i++, res = res.sqr()) {
if (w[i] !== 0) break;
}
if (++i < w.length) {
for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
if (w[i] === 0) continue;
res = res.mul(q);
}
}
return res;
};
// Shift-left in-place
BN.prototype.iushln = function iushln (bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
var i;
if (r !== 0) {
var carry = 0;
for (i = 0; i < this.length; i++) {
var newCarry = this.words[i] & carryMask;
var c = ((this.words[i] | 0) - newCarry) << r;
this.words[i] = c | carry;
carry = newCarry >>> (26 - r);
}
if (carry) {
this.words[i] = carry;
this.length++;
}
}
if (s !== 0) {
for (i = this.length - 1; i >= 0; i--) {
this.words[i + s] = this.words[i];
}
for (i = 0; i < s; i++) {
this.words[i] = 0;
}
this.length += s;
}
return this._strip();
};
BN.prototype.ishln = function ishln (bits) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushln(bits);
};
// Shift-right in-place
// NOTE: `hint` is a lowest bit before trailing zeroes
// NOTE: if `extended` is present - it will be filled with destroyed bits
BN.prototype.iushrn = function iushrn (bits, hint, extended) {
assert(typeof bits === 'number' && bits >= 0);
var h;
if (hint) {
h = (hint - (hint % 26)) / 26;
} else {
h = 0;
}
var r = bits % 26;
var s = Math.min((bits - r) / 26, this.length);
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
var maskedWords = extended;
h -= s;
h = Math.max(0, h);
// Extended mode, copy masked part
if (maskedWords) {
for (var i = 0; i < s; i++) {
maskedWords.words[i] = this.words[i];
}
maskedWords.length = s;
}
if (s === 0) {
// No-op, we should not move anything at all
} else if (this.length > s) {
this.length -= s;
for (i = 0; i < this.length; i++) {
this.words[i] = this.words[i + s];
}
} else {
this.words[0] = 0;
this.length = 1;
}
var carry = 0;
for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
var word = this.words[i] | 0;
this.words[i] = (carry << (26 - r)) | (word >>> r);
carry = word & mask;
}
// Push carried bits as a mask
if (maskedWords && carry !== 0) {
maskedWords.words[maskedWords.length++] = carry;
}
if (this.length === 0) {
this.words[0] = 0;
this.length = 1;
}
return this._strip();
};
BN.prototype.ishrn = function ishrn (bits, hint, extended) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushrn(bits, hint, extended);
};
// Shift-left
BN.prototype.shln = function shln (bits) {
return this.clone().ishln(bits);
};
BN.prototype.ushln = function ushln (bits) {
return this.clone().iushln(bits);
};
// Shift-right
BN.prototype.shrn = function shrn (bits) {
return this.clone().ishrn(bits);
};
BN.prototype.ushrn = function ushrn (bits) {
return this.clone().iushrn(bits);
};
// Test if n bit is set
BN.prototype.testn = function testn (bit) {
assert(typeof bit === 'number' && bit >= 0);
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) return false;
// Check bit and return
var w = this.words[s];
return !!(w & q);
};
// Return only lowers bits of number (in-place)
BN.prototype.imaskn = function imaskn (bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
assert(this.negative === 0, 'imaskn works only with positive numbers');
if (this.length <= s) {
return this;
}
if (r !== 0) {
s++;
}
this.length = Math.min(s, this.length);
if (r !== 0) {
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
this.words[this.length - 1] &= mask;
}
return this._strip();
};
// Return only lowers bits of number
BN.prototype.maskn = function maskn (bits) {
return this.clone().imaskn(bits);
};
// Add plain number `num` to `this`
BN.prototype.iaddn = function iaddn (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
if (num < 0) return this.isubn(-num);
// Possible sign change
if (this.negative !== 0) {
if (this.length === 1 && (this.words[0] | 0) <= num) {
this.words[0] = num - (this.words[0] | 0);
this.negative = 0;
return this;
}
this.negative = 0;
this.isubn(num);
this.negative = 1;
return this;
}
// Add without checks
return this._iaddn(num);
};
BN.prototype._iaddn = function _iaddn (num) {
this.words[0] += num;
// Carry
for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
this.words[i] -= 0x4000000;
if (i === this.length - 1) {
this.words[i + 1] = 1;
} else {
this.words[i + 1]++;
}
}
this.length = Math.max(this.length, i + 1);
return this;
};
// Subtract plain number `num` from `this`
BN.prototype.isubn = function isubn (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
if (num < 0) return this.iaddn(-num);
if (this.negative !== 0) {
this.negative = 0;
this.iaddn(num);
this.negative = 1;
return this;
}
this.words[0] -= num;
if (this.length === 1 && this.words[0] < 0) {
this.words[0] = -this.words[0];
this.negative = 1;
} else {
// Carry
for (var i = 0; i < this.length && this.words[i] < 0; i++) {
this.words[i] += 0x4000000;
this.words[i + 1] -= 1;
}
}
return this._strip();
};
BN.prototype.addn = function addn (num) {
return this.clone().iaddn(num);
};
BN.prototype.subn = function subn (num) {
return this.clone().isubn(num);
};
BN.prototype.iabs = function iabs () {
this.negative = 0;
return this;
};
BN.prototype.abs = function abs () {
return this.clone().iabs();
};
BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
var len = num.length + shift;
var i;
this._expand(len);
var w;
var carry = 0;
for (i = 0; i < num.length; i++) {
w = (this.words[i + shift] | 0) + carry;
var right = (num.words[i] | 0) * mul;
w -= right & 0x3ffffff;
carry = (w >> 26) - ((right / 0x4000000) | 0);
this.words[i + shift] = w & 0x3ffffff;
}
for (; i < this.length - shift; i++) {
w = (this.words[i + shift] | 0) + carry;
carry = w >> 26;
this.words[i + shift] = w & 0x3ffffff;
}
if (carry === 0) return this._strip();
// Subtraction overflow
assert(carry === -1);
carry = 0;
for (i = 0; i < this.length; i++) {
w = -(this.words[i] | 0) + carry;
carry = w >> 26;
this.words[i] = w & 0x3ffffff;
}
this.negative = 1;
return this._strip();
};
BN.prototype._wordDiv = function _wordDiv (num, mode) {
var shift = this.length - num.length;
var a = this.clone();
var b = num;
// Normalize
var bhi = b.words[b.length - 1] | 0;
var bhiBits = this._countBits(bhi);
shift = 26 - bhiBits;
if (shift !== 0) {
b = b.ushln(shift);
a.iushln(shift);
bhi = b.words[b.length - 1] | 0;
}
// Initialize quotient
var m = a.length - b.length;
var q;
if (mode !== 'mod') {
q = new BN(null);
q.length = m + 1;
q.words = new Array(q.length);
for (var i = 0; i < q.length; i++) {
q.words[i] = 0;
}
}
var diff = a.clone()._ishlnsubmul(b, 1, m);
if (diff.negative === 0) {
a = diff;
if (q) {
q.words[m] = 1;
}
}
for (var j = m - 1; j >= 0; j--) {
var qj = (a.words[b.length + j] | 0) * 0x4000000 +
(a.words[b.length + j - 1] | 0);
// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj = Math.min((qj / bhi) | 0, 0x3ffffff);
a._ishlnsubmul(b, qj, j);
while (a.negative !== 0) {
qj--;
a.negative = 0;
a._ishlnsubmul(b, 1, j);
if (!a.isZero()) {
a.negative ^= 1;
}
}
if (q) {
q.words[j] = qj;
}
}
if (q) {
q._strip();
}
a._strip();
// Denormalize
if (mode !== 'div' && shift !== 0) {
a.iushrn(shift);
}
return {
div: q || null,
mod: a
};
};
// NOTE: 1) `mode` can be set to `mod` to request mod only,
// to `div` to request div only, or be absent to
// request both div & mod
// 2) `positive` is true if unsigned mod is requested
BN.prototype.divmod = function divmod (num, mode, positive) {
assert(!num.isZero());
if (this.isZero()) {
return {
div: new BN(0),
mod: new BN(0)
};
}
var div, mod, res;
if (this.negative !== 0 && num.negative === 0) {
res = this.neg().divmod(num, mode);
if (mode !== 'mod') {
div = res.div.neg();
}
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.negative !== 0) {
mod.iadd(num);
}
}
return {
div: div,
mod: mod
};
}
if (this.negative === 0 && num.negative !== 0) {
res = this.divmod(num.neg(), mode);
if (mode !== 'mod') {
div = res.div.neg();
}
return {
div: div,
mod: res.mod
};
}
if ((this.negative & num.negative) !== 0) {
res = this.neg().divmod(num.neg(), mode);
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.negative !== 0) {
mod.isub(num);
}
}
return {
div: res.div,
mod: mod
};
}
// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if (num.length > this.length || this.cmp(num) < 0) {
return {
div: new BN(0),
mod: this
};
}
// Very short reduction
if (num.length === 1) {
if (mode === 'div') {
return {
div: this.divn(num.words[0]),
mod: null
};
}
if (mode === 'mod') {
return {
div: null,
mod: new BN(this.modrn(num.words[0]))
};
}
return {
div: this.divn(num.words[0]),
mod: new BN(this.modrn(num.words[0]))
};
}
return this._wordDiv(num, mode);
};
// Find `this` / `num`
BN.prototype.div = function div (num) {
return this.divmod(num, 'div', false).div;
};
// Find `this` % `num`
BN.prototype.mod = function mod (num) {
return this.divmod(num, 'mod', false).mod;
};
BN.prototype.umod = function umod (num) {
return this.divmod(num, 'mod', true).mod;
};
// Find Round(`this` / `num`)
BN.prototype.divRound = function divRound (num) {
var dm = this.divmod(num);
// Fast case - exact division
if (dm.mod.isZero()) return dm.div;
var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
var half = num.ushrn(1);
var r2 = num.andln(1);
var cmp = mod.cmp(half);
// Round down
if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;
// Round up
return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
};
BN.prototype.modrn = function modrn (num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(num <= 0x3ffffff);
var p = (1 << 26) % num;
var acc = 0;
for (var i = this.length - 1; i >= 0; i--) {
acc = (p * acc + (this.words[i] | 0)) % num;
}
return isNegNum ? -acc : acc;
};
// WARNING: DEPRECATED
BN.prototype.modn = function modn (num) {
return this.modrn(num);
};
// In-place division by number
BN.prototype.idivn = function idivn (num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(num <= 0x3ffffff);
var carry = 0;
for (var i = this.length - 1; i >= 0; i--) {
var w = (this.words[i] | 0) + carry * 0x4000000;
this.words[i] = (w / num) | 0;
carry = w % num;
}
this._strip();
return isNegNum ? this.ineg() : this;
};
BN.prototype.divn = function divn (num) {
return this.clone().idivn(num);
};
BN.prototype.egcd = function egcd (p) {
assert(p.negative === 0);
assert(!p.isZero());
var x = this;
var y = p.clone();
if (x.negative !== 0) {
x = x.umod(p);
} else {
x = x.clone();
}
// A * x + B * y = x
var A = new BN(1);
var B = new BN(0);
// C * x + D * y = y
var C = new BN(0);
var D = new BN(1);
var g = 0;
while (x.isEven() && y.isEven()) {
x.iushrn(1);
y.iushrn(1);
++g;
}
var yp = y.clone();
var xp = x.clone();
while (!x.isZero()) {
for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
x.iushrn(i);
while (i-- > 0) {
if (A.isOdd() || B.isOdd()) {
A.iadd(yp);
B.isub(xp);
}
A.iushrn(1);
B.iushrn(1);
}
}
for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
y.iushrn(j);
while (j-- > 0) {
if (C.isOdd() || D.isOdd()) {
C.iadd(yp);
D.isub(xp);
}
C.iushrn(1);
D.iushrn(1);
}
}
if (x.cmp(y) >= 0) {
x.isub(y);
A.isub(C);
B.isub(D);
} else {
y.isub(x);
C.isub(A);
D.isub(B);
}
}
return {
a: C,
b: D,
gcd: y.iushln(g)
};
};
// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp = function _invmp (p) {
assert(p.negative === 0);
assert(!p.isZero());
var a = this;
var b = p.clone();
if (a.negative !== 0) {
a = a.umod(p);
} else {
a = a.clone();
}
var x1 = new BN(1);
var x2 = new BN(0);
var delta = b.clone();
while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
a.iushrn(i);
while (i-- > 0) {
if (x1.isOdd()) {
x1.iadd(delta);
}
x1.iushrn(1);
}
}
for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
b.iushrn(j);
while (j-- > 0) {
if (x2.isOdd()) {
x2.iadd(delta);
}
x2.iushrn(1);
}
}
if (a.cmp(b) >= 0) {
a.isub(b);
x1.isub(x2);
} else {
b.isub(a);
x2.isub(x1);
}
}
var res;
if (a.cmpn(1) === 0) {
res = x1;
} else {
res = x2;
}
if (res.cmpn(0) < 0) {
res.iadd(p);
}
return res;
};
BN.prototype.gcd = function gcd (num) {
if (this.isZero()) return num.abs();
if (num.isZero()) return this.abs();
var a = this.clone();
var b = num.clone();
a.negative = 0;
b.negative = 0;
// Remove common factor of two
for (var shift = 0; a.isEven() && b.isEven(); shift++) {
a.iushrn(1);
b.iushrn(1);
}
do {
while (a.isEven()) {
a.iushrn(1);
}
while (b.isEven()) {
b.iushrn(1);
}
var r = a.cmp(b);
if (r < 0) {
// Swap `a` and `b` to make `a` always bigger than `b`
var t = a;
a = b;
b = t;
} else if (r === 0 || b.cmpn(1) === 0) {
break;
}
a.isub(b);
} while (true);
return b.iushln(shift);
};
// Invert number in the field F(num)
BN.prototype.invm = function invm (num) {
return this.egcd(num).a.umod(num);
};
BN.prototype.isEven = function isEven () {
return (this.words[0] & 1) === 0;
};
BN.prototype.isOdd = function isOdd () {
return (this.words[0] & 1) === 1;
};
// And first word and num
BN.prototype.andln = function andln (num) {
return this.words[0] & num;
};
// Increment at the bit position in-line
BN.prototype.bincn = function bincn (bit) {
assert(typeof bit === 'number');
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
this._expand(s + 1);
this.words[s] |= q;
return this;
}
// Add bit and propagate, if needed
var carry = q;
for (var i = s; carry !== 0 && i < this.length; i++) {
var w = this.words[i] | 0;
w += carry;
carry = w >>> 26;
w &= 0x3ffffff;
this.words[i] = w;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.isZero = function isZero () {
return this.length === 1 && this.words[0] === 0;
};
BN.prototype.cmpn = function cmpn (num) {
var negative = num < 0;
if (this.negative !== 0 && !negative) return -1;
if (this.negative === 0 && negative) return 1;
this._strip();
var res;
if (this.length > 1) {
res = 1;
} else {
if (negative) {
num = -num;
}
assert(num <= 0x3ffffff, 'Number is too big');
var w = this.words[0] | 0;
res = w === num ? 0 : w < num ? -1 : 1;
}
if (this.negative !== 0) return -res | 0;
return res;
};
// Compare two numbers and return:
// 1 - if `this` > `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp = function cmp (num) {
if (this.negative !== 0 && num.negative === 0) return -1;
if (this.negative === 0 && num.negative !== 0) return 1;
var res = this.ucmp(num);
if (this.negative !== 0) return -res | 0;
return res;
};
// Unsigned comparison
BN.prototype.ucmp = function ucmp (num) {
// At this point both numbers have the same sign
if (this.length > num.length) return 1;
if (this.length < num.length) return -1;
var res = 0;
for (var i = this.length - 1; i >= 0; i--) {
var a = this.words[i] | 0;
var b = num.words[i] | 0;
if (a === b) continue;
if (a < b) {
res = -1;
} else if (a > b) {
res = 1;
}
break;
}
return res;
};
BN.prototype.gtn = function gtn (num) {
return this.cmpn(num) === 1;
};
BN.prototype.gt = function gt (num) {
return this.cmp(num) === 1;
};
BN.prototype.gten = function gten (num) {
return this.cmpn(num) >= 0;
};
BN.prototype.gte = function gte (num) {
return this.cmp(num) >= 0;
};
BN.prototype.ltn = function ltn (num) {
return this.cmpn(num) === -1;
};
BN.prototype.lt = function lt (num) {
return this.cmp(num) === -1;
};
BN.prototype.lten = function lten (num) {
return this.cmpn(num) <= 0;
};
BN.prototype.lte = function lte (num) {
return this.cmp(num) <= 0;
};
BN.prototype.eqn = function eqn (num) {
return this.cmpn(num) === 0;
};
BN.prototype.eq = function eq (num) {
return this.cmp(num) === 0;
};
//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red = function red (num) {
return new Red(num);
};
BN.prototype.toRed = function toRed (ctx) {
assert(!this.red, 'Already a number in reduction context');
assert(this.negative === 0, 'red works only with positives');
return ctx.convertTo(this)._forceRed(ctx);
};
BN.prototype.fromRed = function fromRed () {
assert(this.red, 'fromRed works only with numbers in reduction context');
return this.red.convertFrom(this);
};
BN.prototype._forceRed = function _forceRed (ctx) {
this.red = ctx;
return this;
};
BN.prototype.forceRed = function forceRed (ctx) {
assert(!this.red, 'Already a number in reduction context');
return this._forceRed(ctx);
};
BN.prototype.redAdd = function redAdd (num) {
assert(this.red, 'redAdd works only with red numbers');
return this.red.add(this, num);
};
BN.prototype.redIAdd = function redIAdd (num) {
assert(this.red, 'redIAdd works only with red numbers');
return this.red.iadd(this, num);
};
BN.prototype.redSub = function redSub (num) {
assert(this.red, 'redSub works only with red numbers');
return this.red.sub(this, num);
};
BN.prototype.redISub = function redISub (num) {
assert(this.red, 'redISub works only with red numbers');
return this.red.isub(this, num);
};
BN.prototype.redShl = function redShl (num) {
assert(this.red, 'redShl works only with red numbers');
return this.red.shl(this, num);
};
BN.prototype.redMul = function redMul (num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.mul(this, num);
};
BN.prototype.redIMul = function redIMul (num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.imul(this, num);
};
BN.prototype.redSqr = function redSqr () {
assert(this.red, 'redSqr works only with red numbers');
this.red._verify1(this);
return this.red.sqr(this);
};
BN.prototype.redISqr = function redISqr () {
assert(this.red, 'redISqr works only with red numbers');
this.red._verify1(this);
return this.red.isqr(this);
};
// Square root over p
BN.prototype.redSqrt = function redSqrt () {
assert(this.red, 'redSqrt works only with red numbers');
this.red._verify1(this);
return this.red.sqrt(this);
};
BN.prototype.redInvm = function redInvm () {
assert(this.red, 'redInvm works only with red numbers');
this.red._verify1(this);
return this.red.invm(this);
};
// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg = function redNeg () {
assert(this.red, 'redNeg works only with red numbers');
this.red._verify1(this);
return this.red.neg(this);
};
BN.prototype.redPow = function redPow (num) {
assert(this.red && !num.red, 'redPow(normalNum)');
this.red._verify1(this);
return this.red.pow(this, num);
};
// Prime numbers with efficient reduction
var primes = {
k256: null,
p224: null,
p192: null,
p25519: null
};
// Pseudo-Mersenne prime
function MPrime (name, p) {
// P = 2 ^ N - K
this.name = name;
this.p = new BN(p, 16);
this.n = this.p.bitLength();
this.k = new BN(1).iushln(this.n).isub(this.p);
this.tmp = this._tmp();
}
MPrime.prototype._tmp = function _tmp () {
var tmp = new BN(null);
tmp.words = new Array(Math.ceil(this.n / 13));
return tmp;
};
MPrime.prototype.ireduce = function ireduce (num) {
// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r = num;
var rlen;
do {
this.split(r, this.tmp);
r = this.imulK(r);
r = r.iadd(this.tmp);
rlen = r.bitLength();
} while (rlen > this.n);
var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
if (cmp === 0) {
r.words[0] = 0;
r.length = 1;
} else if (cmp > 0) {
r.isub(this.p);
} else {
if (r.strip !== undefined) {
// r is a BN v4 instance
r.strip();
} else {
// r is a BN v5 instance
r._strip();
}
}
return r;
};
MPrime.prototype.split = function split (input, out) {
input.iushrn(this.n, 0, out);
};
MPrime.prototype.imulK = function imulK (num) {
return num.imul(this.k);
};
function K256 () {
MPrime.call(
this,
'k256',
'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
}
inherits(K256, MPrime);
K256.prototype.split = function split (input, output) {
// 256 = 9 * 26 + 22
var mask = 0x3fffff;
var outLen = Math.min(input.length, 9);
for (var i = 0; i < outLen; i++) {
output.words[i] = input.words[i];
}
output.length = outLen;
if (input.length <= 9) {
input.words[0] = 0;
input.length = 1;
return;
}
// Shift by 9 limbs
var prev = input.words[9];
output.words[output.length++] = prev & mask;
for (i = 10; i < input.length; i++) {
var next = input.words[i] | 0;
input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
prev = next;
}
prev >>>= 22;
input.words[i - 10] = prev;
if (prev === 0 && input.length > 10) {
input.length -= 10;
} else {
input.length -= 9;
}
};
K256.prototype.imulK = function imulK (num) {
// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var lo = 0;
for (var i = 0; i < num.length; i++) {
var w = num.words[i] | 0;
lo += w * 0x3d1;
num.words[i] = lo & 0x3ffffff;
lo = w * 0x40 + ((lo / 0x4000000) | 0);
}
// Fast length reduction
if (num.words[num.length - 1] === 0) {
num.length--;
if (num.words[num.length - 1] === 0) {
num.length--;
}
}
return num;
};
function P224 () {
MPrime.call(
this,
'p224',
'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
}
inherits(P224, MPrime);
function P192 () {
MPrime.call(
this,
'p192',
'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
}
inherits(P192, MPrime);
function P25519 () {
// 2 ^ 255 - 19
MPrime.call(
this,
'25519',
'7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
}
inherits(P25519, MPrime);
P25519.prototype.imulK = function imulK (num) {
// K = 0x13
var carry = 0;
for (var i = 0; i < num.length; i++) {
var hi = (num.words[i] | 0) * 0x13 + carry;
var lo = hi & 0x3ffffff;
hi >>>= 26;
num.words[i] = lo;
carry = hi;
}
if (carry !== 0) {
num.words[num.length++] = carry;
}
return num;
};
// Exported mostly for testing purposes, use plain name instead
BN._prime = function prime (name) {
// Cached version of prime
if (primes[name]) return primes[name];
var prime;
if (name === 'k256') {
prime = new K256();
} else if (name === 'p224') {
prime = new P224();
} else if (name === 'p192') {
prime = new P192();
} else if (name === 'p25519') {
prime = new P25519();
} else {
throw new Error('Unknown prime ' + name);
}
primes[name] = prime;
return prime;
};
//
// Base reduction engine
//
function Red (m) {
if (typeof m === 'string') {
var prime = BN._prime(m);
this.m = prime.p;
this.prime = prime;
} else {
assert(m.gtn(1), 'modulus must be greater than 1');
this.m = m;
this.prime = null;
}
}
Red.prototype._verify1 = function _verify1 (a) {
assert(a.negative === 0, 'red works only with positives');
assert(a.red, 'red works only with red numbers');
};
Red.prototype._verify2 = function _verify2 (a, b) {
assert((a.negative | b.negative) === 0, 'red works only with positives');
assert(a.red && a.red === b.red,
'red works only with red numbers');
};
Red.prototype.imod = function imod (a) {
if (this.prime) return this.prime.ireduce(a)._forceRed(this);
move(a, a.umod(this.m)._forceRed(this));
return a;
};
Red.prototype.neg = function neg (a) {
if (a.isZero()) {
return a.clone();
}
return this.m.sub(a)._forceRed(this);
};
Red.prototype.add = function add (a, b) {
this._verify2(a, b);
var res = a.add(b);
if (res.cmp(this.m) >= 0) {
res.isub(this.m);
}
return res._forceRed(this);
};
Red.prototype.iadd = function iadd (a, b) {
this._verify2(a, b);
var res = a.iadd(b);
if (res.cmp(this.m) >= 0) {
res.isub(this.m);
}
return res;
};
Red.prototype.sub = function sub (a, b) {
this._verify2(a, b);
var res = a.sub(b);
if (res.cmpn(0) < 0) {
res.iadd(this.m);
}
return res._forceRed(this);
};
Red.prototype.isub = function isub (a, b) {
this._verify2(a, b);
var res = a.isub(b);
if (res.cmpn(0) < 0) {
res.iadd(this.m);
}
return res;
};
Red.prototype.shl = function shl (a, num) {
this._verify1(a);
return this.imod(a.ushln(num));
};
Red.prototype.imul = function imul (a, b) {
this._verify2(a, b);
return this.imod(a.imul(b));
};
Red.prototype.mul = function mul (a, b) {
this._verify2(a, b);
return this.imod(a.mul(b));
};
Red.prototype.isqr = function isqr (a) {
return this.imul(a, a.clone());
};
Red.prototype.sqr = function sqr (a) {
return this.mul(a, a);
};
Red.prototype.sqrt = function sqrt (a) {
if (a.isZero()) return a.clone();
var mod3 = this.m.andln(3);
assert(mod3 % 2 === 1);
// Fast case
if (mod3 === 3) {
var pow = this.m.add(new BN(1)).iushrn(2);
return this.pow(a, pow);
}
// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q = this.m.subn(1);
var s = 0;
while (!q.isZero() && q.andln(1) === 0) {
s++;
q.iushrn(1);
}
assert(!q.isZero());
var one = new BN(1).toRed(this);
var nOne = one.redNeg();
// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow = this.m.subn(1).iushrn(1);
var z = this.m.bitLength();
z = new BN(2 * z * z).toRed(this);
while (this.pow(z, lpow).cmp(nOne) !== 0) {
z.redIAdd(nOne);
}
var c = this.pow(z, q);
var r = this.pow(a, q.addn(1).iushrn(1));
var t = this.pow(a, q);
var m = s;
while (t.cmp(one) !== 0) {
var tmp = t;
for (var i = 0; tmp.cmp(one) !== 0; i++) {
tmp = tmp.redSqr();
}
assert(i < m);
var b = this.pow(c, new BN(1).iushln(m - i - 1));
r = r.redMul(b);
c = b.redSqr();
t = t.redMul(c);
m = i;
}
return r;
};
Red.prototype.invm = function invm (a) {
var inv = a._invmp(this.m);
if (inv.negative !== 0) {
inv.negative = 0;
return this.imod(inv).redNeg();
} else {
return this.imod(inv);
}
};
Red.prototype.pow = function pow (a, num) {
if (num.isZero()) return new BN(1).toRed(this);
if (num.cmpn(1) === 0) return a.clone();
var windowSize = 4;
var wnd = new Array(1 << windowSize);
wnd[0] = new BN(1).toRed(this);
wnd[1] = a;
for (var i = 2; i < wnd.length; i++) {
wnd[i] = this.mul(wnd[i - 1], a);
}
var res = wnd[0];
var current = 0;
var currentLen = 0;
var start = num.bitLength() % 26;
if (start === 0) {
start = 26;
}
for (i = num.length - 1; i >= 0; i--) {
var word = num.words[i];
for (var j = start - 1; j >= 0; j--) {
var bit = (word >> j) & 1;
if (res !== wnd[0]) {
res = this.sqr(res);
}
if (bit === 0 && current === 0) {
currentLen = 0;
continue;
}
current <<= 1;
current |= bit;
currentLen++;
if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
res = this.mul(res, wnd[current]);
currentLen = 0;
current = 0;
}
start = 26;
}
return res;
};
Red.prototype.convertTo = function convertTo (num) {
var r = num.umod(this.m);
return r === num ? r.clone() : r;
};
Red.prototype.convertFrom = function convertFrom (num) {
var res = num.clone();
res.red = null;
return res;
};
//
// Montgomery method engine
//
BN.mont = function mont (num) {
return new Mont(num);
};
function Mont (m) {
Red.call(this, m);
this.shift = this.m.bitLength();
if (this.shift % 26 !== 0) {
this.shift += 26 - (this.shift % 26);
}
this.r = new BN(1).iushln(this.shift);
this.r2 = this.imod(this.r.sqr());
this.rinv = this.r._invmp(this.m);
this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
this.minv = this.minv.umod(this.r);
this.minv = this.r.sub(this.minv);
}
inherits(Mont, Red);
Mont.prototype.convertTo = function convertTo (num) {
return this.imod(num.ushln(this.shift));
};
Mont.prototype.convertFrom = function convertFrom (num) {
var r = this.imod(num.mul(this.rinv));
r.red = null;
return r;
};
Mont.prototype.imul = function imul (a, b) {
if (a.isZero() || b.isZero()) {
a.words[0] = 0;
a.length = 1;
return a;
}
var t = a.imul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) {
res = u.isub(this.m);
} else if (u.cmpn(0) < 0) {
res = u.iadd(this.m);
}
return res._forceRed(this);
};
Mont.prototype.mul = function mul (a, b) {
if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
var t = a.mul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) {
res = u.isub(this.m);
} else if (u.cmpn(0) < 0) {
res = u.iadd(this.m);
}
return res._forceRed(this);
};
Mont.prototype.invm = function invm (a) {
// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res = this.imod(a._invmp(this.m).mul(this.r2));
return res._forceRed(this);
};
})( false || module, this);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)(module)))
/***/ }),
/* 1 */,
/* 2 */,
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
var hash = exports;
hash.utils = __webpack_require__(6);
hash.common = __webpack_require__(12);
hash.sha = __webpack_require__(39);
hash.ripemd = __webpack_require__(43);
hash.hmac = __webpack_require__(44);
// Proxy hash functions to the main object
hash.sha1 = hash.sha.sha1;
hash.sha256 = hash.sha.sha256;
hash.sha224 = hash.sha.sha224;
hash.sha384 = hash.sha.sha384;
hash.sha512 = hash.sha.sha512;
hash.ripemd160 = hash.ripemd.ripemd160;
/***/ }),
/* 4 */,
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
(function(root) {
function checkInt(value) {
return (parseInt(value) === value);
}
function checkInts(arrayish) {
if (!checkInt(arrayish.length)) { return false; }
for (var i = 0; i < arrayish.length; i++) {
if (!checkInt(arrayish[i]) || arrayish[i] < 0 || arrayish[i] > 255) {
return false;
}
}
return true;
}
function coerceArray(arg, copy) {
// ArrayBuffer view
if (arg.buffer && ArrayBuffer.isView(arg) && arg.name === 'Uint8Array') {
if (copy) {
if (arg.slice) {
arg = arg.slice();
} else {
arg = Array.prototype.slice.call(arg);
}
}
return arg;
}
// It's an array; check it is a valid representation of a byte
if (Array.isArray(arg)) {
if (!checkInts(arg)) {
throw new Error('Array contains invalid value: ' + arg);
}
return new Uint8Array(arg);
}
// Something else, but behaves like an array (maybe a Buffer? Arguments?)
if (checkInt(arg.length) && checkInts(arg)) {
return new Uint8Array(arg);
}
throw new Error('unsupported array-like object');
}
function createArray(length) {
return new Uint8Array(length);
}
function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) {
if (sourceStart != null || sourceEnd != null) {
if (sourceArray.slice) {
sourceArray = sourceArray.slice(sourceStart, sourceEnd);
} else {
sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd);
}
}
targetArray.set(sourceArray, targetStart);
}
var convertUtf8 = (function() {
function toBytes(text) {
var result = [], i = 0;
text = encodeURI(text);
while (i < text.length) {
var c = text.charCodeAt(i++);
// if it is a % sign, encode the following 2 bytes as a hex value
if (c === 37) {
result.push(parseInt(text.substr(i, 2), 16))
i += 2;
// otherwise, just the actual byte
} else {
result.push(c)
}
}
return coerceArray(result);
}
function fromBytes(bytes) {
var result = [], i = 0;
while (i < bytes.length) {
var c = bytes[i];
if (c < 128) {
result.push(String.fromCharCode(c));
i++;
} else if (c > 191 && c < 224) {
result.push(String.fromCharCode(((c & 0x1f) << 6) | (bytes[i + 1] & 0x3f)));
i += 2;
} else {
result.push(String.fromCharCode(((c & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f)));
i += 3;
}
}
return result.join('');
}
return {
toBytes: toBytes,
fromBytes: fromBytes,
}
})();
var convertHex = (function() {
function toBytes(text) {
var result = [];
for (var i = 0; i < text.length; i += 2) {
result.push(parseInt(text.substr(i, 2), 16));
}
return result;
}
// http://ixti.net/development/javascript/2011/11/11/base64-encodedecode-of-utf8-in-browser-with-js.html
var Hex = '0123456789abcdef';
function fromBytes(bytes) {
var result = [];
for (var i = 0; i < bytes.length; i++) {
var v = bytes[i];
result.push(Hex[(v & 0xf0) >> 4] + Hex[v & 0x0f]);
}
return result.join('');
}
return {
toBytes: toBytes,
fromBytes: fromBytes,
}
})();
// Number of rounds by keysize
var numberOfRounds = {16: 10, 24: 12, 32: 14}
// Round constant words
var rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91];
// S-box and Inverse S-box (S is for Substitution)
var S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];
var Si =[0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d];
// Transformations for encryption
var T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a];
var T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616];
var T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16];
var T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c];
// Transformations for decryption
var T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742];
var T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857];
var T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8];
var T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0];
// Transformations for decryption key expansion
var U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3];
var U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697];
var U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46];
var U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d];
function convertToInt32(bytes) {
var result = [];
for (var i = 0; i < bytes.length; i += 4) {
result.push(
(bytes[i ] << 24) |
(bytes[i + 1] << 16) |
(bytes[i + 2] << 8) |
bytes[i + 3]
);
}
return result;
}
var AES = function(key) {
if (!(this instanceof AES)) {
throw Error('AES must be instanitated with `new`');
}
Object.defineProperty(this, 'key', {
value: coerceArray(key, true)
});
this._prepare();
}
AES.prototype._prepare = function() {
var rounds = numberOfRounds[this.key.length];
if (rounds == null) {
throw new Error('invalid key size (must be 16, 24 or 32 bytes)');
}
// encryption round keys
this._Ke = [];
// decryption round keys
this._Kd = [];
for (var i = 0; i <= rounds; i++) {
this._Ke.push([0, 0, 0, 0]);
this._Kd.push([0, 0, 0, 0]);
}
var roundKeyCount = (rounds + 1) * 4;
var KC = this.key.length / 4;
// convert the key into ints
var tk = convertToInt32(this.key);
// copy values into round key arrays
var index;
for (var i = 0; i < KC; i++) {
index = i >> 2;
this._Ke[index][i % 4] = tk[i];
this._Kd[rounds - index][i % 4] = tk[i];
}
// key expansion (fips-197 section 5.2)
var rconpointer = 0;
var t = KC, tt;
while (t < roundKeyCount) {
tt = tk[KC - 1];
tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^
(S[(tt >> 8) & 0xFF] << 16) ^
(S[ tt & 0xFF] << 8) ^
S[(tt >> 24) & 0xFF] ^
(rcon[rconpointer] << 24));
rconpointer += 1;
// key expansion (for non-256 bit)
if (KC != 8) {
for (var i = 1; i < KC; i++) {
tk[i] ^= tk[i - 1];
}
// key expansion for 256-bit keys is "slightly different" (fips-197)
} else {
for (var i = 1; i < (KC / 2); i++) {
tk[i] ^= tk[i - 1];
}
tt = tk[(KC / 2) - 1];
tk[KC / 2] ^= (S[ tt & 0xFF] ^
(S[(tt >> 8) & 0xFF] << 8) ^
(S[(tt >> 16) & 0xFF] << 16) ^
(S[(tt >> 24) & 0xFF] << 24));
for (var i = (KC / 2) + 1; i < KC; i++) {
tk[i] ^= tk[i - 1];
}
}
// copy values into round key arrays
var i = 0, r, c;
while (i < KC && t < roundKeyCount) {
r = t >> 2;
c = t % 4;
this._Ke[r][c] = tk[i];
this._Kd[rounds - r][c] = tk[i++];
t++;
}
}
// inverse-cipher-ify the decryption round key (fips-197 section 5.3)
for (var r = 1; r < rounds; r++) {
for (var c = 0; c < 4; c++) {
tt = this._Kd[r][c];
this._Kd[r][c] = (U1[(tt >> 24) & 0xFF] ^
U2[(tt >> 16) & 0xFF] ^
U3[(tt >> 8) & 0xFF] ^
U4[ tt & 0xFF]);
}
}
}
AES.prototype.encrypt = function(plaintext) {
if (plaintext.length != 16) {
throw new Error('invalid plaintext size (must be 16 bytes)');
}
var rounds = this._Ke.length - 1;
var a = [0, 0, 0, 0];
// convert plaintext to (ints ^ key)
var t = convertToInt32(plaintext);
for (var i = 0; i < 4; i++) {
t[i] ^= this._Ke[0][i];
}
// apply round transforms
for (var r = 1; r < rounds; r++) {
for (var i = 0; i < 4; i++) {
a[i] = (T1[(t[ i ] >> 24) & 0xff] ^
T2[(t[(i + 1) % 4] >> 16) & 0xff] ^
T3[(t[(i + 2) % 4] >> 8) & 0xff] ^
T4[ t[(i + 3) % 4] & 0xff] ^
this._Ke[r][i]);
}
t = a.slice();
}
// the last round is special
var result = createArray(16), tt;
for (var i = 0; i < 4; i++) {
tt = this._Ke[rounds][i];
result[4 * i ] = (S[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
result[4 * i + 3] = (S[ t[(i + 3) % 4] & 0xff] ^ tt ) & 0xff;
}
return result;
}
AES.prototype.decrypt = function(ciphertext) {
if (ciphertext.length != 16) {
throw new Error('invalid ciphertext size (must be 16 bytes)');
}
var rounds = this._Kd.length - 1;
var a = [0, 0, 0, 0];
// convert plaintext to (ints ^ key)
var t = convertToInt32(ciphertext);
for (var i = 0; i < 4; i++) {
t[i] ^= this._Kd[0][i];
}
// apply round transforms
for (var r = 1; r < rounds; r++) {
for (var i = 0; i < 4; i++) {
a[i] = (T5[(t[ i ] >> 24) & 0xff] ^
T6[(t[(i + 3) % 4] >> 16) & 0xff] ^
T7[(t[(i + 2) % 4] >> 8) & 0xff] ^
T8[ t[(i + 1) % 4] & 0xff] ^
this._Kd[r][i]);
}
t = a.slice();
}
// the last round is special
var result = createArray(16), tt;
for (var i = 0; i < 4; i++) {
tt = this._Kd[rounds][i];
result[4 * i ] = (Si[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
result[4 * i + 3] = (Si[ t[(i + 1) % 4] & 0xff] ^ tt ) & 0xff;
}
return result;
}
/**
* Mode Of Operation - Electonic Codebook (ECB)
*/
var ModeOfOperationECB = function(key) {
if (!(this instanceof ModeOfOperationECB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Electronic Code Block";
this.name = "ecb";
this._aes = new AES(key);
}
ModeOfOperationECB.prototype.encrypt = function(plaintext) {
plaintext = coerceArray(plaintext);
if ((plaintext.length % 16) !== 0) {
throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
}
var ciphertext = createArray(plaintext.length);
var block = createArray(16);
for (var i = 0; i < plaintext.length; i += 16) {
copyArray(plaintext, block, 0, i, i + 16);
block = this._aes.encrypt(block);
copyArray(block, ciphertext, i);
}
return ciphertext;
}
ModeOfOperationECB.prototype.decrypt = function(ciphertext) {
ciphertext = coerceArray(ciphertext);
if ((ciphertext.length % 16) !== 0) {
throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
}
var plaintext = createArray(ciphertext.length);
var block = createArray(16);
for (var i = 0; i < ciphertext.length; i += 16) {
copyArray(ciphertext, block, 0, i, i + 16);
block = this._aes.decrypt(block);
copyArray(block, plaintext, i);
}
return plaintext;
}
/**
* Mode Of Operation - Cipher Block Chaining (CBC)
*/
var ModeOfOperationCBC = function(key, iv) {
if (!(this instanceof ModeOfOperationCBC)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Cipher Block Chaining";
this.name = "cbc";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 bytes)');
}
this._lastCipherblock = coerceArray(iv, true);
this._aes = new AES(key);
}
ModeOfOperationCBC.prototype.encrypt = function(plaintext) {
plaintext = coerceArray(plaintext);
if ((plaintext.length % 16) !== 0) {
throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
}
var ciphertext = createArray(plaintext.length);
var block = createArray(16);
for (var i = 0; i < plaintext.length; i += 16) {
copyArray(plaintext, block, 0, i, i + 16);
for (var j = 0; j < 16; j++) {
block[j] ^= this._lastCipherblock[j];
}
this._lastCipherblock = this._aes.encrypt(block);
copyArray(this._lastCipherblock, ciphertext, i);
}
return ciphertext;
}
ModeOfOperationCBC.prototype.decrypt = function(ciphertext) {
ciphertext = coerceArray(ciphertext);
if ((ciphertext.length % 16) !== 0) {
throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
}
var plaintext = createArray(ciphertext.length);
var block = createArray(16);
for (var i = 0; i < ciphertext.length; i += 16) {
copyArray(ciphertext, block, 0, i, i + 16);
block = this._aes.decrypt(block);
for (var j = 0; j < 16; j++) {
plaintext[i + j] = block[j] ^ this._lastCipherblock[j];
}
copyArray(ciphertext, this._lastCipherblock, 0, i, i + 16);
}
return plaintext;
}
/**
* Mode Of Operation - Cipher Feedback (CFB)
*/
var ModeOfOperationCFB = function(key, iv, segmentSize) {
if (!(this instanceof ModeOfOperationCFB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Cipher Feedback";
this.name = "cfb";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 size)');
}
if (!segmentSize) { segmentSize = 1; }
this.segmentSize = segmentSize;
this._shiftRegister = coerceArray(iv, true);
this._aes = new AES(key);
}
ModeOfOperationCFB.prototype.encrypt = function(plaintext) {
if ((plaintext.length % this.segmentSize) != 0) {
throw new Error('invalid plaintext size (must be segmentSize bytes)');
}
var encrypted = coerceArray(plaintext, true);
var xorSegment;
for (var i = 0; i < encrypted.length; i += this.segmentSize) {
xorSegment = this._aes.encrypt(this._shiftRegister);
for (var j = 0; j < this.segmentSize; j++) {
encrypted[i + j] ^= xorSegment[j];
}
// Shift the register
copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
}
return encrypted;
}
ModeOfOperationCFB.prototype.decrypt = function(ciphertext) {
if ((ciphertext.length % this.segmentSize) != 0) {
throw new Error('invalid ciphertext size (must be segmentSize bytes)');
}
var plaintext = coerceArray(ciphertext, true);
var xorSegment;
for (var i = 0; i < plaintext.length; i += this.segmentSize) {
xorSegment = this._aes.encrypt(this._shiftRegister);
for (var j = 0; j < this.segmentSize; j++) {
plaintext[i + j] ^= xorSegment[j];
}
// Shift the register
copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
}
return plaintext;
}
/**
* Mode Of Operation - Output Feedback (OFB)
*/
var ModeOfOperationOFB = function(key, iv) {
if (!(this instanceof ModeOfOperationOFB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Output Feedback";
this.name = "ofb";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 bytes)');
}
this._lastPrecipher = coerceArray(iv, true);
this._lastPrecipherIndex = 16;
this._aes = new AES(key);
}
ModeOfOperationOFB.prototype.encrypt = function(plaintext) {
var encrypted = coerceArray(plaintext, true);
for (var i = 0; i < encrypted.length; i++) {
if (this._lastPrecipherIndex === 16) {
this._lastPrecipher = this._aes.encrypt(this._lastPrecipher);
this._lastPrecipherIndex = 0;
}
encrypted[i] ^= this._lastPrecipher[this._lastPrecipherIndex++];
}
return encrypted;
}
// Decryption is symetric
ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt;
/**
* Counter object for CTR common mode of operation
*/
var Counter = function(initialValue) {
if (!(this instanceof Counter)) {
throw Error('Counter must be instanitated with `new`');
}
// We allow 0, but anything false-ish uses the default 1
if (initialValue !== 0 && !initialValue) { initialValue = 1; }
if (typeof(initialValue) === 'number') {
this._counter = createArray(16);
this.setValue(initialValue);
} else {
this.setBytes(initialValue);
}
}
Counter.prototype.setValue = function(value) {
if (typeof(value) !== 'number' || parseInt(value) != value) {
throw new Error('invalid counter value (must be an integer)');
}
for (var index = 15; index >= 0; --index) {
this._counter[index] = value % 256;
value = value >> 8;
}
}
Counter.prototype.setBytes = function(bytes) {
bytes = coerceArray(bytes, true);
if (bytes.length != 16) {
throw new Error('invalid counter bytes size (must be 16 bytes)');
}
this._counter = bytes;
};
Counter.prototype.increment = function() {
for (var i = 15; i >= 0; i--) {
if (this._counter[i] === 255) {
this._counter[i] = 0;
} else {
this._counter[i]++;
break;
}
}
}
/**
* Mode Of Operation - Counter (CTR)
*/
var ModeOfOperationCTR = function(key, counter) {
if (!(this instanceof ModeOfOperationCTR)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Counter";
this.name = "ctr";
if (!(counter instanceof Counter)) {
counter = new Counter(counter)
}
this._counter = counter;
this._remainingCounter = null;
this._remainingCounterIndex = 16;
this._aes = new AES(key);
}
ModeOfOperationCTR.prototype.encrypt = function(plaintext) {
var encrypted = coerceArray(plaintext, true);
for (var i = 0; i < encrypted.length; i++) {
if (this._remainingCounterIndex === 16) {
this._remainingCounter = this._aes.encrypt(this._counter._counter);
this._remainingCounterIndex = 0;
this._counter.increment();
}
encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];
}
return encrypted;
}
// Decryption is symetric
ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt;
///////////////////////
// Padding
// See:https://tools.ietf.org/html/rfc2315
function pkcs7pad(data) {
data = coerceArray(data, true);
var padder = 16 - (data.length % 16);
var result = createArray(data.length + padder);
copyArray(data, result);
for (var i = data.length; i < result.length; i++) {
result[i] = padder;
}
return result;
}
function pkcs7strip(data) {
data = coerceArray(data, true);
if (data.length < 16) { throw new Error('PKCS#7 invalid length'); }
var padder = data[data.length - 1];
if (padder > 16) { throw new Error('PKCS#7 padding byte out of range'); }
var length = data.length - padder;
for (var i = 0; i < padder; i++) {
if (data[length + i] !== padder) {
throw new Error('PKCS#7 invalid padding byte');
}
}
var result = createArray(length);
copyArray(data, result, 0, 0, length);
return result;
}
///////////////////////
// Exporting
// The block cipher
var aesjs = {
AES: AES,
Counter: Counter,
ModeOfOperation: {
ecb: ModeOfOperationECB,
cbc: ModeOfOperationCBC,
cfb: ModeOfOperationCFB,
ofb: ModeOfOperationOFB,
ctr: ModeOfOperationCTR
},
utils: {
hex: convertHex,
utf8: convertUtf8
},
padding: {
pkcs7: {
pad: pkcs7pad,
strip: pkcs7strip
}
},
_arrayTest: {
coerceArray: coerceArray,
createArray: createArray,
copyArray: copyArray,
}
};
// node.js
if (true) {
module.exports = aesjs
// RequireJS/AMD
// http://www.requirejs.org/docs/api.html
// https://github.com/amdjs/amdjs-api/wiki/AMD
} else {}
})(this);
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assert = __webpack_require__(11);
var inherits = __webpack_require__(36);
exports.inherits = inherits;
function isSurrogatePair(msg, i) {
if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
return false;
}
if (i < 0 || i + 1 >= msg.length) {
return false;
}
return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
}
function toArray(msg, enc) {
if (Array.isArray(msg))
return msg.slice();
if (!msg)
return [];
var res = [];
if (typeof msg === 'string') {
if (!enc) {
// Inspired by stringToUtf8ByteArray() in closure-library by Google
// https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Apache License 2.0
// https://github.com/google/closure-library/blob/master/LICENSE
var p = 0;
for (var i = 0; i < msg.length; i++) {
var c = msg.charCodeAt(i);
if (c < 128) {
res[p++] = c;
} else if (c < 2048) {
res[p++] = (c >> 6) | 192;
res[p++] = (c & 63) | 128;
} else if (isSurrogatePair(msg, i)) {
c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
res[p++] = (c >> 18) | 240;
res[p++] = ((c >> 12) & 63) | 128;
res[p++] = ((c >> 6) & 63) | 128;
res[p++] = (c & 63) | 128;
} else {
res[p++] = (c >> 12) | 224;
res[p++] = ((c >> 6) & 63) | 128;
res[p++] = (c & 63) | 128;
}
}
} else if (enc === 'hex') {
msg = msg.replace(/[^a-z0-9]+/ig, '');
if (msg.length % 2 !== 0)
msg = '0' + msg;
for (i = 0; i < msg.length; i += 2)
res.push(parseInt(msg[i] + msg[i + 1], 16));
}
} else {
for (i = 0; i < msg.length; i++)
res[i] = msg[i] | 0;
}
return res;
}
exports.toArray = toArray;
function toHex(msg) {
var res = '';
for (var i = 0; i < msg.length; i++)
res += zero2(msg[i].toString(16));
return res;
}
exports.toHex = toHex;
function htonl(w) {
var res = (w >>> 24) |
((w >>> 8) & 0xff00) |
((w << 8) & 0xff0000) |
((w & 0xff) << 24);
return res >>> 0;
}
exports.htonl = htonl;
function toHex32(msg, endian) {
var res = '';
for (var i = 0; i < msg.length; i++) {
var w = msg[i];
if (endian === 'little')
w = htonl(w);
res += zero8(w.toString(16));
}
return res;
}
exports.toHex32 = toHex32;
function zero2(word) {
if (word.length === 1)
return '0' + word;
else
return word;
}
exports.zero2 = zero2;
function zero8(word) {
if (word.length === 7)
return '0' + word;
else if (word.length === 6)
return '00' + word;
else if (word.length === 5)
return '000' + word;
else if (word.length === 4)
return '0000' + word;
else if (word.length === 3)
return '00000' + word;
else if (word.length === 2)
return '000000' + word;
else if (word.length === 1)
return '0000000' + word;
else
return word;
}
exports.zero8 = zero8;
function join32(msg, start, end, endian) {
var len = end - start;
assert(len % 4 === 0);
var res = new Array(len / 4);
for (var i = 0, k = start; i < res.length; i++, k += 4) {
var w;
if (endian === 'big')
w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
else
w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
res[i] = w >>> 0;
}
return res;
}
exports.join32 = join32;
function split32(msg, endian) {
var res = new Array(msg.length * 4);
for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
var m = msg[i];
if (endian === 'big') {
res[k] = m >>> 24;
res[k + 1] = (m >>> 16) & 0xff;
res[k + 2] = (m >>> 8) & 0xff;
res[k + 3] = m & 0xff;
} else {
res[k + 3] = m >>> 24;
res[k + 2] = (m >>> 16) & 0xff;
res[k + 1] = (m >>> 8) & 0xff;
res[k] = m & 0xff;
}
}
return res;
}
exports.split32 = split32;
function rotr32(w, b) {
return (w >>> b) | (w << (32 - b));
}
exports.rotr32 = rotr32;
function rotl32(w, b) {
return (w << b) | (w >>> (32 - b));
}
exports.rotl32 = rotl32;
function sum32(a, b) {
return (a + b) >>> 0;
}
exports.sum32 = sum32;
function sum32_3(a, b, c) {
return (a + b + c) >>> 0;
}
exports.sum32_3 = sum32_3;
function sum32_4(a, b, c, d) {
return (a + b + c + d) >>> 0;
}
exports.sum32_4 = sum32_4;
function sum32_5(a, b, c, d, e) {
return (a + b + c + d + e) >>> 0;
}
exports.sum32_5 = sum32_5;
function sum64(buf, pos, ah, al) {
var bh = buf[pos];
var bl = buf[pos + 1];
var lo = (al + bl) >>> 0;
var hi = (lo < al ? 1 : 0) + ah + bh;
buf[pos] = hi >>> 0;
buf[pos + 1] = lo;
}
exports.sum64 = sum64;
function sum64_hi(ah, al, bh, bl) {
var lo = (al + bl) >>> 0;
var hi = (lo < al ? 1 : 0) + ah + bh;
return hi >>> 0;
}
exports.sum64_hi = sum64_hi;
function sum64_lo(ah, al, bh, bl) {
var lo = al + bl;
return lo >>> 0;
}
exports.sum64_lo = sum64_lo;
function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
var carry = 0;
var lo = al;
lo = (lo + bl) >>> 0;
carry += lo < al ? 1 : 0;
lo = (lo + cl) >>> 0;
carry += lo < cl ? 1 : 0;
lo = (lo + dl) >>> 0;
carry += lo < dl ? 1 : 0;
var hi = ah + bh + ch + dh + carry;
return hi >>> 0;
}
exports.sum64_4_hi = sum64_4_hi;
function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
var lo = al + bl + cl + dl;
return lo >>> 0;
}
exports.sum64_4_lo = sum64_4_lo;
function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
var carry = 0;
var lo = al;
lo = (lo + bl) >>> 0;
carry += lo < al ? 1 : 0;
lo = (lo + cl) >>> 0;
carry += lo < cl ? 1 : 0;
lo = (lo + dl) >>> 0;
carry += lo < dl ? 1 : 0;
lo = (lo + el) >>> 0;
carry += lo < el ? 1 : 0;
var hi = ah + bh + ch + dh + eh + carry;
return hi >>> 0;
}
exports.sum64_5_hi = sum64_5_hi;
function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
var lo = al + bl + cl + dl + el;
return lo >>> 0;
}
exports.sum64_5_lo = sum64_5_lo;
function rotr64_hi(ah, al, num) {
var r = (al << (32 - num)) | (ah >>> num);
return r >>> 0;
}
exports.rotr64_hi = rotr64_hi;
function rotr64_lo(ah, al, num) {
var r = (ah << (32 - num)) | (al >>> num);
return r >>> 0;
}
exports.rotr64_lo = rotr64_lo;
function shr64_hi(ah, al, num) {
return ah >>> num;
}
exports.shr64_hi = shr64_hi;
function shr64_lo(ah, al, num) {
var r = (ah << (32 - num)) | (al >>> num);
return r >>> 0;
}
exports.shr64_lo = shr64_lo;
/***/ }),
/* 7 */,
/* 8 */,
/* 9 */,
/* 10 */,
/* 11 */
/***/ (function(module, exports) {
module.exports = assert;
function assert(val, msg) {
if (!val)
throw new Error(msg || 'Assertion failed');
}
assert.equal = function assertEqual(l, r, msg) {
if (l != r)
throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
};
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var assert = __webpack_require__(11);
function BlockHash() {
this.pending = null;
this.pendingTotal = 0;
this.blockSize = this.constructor.blockSize;
this.outSize = this.constructor.outSize;
this.hmacStrength = this.constructor.hmacStrength;
this.padLength = this.constructor.padLength / 8;
this.endian = 'big';
this._delta8 = this.blockSize / 8;
this._delta32 = this.blockSize / 32;
}
exports.BlockHash = BlockHash;
BlockHash.prototype.update = function update(msg, enc) {
// Convert message to array, pad it, and join into 32bit blocks
msg = utils.toArray(msg, enc);
if (!this.pending)
this.pending = msg;
else
this.pending = this.pending.concat(msg);
this.pendingTotal += msg.length;
// Enough data, try updating
if (this.pending.length >= this._delta8) {
msg = this.pending;
// Process pending data in blocks
var r = msg.length % this._delta8;
this.pending = msg.slice(msg.length - r, msg.length);
if (this.pending.length === 0)
this.pending = null;
msg = utils.join32(msg, 0, msg.length - r, this.endian);
for (var i = 0; i < msg.length; i += this._delta32)
this._update(msg, i, i + this._delta32);
}
return this;
};
BlockHash.prototype.digest = function digest(enc) {
this.update(this._pad());
assert(this.pending === null);
return this._digest(enc);
};
BlockHash.prototype._pad = function pad() {
var len = this.pendingTotal;
var bytes = this._delta8;
var k = bytes - ((len + this.padLength) % bytes);
var res = new Array(k + this.padLength);
res[0] = 0x80;
for (var i = 1; i < k; i++)
res[i] = 0;
// Append length
len <<= 3;
if (this.endian === 'big') {
for (var t = 8; t < this.padLength; t++)
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
res[i++] = (len >>> 24) & 0xff;
res[i++] = (len >>> 16) & 0xff;
res[i++] = (len >>> 8) & 0xff;
res[i++] = len & 0xff;
} else {
res[i++] = len & 0xff;
res[i++] = (len >>> 8) & 0xff;
res[i++] = (len >>> 16) & 0xff;
res[i++] = (len >>> 24) & 0xff;
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
for (t = 8; t < this.padLength; t++)
res[i++] = 0;
}
return res;
};
/***/ }),
/* 13 */
/***/ (function(module, exports) {
module.exports = require("fs/promises");
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;/**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the semantic version number. */
var VERSION = '4.17.21';
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Error message constants. */
var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
FUNC_ERROR_TEXT = 'Expected a function',
INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used as default options for `_.truncate`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_FILTER_FLAG = 1,
LAZY_MAP_FLAG = 2,
LAZY_WHILE_FLAG = 3;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_SAFE_INTEGER = 9007199254740991,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
domExcTag = '[object DOMException]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]',
weakSetTag = '[object WeakSet]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match HTML entities and HTML characters. */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
reUnescapedHtml = /[&<>"']/g,
reHasEscapedHtml = RegExp(reEscapedHtml.source),
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/** Used to match template delimiters. */
var reEscape = /<%-([\s\S]+?)%>/g,
reEvaluate = /<%([\s\S]+?)%>/g,
reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
reHasRegExpChar = RegExp(reRegExpChar.source);
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/** Used to match words composed of alphanumeric characters. */
var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
/**
* Used to validate the `validate` option in `_.template` variable.
*
* Forbids characters which could potentially change the meaning of the function argument definition:
* - "()," (modification of function parameters)
* - "=" (default value)
* - "[]{}" (destructuring of function parameters)
* - "/" (beginning of a comment)
* - whitespace
*/
var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Used to match
* [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to match Latin Unicode letters (excluding mathematical operators). */
var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsPunctuationRange = '\\u2000-\\u206f',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]",
rsAstral = '[' + rsAstralRange + ']',
rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match apostrophes. */
var reApos = RegExp(rsApos, 'g');
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
*/
var reComboMark = RegExp(rsCombo, 'g');
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/** Used to match complex or compound words. */
var reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
rsUpper + '+' + rsOptContrUpper,
rsOrdUpper,
rsOrdLower,
rsDigits,
rsEmoji
].join('|'), 'g');
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/** Used to detect strings that need a more robust regexp to match words. */
var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/** Used to assign default `context` object properties. */
var contextProps = [
'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
'_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
];
/** Used to make template sourceURLs easier to identify. */
var templateCounter = -1;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/** Used to map Latin Unicode letters to basic Latin letters. */
var deburredLetters = {
// Latin-1 Supplement block.
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss',
// Latin Extended-A block.
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
'\u0132': 'IJ', '\u0133': 'ij',
'\u0152': 'Oe', '\u0153': 'oe',
'\u0149': "'n", '\u017f': 's'
};
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
/** Used to map HTML entities to characters. */
var htmlUnescapes = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'"
};
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Built-in method references without a dependency on `root`. */
var freeParseFloat = parseFloat,
freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = true && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
nodeIsDate = nodeUtil && nodeUtil.isDate,
nodeIsMap = nodeUtil && nodeUtil.isMap,
nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
nodeIsSet = nodeUtil && nodeUtil.isSet,
nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/*--------------------------------------------------------------------------*/
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/**
* A specialized version of `baseAggregator` for arrays.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function arrayAggregator(array, setter, iteratee, accumulator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
var value = array[index];
setter(accumulator, value, iteratee(value), array);
}
return accumulator;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.forEachRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEachRight(array, iteratee) {
var length = array == null ? 0 : array.length;
while (length--) {
if (iteratee(array[length], length, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.every` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* A specialized version of `_.reduceRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the last element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduceRight(array, iteratee, accumulator, initAccum) {
var length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[--length];
}
while (length--) {
accumulator = iteratee(accumulator, array[length], length, array);
}
return accumulator;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
var asciiSize = baseProperty('length');
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
/**
* Splits an ASCII `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function asciiWords(string) {
return string.match(reAsciiWord) || [];
}
/**
* The base implementation of methods like `_.findKey` and `_.findLastKey`,
* without support for iteratee shorthands, which iterates over `collection`
* using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFindKey(collection, predicate, eachFunc) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = key;
return false;
}
});
return result;
}
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
/**
* This function is like `baseIndexOf` except that it accepts a comparator.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @param {Function} comparator The comparator invoked per element.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOfWith(array, value, fromIndex, comparator) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (comparator(array[index], value)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
/**
* The base implementation of `_.mean` and `_.meanBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the mean.
*/
function baseMean(array, iteratee) {
var length = array == null ? 0 : array.length;
return length ? (baseSum(array, iteratee) / length) : NAN;
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` corresponding to the property names of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the key-value pairs.
*/
function baseToPairs(object, props) {
return arrayMap(props, function(key) {
return [key, object[key]];
});
}
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
/**
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
var deburrLetter = basePropertyOf(deburredLetters);
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
var escapeHtmlChar = basePropertyOf(htmlEscapes);
/**
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
/**
* Checks if `string` contains a word composed of Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a word is found, else `false`.
*/
function hasUnicodeWord(string) {
return reHasUnicodeWord.test(string);
}
/**
* Converts `iterator` to an array.
*
* @private
* @param {Object} iterator The iterator to convert.
* @returns {Array} Returns the converted array.
*/
function iteratorToArray(iterator) {
var data,
result = [];
while (!(data = iterator.next()).done) {
result.push(data.value);
}
return result;
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/**
* Converts `set` to its value-value pairs.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the value-value pairs.
*/
function setToPairs(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = [value, value];
});
return result;
}
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* A specialized version of `_.lastIndexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictLastIndexOf(array, value, fromIndex) {
var index = fromIndex + 1;
while (index--) {
if (array[index] === value) {
return index;
}
}
return index;
}
/**
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
*/
function stringSize(string) {
return hasUnicode(string)
? unicodeSize(string)
: asciiSize(string);
}
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
/**
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
/**
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
function unicodeSize(string) {
var result = reUnicode.lastIndex = 0;
while (reUnicode.test(string)) {
++result;
}
return result;
}
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
/**
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function unicodeWords(string) {
return string.match(reUnicodeWord) || [];
}
/*--------------------------------------------------------------------------*/
/**
* Create a new pristine `lodash` function using the `context` object.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Util
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
*
* _.mixin({ 'foo': _.constant('foo') });
*
* var lodash = _.runInContext();
* lodash.mixin({ 'bar': lodash.constant('bar') });
*
* _.isFunction(_.foo);
* // => true
* _.isFunction(_.bar);
* // => false
*
* lodash.isFunction(lodash.foo);
* // => false
* lodash.isFunction(lodash.bar);
* // => true
*
* // Create a suped-up `defer` in Node.js.
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
*/
var runInContext = (function runInContext(context) {
context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));
/** Built-in constructor references. */
var Array = context.Array,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = context['__core-js_shared__'];
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = root._;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? context.Buffer : undefined,
Symbol = context.Symbol,
Uint8Array = context.Uint8Array,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
getPrototype = overArg(Object.getPrototypeOf, Object),
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice,
spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
symIterator = Symbol ? Symbol.iterator : undefined,
symToStringTag = Symbol ? Symbol.toStringTag : undefined;
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
/** Mocked built-ins. */
var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
ctxNow = Date && Date.now !== root.Date.now && Date.now,
ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeFloor = Math.floor,
nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeIsFinite = context.isFinite,
nativeJoin = arrayProto.join,
nativeKeys = overArg(Object.keys, Object),
nativeMax = Math.max,
nativeMin = Math.min,
nativeNow = Date.now,
nativeParseInt = context.parseInt,
nativeRandom = Math.random,
nativeReverse = arrayProto.reverse;
/* Built-in method references that are verified to be native. */
var DataView = getNative(context, 'DataView'),
Map = getNative(context, 'Map'),
Promise = getNative(context, 'Promise'),
Set = getNative(context, 'Set'),
WeakMap = getNative(context, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
/** Used to lookup unminified function names. */
var realNames = {};
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB) as well as ES2015 template strings. Change the
* following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type {Object}
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'escape': reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'evaluate': reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type {string}
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type {Object}
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type {Function}
*/
'_': lodash
}
};
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
/*------------------------------------------------------------------------*/
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
/**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/
function lazyClone() {
var result = new LazyWrapper(this.__wrapped__);
result.__actions__ = copyArray(this.__actions__);
result.__dir__ = this.__dir__;
result.__filtered__ = this.__filtered__;
result.__iteratees__ = copyArray(this.__iteratees__);
result.__takeCount__ = this.__takeCount__;
result.__views__ = copyArray(this.__views__);
return result;
}
/**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/
function lazyReverse() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1;
result.__filtered__ = true;
} else {
result = this.clone();
result.__dir__ *= -1;
}
return result;
}
/**
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
*/
function lazyValue() {
var array = this.__wrapped__.value(),
dir = this.__dir__,
isArr = isArray(array),
isRight = dir < 0,
arrLength = isArr ? array.length : 0,
view = getView(0, arrLength, this.__views__),
start = view.start,
end = view.end,
length = end - start,
index = isRight ? end : (start - 1),
iteratees = this.__iteratees__,
iterLength = iteratees.length,
resIndex = 0,
takeCount = nativeMin(length, this.__takeCount__);
if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
return baseWrapperValue(array, this.__actions__);
}
var result = [];
outer:
while (length-- && resIndex < takeCount) {
index += dir;
var iterIndex = -1,
value = array[index];
while (++iterIndex < iterLength) {
var data = iteratees[iterIndex],
iteratee = data.iteratee,
type = data.type,
computed = iteratee(value);
if (type == LAZY_MAP_FLAG) {
value = computed;
} else if (!computed) {
if (type == LAZY_FILTER_FLAG) {
continue outer;
} else {
break outer;
}
}
}
result[resIndex++] = value;
}
return result;
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
/*------------------------------------------------------------------------*/
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/*------------------------------------------------------------------------*/
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/*------------------------------------------------------------------------*/
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/*------------------------------------------------------------------------*/
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/*------------------------------------------------------------------------*/
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/*------------------------------------------------------------------------*/
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/**
* A specialized version of `_.sample` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @returns {*} Returns the random element.
*/
function arraySample(array) {
var length = array.length;
return length ? array[baseRandom(0, length - 1)] : undefined;
}
/**
* A specialized version of `_.sampleSize` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function arraySampleSize(array, n) {
return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
}
/**
* A specialized version of `_.shuffle` for arrays.
*
* @private
* @param {Array} array The array to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function arrayShuffle(array) {
return shuffleSelf(copyArray(array));
}
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Aggregates elements of `collection` on `accumulator` with keys transformed
* by `iteratee` and values set by `setter`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function baseAggregator(collection, setter, iteratee, accumulator) {
baseEach(collection, function(value, key, collection) {
setter(accumulator, value, iteratee(value), collection);
});
return accumulator;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
/**
* The base implementation of `_.at` without support for individual paths.
*
* @private
* @param {Object} object The object to iterate over.
* @param {string[]} paths The property paths to pick.
* @returns {Array} Returns the picked elements.
*/
function baseAt(object, paths) {
var index = -1,
length = paths.length,
result = Array(length),
skip = object == null;
while (++index < length) {
result[index] = skip ? undefined : get(object, paths[index]);
}
return result;
}
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
/**
* The base implementation of `_.conforms` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
*/
function baseConforms(source) {
var props = keys(source);
return function(object) {
return baseConformsTo(object, source, props);
};
}
/**
* The base implementation of `_.conformsTo` which accepts `props` to check.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
*/
function baseConformsTo(object, source, props) {
var length = props.length;
if (object == null) {
return !length;
}
object = Object(object);
while (length--) {
var key = props[length],
predicate = source[key],
value = object[key];
if ((value === undefined && !(key in object)) || !predicate(value)) {
return false;
}
}
return true;
}
/**
* The base implementation of `_.delay` and `_.defer` which accepts `args`
* to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Array} args The arguments to provide to `func`.
* @returns {number|Object} Returns the timer id or timeout object.
*/
function baseDelay(func, wait, args) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* The base implementation of `_.forEachRight` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEachRight = createBaseEach(baseForOwnRight, true);
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
/**
* The base implementation of methods like `_.max` and `_.min` which accepts a
* `comparator` to determine the extremum value.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The iteratee invoked per iteration.
* @param {Function} comparator The comparator used to compare values.
* @returns {*} Returns the extremum value.
*/
function baseExtremum(array, iteratee, comparator) {
var index = -1,
length = array.length;
while (++index < length) {
var value = array[index],
current = iteratee(value);
if (current != null && (computed === undefined
? (current === current && !isSymbol(current))
: comparator(current, computed)
)) {
var computed = current,
result = value;
}
}
return result;
}
/**
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
*/
function baseFill(array, value, start, end) {
var length = array.length;
start = toInteger(start);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (end === undefined || end > length) ? length : toInteger(end);
if (end < 0) {
end += length;
}
end = start > end ? 0 : toLength(end);
while (start < end) {
array[start++] = value;
}
return array;
}
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseForRight = createBaseFor(true);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.forOwnRight` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
return object && baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from `props`.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the function names.
*/
function baseFunctions(object, props) {
return arrayFilter(props, function(key) {
return isFunction(object[key]);
});
}
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* The base implementation of `_.gt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
*/
function baseGt(value, other) {
return value > other;
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
/**
* The base implementation of `_.inRange` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to check.
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
*/
function baseInRange(number, start, end) {
return number >= nativeMin(start, end) && number < nativeMax(start, end);
}
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
/**
* The base implementation of `_.invoke` without support for individual
* method arguments.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {Array} args The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
*/
function baseInvoke(object, path, args) {
path = castPath(path, object);
object = parent(object, path);
var func = object == null ? object : object[toKey(last(path))];
return func == null ? undefined : apply(func, object, args);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isArrayBuffer` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
*/
function baseIsArrayBuffer(value) {
return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
}
/**
* The base implementation of `_.isDate` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
*/
function baseIsDate(value) {
return isObjectLike(value) && baseGetTag(value) == dateTag;
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag(value) == mapTag;
}
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
*/
function baseIsRegExp(value) {
return isObjectLike(value) && baseGetTag(value) == regexpTag;
}
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag(value) == setTag;
}
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.lt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
*/
function baseLt(value, other) {
return value < other;
}
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
stack || (stack = new Stack);
if (isObject(srcValue)) {
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = safeGet(object, key),
srcValue = safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || isFunction(objValue)) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
/**
* The base implementation of `_.nth` which doesn't coerce arguments.
*
* @private
* @param {Array} array The array to query.
* @param {number} n The index of the element to return.
* @returns {*} Returns the nth element of `array`.
*/
function baseNth(array, n) {
var length = array.length;
if (!length) {
return;
}
n += n < 0 ? length : 0;
return isIndex(n, length) ? array[n] : undefined;
}
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
if (iteratees.length) {
iteratees = arrayMap(iteratees, function(iteratee) {
if (isArray(iteratee)) {
return function(value) {
return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
}
}
return iteratee;
});
} else {
iteratees = [identity];
}
var index = -1;
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
/**
* The base implementation of `_.pullAllBy` without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
*/
function basePullAll(array, values, iteratee, comparator) {
var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
index = -1,
length = values.length,
seen = array;
if (array === values) {
values = copyArray(values);
}
if (iteratee) {
seen = arrayMap(array, baseUnary(iteratee));
}
while (++index < length) {
var fromIndex = 0,
value = values[index],
computed = iteratee ? iteratee(value) : value;
while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
if (seen !== array) {
splice.call(seen, fromIndex, 1);
}
splice.call(array, fromIndex, 1);
}
}
return array;
}
/**
* The base implementation of `_.pullAt` without support for individual
* indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
*/
function basePullAt(array, indexes) {
var length = array ? indexes.length : 0,
lastIndex = length - 1;
while (length--) {
var index = indexes[length];
if (length == lastIndex || index !== previous) {
var previous = index;
if (isIndex(index)) {
splice.call(array, index, 1);
} else {
baseUnset(array, index);
}
}
}
return array;
}
/**
* The base implementation of `_.random` without support for returning
* floating-point numbers.
*
* @private
* @param {number} lower The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the random number.
*/
function baseRandom(lower, upper) {
return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
/**
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
*/
function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = nativeFloor(n / 2);
if (n) {
string += string;
}
} while (n);
return result;
}
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
/**
* The base implementation of `_.sample`.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
*/
function baseSample(collection) {
return arraySample(values(collection));
}
/**
* The base implementation of `_.sampleSize` without param guards.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function baseSampleSize(collection, n) {
var array = values(collection);
return shuffleSelf(array, baseClamp(n, 0, array.length));
}
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
/**
* The base implementation of `_.shuffle`.
*
* @private
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function baseShuffle(collection) {
return shuffleSelf(values(collection));
}
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
/**
* The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
* performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndex(array, value, retHighest) {
var low = 0,
high = array == null ? low : array.length;
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
while (low < high) {
var mid = (low + high) >>> 1,
computed = array[mid];
if (computed !== null && !isSymbol(computed) &&
(retHighest ? (computed <= value) : (computed < value))) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
return baseSortedIndexBy(array, value, identity, retHighest);
}
/**
* The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
* which invokes `iteratee` for `value` and each element of `array` to compute
* their sort ranking. The iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The iteratee invoked per element.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndexBy(array, value, iteratee, retHighest) {
var low = 0,
high = array == null ? 0 : array.length;
if (high === 0) {
return 0;
}
value = iteratee(value);
var valIsNaN = value !== value,
valIsNull = value === null,
valIsSymbol = isSymbol(value),
valIsUndefined = value === undefined;
while (low < high) {
var mid = nativeFloor((low + high) / 2),
computed = iteratee(array[mid]),
othIsDefined = computed !== undefined,
othIsNull = computed === null,
othIsReflexive = computed === computed,
othIsSymbol = isSymbol(computed);
if (valIsNaN) {
var setLow = retHighest || othIsReflexive;
} else if (valIsUndefined) {
setLow = othIsReflexive && (retHighest || othIsDefined);
} else if (valIsNull) {
setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
} else if (valIsSymbol) {
setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
} else if (othIsNull || othIsSymbol) {
setLow = false;
} else {
setLow = retHighest ? (computed <= value) : (computed < value);
}
if (setLow) {
low = mid + 1;
} else {
high = mid;
}
}
return nativeMin(high, MAX_ARRAY_INDEX);
}
/**
* The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseSortedUniq(array, iteratee) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
if (!index || !eq(computed, seen)) {
var seen = computed;
result[resIndex++] = value === 0 ? 0 : value;
}
}
return result;
}
/**
* The base implementation of `_.toNumber` which doesn't ensure correct
* conversions of binary, hexadecimal, or octal string values.
*
* @private
* @param {*} value The value to process.
* @returns {number} Returns the number.
*/
function baseToNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
return +value;
}
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseUniq(array, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
length = array.length,
isCommon = true,
result = [],
seen = result;
if (comparator) {
isCommon = false;
includes = arrayIncludesWith;
}
else if (length >= LARGE_ARRAY_SIZE) {
var set = iteratee ? null : createSet(array);
if (set) {
return setToArray(set);
}
isCommon = false;
includes = cacheHas;
seen = new SetCache;
}
else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
/**
* The base implementation of `_.update`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to update.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseUpdate(object, path, updater, customizer) {
return baseSet(object, path, updater(baseGet(object, path)), customizer);
}
/**
* The base implementation of methods like `_.dropWhile` and `_.takeWhile`
* without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the slice of `array`.
*/
function baseWhile(array, predicate, isDrop, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length) &&
predicate(array[index], index, array)) {}
return isDrop
? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
: baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
}
/**
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to perform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
*/
function baseWrapperValue(value, actions) {
var result = value;
if (result instanceof LazyWrapper) {
result = result.value();
}
return arrayReduce(actions, function(result, action) {
return action.func.apply(action.thisArg, arrayPush([result], action.args));
}, result);
}
/**
* The base implementation of methods like `_.xor`, without support for
* iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of values.
*/
function baseXor(arrays, iteratee, comparator) {
var length = arrays.length;
if (length < 2) {
return length ? baseUniq(arrays[0]) : [];
}
var index = -1,
result = Array(length);
while (++index < length) {
var array = arrays[index],
othIndex = -1;
while (++othIndex < length) {
if (othIndex != index) {
result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
}
}
}
return baseUniq(baseFlatten(result, 1), iteratee, comparator);
}
/**
* This base implementation of `_.zipObject` which assigns values using `assignFunc`.
*
* @private
* @param {Array} props The property identifiers.
* @param {Array} values The property values.
* @param {Function} assignFunc The function to assign values.
* @returns {Object} Returns the new object.
*/
function baseZipObject(props, values, assignFunc) {
var index = -1,
length = props.length,
valsLength = values.length,
result = {};
while (++index < length) {
var value = index < valsLength ? values[index] : undefined;
assignFunc(result, props[index], value);
}
return result;
}
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
/**
* A `baseRest` alias which can be replaced with `identity` by module
* replacement plugins.
*
* @private
* @type {Function}
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
var castRest = baseRest;
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
/**
* A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
*
* @private
* @param {number|Object} id The timer id or timeout object of the timer to clear.
*/
var clearTimeout = ctxClearTimeout || function(id) {
return root.clearTimeout(id);
};
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee, 2), accumulator);
};
}
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
/**
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
*/
function createCaseFirst(methodName) {
return function(string) {
string = toString(string);
var strSymbols = hasUnicode(string)
? stringToArray(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
};
}
/**
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder(callback) {
return function(string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
};
}
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = getIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
return flatRest(function(funcs) {
var length = funcs.length,
index = length,
prereq = LodashWrapper.prototype.thru;
if (fromRight) {
funcs.reverse();
}
while (index--) {
var func = funcs[index];
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
var wrapper = new LodashWrapper([], true);
}
}
index = wrapper ? index : length;
while (++index < length) {
func = funcs[index];
var funcName = getFuncName(func),
data = funcName == 'wrapper' ? getData(func) : undefined;
if (data && isLaziable(data[0]) &&
data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
!data[4].length && data[9] == 1
) {
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
} else {
wrapper = (func.length == 1 && isLaziable(func))
? wrapper[funcName]()
: wrapper.thru(func);
}
}
return function() {
var args = arguments,
value = args[0];
if (wrapper && args.length == 1 && isArray(value)) {
return wrapper.plant(value).value();
}
var index = 0,
result = length ? funcs[index].apply(this, args) : value;
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
});
}
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
/**
* Creates a function that performs a mathematical operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @param {number} [defaultValue] The value used for `undefined` arguments.
* @returns {Function} Returns the new mathematical operation function.
*/
function createMathOperation(operator, defaultValue) {
return function(value, other) {
var result;
if (value === undefined && other === undefined) {
return defaultValue;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
};
}
/**
* Creates a function like `_.over`.
*
* @private
* @param {Function} arrayFunc The function to iterate over iteratees.
* @returns {Function} Returns the new over function.
*/
function createOver(arrayFunc) {
return flatRest(function(iteratees) {
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
return baseRest(function(args) {
var thisArg = this;
return arrayFunc(iteratees, function(iteratee) {
return apply(iteratee, thisArg, args);
});
});
});
}
/**
* Creates the padding for `string` based on `length`. The `chars` string
* is truncated if the number of characters exceeds `length`.
*
* @private
* @param {number} length The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padding for `string`.
*/
function createPadding(length, chars) {
chars = chars === undefined ? ' ' : baseToString(chars);
var charsLength = chars.length;
if (charsLength < 2) {
return charsLength ? baseRepeat(chars, length) : chars;
}
var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
return hasUnicode(chars)
? castSlice(stringToArray(result), 0, length).join('')
: result.slice(0, length);
}
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
/**
* Creates a function that performs a relational operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @returns {Function} Returns the new relational operation function.
*/
function createRelationalOperation(operator) {
return function(value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
};
}
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
/**
* Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
* @returns {Function} Returns the new round function.
*/
function createRound(methodName) {
var func = Math[methodName];
return function(number, precision) {
number = toNumber(number);
precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
if (precision && nativeIsFinite(number)) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
};
}
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/
var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
return new Set(values);
};
/**
* Creates a `_.toPairs` or `_.toPairsIn` function.
*
* @private
* @param {Function} keysFunc The function to get the keys of a given object.
* @returns {Function} Returns the new pairs function.
*/
function createToPairs(keysFunc) {
return function(object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
};
}
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
/**
* Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
* objects into destination objects that are passed thru.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to merge.
* @param {Object} object The parent object of `objValue`.
* @param {Object} source The parent object of `srcValue`.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
* @returns {*} Returns the value to assign.
*/
function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
if (isObject(objValue) && isObject(srcValue)) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, objValue);
baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
stack['delete'](srcValue);
}
return objValue;
}
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Check that cyclic values are equal.
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Check that cyclic values are equal.
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
return object.placeholder;
}
/**
* Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
* this function returns the custom method, otherwise it returns `baseIteratee`.
* If arguments are provided, the chosen function is invoked with them and
* its result is returned.
*
* @private
* @param {*} [value] The value to convert to an iteratee.
* @param {number} [arity] The arity of the created iteratee.
* @returns {Function} Returns the chosen function or its result.
*/
function getIteratee() {
var result = lodash.iteratee || iteratee;
result = result === iteratee ? baseIteratee : result;
return arguments.length ? result(arguments[0], arguments[1]) : result;
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms.length;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return new Ctor;
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return new Ctor;
case symbolTag:
return cloneSymbol(object);
}
}
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/**
* Checks if `func` is capable of being masked.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `func` is maskable, else `false`.
*/
var isMaskable = coreJsData ? isFunction : stubFalse;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
/**
* A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @returns {number|Object} Returns the timer id or timeout object.
*/
var setTimeout = ctxSetTimeout || function(func, wait) {
return root.setTimeout(func, wait);
};
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
/**
* A specialized version of `_.shuffle` which mutates and sets the size of `array`.
*
* @private
* @param {Array} array The array to shuffle.
* @param {number} [size=array.length] The size of `array`.
* @returns {Array} Returns `array`.
*/
function shuffleSelf(array, size) {
var index = -1,
length = array.length,
lastIndex = length - 1;
size = size === undefined ? length : size;
while (++index < size) {
var rand = baseRandom(index, lastIndex),
value = array[rand];
array[rand] = array[index];
array[index] = value;
}
array.length = size;
return array;
}
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the new array of chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
size = nativeMax(toInteger(size), 0);
}
var length = array == null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0,
resIndex = 0,
result = Array(nativeCeil(length / size));
while (index < length) {
result[resIndex++] = baseSlice(array, index, (index += size));
}
return result;
}
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
/**
* Creates a new array concatenating `array` with any additional arrays
* and/or values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to concatenate.
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var other = _.concat(array, 2, [3], [[4]]);
*
* console.log(other);
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
*/
function concat() {
var length = arguments.length;
if (!length) {
return [];
}
var args = Array(length - 1),
array = arguments[0],
index = length;
while (index--) {
args[index - 1] = arguments[index];
}
return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
}
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
/**
* This method is like `_.difference` except that it accepts `iteratee` which
* is invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* **Note:** Unlike `_.pullAllBy`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2]
*
* // The `_.property` iteratee shorthand.
* _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var differenceBy = baseRest(function(array, values) {
var iteratee = last(values);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.difference` except that it accepts `comparator`
* which is invoked to compare elements of `array` to `values`. The order and
* references of result values are determined by the first array. The comparator
* is invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.pullAllWith`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
*
* _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
* // => [{ 'x': 2, 'y': 1 }]
*/
var differenceWith = baseRest(function(array, values) {
var comparator = last(values);
if (isArrayLikeObject(comparator)) {
comparator = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
: [];
});
/**
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function drop(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function dropRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.dropRightWhile(users, function(o) { return !o.active; });
* // => objects for ['barney']
*
* // The `_.matches` iteratee shorthand.
* _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['barney', 'fred']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropRightWhile(users, ['active', false]);
* // => objects for ['barney']
*
* // The `_.property` iteratee shorthand.
* _.dropRightWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true, true)
: [];
}
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.dropWhile(users, function(o) { return !o.active; });
* // => objects for ['pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.dropWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropWhile(users, ['active', false]);
* // => objects for ['pebbles']
*
* // The `_.property` iteratee shorthand.
* _.dropWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true)
: [];
}
/**
* Fills elements of `array` with `value` from `start` up to, but not
* including, `end`.
*
* **Note:** This method mutates `array`.
*
* @static
* @memberOf _
* @since 3.2.0
* @category Array
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8, 10], '*', 1, 3);
* // => [4, '*', '*', 10]
*/
function fill(array, value, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
start = 0;
end = length;
}
return baseFill(array, value, start, end);
}
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, getIteratee(predicate, 3), index);
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length - 1;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = fromIndex < 0
? nativeMax(length + index, 0)
: nativeMin(index, length - 1);
}
return baseFindIndex(array, getIteratee(predicate, 3), index, true);
}
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
/**
* Recursively flattens `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
*/
function flattenDeep(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, INFINITY) : [];
}
/**
* Recursively flatten `array` up to `depth` times.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Array
* @param {Array} array The array to flatten.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* var array = [1, [2, [3, [4]], 5]];
*
* _.flattenDepth(array, 1);
* // => [1, 2, [3, [4]], 5]
*
* _.flattenDepth(array, 2);
* // => [1, 2, 3, [4], 5]
*/
function flattenDepth(array, depth) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(array, depth);
}
/**
* The inverse of `_.toPairs`; this method returns an object composed
* from key-value `pairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* _.fromPairs([['a', 1], ['b', 2]]);
* // => { 'a': 1, 'b': 2 }
*/
function fromPairs(pairs) {
var index = -1,
length = pairs == null ? 0 : pairs.length,
result = {};
while (++index < length) {
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
}
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias first
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.head([1, 2, 3]);
* // => 1
*
* _.head([]);
* // => undefined
*/
function head(array) {
return (array && array.length) ? array[0] : undefined;
}
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
/**
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*/
function initial(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 0, -1) : [];
}
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
/**
* This method is like `_.intersection` except that it accepts `iteratee`
* which is invoked for each element of each `arrays` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [2.1]
*
* // The `_.property` iteratee shorthand.
* _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }]
*/
var intersectionBy = baseRest(function(arrays) {
var iteratee = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
if (iteratee === last(mapped)) {
iteratee = undefined;
} else {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.intersection` except that it accepts `comparator`
* which is invoked to compare elements of `arrays`. The order and references
* of result values are determined by the first array. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.intersectionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }]
*/
var intersectionWith = baseRest(function(arrays) {
var comparator = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
comparator = typeof comparator == 'function' ? comparator : undefined;
if (comparator) {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, undefined, comparator)
: [];
});
/**
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
*/
function join(array, separator) {
return array == null ? '' : nativeJoin.call(array, separator);
}
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
}
return value === value
? strictLastIndexOf(array, value, index)
: baseFindIndex(array, baseIsNaN, index, true);
}
/**
* Gets the element at index `n` of `array`. If `n` is negative, the nth
* element from the end is returned.
*
* @static
* @memberOf _
* @since 4.11.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=0] The index of the element to return.
* @returns {*} Returns the nth element of `array`.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
*
* _.nth(array, 1);
* // => 'b'
*
* _.nth(array, -2);
* // => 'c';
*/
function nth(array, n) {
return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
}
/**
* Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
* to remove elements from an array by predicate.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pull(array, 'a', 'c');
* console.log(array);
* // => ['b', 'b']
*/
var pull = baseRest(pullAll);
/**
* This method is like `_.pull` except that it accepts an array of values to remove.
*
* **Note:** Unlike `_.difference`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pullAll(array, ['a', 'c']);
* console.log(array);
* // => ['b', 'b']
*/
function pullAll(array, values) {
return (array && array.length && values && values.length)
? basePullAll(array, values)
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
*/
function pullAllBy(array, values, iteratee) {
return (array && array.length && values && values.length)
? basePullAll(array, values, getIteratee(iteratee, 2))
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `comparator` which
* is invoked to compare elements of `array` to `values`. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.differenceWith`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
*
* _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
* console.log(array);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
*/
function pullAllWith(array, values, comparator) {
return (array && array.length && values && values.length)
? basePullAll(array, values, undefined, comparator)
: array;
}
/**
* Removes elements from `array` corresponding to `indexes` and returns an
* array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
* var pulled = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => ['a', 'c']
*
* console.log(pulled);
* // => ['b', 'd']
*/
var pullAt = flatRest(function(array, indexes) {
var length = array == null ? 0 : array.length,
result = baseAt(array, indexes);
basePullAt(array, arrayMap(indexes, function(index) {
return isIndex(index, length) ? +index : index;
}).sort(compareAscending));
return result;
});
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
* to pull elements from an array by value.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = getIteratee(predicate, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}
/**
* Reverses `array` so that the first element becomes the last, the second
* element becomes the second to last, and so on.
*
* **Note:** This method mutates `array` and is based on
* [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.reverse(array);
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function reverse(array) {
return array == null ? array : nativeReverse.call(array);
}
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This method is used instead of
* [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
* returned.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function slice(array, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
else {
start = start == null ? 0 : toInteger(start);
end = end === undefined ? length : toInteger(end);
}
return baseSlice(array, start, end);
}
/**
* Uses a binary search to determine the lowest index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*/
function sortedIndex(array, value) {
return baseSortedIndex(array, value);
}
/**
* This method is like `_.sortedIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.sortedIndexBy(objects, { 'x': 4 }, 'x');
* // => 0
*/
function sortedIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
}
/**
* This method is like `_.indexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedIndexOf([4, 5, 5, 5, 6], 5);
* // => 1
*/
function sortedIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 5, 5, 5, 6], 5);
* // => 4
*/
function sortedLastIndex(array, value) {
return baseSortedIndex(array, value, true);
}
/**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 1
*
* // The `_.property` iteratee shorthand.
* _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
* // => 1
*/
function sortedLastIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
}
/**
* This method is like `_.lastIndexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
* // => 3
*/
function sortedLastIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value, true) - 1;
if (eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.uniq` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniq([1, 1, 2]);
* // => [1, 2]
*/
function sortedUniq(array) {
return (array && array.length)
? baseSortedUniq(array)
: [];
}
/**
* This method is like `_.uniqBy` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
* // => [1.1, 2.3]
*/
function sortedUniqBy(array, iteratee) {
return (array && array.length)
? baseSortedUniq(array, getIteratee(iteratee, 2))
: [];
}
/**
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.tail([1, 2, 3]);
* // => [2, 3]
*/
function tail(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 1, length) : [];
}
/**
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
*/
function take(array, n, guard) {
if (!(array && array.length)) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/
function takeRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.takeRightWhile(users, function(o) { return !o.active; });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeRightWhile(users, ['active', false]);
* // => objects for ['fred', 'pebbles']
*
* // The `_.property` iteratee shorthand.
* _.takeRightWhile(users, 'active');
* // => []
*/
function takeRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), false, true)
: [];
}
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.takeWhile(users, function(o) { return !o.active; });
* // => objects for ['barney', 'fred']
*
* // The `_.matches` iteratee shorthand.
* _.takeWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeWhile(users, ['active', false]);
* // => objects for ['barney', 'fred']
*
* // The `_.property` iteratee shorthand.
* _.takeWhile(users, 'active');
* // => []
*/
function takeWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3))
: [];
}
/**
* Creates an array of unique values, in order, from all given arrays using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([2], [1, 2]);
* // => [2, 1]
*/
var union = baseRest(function(arrays) {
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
});
/**
* This method is like `_.union` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which uniqueness is computed. Result values are chosen from the first
* array in which the value occurs. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.unionBy([2.1], [1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
var unionBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
});
/**
* This method is like `_.union` except that it accepts `comparator` which
* is invoked to compare elements of `arrays`. Result values are chosen from
* the first array in which the value occurs. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.unionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var unionWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
});
/**
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
*/
function uniq(array) {
return (array && array.length) ? baseUniq(array) : [];
}
/**
* This method is like `_.uniq` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* uniqueness is computed. The order of result values is determined by the
* order they occur in the array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniqBy([2.1, 1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniqBy(array, iteratee) {
return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
}
/**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/
function uniqWith(array, comparator) {
comparator = typeof comparator == 'function' ? comparator : undefined;
return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
}
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-zip
* configuration.
*
* @static
* @memberOf _
* @since 1.2.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*
* _.unzip(zipped);
* // => [['a', 'b'], [1, 2], [true, false]]
*/
function unzip(array) {
if (!(array && array.length)) {
return [];
}
var length = 0;
array = arrayFilter(array, function(group) {
if (isArrayLikeObject(group)) {
length = nativeMax(group.length, length);
return true;
}
});
return baseTimes(length, function(index) {
return arrayMap(array, baseProperty(index));
});
}
/**
* This method is like `_.unzip` except that it accepts `iteratee` to specify
* how regrouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @param {Function} [iteratee=_.identity] The function to combine
* regrouped values.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
* // => [[1, 10, 100], [2, 20, 200]]
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
*/
function unzipWith(array, iteratee) {
if (!(array && array.length)) {
return [];
}
var result = unzip(array);
if (iteratee == null) {
return result;
}
return arrayMap(result, function(group) {
return apply(iteratee, undefined, group);
});
}
/**
* Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.pull`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.xor
* @example
*
* _.without([2, 1, 2, 3], 1, 2);
* // => [3]
*/
var without = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, values)
: [];
});
/**
* Creates an array of unique values that is the
* [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
* of the given arrays. The order of result values is determined by the order
* they occur in the arrays.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.without
* @example
*
* _.xor([2, 1], [2, 3]);
* // => [1, 3]
*/
var xor = baseRest(function(arrays) {
return baseXor(arrayFilter(arrays, isArrayLikeObject));
});
/**
* This method is like `_.xor` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which by which they're compared. The order of result values is determined
* by the order they occur in the arrays. The iteratee is invoked with one
* argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2, 3.4]
*
* // The `_.property` iteratee shorthand.
* _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var xorBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
});
/**
* This method is like `_.xor` except that it accepts `comparator` which is
* invoked to compare elements of `arrays`. The order of result values is
* determined by the order they occur in the arrays. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.xorWith(objects, others, _.isEqual);
* // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var xorWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
});
/**
* Creates an array of grouped elements, the first of which contains the
* first elements of the given arrays, the second of which contains the
* second elements of the given arrays, and so on.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*/
var zip = baseRest(unzip);
/**
* This method is like `_.fromPairs` except that it accepts two arrays,
* one of property identifiers and one of corresponding values.
*
* @static
* @memberOf _
* @since 0.4.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject(['a', 'b'], [1, 2]);
* // => { 'a': 1, 'b': 2 }
*/
function zipObject(props, values) {
return baseZipObject(props || [], values || [], assignValue);
}
/**
* This method is like `_.zipObject` except that it supports property paths.
*
* @static
* @memberOf _
* @since 4.1.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
* // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
*/
function zipObjectDeep(props, values) {
return baseZipObject(props || [], values || [], baseSet);
}
/**
* This method is like `_.zip` except that it accepts `iteratee` to specify
* how grouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @param {Function} [iteratee=_.identity] The function to combine
* grouped values.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
* return a + b + c;
* });
* // => [111, 222]
*/
var zipWith = baseRest(function(arrays) {
var length = arrays.length,
iteratee = length > 1 ? arrays[length - 1] : undefined;
iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
return unzipWith(arrays, iteratee);
});
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` wrapper instance that wraps `value` with explicit method
* chain sequences enabled. The result of such sequences must be unwrapped
* with `_#value`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Seq
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _
* .chain(users)
* .sortBy('age')
* .map(function(o) {
* return o.user + ' is ' + o.age;
* })
* .head()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
var result = lodash(value);
result.__chain__ = true;
return result;
}
/**
* This method invokes `interceptor` and returns `value`. The interceptor
* is invoked with one argument; (value). The purpose of this method is to
* "tap into" a method chain sequence in order to modify intermediate results.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* // Mutate input array.
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
* The purpose of this method is to "pass thru" values replacing intermediate
* results in a method chain sequence.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => ['abc']
*/
function thru(value, interceptor) {
return interceptor(value);
}
/**
* This method is the wrapper version of `_.at`.
*
* @name at
* @memberOf _
* @since 1.0.0
* @category Seq
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _(object).at(['a[0].b.c', 'a[1]']).value();
* // => [3, 4]
*/
var wrapperAt = flatRest(function(paths) {
var length = paths.length,
start = length ? paths[0] : 0,
value = this.__wrapped__,
interceptor = function(object) { return baseAt(object, paths); };
if (length > 1 || this.__actions__.length ||
!(value instanceof LazyWrapper) || !isIndex(start)) {
return this.thru(interceptor);
}
value = value.slice(start, +start + (length ? 1 : 0));
value.__actions__.push({
'func': thru,
'args': [interceptor],
'thisArg': undefined
});
return new LodashWrapper(value, this.__chain__).thru(function(array) {
if (length && !array.length) {
array.push(undefined);
}
return array;
});
});
/**
* Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
*
* @name chain
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // A sequence without explicit chaining.
* _(users).head();
* // => { 'user': 'barney', 'age': 36 }
*
* // A sequence with explicit chaining.
* _(users)
* .chain()
* .head()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*/
function wrapperChain() {
return chain(this);
}
/**
* Executes the chain sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @since 3.2.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapped.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
*/
function wrapperCommit() {
return new LodashWrapper(this.value(), this.__chain__);
}
/**
* Gets the next value on a wrapped object following the
* [iterator protocol](https://mdn.io/iteration_protocols#iterator).
*
* @name next
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the next iterator value.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped.next();
* // => { 'done': false, 'value': 1 }
*
* wrapped.next();
* // => { 'done': false, 'value': 2 }
*
* wrapped.next();
* // => { 'done': true, 'value': undefined }
*/
function wrapperNext() {
if (this.__values__ === undefined) {
this.__values__ = toArray(this.value());
}
var done = this.__index__ >= this.__values__.length,
value = done ? undefined : this.__values__[this.__index__++];
return { 'done': done, 'value': value };
}
/**
* Enables the wrapper to be iterable.
*
* @name Symbol.iterator
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the wrapper object.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped[Symbol.iterator]() === wrapped;
* // => true
*
* Array.from(wrapped);
* // => [1, 2]
*/
function wrapperToIterator() {
return this;
}
/**
* Creates a clone of the chain sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
* @since 3.2.0
* @category Seq
* @param {*} value The value to plant.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2]).map(square);
* var other = wrapped.plant([3, 4]);
*
* other.value();
* // => [9, 16]
*
* wrapped.value();
* // => [1, 4]
*/
function wrapperPlant(value) {
var result,
parent = this;
while (parent instanceof baseLodash) {
var clone = wrapperClone(parent);
clone.__index__ = 0;
clone.__values__ = undefined;
if (result) {
previous.__wrapped__ = clone;
} else {
result = clone;
}
var previous = clone;
parent = parent.__wrapped__;
}
previous.__wrapped__ = value;
return result;
}
/**
* This method is the wrapper version of `_.reverse`.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
wrapped.__actions__.push({
'func': thru,
'args': [reverse],
'thisArg': undefined
});
return new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(reverse);
}
/**
* Executes the chain sequence to resolve the unwrapped value.
*
* @name value
* @memberOf _
* @since 0.1.0
* @alias toJSON, valueOf
* @category Seq
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}
/*------------------------------------------------------------------------*/
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.5.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': 1, '6': 2 }
*
* // The `_.property` iteratee shorthand.
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
++result[key];
} else {
baseAssignValue(result, key, 1);
}
});
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*
* // Combining several predicates using `_.overEvery` or `_.overSome`.
* _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
* // => objects for ['fred', 'barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=collection.length-1] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
*/
var findLast = createFind(findLastIndex);
/**
* Creates a flattened array of values by running each element in `collection`
* thru `iteratee` and flattening the mapped results. The iteratee is invoked
* with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [n, n];
* }
*
* _.flatMap([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMap(collection, iteratee) {
return baseFlatten(map(collection, iteratee), 1);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDeep([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMapDeep(collection, iteratee) {
return baseFlatten(map(collection, iteratee), INFINITY);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results up to `depth` times.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDepth([1, 2], duplicate, 2);
* // => [[1, 1], [2, 2]]
*/
function flatMapDepth(collection, iteratee, depth) {
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(map(collection, iteratee), depth);
}
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @alias eachRight
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEach
* @example
*
* _.forEachRight([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `2` then `1`.
*/
function forEachRight(collection, iteratee) {
var func = isArray(collection) ? arrayEachRight : baseEachRight;
return func(collection, getIteratee(iteratee, 3));
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*
* // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
baseAssignValue(result, key, [value]);
}
});
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
/**
* Invokes the method at `path` of each element in `collection`, returning
* an array of the results of each invoked method. Any additional arguments
* are provided to each invoked method. If `path` is a function, it's invoked
* for, and `this` bound to, each element in `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array|Function|string} path The path of the method to invoke or
* the function invoked per iteration.
* @param {...*} [args] The arguments to invoke each method with.
* @returns {Array} Returns the array of results.
* @example
*
* _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invokeMap([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
var invokeMap = baseRest(function(collection, path, args) {
var index = -1,
isFunc = typeof path == 'function',
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value) {
result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
});
return result;
});
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the last element responsible for generating the key. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var array = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.keyBy(array, function(o) {
* return String.fromCharCode(o.code);
* });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.keyBy(array, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*/
var keyBy = createAggregator(function(result, value, key) {
baseAssignValue(result, key, value);
});
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
/**
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, the second of which
* contains elements `predicate` returns falsey for. The predicate is
* invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of grouped elements.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.partition(users, function(o) { return o.active; });
* // => objects for [['fred'], ['barney', 'pebbles']]
*
* // The `_.matches` iteratee shorthand.
* _.partition(users, { 'age': 1, 'active': false });
* // => objects for [['pebbles'], ['barney', 'fred']]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.partition(users, ['active', false]);
* // => objects for [['barney', 'pebbles'], ['fred']]
*
* // The `_.property` iteratee shorthand.
* _.partition(users, 'active');
* // => objects for [['fred'], ['barney', 'pebbles']]
*/
var partition = createAggregator(function(result, value, key) {
result[key ? 0 : 1].push(value);
}, function() { return [[], []]; });
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
/**
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduce
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
*
* _.reduceRight(array, function(flattened, other) {
* return flattened.concat(other);
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduceRight : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
}
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.filter
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* _.reject(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.reject(users, { 'age': 40, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.reject(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.reject(users, 'active');
* // => objects for ['barney']
*/
function reject(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, negate(getIteratee(predicate, 3)));
}
/**
* Gets a random element from `collection`.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*/
function sample(collection) {
var func = isArray(collection) ? arraySample : baseSample;
return func(collection);
}
/**
* Gets `n` random elements at unique keys from `collection` up to the
* size of `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @param {number} [n=1] The number of elements to sample.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the random elements.
* @example
*
* _.sampleSize([1, 2, 3], 2);
* // => [3, 1]
*
* _.sampleSize([1, 2, 3], 4);
* // => [2, 3, 1]
*/
function sampleSize(collection, n, guard) {
if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
var func = isArray(collection) ? arraySampleSize : baseSampleSize;
return func(collection, n);
}
/**
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
var func = isArray(collection) ? arrayShuffle : baseShuffle;
return func(collection);
}
/**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
if (collection == null) {
return 0;
}
if (isArrayLike(collection)) {
return isString(collection) ? stringSize(collection) : collection.length;
}
var tag = getTag(collection);
if (tag == mapTag || tag == setTag) {
return collection.size;
}
return baseKeys(collection).length;
}
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
*/
var sortBy = baseRest(function(collection, iteratees) {
if (collection == null) {
return [];
}
var length = iteratees.length;
if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
iteratees = [];
} else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees = [iteratees[0]];
}
return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
/*------------------------------------------------------------------------*/
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = ctxNow || function() {
return root.Date.now();
};
/*------------------------------------------------------------------------*/
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => Logs 'done saving!' after the two async saves have completed.
*/
function after(n, func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that invokes `func`, with up to `n` arguments,
* ignoring any additional arguments.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
n = guard ? undefined : n;
n = (func && n == null) ? func.length : n;
return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
}
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
}
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
/**
* Creates a function that invokes the method at `object[key]` with `partials`
* prepended to the arguments it receives.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist. See
* [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @since 0.10.0
* @category Function
* @param {Object} object The object to invoke the method on.
* @param {string} key The key of the method.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // Bound with placeholders.
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
var bindKey = baseRest(function(object, key, partials) {
var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bindKey));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(key, bitmask, object, partials, holders);
});
/**
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curry.placeholder;
return result;
}
/**
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
function curryRight(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curryRight.placeholder;
return result;
}
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing
? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // => Logs 'deferred' after one millisecond.
*/
var defer = baseRest(function(func, args) {
return baseDelay(func, 1, args);
});
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) {
* console.log(text);
* }, 1000, 'later');
* // => Logs 'later' after one second.
*/
var delay = baseRest(function(func, wait, args) {
return baseDelay(func, toNumber(wait) || 0, args);
});
/**
* Creates a function that invokes `func` with arguments reversed.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to flip arguments for.
* @returns {Function} Returns the new flipped function.
* @example
*
* var flipped = _.flip(function() {
* return _.toArray(arguments);
* });
*
* flipped('a', 'b', 'c', 'd');
* // => ['d', 'c', 'b', 'a']
*/
function flip(func) {
return createWrap(func, WRAP_FLIP_FLAG);
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new negated function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var args = arguments;
switch (args.length) {
case 0: return !predicate.call(this);
case 1: return !predicate.call(this, args[0]);
case 2: return !predicate.call(this, args[0], args[1]);
case 3: return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/
function once(func) {
return before(2, func);
}
/**
* Creates a function that invokes `func` with its arguments transformed.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Function
* @param {Function} func The function to wrap.
* @param {...(Function|Function[])} [transforms=[_.identity]]
* The argument transforms.
* @returns {Function} Returns the new function.
* @example
*
* function doubled(n) {
* return n * 2;
* }
*
* function square(n) {
* return n * n;
* }
*
* var func = _.overArgs(function(x, y) {
* return [x, y];
* }, [square, doubled]);
*
* func(9, 3);
* // => [81, 6]
*
* func(10, 5);
* // => [100, 10]
*/
var overArgs = castRest(function(func, transforms) {
transforms = (transforms.length == 1 && isArray(transforms[0]))
? arrayMap(transforms[0], baseUnary(getIteratee()))
: arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
var funcsLength = transforms.length;
return baseRest(function(args) {
var index = -1,
length = nativeMin(args.length, funcsLength);
while (++index < length) {
args[index] = transforms[index].call(this, args[index]);
}
return apply(func, this, args);
});
});
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
/**
* Creates a function that invokes `func` with arguments arranged according
* to the specified `indexes` where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, [2, 0, 1]);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
*/
var rearg = flatRest(function(func, indexes) {
return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
});
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as
* an array.
*
* **Note:** This method is based on the
* [rest parameter](https://mdn.io/rest_parameters).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.rest(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function rest(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start === undefined ? start : toInteger(start);
return baseRest(func, start);
}
/**
* Creates a function that invokes `func` with the `this` binding of the
* create function and an array of arguments much like
* [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
*
* **Note:** This method is based on the
* [spread operator](https://mdn.io/spread_operator).
*
* @static
* @memberOf _
* @since 3.2.0
* @category Function
* @param {Function} func The function to spread arguments over.
* @param {number} [start=0] The start position of the spread.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* ]);
*
* numbers.then(_.spread(function(x, y) {
* return x + y;
* }));
* // => a Promise of 76
*/
function spread(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start == null ? 0 : nativeMax(toInteger(start), 0);
return baseRest(function(args) {
var array = args[start],
otherArgs = castSlice(args, 0, start);
if (array) {
arrayPush(otherArgs, array);
}
return apply(func, this, otherArgs);
});
}
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
/**
* Creates a function that accepts up to one argument, ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.unary(parseInt));
* // => [6, 8, 10]
*/
function unary(func) {
return ary(func, 1);
}
/**
* Creates a function that provides `value` to `wrapper` as its first
* argument. Any additional arguments provided to the function are appended
* to those provided to the `wrapper`. The wrapper is invoked with the `this`
* binding of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {*} value The value to wrap.
* @param {Function} [wrapper=identity] The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, &amp; pebbles</p>'
*/
function wrap(value, wrapper) {
return partial(castFunction(wrapper), value);
}
/*------------------------------------------------------------------------*/
/**
* Casts `value` as an array if it's not one.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Lang
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast array.
* @example
*
* _.castArray(1);
* // => [1]
*
* _.castArray({ 'a': 1 });
* // => [{ 'a': 1 }]
*
* _.castArray('abc');
* // => ['abc']
*
* _.castArray(null);
* // => [null]
*
* _.castArray(undefined);
* // => [undefined]
*
* _.castArray();
* // => []
*
* var array = [1, 2, 3];
* console.log(_.castArray(array) === array);
* // => true
*/
function castArray() {
if (!arguments.length) {
return [];
}
var value = arguments[0];
return isArray(value) ? value : [value];
}
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return baseClone(value, CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
*/
function cloneWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
}
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.cloneWith` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the deep cloned value.
* @see _.cloneWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* }
*
* var el = _.cloneDeepWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 20
*/
function cloneDeepWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
}
/**
* Checks if `object` conforms to `source` by invoking the predicate
* properties of `source` with the corresponding property values of `object`.
*
* **Note:** This method is equivalent to `_.conforms` when `source` is
* partially applied.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.conformsTo(object, { 'b': function(n) { return n > 1; } });
* // => true
*
* _.conformsTo(object, { 'b': function(n) { return n > 2; } });
* // => false
*/
function conformsTo(object, source) {
return source == null || baseConformsTo(object, source, keys(source));
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is greater than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
* @see _.lt
* @example
*
* _.gt(3, 1);
* // => true
*
* _.gt(3, 3);
* // => false
*
* _.gt(1, 3);
* // => false
*/
var gt = createRelationalOperation(baseGt);
/**
* Checks if `value` is greater than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than or equal to
* `other`, else `false`.
* @see _.lte
* @example
*
* _.gte(3, 1);
* // => true
*
* _.gte(3, 3);
* // => true
*
* _.gte(1, 3);
* // => false
*/
var gte = createRelationalOperation(function(value, other) {
return value >= other;
});
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is classified as an `ArrayBuffer` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
* @example
*
* _.isArrayBuffer(new ArrayBuffer(2));
* // => true
*
* _.isArrayBuffer(new Array(2));
* // => false
*/
var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && baseGetTag(value) == boolTag);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Checks if `value` is classified as a `Date` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*
* _.isDate('Mon April 23 2012');
* // => false
*/
var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
/**
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/
function isElement(value) {
return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
}
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
/**
* This method is like `_.isEqual` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with up to
* six arguments: (objValue, othValue [, index|key, object, other, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, othValue) {
* if (isGreeting(objValue) && isGreeting(othValue)) {
* return true;
* }
* }
*
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqualWith(array, other, customizer);
* // => true
*/
function isEqualWith(value, other, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
var result = customizer ? customizer(value, other) : undefined;
return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
}
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
if (!isObjectLike(value)) {
return false;
}
var tag = baseGetTag(value);
return tag == errorTag || tag == domExcTag ||
(typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
}
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/**
* Checks if `value` is an integer.
*
* **Note:** This method is based on
* [`Number.isInteger`](https://mdn.io/Number/isInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an integer, else `false`.
* @example
*
* _.isInteger(3);
* // => true
*
* _.isInteger(Number.MIN_VALUE);
* // => false
*
* _.isInteger(Infinity);
* // => false
*
* _.isInteger('3');
* // => false
*/
function isInteger(value) {
return typeof value == 'number' && value == toInteger(value);
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
/**
* Performs a partial deep comparison between `object` and `source` to
* determine if `object` contains equivalent property values.
*
* **Note:** This method is equivalent to `_.matches` when `source` is
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.isMatch(object, { 'b': 2 });
* // => true
*
* _.isMatch(object, { 'b': 1 });
* // => false
*/
function isMatch(object, source) {
return object === source || baseIsMatch(object, source, getMatchData(source));
}
/**
* This method is like `_.isMatch` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with five
* arguments: (objValue, srcValue, index|key, object, source).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, srcValue) {
* if (isGreeting(objValue) && isGreeting(srcValue)) {
* return true;
* }
* }
*
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatchWith(object, source, customizer);
* // => true
*/
function isMatchWith(object, source, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseIsMatch(object, source, getMatchData(source), customizer);
}
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is a pristine native function.
*
* **Note:** This method can't reliably detect native functions in the presence
* of the core-js package because core-js circumvents this kind of detection.
* Despite multiple requests, the core-js maintainer has made it clear: any
* attempt to fix the detection will be obstructed. As a result, we're left
* with little choice but to throw an error. Unfortunately, this also affects
* packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
* which rely on core-js.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (isMaskable(value)) {
throw new Error(CORE_ERROR_TEXT);
}
return baseIsNative(value);
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is `null` or `undefined`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is nullish, else `false`.
* @example
*
* _.isNil(null);
* // => true
*
* _.isNil(void 0);
* // => true
*
* _.isNil(NaN);
* // => false
*/
function isNil(value) {
return value == null;
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
/**
* Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
* double precision number which isn't the result of a rounded unsafe integer.
*
* **Note:** This method is based on
* [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
* @example
*
* _.isSafeInteger(3);
* // => true
*
* _.isSafeInteger(Number.MIN_VALUE);
* // => false
*
* _.isSafeInteger(Infinity);
* // => false
*
* _.isSafeInteger('3');
* // => false
*/
function isSafeInteger(value) {
return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
/**
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
*/
function isWeakMap(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}
/**
* Checks if `value` is classified as a `WeakSet` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
* @example
*
* _.isWeakSet(new WeakSet);
* // => true
*
* _.isWeakSet(new Set);
* // => false
*/
function isWeakSet(value) {
return isObjectLike(value) && baseGetTag(value) == weakSetTag;
}
/**
* Checks if `value` is less than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
* @see _.gt
* @example
*
* _.lt(1, 3);
* // => true
*
* _.lt(3, 3);
* // => false
*
* _.lt(3, 1);
* // => false
*/
var lt = createRelationalOperation(baseLt);
/**
* Checks if `value` is less than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than or equal to
* `other`, else `false`.
* @see _.gte
* @example
*
* _.lte(1, 3);
* // => true
*
* _.lte(3, 3);
* // => true
*
* _.lte(3, 1);
* // => false
*/
var lte = createRelationalOperation(function(value, other) {
return value <= other;
});
/**
* Converts `value` to an array.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* _.toArray({ 'a': 1, 'b': 2 });
* // => [1, 2]
*
* _.toArray('abc');
* // => ['a', 'b', 'c']
*
* _.toArray(1);
* // => []
*
* _.toArray(null);
* // => []
*/
function toArray(value) {
if (!value) {
return [];
}
if (isArrayLike(value)) {
return isString(value) ? stringToArray(value) : copyArray(value);
}
if (symIterator && value[symIterator]) {
return iteratorToArray(value[symIterator]());
}
var tag = getTag(value),
func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
return func(value);
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/**
* Converts `value` to an integer suitable for use as the length of an
* array-like object.
*
* **Note:** This method is based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toLength(3.2);
* // => 3
*
* _.toLength(Number.MIN_VALUE);
* // => 0
*
* _.toLength(Infinity);
* // => 4294967295
*
* _.toLength('3.2');
* // => 3
*/
function toLength(value) {
return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
/**
* Converts `value` to a safe integer. A safe integer can be compared and
* represented correctly.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toSafeInteger(3.2);
* // => 3
*
* _.toSafeInteger(Number.MIN_VALUE);
* // => 0
*
* _.toSafeInteger(Infinity);
* // => 9007199254740991
*
* _.toSafeInteger('3.2');
* // => 3
*/
function toSafeInteger(value) {
return value
? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
: (value === 0 ? value : 0);
}
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
/*------------------------------------------------------------------------*/
/**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/
var assign = createAssigner(function(object, source) {
if (isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
assignValue(object, key, source[key]);
}
}
});
/**
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assign
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assignIn({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
*/
var assignIn = createAssigner(function(object, source) {
copyObject(source, keysIn(source), object);
});
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
/**
* This method is like `_.assign` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignInWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keys(source), object, customizer);
});
/**
* Creates an array of values corresponding to `paths` of `object`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Array} Returns the picked values.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _.at(object, ['a[0].b.c', 'a[1]']);
* // => [3, 4]
*/
var at = flatRest(baseAt);
/**
* Creates an object that inherits from the `prototype` object. If a
* `properties` object is given, its own enumerable string keyed properties
* are assigned to the created object.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties == null ? result : baseAssign(result, properties);
}
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(object, sources) {
object = Object(object);
var index = -1;
var length = sources.length;
var guard = length > 2 ? sources[2] : undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
length = 1;
}
while (++index < length) {
var source = sources[index];
var props = keysIn(source);
var propsIndex = -1;
var propsLength = props.length;
while (++propsIndex < propsLength) {
var key = props[propsIndex];
var value = object[key];
if (value === undefined ||
(eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
object[key] = source[key];
}
}
}
return object;
});
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaults
* @example
*
* _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
* // => { 'a': { 'b': 2, 'c': 3 } }
*/
var defaultsDeep = baseRest(function(args) {
args.push(undefined, customDefaultsMerge);
return apply(mergeWith, undefined, args);
});
/**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
*/
function findKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
}
/**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(o) { return o.age < 40; });
* // => returns 'pebbles' assuming `_.findKey` returns 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/
function findLastKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
}
/**
* Iterates over own and inherited enumerable string keyed properties of an
* object and invokes `iteratee` for each property. The iteratee is invoked
* with three arguments: (value, key, object). Iteratee functions may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forInRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
*/
function forIn(object, iteratee) {
return object == null
? object
: baseFor(object, getIteratee(iteratee, 3), keysIn);
}
/**
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forIn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
*/
function forInRight(object, iteratee) {
return object == null
? object
: baseForRight(object, getIteratee(iteratee, 3), keysIn);
}
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
*/
function forOwnRight(object, iteratee) {
return object && baseForOwnRight(object, getIteratee(iteratee, 3));
}
/**
* Creates an array of function property names from own enumerable properties
* of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functionsIn
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functions(new Foo);
* // => ['a', 'b']
*/
function functions(object) {
return object == null ? [] : baseFunctions(object, keys(object));
}
/**
* Creates an array of function property names from own and inherited
* enumerable properties of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functions
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functionsIn(new Foo);
* // => ['a', 'b', 'c']
*/
function functionsIn(object) {
return object == null ? [] : baseFunctions(object, keysIn(object));
}
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
result[value] = key;
}, constant(identity));
/**
* This method is like `_.invert` except that the inverted object is generated
* from the results of running each element of `object` thru `iteratee`. The
* corresponding inverted value of each inverted key is an array of keys
* responsible for generating the inverted value. The iteratee is invoked
* with one argument: (value).
*
* @static
* @memberOf _
* @since 4.1.0
* @category Object
* @param {Object} object The object to invert.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invertBy(object);
* // => { '1': ['a', 'c'], '2': ['b'] }
*
* _.invertBy(object, function(value) {
* return 'group' + value;
* });
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
var invertBy = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}, getIteratee);
/**
* Invokes the method at `path` of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
* @example
*
* var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
*
* _.invoke(object, 'a[0].b.c.slice', 1, 3);
* // => [2, 3]
*/
var invoke = baseRest(baseInvoke);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
/**
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/
var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
baseMerge(object, source, srcIndex, customizer);
});
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
/**
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable string keyed properties of `object` that
* `predicate` doesn't return truthy for. The predicate is invoked with two
* arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
*/
function omitBy(object, predicate) {
return pickBy(object, negate(getIteratee(predicate)));
}
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = getIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
/**
* This method is like `_.get` except that if the resolved value is a
* function it's invoked with the `this` binding of its parent object and
* its result is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to resolve.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
*
* _.result(object, 'a[0].b.c1');
* // => 3
*
* _.result(object, 'a[0].b.c2');
* // => 4
*
* _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
* _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
*/
function result(object, path, defaultValue) {
path = castPath(path, object);
var index = -1,
length = path.length;
// Ensure the loop is entered when path is empty.
if (!length) {
length = 1;
object = undefined;
}
while (++index < length) {
var value = object == null ? undefined : object[toKey(path[index])];
if (value === undefined) {
index = length;
value = defaultValue;
}
object = isFunction(value) ? value.call(object) : value;
}
return object;
}
/**
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties. Use `_.setWith` to customize
* `path` creation.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, ['x', '0', 'y', 'z'], 5);
* console.log(object.x[0].y.z);
* // => 5
*/
function set(object, path, value) {
return object == null ? object : baseSet(object, path, value);
}
/**
* This method is like `_.set` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.setWith(object, '[0][1]', 'a', Object);
* // => { '0': { '1': 'a' } }
*/
function setWith(object, path, value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseSet(object, path, value, customizer);
}
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`. If `object` is a map or set, its
* entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/
var toPairs = createToPairs(keys);
/**
* Creates an array of own and inherited enumerable string keyed-value pairs
* for `object` which can be consumed by `_.fromPairs`. If `object` is a map
* or set, its entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entriesIn
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairsIn(new Foo);
* // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
*/
var toPairsIn = createToPairs(keysIn);
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* }, []);
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] }
*/
function transform(object, iteratee, accumulator) {
var isArr = isArray(object),
isArrLike = isArr || isBuffer(object) || isTypedArray(object);
iteratee = getIteratee(iteratee, 4);
if (accumulator == null) {
var Ctor = object && object.constructor;
if (isArrLike) {
accumulator = isArr ? new Ctor : [];
}
else if (isObject(object)) {
accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
else {
accumulator = {};
}
}
(isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
/**
* Removes the property at `path` of `object`.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 7 } }] };
* _.unset(object, 'a[0].b.c');
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*
* _.unset(object, ['a', '0', 'b', 'c']);
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*/
function unset(object, path) {
return object == null ? true : baseUnset(object, path);
}
/**
* This method is like `_.set` except that accepts `updater` to produce the
* value to set. Use `_.updateWith` to customize `path` creation. The `updater`
* is invoked with one argument: (value).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.update(object, 'a[0].b.c', function(n) { return n * n; });
* console.log(object.a[0].b.c);
* // => 9
*
* _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
* console.log(object.x[0].y.z);
* // => 0
*/
function update(object, path, updater) {
return object == null ? object : baseUpdate(object, path, castFunction(updater));
}
/**
* This method is like `_.update` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.updateWith(object, '[0][1]', _.constant('a'), Object);
* // => { '0': { '1': 'a' } }
*/
function updateWith(object, path, updater, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
}
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
/**
* Creates an array of the own and inherited enumerable string keyed property
* values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
*/
function valuesIn(object) {
return object == null ? [] : baseValues(object, keysIn(object));
}
/*------------------------------------------------------------------------*/
/**
* Clamps `number` within the inclusive `lower` and `upper` bounds.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Number
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
* @example
*
* _.clamp(-10, -5, 5);
* // => -5
*
* _.clamp(10, -5, 5);
* // => 5
*/
function clamp(number, lower, upper) {
if (upper === undefined) {
upper = lower;
lower = undefined;
}
if (upper !== undefined) {
upper = toNumber(upper);
upper = upper === upper ? upper : 0;
}
if (lower !== undefined) {
lower = toNumber(lower);
lower = lower === lower ? lower : 0;
}
return baseClamp(toNumber(number), lower, upper);
}
/**
* Checks if `n` is between `start` and up to, but not including, `end`. If
* `end` is not specified, it's set to `start` with `start` then set to `0`.
* If `start` is greater than `end` the params are swapped to support
* negative ranges.
*
* @static
* @memberOf _
* @since 3.3.0
* @category Number
* @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @see _.range, _.rangeRight
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*
* _.inRange(-3, -2, -6);
* // => true
*/
function inRange(number, start, end) {
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
number = toNumber(number);
return baseInRange(number, start, end);
}
/**
* Produces a random number between the inclusive `lower` and `upper` bounds.
* If only one argument is provided a number between `0` and the given number
* is returned. If `floating` is `true`, or either `lower` or `upper` are
* floats, a floating-point number is returned instead of an integer.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Number
* @param {number} [lower=0] The lower bound.
* @param {number} [upper=1] The upper bound.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(lower, upper, floating) {
if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
upper = floating = undefined;
}
if (floating === undefined) {
if (typeof upper == 'boolean') {
floating = upper;
upper = undefined;
}
else if (typeof lower == 'boolean') {
floating = lower;
lower = undefined;
}
}
if (lower === undefined && upper === undefined) {
lower = 0;
upper = 1;
}
else {
lower = toFinite(lower);
if (upper === undefined) {
upper = lower;
lower = 0;
} else {
upper = toFinite(upper);
}
}
if (lower > upper) {
var temp = lower;
lower = upper;
upper = temp;
}
if (floating || lower % 1 || upper % 1) {
var rand = nativeRandom();
return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
}
return baseRandom(lower, upper);
}
/*------------------------------------------------------------------------*/
/**
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar--');
* // => 'fooBar'
*
* _.camelCase('__FOO_BAR__');
* // => 'fooBar'
*/
var camelCase = createCompounder(function(result, word, index) {
word = word.toLowerCase();
return result + (index ? capitalize(word) : word);
});
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}
/**
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr(string) {
string = toString(string);
return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
/**
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search up to.
* @returns {boolean} Returns `true` if `string` ends with `target`,
* else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = toString(string);
target = baseToString(target);
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
var end = position;
position -= target.length;
return position >= 0 && string.slice(position, end) == target;
}
/**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, &amp; pebbles'
*/
function escape(string) {
string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
/**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = toString(string);
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar, '\\$&')
: string;
}
/**
* Converts `string` to
* [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__FOO_BAR__');
* // => 'foo-bar'
*/
var kebabCase = createCompounder(function(result, word, index) {
return result + (index ? '-' : '') + word.toLowerCase();
});
/**
* Converts `string`, as space separated words, to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.lowerCase('--Foo-Bar--');
* // => 'foo bar'
*
* _.lowerCase('fooBar');
* // => 'foo bar'
*
* _.lowerCase('__FOO_BAR__');
* // => 'foo bar'
*/
var lowerCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toLowerCase();
});
/**
* Converts the first character of `string` to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.lowerFirst('Fred');
* // => 'fred'
*
* _.lowerFirst('FRED');
* // => 'fRED'
*/
var lowerFirst = createCaseFirst('toLowerCase');
/**
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/
function pad(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
if (!length || strLength >= length) {
return string;
}
var mid = (length - strLength) / 2;
return (
createPadding(nativeFloor(mid), chars) +
string +
createPadding(nativeCeil(mid), chars)
);
}
/**
* Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padEnd('abc', 6);
* // => 'abc '
*
* _.padEnd('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padEnd('abc', 3);
* // => 'abc'
*/
function padEnd(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (string + createPadding(length - strLength, chars))
: string;
}
/**
* Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padStart('abc', 6);
* // => ' abc'
*
* _.padStart('abc', 6, '_-');
* // => '_-_abc'
*
* _.padStart('abc', 3);
* // => 'abc'
*/
function padStart(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (createPadding(length - strLength, chars) + string)
: string;
}
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
}
/**
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=1] The number of times to repeat the string.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
*/
function repeat(string, n, guard) {
if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
return baseRepeat(toString(string), n);
}
/**
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
*/
function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
}
/**
* Converts `string` to
* [snake case](https://en.wikipedia.org/wiki/Snake_case).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the snake cased string.
* @example
*
* _.snakeCase('Foo Bar');
* // => 'foo_bar'
*
* _.snakeCase('fooBar');
* // => 'foo_bar'
*
* _.snakeCase('--FOO-BAR--');
* // => 'foo_bar'
*/
var snakeCase = createCompounder(function(result, word, index) {
return result + (index ? '_' : '') + word.toLowerCase();
});
/**
* Splits `string` by `separator`.
*
* **Note:** This method is based on
* [`String#split`](https://mdn.io/String/split).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to split.
* @param {RegExp|string} separator The separator pattern to split by.
* @param {number} [limit] The length to truncate results to.
* @returns {Array} Returns the string segments.
* @example
*
* _.split('a-b-c', '-', 2);
* // => ['a', 'b']
*/
function split(string, separator, limit) {
if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
separator = limit = undefined;
}
limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
if (!limit) {
return [];
}
string = toString(string);
if (string && (
typeof separator == 'string' ||
(separator != null && !isRegExp(separator))
)) {
separator = baseToString(separator);
if (!separator && hasUnicode(string)) {
return castSlice(stringToArray(string), 0, limit);
}
}
return string.split(separator, limit);
}
/**
* Converts `string` to
* [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @since 3.1.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar--');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__FOO_BAR__');
* // => 'FOO BAR'
*/
var startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + upperFirst(word);
});
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is given, it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='lodash.templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
* // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b>&lt;script&gt;</b>'
*
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
*
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(string, options, guard) {
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
if (guard && isIterateeCall(string, options, guard)) {
options = undefined;
}
string = toString(string);
options = assignInWith({}, options, settings, customDefaultsAssignIn);
var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
// The sourceURL gets injected into the source that's eval-ed, so be careful
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
var sourceURL = '//# sourceURL=' +
(hasOwnProperty.call(options, 'sourceURL')
? (options.sourceURL + '').replace(/\s/g, ' ')
: ('lodash.templateSources[' + (++templateCounter) + ']')
) + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = hasOwnProperty.call(options, 'variable') && options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if (reForbiddenIdentifierChars.test(variable)) {
throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
return Function(importsKeys, sourceURL + 'return ' + source)
.apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
/**
* Converts `string`, as a whole, to lower case just like
* [String#toLowerCase](https://mdn.io/toLowerCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.toLower('--Foo-Bar--');
* // => '--foo-bar--'
*
* _.toLower('fooBar');
* // => 'foobar'
*
* _.toLower('__FOO_BAR__');
* // => '__foo_bar__'
*/
function toLower(value) {
return toString(value).toLowerCase();
}
/**
* Converts `string`, as a whole, to upper case just like
* [String#toUpperCase](https://mdn.io/toUpperCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.toUpper('--foo-bar--');
* // => '--FOO-BAR--'
*
* _.toUpper('fooBar');
* // => 'FOOBAR'
*
* _.toUpper('__foo_bar__');
* // => '__FOO_BAR__'
*/
function toUpper(value) {
return toString(value).toUpperCase();
}
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return baseTrim(string);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.slice(0, trimmedEndIndex(string) + 1);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
/**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimStart(' abc ');
* // => 'abc '
*
* _.trimStart('-_-abc-_-', '_-');
* // => 'abc-_-'
*/
function trimStart(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimStart, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
start = charsStartIndex(strSymbols, stringToArray(chars));
return castSlice(strSymbols, start).join('');
}
/**
* Truncates `string` if it's longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object} [options={}] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @returns {string} Returns the truncated string.
* @example
*
* _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
}
string = toString(string);
var strLength = string.length;
if (hasUnicode(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) {
return string;
}
var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
var result = strSymbols
? castSlice(strSymbols, 0, end).join('')
: string.slice(0, end);
if (separator === undefined) {
return result + omission;
}
if (strSymbols) {
end += (result.length - end);
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
substring = result;
if (!separator.global) {
separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
var newEnd = match.index;
}
result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
/**
* The inverse of `_.escape`; this method converts the HTML entities
* `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
* their corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional
* HTML entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @since 0.6.0
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, &amp; pebbles');
* // => 'fred, barney, & pebbles'
*/
function unescape(string) {
string = toString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}
/**
* Converts `string`, as space separated words, to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.upperCase('--foo-bar');
* // => 'FOO BAR'
*
* _.upperCase('fooBar');
* // => 'FOO BAR'
*
* _.upperCase('__foo_bar__');
* // => 'FOO BAR'
*/
var upperCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toUpperCase();
});
/**
* Converts the first character of `string` to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.upperFirst('fred');
* // => 'Fred'
*
* _.upperFirst('FRED');
* // => 'FRED'
*/
var upperFirst = createCaseFirst('toUpperCase');
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
string = toString(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
}
return string.match(pattern) || [];
}
/*------------------------------------------------------------------------*/
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
var attempt = baseRest(function(func, args) {
try {
return apply(func, undefined, args);
} catch (e) {
return isError(e) ? e : new Error(e);
}
});
/**
* Binds methods of an object to the object itself, overwriting the existing
* method.
*
* **Note:** This method doesn't set the "length" property of bound functions.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} methodNames The object method names to bind.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'click': function() {
* console.log('clicked ' + this.label);
* }
* };
*
* _.bindAll(view, ['click']);
* jQuery(element).on('click', view.click);
* // => Logs 'clicked docs' when clicked.
*/
var bindAll = flatRest(function(object, methodNames) {
arrayEach(methodNames, function(key) {
key = toKey(key);
baseAssignValue(object, key, bind(object[key], object));
});
return object;
});
/**
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* var func = _.cond([
* [_.matches({ 'a': 1 }), _.constant('matches A')],
* [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
* [_.stubTrue, _.constant('no match')]
* ]);
*
* func({ 'a': 1, 'b': 2 });
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 });
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' });
* // => 'no match'
*/
function cond(pairs) {
var length = pairs == null ? 0 : pairs.length,
toIteratee = getIteratee();
pairs = !length ? [] : arrayMap(pairs, function(pair) {
if (typeof pair[1] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return [toIteratee(pair[0]), pair[1]];
});
return baseRest(function(args) {
var index = -1;
while (++index < length) {
var pair = pairs[index];
if (apply(pair[0], this, args)) {
return apply(pair[1], this, args);
}
}
});
}
/**
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
*/
function conforms(source) {
return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* Checks `value` to determine whether a default value should be returned in
* its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
* or `undefined`.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Util
* @param {*} value The value to check.
* @param {*} defaultValue The default value.
* @returns {*} Returns the resolved value.
* @example
*
* _.defaultTo(1, 10);
* // => 1
*
* _.defaultTo(undefined, 10);
* // => 10
*/
function defaultTo(value, defaultValue) {
return (value == null || value !== value) ? defaultValue : value;
}
/**
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flowRight
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow([_.add, square]);
* addSquare(1, 2);
* // => 9
*/
var flow = createFlow();
/**
* This method is like `_.flow` except that it creates a function that
* invokes the given functions from right to left.
*
* @static
* @since 3.0.0
* @memberOf _
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flow
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight([square, _.add]);
* addSquare(1, 2);
* // => 9
*/
var flowRight = createFlow(true);
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
*/
function iteratee(func) {
return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between a given
* object and `source`, returning `true` if the given object has equivalent
* property values, else `false`.
*
* **Note:** The created function is equivalent to `_.isMatch` with `source`
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
* // => [{ 'a': 4, 'b': 5, 'c': 6 }]
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matches(source) {
return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between the
* value at `path` of a given object to `srcValue`, returning `true` if the
* object value is equivalent, else `false`.
*
* **Note:** Partial comparisons will match empty array and empty object
* `srcValue` values against any array or object value, respectively. See
* `_.isEqual` for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.2.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.find(objects, _.matchesProperty('a', 4));
* // => { 'a': 4, 'b': 5, 'c': 6 }
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matchesProperty(path, srcValue) {
return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
}
/**
* Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var objects = [
* { 'a': { 'b': _.constant(2) } },
* { 'a': { 'b': _.constant(1) } }
* ];
*
* _.map(objects, _.method('a.b'));
* // => [2, 1]
*
* _.map(objects, _.method(['a', 'b']));
* // => [2, 1]
*/
var method = baseRest(function(path, args) {
return function(object) {
return baseInvoke(object, path, args);
};
});
/**
* The opposite of `_.method`; this method creates a function that invokes
* the method at a given path of `object`. Any additional arguments are
* provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Object} object The object to query.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var array = _.times(3, _.constant),
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.methodOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.methodOf(object));
* // => [2, 0]
*/
var methodOf = baseRest(function(object, args) {
return function(path) {
return baseInvoke(object, path, args);
};
});
/**
* Adds all own enumerable string keyed function properties of a source
* object to the destination object. If `object` is a function, then methods
* are added to its prototype as well.
*
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
* avoid conflicts caused by modifying the original.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Function|Object} [object=lodash] The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.chain=true] Specify whether mixins are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
*/
function mixin(object, source, options) {
var props = keys(source),
methodNames = baseFunctions(source, props);
if (options == null &&
!(isObject(source) && (methodNames.length || !props.length))) {
options = source;
source = object;
object = this;
methodNames = baseFunctions(source, keys(source));
}
var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
isFunc = isFunction(object);
arrayEach(methodNames, function(methodName) {
var func = source[methodName];
object[methodName] = func;
if (isFunc) {
object.prototype[methodName] = function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
};
}
});
return object;
}
/**
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
if (root._ === this) {
root._ = oldDash;
}
return this;
}
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
/**
* Creates a function that gets the argument at index `n`. If `n` is negative,
* the nth argument from the end is returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [n=0] The index of the argument to return.
* @returns {Function} Returns the new pass-thru function.
* @example
*
* var func = _.nthArg(1);
* func('a', 'b', 'c', 'd');
* // => 'b'
*
* var func = _.nthArg(-2);
* func('a', 'b', 'c', 'd');
* // => 'c'
*/
function nthArg(n) {
n = toInteger(n);
return baseRest(function(args) {
return baseNth(args, n);
});
}
/**
* Creates a function that invokes `iteratees` with the arguments it receives
* and returns their results.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to invoke.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.over([Math.max, Math.min]);
*
* func(1, 2, 3, 4);
* // => [4, 1]
*/
var over = createOver(arrayMap);
/**
* Creates a function that checks if **all** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overEvery([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => false
*
* func(NaN);
* // => false
*/
var overEvery = createOver(arrayEvery);
/**
* Creates a function that checks if **any** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overSome([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => true
*
* func(NaN);
* // => false
*
* var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
* var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
*/
var overSome = createOver(arraySome);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
/**
* The opposite of `_.property`; this method creates a function that returns
* the value at a given path of `object`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
* @example
*
* var array = [0, 1, 2],
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.propertyOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
* // => [2, 0]
*/
function propertyOf(object) {
return function(path) {
return object == null ? undefined : baseGet(object, path);
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = createRange();
/**
* This method is like `_.range` except that it populates values in
* descending order.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.range
* @example
*
* _.rangeRight(4);
* // => [3, 2, 1, 0]
*
* _.rangeRight(-4);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 5);
* // => [4, 3, 2, 1]
*
* _.rangeRight(0, 20, 5);
* // => [15, 10, 5, 0]
*
* _.rangeRight(0, -4, -1);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 4, 0);
* // => [1, 1, 1]
*
* _.rangeRight(0);
* // => []
*/
var rangeRight = createRange(true);
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
/**
* This method returns a new empty object.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Object} Returns the new empty object.
* @example
*
* var objects = _.times(2, _.stubObject);
*
* console.log(objects);
* // => [{}, {}]
*
* console.log(objects[0] === objects[1]);
* // => false
*/
function stubObject() {
return {};
}
/**
* This method returns an empty string.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {string} Returns the empty string.
* @example
*
* _.times(2, _.stubString);
* // => ['', '']
*/
function stubString() {
return '';
}
/**
* This method returns `true`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `true`.
* @example
*
* _.times(2, _.stubTrue);
* // => [true, true]
*/
function stubTrue() {
return true;
}
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = getIteratee(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
/**
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
*/
function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
}
/**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return toString(prefix) + id;
}
/*------------------------------------------------------------------------*/
/**
* Adds two numbers.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {number} augend The first number in an addition.
* @param {number} addend The second number in an addition.
* @returns {number} Returns the total.
* @example
*
* _.add(6, 4);
* // => 10
*/
var add = createMathOperation(function(augend, addend) {
return augend + addend;
}, 0);
/**
* Computes `number` rounded up to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round up.
* @param {number} [precision=0] The precision to round up to.
* @returns {number} Returns the rounded up number.
* @example
*
* _.ceil(4.006);
* // => 5
*
* _.ceil(6.004, 2);
* // => 6.01
*
* _.ceil(6040, -2);
* // => 6100
*/
var ceil = createRound('ceil');
/**
* Divide two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} dividend The first number in a division.
* @param {number} divisor The second number in a division.
* @returns {number} Returns the quotient.
* @example
*
* _.divide(6, 4);
* // => 1.5
*/
var divide = createMathOperation(function(dividend, divisor) {
return dividend / divisor;
}, 1);
/**
* Computes `number` rounded down to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round down.
* @param {number} [precision=0] The precision to round down to.
* @returns {number} Returns the rounded down number.
* @example
*
* _.floor(4.006);
* // => 4
*
* _.floor(0.046, 2);
* // => 0.04
*
* _.floor(4060, -2);
* // => 4000
*/
var floor = createRound('floor');
/**
* Computes the maximum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => undefined
*/
function max(array) {
return (array && array.length)
? baseExtremum(array, identity, baseGt)
: undefined;
}
/**
* This method is like `_.max` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the maximum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.maxBy(objects, function(o) { return o.n; });
* // => { 'n': 2 }
*
* // The `_.property` iteratee shorthand.
* _.maxBy(objects, 'n');
* // => { 'n': 2 }
*/
function maxBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
: undefined;
}
/**
* Computes the mean of the values in `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the mean.
* @example
*
* _.mean([4, 2, 8, 6]);
* // => 5
*/
function mean(array) {
return baseMean(array, identity);
}
/**
* This method is like `_.mean` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be averaged.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the mean.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.meanBy(objects, function(o) { return o.n; });
* // => 5
*
* // The `_.property` iteratee shorthand.
* _.meanBy(objects, 'n');
* // => 5
*/
function meanBy(array, iteratee) {
return baseMean(array, getIteratee(iteratee, 2));
}
/**
* Computes the minimum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => undefined
*/
function min(array) {
return (array && array.length)
? baseExtremum(array, identity, baseLt)
: undefined;
}
/**
* This method is like `_.min` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the minimum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.minBy(objects, function(o) { return o.n; });
* // => { 'n': 1 }
*
* // The `_.property` iteratee shorthand.
* _.minBy(objects, 'n');
* // => { 'n': 1 }
*/
function minBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
: undefined;
}
/**
* Multiply two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} multiplier The first number in a multiplication.
* @param {number} multiplicand The second number in a multiplication.
* @returns {number} Returns the product.
* @example
*
* _.multiply(6, 4);
* // => 24
*/
var multiply = createMathOperation(function(multiplier, multiplicand) {
return multiplier * multiplicand;
}, 1);
/**
* Computes `number` rounded to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round.
* @param {number} [precision=0] The precision to round to.
* @returns {number} Returns the rounded number.
* @example
*
* _.round(4.006);
* // => 4
*
* _.round(4.006, 2);
* // => 4.01
*
* _.round(4060, -2);
* // => 4100
*/
var round = createRound('round');
/**
* Subtract two numbers.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {number} minuend The first number in a subtraction.
* @param {number} subtrahend The second number in a subtraction.
* @returns {number} Returns the difference.
* @example
*
* _.subtract(6, 4);
* // => 2
*/
var subtract = createMathOperation(function(minuend, subtrahend) {
return minuend - subtrahend;
}, 0);
/**
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
*/
function sum(array) {
return (array && array.length)
? baseSum(array, identity)
: 0;
}
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, getIteratee(iteratee, 2))
: 0;
}
/*------------------------------------------------------------------------*/
// Add methods that return wrapped values in chain sequences.
lodash.after = after;
lodash.ary = ary;
lodash.assign = assign;
lodash.assignIn = assignIn;
lodash.assignInWith = assignInWith;
lodash.assignWith = assignWith;
lodash.at = at;
lodash.before = before;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.castArray = castArray;
lodash.chain = chain;
lodash.chunk = chunk;
lodash.compact = compact;
lodash.concat = concat;
lodash.cond = cond;
lodash.conforms = conforms;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.curry = curry;
lodash.curryRight = curryRight;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defaultsDeep = defaultsDeep;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.differenceBy = differenceBy;
lodash.differenceWith = differenceWith;
lodash.drop = drop;
lodash.dropRight = dropRight;
lodash.dropRightWhile = dropRightWhile;
lodash.dropWhile = dropWhile;
lodash.fill = fill;
lodash.filter = filter;
lodash.flatMap = flatMap;
lodash.flatMapDeep = flatMapDeep;
lodash.flatMapDepth = flatMapDepth;
lodash.flatten = flatten;
lodash.flattenDeep = flattenDeep;
lodash.flattenDepth = flattenDepth;
lodash.flip = flip;
lodash.flow = flow;
lodash.flowRight = flowRight;
lodash.fromPairs = fromPairs;
lodash.functions = functions;
lodash.functionsIn = functionsIn;
lodash.groupBy = groupBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.intersectionBy = intersectionBy;
lodash.intersectionWith = intersectionWith;
lodash.invert = invert;
lodash.invertBy = invertBy;
lodash.invokeMap = invokeMap;
lodash.iteratee = iteratee;
lodash.keyBy = keyBy;
lodash.keys = keys;
lodash.keysIn = keysIn;
lodash.map = map;
lodash.mapKeys = mapKeys;
lodash.mapValues = mapValues;
lodash.matches = matches;
lodash.matchesProperty = matchesProperty;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.mergeWith = mergeWith;
lodash.method = method;
lodash.methodOf = methodOf;
lodash.mixin = mixin;
lodash.negate = negate;
lodash.nthArg = nthArg;
lodash.omit = omit;
lodash.omitBy = omitBy;
lodash.once = once;
lodash.orderBy = orderBy;
lodash.over = over;
lodash.overArgs = overArgs;
lodash.overEvery = overEvery;
lodash.overSome = overSome;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.partition = partition;
lodash.pick = pick;
lodash.pickBy = pickBy;
lodash.property = property;
lodash.propertyOf = propertyOf;
lodash.pull = pull;
lodash.pullAll = pullAll;
lodash.pullAllBy = pullAllBy;
lodash.pullAllWith = pullAllWith;
lodash.pullAt = pullAt;
lodash.range = range;
lodash.rangeRight = rangeRight;
lodash.rearg = rearg;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.reverse = reverse;
lodash.sampleSize = sampleSize;
lodash.set = set;
lodash.setWith = setWith;
lodash.shuffle = shuffle;
lodash.slice = slice;
lodash.sortBy = sortBy;
lodash.sortedUniq = sortedUniq;
lodash.sortedUniqBy = sortedUniqBy;
lodash.split = split;
lodash.spread = spread;
lodash.tail = tail;
lodash.take = take;
lodash.takeRight = takeRight;
lodash.takeRightWhile = takeRightWhile;
lodash.takeWhile = takeWhile;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.thru = thru;
lodash.toArray = toArray;
lodash.toPairs = toPairs;
lodash.toPairsIn = toPairsIn;
lodash.toPath = toPath;
lodash.toPlainObject = toPlainObject;
lodash.transform = transform;
lodash.unary = unary;
lodash.union = union;
lodash.unionBy = unionBy;
lodash.unionWith = unionWith;
lodash.uniq = uniq;
lodash.uniqBy = uniqBy;
lodash.uniqWith = uniqWith;
lodash.unset = unset;
lodash.unzip = unzip;
lodash.unzipWith = unzipWith;
lodash.update = update;
lodash.updateWith = updateWith;
lodash.values = values;
lodash.valuesIn = valuesIn;
lodash.without = without;
lodash.words = words;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.xorBy = xorBy;
lodash.xorWith = xorWith;
lodash.zip = zip;
lodash.zipObject = zipObject;
lodash.zipObjectDeep = zipObjectDeep;
lodash.zipWith = zipWith;
// Add aliases.
lodash.entries = toPairs;
lodash.entriesIn = toPairsIn;
lodash.extend = assignIn;
lodash.extendWith = assignInWith;
// Add methods to `lodash.prototype`.
mixin(lodash, lodash);
/*------------------------------------------------------------------------*/
// Add methods that return unwrapped values in chain sequences.
lodash.add = add;
lodash.attempt = attempt;
lodash.camelCase = camelCase;
lodash.capitalize = capitalize;
lodash.ceil = ceil;
lodash.clamp = clamp;
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.cloneDeepWith = cloneDeepWith;
lodash.cloneWith = cloneWith;
lodash.conformsTo = conformsTo;
lodash.deburr = deburr;
lodash.defaultTo = defaultTo;
lodash.divide = divide;
lodash.endsWith = endsWith;
lodash.eq = eq;
lodash.escape = escape;
lodash.escapeRegExp = escapeRegExp;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.floor = floor;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.get = get;
lodash.gt = gt;
lodash.gte = gte;
lodash.has = has;
lodash.hasIn = hasIn;
lodash.head = head;
lodash.identity = identity;
lodash.includes = includes;
lodash.indexOf = indexOf;
lodash.inRange = inRange;
lodash.invoke = invoke;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isArrayBuffer = isArrayBuffer;
lodash.isArrayLike = isArrayLike;
lodash.isArrayLikeObject = isArrayLikeObject;
lodash.isBoolean = isBoolean;
lodash.isBuffer = isBuffer;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isEqualWith = isEqualWith;
lodash.isError = isError;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isInteger = isInteger;
lodash.isLength = isLength;
lodash.isMap = isMap;
lodash.isMatch = isMatch;
lodash.isMatchWith = isMatchWith;
lodash.isNaN = isNaN;
lodash.isNative = isNative;
lodash.isNil = isNil;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isObjectLike = isObjectLike;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isSafeInteger = isSafeInteger;
lodash.isSet = isSet;
lodash.isString = isString;
lodash.isSymbol = isSymbol;
lodash.isTypedArray = isTypedArray;
lodash.isUndefined = isUndefined;
lodash.isWeakMap = isWeakMap;
lodash.isWeakSet = isWeakSet;
lodash.join = join;
lodash.kebabCase = kebabCase;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.lowerCase = lowerCase;
lodash.lowerFirst = lowerFirst;
lodash.lt = lt;
lodash.lte = lte;
lodash.max = max;
lodash.maxBy = maxBy;
lodash.mean = mean;
lodash.meanBy = meanBy;
lodash.min = min;
lodash.minBy = minBy;
lodash.stubArray = stubArray;
lodash.stubFalse = stubFalse;
lodash.stubObject = stubObject;
lodash.stubString = stubString;
lodash.stubTrue = stubTrue;
lodash.multiply = multiply;
lodash.nth = nth;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.pad = pad;
lodash.padEnd = padEnd;
lodash.padStart = padStart;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.repeat = repeat;
lodash.replace = replace;
lodash.result = result;
lodash.round = round;
lodash.runInContext = runInContext;
lodash.sample = sample;
lodash.size = size;
lodash.snakeCase = snakeCase;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.sortedIndexBy = sortedIndexBy;
lodash.sortedIndexOf = sortedIndexOf;
lodash.sortedLastIndex = sortedLastIndex;
lodash.sortedLastIndexBy = sortedLastIndexBy;
lodash.sortedLastIndexOf = sortedLastIndexOf;
lodash.startCase = startCase;
lodash.startsWith = startsWith;
lodash.subtract = subtract;
lodash.sum = sum;
lodash.sumBy = sumBy;
lodash.template = template;
lodash.times = times;
lodash.toFinite = toFinite;
lodash.toInteger = toInteger;
lodash.toLength = toLength;
lodash.toLower = toLower;
lodash.toNumber = toNumber;
lodash.toSafeInteger = toSafeInteger;
lodash.toString = toString;
lodash.toUpper = toUpper;
lodash.trim = trim;
lodash.trimEnd = trimEnd;
lodash.trimStart = trimStart;
lodash.truncate = truncate;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
lodash.upperCase = upperCase;
lodash.upperFirst = upperFirst;
// Add aliases.
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.first = head;
mixin(lodash, (function() {
var source = {};
baseForOwn(lodash, function(func, methodName) {
if (!hasOwnProperty.call(lodash.prototype, methodName)) {
source[methodName] = func;
}
});
return source;
}()), { 'chain': false });
/*------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type {string}
*/
lodash.VERSION = VERSION;
// Assign default placeholders.
arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
lodash[methodName].placeholder = lodash;
});
// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop', 'take'], function(methodName, index) {
LazyWrapper.prototype[methodName] = function(n) {
n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
var result = (this.__filtered__ && !index)
? new LazyWrapper(this)
: this.clone();
if (result.__filtered__) {
result.__takeCount__ = nativeMin(n, result.__takeCount__);
} else {
result.__views__.push({
'size': nativeMin(n, MAX_ARRAY_LENGTH),
'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
});
}
return result;
};
LazyWrapper.prototype[methodName + 'Right'] = function(n) {
return this.reverse()[methodName](n).reverse();
};
});
// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
var type = index + 1,
isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
LazyWrapper.prototype[methodName] = function(iteratee) {
var result = this.clone();
result.__iteratees__.push({
'iteratee': getIteratee(iteratee, 3),
'type': type
});
result.__filtered__ = result.__filtered__ || isFilter;
return result;
};
});
// Add `LazyWrapper` methods for `_.head` and `_.last`.
arrayEach(['head', 'last'], function(methodName, index) {
var takeName = 'take' + (index ? 'Right' : '');
LazyWrapper.prototype[methodName] = function() {
return this[takeName](1).value()[0];
};
});
// Add `LazyWrapper` methods for `_.initial` and `_.tail`.
arrayEach(['initial', 'tail'], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
};
});
LazyWrapper.prototype.compact = function() {
return this.filter(identity);
};
LazyWrapper.prototype.find = function(predicate) {
return this.filter(predicate).head();
};
LazyWrapper.prototype.findLast = function(predicate) {
return this.reverse().find(predicate);
};
LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
if (typeof path == 'function') {
return new LazyWrapper(this);
}
return this.map(function(value) {
return baseInvoke(value, path, args);
});
});
LazyWrapper.prototype.reject = function(predicate) {
return this.filter(negate(getIteratee(predicate)));
};
LazyWrapper.prototype.slice = function(start, end) {
start = toInteger(start);
var result = this;
if (result.__filtered__ && (start > 0 || end < 0)) {
return new LazyWrapper(result);
}
if (start < 0) {
result = result.takeRight(-start);
} else if (start) {
result = result.drop(start);
}
if (end !== undefined) {
end = toInteger(end);
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
}
return result;
};
LazyWrapper.prototype.takeRightWhile = function(predicate) {
return this.reverse().takeWhile(predicate).reverse();
};
LazyWrapper.prototype.toArray = function() {
return this.take(MAX_ARRAY_LENGTH);
};
// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
isTaker = /^(?:head|last)$/.test(methodName),
lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
retUnwrapped = isTaker || /^find/.test(methodName);
if (!lodashFunc) {
return;
}
lodash.prototype[methodName] = function() {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
};
});
// Add `Array` methods to `lodash.prototype`.
arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
var func = arrayProto[methodName],
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
retUnwrapped = /^(?:pop|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
};
});
// Map minified method names to their real names.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName];
if (lodashFunc) {
var key = lodashFunc.name + '';
if (!hasOwnProperty.call(realNames, key)) {
realNames[key] = [];
}
realNames[key].push({ 'name': methodName, 'func': lodashFunc });
}
});
realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
'name': 'wrapper',
'func': undefined
}];
// Add methods to `LazyWrapper`.
LazyWrapper.prototype.clone = lazyClone;
LazyWrapper.prototype.reverse = lazyReverse;
LazyWrapper.prototype.value = lazyValue;
// Add chain sequence methods to the `lodash` wrapper.
lodash.prototype.at = wrapperAt;
lodash.prototype.chain = wrapperChain;
lodash.prototype.commit = wrapperCommit;
lodash.prototype.next = wrapperNext;
lodash.prototype.plant = wrapperPlant;
lodash.prototype.reverse = wrapperReverse;
lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
// Add lazy aliases.
lodash.prototype.first = lodash.prototype.head;
if (symIterator) {
lodash.prototype[symIterator] = wrapperToIterator;
}
return lodash;
});
/*--------------------------------------------------------------------------*/
// Export lodash.
var _ = runInContext();
// Some AMD build optimizers, like r.js, check for condition patterns like:
if (true) {
// Expose Lodash on the global object to prevent errors when Lodash is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
// Use `_.noConflict` to remove Lodash from the global object.
root._ = _;
// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return _;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
// Check for `exports` after `define` in case a build optimizer adds it.
else {}
}.call(this));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)(module)))
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
(function(root) {
const MAX_VALUE = 0x7fffffff;
// The SHA256 and PBKDF2 implementation are from scrypt-async-js:
// See: https://github.com/dchest/scrypt-async-js
function SHA256(m) {
const K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;
let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
const w = new Uint32Array(64);
function blocks(p) {
let off = 0, len = p.length;
while (len >= 64) {
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7, u, i, j, t1, t2;
for (i = 0; i < 16; i++) {
j = off + i*4;
w[i] = ((p[j] & 0xff)<<24) | ((p[j+1] & 0xff)<<16) |
((p[j+2] & 0xff)<<8) | (p[j+3] & 0xff);
}
for (i = 16; i < 64; i++) {
u = w[i-2];
t1 = ((u>>>17) | (u<<(32-17))) ^ ((u>>>19) | (u<<(32-19))) ^ (u>>>10);
u = w[i-15];
t2 = ((u>>>7) | (u<<(32-7))) ^ ((u>>>18) | (u<<(32-18))) ^ (u>>>3);
w[i] = (((t1 + w[i-7]) | 0) + ((t2 + w[i-16]) | 0)) | 0;
}
for (i = 0; i < 64; i++) {
t1 = ((((((e>>>6) | (e<<(32-6))) ^ ((e>>>11) | (e<<(32-11))) ^
((e>>>25) | (e<<(32-25)))) + ((e & f) ^ (~e & g))) | 0) +
((h + ((K[i] + w[i]) | 0)) | 0)) | 0;
t2 = ((((a>>>2) | (a<<(32-2))) ^ ((a>>>13) | (a<<(32-13))) ^
((a>>>22) | (a<<(32-22)))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
h0 = (h0 + a) | 0;
h1 = (h1 + b) | 0;
h2 = (h2 + c) | 0;
h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0;
h5 = (h5 + f) | 0;
h6 = (h6 + g) | 0;
h7 = (h7 + h) | 0;
off += 64;
len -= 64;
}
}
blocks(m);
let i, bytesLeft = m.length % 64,
bitLenHi = (m.length / 0x20000000) | 0,
bitLenLo = m.length << 3,
numZeros = (bytesLeft < 56) ? 56 : 120,
p = m.slice(m.length - bytesLeft, m.length);
p.push(0x80);
for (i = bytesLeft + 1; i < numZeros; i++) { p.push(0); }
p.push((bitLenHi >>> 24) & 0xff);
p.push((bitLenHi >>> 16) & 0xff);
p.push((bitLenHi >>> 8) & 0xff);
p.push((bitLenHi >>> 0) & 0xff);
p.push((bitLenLo >>> 24) & 0xff);
p.push((bitLenLo >>> 16) & 0xff);
p.push((bitLenLo >>> 8) & 0xff);
p.push((bitLenLo >>> 0) & 0xff);
blocks(p);
return [
(h0 >>> 24) & 0xff, (h0 >>> 16) & 0xff, (h0 >>> 8) & 0xff, (h0 >>> 0) & 0xff,
(h1 >>> 24) & 0xff, (h1 >>> 16) & 0xff, (h1 >>> 8) & 0xff, (h1 >>> 0) & 0xff,
(h2 >>> 24) & 0xff, (h2 >>> 16) & 0xff, (h2 >>> 8) & 0xff, (h2 >>> 0) & 0xff,
(h3 >>> 24) & 0xff, (h3 >>> 16) & 0xff, (h3 >>> 8) & 0xff, (h3 >>> 0) & 0xff,
(h4 >>> 24) & 0xff, (h4 >>> 16) & 0xff, (h4 >>> 8) & 0xff, (h4 >>> 0) & 0xff,
(h5 >>> 24) & 0xff, (h5 >>> 16) & 0xff, (h5 >>> 8) & 0xff, (h5 >>> 0) & 0xff,
(h6 >>> 24) & 0xff, (h6 >>> 16) & 0xff, (h6 >>> 8) & 0xff, (h6 >>> 0) & 0xff,
(h7 >>> 24) & 0xff, (h7 >>> 16) & 0xff, (h7 >>> 8) & 0xff, (h7 >>> 0) & 0xff
];
}
function PBKDF2_HMAC_SHA256_OneIter(password, salt, dkLen) {
// compress password if it's longer than hash block length
password = (password.length <= 64) ? password : SHA256(password);
const innerLen = 64 + salt.length + 4;
const inner = new Array(innerLen);
const outerKey = new Array(64);
let i;
let dk = [];
// inner = (password ^ ipad) || salt || counter
for (i = 0; i < 64; i++) { inner[i] = 0x36; }
for (i = 0; i < password.length; i++) { inner[i] ^= password[i]; }
for (i = 0; i < salt.length; i++) { inner[64 + i] = salt[i]; }
for (i = innerLen - 4; i < innerLen; i++) { inner[i] = 0; }
// outerKey = password ^ opad
for (i = 0; i < 64; i++) outerKey[i] = 0x5c;
for (i = 0; i < password.length; i++) outerKey[i] ^= password[i];
// increments counter inside inner
function incrementCounter() {
for (let i = innerLen - 1; i >= innerLen - 4; i--) {
inner[i]++;
if (inner[i] <= 0xff) return;
inner[i] = 0;
}
}
// output blocks = SHA256(outerKey || SHA256(inner)) ...
while (dkLen >= 32) {
incrementCounter();
dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))));
dkLen -= 32;
}
if (dkLen > 0) {
incrementCounter();
dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))).slice(0, dkLen));
}
return dk;
}
// The following is an adaptation of scryptsy
// See: https://www.npmjs.com/package/scryptsy
function blockmix_salsa8(BY, Yi, r, x, _X) {
let i;
arraycopy(BY, (2 * r - 1) * 16, _X, 0, 16);
for (i = 0; i < 2 * r; i++) {
blockxor(BY, i * 16, _X, 16);
salsa20_8(_X, x);
arraycopy(_X, 0, BY, Yi + (i * 16), 16);
}
for (i = 0; i < r; i++) {
arraycopy(BY, Yi + (i * 2) * 16, BY, (i * 16), 16);
}
for (i = 0; i < r; i++) {
arraycopy(BY, Yi + (i * 2 + 1) * 16, BY, (i + r) * 16, 16);
}
}
function R(a, b) {
return (a << b) | (a >>> (32 - b));
}
function salsa20_8(B, x) {
arraycopy(B, 0, x, 0, 16);
for (let i = 8; i > 0; i -= 2) {
x[ 4] ^= R(x[ 0] + x[12], 7);
x[ 8] ^= R(x[ 4] + x[ 0], 9);
x[12] ^= R(x[ 8] + x[ 4], 13);
x[ 0] ^= R(x[12] + x[ 8], 18);
x[ 9] ^= R(x[ 5] + x[ 1], 7);
x[13] ^= R(x[ 9] + x[ 5], 9);
x[ 1] ^= R(x[13] + x[ 9], 13);
x[ 5] ^= R(x[ 1] + x[13], 18);
x[14] ^= R(x[10] + x[ 6], 7);
x[ 2] ^= R(x[14] + x[10], 9);
x[ 6] ^= R(x[ 2] + x[14], 13);
x[10] ^= R(x[ 6] + x[ 2], 18);
x[ 3] ^= R(x[15] + x[11], 7);
x[ 7] ^= R(x[ 3] + x[15], 9);
x[11] ^= R(x[ 7] + x[ 3], 13);
x[15] ^= R(x[11] + x[ 7], 18);
x[ 1] ^= R(x[ 0] + x[ 3], 7);
x[ 2] ^= R(x[ 1] + x[ 0], 9);
x[ 3] ^= R(x[ 2] + x[ 1], 13);
x[ 0] ^= R(x[ 3] + x[ 2], 18);
x[ 6] ^= R(x[ 5] + x[ 4], 7);
x[ 7] ^= R(x[ 6] + x[ 5], 9);
x[ 4] ^= R(x[ 7] + x[ 6], 13);
x[ 5] ^= R(x[ 4] + x[ 7], 18);
x[11] ^= R(x[10] + x[ 9], 7);
x[ 8] ^= R(x[11] + x[10], 9);
x[ 9] ^= R(x[ 8] + x[11], 13);
x[10] ^= R(x[ 9] + x[ 8], 18);
x[12] ^= R(x[15] + x[14], 7);
x[13] ^= R(x[12] + x[15], 9);
x[14] ^= R(x[13] + x[12], 13);
x[15] ^= R(x[14] + x[13], 18);
}
for (let i = 0; i < 16; ++i) {
B[i] += x[i];
}
}
// naive approach... going back to loop unrolling may yield additional performance
function blockxor(S, Si, D, len) {
for (let i = 0; i < len; i++) {
D[i] ^= S[Si + i]
}
}
function arraycopy(src, srcPos, dest, destPos, length) {
while (length--) {
dest[destPos++] = src[srcPos++];
}
}
function checkBufferish(o) {
if (!o || typeof(o.length) !== 'number') { return false; }
for (let i = 0; i < o.length; i++) {
const v = o[i];
if (typeof(v) !== 'number' || v % 1 || v < 0 || v >= 256) {
return false;
}
}
return true;
}
function ensureInteger(value, name) {
if (typeof(value) !== "number" || (value % 1)) { throw new Error('invalid ' + name); }
return value;
}
// N = Cpu cost, r = Memory cost, p = parallelization cost
// callback(error, progress, key)
function _scrypt(password, salt, N, r, p, dkLen, callback) {
N = ensureInteger(N, 'N');
r = ensureInteger(r, 'r');
p = ensureInteger(p, 'p');
dkLen = ensureInteger(dkLen, 'dkLen');
if (N === 0 || (N & (N - 1)) !== 0) { throw new Error('N must be power of 2'); }
if (N > MAX_VALUE / 128 / r) { throw new Error('N too large'); }
if (r > MAX_VALUE / 128 / p) { throw new Error('r too large'); }
if (!checkBufferish(password)) {
throw new Error('password must be an array or buffer');
}
password = Array.prototype.slice.call(password);
if (!checkBufferish(salt)) {
throw new Error('salt must be an array or buffer');
}
salt = Array.prototype.slice.call(salt);
let b = PBKDF2_HMAC_SHA256_OneIter(password, salt, p * 128 * r);
const B = new Uint32Array(p * 32 * r)
for (let i = 0; i < B.length; i++) {
const j = i * 4;
B[i] = ((b[j + 3] & 0xff) << 24) |
((b[j + 2] & 0xff) << 16) |
((b[j + 1] & 0xff) << 8) |
((b[j + 0] & 0xff) << 0);
}
const XY = new Uint32Array(64 * r);
const V = new Uint32Array(32 * r * N);
const Yi = 32 * r;
// scratch space
const x = new Uint32Array(16); // salsa20_8
const _X = new Uint32Array(16); // blockmix_salsa8
const totalOps = p * N * 2;
let currentOp = 0;
let lastPercent10 = null;
// Set this to true to abandon the scrypt on the next step
let stop = false;
// State information
let state = 0;
let i0 = 0, i1;
let Bi;
// How many blockmix_salsa8 can we do per step?
const limit = callback ? parseInt(1000 / r): 0xffffffff;
// Trick from scrypt-async; if there is a setImmediate shim in place, use it
const nextTick = (typeof(setImmediate) !== 'undefined') ? setImmediate : setTimeout;
// This is really all I changed; making scryptsy a state machine so we occasionally
// stop and give other evnts on the evnt loop a chance to run. ~RicMoo
const incrementalSMix = function() {
if (stop) {
return callback(new Error('cancelled'), currentOp / totalOps);
}
let steps;
switch (state) {
case 0:
// for (var i = 0; i < p; i++)...
Bi = i0 * 32 * r;
arraycopy(B, Bi, XY, 0, Yi); // ROMix - 1
state = 1; // Move to ROMix 2
i1 = 0;
// Fall through
case 1:
// Run up to 1000 steps of the first inner smix loop
steps = N - i1;
if (steps > limit) { steps = limit; }
for (let i = 0; i < steps; i++) { // ROMix - 2
arraycopy(XY, 0, V, (i1 + i) * Yi, Yi) // ROMix - 3
blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 4
}
// for (var i = 0; i < N; i++)
i1 += steps;
currentOp += steps;
if (callback) {
// Call the callback with the progress (optionally stopping us)
const percent10 = parseInt(1000 * currentOp / totalOps);
if (percent10 !== lastPercent10) {
stop = callback(null, currentOp / totalOps);
if (stop) { break; }
lastPercent10 = percent10;
}
}
if (i1 < N) { break; }
i1 = 0; // Move to ROMix 6
state = 2;
// Fall through
case 2:
// Run up to 1000 steps of the second inner smix loop
steps = N - i1;
if (steps > limit) { steps = limit; }
for (let i = 0; i < steps; i++) { // ROMix - 6
const offset = (2 * r - 1) * 16; // ROMix - 7
const j = XY[offset] & (N - 1);
blockxor(V, j * Yi, XY, Yi); // ROMix - 8 (inner)
blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 9 (outer)
}
// for (var i = 0; i < N; i++)...
i1 += steps;
currentOp += steps;
// Call the callback with the progress (optionally stopping us)
if (callback) {
const percent10 = parseInt(1000 * currentOp / totalOps);
if (percent10 !== lastPercent10) {
stop = callback(null, currentOp / totalOps);
if (stop) { break; }
lastPercent10 = percent10;
}
}
if (i1 < N) { break; }
arraycopy(XY, 0, B, Bi, Yi); // ROMix - 10
// for (var i = 0; i < p; i++)...
i0++;
if (i0 < p) {
state = 0;
break;
}
b = [];
for (let i = 0; i < B.length; i++) {
b.push((B[i] >> 0) & 0xff);
b.push((B[i] >> 8) & 0xff);
b.push((B[i] >> 16) & 0xff);
b.push((B[i] >> 24) & 0xff);
}
const derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen);
// Send the result to the callback
if (callback) { callback(null, 1.0, derivedKey); }
// Done; don't break (which would reschedule)
return derivedKey;
}
// Schedule the next steps
if (callback) { nextTick(incrementalSMix); }
}
// Run the smix state machine until completion
if (!callback) {
while (true) {
const derivedKey = incrementalSMix();
if (derivedKey != undefined) { return derivedKey; }
}
}
// Bootstrap the async incremental smix
incrementalSMix();
}
const lib = {
scrypt: function(password, salt, N, r, p, dkLen, progressCallback) {
return new Promise(function(resolve, reject) {
let lastProgress = 0;
if (progressCallback) { progressCallback(0); }
_scrypt(password, salt, N, r, p, dkLen, function(error, progress, key) {
if (error) {
reject(error);
} else if (key) {
if (progressCallback && lastProgress !== 1) {
progressCallback(1);
}
resolve(new Uint8Array(key));
} else if (progressCallback && progress !== lastProgress) {
lastProgress = progress;
return progressCallback(progress);
}
});
});
},
syncScrypt: function(password, salt, N, r, p, dkLen) {
return new Uint8Array(_scrypt(password, salt, N, r, p, dkLen));
}
};
// node.js
if (true) {
module.exports = lib;
// RequireJS/AMD
// http://www.requirejs.org/docs/api.html
// https://github.com/amdjs/amdjs-api/wiki/AMD
} else {}
})(this);
/***/ }),
/* 16 */,
/* 17 */,
/* 18 */
/***/ (function(module, exports) {
module.exports = function(module) {
if (!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if (!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 19 */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
// pre-compute lookup table
var ALPHABET_MAP = {}
for (var z = 0; z < ALPHABET.length; z++) {
var x = ALPHABET.charAt(z)
if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
ALPHABET_MAP[x] = z
}
function polymodStep (pre) {
var b = pre >> 25
return ((pre & 0x1FFFFFF) << 5) ^
(-((b >> 0) & 1) & 0x3b6a57b2) ^
(-((b >> 1) & 1) & 0x26508e6d) ^
(-((b >> 2) & 1) & 0x1ea119fa) ^
(-((b >> 3) & 1) & 0x3d4233dd) ^
(-((b >> 4) & 1) & 0x2a1462b3)
}
function prefixChk (prefix) {
var chk = 1
for (var i = 0; i < prefix.length; ++i) {
var c = prefix.charCodeAt(i)
if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')'
chk = polymodStep(chk) ^ (c >> 5)
}
chk = polymodStep(chk)
for (i = 0; i < prefix.length; ++i) {
var v = prefix.charCodeAt(i)
chk = polymodStep(chk) ^ (v & 0x1f)
}
return chk
}
function encode (prefix, words, LIMIT) {
LIMIT = LIMIT || 90
if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit')
prefix = prefix.toLowerCase()
// determine chk mod
var chk = prefixChk(prefix)
if (typeof chk === 'string') throw new Error(chk)
var result = prefix + '1'
for (var i = 0; i < words.length; ++i) {
var x = words[i]
if ((x >> 5) !== 0) throw new Error('Non 5-bit word')
chk = polymodStep(chk) ^ x
result += ALPHABET.charAt(x)
}
for (i = 0; i < 6; ++i) {
chk = polymodStep(chk)
}
chk ^= 1
for (i = 0; i < 6; ++i) {
var v = (chk >> ((5 - i) * 5)) & 0x1f
result += ALPHABET.charAt(v)
}
return result
}
function __decode (str, LIMIT) {
LIMIT = LIMIT || 90
if (str.length < 8) return str + ' too short'
if (str.length > LIMIT) return 'Exceeds length limit'
// don't allow mixed case
var lowered = str.toLowerCase()
var uppered = str.toUpperCase()
if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str
str = lowered
var split = str.lastIndexOf('1')
if (split === -1) return 'No separator character for ' + str
if (split === 0) return 'Missing prefix for ' + str
var prefix = str.slice(0, split)
var wordChars = str.slice(split + 1)
if (wordChars.length < 6) return 'Data too short'
var chk = prefixChk(prefix)
if (typeof chk === 'string') return chk
var words = []
for (var i = 0; i < wordChars.length; ++i) {
var c = wordChars.charAt(i)
var v = ALPHABET_MAP[c]
if (v === undefined) return 'Unknown character ' + c
chk = polymodStep(chk) ^ v
// not in the checksum?
if (i + 6 >= wordChars.length) continue
words.push(v)
}
if (chk !== 1) return 'Invalid checksum for ' + str
return { prefix: prefix, words: words }
}
function decodeUnsafe () {
var res = __decode.apply(null, arguments)
if (typeof res === 'object') return res
}
function decode (str) {
var res = __decode.apply(null, arguments)
if (typeof res === 'object') return res
throw new Error(res)
}
function convert (data, inBits, outBits, pad) {
var value = 0
var bits = 0
var maxV = (1 << outBits) - 1
var result = []
for (var i = 0; i < data.length; ++i) {
value = (value << inBits) | data[i]
bits += inBits
while (bits >= outBits) {
bits -= outBits
result.push((value >> bits) & maxV)
}
}
if (pad) {
if (bits > 0) {
result.push((value << (outBits - bits)) & maxV)
}
} else {
if (bits >= inBits) return 'Excess padding'
if ((value << (outBits - bits)) & maxV) return 'Non-zero padding'
}
return result
}
function toWordsUnsafe (bytes) {
var res = convert(bytes, 8, 5, true)
if (Array.isArray(res)) return res
}
function toWords (bytes) {
var res = convert(bytes, 8, 5, true)
if (Array.isArray(res)) return res
throw new Error(res)
}
function fromWordsUnsafe (words) {
var res = convert(words, 5, 8, false)
if (Array.isArray(res)) return res
}
function fromWords (words) {
var res = convert(words, 5, 8, false)
if (Array.isArray(res)) return res
throw new Error(res)
}
module.exports = {
decodeUnsafe: decodeUnsafe,
decode: decode,
encode: encode,
toWordsUnsafe: toWordsUnsafe,
toWords: toWords,
fromWordsUnsafe: fromWordsUnsafe,
fromWords: fromWords
}
/***/ }),
/* 21 */,
/* 22 */,
/* 23 */,
/* 24 */
/***/ (function(module, exports) {
module.exports = require("buffer");
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var rotr32 = utils.rotr32;
function ft_1(s, x, y, z) {
if (s === 0)
return ch32(x, y, z);
if (s === 1 || s === 3)
return p32(x, y, z);
if (s === 2)
return maj32(x, y, z);
}
exports.ft_1 = ft_1;
function ch32(x, y, z) {
return (x & y) ^ ((~x) & z);
}
exports.ch32 = ch32;
function maj32(x, y, z) {
return (x & y) ^ (x & z) ^ (y & z);
}
exports.maj32 = maj32;
function p32(x, y, z) {
return x ^ y ^ z;
}
exports.p32 = p32;
function s0_256(x) {
return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
}
exports.s0_256 = s0_256;
function s1_256(x) {
return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
}
exports.s1_256 = s1_256;
function g0_256(x) {
return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
}
exports.g0_256 = g0_256;
function g1_256(x) {
return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
}
exports.g1_256 = g1_256;
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var common = __webpack_require__(12);
var shaCommon = __webpack_require__(25);
var assert = __webpack_require__(11);
var sum32 = utils.sum32;
var sum32_4 = utils.sum32_4;
var sum32_5 = utils.sum32_5;
var ch32 = shaCommon.ch32;
var maj32 = shaCommon.maj32;
var s0_256 = shaCommon.s0_256;
var s1_256 = shaCommon.s1_256;
var g0_256 = shaCommon.g0_256;
var g1_256 = shaCommon.g1_256;
var BlockHash = common.BlockHash;
var sha256_K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
function SHA256() {
if (!(this instanceof SHA256))
return new SHA256();
BlockHash.call(this);
this.h = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
];
this.k = sha256_K;
this.W = new Array(64);
}
utils.inherits(SHA256, BlockHash);
module.exports = SHA256;
SHA256.blockSize = 512;
SHA256.outSize = 256;
SHA256.hmacStrength = 192;
SHA256.padLength = 64;
SHA256.prototype._update = function _update(msg, start) {
var W = this.W;
for (var i = 0; i < 16; i++)
W[i] = msg[start + i];
for (; i < W.length; i++)
W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
var a = this.h[0];
var b = this.h[1];
var c = this.h[2];
var d = this.h[3];
var e = this.h[4];
var f = this.h[5];
var g = this.h[6];
var h = this.h[7];
assert(this.k.length === W.length);
for (i = 0; i < W.length; i++) {
var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
var T2 = sum32(s0_256(a), maj32(a, b, c));
h = g;
g = f;
f = e;
e = sum32(d, T1);
d = c;
c = b;
b = a;
a = sum32(T1, T2);
}
this.h[0] = sum32(this.h[0], a);
this.h[1] = sum32(this.h[1], b);
this.h[2] = sum32(this.h[2], c);
this.h[3] = sum32(this.h[3], d);
this.h[4] = sum32(this.h[4], e);
this.h[5] = sum32(this.h[5], f);
this.h[6] = sum32(this.h[6], g);
this.h[7] = sum32(this.h[7], h);
};
SHA256.prototype._digest = function digest(enc) {
if (enc === 'hex')
return utils.toHex32(this.h, 'big');
else
return utils.split32(this.h, 'big');
};
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var common = __webpack_require__(12);
var assert = __webpack_require__(11);
var rotr64_hi = utils.rotr64_hi;
var rotr64_lo = utils.rotr64_lo;
var shr64_hi = utils.shr64_hi;
var shr64_lo = utils.shr64_lo;
var sum64 = utils.sum64;
var sum64_hi = utils.sum64_hi;
var sum64_lo = utils.sum64_lo;
var sum64_4_hi = utils.sum64_4_hi;
var sum64_4_lo = utils.sum64_4_lo;
var sum64_5_hi = utils.sum64_5_hi;
var sum64_5_lo = utils.sum64_5_lo;
var BlockHash = common.BlockHash;
var sha512_K = [
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];
function SHA512() {
if (!(this instanceof SHA512))
return new SHA512();
BlockHash.call(this);
this.h = [
0x6a09e667, 0xf3bcc908,
0xbb67ae85, 0x84caa73b,
0x3c6ef372, 0xfe94f82b,
0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1,
0x9b05688c, 0x2b3e6c1f,
0x1f83d9ab, 0xfb41bd6b,
0x5be0cd19, 0x137e2179 ];
this.k = sha512_K;
this.W = new Array(160);
}
utils.inherits(SHA512, BlockHash);
module.exports = SHA512;
SHA512.blockSize = 1024;
SHA512.outSize = 512;
SHA512.hmacStrength = 192;
SHA512.padLength = 128;
SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
var W = this.W;
// 32 x 32bit words
for (var i = 0; i < 32; i++)
W[i] = msg[start + i];
for (; i < W.length; i += 2) {
var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
var c1_hi = W[i - 14]; // i - 7
var c1_lo = W[i - 13];
var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
var c3_hi = W[i - 32]; // i - 16
var c3_lo = W[i - 31];
W[i] = sum64_4_hi(
c0_hi, c0_lo,
c1_hi, c1_lo,
c2_hi, c2_lo,
c3_hi, c3_lo);
W[i + 1] = sum64_4_lo(
c0_hi, c0_lo,
c1_hi, c1_lo,
c2_hi, c2_lo,
c3_hi, c3_lo);
}
};
SHA512.prototype._update = function _update(msg, start) {
this._prepareBlock(msg, start);
var W = this.W;
var ah = this.h[0];
var al = this.h[1];
var bh = this.h[2];
var bl = this.h[3];
var ch = this.h[4];
var cl = this.h[5];
var dh = this.h[6];
var dl = this.h[7];
var eh = this.h[8];
var el = this.h[9];
var fh = this.h[10];
var fl = this.h[11];
var gh = this.h[12];
var gl = this.h[13];
var hh = this.h[14];
var hl = this.h[15];
assert(this.k.length === W.length);
for (var i = 0; i < W.length; i += 2) {
var c0_hi = hh;
var c0_lo = hl;
var c1_hi = s1_512_hi(eh, el);
var c1_lo = s1_512_lo(eh, el);
var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
var c3_hi = this.k[i];
var c3_lo = this.k[i + 1];
var c4_hi = W[i];
var c4_lo = W[i + 1];
var T1_hi = sum64_5_hi(
c0_hi, c0_lo,
c1_hi, c1_lo,
c2_hi, c2_lo,
c3_hi, c3_lo,
c4_hi, c4_lo);
var T1_lo = sum64_5_lo(
c0_hi, c0_lo,
c1_hi, c1_lo,
c2_hi, c2_lo,
c3_hi, c3_lo,
c4_hi, c4_lo);
c0_hi = s0_512_hi(ah, al);
c0_lo = s0_512_lo(ah, al);
c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
eh = sum64_hi(dh, dl, T1_hi, T1_lo);
el = sum64_lo(dl, dl, T1_hi, T1_lo);
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
}
sum64(this.h, 0, ah, al);
sum64(this.h, 2, bh, bl);
sum64(this.h, 4, ch, cl);
sum64(this.h, 6, dh, dl);
sum64(this.h, 8, eh, el);
sum64(this.h, 10, fh, fl);
sum64(this.h, 12, gh, gl);
sum64(this.h, 14, hh, hl);
};
SHA512.prototype._digest = function digest(enc) {
if (enc === 'hex')
return utils.toHex32(this.h, 'big');
else
return utils.split32(this.h, 'big');
};
function ch64_hi(xh, xl, yh, yl, zh) {
var r = (xh & yh) ^ ((~xh) & zh);
if (r < 0)
r += 0x100000000;
return r;
}
function ch64_lo(xh, xl, yh, yl, zh, zl) {
var r = (xl & yl) ^ ((~xl) & zl);
if (r < 0)
r += 0x100000000;
return r;
}
function maj64_hi(xh, xl, yh, yl, zh) {
var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
if (r < 0)
r += 0x100000000;
return r;
}
function maj64_lo(xh, xl, yh, yl, zh, zl) {
var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
if (r < 0)
r += 0x100000000;
return r;
}
function s0_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 28);
var c1_hi = rotr64_hi(xl, xh, 2); // 34
var c2_hi = rotr64_hi(xl, xh, 7); // 39
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function s0_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 28);
var c1_lo = rotr64_lo(xl, xh, 2); // 34
var c2_lo = rotr64_lo(xl, xh, 7); // 39
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function s1_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 14);
var c1_hi = rotr64_hi(xh, xl, 18);
var c2_hi = rotr64_hi(xl, xh, 9); // 41
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function s1_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 14);
var c1_lo = rotr64_lo(xh, xl, 18);
var c2_lo = rotr64_lo(xl, xh, 9); // 41
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function g0_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 1);
var c1_hi = rotr64_hi(xh, xl, 8);
var c2_hi = shr64_hi(xh, xl, 7);
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function g0_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 1);
var c1_lo = rotr64_lo(xh, xl, 8);
var c2_lo = shr64_lo(xh, xl, 7);
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function g1_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 19);
var c1_hi = rotr64_hi(xl, xh, 29); // 61
var c2_hi = shr64_hi(xh, xl, 6);
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function g1_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 19);
var c1_lo = rotr64_lo(xl, xh, 29); // 61
var c2_lo = shr64_lo(xh, xl, 6);
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) {
'use strict';
// Utils
function assert (val, msg) {
if (!val) throw new Error(msg || 'Assertion failed');
}
// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits (ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
// BN
function BN (number, base, endian) {
if (BN.isBN(number)) {
return number;
}
this.negative = 0;
this.words = null;
this.length = 0;
// Reduction context
this.red = null;
if (number !== null) {
if (base === 'le' || base === 'be') {
endian = base;
base = 10;
}
this._init(number || 0, base || 10, endian || 'be');
}
}
if (typeof module === 'object') {
module.exports = BN;
} else {
exports.BN = BN;
}
BN.BN = BN;
BN.wordSize = 26;
var Buffer;
try {
if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
Buffer = window.Buffer;
} else {
Buffer = __webpack_require__(24).Buffer;
}
} catch (e) {
}
BN.isBN = function isBN (num) {
if (num instanceof BN) {
return true;
}
return num !== null && typeof num === 'object' &&
num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
};
BN.max = function max (left, right) {
if (left.cmp(right) > 0) return left;
return right;
};
BN.min = function min (left, right) {
if (left.cmp(right) < 0) return left;
return right;
};
BN.prototype._init = function init (number, base, endian) {
if (typeof number === 'number') {
return this._initNumber(number, base, endian);
}
if (typeof number === 'object') {
return this._initArray(number, base, endian);
}
if (base === 'hex') {
base = 16;
}
assert(base === (base | 0) && base >= 2 && base <= 36);
number = number.toString().replace(/\s+/g, '');
var start = 0;
if (number[0] === '-') {
start++;
this.negative = 1;
}
if (start < number.length) {
if (base === 16) {
this._parseHex(number, start, endian);
} else {
this._parseBase(number, base, start);
if (endian === 'le') {
this._initArray(this.toArray(), base, endian);
}
}
}
};
BN.prototype._initNumber = function _initNumber (number, base, endian) {
if (number < 0) {
this.negative = 1;
number = -number;
}
if (number < 0x4000000) {
this.words = [number & 0x3ffffff];
this.length = 1;
} else if (number < 0x10000000000000) {
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff
];
this.length = 2;
} else {
assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff,
1
];
this.length = 3;
}
if (endian !== 'le') return;
// Reverse the bytes
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initArray = function _initArray (number, base, endian) {
// Perhaps a Uint8Array
assert(typeof number.length === 'number');
if (number.length <= 0) {
this.words = [0];
this.length = 1;
return this;
}
this.length = Math.ceil(number.length / 3);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
this.words[i] = 0;
}
var j, w;
var off = 0;
if (endian === 'be') {
for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
} else if (endian === 'le') {
for (i = 0, j = 0; i < number.length; i += 3) {
w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
}
return this._strip();
};
function parseHex4Bits (string, index) {
var c = string.charCodeAt(index);
// '0' - '9'
if (c >= 48 && c <= 57) {
return c - 48;
// 'A' - 'F'
} else if (c >= 65 && c <= 70) {
return c - 55;
// 'a' - 'f'
} else if (c >= 97 && c <= 102) {
return c - 87;
} else {
assert(false, 'Invalid character in ' + string);
}
}
function parseHexByte (string, lowerBound, index) {
var r = parseHex4Bits(string, index);
if (index - 1 >= lowerBound) {
r |= parseHex4Bits(string, index - 1) << 4;
}
return r;
}
BN.prototype._parseHex = function _parseHex (number, start, endian) {
// Create possibly bigger array to ensure that it fits the number
this.length = Math.ceil((number.length - start) / 6);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
this.words[i] = 0;
}
// 24-bits chunks
var off = 0;
var j = 0;
var w;
if (endian === 'be') {
for (i = number.length - 1; i >= start; i -= 2) {
w = parseHexByte(number, start, i) << off;
this.words[j] |= w & 0x3ffffff;
if (off >= 18) {
off -= 18;
j += 1;
this.words[j] |= w >>> 26;
} else {
off += 8;
}
}
} else {
var parseLength = number.length - start;
for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
w = parseHexByte(number, start, i) << off;
this.words[j] |= w & 0x3ffffff;
if (off >= 18) {
off -= 18;
j += 1;
this.words[j] |= w >>> 26;
} else {
off += 8;
}
}
}
this._strip();
};
function parseBase (str, start, end, mul) {
var r = 0;
var b = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r *= mul;
// 'a'
if (c >= 49) {
b = c - 49 + 0xa;
// 'A'
} else if (c >= 17) {
b = c - 17 + 0xa;
// '0' - '9'
} else {
b = c;
}
assert(c >= 0 && b < mul, 'Invalid character');
r += b;
}
return r;
}
BN.prototype._parseBase = function _parseBase (number, base, start) {
// Initialize as zero
this.words = [0];
this.length = 1;
// Find length of limb in base
for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
limbLen++;
}
limbLen--;
limbPow = (limbPow / base) | 0;
var total = number.length - start;
var mod = total % limbLen;
var end = Math.min(total, total - mod) + start;
var word = 0;
for (var i = start; i < end; i += limbLen) {
word = parseBase(number, i, i + limbLen, base);
this.imuln(limbPow);
if (this.words[0] + word < 0x4000000) {
this.words[0] += word;
} else {
this._iaddn(word);
}
}
if (mod !== 0) {
var pow = 1;
word = parseBase(number, i, number.length, base);
for (i = 0; i < mod; i++) {
pow *= base;
}
this.imuln(pow);
if (this.words[0] + word < 0x4000000) {
this.words[0] += word;
} else {
this._iaddn(word);
}
}
this._strip();
};
BN.prototype.copy = function copy (dest) {
dest.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
dest.words[i] = this.words[i];
}
dest.length = this.length;
dest.negative = this.negative;
dest.red = this.red;
};
function move (dest, src) {
dest.words = src.words;
dest.length = src.length;
dest.negative = src.negative;
dest.red = src.red;
}
BN.prototype._move = function _move (dest) {
move(dest, this);
};
BN.prototype.clone = function clone () {
var r = new BN(null);
this.copy(r);
return r;
};
BN.prototype._expand = function _expand (size) {
while (this.length < size) {
this.words[this.length++] = 0;
}
return this;
};
// Remove leading `0` from `this`
BN.prototype._strip = function strip () {
while (this.length > 1 && this.words[this.length - 1] === 0) {
this.length--;
}
return this._normSign();
};
BN.prototype._normSign = function _normSign () {
// -0 = 0
if (this.length === 1 && this.words[0] === 0) {
this.negative = 0;
}
return this;
};
// Check Symbol.for because not everywhere where Symbol defined
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {
try {
BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;
} catch (e) {
BN.prototype.inspect = inspect;
}
} else {
BN.prototype.inspect = inspect;
}
function inspect () {
return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
}
/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/
var zeros = [
'',
'0',
'00',
'000',
'0000',
'00000',
'000000',
'0000000',
'00000000',
'000000000',
'0000000000',
'00000000000',
'000000000000',
'0000000000000',
'00000000000000',
'000000000000000',
'0000000000000000',
'00000000000000000',
'000000000000000000',
'0000000000000000000',
'00000000000000000000',
'000000000000000000000',
'0000000000000000000000',
'00000000000000000000000',
'000000000000000000000000',
'0000000000000000000000000'
];
var groupSizes = [
0, 0,
25, 16, 12, 11, 10, 9, 8,
8, 7, 7, 7, 7, 6, 6,
6, 6, 6, 6, 6, 5, 5,
5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5
];
var groupBases = [
0, 0,
33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
];
BN.prototype.toString = function toString (base, padding) {
base = base || 10;
padding = padding | 0 || 1;
var out;
if (base === 16 || base === 'hex') {
out = '';
var off = 0;
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = this.words[i];
var word = (((w << off) | carry) & 0xffffff).toString(16);
carry = (w >>> (24 - off)) & 0xffffff;
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
if (carry !== 0 || i !== this.length - 1) {
out = zeros[6 - word.length] + word + out;
} else {
out = word + out;
}
}
if (carry !== 0) {
out = carry.toString(16) + out;
}
while (out.length % padding !== 0) {
out = '0' + out;
}
if (this.negative !== 0) {
out = '-' + out;
}
return out;
}
if (base === (base | 0) && base >= 2 && base <= 36) {
// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize = groupSizes[base];
// var groupBase = Math.pow(base, groupSize);
var groupBase = groupBases[base];
out = '';
var c = this.clone();
c.negative = 0;
while (!c.isZero()) {
var r = c.modrn(groupBase).toString(base);
c = c.idivn(groupBase);
if (!c.isZero()) {
out = zeros[groupSize - r.length] + r + out;
} else {
out = r + out;
}
}
if (this.isZero()) {
out = '0' + out;
}
while (out.length % padding !== 0) {
out = '0' + out;
}
if (this.negative !== 0) {
out = '-' + out;
}
return out;
}
assert(false, 'Base should be between 2 and 36');
};
BN.prototype.toNumber = function toNumber () {
var ret = this.words[0];
if (this.length === 2) {
ret += this.words[1] * 0x4000000;
} else if (this.length === 3 && this.words[2] === 0x01) {
// NOTE: at this stage it is known that the top bit is set
ret += 0x10000000000000 + (this.words[1] * 0x4000000);
} else if (this.length > 2) {
assert(false, 'Number can only safely store up to 53 bits');
}
return (this.negative !== 0) ? -ret : ret;
};
BN.prototype.toJSON = function toJSON () {
return this.toString(16, 2);
};
if (Buffer) {
BN.prototype.toBuffer = function toBuffer (endian, length) {
return this.toArrayLike(Buffer, endian, length);
};
}
BN.prototype.toArray = function toArray (endian, length) {
return this.toArrayLike(Array, endian, length);
};
var allocate = function allocate (ArrayType, size) {
if (ArrayType.allocUnsafe) {
return ArrayType.allocUnsafe(size);
}
return new ArrayType(size);
};
BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
this._strip();
var byteLength = this.byteLength();
var reqLength = length || Math.max(1, byteLength);
assert(byteLength <= reqLength, 'byte array longer than desired length');
assert(reqLength > 0, 'Requested array length <= 0');
var res = allocate(ArrayType, reqLength);
var postfix = endian === 'le' ? 'LE' : 'BE';
this['_toArrayLike' + postfix](res, byteLength);
return res;
};
BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {
var position = 0;
var carry = 0;
for (var i = 0, shift = 0; i < this.length; i++) {
var word = (this.words[i] << shift) | carry;
res[position++] = word & 0xff;
if (position < res.length) {
res[position++] = (word >> 8) & 0xff;
}
if (position < res.length) {
res[position++] = (word >> 16) & 0xff;
}
if (shift === 6) {
if (position < res.length) {
res[position++] = (word >> 24) & 0xff;
}
carry = 0;
shift = 0;
} else {
carry = word >>> 24;
shift += 2;
}
}
if (position < res.length) {
res[position++] = carry;
while (position < res.length) {
res[position++] = 0;
}
}
};
BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {
var position = res.length - 1;
var carry = 0;
for (var i = 0, shift = 0; i < this.length; i++) {
var word = (this.words[i] << shift) | carry;
res[position--] = word & 0xff;
if (position >= 0) {
res[position--] = (word >> 8) & 0xff;
}
if (position >= 0) {
res[position--] = (word >> 16) & 0xff;
}
if (shift === 6) {
if (position >= 0) {
res[position--] = (word >> 24) & 0xff;
}
carry = 0;
shift = 0;
} else {
carry = word >>> 24;
shift += 2;
}
}
if (position >= 0) {
res[position--] = carry;
while (position >= 0) {
res[position--] = 0;
}
}
};
if (Math.clz32) {
BN.prototype._countBits = function _countBits (w) {
return 32 - Math.clz32(w);
};
} else {
BN.prototype._countBits = function _countBits (w) {
var t = w;
var r = 0;
if (t >= 0x1000) {
r += 13;
t >>>= 13;
}
if (t >= 0x40) {
r += 7;
t >>>= 7;
}
if (t >= 0x8) {
r += 4;
t >>>= 4;
}
if (t >= 0x02) {
r += 2;
t >>>= 2;
}
return r + t;
};
}
BN.prototype._zeroBits = function _zeroBits (w) {
// Short-cut
if (w === 0) return 26;
var t = w;
var r = 0;
if ((t & 0x1fff) === 0) {
r += 13;
t >>>= 13;
}
if ((t & 0x7f) === 0) {
r += 7;
t >>>= 7;
}
if ((t & 0xf) === 0) {
r += 4;
t >>>= 4;
}
if ((t & 0x3) === 0) {
r += 2;
t >>>= 2;
}
if ((t & 0x1) === 0) {
r++;
}
return r;
};
// Return number of used bits in a BN
BN.prototype.bitLength = function bitLength () {
var w = this.words[this.length - 1];
var hi = this._countBits(w);
return (this.length - 1) * 26 + hi;
};
function toBitArray (num) {
var w = new Array(num.bitLength());
for (var bit = 0; bit < w.length; bit++) {
var off = (bit / 26) | 0;
var wbit = bit % 26;
w[bit] = (num.words[off] >>> wbit) & 0x01;
}
return w;
}
// Number of trailing zero bits
BN.prototype.zeroBits = function zeroBits () {
if (this.isZero()) return 0;
var r = 0;
for (var i = 0; i < this.length; i++) {
var b = this._zeroBits(this.words[i]);
r += b;
if (b !== 26) break;
}
return r;
};
BN.prototype.byteLength = function byteLength () {
return Math.ceil(this.bitLength() / 8);
};
BN.prototype.toTwos = function toTwos (width) {
if (this.negative !== 0) {
return this.abs().inotn(width).iaddn(1);
}
return this.clone();
};
BN.prototype.fromTwos = function fromTwos (width) {
if (this.testn(width - 1)) {
return this.notn(width).iaddn(1).ineg();
}
return this.clone();
};
BN.prototype.isNeg = function isNeg () {
return this.negative !== 0;
};
// Return negative clone of `this`
BN.prototype.neg = function neg () {
return this.clone().ineg();
};
BN.prototype.ineg = function ineg () {
if (!this.isZero()) {
this.negative ^= 1;
}
return this;
};
// Or `num` with `this` in-place
BN.prototype.iuor = function iuor (num) {
while (this.length < num.length) {
this.words[this.length++] = 0;
}
for (var i = 0; i < num.length; i++) {
this.words[i] = this.words[i] | num.words[i];
}
return this._strip();
};
BN.prototype.ior = function ior (num) {
assert((this.negative | num.negative) === 0);
return this.iuor(num);
};
// Or `num` with `this`
BN.prototype.or = function or (num) {
if (this.length > num.length) return this.clone().ior(num);
return num.clone().ior(this);
};
BN.prototype.uor = function uor (num) {
if (this.length > num.length) return this.clone().iuor(num);
return num.clone().iuor(this);
};
// And `num` with `this` in-place
BN.prototype.iuand = function iuand (num) {
// b = min-length(num, this)
var b;
if (this.length > num.length) {
b = num;
} else {
b = this;
}
for (var i = 0; i < b.length; i++) {
this.words[i] = this.words[i] & num.words[i];
}
this.length = b.length;
return this._strip();
};
BN.prototype.iand = function iand (num) {
assert((this.negative | num.negative) === 0);
return this.iuand(num);
};
// And `num` with `this`
BN.prototype.and = function and (num) {
if (this.length > num.length) return this.clone().iand(num);
return num.clone().iand(this);
};
BN.prototype.uand = function uand (num) {
if (this.length > num.length) return this.clone().iuand(num);
return num.clone().iuand(this);
};
// Xor `num` with `this` in-place
BN.prototype.iuxor = function iuxor (num) {
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
for (var i = 0; i < b.length; i++) {
this.words[i] = a.words[i] ^ b.words[i];
}
if (this !== a) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
this.length = a.length;
return this._strip();
};
BN.prototype.ixor = function ixor (num) {
assert((this.negative | num.negative) === 0);
return this.iuxor(num);
};
// Xor `num` with `this`
BN.prototype.xor = function xor (num) {
if (this.length > num.length) return this.clone().ixor(num);
return num.clone().ixor(this);
};
BN.prototype.uxor = function uxor (num) {
if (this.length > num.length) return this.clone().iuxor(num);
return num.clone().iuxor(this);
};
// Not ``this`` with ``width`` bitwidth
BN.prototype.inotn = function inotn (width) {
assert(typeof width === 'number' && width >= 0);
var bytesNeeded = Math.ceil(width / 26) | 0;
var bitsLeft = width % 26;
// Extend the buffer with leading zeroes
this._expand(bytesNeeded);
if (bitsLeft > 0) {
bytesNeeded--;
}
// Handle complete words
for (var i = 0; i < bytesNeeded; i++) {
this.words[i] = ~this.words[i] & 0x3ffffff;
}
// Handle the residue
if (bitsLeft > 0) {
this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
}
// And remove leading zeroes
return this._strip();
};
BN.prototype.notn = function notn (width) {
return this.clone().inotn(width);
};
// Set `bit` of `this`
BN.prototype.setn = function setn (bit, val) {
assert(typeof bit === 'number' && bit >= 0);
var off = (bit / 26) | 0;
var wbit = bit % 26;
this._expand(off + 1);
if (val) {
this.words[off] = this.words[off] | (1 << wbit);
} else {
this.words[off] = this.words[off] & ~(1 << wbit);
}
return this._strip();
};
// Add `num` to `this` in-place
BN.prototype.iadd = function iadd (num) {
var r;
// negative + positive
if (this.negative !== 0 && num.negative === 0) {
this.negative = 0;
r = this.isub(num);
this.negative ^= 1;
return this._normSign();
// positive + negative
} else if (this.negative === 0 && num.negative !== 0) {
num.negative = 0;
r = this.isub(num);
num.negative = 1;
return r._normSign();
}
// a.length > b.length
var a, b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
for (; carry !== 0 && i < a.length; i++) {
r = (a.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
this.length = a.length;
if (carry !== 0) {
this.words[this.length] = carry;
this.length++;
// Copy the rest of the words
} else if (a !== this) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
return this;
};
// Add `num` to `this`
BN.prototype.add = function add (num) {
var res;
if (num.negative !== 0 && this.negative === 0) {
num.negative = 0;
res = this.sub(num);
num.negative ^= 1;
return res;
} else if (num.negative === 0 && this.negative !== 0) {
this.negative = 0;
res = num.sub(this);
this.negative = 1;
return res;
}
if (this.length > num.length) return this.clone().iadd(num);
return num.clone().iadd(this);
};
// Subtract `num` from `this` in-place
BN.prototype.isub = function isub (num) {
// this - (-num) = this + num
if (num.negative !== 0) {
num.negative = 0;
var r = this.iadd(num);
num.negative = 1;
return r._normSign();
// -this - num = -(this + num)
} else if (this.negative !== 0) {
this.negative = 0;
this.iadd(num);
this.negative = 1;
return this._normSign();
}
// At this point both numbers are positive
var cmp = this.cmp(num);
// Optimization - zeroify
if (cmp === 0) {
this.negative = 0;
this.length = 1;
this.words[0] = 0;
return this;
}
// a > b
var a, b;
if (cmp > 0) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
for (; carry !== 0 && i < a.length; i++) {
r = (a.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
// Copy rest of the words
if (carry === 0 && i < a.length && a !== this) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
this.length = Math.max(this.length, i);
if (a !== this) {
this.negative = 1;
}
return this._strip();
};
// Subtract `num` from `this`
BN.prototype.sub = function sub (num) {
return this.clone().isub(num);
};
function smallMulTo (self, num, out) {
out.negative = num.negative ^ self.negative;
var len = (self.length + num.length) | 0;
out.length = len;
len = (len - 1) | 0;
// Peel one iteration (compiler can't do it, because of code complexity)
var a = self.words[0] | 0;
var b = num.words[0] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
var carry = (r / 0x4000000) | 0;
out.words[0] = lo;
for (var k = 1; k < len; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = carry >>> 26;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
var i = (k - j) | 0;
a = self.words[i] | 0;
b = num.words[j] | 0;
r = a * b + rword;
ncarry += (r / 0x4000000) | 0;
rword = r & 0x3ffffff;
}
out.words[k] = rword | 0;
carry = ncarry | 0;
}
if (carry !== 0) {
out.words[k] = carry | 0;
} else {
out.length--;
}
return out._strip();
}
// TODO(indutny): it may be reasonable to omit it for users who don't need
// to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
// multiplication (like elliptic secp256k1).
var comb10MulTo = function comb10MulTo (self, num, out) {
var a = self.words;
var b = num.words;
var o = out.words;
var c = 0;
var lo;
var mid;
var hi;
var a0 = a[0] | 0;
var al0 = a0 & 0x1fff;
var ah0 = a0 >>> 13;
var a1 = a[1] | 0;
var al1 = a1 & 0x1fff;
var ah1 = a1 >>> 13;
var a2 = a[2] | 0;
var al2 = a2 & 0x1fff;
var ah2 = a2 >>> 13;
var a3 = a[3] | 0;
var al3 = a3 & 0x1fff;
var ah3 = a3 >>> 13;
var a4 = a[4] | 0;
var al4 = a4 & 0x1fff;
var ah4 = a4 >>> 13;
var a5 = a[5] | 0;
var al5 = a5 & 0x1fff;
var ah5 = a5 >>> 13;
var a6 = a[6] | 0;
var al6 = a6 & 0x1fff;
var ah6 = a6 >>> 13;
var a7 = a[7] | 0;
var al7 = a7 & 0x1fff;
var ah7 = a7 >>> 13;
var a8 = a[8] | 0;
var al8 = a8 & 0x1fff;
var ah8 = a8 >>> 13;
var a9 = a[9] | 0;
var al9 = a9 & 0x1fff;
var ah9 = a9 >>> 13;
var b0 = b[0] | 0;
var bl0 = b0 & 0x1fff;
var bh0 = b0 >>> 13;
var b1 = b[1] | 0;
var bl1 = b1 & 0x1fff;
var bh1 = b1 >>> 13;
var b2 = b[2] | 0;
var bl2 = b2 & 0x1fff;
var bh2 = b2 >>> 13;
var b3 = b[3] | 0;
var bl3 = b3 & 0x1fff;
var bh3 = b3 >>> 13;
var b4 = b[4] | 0;
var bl4 = b4 & 0x1fff;
var bh4 = b4 >>> 13;
var b5 = b[5] | 0;
var bl5 = b5 & 0x1fff;
var bh5 = b5 >>> 13;
var b6 = b[6] | 0;
var bl6 = b6 & 0x1fff;
var bh6 = b6 >>> 13;
var b7 = b[7] | 0;
var bl7 = b7 & 0x1fff;
var bh7 = b7 >>> 13;
var b8 = b[8] | 0;
var bl8 = b8 & 0x1fff;
var bh8 = b8 >>> 13;
var b9 = b[9] | 0;
var bl9 = b9 & 0x1fff;
var bh9 = b9 >>> 13;
out.negative = self.negative ^ num.negative;
out.length = 19;
/* k = 0 */
lo = Math.imul(al0, bl0);
mid = Math.imul(al0, bh0);
mid = (mid + Math.imul(ah0, bl0)) | 0;
hi = Math.imul(ah0, bh0);
var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
w0 &= 0x3ffffff;
/* k = 1 */
lo = Math.imul(al1, bl0);
mid = Math.imul(al1, bh0);
mid = (mid + Math.imul(ah1, bl0)) | 0;
hi = Math.imul(ah1, bh0);
lo = (lo + Math.imul(al0, bl1)) | 0;
mid = (mid + Math.imul(al0, bh1)) | 0;
mid = (mid + Math.imul(ah0, bl1)) | 0;
hi = (hi + Math.imul(ah0, bh1)) | 0;
var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
w1 &= 0x3ffffff;
/* k = 2 */
lo = Math.imul(al2, bl0);
mid = Math.imul(al2, bh0);
mid = (mid + Math.imul(ah2, bl0)) | 0;
hi = Math.imul(ah2, bh0);
lo = (lo + Math.imul(al1, bl1)) | 0;
mid = (mid + Math.imul(al1, bh1)) | 0;
mid = (mid + Math.imul(ah1, bl1)) | 0;
hi = (hi + Math.imul(ah1, bh1)) | 0;
lo = (lo + Math.imul(al0, bl2)) | 0;
mid = (mid + Math.imul(al0, bh2)) | 0;
mid = (mid + Math.imul(ah0, bl2)) | 0;
hi = (hi + Math.imul(ah0, bh2)) | 0;
var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
w2 &= 0x3ffffff;
/* k = 3 */
lo = Math.imul(al3, bl0);
mid = Math.imul(al3, bh0);
mid = (mid + Math.imul(ah3, bl0)) | 0;
hi = Math.imul(ah3, bh0);
lo = (lo + Math.imul(al2, bl1)) | 0;
mid = (mid + Math.imul(al2, bh1)) | 0;
mid = (mid + Math.imul(ah2, bl1)) | 0;
hi = (hi + Math.imul(ah2, bh1)) | 0;
lo = (lo + Math.imul(al1, bl2)) | 0;
mid = (mid + Math.imul(al1, bh2)) | 0;
mid = (mid + Math.imul(ah1, bl2)) | 0;
hi = (hi + Math.imul(ah1, bh2)) | 0;
lo = (lo + Math.imul(al0, bl3)) | 0;
mid = (mid + Math.imul(al0, bh3)) | 0;
mid = (mid + Math.imul(ah0, bl3)) | 0;
hi = (hi + Math.imul(ah0, bh3)) | 0;
var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
w3 &= 0x3ffffff;
/* k = 4 */
lo = Math.imul(al4, bl0);
mid = Math.imul(al4, bh0);
mid = (mid + Math.imul(ah4, bl0)) | 0;
hi = Math.imul(ah4, bh0);
lo = (lo + Math.imul(al3, bl1)) | 0;
mid = (mid + Math.imul(al3, bh1)) | 0;
mid = (mid + Math.imul(ah3, bl1)) | 0;
hi = (hi + Math.imul(ah3, bh1)) | 0;
lo = (lo + Math.imul(al2, bl2)) | 0;
mid = (mid + Math.imul(al2, bh2)) | 0;
mid = (mid + Math.imul(ah2, bl2)) | 0;
hi = (hi + Math.imul(ah2, bh2)) | 0;
lo = (lo + Math.imul(al1, bl3)) | 0;
mid = (mid + Math.imul(al1, bh3)) | 0;
mid = (mid + Math.imul(ah1, bl3)) | 0;
hi = (hi + Math.imul(ah1, bh3)) | 0;
lo = (lo + Math.imul(al0, bl4)) | 0;
mid = (mid + Math.imul(al0, bh4)) | 0;
mid = (mid + Math.imul(ah0, bl4)) | 0;
hi = (hi + Math.imul(ah0, bh4)) | 0;
var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
w4 &= 0x3ffffff;
/* k = 5 */
lo = Math.imul(al5, bl0);
mid = Math.imul(al5, bh0);
mid = (mid + Math.imul(ah5, bl0)) | 0;
hi = Math.imul(ah5, bh0);
lo = (lo + Math.imul(al4, bl1)) | 0;
mid = (mid + Math.imul(al4, bh1)) | 0;
mid = (mid + Math.imul(ah4, bl1)) | 0;
hi = (hi + Math.imul(ah4, bh1)) | 0;
lo = (lo + Math.imul(al3, bl2)) | 0;
mid = (mid + Math.imul(al3, bh2)) | 0;
mid = (mid + Math.imul(ah3, bl2)) | 0;
hi = (hi + Math.imul(ah3, bh2)) | 0;
lo = (lo + Math.imul(al2, bl3)) | 0;
mid = (mid + Math.imul(al2, bh3)) | 0;
mid = (mid + Math.imul(ah2, bl3)) | 0;
hi = (hi + Math.imul(ah2, bh3)) | 0;
lo = (lo + Math.imul(al1, bl4)) | 0;
mid = (mid + Math.imul(al1, bh4)) | 0;
mid = (mid + Math.imul(ah1, bl4)) | 0;
hi = (hi + Math.imul(ah1, bh4)) | 0;
lo = (lo + Math.imul(al0, bl5)) | 0;
mid = (mid + Math.imul(al0, bh5)) | 0;
mid = (mid + Math.imul(ah0, bl5)) | 0;
hi = (hi + Math.imul(ah0, bh5)) | 0;
var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
w5 &= 0x3ffffff;
/* k = 6 */
lo = Math.imul(al6, bl0);
mid = Math.imul(al6, bh0);
mid = (mid + Math.imul(ah6, bl0)) | 0;
hi = Math.imul(ah6, bh0);
lo = (lo + Math.imul(al5, bl1)) | 0;
mid = (mid + Math.imul(al5, bh1)) | 0;
mid = (mid + Math.imul(ah5, bl1)) | 0;
hi = (hi + Math.imul(ah5, bh1)) | 0;
lo = (lo + Math.imul(al4, bl2)) | 0;
mid = (mid + Math.imul(al4, bh2)) | 0;
mid = (mid + Math.imul(ah4, bl2)) | 0;
hi = (hi + Math.imul(ah4, bh2)) | 0;
lo = (lo + Math.imul(al3, bl3)) | 0;
mid = (mid + Math.imul(al3, bh3)) | 0;
mid = (mid + Math.imul(ah3, bl3)) | 0;
hi = (hi + Math.imul(ah3, bh3)) | 0;
lo = (lo + Math.imul(al2, bl4)) | 0;
mid = (mid + Math.imul(al2, bh4)) | 0;
mid = (mid + Math.imul(ah2, bl4)) | 0;
hi = (hi + Math.imul(ah2, bh4)) | 0;
lo = (lo + Math.imul(al1, bl5)) | 0;
mid = (mid + Math.imul(al1, bh5)) | 0;
mid = (mid + Math.imul(ah1, bl5)) | 0;
hi = (hi + Math.imul(ah1, bh5)) | 0;
lo = (lo + Math.imul(al0, bl6)) | 0;
mid = (mid + Math.imul(al0, bh6)) | 0;
mid = (mid + Math.imul(ah0, bl6)) | 0;
hi = (hi + Math.imul(ah0, bh6)) | 0;
var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
w6 &= 0x3ffffff;
/* k = 7 */
lo = Math.imul(al7, bl0);
mid = Math.imul(al7, bh0);
mid = (mid + Math.imul(ah7, bl0)) | 0;
hi = Math.imul(ah7, bh0);
lo = (lo + Math.imul(al6, bl1)) | 0;
mid = (mid + Math.imul(al6, bh1)) | 0;
mid = (mid + Math.imul(ah6, bl1)) | 0;
hi = (hi + Math.imul(ah6, bh1)) | 0;
lo = (lo + Math.imul(al5, bl2)) | 0;
mid = (mid + Math.imul(al5, bh2)) | 0;
mid = (mid + Math.imul(ah5, bl2)) | 0;
hi = (hi + Math.imul(ah5, bh2)) | 0;
lo = (lo + Math.imul(al4, bl3)) | 0;
mid = (mid + Math.imul(al4, bh3)) | 0;
mid = (mid + Math.imul(ah4, bl3)) | 0;
hi = (hi + Math.imul(ah4, bh3)) | 0;
lo = (lo + Math.imul(al3, bl4)) | 0;
mid = (mid + Math.imul(al3, bh4)) | 0;
mid = (mid + Math.imul(ah3, bl4)) | 0;
hi = (hi + Math.imul(ah3, bh4)) | 0;
lo = (lo + Math.imul(al2, bl5)) | 0;
mid = (mid + Math.imul(al2, bh5)) | 0;
mid = (mid + Math.imul(ah2, bl5)) | 0;
hi = (hi + Math.imul(ah2, bh5)) | 0;
lo = (lo + Math.imul(al1, bl6)) | 0;
mid = (mid + Math.imul(al1, bh6)) | 0;
mid = (mid + Math.imul(ah1, bl6)) | 0;
hi = (hi + Math.imul(ah1, bh6)) | 0;
lo = (lo + Math.imul(al0, bl7)) | 0;
mid = (mid + Math.imul(al0, bh7)) | 0;
mid = (mid + Math.imul(ah0, bl7)) | 0;
hi = (hi + Math.imul(ah0, bh7)) | 0;
var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
w7 &= 0x3ffffff;
/* k = 8 */
lo = Math.imul(al8, bl0);
mid = Math.imul(al8, bh0);
mid = (mid + Math.imul(ah8, bl0)) | 0;
hi = Math.imul(ah8, bh0);
lo = (lo + Math.imul(al7, bl1)) | 0;
mid = (mid + Math.imul(al7, bh1)) | 0;
mid = (mid + Math.imul(ah7, bl1)) | 0;
hi = (hi + Math.imul(ah7, bh1)) | 0;
lo = (lo + Math.imul(al6, bl2)) | 0;
mid = (mid + Math.imul(al6, bh2)) | 0;
mid = (mid + Math.imul(ah6, bl2)) | 0;
hi = (hi + Math.imul(ah6, bh2)) | 0;
lo = (lo + Math.imul(al5, bl3)) | 0;
mid = (mid + Math.imul(al5, bh3)) | 0;
mid = (mid + Math.imul(ah5, bl3)) | 0;
hi = (hi + Math.imul(ah5, bh3)) | 0;
lo = (lo + Math.imul(al4, bl4)) | 0;
mid = (mid + Math.imul(al4, bh4)) | 0;
mid = (mid + Math.imul(ah4, bl4)) | 0;
hi = (hi + Math.imul(ah4, bh4)) | 0;
lo = (lo + Math.imul(al3, bl5)) | 0;
mid = (mid + Math.imul(al3, bh5)) | 0;
mid = (mid + Math.imul(ah3, bl5)) | 0;
hi = (hi + Math.imul(ah3, bh5)) | 0;
lo = (lo + Math.imul(al2, bl6)) | 0;
mid = (mid + Math.imul(al2, bh6)) | 0;
mid = (mid + Math.imul(ah2, bl6)) | 0;
hi = (hi + Math.imul(ah2, bh6)) | 0;
lo = (lo + Math.imul(al1, bl7)) | 0;
mid = (mid + Math.imul(al1, bh7)) | 0;
mid = (mid + Math.imul(ah1, bl7)) | 0;
hi = (hi + Math.imul(ah1, bh7)) | 0;
lo = (lo + Math.imul(al0, bl8)) | 0;
mid = (mid + Math.imul(al0, bh8)) | 0;
mid = (mid + Math.imul(ah0, bl8)) | 0;
hi = (hi + Math.imul(ah0, bh8)) | 0;
var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
w8 &= 0x3ffffff;
/* k = 9 */
lo = Math.imul(al9, bl0);
mid = Math.imul(al9, bh0);
mid = (mid + Math.imul(ah9, bl0)) | 0;
hi = Math.imul(ah9, bh0);
lo = (lo + Math.imul(al8, bl1)) | 0;
mid = (mid + Math.imul(al8, bh1)) | 0;
mid = (mid + Math.imul(ah8, bl1)) | 0;
hi = (hi + Math.imul(ah8, bh1)) | 0;
lo = (lo + Math.imul(al7, bl2)) | 0;
mid = (mid + Math.imul(al7, bh2)) | 0;
mid = (mid + Math.imul(ah7, bl2)) | 0;
hi = (hi + Math.imul(ah7, bh2)) | 0;
lo = (lo + Math.imul(al6, bl3)) | 0;
mid = (mid + Math.imul(al6, bh3)) | 0;
mid = (mid + Math.imul(ah6, bl3)) | 0;
hi = (hi + Math.imul(ah6, bh3)) | 0;
lo = (lo + Math.imul(al5, bl4)) | 0;
mid = (mid + Math.imul(al5, bh4)) | 0;
mid = (mid + Math.imul(ah5, bl4)) | 0;
hi = (hi + Math.imul(ah5, bh4)) | 0;
lo = (lo + Math.imul(al4, bl5)) | 0;
mid = (mid + Math.imul(al4, bh5)) | 0;
mid = (mid + Math.imul(ah4, bl5)) | 0;
hi = (hi + Math.imul(ah4, bh5)) | 0;
lo = (lo + Math.imul(al3, bl6)) | 0;
mid = (mid + Math.imul(al3, bh6)) | 0;
mid = (mid + Math.imul(ah3, bl6)) | 0;
hi = (hi + Math.imul(ah3, bh6)) | 0;
lo = (lo + Math.imul(al2, bl7)) | 0;
mid = (mid + Math.imul(al2, bh7)) | 0;
mid = (mid + Math.imul(ah2, bl7)) | 0;
hi = (hi + Math.imul(ah2, bh7)) | 0;
lo = (lo + Math.imul(al1, bl8)) | 0;
mid = (mid + Math.imul(al1, bh8)) | 0;
mid = (mid + Math.imul(ah1, bl8)) | 0;
hi = (hi + Math.imul(ah1, bh8)) | 0;
lo = (lo + Math.imul(al0, bl9)) | 0;
mid = (mid + Math.imul(al0, bh9)) | 0;
mid = (mid + Math.imul(ah0, bl9)) | 0;
hi = (hi + Math.imul(ah0, bh9)) | 0;
var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
w9 &= 0x3ffffff;
/* k = 10 */
lo = Math.imul(al9, bl1);
mid = Math.imul(al9, bh1);
mid = (mid + Math.imul(ah9, bl1)) | 0;
hi = Math.imul(ah9, bh1);
lo = (lo + Math.imul(al8, bl2)) | 0;
mid = (mid + Math.imul(al8, bh2)) | 0;
mid = (mid + Math.imul(ah8, bl2)) | 0;
hi = (hi + Math.imul(ah8, bh2)) | 0;
lo = (lo + Math.imul(al7, bl3)) | 0;
mid = (mid + Math.imul(al7, bh3)) | 0;
mid = (mid + Math.imul(ah7, bl3)) | 0;
hi = (hi + Math.imul(ah7, bh3)) | 0;
lo = (lo + Math.imul(al6, bl4)) | 0;
mid = (mid + Math.imul(al6, bh4)) | 0;
mid = (mid + Math.imul(ah6, bl4)) | 0;
hi = (hi + Math.imul(ah6, bh4)) | 0;
lo = (lo + Math.imul(al5, bl5)) | 0;
mid = (mid + Math.imul(al5, bh5)) | 0;
mid = (mid + Math.imul(ah5, bl5)) | 0;
hi = (hi + Math.imul(ah5, bh5)) | 0;
lo = (lo + Math.imul(al4, bl6)) | 0;
mid = (mid + Math.imul(al4, bh6)) | 0;
mid = (mid + Math.imul(ah4, bl6)) | 0;
hi = (hi + Math.imul(ah4, bh6)) | 0;
lo = (lo + Math.imul(al3, bl7)) | 0;
mid = (mid + Math.imul(al3, bh7)) | 0;
mid = (mid + Math.imul(ah3, bl7)) | 0;
hi = (hi + Math.imul(ah3, bh7)) | 0;
lo = (lo + Math.imul(al2, bl8)) | 0;
mid = (mid + Math.imul(al2, bh8)) | 0;
mid = (mid + Math.imul(ah2, bl8)) | 0;
hi = (hi + Math.imul(ah2, bh8)) | 0;
lo = (lo + Math.imul(al1, bl9)) | 0;
mid = (mid + Math.imul(al1, bh9)) | 0;
mid = (mid + Math.imul(ah1, bl9)) | 0;
hi = (hi + Math.imul(ah1, bh9)) | 0;
var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
w10 &= 0x3ffffff;
/* k = 11 */
lo = Math.imul(al9, bl2);
mid = Math.imul(al9, bh2);
mid = (mid + Math.imul(ah9, bl2)) | 0;
hi = Math.imul(ah9, bh2);
lo = (lo + Math.imul(al8, bl3)) | 0;
mid = (mid + Math.imul(al8, bh3)) | 0;
mid = (mid + Math.imul(ah8, bl3)) | 0;
hi = (hi + Math.imul(ah8, bh3)) | 0;
lo = (lo + Math.imul(al7, bl4)) | 0;
mid = (mid + Math.imul(al7, bh4)) | 0;
mid = (mid + Math.imul(ah7, bl4)) | 0;
hi = (hi + Math.imul(ah7, bh4)) | 0;
lo = (lo + Math.imul(al6, bl5)) | 0;
mid = (mid + Math.imul(al6, bh5)) | 0;
mid = (mid + Math.imul(ah6, bl5)) | 0;
hi = (hi + Math.imul(ah6, bh5)) | 0;
lo = (lo + Math.imul(al5, bl6)) | 0;
mid = (mid + Math.imul(al5, bh6)) | 0;
mid = (mid + Math.imul(ah5, bl6)) | 0;
hi = (hi + Math.imul(ah5, bh6)) | 0;
lo = (lo + Math.imul(al4, bl7)) | 0;
mid = (mid + Math.imul(al4, bh7)) | 0;
mid = (mid + Math.imul(ah4, bl7)) | 0;
hi = (hi + Math.imul(ah4, bh7)) | 0;
lo = (lo + Math.imul(al3, bl8)) | 0;
mid = (mid + Math.imul(al3, bh8)) | 0;
mid = (mid + Math.imul(ah3, bl8)) | 0;
hi = (hi + Math.imul(ah3, bh8)) | 0;
lo = (lo + Math.imul(al2, bl9)) | 0;
mid = (mid + Math.imul(al2, bh9)) | 0;
mid = (mid + Math.imul(ah2, bl9)) | 0;
hi = (hi + Math.imul(ah2, bh9)) | 0;
var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
w11 &= 0x3ffffff;
/* k = 12 */
lo = Math.imul(al9, bl3);
mid = Math.imul(al9, bh3);
mid = (mid + Math.imul(ah9, bl3)) | 0;
hi = Math.imul(ah9, bh3);
lo = (lo + Math.imul(al8, bl4)) | 0;
mid = (mid + Math.imul(al8, bh4)) | 0;
mid = (mid + Math.imul(ah8, bl4)) | 0;
hi = (hi + Math.imul(ah8, bh4)) | 0;
lo = (lo + Math.imul(al7, bl5)) | 0;
mid = (mid + Math.imul(al7, bh5)) | 0;
mid = (mid + Math.imul(ah7, bl5)) | 0;
hi = (hi + Math.imul(ah7, bh5)) | 0;
lo = (lo + Math.imul(al6, bl6)) | 0;
mid = (mid + Math.imul(al6, bh6)) | 0;
mid = (mid + Math.imul(ah6, bl6)) | 0;
hi = (hi + Math.imul(ah6, bh6)) | 0;
lo = (lo + Math.imul(al5, bl7)) | 0;
mid = (mid + Math.imul(al5, bh7)) | 0;
mid = (mid + Math.imul(ah5, bl7)) | 0;
hi = (hi + Math.imul(ah5, bh7)) | 0;
lo = (lo + Math.imul(al4, bl8)) | 0;
mid = (mid + Math.imul(al4, bh8)) | 0;
mid = (mid + Math.imul(ah4, bl8)) | 0;
hi = (hi + Math.imul(ah4, bh8)) | 0;
lo = (lo + Math.imul(al3, bl9)) | 0;
mid = (mid + Math.imul(al3, bh9)) | 0;
mid = (mid + Math.imul(ah3, bl9)) | 0;
hi = (hi + Math.imul(ah3, bh9)) | 0;
var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
w12 &= 0x3ffffff;
/* k = 13 */
lo = Math.imul(al9, bl4);
mid = Math.imul(al9, bh4);
mid = (mid + Math.imul(ah9, bl4)) | 0;
hi = Math.imul(ah9, bh4);
lo = (lo + Math.imul(al8, bl5)) | 0;
mid = (mid + Math.imul(al8, bh5)) | 0;
mid = (mid + Math.imul(ah8, bl5)) | 0;
hi = (hi + Math.imul(ah8, bh5)) | 0;
lo = (lo + Math.imul(al7, bl6)) | 0;
mid = (mid + Math.imul(al7, bh6)) | 0;
mid = (mid + Math.imul(ah7, bl6)) | 0;
hi = (hi + Math.imul(ah7, bh6)) | 0;
lo = (lo + Math.imul(al6, bl7)) | 0;
mid = (mid + Math.imul(al6, bh7)) | 0;
mid = (mid + Math.imul(ah6, bl7)) | 0;
hi = (hi + Math.imul(ah6, bh7)) | 0;
lo = (lo + Math.imul(al5, bl8)) | 0;
mid = (mid + Math.imul(al5, bh8)) | 0;
mid = (mid + Math.imul(ah5, bl8)) | 0;
hi = (hi + Math.imul(ah5, bh8)) | 0;
lo = (lo + Math.imul(al4, bl9)) | 0;
mid = (mid + Math.imul(al4, bh9)) | 0;
mid = (mid + Math.imul(ah4, bl9)) | 0;
hi = (hi + Math.imul(ah4, bh9)) | 0;
var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
w13 &= 0x3ffffff;
/* k = 14 */
lo = Math.imul(al9, bl5);
mid = Math.imul(al9, bh5);
mid = (mid + Math.imul(ah9, bl5)) | 0;
hi = Math.imul(ah9, bh5);
lo = (lo + Math.imul(al8, bl6)) | 0;
mid = (mid + Math.imul(al8, bh6)) | 0;
mid = (mid + Math.imul(ah8, bl6)) | 0;
hi = (hi + Math.imul(ah8, bh6)) | 0;
lo = (lo + Math.imul(al7, bl7)) | 0;
mid = (mid + Math.imul(al7, bh7)) | 0;
mid = (mid + Math.imul(ah7, bl7)) | 0;
hi = (hi + Math.imul(ah7, bh7)) | 0;
lo = (lo + Math.imul(al6, bl8)) | 0;
mid = (mid + Math.imul(al6, bh8)) | 0;
mid = (mid + Math.imul(ah6, bl8)) | 0;
hi = (hi + Math.imul(ah6, bh8)) | 0;
lo = (lo + Math.imul(al5, bl9)) | 0;
mid = (mid + Math.imul(al5, bh9)) | 0;
mid = (mid + Math.imul(ah5, bl9)) | 0;
hi = (hi + Math.imul(ah5, bh9)) | 0;
var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
w14 &= 0x3ffffff;
/* k = 15 */
lo = Math.imul(al9, bl6);
mid = Math.imul(al9, bh6);
mid = (mid + Math.imul(ah9, bl6)) | 0;
hi = Math.imul(ah9, bh6);
lo = (lo + Math.imul(al8, bl7)) | 0;
mid = (mid + Math.imul(al8, bh7)) | 0;
mid = (mid + Math.imul(ah8, bl7)) | 0;
hi = (hi + Math.imul(ah8, bh7)) | 0;
lo = (lo + Math.imul(al7, bl8)) | 0;
mid = (mid + Math.imul(al7, bh8)) | 0;
mid = (mid + Math.imul(ah7, bl8)) | 0;
hi = (hi + Math.imul(ah7, bh8)) | 0;
lo = (lo + Math.imul(al6, bl9)) | 0;
mid = (mid + Math.imul(al6, bh9)) | 0;
mid = (mid + Math.imul(ah6, bl9)) | 0;
hi = (hi + Math.imul(ah6, bh9)) | 0;
var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
w15 &= 0x3ffffff;
/* k = 16 */
lo = Math.imul(al9, bl7);
mid = Math.imul(al9, bh7);
mid = (mid + Math.imul(ah9, bl7)) | 0;
hi = Math.imul(ah9, bh7);
lo = (lo + Math.imul(al8, bl8)) | 0;
mid = (mid + Math.imul(al8, bh8)) | 0;
mid = (mid + Math.imul(ah8, bl8)) | 0;
hi = (hi + Math.imul(ah8, bh8)) | 0;
lo = (lo + Math.imul(al7, bl9)) | 0;
mid = (mid + Math.imul(al7, bh9)) | 0;
mid = (mid + Math.imul(ah7, bl9)) | 0;
hi = (hi + Math.imul(ah7, bh9)) | 0;
var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
w16 &= 0x3ffffff;
/* k = 17 */
lo = Math.imul(al9, bl8);
mid = Math.imul(al9, bh8);
mid = (mid + Math.imul(ah9, bl8)) | 0;
hi = Math.imul(ah9, bh8);
lo = (lo + Math.imul(al8, bl9)) | 0;
mid = (mid + Math.imul(al8, bh9)) | 0;
mid = (mid + Math.imul(ah8, bl9)) | 0;
hi = (hi + Math.imul(ah8, bh9)) | 0;
var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
w17 &= 0x3ffffff;
/* k = 18 */
lo = Math.imul(al9, bl9);
mid = Math.imul(al9, bh9);
mid = (mid + Math.imul(ah9, bl9)) | 0;
hi = Math.imul(ah9, bh9);
var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
w18 &= 0x3ffffff;
o[0] = w0;
o[1] = w1;
o[2] = w2;
o[3] = w3;
o[4] = w4;
o[5] = w5;
o[6] = w6;
o[7] = w7;
o[8] = w8;
o[9] = w9;
o[10] = w10;
o[11] = w11;
o[12] = w12;
o[13] = w13;
o[14] = w14;
o[15] = w15;
o[16] = w16;
o[17] = w17;
o[18] = w18;
if (c !== 0) {
o[19] = c;
out.length++;
}
return out;
};
// Polyfill comb
if (!Math.imul) {
comb10MulTo = smallMulTo;
}
function bigMulTo (self, num, out) {
out.negative = num.negative ^ self.negative;
out.length = self.length + num.length;
var carry = 0;
var hncarry = 0;
for (var k = 0; k < out.length - 1; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = hncarry;
hncarry = 0;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
var i = k - j;
var a = self.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
lo = (lo + rword) | 0;
rword = lo & 0x3ffffff;
ncarry = (ncarry + (lo >>> 26)) | 0;
hncarry += ncarry >>> 26;
ncarry &= 0x3ffffff;
}
out.words[k] = rword;
carry = ncarry;
ncarry = hncarry;
}
if (carry !== 0) {
out.words[k] = carry;
} else {
out.length--;
}
return out._strip();
}
function jumboMulTo (self, num, out) {
// Temporary disable, see https://github.com/indutny/bn.js/issues/211
// var fftm = new FFTM();
// return fftm.mulp(self, num, out);
return bigMulTo(self, num, out);
}
BN.prototype.mulTo = function mulTo (num, out) {
var res;
var len = this.length + num.length;
if (this.length === 10 && num.length === 10) {
res = comb10MulTo(this, num, out);
} else if (len < 63) {
res = smallMulTo(this, num, out);
} else if (len < 1024) {
res = bigMulTo(this, num, out);
} else {
res = jumboMulTo(this, num, out);
}
return res;
};
// Cooley-Tukey algorithm for FFT
// slightly revisited to rely on looping instead of recursion
function FFTM (x, y) {
this.x = x;
this.y = y;
}
FFTM.prototype.makeRBT = function makeRBT (N) {
var t = new Array(N);
var l = BN.prototype._countBits(N) - 1;
for (var i = 0; i < N; i++) {
t[i] = this.revBin(i, l, N);
}
return t;
};
// Returns binary-reversed representation of `x`
FFTM.prototype.revBin = function revBin (x, l, N) {
if (x === 0 || x === N - 1) return x;
var rb = 0;
for (var i = 0; i < l; i++) {
rb |= (x & 1) << (l - i - 1);
x >>= 1;
}
return rb;
};
// Performs "tweedling" phase, therefore 'emulating'
// behaviour of the recursive algorithm
FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
for (var i = 0; i < N; i++) {
rtws[i] = rws[rbt[i]];
itws[i] = iws[rbt[i]];
}
};
FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
this.permute(rbt, rws, iws, rtws, itws, N);
for (var s = 1; s < N; s <<= 1) {
var l = s << 1;
var rtwdf = Math.cos(2 * Math.PI / l);
var itwdf = Math.sin(2 * Math.PI / l);
for (var p = 0; p < N; p += l) {
var rtwdf_ = rtwdf;
var itwdf_ = itwdf;
for (var j = 0; j < s; j++) {
var re = rtws[p + j];
var ie = itws[p + j];
var ro = rtws[p + j + s];
var io = itws[p + j + s];
var rx = rtwdf_ * ro - itwdf_ * io;
io = rtwdf_ * io + itwdf_ * ro;
ro = rx;
rtws[p + j] = re + ro;
itws[p + j] = ie + io;
rtws[p + j + s] = re - ro;
itws[p + j + s] = ie - io;
/* jshint maxdepth : false */
if (j !== l) {
rx = rtwdf * rtwdf_ - itwdf * itwdf_;
itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
rtwdf_ = rx;
}
}
}
}
};
FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
var N = Math.max(m, n) | 1;
var odd = N & 1;
var i = 0;
for (N = N / 2 | 0; N; N = N >>> 1) {
i++;
}
return 1 << i + 1 + odd;
};
FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
if (N <= 1) return;
for (var i = 0; i < N / 2; i++) {
var t = rws[i];
rws[i] = rws[N - i - 1];
rws[N - i - 1] = t;
t = iws[i];
iws[i] = -iws[N - i - 1];
iws[N - i - 1] = -t;
}
};
FFTM.prototype.normalize13b = function normalize13b (ws, N) {
var carry = 0;
for (var i = 0; i < N / 2; i++) {
var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
Math.round(ws[2 * i] / N) +
carry;
ws[i] = w & 0x3ffffff;
if (w < 0x4000000) {
carry = 0;
} else {
carry = w / 0x4000000 | 0;
}
}
return ws;
};
FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
var carry = 0;
for (var i = 0; i < len; i++) {
carry = carry + (ws[i] | 0);
rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
}
// Pad with zeroes
for (i = 2 * len; i < N; ++i) {
rws[i] = 0;
}
assert(carry === 0);
assert((carry & ~0x1fff) === 0);
};
FFTM.prototype.stub = function stub (N) {
var ph = new Array(N);
for (var i = 0; i < N; i++) {
ph[i] = 0;
}
return ph;
};
FFTM.prototype.mulp = function mulp (x, y, out) {
var N = 2 * this.guessLen13b(x.length, y.length);
var rbt = this.makeRBT(N);
var _ = this.stub(N);
var rws = new Array(N);
var rwst = new Array(N);
var iwst = new Array(N);
var nrws = new Array(N);
var nrwst = new Array(N);
var niwst = new Array(N);
var rmws = out.words;
rmws.length = N;
this.convert13b(x.words, x.length, rws, N);
this.convert13b(y.words, y.length, nrws, N);
this.transform(rws, _, rwst, iwst, N, rbt);
this.transform(nrws, _, nrwst, niwst, N, rbt);
for (var i = 0; i < N; i++) {
var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
rwst[i] = rx;
}
this.conjugate(rwst, iwst, N);
this.transform(rwst, iwst, rmws, _, N, rbt);
this.conjugate(rmws, _, N);
this.normalize13b(rmws, N);
out.negative = x.negative ^ y.negative;
out.length = x.length + y.length;
return out._strip();
};
// Multiply `this` by `num`
BN.prototype.mul = function mul (num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return this.mulTo(num, out);
};
// Multiply employing FFT
BN.prototype.mulf = function mulf (num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return jumboMulTo(this, num, out);
};
// In-place Multiplication
BN.prototype.imul = function imul (num) {
return this.clone().mulTo(num, this);
};
BN.prototype.imuln = function imuln (num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(typeof num === 'number');
assert(num < 0x4000000);
// Carry
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = (this.words[i] | 0) * num;
var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
carry >>= 26;
carry += (w / 0x4000000) | 0;
// NOTE: lo is 27bit maximum
carry += lo >>> 26;
this.words[i] = lo & 0x3ffffff;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return isNegNum ? this.ineg() : this;
};
BN.prototype.muln = function muln (num) {
return this.clone().imuln(num);
};
// `this` * `this`
BN.prototype.sqr = function sqr () {
return this.mul(this);
};
// `this` * `this` in-place
BN.prototype.isqr = function isqr () {
return this.imul(this.clone());
};
// Math.pow(`this`, `num`)
BN.prototype.pow = function pow (num) {
var w = toBitArray(num);
if (w.length === 0) return new BN(1);
// Skip leading zeroes
var res = this;
for (var i = 0; i < w.length; i++, res = res.sqr()) {
if (w[i] !== 0) break;
}
if (++i < w.length) {
for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
if (w[i] === 0) continue;
res = res.mul(q);
}
}
return res;
};
// Shift-left in-place
BN.prototype.iushln = function iushln (bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
var i;
if (r !== 0) {
var carry = 0;
for (i = 0; i < this.length; i++) {
var newCarry = this.words[i] & carryMask;
var c = ((this.words[i] | 0) - newCarry) << r;
this.words[i] = c | carry;
carry = newCarry >>> (26 - r);
}
if (carry) {
this.words[i] = carry;
this.length++;
}
}
if (s !== 0) {
for (i = this.length - 1; i >= 0; i--) {
this.words[i + s] = this.words[i];
}
for (i = 0; i < s; i++) {
this.words[i] = 0;
}
this.length += s;
}
return this._strip();
};
BN.prototype.ishln = function ishln (bits) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushln(bits);
};
// Shift-right in-place
// NOTE: `hint` is a lowest bit before trailing zeroes
// NOTE: if `extended` is present - it will be filled with destroyed bits
BN.prototype.iushrn = function iushrn (bits, hint, extended) {
assert(typeof bits === 'number' && bits >= 0);
var h;
if (hint) {
h = (hint - (hint % 26)) / 26;
} else {
h = 0;
}
var r = bits % 26;
var s = Math.min((bits - r) / 26, this.length);
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
var maskedWords = extended;
h -= s;
h = Math.max(0, h);
// Extended mode, copy masked part
if (maskedWords) {
for (var i = 0; i < s; i++) {
maskedWords.words[i] = this.words[i];
}
maskedWords.length = s;
}
if (s === 0) {
// No-op, we should not move anything at all
} else if (this.length > s) {
this.length -= s;
for (i = 0; i < this.length; i++) {
this.words[i] = this.words[i + s];
}
} else {
this.words[0] = 0;
this.length = 1;
}
var carry = 0;
for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
var word = this.words[i] | 0;
this.words[i] = (carry << (26 - r)) | (word >>> r);
carry = word & mask;
}
// Push carried bits as a mask
if (maskedWords && carry !== 0) {
maskedWords.words[maskedWords.length++] = carry;
}
if (this.length === 0) {
this.words[0] = 0;
this.length = 1;
}
return this._strip();
};
BN.prototype.ishrn = function ishrn (bits, hint, extended) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushrn(bits, hint, extended);
};
// Shift-left
BN.prototype.shln = function shln (bits) {
return this.clone().ishln(bits);
};
BN.prototype.ushln = function ushln (bits) {
return this.clone().iushln(bits);
};
// Shift-right
BN.prototype.shrn = function shrn (bits) {
return this.clone().ishrn(bits);
};
BN.prototype.ushrn = function ushrn (bits) {
return this.clone().iushrn(bits);
};
// Test if n bit is set
BN.prototype.testn = function testn (bit) {
assert(typeof bit === 'number' && bit >= 0);
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) return false;
// Check bit and return
var w = this.words[s];
return !!(w & q);
};
// Return only lowers bits of number (in-place)
BN.prototype.imaskn = function imaskn (bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
assert(this.negative === 0, 'imaskn works only with positive numbers');
if (this.length <= s) {
return this;
}
if (r !== 0) {
s++;
}
this.length = Math.min(s, this.length);
if (r !== 0) {
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
this.words[this.length - 1] &= mask;
}
return this._strip();
};
// Return only lowers bits of number
BN.prototype.maskn = function maskn (bits) {
return this.clone().imaskn(bits);
};
// Add plain number `num` to `this`
BN.prototype.iaddn = function iaddn (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
if (num < 0) return this.isubn(-num);
// Possible sign change
if (this.negative !== 0) {
if (this.length === 1 && (this.words[0] | 0) <= num) {
this.words[0] = num - (this.words[0] | 0);
this.negative = 0;
return this;
}
this.negative = 0;
this.isubn(num);
this.negative = 1;
return this;
}
// Add without checks
return this._iaddn(num);
};
BN.prototype._iaddn = function _iaddn (num) {
this.words[0] += num;
// Carry
for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
this.words[i] -= 0x4000000;
if (i === this.length - 1) {
this.words[i + 1] = 1;
} else {
this.words[i + 1]++;
}
}
this.length = Math.max(this.length, i + 1);
return this;
};
// Subtract plain number `num` from `this`
BN.prototype.isubn = function isubn (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
if (num < 0) return this.iaddn(-num);
if (this.negative !== 0) {
this.negative = 0;
this.iaddn(num);
this.negative = 1;
return this;
}
this.words[0] -= num;
if (this.length === 1 && this.words[0] < 0) {
this.words[0] = -this.words[0];
this.negative = 1;
} else {
// Carry
for (var i = 0; i < this.length && this.words[i] < 0; i++) {
this.words[i] += 0x4000000;
this.words[i + 1] -= 1;
}
}
return this._strip();
};
BN.prototype.addn = function addn (num) {
return this.clone().iaddn(num);
};
BN.prototype.subn = function subn (num) {
return this.clone().isubn(num);
};
BN.prototype.iabs = function iabs () {
this.negative = 0;
return this;
};
BN.prototype.abs = function abs () {
return this.clone().iabs();
};
BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
var len = num.length + shift;
var i;
this._expand(len);
var w;
var carry = 0;
for (i = 0; i < num.length; i++) {
w = (this.words[i + shift] | 0) + carry;
var right = (num.words[i] | 0) * mul;
w -= right & 0x3ffffff;
carry = (w >> 26) - ((right / 0x4000000) | 0);
this.words[i + shift] = w & 0x3ffffff;
}
for (; i < this.length - shift; i++) {
w = (this.words[i + shift] | 0) + carry;
carry = w >> 26;
this.words[i + shift] = w & 0x3ffffff;
}
if (carry === 0) return this._strip();
// Subtraction overflow
assert(carry === -1);
carry = 0;
for (i = 0; i < this.length; i++) {
w = -(this.words[i] | 0) + carry;
carry = w >> 26;
this.words[i] = w & 0x3ffffff;
}
this.negative = 1;
return this._strip();
};
BN.prototype._wordDiv = function _wordDiv (num, mode) {
var shift = this.length - num.length;
var a = this.clone();
var b = num;
// Normalize
var bhi = b.words[b.length - 1] | 0;
var bhiBits = this._countBits(bhi);
shift = 26 - bhiBits;
if (shift !== 0) {
b = b.ushln(shift);
a.iushln(shift);
bhi = b.words[b.length - 1] | 0;
}
// Initialize quotient
var m = a.length - b.length;
var q;
if (mode !== 'mod') {
q = new BN(null);
q.length = m + 1;
q.words = new Array(q.length);
for (var i = 0; i < q.length; i++) {
q.words[i] = 0;
}
}
var diff = a.clone()._ishlnsubmul(b, 1, m);
if (diff.negative === 0) {
a = diff;
if (q) {
q.words[m] = 1;
}
}
for (var j = m - 1; j >= 0; j--) {
var qj = (a.words[b.length + j] | 0) * 0x4000000 +
(a.words[b.length + j - 1] | 0);
// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj = Math.min((qj / bhi) | 0, 0x3ffffff);
a._ishlnsubmul(b, qj, j);
while (a.negative !== 0) {
qj--;
a.negative = 0;
a._ishlnsubmul(b, 1, j);
if (!a.isZero()) {
a.negative ^= 1;
}
}
if (q) {
q.words[j] = qj;
}
}
if (q) {
q._strip();
}
a._strip();
// Denormalize
if (mode !== 'div' && shift !== 0) {
a.iushrn(shift);
}
return {
div: q || null,
mod: a
};
};
// NOTE: 1) `mode` can be set to `mod` to request mod only,
// to `div` to request div only, or be absent to
// request both div & mod
// 2) `positive` is true if unsigned mod is requested
BN.prototype.divmod = function divmod (num, mode, positive) {
assert(!num.isZero());
if (this.isZero()) {
return {
div: new BN(0),
mod: new BN(0)
};
}
var div, mod, res;
if (this.negative !== 0 && num.negative === 0) {
res = this.neg().divmod(num, mode);
if (mode !== 'mod') {
div = res.div.neg();
}
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.negative !== 0) {
mod.iadd(num);
}
}
return {
div: div,
mod: mod
};
}
if (this.negative === 0 && num.negative !== 0) {
res = this.divmod(num.neg(), mode);
if (mode !== 'mod') {
div = res.div.neg();
}
return {
div: div,
mod: res.mod
};
}
if ((this.negative & num.negative) !== 0) {
res = this.neg().divmod(num.neg(), mode);
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.negative !== 0) {
mod.isub(num);
}
}
return {
div: res.div,
mod: mod
};
}
// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if (num.length > this.length || this.cmp(num) < 0) {
return {
div: new BN(0),
mod: this
};
}
// Very short reduction
if (num.length === 1) {
if (mode === 'div') {
return {
div: this.divn(num.words[0]),
mod: null
};
}
if (mode === 'mod') {
return {
div: null,
mod: new BN(this.modrn(num.words[0]))
};
}
return {
div: this.divn(num.words[0]),
mod: new BN(this.modrn(num.words[0]))
};
}
return this._wordDiv(num, mode);
};
// Find `this` / `num`
BN.prototype.div = function div (num) {
return this.divmod(num, 'div', false).div;
};
// Find `this` % `num`
BN.prototype.mod = function mod (num) {
return this.divmod(num, 'mod', false).mod;
};
BN.prototype.umod = function umod (num) {
return this.divmod(num, 'mod', true).mod;
};
// Find Round(`this` / `num`)
BN.prototype.divRound = function divRound (num) {
var dm = this.divmod(num);
// Fast case - exact division
if (dm.mod.isZero()) return dm.div;
var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
var half = num.ushrn(1);
var r2 = num.andln(1);
var cmp = mod.cmp(half);
// Round down
if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;
// Round up
return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
};
BN.prototype.modrn = function modrn (num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(num <= 0x3ffffff);
var p = (1 << 26) % num;
var acc = 0;
for (var i = this.length - 1; i >= 0; i--) {
acc = (p * acc + (this.words[i] | 0)) % num;
}
return isNegNum ? -acc : acc;
};
// WARNING: DEPRECATED
BN.prototype.modn = function modn (num) {
return this.modrn(num);
};
// In-place division by number
BN.prototype.idivn = function idivn (num) {
var isNegNum = num < 0;
if (isNegNum) num = -num;
assert(num <= 0x3ffffff);
var carry = 0;
for (var i = this.length - 1; i >= 0; i--) {
var w = (this.words[i] | 0) + carry * 0x4000000;
this.words[i] = (w / num) | 0;
carry = w % num;
}
this._strip();
return isNegNum ? this.ineg() : this;
};
BN.prototype.divn = function divn (num) {
return this.clone().idivn(num);
};
BN.prototype.egcd = function egcd (p) {
assert(p.negative === 0);
assert(!p.isZero());
var x = this;
var y = p.clone();
if (x.negative !== 0) {
x = x.umod(p);
} else {
x = x.clone();
}
// A * x + B * y = x
var A = new BN(1);
var B = new BN(0);
// C * x + D * y = y
var C = new BN(0);
var D = new BN(1);
var g = 0;
while (x.isEven() && y.isEven()) {
x.iushrn(1);
y.iushrn(1);
++g;
}
var yp = y.clone();
var xp = x.clone();
while (!x.isZero()) {
for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
x.iushrn(i);
while (i-- > 0) {
if (A.isOdd() || B.isOdd()) {
A.iadd(yp);
B.isub(xp);
}
A.iushrn(1);
B.iushrn(1);
}
}
for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
y.iushrn(j);
while (j-- > 0) {
if (C.isOdd() || D.isOdd()) {
C.iadd(yp);
D.isub(xp);
}
C.iushrn(1);
D.iushrn(1);
}
}
if (x.cmp(y) >= 0) {
x.isub(y);
A.isub(C);
B.isub(D);
} else {
y.isub(x);
C.isub(A);
D.isub(B);
}
}
return {
a: C,
b: D,
gcd: y.iushln(g)
};
};
// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp = function _invmp (p) {
assert(p.negative === 0);
assert(!p.isZero());
var a = this;
var b = p.clone();
if (a.negative !== 0) {
a = a.umod(p);
} else {
a = a.clone();
}
var x1 = new BN(1);
var x2 = new BN(0);
var delta = b.clone();
while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
a.iushrn(i);
while (i-- > 0) {
if (x1.isOdd()) {
x1.iadd(delta);
}
x1.iushrn(1);
}
}
for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
b.iushrn(j);
while (j-- > 0) {
if (x2.isOdd()) {
x2.iadd(delta);
}
x2.iushrn(1);
}
}
if (a.cmp(b) >= 0) {
a.isub(b);
x1.isub(x2);
} else {
b.isub(a);
x2.isub(x1);
}
}
var res;
if (a.cmpn(1) === 0) {
res = x1;
} else {
res = x2;
}
if (res.cmpn(0) < 0) {
res.iadd(p);
}
return res;
};
BN.prototype.gcd = function gcd (num) {
if (this.isZero()) return num.abs();
if (num.isZero()) return this.abs();
var a = this.clone();
var b = num.clone();
a.negative = 0;
b.negative = 0;
// Remove common factor of two
for (var shift = 0; a.isEven() && b.isEven(); shift++) {
a.iushrn(1);
b.iushrn(1);
}
do {
while (a.isEven()) {
a.iushrn(1);
}
while (b.isEven()) {
b.iushrn(1);
}
var r = a.cmp(b);
if (r < 0) {
// Swap `a` and `b` to make `a` always bigger than `b`
var t = a;
a = b;
b = t;
} else if (r === 0 || b.cmpn(1) === 0) {
break;
}
a.isub(b);
} while (true);
return b.iushln(shift);
};
// Invert number in the field F(num)
BN.prototype.invm = function invm (num) {
return this.egcd(num).a.umod(num);
};
BN.prototype.isEven = function isEven () {
return (this.words[0] & 1) === 0;
};
BN.prototype.isOdd = function isOdd () {
return (this.words[0] & 1) === 1;
};
// And first word and num
BN.prototype.andln = function andln (num) {
return this.words[0] & num;
};
// Increment at the bit position in-line
BN.prototype.bincn = function bincn (bit) {
assert(typeof bit === 'number');
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
this._expand(s + 1);
this.words[s] |= q;
return this;
}
// Add bit and propagate, if needed
var carry = q;
for (var i = s; carry !== 0 && i < this.length; i++) {
var w = this.words[i] | 0;
w += carry;
carry = w >>> 26;
w &= 0x3ffffff;
this.words[i] = w;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.isZero = function isZero () {
return this.length === 1 && this.words[0] === 0;
};
BN.prototype.cmpn = function cmpn (num) {
var negative = num < 0;
if (this.negative !== 0 && !negative) return -1;
if (this.negative === 0 && negative) return 1;
this._strip();
var res;
if (this.length > 1) {
res = 1;
} else {
if (negative) {
num = -num;
}
assert(num <= 0x3ffffff, 'Number is too big');
var w = this.words[0] | 0;
res = w === num ? 0 : w < num ? -1 : 1;
}
if (this.negative !== 0) return -res | 0;
return res;
};
// Compare two numbers and return:
// 1 - if `this` > `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp = function cmp (num) {
if (this.negative !== 0 && num.negative === 0) return -1;
if (this.negative === 0 && num.negative !== 0) return 1;
var res = this.ucmp(num);
if (this.negative !== 0) return -res | 0;
return res;
};
// Unsigned comparison
BN.prototype.ucmp = function ucmp (num) {
// At this point both numbers have the same sign
if (this.length > num.length) return 1;
if (this.length < num.length) return -1;
var res = 0;
for (var i = this.length - 1; i >= 0; i--) {
var a = this.words[i] | 0;
var b = num.words[i] | 0;
if (a === b) continue;
if (a < b) {
res = -1;
} else if (a > b) {
res = 1;
}
break;
}
return res;
};
BN.prototype.gtn = function gtn (num) {
return this.cmpn(num) === 1;
};
BN.prototype.gt = function gt (num) {
return this.cmp(num) === 1;
};
BN.prototype.gten = function gten (num) {
return this.cmpn(num) >= 0;
};
BN.prototype.gte = function gte (num) {
return this.cmp(num) >= 0;
};
BN.prototype.ltn = function ltn (num) {
return this.cmpn(num) === -1;
};
BN.prototype.lt = function lt (num) {
return this.cmp(num) === -1;
};
BN.prototype.lten = function lten (num) {
return this.cmpn(num) <= 0;
};
BN.prototype.lte = function lte (num) {
return this.cmp(num) <= 0;
};
BN.prototype.eqn = function eqn (num) {
return this.cmpn(num) === 0;
};
BN.prototype.eq = function eq (num) {
return this.cmp(num) === 0;
};
//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red = function red (num) {
return new Red(num);
};
BN.prototype.toRed = function toRed (ctx) {
assert(!this.red, 'Already a number in reduction context');
assert(this.negative === 0, 'red works only with positives');
return ctx.convertTo(this)._forceRed(ctx);
};
BN.prototype.fromRed = function fromRed () {
assert(this.red, 'fromRed works only with numbers in reduction context');
return this.red.convertFrom(this);
};
BN.prototype._forceRed = function _forceRed (ctx) {
this.red = ctx;
return this;
};
BN.prototype.forceRed = function forceRed (ctx) {
assert(!this.red, 'Already a number in reduction context');
return this._forceRed(ctx);
};
BN.prototype.redAdd = function redAdd (num) {
assert(this.red, 'redAdd works only with red numbers');
return this.red.add(this, num);
};
BN.prototype.redIAdd = function redIAdd (num) {
assert(this.red, 'redIAdd works only with red numbers');
return this.red.iadd(this, num);
};
BN.prototype.redSub = function redSub (num) {
assert(this.red, 'redSub works only with red numbers');
return this.red.sub(this, num);
};
BN.prototype.redISub = function redISub (num) {
assert(this.red, 'redISub works only with red numbers');
return this.red.isub(this, num);
};
BN.prototype.redShl = function redShl (num) {
assert(this.red, 'redShl works only with red numbers');
return this.red.shl(this, num);
};
BN.prototype.redMul = function redMul (num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.mul(this, num);
};
BN.prototype.redIMul = function redIMul (num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.imul(this, num);
};
BN.prototype.redSqr = function redSqr () {
assert(this.red, 'redSqr works only with red numbers');
this.red._verify1(this);
return this.red.sqr(this);
};
BN.prototype.redISqr = function redISqr () {
assert(this.red, 'redISqr works only with red numbers');
this.red._verify1(this);
return this.red.isqr(this);
};
// Square root over p
BN.prototype.redSqrt = function redSqrt () {
assert(this.red, 'redSqrt works only with red numbers');
this.red._verify1(this);
return this.red.sqrt(this);
};
BN.prototype.redInvm = function redInvm () {
assert(this.red, 'redInvm works only with red numbers');
this.red._verify1(this);
return this.red.invm(this);
};
// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg = function redNeg () {
assert(this.red, 'redNeg works only with red numbers');
this.red._verify1(this);
return this.red.neg(this);
};
BN.prototype.redPow = function redPow (num) {
assert(this.red && !num.red, 'redPow(normalNum)');
this.red._verify1(this);
return this.red.pow(this, num);
};
// Prime numbers with efficient reduction
var primes = {
k256: null,
p224: null,
p192: null,
p25519: null
};
// Pseudo-Mersenne prime
function MPrime (name, p) {
// P = 2 ^ N - K
this.name = name;
this.p = new BN(p, 16);
this.n = this.p.bitLength();
this.k = new BN(1).iushln(this.n).isub(this.p);
this.tmp = this._tmp();
}
MPrime.prototype._tmp = function _tmp () {
var tmp = new BN(null);
tmp.words = new Array(Math.ceil(this.n / 13));
return tmp;
};
MPrime.prototype.ireduce = function ireduce (num) {
// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r = num;
var rlen;
do {
this.split(r, this.tmp);
r = this.imulK(r);
r = r.iadd(this.tmp);
rlen = r.bitLength();
} while (rlen > this.n);
var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
if (cmp === 0) {
r.words[0] = 0;
r.length = 1;
} else if (cmp > 0) {
r.isub(this.p);
} else {
if (r.strip !== undefined) {
// r is a BN v4 instance
r.strip();
} else {
// r is a BN v5 instance
r._strip();
}
}
return r;
};
MPrime.prototype.split = function split (input, out) {
input.iushrn(this.n, 0, out);
};
MPrime.prototype.imulK = function imulK (num) {
return num.imul(this.k);
};
function K256 () {
MPrime.call(
this,
'k256',
'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
}
inherits(K256, MPrime);
K256.prototype.split = function split (input, output) {
// 256 = 9 * 26 + 22
var mask = 0x3fffff;
var outLen = Math.min(input.length, 9);
for (var i = 0; i < outLen; i++) {
output.words[i] = input.words[i];
}
output.length = outLen;
if (input.length <= 9) {
input.words[0] = 0;
input.length = 1;
return;
}
// Shift by 9 limbs
var prev = input.words[9];
output.words[output.length++] = prev & mask;
for (i = 10; i < input.length; i++) {
var next = input.words[i] | 0;
input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
prev = next;
}
prev >>>= 22;
input.words[i - 10] = prev;
if (prev === 0 && input.length > 10) {
input.length -= 10;
} else {
input.length -= 9;
}
};
K256.prototype.imulK = function imulK (num) {
// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var lo = 0;
for (var i = 0; i < num.length; i++) {
var w = num.words[i] | 0;
lo += w * 0x3d1;
num.words[i] = lo & 0x3ffffff;
lo = w * 0x40 + ((lo / 0x4000000) | 0);
}
// Fast length reduction
if (num.words[num.length - 1] === 0) {
num.length--;
if (num.words[num.length - 1] === 0) {
num.length--;
}
}
return num;
};
function P224 () {
MPrime.call(
this,
'p224',
'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
}
inherits(P224, MPrime);
function P192 () {
MPrime.call(
this,
'p192',
'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
}
inherits(P192, MPrime);
function P25519 () {
// 2 ^ 255 - 19
MPrime.call(
this,
'25519',
'7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
}
inherits(P25519, MPrime);
P25519.prototype.imulK = function imulK (num) {
// K = 0x13
var carry = 0;
for (var i = 0; i < num.length; i++) {
var hi = (num.words[i] | 0) * 0x13 + carry;
var lo = hi & 0x3ffffff;
hi >>>= 26;
num.words[i] = lo;
carry = hi;
}
if (carry !== 0) {
num.words[num.length++] = carry;
}
return num;
};
// Exported mostly for testing purposes, use plain name instead
BN._prime = function prime (name) {
// Cached version of prime
if (primes[name]) return primes[name];
var prime;
if (name === 'k256') {
prime = new K256();
} else if (name === 'p224') {
prime = new P224();
} else if (name === 'p192') {
prime = new P192();
} else if (name === 'p25519') {
prime = new P25519();
} else {
throw new Error('Unknown prime ' + name);
}
primes[name] = prime;
return prime;
};
//
// Base reduction engine
//
function Red (m) {
if (typeof m === 'string') {
var prime = BN._prime(m);
this.m = prime.p;
this.prime = prime;
} else {
assert(m.gtn(1), 'modulus must be greater than 1');
this.m = m;
this.prime = null;
}
}
Red.prototype._verify1 = function _verify1 (a) {
assert(a.negative === 0, 'red works only with positives');
assert(a.red, 'red works only with red numbers');
};
Red.prototype._verify2 = function _verify2 (a, b) {
assert((a.negative | b.negative) === 0, 'red works only with positives');
assert(a.red && a.red === b.red,
'red works only with red numbers');
};
Red.prototype.imod = function imod (a) {
if (this.prime) return this.prime.ireduce(a)._forceRed(this);
move(a, a.umod(this.m)._forceRed(this));
return a;
};
Red.prototype.neg = function neg (a) {
if (a.isZero()) {
return a.clone();
}
return this.m.sub(a)._forceRed(this);
};
Red.prototype.add = function add (a, b) {
this._verify2(a, b);
var res = a.add(b);
if (res.cmp(this.m) >= 0) {
res.isub(this.m);
}
return res._forceRed(this);
};
Red.prototype.iadd = function iadd (a, b) {
this._verify2(a, b);
var res = a.iadd(b);
if (res.cmp(this.m) >= 0) {
res.isub(this.m);
}
return res;
};
Red.prototype.sub = function sub (a, b) {
this._verify2(a, b);
var res = a.sub(b);
if (res.cmpn(0) < 0) {
res.iadd(this.m);
}
return res._forceRed(this);
};
Red.prototype.isub = function isub (a, b) {
this._verify2(a, b);
var res = a.isub(b);
if (res.cmpn(0) < 0) {
res.iadd(this.m);
}
return res;
};
Red.prototype.shl = function shl (a, num) {
this._verify1(a);
return this.imod(a.ushln(num));
};
Red.prototype.imul = function imul (a, b) {
this._verify2(a, b);
return this.imod(a.imul(b));
};
Red.prototype.mul = function mul (a, b) {
this._verify2(a, b);
return this.imod(a.mul(b));
};
Red.prototype.isqr = function isqr (a) {
return this.imul(a, a.clone());
};
Red.prototype.sqr = function sqr (a) {
return this.mul(a, a);
};
Red.prototype.sqrt = function sqrt (a) {
if (a.isZero()) return a.clone();
var mod3 = this.m.andln(3);
assert(mod3 % 2 === 1);
// Fast case
if (mod3 === 3) {
var pow = this.m.add(new BN(1)).iushrn(2);
return this.pow(a, pow);
}
// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q = this.m.subn(1);
var s = 0;
while (!q.isZero() && q.andln(1) === 0) {
s++;
q.iushrn(1);
}
assert(!q.isZero());
var one = new BN(1).toRed(this);
var nOne = one.redNeg();
// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow = this.m.subn(1).iushrn(1);
var z = this.m.bitLength();
z = new BN(2 * z * z).toRed(this);
while (this.pow(z, lpow).cmp(nOne) !== 0) {
z.redIAdd(nOne);
}
var c = this.pow(z, q);
var r = this.pow(a, q.addn(1).iushrn(1));
var t = this.pow(a, q);
var m = s;
while (t.cmp(one) !== 0) {
var tmp = t;
for (var i = 0; tmp.cmp(one) !== 0; i++) {
tmp = tmp.redSqr();
}
assert(i < m);
var b = this.pow(c, new BN(1).iushln(m - i - 1));
r = r.redMul(b);
c = b.redSqr();
t = t.redMul(c);
m = i;
}
return r;
};
Red.prototype.invm = function invm (a) {
var inv = a._invmp(this.m);
if (inv.negative !== 0) {
inv.negative = 0;
return this.imod(inv).redNeg();
} else {
return this.imod(inv);
}
};
Red.prototype.pow = function pow (a, num) {
if (num.isZero()) return new BN(1).toRed(this);
if (num.cmpn(1) === 0) return a.clone();
var windowSize = 4;
var wnd = new Array(1 << windowSize);
wnd[0] = new BN(1).toRed(this);
wnd[1] = a;
for (var i = 2; i < wnd.length; i++) {
wnd[i] = this.mul(wnd[i - 1], a);
}
var res = wnd[0];
var current = 0;
var currentLen = 0;
var start = num.bitLength() % 26;
if (start === 0) {
start = 26;
}
for (i = num.length - 1; i >= 0; i--) {
var word = num.words[i];
for (var j = start - 1; j >= 0; j--) {
var bit = (word >> j) & 1;
if (res !== wnd[0]) {
res = this.sqr(res);
}
if (bit === 0 && current === 0) {
currentLen = 0;
continue;
}
current <<= 1;
current |= bit;
currentLen++;
if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
res = this.mul(res, wnd[current]);
currentLen = 0;
current = 0;
}
start = 26;
}
return res;
};
Red.prototype.convertTo = function convertTo (num) {
var r = num.umod(this.m);
return r === num ? r.clone() : r;
};
Red.prototype.convertFrom = function convertFrom (num) {
var res = num.clone();
res.red = null;
return res;
};
//
// Montgomery method engine
//
BN.mont = function mont (num) {
return new Mont(num);
};
function Mont (m) {
Red.call(this, m);
this.shift = this.m.bitLength();
if (this.shift % 26 !== 0) {
this.shift += 26 - (this.shift % 26);
}
this.r = new BN(1).iushln(this.shift);
this.r2 = this.imod(this.r.sqr());
this.rinv = this.r._invmp(this.m);
this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
this.minv = this.minv.umod(this.r);
this.minv = this.r.sub(this.minv);
}
inherits(Mont, Red);
Mont.prototype.convertTo = function convertTo (num) {
return this.imod(num.ushln(this.shift));
};
Mont.prototype.convertFrom = function convertFrom (num) {
var r = this.imod(num.mul(this.rinv));
r.red = null;
return r;
};
Mont.prototype.imul = function imul (a, b) {
if (a.isZero() || b.isZero()) {
a.words[0] = 0;
a.length = 1;
return a;
}
var t = a.imul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) {
res = u.isub(this.m);
} else if (u.cmpn(0) < 0) {
res = u.iadd(this.m);
}
return res._forceRed(this);
};
Mont.prototype.mul = function mul (a, b) {
if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
var t = a.mul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) {
res = u.isub(this.m);
} else if (u.cmpn(0) < 0) {
res = u.iadd(this.m);
}
return res._forceRed(this);
};
Mont.prototype.invm = function invm (a) {
// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res = this.imod(a._invmp(this.m).mul(this.r2));
return res._forceRed(this);
};
})( false || module, this);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)(module)))
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/**
* [js-sha3]{@link https://github.com/emn178/js-sha3}
*
* @version 0.8.0
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2015-2018
* @license MIT
*/
/*jslint bitwise: true */
(function () {
'use strict';
var INPUT_ERROR = 'input is invalid type';
var FINALIZE_ERROR = 'finalize already called';
var WINDOW = typeof window === 'object';
var root = WINDOW ? window : {};
if (root.JS_SHA3_NO_WINDOW) {
WINDOW = false;
}
var WEB_WORKER = !WINDOW && typeof self === 'object';
var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
if (NODE_JS) {
root = global;
} else if (WEB_WORKER) {
root = self;
}
var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;
var AMD = true && __webpack_require__(35);
var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';
var HEX_CHARS = '0123456789abcdef'.split('');
var SHAKE_PADDING = [31, 7936, 2031616, 520093696];
var CSHAKE_PADDING = [4, 1024, 262144, 67108864];
var KECCAK_PADDING = [1, 256, 65536, 16777216];
var PADDING = [6, 1536, 393216, 100663296];
var SHIFT = [0, 8, 16, 24];
var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,
0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,
2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,
2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,
2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
var BITS = [224, 256, 384, 512];
var SHAKE_BITS = [128, 256];
var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];
var CSHAKE_BYTEPAD = {
'128': 168,
'256': 136
};
if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) {
Array.isArray = function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
}
if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {
ArrayBuffer.isView = function (obj) {
return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;
};
}
var createOutputMethod = function (bits, padding, outputType) {
return function (message) {
return new Keccak(bits, padding, bits).update(message)[outputType]();
};
};
var createShakeOutputMethod = function (bits, padding, outputType) {
return function (message, outputBits) {
return new Keccak(bits, padding, outputBits).update(message)[outputType]();
};
};
var createCshakeOutputMethod = function (bits, padding, outputType) {
return function (message, outputBits, n, s) {
return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();
};
};
var createKmacOutputMethod = function (bits, padding, outputType) {
return function (key, message, outputBits, s) {
return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();
};
};
var createOutputMethods = function (method, createMethod, bits, padding) {
for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
var type = OUTPUT_TYPES[i];
method[type] = createMethod(bits, padding, type);
}
return method;
};
var createMethod = function (bits, padding) {
var method = createOutputMethod(bits, padding, 'hex');
method.create = function () {
return new Keccak(bits, padding, bits);
};
method.update = function (message) {
return method.create().update(message);
};
return createOutputMethods(method, createOutputMethod, bits, padding);
};
var createShakeMethod = function (bits, padding) {
var method = createShakeOutputMethod(bits, padding, 'hex');
method.create = function (outputBits) {
return new Keccak(bits, padding, outputBits);
};
method.update = function (message, outputBits) {
return method.create(outputBits).update(message);
};
return createOutputMethods(method, createShakeOutputMethod, bits, padding);
};
var createCshakeMethod = function (bits, padding) {
var w = CSHAKE_BYTEPAD[bits];
var method = createCshakeOutputMethod(bits, padding, 'hex');
method.create = function (outputBits, n, s) {
if (!n && !s) {
return methods['shake' + bits].create(outputBits);
} else {
return new Keccak(bits, padding, outputBits).bytepad([n, s], w);
}
};
method.update = function (message, outputBits, n, s) {
return method.create(outputBits, n, s).update(message);
};
return createOutputMethods(method, createCshakeOutputMethod, bits, padding);
};
var createKmacMethod = function (bits, padding) {
var w = CSHAKE_BYTEPAD[bits];
var method = createKmacOutputMethod(bits, padding, 'hex');
method.create = function (key, outputBits, s) {
return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);
};
method.update = function (key, message, outputBits, s) {
return method.create(key, outputBits, s).update(message);
};
return createOutputMethods(method, createKmacOutputMethod, bits, padding);
};
var algorithms = [
{ name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },
{ name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },
{ name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },
{ name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },
{ name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }
];
var methods = {}, methodNames = [];
for (var i = 0; i < algorithms.length; ++i) {
var algorithm = algorithms[i];
var bits = algorithm.bits;
for (var j = 0; j < bits.length; ++j) {
var methodName = algorithm.name + '_' + bits[j];
methodNames.push(methodName);
methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);
if (algorithm.name !== 'sha3') {
var newMethodName = algorithm.name + bits[j];
methodNames.push(newMethodName);
methods[newMethodName] = methods[methodName];
}
}
}
function Keccak(bits, padding, outputBits) {
this.blocks = [];
this.s = [];
this.padding = padding;
this.outputBits = outputBits;
this.reset = true;
this.finalized = false;
this.block = 0;
this.start = 0;
this.blockCount = (1600 - (bits << 1)) >> 5;
this.byteCount = this.blockCount << 2;
this.outputBlocks = outputBits >> 5;
this.extraBytes = (outputBits & 31) >> 3;
for (var i = 0; i < 50; ++i) {
this.s[i] = 0;
}
}
Keccak.prototype.update = function (message) {
if (this.finalized) {
throw new Error(FINALIZE_ERROR);
}
var notString, type = typeof message;
if (type !== 'string') {
if (type === 'object') {
if (message === null) {
throw new Error(INPUT_ERROR);
} else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {
message = new Uint8Array(message);
} else if (!Array.isArray(message)) {
if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {
throw new Error(INPUT_ERROR);
}
}
} else {
throw new Error(INPUT_ERROR);
}
notString = true;
}
var blocks = this.blocks, byteCount = this.byteCount, length = message.length,
blockCount = this.blockCount, index = 0, s = this.s, i, code;
while (index < length) {
if (this.reset) {
this.reset = false;
blocks[0] = this.block;
for (i = 1; i < blockCount + 1; ++i) {
blocks[i] = 0;
}
}
if (notString) {
for (i = this.start; index < length && i < byteCount; ++index) {
blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
}
} else {
for (i = this.start; index < length && i < byteCount; ++index) {
code = message.charCodeAt(index);
if (code < 0x80) {
blocks[i >> 2] |= code << SHIFT[i++ & 3];
} else if (code < 0x800) {
blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
} else if (code < 0xd800 || code >= 0xe000) {
blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
} else {
code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
}
}
}
this.lastByteIndex = i;
if (i >= byteCount) {
this.start = i - byteCount;
this.block = blocks[blockCount];
for (i = 0; i < blockCount; ++i) {
s[i] ^= blocks[i];
}
f(s);
this.reset = true;
} else {
this.start = i;
}
}
return this;
};
Keccak.prototype.encode = function (x, right) {
var o = x & 255, n = 1;
var bytes = [o];
x = x >> 8;
o = x & 255;
while (o > 0) {
bytes.unshift(o);
x = x >> 8;
o = x & 255;
++n;
}
if (right) {
bytes.push(n);
} else {
bytes.unshift(n);
}
this.update(bytes);
return bytes.length;
};
Keccak.prototype.encodeString = function (str) {
var notString, type = typeof str;
if (type !== 'string') {
if (type === 'object') {
if (str === null) {
throw new Error(INPUT_ERROR);
} else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) {
str = new Uint8Array(str);
} else if (!Array.isArray(str)) {
if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) {
throw new Error(INPUT_ERROR);
}
}
} else {
throw new Error(INPUT_ERROR);
}
notString = true;
}
var bytes = 0, length = str.length;
if (notString) {
bytes = length;
} else {
for (var i = 0; i < str.length; ++i) {
var code = str.charCodeAt(i);
if (code < 0x80) {
bytes += 1;
} else if (code < 0x800) {
bytes += 2;
} else if (code < 0xd800 || code >= 0xe000) {
bytes += 3;
} else {
code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));
bytes += 4;
}
}
}
bytes += this.encode(bytes * 8);
this.update(str);
return bytes;
};
Keccak.prototype.bytepad = function (strs, w) {
var bytes = this.encode(w);
for (var i = 0; i < strs.length; ++i) {
bytes += this.encodeString(strs[i]);
}
var paddingBytes = w - bytes % w;
var zeros = [];
zeros.length = paddingBytes;
this.update(zeros);
return this;
};
Keccak.prototype.finalize = function () {
if (this.finalized) {
return;
}
this.finalized = true;
var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;
blocks[i >> 2] |= this.padding[i & 3];
if (this.lastByteIndex === this.byteCount) {
blocks[0] = blocks[blockCount];
for (i = 1; i < blockCount + 1; ++i) {
blocks[i] = 0;
}
}
blocks[blockCount - 1] |= 0x80000000;
for (i = 0; i < blockCount; ++i) {
s[i] ^= blocks[i];
}
f(s);
};
Keccak.prototype.toString = Keccak.prototype.hex = function () {
this.finalize();
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
extraBytes = this.extraBytes, i = 0, j = 0;
var hex = '', block;
while (j < outputBlocks) {
for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
block = s[i];
hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +
HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +
HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +
HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];
}
if (j % blockCount === 0) {
f(s);
i = 0;
}
}
if (extraBytes) {
block = s[i];
hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];
if (extraBytes > 1) {
hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];
}
if (extraBytes > 2) {
hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];
}
}
return hex;
};
Keccak.prototype.arrayBuffer = function () {
this.finalize();
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
extraBytes = this.extraBytes, i = 0, j = 0;
var bytes = this.outputBits >> 3;
var buffer;
if (extraBytes) {
buffer = new ArrayBuffer((outputBlocks + 1) << 2);
} else {
buffer = new ArrayBuffer(bytes);
}
var array = new Uint32Array(buffer);
while (j < outputBlocks) {
for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
array[j] = s[i];
}
if (j % blockCount === 0) {
f(s);
}
}
if (extraBytes) {
array[i] = s[i];
buffer = buffer.slice(0, bytes);
}
return buffer;
};
Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;
Keccak.prototype.digest = Keccak.prototype.array = function () {
this.finalize();
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
extraBytes = this.extraBytes, i = 0, j = 0;
var array = [], offset, block;
while (j < outputBlocks) {
for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
offset = j << 2;
block = s[i];
array[offset] = block & 0xFF;
array[offset + 1] = (block >> 8) & 0xFF;
array[offset + 2] = (block >> 16) & 0xFF;
array[offset + 3] = (block >> 24) & 0xFF;
}
if (j % blockCount === 0) {
f(s);
}
}
if (extraBytes) {
offset = j << 2;
block = s[i];
array[offset] = block & 0xFF;
if (extraBytes > 1) {
array[offset + 1] = (block >> 8) & 0xFF;
}
if (extraBytes > 2) {
array[offset + 2] = (block >> 16) & 0xFF;
}
}
return array;
};
function Kmac(bits, padding, outputBits) {
Keccak.call(this, bits, padding, outputBits);
}
Kmac.prototype = new Keccak();
Kmac.prototype.finalize = function () {
this.encode(this.outputBits, true);
return Keccak.prototype.finalize.call(this);
};
var f = function (s) {
var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,
b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,
b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,
b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
for (n = 0; n < 48; n += 2) {
c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
h = c8 ^ ((c2 << 1) | (c3 >>> 31));
l = c9 ^ ((c3 << 1) | (c2 >>> 31));
s[0] ^= h;
s[1] ^= l;
s[10] ^= h;
s[11] ^= l;
s[20] ^= h;
s[21] ^= l;
s[30] ^= h;
s[31] ^= l;
s[40] ^= h;
s[41] ^= l;
h = c0 ^ ((c4 << 1) | (c5 >>> 31));
l = c1 ^ ((c5 << 1) | (c4 >>> 31));
s[2] ^= h;
s[3] ^= l;
s[12] ^= h;
s[13] ^= l;
s[22] ^= h;
s[23] ^= l;
s[32] ^= h;
s[33] ^= l;
s[42] ^= h;
s[43] ^= l;
h = c2 ^ ((c6 << 1) | (c7 >>> 31));
l = c3 ^ ((c7 << 1) | (c6 >>> 31));
s[4] ^= h;
s[5] ^= l;
s[14] ^= h;
s[15] ^= l;
s[24] ^= h;
s[25] ^= l;
s[34] ^= h;
s[35] ^= l;
s[44] ^= h;
s[45] ^= l;
h = c4 ^ ((c8 << 1) | (c9 >>> 31));
l = c5 ^ ((c9 << 1) | (c8 >>> 31));
s[6] ^= h;
s[7] ^= l;
s[16] ^= h;
s[17] ^= l;
s[26] ^= h;
s[27] ^= l;
s[36] ^= h;
s[37] ^= l;
s[46] ^= h;
s[47] ^= l;
h = c6 ^ ((c0 << 1) | (c1 >>> 31));
l = c7 ^ ((c1 << 1) | (c0 >>> 31));
s[8] ^= h;
s[9] ^= l;
s[18] ^= h;
s[19] ^= l;
s[28] ^= h;
s[29] ^= l;
s[38] ^= h;
s[39] ^= l;
s[48] ^= h;
s[49] ^= l;
b0 = s[0];
b1 = s[1];
b32 = (s[11] << 4) | (s[10] >>> 28);
b33 = (s[10] << 4) | (s[11] >>> 28);
b14 = (s[20] << 3) | (s[21] >>> 29);
b15 = (s[21] << 3) | (s[20] >>> 29);
b46 = (s[31] << 9) | (s[30] >>> 23);
b47 = (s[30] << 9) | (s[31] >>> 23);
b28 = (s[40] << 18) | (s[41] >>> 14);
b29 = (s[41] << 18) | (s[40] >>> 14);
b20 = (s[2] << 1) | (s[3] >>> 31);
b21 = (s[3] << 1) | (s[2] >>> 31);
b2 = (s[13] << 12) | (s[12] >>> 20);
b3 = (s[12] << 12) | (s[13] >>> 20);
b34 = (s[22] << 10) | (s[23] >>> 22);
b35 = (s[23] << 10) | (s[22] >>> 22);
b16 = (s[33] << 13) | (s[32] >>> 19);
b17 = (s[32] << 13) | (s[33] >>> 19);
b48 = (s[42] << 2) | (s[43] >>> 30);
b49 = (s[43] << 2) | (s[42] >>> 30);
b40 = (s[5] << 30) | (s[4] >>> 2);
b41 = (s[4] << 30) | (s[5] >>> 2);
b22 = (s[14] << 6) | (s[15] >>> 26);
b23 = (s[15] << 6) | (s[14] >>> 26);
b4 = (s[25] << 11) | (s[24] >>> 21);
b5 = (s[24] << 11) | (s[25] >>> 21);
b36 = (s[34] << 15) | (s[35] >>> 17);
b37 = (s[35] << 15) | (s[34] >>> 17);
b18 = (s[45] << 29) | (s[44] >>> 3);
b19 = (s[44] << 29) | (s[45] >>> 3);
b10 = (s[6] << 28) | (s[7] >>> 4);
b11 = (s[7] << 28) | (s[6] >>> 4);
b42 = (s[17] << 23) | (s[16] >>> 9);
b43 = (s[16] << 23) | (s[17] >>> 9);
b24 = (s[26] << 25) | (s[27] >>> 7);
b25 = (s[27] << 25) | (s[26] >>> 7);
b6 = (s[36] << 21) | (s[37] >>> 11);
b7 = (s[37] << 21) | (s[36] >>> 11);
b38 = (s[47] << 24) | (s[46] >>> 8);
b39 = (s[46] << 24) | (s[47] >>> 8);
b30 = (s[8] << 27) | (s[9] >>> 5);
b31 = (s[9] << 27) | (s[8] >>> 5);
b12 = (s[18] << 20) | (s[19] >>> 12);
b13 = (s[19] << 20) | (s[18] >>> 12);
b44 = (s[29] << 7) | (s[28] >>> 25);
b45 = (s[28] << 7) | (s[29] >>> 25);
b26 = (s[38] << 8) | (s[39] >>> 24);
b27 = (s[39] << 8) | (s[38] >>> 24);
b8 = (s[48] << 14) | (s[49] >>> 18);
b9 = (s[49] << 14) | (s[48] >>> 18);
s[0] = b0 ^ (~b2 & b4);
s[1] = b1 ^ (~b3 & b5);
s[10] = b10 ^ (~b12 & b14);
s[11] = b11 ^ (~b13 & b15);
s[20] = b20 ^ (~b22 & b24);
s[21] = b21 ^ (~b23 & b25);
s[30] = b30 ^ (~b32 & b34);
s[31] = b31 ^ (~b33 & b35);
s[40] = b40 ^ (~b42 & b44);
s[41] = b41 ^ (~b43 & b45);
s[2] = b2 ^ (~b4 & b6);
s[3] = b3 ^ (~b5 & b7);
s[12] = b12 ^ (~b14 & b16);
s[13] = b13 ^ (~b15 & b17);
s[22] = b22 ^ (~b24 & b26);
s[23] = b23 ^ (~b25 & b27);
s[32] = b32 ^ (~b34 & b36);
s[33] = b33 ^ (~b35 & b37);
s[42] = b42 ^ (~b44 & b46);
s[43] = b43 ^ (~b45 & b47);
s[4] = b4 ^ (~b6 & b8);
s[5] = b5 ^ (~b7 & b9);
s[14] = b14 ^ (~b16 & b18);
s[15] = b15 ^ (~b17 & b19);
s[24] = b24 ^ (~b26 & b28);
s[25] = b25 ^ (~b27 & b29);
s[34] = b34 ^ (~b36 & b38);
s[35] = b35 ^ (~b37 & b39);
s[44] = b44 ^ (~b46 & b48);
s[45] = b45 ^ (~b47 & b49);
s[6] = b6 ^ (~b8 & b0);
s[7] = b7 ^ (~b9 & b1);
s[16] = b16 ^ (~b18 & b10);
s[17] = b17 ^ (~b19 & b11);
s[26] = b26 ^ (~b28 & b20);
s[27] = b27 ^ (~b29 & b21);
s[36] = b36 ^ (~b38 & b30);
s[37] = b37 ^ (~b39 & b31);
s[46] = b46 ^ (~b48 & b40);
s[47] = b47 ^ (~b49 & b41);
s[8] = b8 ^ (~b0 & b2);
s[9] = b9 ^ (~b1 & b3);
s[18] = b18 ^ (~b10 & b12);
s[19] = b19 ^ (~b11 & b13);
s[28] = b28 ^ (~b20 & b22);
s[29] = b29 ^ (~b21 & b23);
s[38] = b38 ^ (~b30 & b32);
s[39] = b39 ^ (~b31 & b33);
s[48] = b48 ^ (~b40 & b42);
s[49] = b49 ^ (~b41 & b43);
s[0] ^= RC[n];
s[1] ^= RC[n + 1];
}
};
if (COMMON_JS) {
module.exports = methods;
} else {
for (i = 0; i < methodNames.length; ++i) {
root[methodNames[i]] = methods[methodNames[i]];
}
if (AMD) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return methods;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
}
})();
/***/ }),
/* 30 */
/***/ (function(module, exports) {
module.exports = require("module");
/***/ }),
/* 31 */,
/* 32 */,
/* 33 */,
/* 34 */,
/* 35 */
/***/ (function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(this, {}))
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
try {
var util = __webpack_require__(37);
/* istanbul ignore next */
if (typeof util.inherits !== 'function') throw '';
module.exports = util.inherits;
} catch (e) {
/* istanbul ignore next */
module.exports = __webpack_require__(38);
}
/***/ }),
/* 37 */
/***/ (function(module, exports) {
module.exports = require("util");
/***/ }),
/* 38 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.sha1 = __webpack_require__(40);
exports.sha224 = __webpack_require__(41);
exports.sha256 = __webpack_require__(26);
exports.sha384 = __webpack_require__(42);
exports.sha512 = __webpack_require__(27);
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var common = __webpack_require__(12);
var shaCommon = __webpack_require__(25);
var rotl32 = utils.rotl32;
var sum32 = utils.sum32;
var sum32_5 = utils.sum32_5;
var ft_1 = shaCommon.ft_1;
var BlockHash = common.BlockHash;
var sha1_K = [
0x5A827999, 0x6ED9EBA1,
0x8F1BBCDC, 0xCA62C1D6
];
function SHA1() {
if (!(this instanceof SHA1))
return new SHA1();
BlockHash.call(this);
this.h = [
0x67452301, 0xefcdab89, 0x98badcfe,
0x10325476, 0xc3d2e1f0 ];
this.W = new Array(80);
}
utils.inherits(SHA1, BlockHash);
module.exports = SHA1;
SHA1.blockSize = 512;
SHA1.outSize = 160;
SHA1.hmacStrength = 80;
SHA1.padLength = 64;
SHA1.prototype._update = function _update(msg, start) {
var W = this.W;
for (var i = 0; i < 16; i++)
W[i] = msg[start + i];
for(; i < W.length; i++)
W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
var a = this.h[0];
var b = this.h[1];
var c = this.h[2];
var d = this.h[3];
var e = this.h[4];
for (i = 0; i < W.length; i++) {
var s = ~~(i / 20);
var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
e = d;
d = c;
c = rotl32(b, 30);
b = a;
a = t;
}
this.h[0] = sum32(this.h[0], a);
this.h[1] = sum32(this.h[1], b);
this.h[2] = sum32(this.h[2], c);
this.h[3] = sum32(this.h[3], d);
this.h[4] = sum32(this.h[4], e);
};
SHA1.prototype._digest = function digest(enc) {
if (enc === 'hex')
return utils.toHex32(this.h, 'big');
else
return utils.split32(this.h, 'big');
};
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var SHA256 = __webpack_require__(26);
function SHA224() {
if (!(this instanceof SHA224))
return new SHA224();
SHA256.call(this);
this.h = [
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
}
utils.inherits(SHA224, SHA256);
module.exports = SHA224;
SHA224.blockSize = 512;
SHA224.outSize = 224;
SHA224.hmacStrength = 192;
SHA224.padLength = 64;
SHA224.prototype._digest = function digest(enc) {
// Just truncate output
if (enc === 'hex')
return utils.toHex32(this.h.slice(0, 7), 'big');
else
return utils.split32(this.h.slice(0, 7), 'big');
};
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var SHA512 = __webpack_require__(27);
function SHA384() {
if (!(this instanceof SHA384))
return new SHA384();
SHA512.call(this);
this.h = [
0xcbbb9d5d, 0xc1059ed8,
0x629a292a, 0x367cd507,
0x9159015a, 0x3070dd17,
0x152fecd8, 0xf70e5939,
0x67332667, 0xffc00b31,
0x8eb44a87, 0x68581511,
0xdb0c2e0d, 0x64f98fa7,
0x47b5481d, 0xbefa4fa4 ];
}
utils.inherits(SHA384, SHA512);
module.exports = SHA384;
SHA384.blockSize = 1024;
SHA384.outSize = 384;
SHA384.hmacStrength = 192;
SHA384.padLength = 128;
SHA384.prototype._digest = function digest(enc) {
if (enc === 'hex')
return utils.toHex32(this.h.slice(0, 12), 'big');
else
return utils.split32(this.h.slice(0, 12), 'big');
};
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var common = __webpack_require__(12);
var rotl32 = utils.rotl32;
var sum32 = utils.sum32;
var sum32_3 = utils.sum32_3;
var sum32_4 = utils.sum32_4;
var BlockHash = common.BlockHash;
function RIPEMD160() {
if (!(this instanceof RIPEMD160))
return new RIPEMD160();
BlockHash.call(this);
this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
this.endian = 'little';
}
utils.inherits(RIPEMD160, BlockHash);
exports.ripemd160 = RIPEMD160;
RIPEMD160.blockSize = 512;
RIPEMD160.outSize = 160;
RIPEMD160.hmacStrength = 192;
RIPEMD160.padLength = 64;
RIPEMD160.prototype._update = function update(msg, start) {
var A = this.h[0];
var B = this.h[1];
var C = this.h[2];
var D = this.h[3];
var E = this.h[4];
var Ah = A;
var Bh = B;
var Ch = C;
var Dh = D;
var Eh = E;
for (var j = 0; j < 80; j++) {
var T = sum32(
rotl32(
sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
s[j]),
E);
A = E;
E = D;
D = rotl32(C, 10);
C = B;
B = T;
T = sum32(
rotl32(
sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
sh[j]),
Eh);
Ah = Eh;
Eh = Dh;
Dh = rotl32(Ch, 10);
Ch = Bh;
Bh = T;
}
T = sum32_3(this.h[1], C, Dh);
this.h[1] = sum32_3(this.h[2], D, Eh);
this.h[2] = sum32_3(this.h[3], E, Ah);
this.h[3] = sum32_3(this.h[4], A, Bh);
this.h[4] = sum32_3(this.h[0], B, Ch);
this.h[0] = T;
};
RIPEMD160.prototype._digest = function digest(enc) {
if (enc === 'hex')
return utils.toHex32(this.h, 'little');
else
return utils.split32(this.h, 'little');
};
function f(j, x, y, z) {
if (j <= 15)
return x ^ y ^ z;
else if (j <= 31)
return (x & y) | ((~x) & z);
else if (j <= 47)
return (x | (~y)) ^ z;
else if (j <= 63)
return (x & z) | (y & (~z));
else
return x ^ (y | (~z));
}
function K(j) {
if (j <= 15)
return 0x00000000;
else if (j <= 31)
return 0x5a827999;
else if (j <= 47)
return 0x6ed9eba1;
else if (j <= 63)
return 0x8f1bbcdc;
else
return 0xa953fd4e;
}
function Kh(j) {
if (j <= 15)
return 0x50a28be6;
else if (j <= 31)
return 0x5c4dd124;
else if (j <= 47)
return 0x6d703ef3;
else if (j <= 63)
return 0x7a6d76e9;
else
return 0x00000000;
}
var r = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
];
var rh = [
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
];
var s = [
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
];
var sh = [
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
];
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(6);
var assert = __webpack_require__(11);
function Hmac(hash, key, enc) {
if (!(this instanceof Hmac))
return new Hmac(hash, key, enc);
this.Hash = hash;
this.blockSize = hash.blockSize / 8;
this.outSize = hash.outSize / 8;
this.inner = null;
this.outer = null;
this._init(utils.toArray(key, enc));
}
module.exports = Hmac;
Hmac.prototype._init = function init(key) {
// Shorten key, if needed
if (key.length > this.blockSize)
key = new this.Hash().update(key).digest();
assert(key.length <= this.blockSize);
// Add padding to key
for (var i = key.length; i < this.blockSize; i++)
key.push(0);
for (i = 0; i < key.length; i++)
key[i] ^= 0x36;
this.inner = new this.Hash().update(key);
// 0x36 ^ 0x5c = 0x6a
for (i = 0; i < key.length; i++)
key[i] ^= 0x6a;
this.outer = new this.Hash().update(key);
};
Hmac.prototype.update = function update(msg, enc) {
this.inner.update(msg, enc);
return this;
};
Hmac.prototype.digest = function digest(enc) {
this.outer.update(this.inner.digest());
return this.outer.digest(enc);
};
/***/ }),
/* 45 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// NAMESPACE OBJECT: ./node_modules/@ethersproject/rlp/lib.esm/index.js
var rlp_lib_esm_namespaceObject = {};
__webpack_require__.r(rlp_lib_esm_namespaceObject);
__webpack_require__.d(rlp_lib_esm_namespaceObject, "encode", function() { return lib_esm_encode; });
__webpack_require__.d(rlp_lib_esm_namespaceObject, "decode", function() { return lib_esm_decode; });
// NAMESPACE OBJECT: ./node_modules/@ethersproject/providers/lib.esm/index.js
var providers_lib_esm_namespaceObject = {};
__webpack_require__.r(providers_lib_esm_namespaceObject);
__webpack_require__.d(providers_lib_esm_namespaceObject, "Provider", function() { return lib_esm_Provider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "BaseProvider", function() { return base_provider_BaseProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "Resolver", function() { return base_provider_Resolver; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "UrlJsonRpcProvider", function() { return url_json_rpc_provider_UrlJsonRpcProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "FallbackProvider", function() { return fallback_provider_FallbackProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "AlchemyProvider", function() { return alchemy_provider_AlchemyProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "AlchemyWebSocketProvider", function() { return alchemy_provider_AlchemyWebSocketProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "AnkrProvider", function() { return ankr_provider_AnkrProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "CloudflareProvider", function() { return cloudflare_provider_CloudflareProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "EtherscanProvider", function() { return etherscan_provider_EtherscanProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "InfuraProvider", function() { return infura_provider_InfuraProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "InfuraWebSocketProvider", function() { return infura_provider_InfuraWebSocketProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "JsonRpcProvider", function() { return json_rpc_provider_JsonRpcProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "JsonRpcBatchProvider", function() { return json_rpc_batch_provider_JsonRpcBatchProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "NodesmithProvider", function() { return nodesmith_provider_NodesmithProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "PocketProvider", function() { return pocket_provider_PocketProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "StaticJsonRpcProvider", function() { return url_json_rpc_provider_StaticJsonRpcProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "Web3Provider", function() { return web3_provider_Web3Provider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "WebSocketProvider", function() { return websocket_provider_WebSocketProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "IpcProvider", function() { return IpcProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "JsonRpcSigner", function() { return json_rpc_provider_JsonRpcSigner; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "getDefaultProvider", function() { return getDefaultProvider; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "getNetwork", function() { return lib_esm_getNetwork; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "isCommunityResource", function() { return isCommunityResource; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "isCommunityResourcable", function() { return isCommunityResourcable; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "showThrottleMessage", function() { return showThrottleMessage; });
__webpack_require__.d(providers_lib_esm_namespaceObject, "Formatter", function() { return formatter_Formatter; });
// NAMESPACE OBJECT: ./node_modules/@ethersproject/base64/lib.esm/index.js
var base64_lib_esm_namespaceObject = {};
__webpack_require__.r(base64_lib_esm_namespaceObject);
__webpack_require__.d(base64_lib_esm_namespaceObject, "decode", function() { return decode; });
__webpack_require__.d(base64_lib_esm_namespaceObject, "encode", function() { return encode; });
// NAMESPACE OBJECT: ./node_modules/ethers/lib.esm/utils.js
var lib_esm_utils_namespaceObject = {};
__webpack_require__.r(lib_esm_utils_namespaceObject);
__webpack_require__.d(lib_esm_utils_namespaceObject, "AbiCoder", function() { return abi_coder_AbiCoder; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "defaultAbiCoder", function() { return defaultAbiCoder; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "Fragment", function() { return fragments_Fragment; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "ConstructorFragment", function() { return fragments_ConstructorFragment; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "ErrorFragment", function() { return ErrorFragment; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "EventFragment", function() { return EventFragment; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "FunctionFragment", function() { return fragments_FunctionFragment; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "ParamType", function() { return fragments_ParamType; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "FormatTypes", function() { return FormatTypes; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "checkResultErrors", function() { return checkResultErrors; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "Logger", function() { return lib_esm_Logger; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "RLP", function() { return rlp_lib_esm_namespaceObject; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "_fetchData", function() { return _fetchData; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "fetchJson", function() { return fetchJson; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "poll", function() { return lib_esm_poll; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "checkProperties", function() { return checkProperties; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "deepCopy", function() { return deepCopy; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "defineReadOnly", function() { return defineReadOnly; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "getStatic", function() { return getStatic; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "resolveProperties", function() { return resolveProperties; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "shallowCopy", function() { return shallowCopy; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "arrayify", function() { return arrayify; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "concat", function() { return concat; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "stripZeros", function() { return stripZeros; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "zeroPad", function() { return zeroPad; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "isBytes", function() { return isBytes; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "isBytesLike", function() { return isBytesLike; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "defaultPath", function() { return defaultPath; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "HDNode", function() { return lib_esm_HDNode; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "SigningKey", function() { return lib_esm_SigningKey; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "Interface", function() { return interface_Interface; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "LogDescription", function() { return interface_LogDescription; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "TransactionDescription", function() { return interface_TransactionDescription; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "base58", function() { return Base58; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "base64", function() { return base64_lib_esm_namespaceObject; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "hexlify", function() { return hexlify; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "isHexString", function() { return isHexString; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "hexConcat", function() { return hexConcat; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "hexStripZeros", function() { return hexStripZeros; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "hexValue", function() { return hexValue; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "hexZeroPad", function() { return hexZeroPad; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "hexDataLength", function() { return hexDataLength; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "hexDataSlice", function() { return hexDataSlice; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "nameprep", function() { return nameprep; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "_toEscapedUtf8String", function() { return _toEscapedUtf8String; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "toUtf8Bytes", function() { return toUtf8Bytes; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "toUtf8CodePoints", function() { return toUtf8CodePoints; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "toUtf8String", function() { return toUtf8String; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "Utf8ErrorFuncs", function() { return Utf8ErrorFuncs; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "formatBytes32String", function() { return formatBytes32String; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "parseBytes32String", function() { return parseBytes32String; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "dnsEncode", function() { return dnsEncode; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "hashMessage", function() { return hashMessage; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "namehash", function() { return namehash; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "isValidName", function() { return isValidName; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "id", function() { return id_id; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "_TypedDataEncoder", function() { return typed_data_TypedDataEncoder; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "getAddress", function() { return getAddress; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "getIcapAddress", function() { return getIcapAddress; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "getContractAddress", function() { return getContractAddress; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "getCreate2Address", function() { return getCreate2Address; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "isAddress", function() { return isAddress; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "formatEther", function() { return formatEther; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "parseEther", function() { return parseEther; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "formatUnits", function() { return formatUnits; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "parseUnits", function() { return parseUnits; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "commify", function() { return commify; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "computeHmac", function() { return computeHmac; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "keccak256", function() { return keccak256; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "ripemd160", function() { return ripemd160; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "sha256", function() { return sha256; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "sha512", function() { return sha512; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "randomBytes", function() { return random_randomBytes; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "shuffled", function() { return shuffled; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "solidityPack", function() { return lib_esm_pack; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "solidityKeccak256", function() { return lib_esm_keccak256; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "soliditySha256", function() { return lib_esm_sha256; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "splitSignature", function() { return splitSignature; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "joinSignature", function() { return joinSignature; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "accessListify", function() { return accessListify; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "parseTransaction", function() { return parse; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "serializeTransaction", function() { return lib_esm_serialize; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "TransactionTypes", function() { return TransactionTypes; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "getJsonWalletAddress", function() { return getJsonWalletAddress; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "computeAddress", function() { return computeAddress; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "recoverAddress", function() { return recoverAddress; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "computePublicKey", function() { return computePublicKey; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "recoverPublicKey", function() { return recoverPublicKey; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "verifyMessage", function() { return verifyMessage; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "verifyTypedData", function() { return verifyTypedData; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "getAccountPath", function() { return getAccountPath; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "mnemonicToEntropy", function() { return mnemonicToEntropy; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "entropyToMnemonic", function() { return entropyToMnemonic; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "isValidMnemonic", function() { return isValidMnemonic; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "mnemonicToSeed", function() { return mnemonicToSeed; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "SupportedAlgorithm", function() { return SupportedAlgorithm; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "UnicodeNormalizationForm", function() { return UnicodeNormalizationForm; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "Utf8ErrorReason", function() { return Utf8ErrorReason; });
__webpack_require__.d(lib_esm_utils_namespaceObject, "Indexed", function() { return interface_Indexed; });
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(19);
var external_path_default = /*#__PURE__*/__webpack_require__.n(external_path_);
// EXTERNAL MODULE: external "fs/promises"
var promises_ = __webpack_require__(13);
// EXTERNAL MODULE: ./node_modules/@ethersproject/bignumber/node_modules/bn.js/lib/bn.js
var bn = __webpack_require__(28);
var bn_default = /*#__PURE__*/__webpack_require__.n(bn);
// CONCATENATED MODULE: ./node_modules/@ethersproject/logger/lib.esm/_version.js
const _version_version = "logger/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/logger/lib.esm/index.js
let _permanentCensorErrors = false;
let _censorErrors = false;
const LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 };
let _logLevel = LogLevels["default"];
let _globalLogger = null;
function _checkNormalize() {
try {
const missing = [];
// Make sure all forms of normalization are supported
["NFD", "NFC", "NFKD", "NFKC"].forEach((form) => {
try {
if ("test".normalize(form) !== "test") {
throw new Error("bad normalize");
}
;
}
catch (error) {
missing.push(form);
}
});
if (missing.length) {
throw new Error("missing " + missing.join(", "));
}
if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) {
throw new Error("broken implementation");
}
}
catch (error) {
return error.message;
}
return null;
}
const _normalizeError = _checkNormalize();
var LogLevel;
(function (LogLevel) {
LogLevel["DEBUG"] = "DEBUG";
LogLevel["INFO"] = "INFO";
LogLevel["WARNING"] = "WARNING";
LogLevel["ERROR"] = "ERROR";
LogLevel["OFF"] = "OFF";
})(LogLevel || (LogLevel = {}));
var ErrorCode;
(function (ErrorCode) {
///////////////////
// Generic Errors
// Unknown Error
ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
// Not Implemented
ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED";
// Unsupported Operation
// - operation
ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION";
// Network Error (i.e. Ethereum Network, such as an invalid chain ID)
// - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown)
ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
// Some sort of bad response from the server
ErrorCode["SERVER_ERROR"] = "SERVER_ERROR";
// Timeout
ErrorCode["TIMEOUT"] = "TIMEOUT";
///////////////////
// Operational Errors
// Buffer Overrun
ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN";
// Numeric Fault
// - operation: the operation being executed
// - fault: the reason this faulted
ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT";
///////////////////
// Argument Errors
// Missing new operator to an object
// - name: The name of the class
ErrorCode["MISSING_NEW"] = "MISSING_NEW";
// Invalid argument (e.g. value is incompatible with type) to a function:
// - argument: The argument name that was invalid
// - value: The value of the argument
ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT";
// Missing argument to a function:
// - count: The number of arguments received
// - expectedCount: The number of arguments expected
ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT";
// Too many arguments
// - count: The number of arguments received
// - expectedCount: The number of arguments expected
ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT";
///////////////////
// Blockchain Errors
// Call exception
// - transaction: the transaction
// - address?: the contract address
// - args?: The arguments passed into the function
// - method?: The Solidity method signature
// - errorSignature?: The EIP848 error signature
// - errorArgs?: The EIP848 error parameters
// - reason: The reason (only for EIP848 "Error(string)")
ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION";
// Insufficient funds (< value + gasLimit * gasPrice)
// - transaction: the transaction attempted
ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
// Nonce has already been used
// - transaction: the transaction attempted
ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED";
// The replacement fee for the transaction is too low
// - transaction: the transaction attempted
ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED";
// The gas limit could not be estimated
// - transaction: the transaction passed to estimateGas
ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT";
// The transaction was replaced by one with a higher gas price
// - reason: "cancelled", "replaced" or "repriced"
// - cancelled: true if reason == "cancelled" or reason == "replaced")
// - hash: original transaction hash
// - replacement: the full TransactionsResponse for the replacement
// - receipt: the receipt of the replacement
ErrorCode["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED";
///////////////////
// Interaction Errors
// The user rejected the action, such as signing a message or sending
// a transaction
ErrorCode["ACTION_REJECTED"] = "ACTION_REJECTED";
})(ErrorCode || (ErrorCode = {}));
;
const HEX = "0123456789abcdef";
class lib_esm_Logger {
constructor(version) {
Object.defineProperty(this, "version", {
enumerable: true,
value: version,
writable: false
});
}
_log(logLevel, args) {
const level = logLevel.toLowerCase();
if (LogLevels[level] == null) {
this.throwArgumentError("invalid log level name", "logLevel", logLevel);
}
if (_logLevel > LogLevels[level]) {
return;
}
console.log.apply(console, args);
}
debug(...args) {
this._log(lib_esm_Logger.levels.DEBUG, args);
}
info(...args) {
this._log(lib_esm_Logger.levels.INFO, args);
}
warn(...args) {
this._log(lib_esm_Logger.levels.WARNING, args);
}
makeError(message, code, params) {
// Errors are being censored
if (_censorErrors) {
return this.makeError("censored error", code, {});
}
if (!code) {
code = lib_esm_Logger.errors.UNKNOWN_ERROR;
}
if (!params) {
params = {};
}
const messageDetails = [];
Object.keys(params).forEach((key) => {
const value = params[key];
try {
if (value instanceof Uint8Array) {
let hex = "";
for (let i = 0; i < value.length; i++) {
hex += HEX[value[i] >> 4];
hex += HEX[value[i] & 0x0f];
}
messageDetails.push(key + "=Uint8Array(0x" + hex + ")");
}
else {
messageDetails.push(key + "=" + JSON.stringify(value));
}
}
catch (error) {
messageDetails.push(key + "=" + JSON.stringify(params[key].toString()));
}
});
messageDetails.push(`code=${code}`);
messageDetails.push(`version=${this.version}`);
const reason = message;
let url = "";
switch (code) {
case ErrorCode.NUMERIC_FAULT: {
url = "NUMERIC_FAULT";
const fault = message;
switch (fault) {
case "overflow":
case "underflow":
case "division-by-zero":
url += "-" + fault;
break;
case "negative-power":
case "negative-width":
url += "-unsupported";
break;
case "unbound-bitwise-result":
url += "-unbound-result";
break;
}
break;
}
case ErrorCode.CALL_EXCEPTION:
case ErrorCode.INSUFFICIENT_FUNDS:
case ErrorCode.MISSING_NEW:
case ErrorCode.NONCE_EXPIRED:
case ErrorCode.REPLACEMENT_UNDERPRICED:
case ErrorCode.TRANSACTION_REPLACED:
case ErrorCode.UNPREDICTABLE_GAS_LIMIT:
url = code;
break;
}
if (url) {
message += " [ See: https:/\/links.ethers.org/v5-errors-" + url + " ]";
}
if (messageDetails.length) {
message += " (" + messageDetails.join(", ") + ")";
}
// @TODO: Any??
const error = new Error(message);
error.reason = reason;
error.code = code;
Object.keys(params).forEach(function (key) {
error[key] = params[key];
});
return error;
}
throwError(message, code, params) {
throw this.makeError(message, code, params);
}
throwArgumentError(message, name, value) {
return this.throwError(message, lib_esm_Logger.errors.INVALID_ARGUMENT, {
argument: name,
value: value
});
}
assert(condition, message, code, params) {
if (!!condition) {
return;
}
this.throwError(message, code, params);
}
assertArgument(condition, message, name, value) {
if (!!condition) {
return;
}
this.throwArgumentError(message, name, value);
}
checkNormalize(message) {
if (message == null) {
message = "platform missing String.prototype.normalize";
}
if (_normalizeError) {
this.throwError("platform missing String.prototype.normalize", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "String.prototype.normalize", form: _normalizeError
});
}
}
checkSafeUint53(value, message) {
if (typeof (value) !== "number") {
return;
}
if (message == null) {
message = "value not safe";
}
if (value < 0 || value >= 0x1fffffffffffff) {
this.throwError(message, lib_esm_Logger.errors.NUMERIC_FAULT, {
operation: "checkSafeInteger",
fault: "out-of-safe-range",
value: value
});
}
if (value % 1) {
this.throwError(message, lib_esm_Logger.errors.NUMERIC_FAULT, {
operation: "checkSafeInteger",
fault: "non-integer",
value: value
});
}
}
checkArgumentCount(count, expectedCount, message) {
if (message) {
message = ": " + message;
}
else {
message = "";
}
if (count < expectedCount) {
this.throwError("missing argument" + message, lib_esm_Logger.errors.MISSING_ARGUMENT, {
count: count,
expectedCount: expectedCount
});
}
if (count > expectedCount) {
this.throwError("too many arguments" + message, lib_esm_Logger.errors.UNEXPECTED_ARGUMENT, {
count: count,
expectedCount: expectedCount
});
}
}
checkNew(target, kind) {
if (target === Object || target == null) {
this.throwError("missing new", lib_esm_Logger.errors.MISSING_NEW, { name: kind.name });
}
}
checkAbstract(target, kind) {
if (target === kind) {
this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" });
}
else if (target === Object || target == null) {
this.throwError("missing new", lib_esm_Logger.errors.MISSING_NEW, { name: kind.name });
}
}
static globalLogger() {
if (!_globalLogger) {
_globalLogger = new lib_esm_Logger(_version_version);
}
return _globalLogger;
}
static setCensorship(censorship, permanent) {
if (!censorship && permanent) {
this.globalLogger().throwError("cannot permanently disable censorship", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "setCensorship"
});
}
if (_permanentCensorErrors) {
if (!censorship) {
return;
}
this.globalLogger().throwError("error censorship permanent", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "setCensorship"
});
}
_censorErrors = !!censorship;
_permanentCensorErrors = !!permanent;
}
static setLogLevel(logLevel) {
const level = LogLevels[logLevel.toLowerCase()];
if (level == null) {
lib_esm_Logger.globalLogger().warn("invalid log level - " + logLevel);
return;
}
_logLevel = level;
}
static from(version) {
return new lib_esm_Logger(version);
}
}
lib_esm_Logger.errors = ErrorCode;
lib_esm_Logger.levels = LogLevel;
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/bytes/lib.esm/_version.js
const lib_esm_version_version = "bytes/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/bytes/lib.esm/index.js
const lib_esm_logger = new lib_esm_Logger(lib_esm_version_version);
///////////////////////////////
function isHexable(value) {
return !!(value.toHexString);
}
function addSlice(array) {
if (array.slice) {
return array;
}
array.slice = function () {
const args = Array.prototype.slice.call(arguments);
return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));
};
return array;
}
function isBytesLike(value) {
return ((isHexString(value) && !(value.length % 2)) || isBytes(value));
}
function isInteger(value) {
return (typeof (value) === "number" && value == value && (value % 1) === 0);
}
function isBytes(value) {
if (value == null) {
return false;
}
if (value.constructor === Uint8Array) {
return true;
}
if (typeof (value) === "string") {
return false;
}
if (!isInteger(value.length) || value.length < 0) {
return false;
}
for (let i = 0; i < value.length; i++) {
const v = value[i];
if (!isInteger(v) || v < 0 || v >= 256) {
return false;
}
}
return true;
}
function arrayify(value, options) {
if (!options) {
options = {};
}
if (typeof (value) === "number") {
lib_esm_logger.checkSafeUint53(value, "invalid arrayify value");
const result = [];
while (value) {
result.unshift(value & 0xff);
value = parseInt(String(value / 256));
}
if (result.length === 0) {
result.push(0);
}
return addSlice(new Uint8Array(result));
}
if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
value = "0x" + value;
}
if (isHexable(value)) {
value = value.toHexString();
}
if (isHexString(value)) {
let hex = value.substring(2);
if (hex.length % 2) {
if (options.hexPad === "left") {
hex = "0" + hex;
}
else if (options.hexPad === "right") {
hex += "0";
}
else {
lib_esm_logger.throwArgumentError("hex data is odd-length", "value", value);
}
}
const result = [];
for (let i = 0; i < hex.length; i += 2) {
result.push(parseInt(hex.substring(i, i + 2), 16));
}
return addSlice(new Uint8Array(result));
}
if (isBytes(value)) {
return addSlice(new Uint8Array(value));
}
return lib_esm_logger.throwArgumentError("invalid arrayify value", "value", value);
}
function concat(items) {
const objects = items.map(item => arrayify(item));
const length = objects.reduce((accum, item) => (accum + item.length), 0);
const result = new Uint8Array(length);
objects.reduce((offset, object) => {
result.set(object, offset);
return offset + object.length;
}, 0);
return addSlice(result);
}
function stripZeros(value) {
let result = arrayify(value);
if (result.length === 0) {
return result;
}
// Find the first non-zero entry
let start = 0;
while (start < result.length && result[start] === 0) {
start++;
}
// If we started with zeros, strip them
if (start) {
result = result.slice(start);
}
return result;
}
function zeroPad(value, length) {
value = arrayify(value);
if (value.length > length) {
lib_esm_logger.throwArgumentError("value out of range", "value", arguments[0]);
}
const result = new Uint8Array(length);
result.set(value, length - value.length);
return addSlice(result);
}
function isHexString(value, length) {
if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
return false;
}
if (length && value.length !== 2 + 2 * length) {
return false;
}
return true;
}
const HexCharacters = "0123456789abcdef";
function hexlify(value, options) {
if (!options) {
options = {};
}
if (typeof (value) === "number") {
lib_esm_logger.checkSafeUint53(value, "invalid hexlify value");
let hex = "";
while (value) {
hex = HexCharacters[value & 0xf] + hex;
value = Math.floor(value / 16);
}
if (hex.length) {
if (hex.length % 2) {
hex = "0" + hex;
}
return "0x" + hex;
}
return "0x00";
}
if (typeof (value) === "bigint") {
value = value.toString(16);
if (value.length % 2) {
return ("0x0" + value);
}
return "0x" + value;
}
if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
value = "0x" + value;
}
if (isHexable(value)) {
return value.toHexString();
}
if (isHexString(value)) {
if (value.length % 2) {
if (options.hexPad === "left") {
value = "0x0" + value.substring(2);
}
else if (options.hexPad === "right") {
value += "0";
}
else {
lib_esm_logger.throwArgumentError("hex data is odd-length", "value", value);
}
}
return value.toLowerCase();
}
if (isBytes(value)) {
let result = "0x";
for (let i = 0; i < value.length; i++) {
let v = value[i];
result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];
}
return result;
}
return lib_esm_logger.throwArgumentError("invalid hexlify value", "value", value);
}
/*
function unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {
if (typeof(value) === "string" && value.length % 2 && value.substring(0, 2) === "0x") {
return "0x0" + value.substring(2);
}
return value;
}
*/
function hexDataLength(data) {
if (typeof (data) !== "string") {
data = hexlify(data);
}
else if (!isHexString(data) || (data.length % 2)) {
return null;
}
return (data.length - 2) / 2;
}
function hexDataSlice(data, offset, endOffset) {
if (typeof (data) !== "string") {
data = hexlify(data);
}
else if (!isHexString(data) || (data.length % 2)) {
lib_esm_logger.throwArgumentError("invalid hexData", "value", data);
}
offset = 2 + 2 * offset;
if (endOffset != null) {
return "0x" + data.substring(offset, 2 + 2 * endOffset);
}
return "0x" + data.substring(offset);
}
function hexConcat(items) {
let result = "0x";
items.forEach((item) => {
result += hexlify(item).substring(2);
});
return result;
}
function hexValue(value) {
const trimmed = hexStripZeros(hexlify(value, { hexPad: "left" }));
if (trimmed === "0x") {
return "0x0";
}
return trimmed;
}
function hexStripZeros(value) {
if (typeof (value) !== "string") {
value = hexlify(value);
}
if (!isHexString(value)) {
lib_esm_logger.throwArgumentError("invalid hex string", "value", value);
}
value = value.substring(2);
let offset = 0;
while (offset < value.length && value[offset] === "0") {
offset++;
}
return "0x" + value.substring(offset);
}
function hexZeroPad(value, length) {
if (typeof (value) !== "string") {
value = hexlify(value);
}
else if (!isHexString(value)) {
lib_esm_logger.throwArgumentError("invalid hex string", "value", value);
}
if (value.length > 2 * length + 2) {
lib_esm_logger.throwArgumentError("value out of range", "value", arguments[1]);
}
while (value.length < 2 * length + 2) {
value = "0x0" + value.substring(2);
}
return value;
}
function splitSignature(signature) {
const result = {
r: "0x",
s: "0x",
_vs: "0x",
recoveryParam: 0,
v: 0,
yParityAndS: "0x",
compact: "0x"
};
if (isBytesLike(signature)) {
let bytes = arrayify(signature);
// Get the r, s and v
if (bytes.length === 64) {
// EIP-2098; pull the v from the top bit of s and clear it
result.v = 27 + (bytes[32] >> 7);
bytes[32] &= 0x7f;
result.r = hexlify(bytes.slice(0, 32));
result.s = hexlify(bytes.slice(32, 64));
}
else if (bytes.length === 65) {
result.r = hexlify(bytes.slice(0, 32));
result.s = hexlify(bytes.slice(32, 64));
result.v = bytes[64];
}
else {
lib_esm_logger.throwArgumentError("invalid signature string", "signature", signature);
}
// Allow a recid to be used as the v
if (result.v < 27) {
if (result.v === 0 || result.v === 1) {
result.v += 27;
}
else {
lib_esm_logger.throwArgumentError("signature invalid v byte", "signature", signature);
}
}
// Compute recoveryParam from v
result.recoveryParam = 1 - (result.v % 2);
// Compute _vs from recoveryParam and s
if (result.recoveryParam) {
bytes[32] |= 0x80;
}
result._vs = hexlify(bytes.slice(32, 64));
}
else {
result.r = signature.r;
result.s = signature.s;
result.v = signature.v;
result.recoveryParam = signature.recoveryParam;
result._vs = signature._vs;
// If the _vs is available, use it to populate missing s, v and recoveryParam
// and verify non-missing s, v and recoveryParam
if (result._vs != null) {
const vs = zeroPad(arrayify(result._vs), 32);
result._vs = hexlify(vs);
// Set or check the recid
const recoveryParam = ((vs[0] >= 128) ? 1 : 0);
if (result.recoveryParam == null) {
result.recoveryParam = recoveryParam;
}
else if (result.recoveryParam !== recoveryParam) {
lib_esm_logger.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature);
}
// Set or check the s
vs[0] &= 0x7f;
const s = hexlify(vs);
if (result.s == null) {
result.s = s;
}
else if (result.s !== s) {
lib_esm_logger.throwArgumentError("signature v mismatch _vs", "signature", signature);
}
}
// Use recid and v to populate each other
if (result.recoveryParam == null) {
if (result.v == null) {
lib_esm_logger.throwArgumentError("signature missing v and recoveryParam", "signature", signature);
}
else if (result.v === 0 || result.v === 1) {
result.recoveryParam = result.v;
}
else {
result.recoveryParam = 1 - (result.v % 2);
}
}
else {
if (result.v == null) {
result.v = 27 + result.recoveryParam;
}
else {
const recId = (result.v === 0 || result.v === 1) ? result.v : (1 - (result.v % 2));
if (result.recoveryParam !== recId) {
lib_esm_logger.throwArgumentError("signature recoveryParam mismatch v", "signature", signature);
}
}
}
if (result.r == null || !isHexString(result.r)) {
lib_esm_logger.throwArgumentError("signature missing or invalid r", "signature", signature);
}
else {
result.r = hexZeroPad(result.r, 32);
}
if (result.s == null || !isHexString(result.s)) {
lib_esm_logger.throwArgumentError("signature missing or invalid s", "signature", signature);
}
else {
result.s = hexZeroPad(result.s, 32);
}
const vs = arrayify(result.s);
if (vs[0] >= 128) {
lib_esm_logger.throwArgumentError("signature s out of range", "signature", signature);
}
if (result.recoveryParam) {
vs[0] |= 0x80;
}
const _vs = hexlify(vs);
if (result._vs) {
if (!isHexString(result._vs)) {
lib_esm_logger.throwArgumentError("signature invalid _vs", "signature", signature);
}
result._vs = hexZeroPad(result._vs, 32);
}
// Set or check the _vs
if (result._vs == null) {
result._vs = _vs;
}
else if (result._vs !== _vs) {
lib_esm_logger.throwArgumentError("signature _vs mismatch v and s", "signature", signature);
}
}
result.yParityAndS = result._vs;
result.compact = result.r + result.yParityAndS.substring(2);
return result;
}
function joinSignature(signature) {
signature = splitSignature(signature);
return hexlify(concat([
signature.r,
signature.s,
(signature.recoveryParam ? "0x1c" : "0x1b")
]));
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/bignumber/lib.esm/_version.js
const bignumber_lib_esm_version_version = "bignumber/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/bignumber/lib.esm/bignumber.js
/**
* BigNumber
*
* A wrapper around the BN.js object. We use the BN.js library
* because it is used by elliptic, so it is required regardless.
*
*/
var BN = bn_default.a.BN;
const bignumber_logger = new lib_esm_Logger(bignumber_lib_esm_version_version);
const _constructorGuard = {};
const MAX_SAFE = 0x1fffffffffffff;
function isBigNumberish(value) {
return (value != null) && (bignumber_BigNumber.isBigNumber(value) ||
(typeof (value) === "number" && (value % 1) === 0) ||
(typeof (value) === "string" && !!value.match(/^-?[0-9]+$/)) ||
isHexString(value) ||
(typeof (value) === "bigint") ||
isBytes(value));
}
// Only warn about passing 10 into radix once
let _warnedToStringRadix = false;
class bignumber_BigNumber {
constructor(constructorGuard, hex) {
if (constructorGuard !== _constructorGuard) {
bignumber_logger.throwError("cannot call constructor directly; use BigNumber.from", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new (BigNumber)"
});
}
this._hex = hex;
this._isBigNumber = true;
Object.freeze(this);
}
fromTwos(value) {
return toBigNumber(toBN(this).fromTwos(value));
}
toTwos(value) {
return toBigNumber(toBN(this).toTwos(value));
}
abs() {
if (this._hex[0] === "-") {
return bignumber_BigNumber.from(this._hex.substring(1));
}
return this;
}
add(other) {
return toBigNumber(toBN(this).add(toBN(other)));
}
sub(other) {
return toBigNumber(toBN(this).sub(toBN(other)));
}
div(other) {
const o = bignumber_BigNumber.from(other);
if (o.isZero()) {
throwFault("division-by-zero", "div");
}
return toBigNumber(toBN(this).div(toBN(other)));
}
mul(other) {
return toBigNumber(toBN(this).mul(toBN(other)));
}
mod(other) {
const value = toBN(other);
if (value.isNeg()) {
throwFault("division-by-zero", "mod");
}
return toBigNumber(toBN(this).umod(value));
}
pow(other) {
const value = toBN(other);
if (value.isNeg()) {
throwFault("negative-power", "pow");
}
return toBigNumber(toBN(this).pow(value));
}
and(other) {
const value = toBN(other);
if (this.isNegative() || value.isNeg()) {
throwFault("unbound-bitwise-result", "and");
}
return toBigNumber(toBN(this).and(value));
}
or(other) {
const value = toBN(other);
if (this.isNegative() || value.isNeg()) {
throwFault("unbound-bitwise-result", "or");
}
return toBigNumber(toBN(this).or(value));
}
xor(other) {
const value = toBN(other);
if (this.isNegative() || value.isNeg()) {
throwFault("unbound-bitwise-result", "xor");
}
return toBigNumber(toBN(this).xor(value));
}
mask(value) {
if (this.isNegative() || value < 0) {
throwFault("negative-width", "mask");
}
return toBigNumber(toBN(this).maskn(value));
}
shl(value) {
if (this.isNegative() || value < 0) {
throwFault("negative-width", "shl");
}
return toBigNumber(toBN(this).shln(value));
}
shr(value) {
if (this.isNegative() || value < 0) {
throwFault("negative-width", "shr");
}
return toBigNumber(toBN(this).shrn(value));
}
eq(other) {
return toBN(this).eq(toBN(other));
}
lt(other) {
return toBN(this).lt(toBN(other));
}
lte(other) {
return toBN(this).lte(toBN(other));
}
gt(other) {
return toBN(this).gt(toBN(other));
}
gte(other) {
return toBN(this).gte(toBN(other));
}
isNegative() {
return (this._hex[0] === "-");
}
isZero() {
return toBN(this).isZero();
}
toNumber() {
try {
return toBN(this).toNumber();
}
catch (error) {
throwFault("overflow", "toNumber", this.toString());
}
return null;
}
toBigInt() {
try {
return BigInt(this.toString());
}
catch (e) { }
return bignumber_logger.throwError("this platform does not support BigInt", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
value: this.toString()
});
}
toString() {
// Lots of people expect this, which we do not support, so check (See: #889)
if (arguments.length > 0) {
if (arguments[0] === 10) {
if (!_warnedToStringRadix) {
_warnedToStringRadix = true;
bignumber_logger.warn("BigNumber.toString does not accept any parameters; base-10 is assumed");
}
}
else if (arguments[0] === 16) {
bignumber_logger.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", lib_esm_Logger.errors.UNEXPECTED_ARGUMENT, {});
}
else {
bignumber_logger.throwError("BigNumber.toString does not accept parameters", lib_esm_Logger.errors.UNEXPECTED_ARGUMENT, {});
}
}
return toBN(this).toString(10);
}
toHexString() {
return this._hex;
}
toJSON(key) {
return { type: "BigNumber", hex: this.toHexString() };
}
static from(value) {
if (value instanceof bignumber_BigNumber) {
return value;
}
if (typeof (value) === "string") {
if (value.match(/^-?0x[0-9a-f]+$/i)) {
return new bignumber_BigNumber(_constructorGuard, toHex(value));
}
if (value.match(/^-?[0-9]+$/)) {
return new bignumber_BigNumber(_constructorGuard, toHex(new BN(value)));
}
return bignumber_logger.throwArgumentError("invalid BigNumber string", "value", value);
}
if (typeof (value) === "number") {
if (value % 1) {
throwFault("underflow", "BigNumber.from", value);
}
if (value >= MAX_SAFE || value <= -MAX_SAFE) {
throwFault("overflow", "BigNumber.from", value);
}
return bignumber_BigNumber.from(String(value));
}
const anyValue = value;
if (typeof (anyValue) === "bigint") {
return bignumber_BigNumber.from(anyValue.toString());
}
if (isBytes(anyValue)) {
return bignumber_BigNumber.from(hexlify(anyValue));
}
if (anyValue) {
// Hexable interface (takes priority)
if (anyValue.toHexString) {
const hex = anyValue.toHexString();
if (typeof (hex) === "string") {
return bignumber_BigNumber.from(hex);
}
}
else {
// For now, handle legacy JSON-ified values (goes away in v6)
let hex = anyValue._hex;
// New-form JSON
if (hex == null && anyValue.type === "BigNumber") {
hex = anyValue.hex;
}
if (typeof (hex) === "string") {
if (isHexString(hex) || (hex[0] === "-" && isHexString(hex.substring(1)))) {
return bignumber_BigNumber.from(hex);
}
}
}
}
return bignumber_logger.throwArgumentError("invalid BigNumber value", "value", value);
}
static isBigNumber(value) {
return !!(value && value._isBigNumber);
}
}
// Normalize the hex string
function toHex(value) {
// For BN, call on the hex string
if (typeof (value) !== "string") {
return toHex(value.toString(16));
}
// If negative, prepend the negative sign to the normalized positive value
if (value[0] === "-") {
// Strip off the negative sign
value = value.substring(1);
// Cannot have multiple negative signs (e.g. "--0x04")
if (value[0] === "-") {
bignumber_logger.throwArgumentError("invalid hex", "value", value);
}
// Call toHex on the positive component
value = toHex(value);
// Do not allow "-0x00"
if (value === "0x00") {
return value;
}
// Negate the value
return "-" + value;
}
// Add a "0x" prefix if missing
if (value.substring(0, 2) !== "0x") {
value = "0x" + value;
}
// Normalize zero
if (value === "0x") {
return "0x00";
}
// Make the string even length
if (value.length % 2) {
value = "0x0" + value.substring(2);
}
// Trim to smallest even-length string
while (value.length > 4 && value.substring(0, 4) === "0x00") {
value = "0x" + value.substring(4);
}
return value;
}
function toBigNumber(value) {
return bignumber_BigNumber.from(toHex(value));
}
function toBN(value) {
const hex = bignumber_BigNumber.from(value).toHexString();
if (hex[0] === "-") {
return (new BN("-" + hex.substring(3), 16));
}
return new BN(hex.substring(2), 16);
}
function throwFault(fault, operation, value) {
const params = { fault: fault, operation: operation };
if (value != null) {
params.value = value;
}
return bignumber_logger.throwError(fault, lib_esm_Logger.errors.NUMERIC_FAULT, params);
}
// value should have no prefix
function _base36To16(value) {
return (new BN(value, 36)).toString(16);
}
// value should have no prefix
function _base16To36(value) {
return (new BN(value, 16)).toString(36);
}
//# sourceMappingURL=bignumber.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/properties/lib.esm/_version.js
const properties_lib_esm_version_version = "properties/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/properties/lib.esm/index.js
var __awaiter = (undefined && undefined.__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());
});
};
const properties_lib_esm_logger = new lib_esm_Logger(properties_lib_esm_version_version);
function defineReadOnly(object, name, value) {
Object.defineProperty(object, name, {
enumerable: true,
value: value,
writable: false,
});
}
// Crawl up the constructor chain to find a static method
function getStatic(ctor, key) {
for (let i = 0; i < 32; i++) {
if (ctor[key]) {
return ctor[key];
}
if (!ctor.prototype || typeof (ctor.prototype) !== "object") {
break;
}
ctor = Object.getPrototypeOf(ctor.prototype).constructor;
}
return null;
}
function resolveProperties(object) {
return __awaiter(this, void 0, void 0, function* () {
const promises = Object.keys(object).map((key) => {
const value = object[key];
return Promise.resolve(value).then((v) => ({ key: key, value: v }));
});
const results = yield Promise.all(promises);
return results.reduce((accum, result) => {
accum[(result.key)] = result.value;
return accum;
}, {});
});
}
function checkProperties(object, properties) {
if (!object || typeof (object) !== "object") {
properties_lib_esm_logger.throwArgumentError("invalid object", "object", object);
}
Object.keys(object).forEach((key) => {
if (!properties[key]) {
properties_lib_esm_logger.throwArgumentError("invalid object key - " + key, "transaction:" + key, object);
}
});
}
function shallowCopy(object) {
const result = {};
for (const key in object) {
result[key] = object[key];
}
return result;
}
const opaque = { bigint: true, boolean: true, "function": true, number: true, string: true };
function _isFrozen(object) {
// Opaque objects are not mutable, so safe to copy by assignment
if (object === undefined || object === null || opaque[typeof (object)]) {
return true;
}
if (Array.isArray(object) || typeof (object) === "object") {
if (!Object.isFrozen(object)) {
return false;
}
const keys = Object.keys(object);
for (let i = 0; i < keys.length; i++) {
let value = null;
try {
value = object[keys[i]];
}
catch (error) {
// If accessing a value triggers an error, it is a getter
// designed to do so (e.g. Result) and is therefore "frozen"
continue;
}
if (!_isFrozen(value)) {
return false;
}
}
return true;
}
return properties_lib_esm_logger.throwArgumentError(`Cannot deepCopy ${typeof (object)}`, "object", object);
}
// Returns a new copy of object, such that no properties may be replaced.
// New properties may be added only to objects.
function _deepCopy(object) {
if (_isFrozen(object)) {
return object;
}
// Arrays are mutable, so we need to create a copy
if (Array.isArray(object)) {
return Object.freeze(object.map((item) => deepCopy(item)));
}
if (typeof (object) === "object") {
const result = {};
for (const key in object) {
const value = object[key];
if (value === undefined) {
continue;
}
defineReadOnly(result, key, deepCopy(value));
}
return result;
}
return properties_lib_esm_logger.throwArgumentError(`Cannot deepCopy ${typeof (object)}`, "object", object);
}
function deepCopy(object) {
return _deepCopy(object);
}
class Description {
constructor(info) {
for (const key in info) {
this[key] = deepCopy(info[key]);
}
}
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abstract-provider/lib.esm/_version.js
const abstract_provider_lib_esm_version_version = "abstract-provider/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abstract-provider/lib.esm/index.js
var lib_esm_awaiter = (undefined && undefined.__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());
});
};
const abstract_provider_lib_esm_logger = new lib_esm_Logger(abstract_provider_lib_esm_version_version);
;
;
//export type CallTransactionable = {
// call(transaction: TransactionRequest): Promise<TransactionResponse>;
//};
class lib_esm_ForkEvent extends Description {
static isForkEvent(value) {
return !!(value && value._isForkEvent);
}
}
class lib_esm_BlockForkEvent extends lib_esm_ForkEvent {
constructor(blockHash, expiry) {
if (!isHexString(blockHash, 32)) {
abstract_provider_lib_esm_logger.throwArgumentError("invalid blockHash", "blockHash", blockHash);
}
super({
_isForkEvent: true,
_isBlockForkEvent: true,
expiry: (expiry || 0),
blockHash: blockHash
});
}
}
class lib_esm_TransactionForkEvent extends lib_esm_ForkEvent {
constructor(hash, expiry) {
if (!isHexString(hash, 32)) {
abstract_provider_lib_esm_logger.throwArgumentError("invalid transaction hash", "hash", hash);
}
super({
_isForkEvent: true,
_isTransactionForkEvent: true,
expiry: (expiry || 0),
hash: hash
});
}
}
class lib_esm_TransactionOrderForkEvent extends lib_esm_ForkEvent {
constructor(beforeHash, afterHash, expiry) {
if (!isHexString(beforeHash, 32)) {
abstract_provider_lib_esm_logger.throwArgumentError("invalid transaction hash", "beforeHash", beforeHash);
}
if (!isHexString(afterHash, 32)) {
abstract_provider_lib_esm_logger.throwArgumentError("invalid transaction hash", "afterHash", afterHash);
}
super({
_isForkEvent: true,
_isTransactionOrderForkEvent: true,
expiry: (expiry || 0),
beforeHash: beforeHash,
afterHash: afterHash
});
}
}
///////////////////////////////
// Exported Abstracts
class lib_esm_Provider {
constructor() {
abstract_provider_lib_esm_logger.checkAbstract(new.target, lib_esm_Provider);
defineReadOnly(this, "_isProvider", true);
}
getFeeData() {
return lib_esm_awaiter(this, void 0, void 0, function* () {
const { block, gasPrice } = yield resolveProperties({
block: this.getBlock("latest"),
gasPrice: this.getGasPrice().catch((error) => {
// @TODO: Why is this now failing on Calaveras?
//console.log(error);
return null;
})
});
let lastBaseFeePerGas = null, maxFeePerGas = null, maxPriorityFeePerGas = null;
if (block && block.baseFeePerGas) {
// We may want to compute this more accurately in the future,
// using the formula "check if the base fee is correct".
// See: https://eips.ethereum.org/EIPS/eip-1559
lastBaseFeePerGas = block.baseFeePerGas;
maxPriorityFeePerGas = bignumber_BigNumber.from("1500000000");
maxFeePerGas = block.baseFeePerGas.mul(2).add(maxPriorityFeePerGas);
}
return { lastBaseFeePerGas, maxFeePerGas, maxPriorityFeePerGas, gasPrice };
});
}
// Alias for "on"
addListener(eventName, listener) {
return this.on(eventName, listener);
}
// Alias for "off"
removeListener(eventName, listener) {
return this.off(eventName, listener);
}
static isProvider(value) {
return !!(value && value._isProvider);
}
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/networks/lib.esm/_version.js
const networks_lib_esm_version_version = "networks/5.7.1";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/networks/lib.esm/index.js
const networks_lib_esm_logger = new lib_esm_Logger(networks_lib_esm_version_version);
;
function isRenetworkable(value) {
return (value && typeof (value.renetwork) === "function");
}
function ethDefaultProvider(network) {
const func = function (providers, options) {
if (options == null) {
options = {};
}
const providerList = [];
if (providers.InfuraProvider && options.infura !== "-") {
try {
providerList.push(new providers.InfuraProvider(network, options.infura));
}
catch (error) { }
}
if (providers.EtherscanProvider && options.etherscan !== "-") {
try {
providerList.push(new providers.EtherscanProvider(network, options.etherscan));
}
catch (error) { }
}
if (providers.AlchemyProvider && options.alchemy !== "-") {
try {
providerList.push(new providers.AlchemyProvider(network, options.alchemy));
}
catch (error) { }
}
if (providers.PocketProvider && options.pocket !== "-") {
// These networks are currently faulty on Pocket as their
// network does not handle the Berlin hardfork, which is
// live on these ones.
// @TODO: This goes away once Pocket has upgraded their nodes
const skip = ["goerli", "ropsten", "rinkeby", "sepolia"];
try {
const provider = new providers.PocketProvider(network, options.pocket);
if (provider.network && skip.indexOf(provider.network.name) === -1) {
providerList.push(provider);
}
}
catch (error) { }
}
if (providers.CloudflareProvider && options.cloudflare !== "-") {
try {
providerList.push(new providers.CloudflareProvider(network));
}
catch (error) { }
}
if (providers.AnkrProvider && options.ankr !== "-") {
try {
const skip = ["ropsten"];
const provider = new providers.AnkrProvider(network, options.ankr);
if (provider.network && skip.indexOf(provider.network.name) === -1) {
providerList.push(provider);
}
}
catch (error) { }
}
if (providerList.length === 0) {
return null;
}
if (providers.FallbackProvider) {
let quorum = 1;
if (options.quorum != null) {
quorum = options.quorum;
}
else if (network === "homestead") {
quorum = 2;
}
return new providers.FallbackProvider(providerList, quorum);
}
return providerList[0];
};
func.renetwork = function (network) {
return ethDefaultProvider(network);
};
return func;
}
function etcDefaultProvider(url, network) {
const func = function (providers, options) {
if (providers.JsonRpcProvider) {
return new providers.JsonRpcProvider(url, network);
}
return null;
};
func.renetwork = function (network) {
return etcDefaultProvider(url, network);
};
return func;
}
const homestead = {
chainId: 1,
ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
name: "homestead",
_defaultProvider: ethDefaultProvider("homestead")
};
const ropsten = {
chainId: 3,
ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
name: "ropsten",
_defaultProvider: ethDefaultProvider("ropsten")
};
const classicMordor = {
chainId: 63,
name: "classicMordor",
_defaultProvider: etcDefaultProvider("https://www.ethercluster.com/mordor", "classicMordor")
};
// See: https://chainlist.org
const networks = {
unspecified: { chainId: 0, name: "unspecified" },
homestead: homestead,
mainnet: homestead,
morden: { chainId: 2, name: "morden" },
ropsten: ropsten,
testnet: ropsten,
rinkeby: {
chainId: 4,
ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
name: "rinkeby",
_defaultProvider: ethDefaultProvider("rinkeby")
},
kovan: {
chainId: 42,
name: "kovan",
_defaultProvider: ethDefaultProvider("kovan")
},
goerli: {
chainId: 5,
ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
name: "goerli",
_defaultProvider: ethDefaultProvider("goerli")
},
kintsugi: { chainId: 1337702, name: "kintsugi" },
sepolia: {
chainId: 11155111,
name: "sepolia",
_defaultProvider: ethDefaultProvider("sepolia")
},
// ETC (See: #351)
classic: {
chainId: 61,
name: "classic",
_defaultProvider: etcDefaultProvider("https:/\/www.ethercluster.com/etc", "classic")
},
classicMorden: { chainId: 62, name: "classicMorden" },
classicMordor: classicMordor,
classicTestnet: classicMordor,
classicKotti: {
chainId: 6,
name: "classicKotti",
_defaultProvider: etcDefaultProvider("https:/\/www.ethercluster.com/kotti", "classicKotti")
},
xdai: { chainId: 100, name: "xdai" },
matic: {
chainId: 137,
name: "matic",
_defaultProvider: ethDefaultProvider("matic")
},
maticmum: { chainId: 80001, name: "maticmum" },
optimism: {
chainId: 10,
name: "optimism",
_defaultProvider: ethDefaultProvider("optimism")
},
"optimism-kovan": { chainId: 69, name: "optimism-kovan" },
"optimism-goerli": { chainId: 420, name: "optimism-goerli" },
arbitrum: { chainId: 42161, name: "arbitrum" },
"arbitrum-rinkeby": { chainId: 421611, name: "arbitrum-rinkeby" },
"arbitrum-goerli": { chainId: 421613, name: "arbitrum-goerli" },
bnb: { chainId: 56, name: "bnb" },
bnbt: { chainId: 97, name: "bnbt" },
};
/**
* getNetwork
*
* Converts a named common networks or chain ID (network ID) to a Network
* and verifies a network is a valid Network..
*/
function lib_esm_getNetwork(network) {
// No network (null)
if (network == null) {
return null;
}
if (typeof (network) === "number") {
for (const name in networks) {
const standard = networks[name];
if (standard.chainId === network) {
return {
name: standard.name,
chainId: standard.chainId,
ensAddress: (standard.ensAddress || null),
_defaultProvider: (standard._defaultProvider || null)
};
}
}
return {
chainId: network,
name: "unknown"
};
}
if (typeof (network) === "string") {
const standard = networks[network];
if (standard == null) {
return null;
}
return {
name: standard.name,
chainId: standard.chainId,
ensAddress: standard.ensAddress,
_defaultProvider: (standard._defaultProvider || null)
};
}
const standard = networks[network.name];
// Not a standard network; check that it is a valid network in general
if (!standard) {
if (typeof (network.chainId) !== "number") {
networks_lib_esm_logger.throwArgumentError("invalid network chainId", "network", network);
}
return network;
}
// Make sure the chainId matches the expected network chainId (or is 0; disable EIP-155)
if (network.chainId !== 0 && network.chainId !== standard.chainId) {
networks_lib_esm_logger.throwArgumentError("network chainId mismatch", "network", network);
}
// @TODO: In the next major version add an attach function to a defaultProvider
// class and move the _defaultProvider internal to this file (extend Network)
let defaultProvider = network._defaultProvider || null;
if (defaultProvider == null && standard._defaultProvider) {
if (isRenetworkable(standard._defaultProvider)) {
defaultProvider = standard._defaultProvider.renetwork(network);
}
else {
defaultProvider = standard._defaultProvider;
}
}
// Standard Network (allow overriding the ENS address)
return {
name: network.name,
chainId: standard.chainId,
ensAddress: (network.ensAddress || standard.ensAddress || null),
_defaultProvider: defaultProvider
};
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/base64/lib.esm/base64.js
function decode(textData) {
textData = atob(textData);
const data = [];
for (let i = 0; i < textData.length; i++) {
data.push(textData.charCodeAt(i));
}
return arrayify(data);
}
function encode(data) {
data = arrayify(data);
let textData = "";
for (let i = 0; i < data.length; i++) {
textData += String.fromCharCode(data[i]);
}
return btoa(textData);
}
//# sourceMappingURL=base64.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/basex/lib.esm/index.js
/**
* var basex = require("base-x");
*
* This implementation is heavily based on base-x. The main reason to
* deviate was to prevent the dependency of Buffer.
*
* Contributors:
*
* base-x encoding
* Forked from https://github.com/cryptocoinjs/bs58
* Originally written by Mike Hearn for BitcoinJ
* Copyright (c) 2011 Google Inc
* Ported to JavaScript by Stefan Thomas
* Merged Buffer refactorings from base58-native by Stephen Pair
* Copyright (c) 2013 BitPay Inc
*
* The MIT License (MIT)
*
* Copyright base-x contributors (c) 2016
*
* 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.
*
*/
class lib_esm_BaseX {
constructor(alphabet) {
defineReadOnly(this, "alphabet", alphabet);
defineReadOnly(this, "base", alphabet.length);
defineReadOnly(this, "_alphabetMap", {});
defineReadOnly(this, "_leader", alphabet.charAt(0));
// pre-compute lookup table
for (let i = 0; i < alphabet.length; i++) {
this._alphabetMap[alphabet.charAt(i)] = i;
}
}
encode(value) {
let source = arrayify(value);
if (source.length === 0) {
return "";
}
let digits = [0];
for (let i = 0; i < source.length; ++i) {
let carry = source[i];
for (let j = 0; j < digits.length; ++j) {
carry += digits[j] << 8;
digits[j] = carry % this.base;
carry = (carry / this.base) | 0;
}
while (carry > 0) {
digits.push(carry % this.base);
carry = (carry / this.base) | 0;
}
}
let string = "";
// deal with leading zeros
for (let k = 0; source[k] === 0 && k < source.length - 1; ++k) {
string += this._leader;
}
// convert digits to a string
for (let q = digits.length - 1; q >= 0; --q) {
string += this.alphabet[digits[q]];
}
return string;
}
decode(value) {
if (typeof (value) !== "string") {
throw new TypeError("Expected String");
}
let bytes = [];
if (value.length === 0) {
return new Uint8Array(bytes);
}
bytes.push(0);
for (let i = 0; i < value.length; i++) {
let byte = this._alphabetMap[value[i]];
if (byte === undefined) {
throw new Error("Non-base" + this.base + " character");
}
let carry = byte;
for (let j = 0; j < bytes.length; ++j) {
carry += bytes[j] * this.base;
bytes[j] = carry & 0xff;
carry >>= 8;
}
while (carry > 0) {
bytes.push(carry & 0xff);
carry >>= 8;
}
}
// deal with leading zeros
for (let k = 0; value[k] === this._leader && k < value.length - 1; ++k) {
bytes.push(0);
}
return arrayify(new Uint8Array(bytes.reverse()));
}
}
const Base32 = new lib_esm_BaseX("abcdefghijklmnopqrstuvwxyz234567");
const Base58 = new lib_esm_BaseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
//console.log(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj"))
//console.log(Base58.encode(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj")))
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/constants/lib.esm/hashes.js
const HashZero = "0x0000000000000000000000000000000000000000000000000000000000000000";
//# sourceMappingURL=hashes.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/strings/lib.esm/_version.js
const strings_lib_esm_version_version = "strings/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/strings/lib.esm/utf8.js
const utf8_logger = new lib_esm_Logger(strings_lib_esm_version_version);
///////////////////////////////
var UnicodeNormalizationForm;
(function (UnicodeNormalizationForm) {
UnicodeNormalizationForm["current"] = "";
UnicodeNormalizationForm["NFC"] = "NFC";
UnicodeNormalizationForm["NFD"] = "NFD";
UnicodeNormalizationForm["NFKC"] = "NFKC";
UnicodeNormalizationForm["NFKD"] = "NFKD";
})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {}));
;
var Utf8ErrorReason;
(function (Utf8ErrorReason) {
// A continuation byte was present where there was nothing to continue
// - offset = the index the codepoint began in
Utf8ErrorReason["UNEXPECTED_CONTINUE"] = "unexpected continuation byte";
// An invalid (non-continuation) byte to start a UTF-8 codepoint was found
// - offset = the index the codepoint began in
Utf8ErrorReason["BAD_PREFIX"] = "bad codepoint prefix";
// The string is too short to process the expected codepoint
// - offset = the index the codepoint began in
Utf8ErrorReason["OVERRUN"] = "string overrun";
// A missing continuation byte was expected but not found
// - offset = the index the continuation byte was expected at
Utf8ErrorReason["MISSING_CONTINUE"] = "missing continuation byte";
// The computed code point is outside the range for UTF-8
// - offset = start of this codepoint
// - badCodepoint = the computed codepoint; outside the UTF-8 range
Utf8ErrorReason["OUT_OF_RANGE"] = "out of UTF-8 range";
// UTF-8 strings may not contain UTF-16 surrogate pairs
// - offset = start of this codepoint
// - badCodepoint = the computed codepoint; inside the UTF-16 surrogate range
Utf8ErrorReason["UTF16_SURROGATE"] = "UTF-16 surrogate";
// The string is an overlong representation
// - offset = start of this codepoint
// - badCodepoint = the computed codepoint; already bounds checked
Utf8ErrorReason["OVERLONG"] = "overlong representation";
})(Utf8ErrorReason || (Utf8ErrorReason = {}));
;
function errorFunc(reason, offset, bytes, output, badCodepoint) {
return utf8_logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes);
}
function ignoreFunc(reason, offset, bytes, output, badCodepoint) {
// If there is an invalid prefix (including stray continuation), skip any additional continuation bytes
if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) {
let i = 0;
for (let o = offset + 1; o < bytes.length; o++) {
if (bytes[o] >> 6 !== 0x02) {
break;
}
i++;
}
return i;
}
// This byte runs us past the end of the string, so just jump to the end
// (but the first byte was read already read and therefore skipped)
if (reason === Utf8ErrorReason.OVERRUN) {
return bytes.length - offset - 1;
}
// Nothing to skip
return 0;
}
function replaceFunc(reason, offset, bytes, output, badCodepoint) {
// Overlong representations are otherwise "valid" code points; just non-deistingtished
if (reason === Utf8ErrorReason.OVERLONG) {
output.push(badCodepoint);
return 0;
}
// Put the replacement character into the output
output.push(0xfffd);
// Otherwise, process as if ignoring errors
return ignoreFunc(reason, offset, bytes, output, badCodepoint);
}
// Common error handing strategies
const Utf8ErrorFuncs = Object.freeze({
error: errorFunc,
ignore: ignoreFunc,
replace: replaceFunc
});
// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
function getUtf8CodePoints(bytes, onError) {
if (onError == null) {
onError = Utf8ErrorFuncs.error;
}
bytes = arrayify(bytes);
const result = [];
let i = 0;
// Invalid bytes are ignored
while (i < bytes.length) {
const c = bytes[i++];
// 0xxx xxxx
if (c >> 7 === 0) {
result.push(c);
continue;
}
// Multibyte; how many bytes left for this character?
let extraLength = null;
let overlongMask = null;
// 110x xxxx 10xx xxxx
if ((c & 0xe0) === 0xc0) {
extraLength = 1;
overlongMask = 0x7f;
// 1110 xxxx 10xx xxxx 10xx xxxx
}
else if ((c & 0xf0) === 0xe0) {
extraLength = 2;
overlongMask = 0x7ff;
// 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
}
else if ((c & 0xf8) === 0xf0) {
extraLength = 3;
overlongMask = 0xffff;
}
else {
if ((c & 0xc0) === 0x80) {
i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes, result);
}
else {
i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes, result);
}
continue;
}
// Do we have enough bytes in our data?
if (i - 1 + extraLength >= bytes.length) {
i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes, result);
continue;
}
// Remove the length prefix from the char
let res = c & ((1 << (8 - extraLength - 1)) - 1);
for (let j = 0; j < extraLength; j++) {
let nextChar = bytes[i];
// Invalid continuation byte
if ((nextChar & 0xc0) != 0x80) {
i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes, result);
res = null;
break;
}
;
res = (res << 6) | (nextChar & 0x3f);
i++;
}
// See above loop for invalid continuation byte
if (res === null) {
continue;
}
// Maximum code point
if (res > 0x10ffff) {
i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes, result, res);
continue;
}
// Reserved for UTF-16 surrogate halves
if (res >= 0xd800 && res <= 0xdfff) {
i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes, result, res);
continue;
}
// Check for overlong sequences (more bytes than needed)
if (res <= overlongMask) {
i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes, result, res);
continue;
}
result.push(res);
}
return result;
}
// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) {
if (form != UnicodeNormalizationForm.current) {
utf8_logger.checkNormalize();
str = str.normalize(form);
}
let result = [];
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 0x80) {
result.push(c);
}
else if (c < 0x800) {
result.push((c >> 6) | 0xc0);
result.push((c & 0x3f) | 0x80);
}
else if ((c & 0xfc00) == 0xd800) {
i++;
const c2 = str.charCodeAt(i);
if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) {
throw new Error("invalid utf-8 string");
}
// Surrogate Pair
const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
result.push((pair >> 18) | 0xf0);
result.push(((pair >> 12) & 0x3f) | 0x80);
result.push(((pair >> 6) & 0x3f) | 0x80);
result.push((pair & 0x3f) | 0x80);
}
else {
result.push((c >> 12) | 0xe0);
result.push(((c >> 6) & 0x3f) | 0x80);
result.push((c & 0x3f) | 0x80);
}
}
return arrayify(result);
}
;
function escapeChar(value) {
const hex = ("0000" + value.toString(16));
return "\\u" + hex.substring(hex.length - 4);
}
function _toEscapedUtf8String(bytes, onError) {
return '"' + getUtf8CodePoints(bytes, onError).map((codePoint) => {
if (codePoint < 256) {
switch (codePoint) {
case 8: return "\\b";
case 9: return "\\t";
case 10: return "\\n";
case 13: return "\\r";
case 34: return "\\\"";
case 92: return "\\\\";
}
if (codePoint >= 32 && codePoint < 127) {
return String.fromCharCode(codePoint);
}
}
if (codePoint <= 0xffff) {
return escapeChar(codePoint);
}
codePoint -= 0x10000;
return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00);
}).join("") + '"';
}
function _toUtf8String(codePoints) {
return codePoints.map((codePoint) => {
if (codePoint <= 0xffff) {
return String.fromCharCode(codePoint);
}
codePoint -= 0x10000;
return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00));
}).join("");
}
function toUtf8String(bytes, onError) {
return _toUtf8String(getUtf8CodePoints(bytes, onError));
}
function toUtf8CodePoints(str, form = UnicodeNormalizationForm.current) {
return getUtf8CodePoints(toUtf8Bytes(str, form));
}
//# sourceMappingURL=utf8.js.map
// EXTERNAL MODULE: ./node_modules/js-sha3/src/sha3.js
var sha3 = __webpack_require__(29);
var sha3_default = /*#__PURE__*/__webpack_require__.n(sha3);
// CONCATENATED MODULE: ./node_modules/@ethersproject/keccak256/lib.esm/index.js
function keccak256(data) {
return '0x' + sha3_default.a.keccak_256(arrayify(data));
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hash/lib.esm/_version.js
const hash_lib_esm_version_version = "hash/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hash/lib.esm/ens-normalize/decoder.js
/**
* MIT License
*
* Copyright (c) 2021 Andrew Raffensperger
*
* 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.
*
* This is a near carbon-copy of the original source (link below) with the
* TypeScript typings added and a few tweaks to make it ES3-compatible.
*
* See: https://github.com/adraffy/ens-normalize.js
*/
// https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js
function flat(array, depth) {
if (depth == null) {
depth = 1;
}
const result = [];
const forEach = result.forEach;
const flatDeep = function (arr, depth) {
forEach.call(arr, function (val) {
if (depth > 0 && Array.isArray(val)) {
flatDeep(val, depth - 1);
}
else {
result.push(val);
}
});
};
flatDeep(array, depth);
return result;
}
function fromEntries(array) {
const result = {};
for (let i = 0; i < array.length; i++) {
const value = array[i];
result[value[0]] = value[1];
}
return result;
}
function decode_arithmetic(bytes) {
let pos = 0;
function u16() { return (bytes[pos++] << 8) | bytes[pos++]; }
// decode the frequency table
let symbol_count = u16();
let total = 1;
let acc = [0, 1]; // first symbol has frequency 1
for (let i = 1; i < symbol_count; i++) {
acc.push(total += u16());
}
// skip the sized-payload that the last 3 symbols index into
let skip = u16();
let pos_payload = pos;
pos += skip;
let read_width = 0;
let read_buffer = 0;
function read_bit() {
if (read_width == 0) {
// this will read beyond end of buffer
// but (undefined|0) => zero pad
read_buffer = (read_buffer << 8) | bytes[pos++];
read_width = 8;
}
return (read_buffer >> --read_width) & 1;
}
const N = 31;
const FULL = Math.pow(2, N);
const HALF = FULL >>> 1;
const QRTR = HALF >> 1;
const MASK = FULL - 1;
// fill register
let register = 0;
for (let i = 0; i < N; i++)
register = (register << 1) | read_bit();
let symbols = [];
let low = 0;
let range = FULL; // treat like a float
while (true) {
let value = Math.floor((((register - low + 1) * total) - 1) / range);
let start = 0;
let end = symbol_count;
while (end - start > 1) { // binary search
let mid = (start + end) >>> 1;
if (value < acc[mid]) {
end = mid;
}
else {
start = mid;
}
}
if (start == 0)
break; // first symbol is end mark
symbols.push(start);
let a = low + Math.floor(range * acc[start] / total);
let b = low + Math.floor(range * acc[start + 1] / total) - 1;
while (((a ^ b) & HALF) == 0) {
register = (register << 1) & MASK | read_bit();
a = (a << 1) & MASK;
b = (b << 1) & MASK | 1;
}
while (a & ~b & QRTR) {
register = (register & HALF) | ((register << 1) & (MASK >>> 1)) | read_bit();
a = (a << 1) ^ HALF;
b = ((b ^ HALF) << 1) | HALF | 1;
}
low = a;
range = 1 + b - a;
}
let offset = symbol_count - 4;
return symbols.map(x => {
switch (x - offset) {
case 3: return offset + 0x10100 + ((bytes[pos_payload++] << 16) | (bytes[pos_payload++] << 8) | bytes[pos_payload++]);
case 2: return offset + 0x100 + ((bytes[pos_payload++] << 8) | bytes[pos_payload++]);
case 1: return offset + bytes[pos_payload++];
default: return x - 1;
}
});
}
// returns an iterator which returns the next symbol
function read_payload(v) {
let pos = 0;
return () => v[pos++];
}
function read_compressed_payload(bytes) {
return read_payload(decode_arithmetic(bytes));
}
// eg. [0,1,2,3...] => [0,-1,1,-2,...]
function decoder_signed(i) {
return (i & 1) ? (~i >> 1) : (i >> 1);
}
function read_counts(n, next) {
let v = Array(n);
for (let i = 0; i < n; i++)
v[i] = 1 + next();
return v;
}
function read_ascending(n, next) {
let v = Array(n);
for (let i = 0, x = -1; i < n; i++)
v[i] = x += 1 + next();
return v;
}
function read_deltas(n, next) {
let v = Array(n);
for (let i = 0, x = 0; i < n; i++)
v[i] = x += decoder_signed(next());
return v;
}
function read_member_array(next, lookup) {
let v = read_ascending(next(), next);
let n = next();
let vX = read_ascending(n, next);
let vN = read_counts(n, next);
for (let i = 0; i < n; i++) {
for (let j = 0; j < vN[i]; j++) {
v.push(vX[i] + j);
}
}
return lookup ? v.map(x => lookup[x]) : v;
}
// returns array of
// [x, ys] => single replacement rule
// [x, ys, n, dx, dx] => linear map
function read_mapped_map(next) {
let ret = [];
while (true) {
let w = next();
if (w == 0)
break;
ret.push(read_linear_table(w, next));
}
while (true) {
let w = next() - 1;
if (w < 0)
break;
ret.push(read_replacement_table(w, next));
}
return fromEntries(flat(ret));
}
function read_zero_terminated_array(next) {
let v = [];
while (true) {
let i = next();
if (i == 0)
break;
v.push(i);
}
return v;
}
function read_transposed(n, w, next) {
let m = Array(n).fill(undefined).map(() => []);
for (let i = 0; i < w; i++) {
read_deltas(n, next).forEach((x, j) => m[j].push(x));
}
return m;
}
function read_linear_table(w, next) {
let dx = 1 + next();
let dy = next();
let vN = read_zero_terminated_array(next);
let m = read_transposed(vN.length, 1 + w, next);
return flat(m.map((v, i) => {
const x = v[0], ys = v.slice(1);
//let [x, ...ys] = v;
//return Array(vN[i]).fill().map((_, j) => {
return Array(vN[i]).fill(undefined).map((_, j) => {
let j_dy = j * dy;
return [x + j * dx, ys.map(y => y + j_dy)];
});
}));
}
function read_replacement_table(w, next) {
let n = 1 + next();
let m = read_transposed(n, 1 + w, next);
return m.map(v => [v[0], v.slice(1)]);
}
function read_emoji_trie(next) {
let sorted = read_member_array(next).sort((a, b) => a - b);
return read();
function read() {
let branches = [];
while (true) {
let keys = read_member_array(next, sorted);
if (keys.length == 0)
break;
branches.push({ set: new Set(keys), node: read() });
}
branches.sort((a, b) => b.set.size - a.set.size); // sort by likelihood
let temp = next();
let valid = temp % 3;
temp = (temp / 3) | 0;
let fe0f = !!(temp & 1);
temp >>= 1;
let save = temp == 1;
let check = temp == 2;
return { branches, valid, fe0f, save, check };
}
}
//# sourceMappingURL=decoder.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hash/lib.esm/ens-normalize/include.js
/**
* MIT License
*
* Copyright (c) 2021 Andrew Raffensperger
*
* 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.
*
* This is a near carbon-copy of the original source (link below) with the
* TypeScript typings added and a few tweaks to make it ES3-compatible.
*
* See: https://github.com/adraffy/ens-normalize.js
*/
function getData() {
return read_compressed_payload(decode('AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=='));
}
//# sourceMappingURL=include.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hash/lib.esm/ens-normalize/lib.js
/**
* MIT License
*
* Copyright (c) 2021 Andrew Raffensperger
*
* 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.
*
* This is a near carbon-copy of the original source (link below) with the
* TypeScript typings added and a few tweaks to make it ES3-compatible.
*
* See: https://github.com/adraffy/ens-normalize.js
*/
const lib_r = getData();
// @TODO: This should be lazily loaded
const VALID = new Set(read_member_array(lib_r));
const IGNORED = new Set(read_member_array(lib_r));
const MAPPED = read_mapped_map(lib_r);
const EMOJI_ROOT = read_emoji_trie(lib_r);
//const NFC_CHECK = new Set(read_member_array(r, Array.from(VALID.values()).sort((a, b) => a - b)));
//const STOP = 0x2E;
const HYPHEN = 0x2D;
const UNDERSCORE = 0x5F;
function explode_cp(name) {
return toUtf8CodePoints(name);
}
function filter_fe0f(cps) {
return cps.filter(cp => cp != 0xFE0F);
}
function ens_normalize_post_check(name) {
for (let label of name.split('.')) {
let cps = explode_cp(label);
try {
for (let i = cps.lastIndexOf(UNDERSCORE) - 1; i >= 0; i--) {
if (cps[i] !== UNDERSCORE) {
throw new Error(`underscore only allowed at start`);
}
}
if (cps.length >= 4 && cps.every(cp => cp < 0x80) && cps[2] === HYPHEN && cps[3] === HYPHEN) {
throw new Error(`invalid label extension`);
}
}
catch (err) {
throw new Error(`Invalid label "${label}": ${err.message}`);
}
}
return name;
}
function ens_normalize(name) {
return ens_normalize_post_check(lib_normalize(name, filter_fe0f));
}
function lib_normalize(name, emoji_filter) {
let input = explode_cp(name).reverse(); // flip for pop
let output = [];
while (input.length) {
let emoji = consume_emoji_reversed(input);
if (emoji) {
output.push(...emoji_filter(emoji));
continue;
}
let cp = input.pop();
if (VALID.has(cp)) {
output.push(cp);
continue;
}
if (IGNORED.has(cp)) {
continue;
}
let cps = MAPPED[cp];
if (cps) {
output.push(...cps);
continue;
}
throw new Error(`Disallowed codepoint: 0x${cp.toString(16).toUpperCase()}`);
}
return ens_normalize_post_check(nfc(String.fromCodePoint(...output)));
}
function nfc(s) {
return s.normalize('NFC');
}
function consume_emoji_reversed(cps, eaten) {
var _a;
let node = EMOJI_ROOT;
let emoji;
let saved;
let stack = [];
let pos = cps.length;
if (eaten)
eaten.length = 0; // clear input buffer (if needed)
while (pos) {
let cp = cps[--pos];
node = (_a = node.branches.find(x => x.set.has(cp))) === null || _a === void 0 ? void 0 : _a.node;
if (!node)
break;
if (node.save) { // remember
saved = cp;
}
else if (node.check) { // check exclusion
if (cp === saved)
break;
}
stack.push(cp);
if (node.fe0f) {
stack.push(0xFE0F);
if (pos > 0 && cps[pos - 1] == 0xFE0F)
pos--; // consume optional FE0F
}
if (node.valid) { // this is a valid emoji (so far)
emoji = stack.slice(); // copy stack
if (node.valid == 2)
emoji.splice(1, 1); // delete FE0F at position 1 (RGI ZWJ don't follow spec!)
if (eaten)
eaten.push(...cps.slice(pos).reverse()); // copy input (if needed)
cps.length = pos; // truncate
}
}
return emoji;
}
//# sourceMappingURL=lib.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hash/lib.esm/namehash.js
const namehash_logger = new lib_esm_Logger(hash_lib_esm_version_version);
const Zeros = new Uint8Array(32);
Zeros.fill(0);
function checkComponent(comp) {
if (comp.length === 0) {
throw new Error("invalid ENS name; empty component");
}
return comp;
}
function ensNameSplit(name) {
const bytes = toUtf8Bytes(ens_normalize(name));
const comps = [];
if (name.length === 0) {
return comps;
}
let last = 0;
for (let i = 0; i < bytes.length; i++) {
const d = bytes[i];
// A separator (i.e. "."); copy this component
if (d === 0x2e) {
comps.push(checkComponent(bytes.slice(last, i)));
last = i + 1;
}
}
// There was a stray separator at the end of the name
if (last >= bytes.length) {
throw new Error("invalid ENS name; empty component");
}
comps.push(checkComponent(bytes.slice(last)));
return comps;
}
function ensNormalize(name) {
return ensNameSplit(name).map((comp) => toUtf8String(comp)).join(".");
}
function isValidName(name) {
try {
return (ensNameSplit(name).length !== 0);
}
catch (error) { }
return false;
}
function namehash(name) {
/* istanbul ignore if */
if (typeof (name) !== "string") {
namehash_logger.throwArgumentError("invalid ENS name; not a string", "name", name);
}
let result = Zeros;
const comps = ensNameSplit(name);
while (comps.length) {
result = keccak256(concat([result, keccak256(comps.pop())]));
}
return hexlify(result);
}
function dnsEncode(name) {
return hexlify(concat(ensNameSplit(name).map((comp) => {
// DNS does not allow components over 63 bytes in length
if (comp.length > 63) {
throw new Error("invalid DNS encoded entry; length exceeds 63 bytes");
}
const bytes = new Uint8Array(comp.length + 1);
bytes.set(comp, 1);
bytes[0] = bytes.length - 1;
return bytes;
}))) + "00";
}
//# sourceMappingURL=namehash.js.map
// EXTERNAL MODULE: ./node_modules/hash.js/lib/hash.js
var lib_hash = __webpack_require__(3);
var hash_default = /*#__PURE__*/__webpack_require__.n(lib_hash);
// CONCATENATED MODULE: ./node_modules/@ethersproject/sha2/lib.esm/types.js
var SupportedAlgorithm;
(function (SupportedAlgorithm) {
SupportedAlgorithm["sha256"] = "sha256";
SupportedAlgorithm["sha512"] = "sha512";
})(SupportedAlgorithm || (SupportedAlgorithm = {}));
;
//# sourceMappingURL=types.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/sha2/lib.esm/_version.js
const sha2_lib_esm_version_version = "sha2/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/sha2/lib.esm/sha2.js
//const _ripemd160 = _hash.ripemd160;
const sha2_logger = new lib_esm_Logger(sha2_lib_esm_version_version);
function ripemd160(data) {
return "0x" + (hash_default.a.ripemd160().update(arrayify(data)).digest("hex"));
}
function sha256(data) {
return "0x" + (hash_default.a.sha256().update(arrayify(data)).digest("hex"));
}
function sha512(data) {
return "0x" + (hash_default.a.sha512().update(arrayify(data)).digest("hex"));
}
function computeHmac(algorithm, key, data) {
if (!SupportedAlgorithm[algorithm]) {
sha2_logger.throwError("unsupported algorithm " + algorithm, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "hmac",
algorithm: algorithm
});
}
return "0x" + hash_default.a.hmac(hash_default.a[algorithm], arrayify(key)).update(arrayify(data)).digest("hex");
}
//# sourceMappingURL=sha2.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/web/lib.esm/_version.js
const web_lib_esm_version_version = "web/5.7.1";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/web/lib.esm/geturl.js
var geturl_awaiter = (undefined && undefined.__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());
});
};
function getUrl(href, options) {
return geturl_awaiter(this, void 0, void 0, function* () {
if (options == null) {
options = {};
}
const request = {
method: (options.method || "GET"),
headers: (options.headers || {}),
body: (options.body || undefined),
};
if (options.skipFetchSetup !== true) {
request.mode = "cors"; // no-cors, cors, *same-origin
request.cache = "no-cache"; // *default, no-cache, reload, force-cache, only-if-cached
request.credentials = "same-origin"; // include, *same-origin, omit
request.redirect = "follow"; // manual, *follow, error
request.referrer = "client"; // no-referrer, *client
}
;
if (options.fetchOptions != null) {
const opts = options.fetchOptions;
if (opts.mode) {
request.mode = (opts.mode);
}
if (opts.cache) {
request.cache = (opts.cache);
}
if (opts.credentials) {
request.credentials = (opts.credentials);
}
if (opts.redirect) {
request.redirect = (opts.redirect);
}
if (opts.referrer) {
request.referrer = opts.referrer;
}
}
const response = yield fetch(href, request);
const body = yield response.arrayBuffer();
const headers = {};
if (response.headers.forEach) {
response.headers.forEach((value, key) => {
headers[key.toLowerCase()] = value;
});
}
else {
((response.headers).keys)().forEach((key) => {
headers[key.toLowerCase()] = response.headers.get(key);
});
}
return {
headers: headers,
statusCode: response.status,
statusMessage: response.statusText,
body: arrayify(new Uint8Array(body)),
};
});
}
//# sourceMappingURL=geturl.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/web/lib.esm/index.js
var web_lib_esm_awaiter = (undefined && undefined.__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());
});
};
const web_lib_esm_logger = new lib_esm_Logger(web_lib_esm_version_version);
function staller(duration) {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}
function bodyify(value, type) {
if (value == null) {
return null;
}
if (typeof (value) === "string") {
return value;
}
if (isBytesLike(value)) {
if (type && (type.split("/")[0] === "text" || type.split(";")[0].trim() === "application/json")) {
try {
return toUtf8String(value);
}
catch (error) { }
;
}
return hexlify(value);
}
return value;
}
function unpercent(value) {
return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => {
return String.fromCharCode(parseInt(code, 16));
}));
}
// This API is still a work in progress; the future changes will likely be:
// - ConnectionInfo => FetchDataRequest<T = any>
// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }
// - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified)
// - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T
// For this reason, it should be considered internal until the API is finalized
function _fetchData(connection, body, processFunc) {
// How many times to retry in the event of a throttle
const attemptLimit = (typeof (connection) === "object" && connection.throttleLimit != null) ? connection.throttleLimit : 12;
web_lib_esm_logger.assertArgument((attemptLimit > 0 && (attemptLimit % 1) === 0), "invalid connection throttle limit", "connection.throttleLimit", attemptLimit);
const throttleCallback = ((typeof (connection) === "object") ? connection.throttleCallback : null);
const throttleSlotInterval = ((typeof (connection) === "object" && typeof (connection.throttleSlotInterval) === "number") ? connection.throttleSlotInterval : 100);
web_lib_esm_logger.assertArgument((throttleSlotInterval > 0 && (throttleSlotInterval % 1) === 0), "invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval);
const errorPassThrough = ((typeof (connection) === "object") ? !!(connection.errorPassThrough) : false);
const headers = {};
let url = null;
// @TODO: Allow ConnectionInfo to override some of these values
const options = {
method: "GET",
};
let allow304 = false;
let timeout = 2 * 60 * 1000;
if (typeof (connection) === "string") {
url = connection;
}
else if (typeof (connection) === "object") {
if (connection == null || connection.url == null) {
web_lib_esm_logger.throwArgumentError("missing URL", "connection.url", connection);
}
url = connection.url;
if (typeof (connection.timeout) === "number" && connection.timeout > 0) {
timeout = connection.timeout;
}
if (connection.headers) {
for (const key in connection.headers) {
headers[key.toLowerCase()] = { key: key, value: String(connection.headers[key]) };
if (["if-none-match", "if-modified-since"].indexOf(key.toLowerCase()) >= 0) {
allow304 = true;
}
}
}
options.allowGzip = !!connection.allowGzip;
if (connection.user != null && connection.password != null) {
if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) {
web_lib_esm_logger.throwError("basic authentication requires a secure https url", lib_esm_Logger.errors.INVALID_ARGUMENT, { argument: "url", url: url, user: connection.user, password: "[REDACTED]" });
}
const authorization = connection.user + ":" + connection.password;
headers["authorization"] = {
key: "Authorization",
value: "Basic " + encode(toUtf8Bytes(authorization))
};
}
if (connection.skipFetchSetup != null) {
options.skipFetchSetup = !!connection.skipFetchSetup;
}
if (connection.fetchOptions != null) {
options.fetchOptions = shallowCopy(connection.fetchOptions);
}
}
const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i");
const dataMatch = ((url) ? url.match(reData) : null);
if (dataMatch) {
try {
const response = {
statusCode: 200,
statusMessage: "OK",
headers: { "content-type": (dataMatch[1] || "text/plain") },
body: (dataMatch[2] ? decode(dataMatch[3]) : unpercent(dataMatch[3]))
};
let result = response.body;
if (processFunc) {
result = processFunc(response.body, response);
}
return Promise.resolve(result);
}
catch (error) {
web_lib_esm_logger.throwError("processing response error", lib_esm_Logger.errors.SERVER_ERROR, {
body: bodyify(dataMatch[1], dataMatch[2]),
error: error,
requestBody: null,
requestMethod: "GET",
url: url
});
}
}
if (body) {
options.method = "POST";
options.body = body;
if (headers["content-type"] == null) {
headers["content-type"] = { key: "Content-Type", value: "application/octet-stream" };
}
if (headers["content-length"] == null) {
headers["content-length"] = { key: "Content-Length", value: String(body.length) };
}
}
const flatHeaders = {};
Object.keys(headers).forEach((key) => {
const header = headers[key];
flatHeaders[header.key] = header.value;
});
options.headers = flatHeaders;
const runningTimeout = (function () {
let timer = null;
const promise = new Promise(function (resolve, reject) {
if (timeout) {
timer = setTimeout(() => {
if (timer == null) {
return;
}
timer = null;
reject(web_lib_esm_logger.makeError("timeout", lib_esm_Logger.errors.TIMEOUT, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
timeout: timeout,
url: url
}));
}, timeout);
}
});
const cancel = function () {
if (timer == null) {
return;
}
clearTimeout(timer);
timer = null;
};
return { promise, cancel };
})();
const runningFetch = (function () {
return web_lib_esm_awaiter(this, void 0, void 0, function* () {
for (let attempt = 0; attempt < attemptLimit; attempt++) {
let response = null;
try {
response = yield getUrl(url, options);
if (attempt < attemptLimit) {
if (response.statusCode === 301 || response.statusCode === 302) {
// Redirection; for now we only support absolute locataions
const location = response.headers.location || "";
if (options.method === "GET" && location.match(/^https:/)) {
url = response.headers.location;
continue;
}
}
else if (response.statusCode === 429) {
// Exponential back-off throttling
let tryAgain = true;
if (throttleCallback) {
tryAgain = yield throttleCallback(attempt, url);
}
if (tryAgain) {
let stall = 0;
const retryAfter = response.headers["retry-after"];
if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
stall = parseInt(retryAfter) * 1000;
}
else {
stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
}
//console.log("Stalling 429");
yield staller(stall);
continue;
}
}
}
}
catch (error) {
response = error.response;
if (response == null) {
runningTimeout.cancel();
web_lib_esm_logger.throwError("missing response", lib_esm_Logger.errors.SERVER_ERROR, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
serverError: error,
url: url
});
}
}
let body = response.body;
if (allow304 && response.statusCode === 304) {
body = null;
}
else if (!errorPassThrough && (response.statusCode < 200 || response.statusCode >= 300)) {
runningTimeout.cancel();
web_lib_esm_logger.throwError("bad response", lib_esm_Logger.errors.SERVER_ERROR, {
status: response.statusCode,
headers: response.headers,
body: bodyify(body, ((response.headers) ? response.headers["content-type"] : null)),
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
});
}
if (processFunc) {
try {
const result = yield processFunc(body, response);
runningTimeout.cancel();
return result;
}
catch (error) {
// Allow the processFunc to trigger a throttle
if (error.throttleRetry && attempt < attemptLimit) {
let tryAgain = true;
if (throttleCallback) {
tryAgain = yield throttleCallback(attempt, url);
}
if (tryAgain) {
const timeout = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
//console.log("Stalling callback");
yield staller(timeout);
continue;
}
}
runningTimeout.cancel();
web_lib_esm_logger.throwError("processing response error", lib_esm_Logger.errors.SERVER_ERROR, {
body: bodyify(body, ((response.headers) ? response.headers["content-type"] : null)),
error: error,
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
});
}
}
runningTimeout.cancel();
// If we had a processFunc, it either returned a T or threw above.
// The "body" is now a Uint8Array.
return body;
}
return web_lib_esm_logger.throwError("failed response", lib_esm_Logger.errors.SERVER_ERROR, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
});
});
})();
return Promise.race([runningTimeout.promise, runningFetch]);
}
function fetchJson(connection, json, processFunc) {
let processJsonFunc = (value, response) => {
let result = null;
if (value != null) {
try {
result = JSON.parse(toUtf8String(value));
}
catch (error) {
web_lib_esm_logger.throwError("invalid JSON", lib_esm_Logger.errors.SERVER_ERROR, {
body: value,
error: error
});
}
}
if (processFunc) {
result = processFunc(result, response);
}
return result;
};
// If we have json to send, we must
// - add content-type of application/json (unless already overridden)
// - convert the json to bytes
let body = null;
if (json != null) {
body = toUtf8Bytes(json);
// Create a connection with the content-type set for JSON
const updated = (typeof (connection) === "string") ? ({ url: connection }) : shallowCopy(connection);
if (updated.headers) {
const hasContentType = (Object.keys(updated.headers).filter((k) => (k.toLowerCase() === "content-type")).length) !== 0;
if (!hasContentType) {
updated.headers = shallowCopy(updated.headers);
updated.headers["content-type"] = "application/json";
}
}
else {
updated.headers = { "content-type": "application/json" };
}
connection = updated;
}
return _fetchData(connection, body, processJsonFunc);
}
function lib_esm_poll(func, options) {
if (!options) {
options = {};
}
options = shallowCopy(options);
if (options.floor == null) {
options.floor = 0;
}
if (options.ceiling == null) {
options.ceiling = 10000;
}
if (options.interval == null) {
options.interval = 250;
}
return new Promise(function (resolve, reject) {
let timer = null;
let done = false;
// Returns true if cancel was successful. Unsuccessful cancel means we're already done.
const cancel = () => {
if (done) {
return false;
}
done = true;
if (timer) {
clearTimeout(timer);
}
return true;
};
if (options.timeout) {
timer = setTimeout(() => {
if (cancel()) {
reject(new Error("timeout"));
}
}, options.timeout);
}
const retryLimit = options.retryLimit;
let attempt = 0;
function check() {
return func().then(function (result) {
// If we have a result, or are allowed null then we're done
if (result !== undefined) {
if (cancel()) {
resolve(result);
}
}
else if (options.oncePoll) {
options.oncePoll.once("poll", check);
}
else if (options.onceBlock) {
options.onceBlock.once("block", check);
// Otherwise, exponential back-off (up to 10s) our next request
}
else if (!done) {
attempt++;
if (attempt > retryLimit) {
if (cancel()) {
reject(new Error("retry limit reached"));
}
return;
}
let timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt)));
if (timeout < options.floor) {
timeout = options.floor;
}
if (timeout > options.ceiling) {
timeout = options.ceiling;
}
setTimeout(check, timeout);
}
return null;
}, function (error) {
if (cancel()) {
reject(error);
}
});
}
check();
});
}
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: ./node_modules/bech32/index.js
var bech32 = __webpack_require__(20);
var bech32_default = /*#__PURE__*/__webpack_require__.n(bech32);
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/_version.js
const providers_lib_esm_version_version = "providers/5.7.2";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/rlp/lib.esm/_version.js
const rlp_lib_esm_version_version = "rlp/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/rlp/lib.esm/index.js
//See: https://github.com/ethereum/wiki/wiki/RLP
const rlp_lib_esm_logger = new lib_esm_Logger(rlp_lib_esm_version_version);
function arrayifyInteger(value) {
const result = [];
while (value) {
result.unshift(value & 0xff);
value >>= 8;
}
return result;
}
function unarrayifyInteger(data, offset, length) {
let result = 0;
for (let i = 0; i < length; i++) {
result = (result * 256) + data[offset + i];
}
return result;
}
function _encode(object) {
if (Array.isArray(object)) {
let payload = [];
object.forEach(function (child) {
payload = payload.concat(_encode(child));
});
if (payload.length <= 55) {
payload.unshift(0xc0 + payload.length);
return payload;
}
const length = arrayifyInteger(payload.length);
length.unshift(0xf7 + length.length);
return length.concat(payload);
}
if (!isBytesLike(object)) {
rlp_lib_esm_logger.throwArgumentError("RLP object must be BytesLike", "object", object);
}
const data = Array.prototype.slice.call(arrayify(object));
if (data.length === 1 && data[0] <= 0x7f) {
return data;
}
else if (data.length <= 55) {
data.unshift(0x80 + data.length);
return data;
}
const length = arrayifyInteger(data.length);
length.unshift(0xb7 + length.length);
return length.concat(data);
}
function lib_esm_encode(object) {
return hexlify(_encode(object));
}
function _decodeChildren(data, offset, childOffset, length) {
const result = [];
while (childOffset < offset + 1 + length) {
const decoded = _decode(data, childOffset);
result.push(decoded.result);
childOffset += decoded.consumed;
if (childOffset > offset + 1 + length) {
rlp_lib_esm_logger.throwError("child data too short", lib_esm_Logger.errors.BUFFER_OVERRUN, {});
}
}
return { consumed: (1 + length), result: result };
}
// returns { consumed: number, result: Object }
function _decode(data, offset) {
if (data.length === 0) {
rlp_lib_esm_logger.throwError("data too short", lib_esm_Logger.errors.BUFFER_OVERRUN, {});
}
// Array with extra length prefix
if (data[offset] >= 0xf8) {
const lengthLength = data[offset] - 0xf7;
if (offset + 1 + lengthLength > data.length) {
rlp_lib_esm_logger.throwError("data short segment too short", lib_esm_Logger.errors.BUFFER_OVERRUN, {});
}
const length = unarrayifyInteger(data, offset + 1, lengthLength);
if (offset + 1 + lengthLength + length > data.length) {
rlp_lib_esm_logger.throwError("data long segment too short", lib_esm_Logger.errors.BUFFER_OVERRUN, {});
}
return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);
}
else if (data[offset] >= 0xc0) {
const length = data[offset] - 0xc0;
if (offset + 1 + length > data.length) {
rlp_lib_esm_logger.throwError("data array too short", lib_esm_Logger.errors.BUFFER_OVERRUN, {});
}
return _decodeChildren(data, offset, offset + 1, length);
}
else if (data[offset] >= 0xb8) {
const lengthLength = data[offset] - 0xb7;
if (offset + 1 + lengthLength > data.length) {
rlp_lib_esm_logger.throwError("data array too short", lib_esm_Logger.errors.BUFFER_OVERRUN, {});
}
const length = unarrayifyInteger(data, offset + 1, lengthLength);
if (offset + 1 + lengthLength + length > data.length) {
rlp_lib_esm_logger.throwError("data array too short", lib_esm_Logger.errors.BUFFER_OVERRUN, {});
}
const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));
return { consumed: (1 + lengthLength + length), result: result };
}
else if (data[offset] >= 0x80) {
const length = data[offset] - 0x80;
if (offset + 1 + length > data.length) {
rlp_lib_esm_logger.throwError("data too short", lib_esm_Logger.errors.BUFFER_OVERRUN, {});
}
const result = hexlify(data.slice(offset + 1, offset + 1 + length));
return { consumed: (1 + length), result: result };
}
return { consumed: 1, result: hexlify(data[offset]) };
}
function lib_esm_decode(data) {
const bytes = arrayify(data);
const decoded = _decode(bytes, 0);
if (decoded.consumed !== bytes.length) {
rlp_lib_esm_logger.throwArgumentError("invalid rlp data", "data", data);
}
return decoded.result;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/address/lib.esm/_version.js
const address_lib_esm_version_version = "address/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/address/lib.esm/index.js
const address_lib_esm_logger = new lib_esm_Logger(address_lib_esm_version_version);
function getChecksumAddress(address) {
if (!isHexString(address, 20)) {
address_lib_esm_logger.throwArgumentError("invalid address", "address", address);
}
address = address.toLowerCase();
const chars = address.substring(2).split("");
const expanded = new Uint8Array(40);
for (let i = 0; i < 40; i++) {
expanded[i] = chars[i].charCodeAt(0);
}
const hashed = arrayify(keccak256(expanded));
for (let i = 0; i < 40; i += 2) {
if ((hashed[i >> 1] >> 4) >= 8) {
chars[i] = chars[i].toUpperCase();
}
if ((hashed[i >> 1] & 0x0f) >= 8) {
chars[i + 1] = chars[i + 1].toUpperCase();
}
}
return "0x" + chars.join("");
}
// Shims for environments that are missing some required constants and functions
const MAX_SAFE_INTEGER = 0x1fffffffffffff;
function log10(x) {
if (Math.log10) {
return Math.log10(x);
}
return Math.log(x) / Math.LN10;
}
// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number
// Create lookup table
const ibanLookup = {};
for (let i = 0; i < 10; i++) {
ibanLookup[String(i)] = String(i);
}
for (let i = 0; i < 26; i++) {
ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);
}
// How many decimal digits can we process? (for 64-bit float, this is 15)
const safeDigits = Math.floor(log10(MAX_SAFE_INTEGER));
function ibanChecksum(address) {
address = address.toUpperCase();
address = address.substring(4) + address.substring(0, 2) + "00";
let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join("");
// Javascript can handle integers safely up to 15 (decimal) digits
while (expanded.length >= safeDigits) {
let block = expanded.substring(0, safeDigits);
expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);
}
let checksum = String(98 - (parseInt(expanded, 10) % 97));
while (checksum.length < 2) {
checksum = "0" + checksum;
}
return checksum;
}
;
function getAddress(address) {
let result = null;
if (typeof (address) !== "string") {
address_lib_esm_logger.throwArgumentError("invalid address", "address", address);
}
if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
// Missing the 0x prefix
if (address.substring(0, 2) !== "0x") {
address = "0x" + address;
}
result = getChecksumAddress(address);
// It is a checksummed address with a bad checksum
if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) {
address_lib_esm_logger.throwArgumentError("bad address checksum", "address", address);
}
// Maybe ICAP? (we only support direct mode)
}
else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
// It is an ICAP address with a bad checksum
if (address.substring(2, 4) !== ibanChecksum(address)) {
address_lib_esm_logger.throwArgumentError("bad icap checksum", "address", address);
}
result = _base36To16(address.substring(4));
while (result.length < 40) {
result = "0" + result;
}
result = getChecksumAddress("0x" + result);
}
else {
address_lib_esm_logger.throwArgumentError("invalid address", "address", address);
}
return result;
}
function isAddress(address) {
try {
getAddress(address);
return true;
}
catch (error) { }
return false;
}
function getIcapAddress(address) {
let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase();
while (base36.length < 30) {
base36 = "0" + base36;
}
return "XE" + ibanChecksum("XE00" + base36) + base36;
}
// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
function getContractAddress(transaction) {
let from = null;
try {
from = getAddress(transaction.from);
}
catch (error) {
address_lib_esm_logger.throwArgumentError("missing from address", "transaction", transaction);
}
const nonce = stripZeros(arrayify(bignumber_BigNumber.from(transaction.nonce).toHexString()));
return getAddress(hexDataSlice(keccak256(lib_esm_encode([from, nonce])), 12));
}
function getCreate2Address(from, salt, initCodeHash) {
if (hexDataLength(salt) !== 32) {
address_lib_esm_logger.throwArgumentError("salt must be 32 bytes", "salt", salt);
}
if (hexDataLength(initCodeHash) !== 32) {
address_lib_esm_logger.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", initCodeHash);
}
return getAddress(hexDataSlice(keccak256(concat(["0xff", getAddress(from), salt, initCodeHash])), 12));
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/constants/lib.esm/addresses.js
const AddressZero = "0x0000000000000000000000000000000000000000";
//# sourceMappingURL=addresses.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/constants/lib.esm/bignumbers.js
const NegativeOne = ( /*#__PURE__*/bignumber_BigNumber.from(-1));
const Zero = ( /*#__PURE__*/bignumber_BigNumber.from(0));
const One = ( /*#__PURE__*/bignumber_BigNumber.from(1));
const Two = ( /*#__PURE__*/bignumber_BigNumber.from(2));
const WeiPerEther = ( /*#__PURE__*/bignumber_BigNumber.from("1000000000000000000"));
const MaxUint256 = ( /*#__PURE__*/bignumber_BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
const MinInt256 = ( /*#__PURE__*/bignumber_BigNumber.from("-0x8000000000000000000000000000000000000000000000000000000000000000"));
const MaxInt256 = ( /*#__PURE__*/bignumber_BigNumber.from("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
//# sourceMappingURL=bignumbers.js.map
// EXTERNAL MODULE: ./node_modules/@ethersproject/signing-key/node_modules/bn.js/lib/bn.js
var lib_bn = __webpack_require__(0);
var lib_bn_default = /*#__PURE__*/__webpack_require__.n(lib_bn);
// CONCATENATED MODULE: ./node_modules/@ethersproject/signing-key/lib.esm/elliptic.js
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function getDefaultExportFromNamespaceIfPresent (n) {
return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
}
function getDefaultExportFromNamespaceIfNotNamed (n) {
return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
}
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var a = Object.defineProperty({}, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var minimalisticAssert = elliptic_assert;
function elliptic_assert(val, msg) {
if (!val)
throw new Error(msg || 'Assertion failed');
}
elliptic_assert.equal = function assertEqual(l, r, msg) {
if (l != r)
throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
};
var utils_1 = createCommonjsModule(function (module, exports) {
'use strict';
var utils = exports;
function toArray(msg, enc) {
if (Array.isArray(msg))
return msg.slice();
if (!msg)
return [];
var res = [];
if (typeof msg !== 'string') {
for (var i = 0; i < msg.length; i++)
res[i] = msg[i] | 0;
return res;
}
if (enc === 'hex') {
msg = msg.replace(/[^a-z0-9]+/ig, '');
if (msg.length % 2 !== 0)
msg = '0' + msg;
for (var i = 0; i < msg.length; i += 2)
res.push(parseInt(msg[i] + msg[i + 1], 16));
} else {
for (var i = 0; i < msg.length; i++) {
var c = msg.charCodeAt(i);
var hi = c >> 8;
var lo = c & 0xff;
if (hi)
res.push(hi, lo);
else
res.push(lo);
}
}
return res;
}
utils.toArray = toArray;
function zero2(word) {
if (word.length === 1)
return '0' + word;
else
return word;
}
utils.zero2 = zero2;
function toHex(msg) {
var res = '';
for (var i = 0; i < msg.length; i++)
res += zero2(msg[i].toString(16));
return res;
}
utils.toHex = toHex;
utils.encode = function encode(arr, enc) {
if (enc === 'hex')
return toHex(arr);
else
return arr;
};
});
var utils_1$1 = createCommonjsModule(function (module, exports) {
'use strict';
var utils = exports;
utils.assert = minimalisticAssert;
utils.toArray = utils_1.toArray;
utils.zero2 = utils_1.zero2;
utils.toHex = utils_1.toHex;
utils.encode = utils_1.encode;
// Represent num in a w-NAF form
function getNAF(num, w, bits) {
var naf = new Array(Math.max(num.bitLength(), bits) + 1);
naf.fill(0);
var ws = 1 << (w + 1);
var k = num.clone();
for (var i = 0; i < naf.length; i++) {
var z;
var mod = k.andln(ws - 1);
if (k.isOdd()) {
if (mod > (ws >> 1) - 1)
z = (ws >> 1) - mod;
else
z = mod;
k.isubn(z);
} else {
z = 0;
}
naf[i] = z;
k.iushrn(1);
}
return naf;
}
utils.getNAF = getNAF;
// Represent k1, k2 in a Joint Sparse Form
function getJSF(k1, k2) {
var jsf = [
[],
[],
];
k1 = k1.clone();
k2 = k2.clone();
var d1 = 0;
var d2 = 0;
var m8;
while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
// First phase
var m14 = (k1.andln(3) + d1) & 3;
var m24 = (k2.andln(3) + d2) & 3;
if (m14 === 3)
m14 = -1;
if (m24 === 3)
m24 = -1;
var u1;
if ((m14 & 1) === 0) {
u1 = 0;
} else {
m8 = (k1.andln(7) + d1) & 7;
if ((m8 === 3 || m8 === 5) && m24 === 2)
u1 = -m14;
else
u1 = m14;
}
jsf[0].push(u1);
var u2;
if ((m24 & 1) === 0) {
u2 = 0;
} else {
m8 = (k2.andln(7) + d2) & 7;
if ((m8 === 3 || m8 === 5) && m14 === 2)
u2 = -m24;
else
u2 = m24;
}
jsf[1].push(u2);
// Second phase
if (2 * d1 === u1 + 1)
d1 = 1 - d1;
if (2 * d2 === u2 + 1)
d2 = 1 - d2;
k1.iushrn(1);
k2.iushrn(1);
}
return jsf;
}
utils.getJSF = getJSF;
function cachedProperty(obj, name, computer) {
var key = '_' + name;
obj.prototype[name] = function cachedProperty() {
return this[key] !== undefined ? this[key] :
this[key] = computer.call(this);
};
}
utils.cachedProperty = cachedProperty;
function parseBytes(bytes) {
return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
bytes;
}
utils.parseBytes = parseBytes;
function intFromLE(bytes) {
return new lib_bn_default.a(bytes, 'hex', 'le');
}
utils.intFromLE = intFromLE;
});
'use strict';
var elliptic_getNAF = utils_1$1.getNAF;
var elliptic_getJSF = utils_1$1.getJSF;
var assert$1 = utils_1$1.assert;
function BaseCurve(type, conf) {
this.type = type;
this.p = new lib_bn_default.a(conf.p, 16);
// Use Montgomery, when there is no fast reduction for the prime
this.red = conf.prime ? lib_bn_default.a.red(conf.prime) : lib_bn_default.a.mont(this.p);
// Useful for many curves
this.zero = new lib_bn_default.a(0).toRed(this.red);
this.one = new lib_bn_default.a(1).toRed(this.red);
this.two = new lib_bn_default.a(2).toRed(this.red);
// Curve configuration, optional
this.n = conf.n && new lib_bn_default.a(conf.n, 16);
this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
// Temporary arrays
this._wnafT1 = new Array(4);
this._wnafT2 = new Array(4);
this._wnafT3 = new Array(4);
this._wnafT4 = new Array(4);
this._bitLength = this.n ? this.n.bitLength() : 0;
// Generalized Greg Maxwell's trick
var adjustCount = this.n && this.p.div(this.n);
if (!adjustCount || adjustCount.cmpn(100) > 0) {
this.redN = null;
} else {
this._maxwellTrick = true;
this.redN = this.n.toRed(this.red);
}
}
var base = BaseCurve;
BaseCurve.prototype.point = function point() {
throw new Error('Not implemented');
};
BaseCurve.prototype.validate = function validate() {
throw new Error('Not implemented');
};
BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
assert$1(p.precomputed);
var doubles = p._getDoubles();
var naf = elliptic_getNAF(k, 1, this._bitLength);
var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
I /= 3;
// Translate into more windowed form
var repr = [];
var j;
var nafW;
for (j = 0; j < naf.length; j += doubles.step) {
nafW = 0;
for (var l = j + doubles.step - 1; l >= j; l--)
nafW = (nafW << 1) + naf[l];
repr.push(nafW);
}
var a = this.jpoint(null, null, null);
var b = this.jpoint(null, null, null);
for (var i = I; i > 0; i--) {
for (j = 0; j < repr.length; j++) {
nafW = repr[j];
if (nafW === i)
b = b.mixedAdd(doubles.points[j]);
else if (nafW === -i)
b = b.mixedAdd(doubles.points[j].neg());
}
a = a.add(b);
}
return a.toP();
};
BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
var w = 4;
// Precompute window
var nafPoints = p._getNAFPoints(w);
w = nafPoints.wnd;
var wnd = nafPoints.points;
// Get NAF form
var naf = elliptic_getNAF(k, w, this._bitLength);
// Add `this`*(N+1) for every w-NAF index
var acc = this.jpoint(null, null, null);
for (var i = naf.length - 1; i >= 0; i--) {
// Count zeroes
for (var l = 0; i >= 0 && naf[i] === 0; i--)
l++;
if (i >= 0)
l++;
acc = acc.dblp(l);
if (i < 0)
break;
var z = naf[i];
assert$1(z !== 0);
if (p.type === 'affine') {
// J +- P
if (z > 0)
acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
else
acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
} else {
// J +- J
if (z > 0)
acc = acc.add(wnd[(z - 1) >> 1]);
else
acc = acc.add(wnd[(-z - 1) >> 1].neg());
}
}
return p.type === 'affine' ? acc.toP() : acc;
};
BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
points,
coeffs,
len,
jacobianResult) {
var wndWidth = this._wnafT1;
var wnd = this._wnafT2;
var naf = this._wnafT3;
// Fill all arrays
var max = 0;
var i;
var j;
var p;
for (i = 0; i < len; i++) {
p = points[i];
var nafPoints = p._getNAFPoints(defW);
wndWidth[i] = nafPoints.wnd;
wnd[i] = nafPoints.points;
}
// Comb small window NAFs
for (i = len - 1; i >= 1; i -= 2) {
var a = i - 1;
var b = i;
if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
naf[a] = elliptic_getNAF(coeffs[a], wndWidth[a], this._bitLength);
naf[b] = elliptic_getNAF(coeffs[b], wndWidth[b], this._bitLength);
max = Math.max(naf[a].length, max);
max = Math.max(naf[b].length, max);
continue;
}
var comb = [
points[a], /* 1 */
null, /* 3 */
null, /* 5 */
points[b], /* 7 */
];
// Try to avoid Projective points, if possible
if (points[a].y.cmp(points[b].y) === 0) {
comb[1] = points[a].add(points[b]);
comb[2] = points[a].toJ().mixedAdd(points[b].neg());
} else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
comb[1] = points[a].toJ().mixedAdd(points[b]);
comb[2] = points[a].add(points[b].neg());
} else {
comb[1] = points[a].toJ().mixedAdd(points[b]);
comb[2] = points[a].toJ().mixedAdd(points[b].neg());
}
var index = [
-3, /* -1 -1 */
-1, /* -1 0 */
-5, /* -1 1 */
-7, /* 0 -1 */
0, /* 0 0 */
7, /* 0 1 */
5, /* 1 -1 */
1, /* 1 0 */
3, /* 1 1 */
];
var jsf = elliptic_getJSF(coeffs[a], coeffs[b]);
max = Math.max(jsf[0].length, max);
naf[a] = new Array(max);
naf[b] = new Array(max);
for (j = 0; j < max; j++) {
var ja = jsf[0][j] | 0;
var jb = jsf[1][j] | 0;
naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
naf[b][j] = 0;
wnd[a] = comb;
}
}
var acc = this.jpoint(null, null, null);
var tmp = this._wnafT4;
for (i = max; i >= 0; i--) {
var k = 0;
while (i >= 0) {
var zero = true;
for (j = 0; j < len; j++) {
tmp[j] = naf[j][i] | 0;
if (tmp[j] !== 0)
zero = false;
}
if (!zero)
break;
k++;
i--;
}
if (i >= 0)
k++;
acc = acc.dblp(k);
if (i < 0)
break;
for (j = 0; j < len; j++) {
var z = tmp[j];
p;
if (z === 0)
continue;
else if (z > 0)
p = wnd[j][(z - 1) >> 1];
else if (z < 0)
p = wnd[j][(-z - 1) >> 1].neg();
if (p.type === 'affine')
acc = acc.mixedAdd(p);
else
acc = acc.add(p);
}
}
// Zeroify references
for (i = 0; i < len; i++)
wnd[i] = null;
if (jacobianResult)
return acc;
else
return acc.toP();
};
function BasePoint(curve, type) {
this.curve = curve;
this.type = type;
this.precomputed = null;
}
BaseCurve.BasePoint = BasePoint;
BasePoint.prototype.eq = function eq(/*other*/) {
throw new Error('Not implemented');
};
BasePoint.prototype.validate = function validate() {
return this.curve.validate(this);
};
BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
bytes = utils_1$1.toArray(bytes, enc);
var len = this.p.byteLength();
// uncompressed, hybrid-odd, hybrid-even
if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
bytes.length - 1 === 2 * len) {
if (bytes[0] === 0x06)
assert$1(bytes[bytes.length - 1] % 2 === 0);
else if (bytes[0] === 0x07)
assert$1(bytes[bytes.length - 1] % 2 === 1);
var res = this.point(bytes.slice(1, 1 + len),
bytes.slice(1 + len, 1 + 2 * len));
return res;
} else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
bytes.length - 1 === len) {
return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
}
throw new Error('Unknown point format');
};
BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
return this.encode(enc, true);
};
BasePoint.prototype._encode = function _encode(compact) {
var len = this.curve.p.byteLength();
var x = this.getX().toArray('be', len);
if (compact)
return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
return [ 0x04 ].concat(x, this.getY().toArray('be', len));
};
BasePoint.prototype.encode = function encode(enc, compact) {
return utils_1$1.encode(this._encode(compact), enc);
};
BasePoint.prototype.precompute = function precompute(power) {
if (this.precomputed)
return this;
var precomputed = {
doubles: null,
naf: null,
beta: null,
};
precomputed.naf = this._getNAFPoints(8);
precomputed.doubles = this._getDoubles(4, power);
precomputed.beta = this._getBeta();
this.precomputed = precomputed;
return this;
};
BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
if (!this.precomputed)
return false;
var doubles = this.precomputed.doubles;
if (!doubles)
return false;
return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
};
BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
if (this.precomputed && this.precomputed.doubles)
return this.precomputed.doubles;
var doubles = [ this ];
var acc = this;
for (var i = 0; i < power; i += step) {
for (var j = 0; j < step; j++)
acc = acc.dbl();
doubles.push(acc);
}
return {
step: step,
points: doubles,
};
};
BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
if (this.precomputed && this.precomputed.naf)
return this.precomputed.naf;
var res = [ this ];
var max = (1 << wnd) - 1;
var dbl = max === 1 ? null : this.dbl();
for (var i = 1; i < max; i++)
res[i] = res[i - 1].add(dbl);
return {
wnd: wnd,
points: res,
};
};
BasePoint.prototype._getBeta = function _getBeta() {
return null;
};
BasePoint.prototype.dblp = function dblp(k) {
var r = this;
for (var i = 0; i < k; i++)
r = r.dbl();
return r;
};
var inherits_browser = createCommonjsModule(function (module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
};
}
});
'use strict';
var assert$2 = utils_1$1.assert;
function ShortCurve(conf) {
base.call(this, 'short', conf);
this.a = new lib_bn_default.a(conf.a, 16).toRed(this.red);
this.b = new lib_bn_default.a(conf.b, 16).toRed(this.red);
this.tinv = this.two.redInvm();
this.zeroA = this.a.fromRed().cmpn(0) === 0;
this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
// If the curve is endomorphic, precalculate beta and lambda
this.endo = this._getEndomorphism(conf);
this._endoWnafT1 = new Array(4);
this._endoWnafT2 = new Array(4);
}
inherits_browser(ShortCurve, base);
var short_1 = ShortCurve;
ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
// No efficient endomorphism
if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
return;
// Compute beta and lambda, that lambda * P = (beta * Px; Py)
var beta;
var lambda;
if (conf.beta) {
beta = new lib_bn_default.a(conf.beta, 16).toRed(this.red);
} else {
var betas = this._getEndoRoots(this.p);
// Choose the smallest beta
beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
beta = beta.toRed(this.red);
}
if (conf.lambda) {
lambda = new lib_bn_default.a(conf.lambda, 16);
} else {
// Choose the lambda that is matching selected beta
var lambdas = this._getEndoRoots(this.n);
if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
lambda = lambdas[0];
} else {
lambda = lambdas[1];
assert$2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
}
}
// Get basis vectors, used for balanced length-two representation
var basis;
if (conf.basis) {
basis = conf.basis.map(function(vec) {
return {
a: new lib_bn_default.a(vec.a, 16),
b: new lib_bn_default.a(vec.b, 16),
};
});
} else {
basis = this._getEndoBasis(lambda);
}
return {
beta: beta,
lambda: lambda,
basis: basis,
};
};
ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
// Find roots of for x^2 + x + 1 in F
// Root = (-1 +- Sqrt(-3)) / 2
//
var red = num === this.p ? this.red : lib_bn_default.a.mont(num);
var tinv = new lib_bn_default.a(2).toRed(red).redInvm();
var ntinv = tinv.redNeg();
var s = new lib_bn_default.a(3).toRed(red).redNeg().redSqrt().redMul(tinv);
var l1 = ntinv.redAdd(s).fromRed();
var l2 = ntinv.redSub(s).fromRed();
return [ l1, l2 ];
};
ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
// aprxSqrt >= sqrt(this.n)
var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
// 3.74
// Run EGCD, until r(L + 1) < aprxSqrt
var u = lambda;
var v = this.n.clone();
var x1 = new lib_bn_default.a(1);
var y1 = new lib_bn_default.a(0);
var x2 = new lib_bn_default.a(0);
var y2 = new lib_bn_default.a(1);
// NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
var a0;
var b0;
// First vector
var a1;
var b1;
// Second vector
var a2;
var b2;
var prevR;
var i = 0;
var r;
var x;
while (u.cmpn(0) !== 0) {
var q = v.div(u);
r = v.sub(q.mul(u));
x = x2.sub(q.mul(x1));
var y = y2.sub(q.mul(y1));
if (!a1 && r.cmp(aprxSqrt) < 0) {
a0 = prevR.neg();
b0 = x1;
a1 = r.neg();
b1 = x;
} else if (a1 && ++i === 2) {
break;
}
prevR = r;
v = u;
u = r;
x2 = x1;
x1 = x;
y2 = y1;
y1 = y;
}
a2 = r.neg();
b2 = x;
var len1 = a1.sqr().add(b1.sqr());
var len2 = a2.sqr().add(b2.sqr());
if (len2.cmp(len1) >= 0) {
a2 = a0;
b2 = b0;
}
// Normalize signs
if (a1.negative) {
a1 = a1.neg();
b1 = b1.neg();
}
if (a2.negative) {
a2 = a2.neg();
b2 = b2.neg();
}
return [
{ a: a1, b: b1 },
{ a: a2, b: b2 },
];
};
ShortCurve.prototype._endoSplit = function _endoSplit(k) {
var basis = this.endo.basis;
var v1 = basis[0];
var v2 = basis[1];
var c1 = v2.b.mul(k).divRound(this.n);
var c2 = v1.b.neg().mul(k).divRound(this.n);
var p1 = c1.mul(v1.a);
var p2 = c2.mul(v2.a);
var q1 = c1.mul(v1.b);
var q2 = c2.mul(v2.b);
// Calculate answer
var k1 = k.sub(p1).sub(p2);
var k2 = q1.add(q2).neg();
return { k1: k1, k2: k2 };
};
ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
x = new lib_bn_default.a(x, 16);
if (!x.red)
x = x.toRed(this.red);
var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
var y = y2.redSqrt();
if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
throw new Error('invalid point');
// XXX Is there any way to tell if the number is odd without converting it
// to non-red form?
var isOdd = y.fromRed().isOdd();
if (odd && !isOdd || !odd && isOdd)
y = y.redNeg();
return this.point(x, y);
};
ShortCurve.prototype.validate = function validate(point) {
if (point.inf)
return true;
var x = point.x;
var y = point.y;
var ax = this.a.redMul(x);
var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
return y.redSqr().redISub(rhs).cmpn(0) === 0;
};
ShortCurve.prototype._endoWnafMulAdd =
function _endoWnafMulAdd(points, coeffs, jacobianResult) {
var npoints = this._endoWnafT1;
var ncoeffs = this._endoWnafT2;
for (var i = 0; i < points.length; i++) {
var split = this._endoSplit(coeffs[i]);
var p = points[i];
var beta = p._getBeta();
if (split.k1.negative) {
split.k1.ineg();
p = p.neg(true);
}
if (split.k2.negative) {
split.k2.ineg();
beta = beta.neg(true);
}
npoints[i * 2] = p;
npoints[i * 2 + 1] = beta;
ncoeffs[i * 2] = split.k1;
ncoeffs[i * 2 + 1] = split.k2;
}
var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
// Clean-up references to points and coefficients
for (var j = 0; j < i * 2; j++) {
npoints[j] = null;
ncoeffs[j] = null;
}
return res;
};
function Point(curve, x, y, isRed) {
base.BasePoint.call(this, curve, 'affine');
if (x === null && y === null) {
this.x = null;
this.y = null;
this.inf = true;
} else {
this.x = new lib_bn_default.a(x, 16);
this.y = new lib_bn_default.a(y, 16);
// Force redgomery representation when loading from JSON
if (isRed) {
this.x.forceRed(this.curve.red);
this.y.forceRed(this.curve.red);
}
if (!this.x.red)
this.x = this.x.toRed(this.curve.red);
if (!this.y.red)
this.y = this.y.toRed(this.curve.red);
this.inf = false;
}
}
inherits_browser(Point, base.BasePoint);
ShortCurve.prototype.point = function point(x, y, isRed) {
return new Point(this, x, y, isRed);
};
ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
return Point.fromJSON(this, obj, red);
};
Point.prototype._getBeta = function _getBeta() {
if (!this.curve.endo)
return;
var pre = this.precomputed;
if (pre && pre.beta)
return pre.beta;
var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
if (pre) {
var curve = this.curve;
var endoMul = function(p) {
return curve.point(p.x.redMul(curve.endo.beta), p.y);
};
pre.beta = beta;
beta.precomputed = {
beta: null,
naf: pre.naf && {
wnd: pre.naf.wnd,
points: pre.naf.points.map(endoMul),
},
doubles: pre.doubles && {
step: pre.doubles.step,
points: pre.doubles.points.map(endoMul),
},
};
}
return beta;
};
Point.prototype.toJSON = function toJSON() {
if (!this.precomputed)
return [ this.x, this.y ];
return [ this.x, this.y, this.precomputed && {
doubles: this.precomputed.doubles && {
step: this.precomputed.doubles.step,
points: this.precomputed.doubles.points.slice(1),
},
naf: this.precomputed.naf && {
wnd: this.precomputed.naf.wnd,
points: this.precomputed.naf.points.slice(1),
},
} ];
};
Point.fromJSON = function fromJSON(curve, obj, red) {
if (typeof obj === 'string')
obj = JSON.parse(obj);
var res = curve.point(obj[0], obj[1], red);
if (!obj[2])
return res;
function obj2point(obj) {
return curve.point(obj[0], obj[1], red);
}
var pre = obj[2];
res.precomputed = {
beta: null,
doubles: pre.doubles && {
step: pre.doubles.step,
points: [ res ].concat(pre.doubles.points.map(obj2point)),
},
naf: pre.naf && {
wnd: pre.naf.wnd,
points: [ res ].concat(pre.naf.points.map(obj2point)),
},
};
return res;
};
Point.prototype.inspect = function inspect() {
if (this.isInfinity())
return '<EC Point Infinity>';
return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
' y: ' + this.y.fromRed().toString(16, 2) + '>';
};
Point.prototype.isInfinity = function isInfinity() {
return this.inf;
};
Point.prototype.add = function add(p) {
// O + P = P
if (this.inf)
return p;
// P + O = P
if (p.inf)
return this;
// P + P = 2P
if (this.eq(p))
return this.dbl();
// P + (-P) = O
if (this.neg().eq(p))
return this.curve.point(null, null);
// P + Q = O
if (this.x.cmp(p.x) === 0)
return this.curve.point(null, null);
var c = this.y.redSub(p.y);
if (c.cmpn(0) !== 0)
c = c.redMul(this.x.redSub(p.x).redInvm());
var nx = c.redSqr().redISub(this.x).redISub(p.x);
var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
return this.curve.point(nx, ny);
};
Point.prototype.dbl = function dbl() {
if (this.inf)
return this;
// 2P = O
var ys1 = this.y.redAdd(this.y);
if (ys1.cmpn(0) === 0)
return this.curve.point(null, null);
var a = this.curve.a;
var x2 = this.x.redSqr();
var dyinv = ys1.redInvm();
var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
var nx = c.redSqr().redISub(this.x.redAdd(this.x));
var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
return this.curve.point(nx, ny);
};
Point.prototype.getX = function getX() {
return this.x.fromRed();
};
Point.prototype.getY = function getY() {
return this.y.fromRed();
};
Point.prototype.mul = function mul(k) {
k = new lib_bn_default.a(k, 16);
if (this.isInfinity())
return this;
else if (this._hasDoubles(k))
return this.curve._fixedNafMul(this, k);
else if (this.curve.endo)
return this.curve._endoWnafMulAdd([ this ], [ k ]);
else
return this.curve._wnafMul(this, k);
};
Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
var points = [ this, p2 ];
var coeffs = [ k1, k2 ];
if (this.curve.endo)
return this.curve._endoWnafMulAdd(points, coeffs);
else
return this.curve._wnafMulAdd(1, points, coeffs, 2);
};
Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
var points = [ this, p2 ];
var coeffs = [ k1, k2 ];
if (this.curve.endo)
return this.curve._endoWnafMulAdd(points, coeffs, true);
else
return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
};
Point.prototype.eq = function eq(p) {
return this === p ||
this.inf === p.inf &&
(this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
};
Point.prototype.neg = function neg(_precompute) {
if (this.inf)
return this;
var res = this.curve.point(this.x, this.y.redNeg());
if (_precompute && this.precomputed) {
var pre = this.precomputed;
var negate = function(p) {
return p.neg();
};
res.precomputed = {
naf: pre.naf && {
wnd: pre.naf.wnd,
points: pre.naf.points.map(negate),
},
doubles: pre.doubles && {
step: pre.doubles.step,
points: pre.doubles.points.map(negate),
},
};
}
return res;
};
Point.prototype.toJ = function toJ() {
if (this.inf)
return this.curve.jpoint(null, null, null);
var res = this.curve.jpoint(this.x, this.y, this.curve.one);
return res;
};
function JPoint(curve, x, y, z) {
base.BasePoint.call(this, curve, 'jacobian');
if (x === null && y === null && z === null) {
this.x = this.curve.one;
this.y = this.curve.one;
this.z = new lib_bn_default.a(0);
} else {
this.x = new lib_bn_default.a(x, 16);
this.y = new lib_bn_default.a(y, 16);
this.z = new lib_bn_default.a(z, 16);
}
if (!this.x.red)
this.x = this.x.toRed(this.curve.red);
if (!this.y.red)
this.y = this.y.toRed(this.curve.red);
if (!this.z.red)
this.z = this.z.toRed(this.curve.red);
this.zOne = this.z === this.curve.one;
}
inherits_browser(JPoint, base.BasePoint);
ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
return new JPoint(this, x, y, z);
};
JPoint.prototype.toP = function toP() {
if (this.isInfinity())
return this.curve.point(null, null);
var zinv = this.z.redInvm();
var zinv2 = zinv.redSqr();
var ax = this.x.redMul(zinv2);
var ay = this.y.redMul(zinv2).redMul(zinv);
return this.curve.point(ax, ay);
};
JPoint.prototype.neg = function neg() {
return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
};
JPoint.prototype.add = function add(p) {
// O + P = P
if (this.isInfinity())
return p;
// P + O = P
if (p.isInfinity())
return this;
// 12M + 4S + 7A
var pz2 = p.z.redSqr();
var z2 = this.z.redSqr();
var u1 = this.x.redMul(pz2);
var u2 = p.x.redMul(z2);
var s1 = this.y.redMul(pz2.redMul(p.z));
var s2 = p.y.redMul(z2.redMul(this.z));
var h = u1.redSub(u2);
var r = s1.redSub(s2);
if (h.cmpn(0) === 0) {
if (r.cmpn(0) !== 0)
return this.curve.jpoint(null, null, null);
else
return this.dbl();
}
var h2 = h.redSqr();
var h3 = h2.redMul(h);
var v = u1.redMul(h2);
var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
var nz = this.z.redMul(p.z).redMul(h);
return this.curve.jpoint(nx, ny, nz);
};
JPoint.prototype.mixedAdd = function mixedAdd(p) {
// O + P = P
if (this.isInfinity())
return p.toJ();
// P + O = P
if (p.isInfinity())
return this;
// 8M + 3S + 7A
var z2 = this.z.redSqr();
var u1 = this.x;
var u2 = p.x.redMul(z2);
var s1 = this.y;
var s2 = p.y.redMul(z2).redMul(this.z);
var h = u1.redSub(u2);
var r = s1.redSub(s2);
if (h.cmpn(0) === 0) {
if (r.cmpn(0) !== 0)
return this.curve.jpoint(null, null, null);
else
return this.dbl();
}
var h2 = h.redSqr();
var h3 = h2.redMul(h);
var v = u1.redMul(h2);
var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
var nz = this.z.redMul(h);
return this.curve.jpoint(nx, ny, nz);
};
JPoint.prototype.dblp = function dblp(pow) {
if (pow === 0)
return this;
if (this.isInfinity())
return this;
if (!pow)
return this.dbl();
var i;
if (this.curve.zeroA || this.curve.threeA) {
var r = this;
for (i = 0; i < pow; i++)
r = r.dbl();
return r;
}
// 1M + 2S + 1A + N * (4S + 5M + 8A)
// N = 1 => 6M + 6S + 9A
var a = this.curve.a;
var tinv = this.curve.tinv;
var jx = this.x;
var jy = this.y;
var jz = this.z;
var jz4 = jz.redSqr().redSqr();
// Reuse results
var jyd = jy.redAdd(jy);
for (i = 0; i < pow; i++) {
var jx2 = jx.redSqr();
var jyd2 = jyd.redSqr();
var jyd4 = jyd2.redSqr();
var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
var t1 = jx.redMul(jyd2);
var nx = c.redSqr().redISub(t1.redAdd(t1));
var t2 = t1.redISub(nx);
var dny = c.redMul(t2);
dny = dny.redIAdd(dny).redISub(jyd4);
var nz = jyd.redMul(jz);
if (i + 1 < pow)
jz4 = jz4.redMul(jyd4);
jx = nx;
jz = nz;
jyd = dny;
}
return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
};
JPoint.prototype.dbl = function dbl() {
if (this.isInfinity())
return this;
if (this.curve.zeroA)
return this._zeroDbl();
else if (this.curve.threeA)
return this._threeDbl();
else
return this._dbl();
};
JPoint.prototype._zeroDbl = function _zeroDbl() {
var nx;
var ny;
var nz;
// Z = 1
if (this.zOne) {
// hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
// #doubling-mdbl-2007-bl
// 1M + 5S + 14A
// XX = X1^2
var xx = this.x.redSqr();
// YY = Y1^2
var yy = this.y.redSqr();
// YYYY = YY^2
var yyyy = yy.redSqr();
// S = 2 * ((X1 + YY)^2 - XX - YYYY)
var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
s = s.redIAdd(s);
// M = 3 * XX + a; a = 0
var m = xx.redAdd(xx).redIAdd(xx);
// T = M ^ 2 - 2*S
var t = m.redSqr().redISub(s).redISub(s);
// 8 * YYYY
var yyyy8 = yyyy.redIAdd(yyyy);
yyyy8 = yyyy8.redIAdd(yyyy8);
yyyy8 = yyyy8.redIAdd(yyyy8);
// X3 = T
nx = t;
// Y3 = M * (S - T) - 8 * YYYY
ny = m.redMul(s.redISub(t)).redISub(yyyy8);
// Z3 = 2*Y1
nz = this.y.redAdd(this.y);
} else {
// hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
// #doubling-dbl-2009-l
// 2M + 5S + 13A
// A = X1^2
var a = this.x.redSqr();
// B = Y1^2
var b = this.y.redSqr();
// C = B^2
var c = b.redSqr();
// D = 2 * ((X1 + B)^2 - A - C)
var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
d = d.redIAdd(d);
// E = 3 * A
var e = a.redAdd(a).redIAdd(a);
// F = E^2
var f = e.redSqr();
// 8 * C
var c8 = c.redIAdd(c);
c8 = c8.redIAdd(c8);
c8 = c8.redIAdd(c8);
// X3 = F - 2 * D
nx = f.redISub(d).redISub(d);
// Y3 = E * (D - X3) - 8 * C
ny = e.redMul(d.redISub(nx)).redISub(c8);
// Z3 = 2 * Y1 * Z1
nz = this.y.redMul(this.z);
nz = nz.redIAdd(nz);
}
return this.curve.jpoint(nx, ny, nz);
};
JPoint.prototype._threeDbl = function _threeDbl() {
var nx;
var ny;
var nz;
// Z = 1
if (this.zOne) {
// hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
// #doubling-mdbl-2007-bl
// 1M + 5S + 15A
// XX = X1^2
var xx = this.x.redSqr();
// YY = Y1^2
var yy = this.y.redSqr();
// YYYY = YY^2
var yyyy = yy.redSqr();
// S = 2 * ((X1 + YY)^2 - XX - YYYY)
var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
s = s.redIAdd(s);
// M = 3 * XX + a
var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
// T = M^2 - 2 * S
var t = m.redSqr().redISub(s).redISub(s);
// X3 = T
nx = t;
// Y3 = M * (S - T) - 8 * YYYY
var yyyy8 = yyyy.redIAdd(yyyy);
yyyy8 = yyyy8.redIAdd(yyyy8);
yyyy8 = yyyy8.redIAdd(yyyy8);
ny = m.redMul(s.redISub(t)).redISub(yyyy8);
// Z3 = 2 * Y1
nz = this.y.redAdd(this.y);
} else {
// hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
// 3M + 5S
// delta = Z1^2
var delta = this.z.redSqr();
// gamma = Y1^2
var gamma = this.y.redSqr();
// beta = X1 * gamma
var beta = this.x.redMul(gamma);
// alpha = 3 * (X1 - delta) * (X1 + delta)
var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
alpha = alpha.redAdd(alpha).redIAdd(alpha);
// X3 = alpha^2 - 8 * beta
var beta4 = beta.redIAdd(beta);
beta4 = beta4.redIAdd(beta4);
var beta8 = beta4.redAdd(beta4);
nx = alpha.redSqr().redISub(beta8);
// Z3 = (Y1 + Z1)^2 - gamma - delta
nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
// Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
var ggamma8 = gamma.redSqr();
ggamma8 = ggamma8.redIAdd(ggamma8);
ggamma8 = ggamma8.redIAdd(ggamma8);
ggamma8 = ggamma8.redIAdd(ggamma8);
ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
}
return this.curve.jpoint(nx, ny, nz);
};
JPoint.prototype._dbl = function _dbl() {
var a = this.curve.a;
// 4M + 6S + 10A
var jx = this.x;
var jy = this.y;
var jz = this.z;
var jz4 = jz.redSqr().redSqr();
var jx2 = jx.redSqr();
var jy2 = jy.redSqr();
var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
var jxd4 = jx.redAdd(jx);
jxd4 = jxd4.redIAdd(jxd4);
var t1 = jxd4.redMul(jy2);
var nx = c.redSqr().redISub(t1.redAdd(t1));
var t2 = t1.redISub(nx);
var jyd8 = jy2.redSqr();
jyd8 = jyd8.redIAdd(jyd8);
jyd8 = jyd8.redIAdd(jyd8);
jyd8 = jyd8.redIAdd(jyd8);
var ny = c.redMul(t2).redISub(jyd8);
var nz = jy.redAdd(jy).redMul(jz);
return this.curve.jpoint(nx, ny, nz);
};
JPoint.prototype.trpl = function trpl() {
if (!this.curve.zeroA)
return this.dbl().add(this);
// hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
// 5M + 10S + ...
// XX = X1^2
var xx = this.x.redSqr();
// YY = Y1^2
var yy = this.y.redSqr();
// ZZ = Z1^2
var zz = this.z.redSqr();
// YYYY = YY^2
var yyyy = yy.redSqr();
// M = 3 * XX + a * ZZ2; a = 0
var m = xx.redAdd(xx).redIAdd(xx);
// MM = M^2
var mm = m.redSqr();
// E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
e = e.redIAdd(e);
e = e.redAdd(e).redIAdd(e);
e = e.redISub(mm);
// EE = E^2
var ee = e.redSqr();
// T = 16*YYYY
var t = yyyy.redIAdd(yyyy);
t = t.redIAdd(t);
t = t.redIAdd(t);
t = t.redIAdd(t);
// U = (M + E)^2 - MM - EE - T
var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
// X3 = 4 * (X1 * EE - 4 * YY * U)
var yyu4 = yy.redMul(u);
yyu4 = yyu4.redIAdd(yyu4);
yyu4 = yyu4.redIAdd(yyu4);
var nx = this.x.redMul(ee).redISub(yyu4);
nx = nx.redIAdd(nx);
nx = nx.redIAdd(nx);
// Y3 = 8 * Y1 * (U * (T - U) - E * EE)
var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
ny = ny.redIAdd(ny);
ny = ny.redIAdd(ny);
ny = ny.redIAdd(ny);
// Z3 = (Z1 + E)^2 - ZZ - EE
var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
return this.curve.jpoint(nx, ny, nz);
};
JPoint.prototype.mul = function mul(k, kbase) {
k = new lib_bn_default.a(k, kbase);
return this.curve._wnafMul(this, k);
};
JPoint.prototype.eq = function eq(p) {
if (p.type === 'affine')
return this.eq(p.toJ());
if (this === p)
return true;
// x1 * z2^2 == x2 * z1^2
var z2 = this.z.redSqr();
var pz2 = p.z.redSqr();
if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
return false;
// y1 * z2^3 == y2 * z1^3
var z3 = z2.redMul(this.z);
var pz3 = pz2.redMul(p.z);
return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
};
JPoint.prototype.eqXToP = function eqXToP(x) {
var zs = this.z.redSqr();
var rx = x.toRed(this.curve.red).redMul(zs);
if (this.x.cmp(rx) === 0)
return true;
var xc = x.clone();
var t = this.curve.redN.redMul(zs);
for (;;) {
xc.iadd(this.curve.n);
if (xc.cmp(this.curve.p) >= 0)
return false;
rx.redIAdd(t);
if (this.x.cmp(rx) === 0)
return true;
}
};
JPoint.prototype.inspect = function inspect() {
if (this.isInfinity())
return '<EC JPoint Infinity>';
return '<EC JPoint x: ' + this.x.toString(16, 2) +
' y: ' + this.y.toString(16, 2) +
' z: ' + this.z.toString(16, 2) + '>';
};
JPoint.prototype.isInfinity = function isInfinity() {
// XXX This code assumes that zero is always zero in red
return this.z.cmpn(0) === 0;
};
var curve_1 = createCommonjsModule(function (module, exports) {
'use strict';
var curve = exports;
curve.base = base;
curve.short = short_1;
curve.mont = /*RicMoo:ethers:require(./mont)*/(null);
curve.edwards = /*RicMoo:ethers:require(./edwards)*/(null);
});
var curves_1 = createCommonjsModule(function (module, exports) {
'use strict';
var curves = exports;
var assert = utils_1$1.assert;
function PresetCurve(options) {
if (options.type === 'short')
this.curve = new curve_1.short(options);
else if (options.type === 'edwards')
this.curve = new curve_1.edwards(options);
else
this.curve = new curve_1.mont(options);
this.g = this.curve.g;
this.n = this.curve.n;
this.hash = options.hash;
assert(this.g.validate(), 'Invalid curve');
assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
}
curves.PresetCurve = PresetCurve;
function defineCurve(name, options) {
Object.defineProperty(curves, name, {
configurable: true,
enumerable: true,
get: function() {
var curve = new PresetCurve(options);
Object.defineProperty(curves, name, {
configurable: true,
enumerable: true,
value: curve,
});
return curve;
},
});
}
defineCurve('p192', {
type: 'short',
prime: 'p192',
p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
hash: hash_default.a.sha256,
gRed: false,
g: [
'188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
'07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',
],
});
defineCurve('p224', {
type: 'short',
prime: 'p224',
p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
hash: hash_default.a.sha256,
gRed: false,
g: [
'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',
],
});
defineCurve('p256', {
type: 'short',
prime: null,
p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
hash: hash_default.a.sha256,
gRed: false,
g: [
'6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
'4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',
],
});
defineCurve('p384', {
type: 'short',
prime: null,
p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
'fffffffe ffffffff 00000000 00000000 ffffffff',
a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
'fffffffe ffffffff 00000000 00000000 fffffffc',
b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
'5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
hash: hash_default.a.sha384,
gRed: false,
g: [
'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
'5502f25d bf55296c 3a545e38 72760ab7',
'3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
'0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',
],
});
defineCurve('p521', {
type: 'short',
prime: null,
p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
'ffffffff ffffffff ffffffff ffffffff ffffffff',
a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
'ffffffff ffffffff ffffffff ffffffff fffffffc',
b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
'99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
'3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
hash: hash_default.a.sha512,
gRed: false,
g: [
'000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
'053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
'00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
'579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
'3fad0761 353c7086 a272c240 88be9476 9fd16650',
],
});
defineCurve('curve25519', {
type: 'mont',
prime: 'p25519',
p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
a: '76d06',
b: '1',
n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
hash: hash_default.a.sha256,
gRed: false,
g: [
'9',
],
});
defineCurve('ed25519', {
type: 'edwards',
prime: 'p25519',
p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
a: '-1',
c: '1',
// -121665 * (121666^(-1)) (mod P)
d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
hash: hash_default.a.sha256,
gRed: false,
g: [
'216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
// 4/5
'6666666666666666666666666666666666666666666666666666666666666658',
],
});
var pre;
try {
pre = /*RicMoo:ethers:require(./precomputed/secp256k1)*/(null).crash();
} catch (e) {
pre = undefined;
}
defineCurve('secp256k1', {
type: 'short',
prime: 'k256',
p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
a: '0',
b: '7',
n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
h: '1',
hash: hash_default.a.sha256,
// Precomputed endomorphism
beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
basis: [
{
a: '3086d221a7d46bcde86c90e49284eb15',
b: '-e4437ed6010e88286f547fa90abfe4c3',
},
{
a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
b: '3086d221a7d46bcde86c90e49284eb15',
},
],
gRed: false,
g: [
'79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
'483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
pre,
],
});
});
'use strict';
function HmacDRBG(options) {
if (!(this instanceof HmacDRBG))
return new HmacDRBG(options);
this.hash = options.hash;
this.predResist = !!options.predResist;
this.outLen = this.hash.outSize;
this.minEntropy = options.minEntropy || this.hash.hmacStrength;
this._reseed = null;
this.reseedInterval = null;
this.K = null;
this.V = null;
var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');
var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');
var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');
minimalisticAssert(entropy.length >= (this.minEntropy / 8),
'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
this._init(entropy, nonce, pers);
}
var hmacDrbg = HmacDRBG;
HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
var seed = entropy.concat(nonce).concat(pers);
this.K = new Array(this.outLen / 8);
this.V = new Array(this.outLen / 8);
for (var i = 0; i < this.V.length; i++) {
this.K[i] = 0x00;
this.V[i] = 0x01;
}
this._update(seed);
this._reseed = 1;
this.reseedInterval = 0x1000000000000; // 2^48
};
HmacDRBG.prototype._hmac = function hmac() {
return new hash_default.a.hmac(this.hash, this.K);
};
HmacDRBG.prototype._update = function update(seed) {
var kmac = this._hmac()
.update(this.V)
.update([ 0x00 ]);
if (seed)
kmac = kmac.update(seed);
this.K = kmac.digest();
this.V = this._hmac().update(this.V).digest();
if (!seed)
return;
this.K = this._hmac()
.update(this.V)
.update([ 0x01 ])
.update(seed)
.digest();
this.V = this._hmac().update(this.V).digest();
};
HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
// Optional entropy enc
if (typeof entropyEnc !== 'string') {
addEnc = add;
add = entropyEnc;
entropyEnc = null;
}
entropy = utils_1.toArray(entropy, entropyEnc);
add = utils_1.toArray(add, addEnc);
minimalisticAssert(entropy.length >= (this.minEntropy / 8),
'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
this._update(entropy.concat(add || []));
this._reseed = 1;
};
HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
if (this._reseed > this.reseedInterval)
throw new Error('Reseed is required');
// Optional encoding
if (typeof enc !== 'string') {
addEnc = add;
add = enc;
enc = null;
}
// Optional additional data
if (add) {
add = utils_1.toArray(add, addEnc || 'hex');
this._update(add);
}
var temp = [];
while (temp.length < len) {
this.V = this._hmac().update(this.V).digest();
temp = temp.concat(this.V);
}
var res = temp.slice(0, len);
this._update(add);
this._reseed++;
return utils_1.encode(res, enc);
};
'use strict';
var assert$3 = utils_1$1.assert;
function KeyPair(ec, options) {
this.ec = ec;
this.priv = null;
this.pub = null;
// KeyPair(ec, { priv: ..., pub: ... })
if (options.priv)
this._importPrivate(options.priv, options.privEnc);
if (options.pub)
this._importPublic(options.pub, options.pubEnc);
}
var elliptic_key = KeyPair;
KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
if (pub instanceof KeyPair)
return pub;
return new KeyPair(ec, {
pub: pub,
pubEnc: enc,
});
};
KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
if (priv instanceof KeyPair)
return priv;
return new KeyPair(ec, {
priv: priv,
privEnc: enc,
});
};
KeyPair.prototype.validate = function validate() {
var pub = this.getPublic();
if (pub.isInfinity())
return { result: false, reason: 'Invalid public key' };
if (!pub.validate())
return { result: false, reason: 'Public key is not a point' };
if (!pub.mul(this.ec.curve.n).isInfinity())
return { result: false, reason: 'Public key * N != O' };
return { result: true, reason: null };
};
KeyPair.prototype.getPublic = function getPublic(compact, enc) {
// compact is optional argument
if (typeof compact === 'string') {
enc = compact;
compact = null;
}
if (!this.pub)
this.pub = this.ec.g.mul(this.priv);
if (!enc)
return this.pub;
return this.pub.encode(enc, compact);
};
KeyPair.prototype.getPrivate = function getPrivate(enc) {
if (enc === 'hex')
return this.priv.toString(16, 2);
else
return this.priv;
};
KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
this.priv = new lib_bn_default.a(key, enc || 16);
// Ensure that the priv won't be bigger than n, otherwise we may fail
// in fixed multiplication method
this.priv = this.priv.umod(this.ec.curve.n);
};
KeyPair.prototype._importPublic = function _importPublic(key, enc) {
if (key.x || key.y) {
// Montgomery points only have an `x` coordinate.
// Weierstrass/Edwards points on the other hand have both `x` and
// `y` coordinates.
if (this.ec.curve.type === 'mont') {
assert$3(key.x, 'Need x coordinate');
} else if (this.ec.curve.type === 'short' ||
this.ec.curve.type === 'edwards') {
assert$3(key.x && key.y, 'Need both x and y coordinate');
}
this.pub = this.ec.curve.point(key.x, key.y);
return;
}
this.pub = this.ec.curve.decodePoint(key, enc);
};
// ECDH
KeyPair.prototype.derive = function derive(pub) {
if(!pub.validate()) {
assert$3(pub.validate(), 'public point not validated');
}
return pub.mul(this.priv).getX();
};
// ECDSA
KeyPair.prototype.sign = function sign(msg, enc, options) {
return this.ec.sign(msg, this, enc, options);
};
KeyPair.prototype.verify = function verify(msg, signature) {
return this.ec.verify(msg, signature, this);
};
KeyPair.prototype.inspect = function inspect() {
return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
' pub: ' + (this.pub && this.pub.inspect()) + ' >';
};
'use strict';
var assert$4 = utils_1$1.assert;
function Signature(options, enc) {
if (options instanceof Signature)
return options;
if (this._importDER(options, enc))
return;
assert$4(options.r && options.s, 'Signature without r or s');
this.r = new lib_bn_default.a(options.r, 16);
this.s = new lib_bn_default.a(options.s, 16);
if (options.recoveryParam === undefined)
this.recoveryParam = null;
else
this.recoveryParam = options.recoveryParam;
}
var elliptic_signature = Signature;
function Position() {
this.place = 0;
}
function getLength(buf, p) {
var initial = buf[p.place++];
if (!(initial & 0x80)) {
return initial;
}
var octetLen = initial & 0xf;
// Indefinite length or overflow
if (octetLen === 0 || octetLen > 4) {
return false;
}
var val = 0;
for (var i = 0, off = p.place; i < octetLen; i++, off++) {
val <<= 8;
val |= buf[off];
val >>>= 0;
}
// Leading zeroes
if (val <= 0x7f) {
return false;
}
p.place = off;
return val;
}
function rmPadding(buf) {
var i = 0;
var len = buf.length - 1;
while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
i++;
}
if (i === 0) {
return buf;
}
return buf.slice(i);
}
Signature.prototype._importDER = function _importDER(data, enc) {
data = utils_1$1.toArray(data, enc);
var p = new Position();
if (data[p.place++] !== 0x30) {
return false;
}
var len = getLength(data, p);
if (len === false) {
return false;
}
if ((len + p.place) !== data.length) {
return false;
}
if (data[p.place++] !== 0x02) {
return false;
}
var rlen = getLength(data, p);
if (rlen === false) {
return false;
}
var r = data.slice(p.place, rlen + p.place);
p.place += rlen;
if (data[p.place++] !== 0x02) {
return false;
}
var slen = getLength(data, p);
if (slen === false) {
return false;
}
if (data.length !== slen + p.place) {
return false;
}
var s = data.slice(p.place, slen + p.place);
if (r[0] === 0) {
if (r[1] & 0x80) {
r = r.slice(1);
} else {
// Leading zeroes
return false;
}
}
if (s[0] === 0) {
if (s[1] & 0x80) {
s = s.slice(1);
} else {
// Leading zeroes
return false;
}
}
this.r = new lib_bn_default.a(r);
this.s = new lib_bn_default.a(s);
this.recoveryParam = null;
return true;
};
function constructLength(arr, len) {
if (len < 0x80) {
arr.push(len);
return;
}
var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
arr.push(octets | 0x80);
while (--octets) {
arr.push((len >>> (octets << 3)) & 0xff);
}
arr.push(len);
}
Signature.prototype.toDER = function toDER(enc) {
var r = this.r.toArray();
var s = this.s.toArray();
// Pad values
if (r[0] & 0x80)
r = [ 0 ].concat(r);
// Pad values
if (s[0] & 0x80)
s = [ 0 ].concat(s);
r = rmPadding(r);
s = rmPadding(s);
while (!s[0] && !(s[1] & 0x80)) {
s = s.slice(1);
}
var arr = [ 0x02 ];
constructLength(arr, r.length);
arr = arr.concat(r);
arr.push(0x02);
constructLength(arr, s.length);
var backHalf = arr.concat(s);
var res = [ 0x30 ];
constructLength(res, backHalf.length);
res = res.concat(backHalf);
return utils_1$1.encode(res, enc);
};
'use strict';
var rand = /*RicMoo:ethers:require(brorand)*/(function() { throw new Error('unsupported'); });
var assert$5 = utils_1$1.assert;
function EC(options) {
if (!(this instanceof EC))
return new EC(options);
// Shortcut `elliptic.ec(curve-name)`
if (typeof options === 'string') {
assert$5(Object.prototype.hasOwnProperty.call(curves_1, options),
'Unknown curve ' + options);
options = curves_1[options];
}
// Shortcut for `elliptic.ec(elliptic.curves.curveName)`
if (options instanceof curves_1.PresetCurve)
options = { curve: options };
this.curve = options.curve.curve;
this.n = this.curve.n;
this.nh = this.n.ushrn(1);
this.g = this.curve.g;
// Point on curve
this.g = options.curve.g;
this.g.precompute(options.curve.n.bitLength() + 1);
// Hash for function for DRBG
this.hash = options.hash || options.curve.hash;
}
var ec = EC;
EC.prototype.keyPair = function keyPair(options) {
return new elliptic_key(this, options);
};
EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
return elliptic_key.fromPrivate(this, priv, enc);
};
EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
return elliptic_key.fromPublic(this, pub, enc);
};
EC.prototype.genKeyPair = function genKeyPair(options) {
if (!options)
options = {};
// Instantiate Hmac_DRBG
var drbg = new hmacDrbg({
hash: this.hash,
pers: options.pers,
persEnc: options.persEnc || 'utf8',
entropy: options.entropy || rand(this.hash.hmacStrength),
entropyEnc: options.entropy && options.entropyEnc || 'utf8',
nonce: this.n.toArray(),
});
var bytes = this.n.byteLength();
var ns2 = this.n.sub(new lib_bn_default.a(2));
for (;;) {
var priv = new lib_bn_default.a(drbg.generate(bytes));
if (priv.cmp(ns2) > 0)
continue;
priv.iaddn(1);
return this.keyFromPrivate(priv);
}
};
EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) {
var delta = msg.byteLength() * 8 - this.n.bitLength();
if (delta > 0)
msg = msg.ushrn(delta);
if (!truncOnly && msg.cmp(this.n) >= 0)
return msg.sub(this.n);
else
return msg;
};
EC.prototype.sign = function sign(msg, key, enc, options) {
if (typeof enc === 'object') {
options = enc;
enc = null;
}
if (!options)
options = {};
key = this.keyFromPrivate(key, enc);
msg = this._truncateToN(new lib_bn_default.a(msg, 16));
// Zero-extend key to provide enough entropy
var bytes = this.n.byteLength();
var bkey = key.getPrivate().toArray('be', bytes);
// Zero-extend nonce to have the same byte size as N
var nonce = msg.toArray('be', bytes);
// Instantiate Hmac_DRBG
var drbg = new hmacDrbg({
hash: this.hash,
entropy: bkey,
nonce: nonce,
pers: options.pers,
persEnc: options.persEnc || 'utf8',
});
// Number of bytes to generate
var ns1 = this.n.sub(new lib_bn_default.a(1));
for (var iter = 0; ; iter++) {
var k = options.k ?
options.k(iter) :
new lib_bn_default.a(drbg.generate(this.n.byteLength()));
k = this._truncateToN(k, true);
if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
continue;
var kp = this.g.mul(k);
if (kp.isInfinity())
continue;
var kpX = kp.getX();
var r = kpX.umod(this.n);
if (r.cmpn(0) === 0)
continue;
var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
s = s.umod(this.n);
if (s.cmpn(0) === 0)
continue;
var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
(kpX.cmp(r) !== 0 ? 2 : 0);
// Use complement of `s`, if it is > `n / 2`
if (options.canonical && s.cmp(this.nh) > 0) {
s = this.n.sub(s);
recoveryParam ^= 1;
}
return new elliptic_signature({ r: r, s: s, recoveryParam: recoveryParam });
}
};
EC.prototype.verify = function verify(msg, signature$1, key, enc) {
msg = this._truncateToN(new lib_bn_default.a(msg, 16));
key = this.keyFromPublic(key, enc);
signature$1 = new elliptic_signature(signature$1, 'hex');
// Perform primitive values validation
var r = signature$1.r;
var s = signature$1.s;
if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
return false;
if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
return false;
// Validate signature
var sinv = s.invm(this.n);
var u1 = sinv.mul(msg).umod(this.n);
var u2 = sinv.mul(r).umod(this.n);
var p;
if (!this.curve._maxwellTrick) {
p = this.g.mulAdd(u1, key.getPublic(), u2);
if (p.isInfinity())
return false;
return p.getX().umod(this.n).cmp(r) === 0;
}
// NOTE: Greg Maxwell's trick, inspired by:
// https://git.io/vad3K
p = this.g.jmulAdd(u1, key.getPublic(), u2);
if (p.isInfinity())
return false;
// Compare `p.x` of Jacobian point with `r`,
// this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
// inverse of `p.z^2`
return p.eqXToP(r);
};
EC.prototype.recoverPubKey = function(msg, signature$1, j, enc) {
assert$5((3 & j) === j, 'The recovery param is more than two bits');
signature$1 = new elliptic_signature(signature$1, enc);
var n = this.n;
var e = new lib_bn_default.a(msg);
var r = signature$1.r;
var s = signature$1.s;
// A set LSB signifies that the y-coordinate is odd
var isYOdd = j & 1;
var isSecondKey = j >> 1;
if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
throw new Error('Unable to find sencond key candinate');
// 1.1. Let x = r + jn.
if (isSecondKey)
r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
else
r = this.curve.pointFromX(r, isYOdd);
var rInv = signature$1.r.invm(n);
var s1 = n.sub(e).mul(rInv).umod(n);
var s2 = s.mul(rInv).umod(n);
// 1.6.1 Compute Q = r^-1 (sR - eG)
// Q = r^-1 (sR + -eG)
return this.g.mulAdd(s1, r, s2);
};
EC.prototype.getKeyRecoveryParam = function(e, signature$1, Q, enc) {
signature$1 = new elliptic_signature(signature$1, enc);
if (signature$1.recoveryParam !== null)
return signature$1.recoveryParam;
for (var i = 0; i < 4; i++) {
var Qprime;
try {
Qprime = this.recoverPubKey(e, signature$1, i);
} catch (e) {
continue;
}
if (Qprime.eq(Q))
return i;
}
throw new Error('Unable to find valid recovery factor');
};
var elliptic_1 = createCommonjsModule(function (module, exports) {
'use strict';
var elliptic = exports;
elliptic.version = /*RicMoo:ethers*/{ version: "6.5.4" }.version;
elliptic.utils = utils_1$1;
elliptic.rand = /*RicMoo:ethers:require(brorand)*/(function() { throw new Error('unsupported'); });
elliptic.curve = curve_1;
elliptic.curves = curves_1;
// Protocols
elliptic.ec = ec;
elliptic.eddsa = /*RicMoo:ethers:require(./elliptic/eddsa)*/(null);
});
var EC$1 = elliptic_1.ec;
//# sourceMappingURL=elliptic.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/signing-key/lib.esm/_version.js
const signing_key_lib_esm_version_version = "signing-key/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/signing-key/lib.esm/index.js
const signing_key_lib_esm_logger = new lib_esm_Logger(signing_key_lib_esm_version_version);
let _curve = null;
function getCurve() {
if (!_curve) {
_curve = new EC$1("secp256k1");
}
return _curve;
}
class lib_esm_SigningKey {
constructor(privateKey) {
defineReadOnly(this, "curve", "secp256k1");
defineReadOnly(this, "privateKey", hexlify(privateKey));
if (hexDataLength(this.privateKey) !== 32) {
signing_key_lib_esm_logger.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]");
}
const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
defineReadOnly(this, "publicKey", "0x" + keyPair.getPublic(false, "hex"));
defineReadOnly(this, "compressedPublicKey", "0x" + keyPair.getPublic(true, "hex"));
defineReadOnly(this, "_isSigningKey", true);
}
_addPoint(other) {
const p0 = getCurve().keyFromPublic(arrayify(this.publicKey));
const p1 = getCurve().keyFromPublic(arrayify(other));
return "0x" + p0.pub.add(p1.pub).encodeCompressed("hex");
}
signDigest(digest) {
const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
const digestBytes = arrayify(digest);
if (digestBytes.length !== 32) {
signing_key_lib_esm_logger.throwArgumentError("bad digest length", "digest", digest);
}
const signature = keyPair.sign(digestBytes, { canonical: true });
return splitSignature({
recoveryParam: signature.recoveryParam,
r: hexZeroPad("0x" + signature.r.toString(16), 32),
s: hexZeroPad("0x" + signature.s.toString(16), 32),
});
}
computeSharedSecret(otherKey) {
const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
const otherKeyPair = getCurve().keyFromPublic(arrayify(computePublicKey(otherKey)));
return hexZeroPad("0x" + keyPair.derive(otherKeyPair.getPublic()).toString(16), 32);
}
static isSigningKey(value) {
return !!(value && value._isSigningKey);
}
}
function recoverPublicKey(digest, signature) {
const sig = splitSignature(signature);
const rs = { r: arrayify(sig.r), s: arrayify(sig.s) };
return "0x" + getCurve().recoverPubKey(arrayify(digest), rs, sig.recoveryParam).encode("hex", false);
}
function computePublicKey(key, compressed) {
const bytes = arrayify(key);
if (bytes.length === 32) {
const signingKey = new lib_esm_SigningKey(bytes);
if (compressed) {
return "0x" + getCurve().keyFromPrivate(bytes).getPublic(true, "hex");
}
return signingKey.publicKey;
}
else if (bytes.length === 33) {
if (compressed) {
return hexlify(bytes);
}
return "0x" + getCurve().keyFromPublic(bytes).getPublic(false, "hex");
}
else if (bytes.length === 65) {
if (!compressed) {
return hexlify(bytes);
}
return "0x" + getCurve().keyFromPublic(bytes).getPublic(true, "hex");
}
return signing_key_lib_esm_logger.throwArgumentError("invalid public or private key", "key", "[REDACTED]");
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/transactions/lib.esm/_version.js
const transactions_lib_esm_version_version = "transactions/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/transactions/lib.esm/index.js
const transactions_lib_esm_logger = new lib_esm_Logger(transactions_lib_esm_version_version);
var TransactionTypes;
(function (TransactionTypes) {
TransactionTypes[TransactionTypes["legacy"] = 0] = "legacy";
TransactionTypes[TransactionTypes["eip2930"] = 1] = "eip2930";
TransactionTypes[TransactionTypes["eip1559"] = 2] = "eip1559";
})(TransactionTypes || (TransactionTypes = {}));
;
///////////////////////////////
function handleAddress(value) {
if (value === "0x") {
return null;
}
return getAddress(value);
}
function handleNumber(value) {
if (value === "0x") {
return Zero;
}
return bignumber_BigNumber.from(value);
}
// Legacy Transaction Fields
const transactionFields = [
{ name: "nonce", maxLength: 32, numeric: true },
{ name: "gasPrice", maxLength: 32, numeric: true },
{ name: "gasLimit", maxLength: 32, numeric: true },
{ name: "to", length: 20 },
{ name: "value", maxLength: 32, numeric: true },
{ name: "data" },
];
const allowedTransactionKeys = {
chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, type: true, value: true
};
function computeAddress(key) {
const publicKey = computePublicKey(key);
return getAddress(hexDataSlice(keccak256(hexDataSlice(publicKey, 1)), 12));
}
function recoverAddress(digest, signature) {
return computeAddress(recoverPublicKey(arrayify(digest), signature));
}
function formatNumber(value, name) {
const result = stripZeros(bignumber_BigNumber.from(value).toHexString());
if (result.length > 32) {
transactions_lib_esm_logger.throwArgumentError("invalid length for " + name, ("transaction:" + name), value);
}
return result;
}
function accessSetify(addr, storageKeys) {
return {
address: getAddress(addr),
storageKeys: (storageKeys || []).map((storageKey, index) => {
if (hexDataLength(storageKey) !== 32) {
transactions_lib_esm_logger.throwArgumentError("invalid access list storageKey", `accessList[${addr}:${index}]`, storageKey);
}
return storageKey.toLowerCase();
})
};
}
function accessListify(value) {
if (Array.isArray(value)) {
return value.map((set, index) => {
if (Array.isArray(set)) {
if (set.length > 2) {
transactions_lib_esm_logger.throwArgumentError("access list expected to be [ address, storageKeys[] ]", `value[${index}]`, set);
}
return accessSetify(set[0], set[1]);
}
return accessSetify(set.address, set.storageKeys);
});
}
const result = Object.keys(value).map((addr) => {
const storageKeys = value[addr].reduce((accum, storageKey) => {
accum[storageKey] = true;
return accum;
}, {});
return accessSetify(addr, Object.keys(storageKeys).sort());
});
result.sort((a, b) => (a.address.localeCompare(b.address)));
return result;
}
function formatAccessList(value) {
return accessListify(value).map((set) => [set.address, set.storageKeys]);
}
function _serializeEip1559(transaction, signature) {
// If there is an explicit gasPrice, make sure it matches the
// EIP-1559 fees; otherwise they may not understand what they
// think they are setting in terms of fee.
if (transaction.gasPrice != null) {
const gasPrice = bignumber_BigNumber.from(transaction.gasPrice);
const maxFeePerGas = bignumber_BigNumber.from(transaction.maxFeePerGas || 0);
if (!gasPrice.eq(maxFeePerGas)) {
transactions_lib_esm_logger.throwArgumentError("mismatch EIP-1559 gasPrice != maxFeePerGas", "tx", {
gasPrice, maxFeePerGas
});
}
}
const fields = [
formatNumber(transaction.chainId || 0, "chainId"),
formatNumber(transaction.nonce || 0, "nonce"),
formatNumber(transaction.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
formatNumber(transaction.maxFeePerGas || 0, "maxFeePerGas"),
formatNumber(transaction.gasLimit || 0, "gasLimit"),
((transaction.to != null) ? getAddress(transaction.to) : "0x"),
formatNumber(transaction.value || 0, "value"),
(transaction.data || "0x"),
(formatAccessList(transaction.accessList || []))
];
if (signature) {
const sig = splitSignature(signature);
fields.push(formatNumber(sig.recoveryParam, "recoveryParam"));
fields.push(stripZeros(sig.r));
fields.push(stripZeros(sig.s));
}
return hexConcat(["0x02", lib_esm_encode(fields)]);
}
function _serializeEip2930(transaction, signature) {
const fields = [
formatNumber(transaction.chainId || 0, "chainId"),
formatNumber(transaction.nonce || 0, "nonce"),
formatNumber(transaction.gasPrice || 0, "gasPrice"),
formatNumber(transaction.gasLimit || 0, "gasLimit"),
((transaction.to != null) ? getAddress(transaction.to) : "0x"),
formatNumber(transaction.value || 0, "value"),
(transaction.data || "0x"),
(formatAccessList(transaction.accessList || []))
];
if (signature) {
const sig = splitSignature(signature);
fields.push(formatNumber(sig.recoveryParam, "recoveryParam"));
fields.push(stripZeros(sig.r));
fields.push(stripZeros(sig.s));
}
return hexConcat(["0x01", lib_esm_encode(fields)]);
}
// Legacy Transactions and EIP-155
function _serialize(transaction, signature) {
checkProperties(transaction, allowedTransactionKeys);
const raw = [];
transactionFields.forEach(function (fieldInfo) {
let value = transaction[fieldInfo.name] || ([]);
const options = {};
if (fieldInfo.numeric) {
options.hexPad = "left";
}
value = arrayify(hexlify(value, options));
// Fixed-width field
if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) {
transactions_lib_esm_logger.throwArgumentError("invalid length for " + fieldInfo.name, ("transaction:" + fieldInfo.name), value);
}
// Variable-width (with a maximum)
if (fieldInfo.maxLength) {
value = stripZeros(value);
if (value.length > fieldInfo.maxLength) {
transactions_lib_esm_logger.throwArgumentError("invalid length for " + fieldInfo.name, ("transaction:" + fieldInfo.name), value);
}
}
raw.push(hexlify(value));
});
let chainId = 0;
if (transaction.chainId != null) {
// A chainId was provided; if non-zero we'll use EIP-155
chainId = transaction.chainId;
if (typeof (chainId) !== "number") {
transactions_lib_esm_logger.throwArgumentError("invalid transaction.chainId", "transaction", transaction);
}
}
else if (signature && !isBytesLike(signature) && signature.v > 28) {
// No chainId provided, but the signature is signing with EIP-155; derive chainId
chainId = Math.floor((signature.v - 35) / 2);
}
// We have an EIP-155 transaction (chainId was specified and non-zero)
if (chainId !== 0) {
raw.push(hexlify(chainId)); // @TODO: hexValue?
raw.push("0x");
raw.push("0x");
}
// Requesting an unsigned transaction
if (!signature) {
return lib_esm_encode(raw);
}
// The splitSignature will ensure the transaction has a recoveryParam in the
// case that the signTransaction function only adds a v.
const sig = splitSignature(signature);
// We pushed a chainId and null r, s on for hashing only; remove those
let v = 27 + sig.recoveryParam;
if (chainId !== 0) {
raw.pop();
raw.pop();
raw.pop();
v += chainId * 2 + 8;
// If an EIP-155 v (directly or indirectly; maybe _vs) was provided, check it!
if (sig.v > 28 && sig.v !== v) {
transactions_lib_esm_logger.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature);
}
}
else if (sig.v !== v) {
transactions_lib_esm_logger.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature);
}
raw.push(hexlify(v));
raw.push(stripZeros(arrayify(sig.r)));
raw.push(stripZeros(arrayify(sig.s)));
return lib_esm_encode(raw);
}
function lib_esm_serialize(transaction, signature) {
// Legacy and EIP-155 Transactions
if (transaction.type == null || transaction.type === 0) {
if (transaction.accessList != null) {
transactions_lib_esm_logger.throwArgumentError("untyped transactions do not support accessList; include type: 1", "transaction", transaction);
}
return _serialize(transaction, signature);
}
// Typed Transactions (EIP-2718)
switch (transaction.type) {
case 1:
return _serializeEip2930(transaction, signature);
case 2:
return _serializeEip1559(transaction, signature);
default:
break;
}
return transactions_lib_esm_logger.throwError(`unsupported transaction type: ${transaction.type}`, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "serializeTransaction",
transactionType: transaction.type
});
}
function _parseEipSignature(tx, fields, serialize) {
try {
const recid = handleNumber(fields[0]).toNumber();
if (recid !== 0 && recid !== 1) {
throw new Error("bad recid");
}
tx.v = recid;
}
catch (error) {
transactions_lib_esm_logger.throwArgumentError("invalid v for transaction type: 1", "v", fields[0]);
}
tx.r = hexZeroPad(fields[1], 32);
tx.s = hexZeroPad(fields[2], 32);
try {
const digest = keccak256(serialize(tx));
tx.from = recoverAddress(digest, { r: tx.r, s: tx.s, recoveryParam: tx.v });
}
catch (error) { }
}
function _parseEip1559(payload) {
const transaction = lib_esm_decode(payload.slice(1));
if (transaction.length !== 9 && transaction.length !== 12) {
transactions_lib_esm_logger.throwArgumentError("invalid component count for transaction type: 2", "payload", hexlify(payload));
}
const maxPriorityFeePerGas = handleNumber(transaction[2]);
const maxFeePerGas = handleNumber(transaction[3]);
const tx = {
type: 2,
chainId: handleNumber(transaction[0]).toNumber(),
nonce: handleNumber(transaction[1]).toNumber(),
maxPriorityFeePerGas: maxPriorityFeePerGas,
maxFeePerGas: maxFeePerGas,
gasPrice: null,
gasLimit: handleNumber(transaction[4]),
to: handleAddress(transaction[5]),
value: handleNumber(transaction[6]),
data: transaction[7],
accessList: accessListify(transaction[8]),
};
// Unsigned EIP-1559 Transaction
if (transaction.length === 9) {
return tx;
}
tx.hash = keccak256(payload);
_parseEipSignature(tx, transaction.slice(9), _serializeEip1559);
return tx;
}
function _parseEip2930(payload) {
const transaction = lib_esm_decode(payload.slice(1));
if (transaction.length !== 8 && transaction.length !== 11) {
transactions_lib_esm_logger.throwArgumentError("invalid component count for transaction type: 1", "payload", hexlify(payload));
}
const tx = {
type: 1,
chainId: handleNumber(transaction[0]).toNumber(),
nonce: handleNumber(transaction[1]).toNumber(),
gasPrice: handleNumber(transaction[2]),
gasLimit: handleNumber(transaction[3]),
to: handleAddress(transaction[4]),
value: handleNumber(transaction[5]),
data: transaction[6],
accessList: accessListify(transaction[7])
};
// Unsigned EIP-2930 Transaction
if (transaction.length === 8) {
return tx;
}
tx.hash = keccak256(payload);
_parseEipSignature(tx, transaction.slice(8), _serializeEip2930);
return tx;
}
// Legacy Transactions and EIP-155
function _parse(rawTransaction) {
const transaction = lib_esm_decode(rawTransaction);
if (transaction.length !== 9 && transaction.length !== 6) {
transactions_lib_esm_logger.throwArgumentError("invalid raw transaction", "rawTransaction", rawTransaction);
}
const tx = {
nonce: handleNumber(transaction[0]).toNumber(),
gasPrice: handleNumber(transaction[1]),
gasLimit: handleNumber(transaction[2]),
to: handleAddress(transaction[3]),
value: handleNumber(transaction[4]),
data: transaction[5],
chainId: 0
};
// Legacy unsigned transaction
if (transaction.length === 6) {
return tx;
}
try {
tx.v = bignumber_BigNumber.from(transaction[6]).toNumber();
}
catch (error) {
// @TODO: What makes snese to do? The v is too big
return tx;
}
tx.r = hexZeroPad(transaction[7], 32);
tx.s = hexZeroPad(transaction[8], 32);
if (bignumber_BigNumber.from(tx.r).isZero() && bignumber_BigNumber.from(tx.s).isZero()) {
// EIP-155 unsigned transaction
tx.chainId = tx.v;
tx.v = 0;
}
else {
// Signed Transaction
tx.chainId = Math.floor((tx.v - 35) / 2);
if (tx.chainId < 0) {
tx.chainId = 0;
}
let recoveryParam = tx.v - 27;
const raw = transaction.slice(0, 6);
if (tx.chainId !== 0) {
raw.push(hexlify(tx.chainId));
raw.push("0x");
raw.push("0x");
recoveryParam -= tx.chainId * 2 + 8;
}
const digest = keccak256(lib_esm_encode(raw));
try {
tx.from = recoverAddress(digest, { r: hexlify(tx.r), s: hexlify(tx.s), recoveryParam: recoveryParam });
}
catch (error) { }
tx.hash = keccak256(rawTransaction);
}
tx.type = null;
return tx;
}
function parse(rawTransaction) {
const payload = arrayify(rawTransaction);
// Legacy and EIP-155 Transactions
if (payload[0] > 0x7f) {
return _parse(payload);
}
// Typed Transaction (EIP-2718)
switch (payload[0]) {
case 1:
return _parseEip2930(payload);
case 2:
return _parseEip1559(payload);
default:
break;
}
return transactions_lib_esm_logger.throwError(`unsupported transaction type: ${payload[0]}`, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "parseTransaction",
transactionType: payload[0]
});
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/formatter.js
const formatter_logger = new lib_esm_Logger(providers_lib_esm_version_version);
class formatter_Formatter {
constructor() {
this.formats = this.getDefaultFormats();
}
getDefaultFormats() {
const formats = ({});
const address = this.address.bind(this);
const bigNumber = this.bigNumber.bind(this);
const blockTag = this.blockTag.bind(this);
const data = this.data.bind(this);
const hash = this.hash.bind(this);
const hex = this.hex.bind(this);
const number = this.number.bind(this);
const type = this.type.bind(this);
const strictData = (v) => { return this.data(v, true); };
formats.transaction = {
hash: hash,
type: type,
accessList: formatter_Formatter.allowNull(this.accessList.bind(this), null),
blockHash: formatter_Formatter.allowNull(hash, null),
blockNumber: formatter_Formatter.allowNull(number, null),
transactionIndex: formatter_Formatter.allowNull(number, null),
confirmations: formatter_Formatter.allowNull(number, null),
from: address,
// either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas)
// must be set
gasPrice: formatter_Formatter.allowNull(bigNumber),
maxPriorityFeePerGas: formatter_Formatter.allowNull(bigNumber),
maxFeePerGas: formatter_Formatter.allowNull(bigNumber),
gasLimit: bigNumber,
to: formatter_Formatter.allowNull(address, null),
value: bigNumber,
nonce: number,
data: data,
r: formatter_Formatter.allowNull(this.uint256),
s: formatter_Formatter.allowNull(this.uint256),
v: formatter_Formatter.allowNull(number),
creates: formatter_Formatter.allowNull(address, null),
raw: formatter_Formatter.allowNull(data),
};
formats.transactionRequest = {
from: formatter_Formatter.allowNull(address),
nonce: formatter_Formatter.allowNull(number),
gasLimit: formatter_Formatter.allowNull(bigNumber),
gasPrice: formatter_Formatter.allowNull(bigNumber),
maxPriorityFeePerGas: formatter_Formatter.allowNull(bigNumber),
maxFeePerGas: formatter_Formatter.allowNull(bigNumber),
to: formatter_Formatter.allowNull(address),
value: formatter_Formatter.allowNull(bigNumber),
data: formatter_Formatter.allowNull(strictData),
type: formatter_Formatter.allowNull(number),
accessList: formatter_Formatter.allowNull(this.accessList.bind(this), null),
};
formats.receiptLog = {
transactionIndex: number,
blockNumber: number,
transactionHash: hash,
address: address,
topics: formatter_Formatter.arrayOf(hash),
data: data,
logIndex: number,
blockHash: hash,
};
formats.receipt = {
to: formatter_Formatter.allowNull(this.address, null),
from: formatter_Formatter.allowNull(this.address, null),
contractAddress: formatter_Formatter.allowNull(address, null),
transactionIndex: number,
// should be allowNull(hash), but broken-EIP-658 support is handled in receipt
root: formatter_Formatter.allowNull(hex),
gasUsed: bigNumber,
logsBloom: formatter_Formatter.allowNull(data),
blockHash: hash,
transactionHash: hash,
logs: formatter_Formatter.arrayOf(this.receiptLog.bind(this)),
blockNumber: number,
confirmations: formatter_Formatter.allowNull(number, null),
cumulativeGasUsed: bigNumber,
effectiveGasPrice: formatter_Formatter.allowNull(bigNumber),
status: formatter_Formatter.allowNull(number),
type: type
};
formats.block = {
hash: formatter_Formatter.allowNull(hash),
parentHash: hash,
number: number,
timestamp: number,
nonce: formatter_Formatter.allowNull(hex),
difficulty: this.difficulty.bind(this),
gasLimit: bigNumber,
gasUsed: bigNumber,
miner: formatter_Formatter.allowNull(address),
extraData: data,
transactions: formatter_Formatter.allowNull(formatter_Formatter.arrayOf(hash)),
baseFeePerGas: formatter_Formatter.allowNull(bigNumber)
};
formats.blockWithTransactions = shallowCopy(formats.block);
formats.blockWithTransactions.transactions = formatter_Formatter.allowNull(formatter_Formatter.arrayOf(this.transactionResponse.bind(this)));
formats.filter = {
fromBlock: formatter_Formatter.allowNull(blockTag, undefined),
toBlock: formatter_Formatter.allowNull(blockTag, undefined),
blockHash: formatter_Formatter.allowNull(hash, undefined),
address: formatter_Formatter.allowNull(address, undefined),
topics: formatter_Formatter.allowNull(this.topics.bind(this), undefined),
};
formats.filterLog = {
blockNumber: formatter_Formatter.allowNull(number),
blockHash: formatter_Formatter.allowNull(hash),
transactionIndex: number,
removed: formatter_Formatter.allowNull(this.boolean.bind(this)),
address: address,
data: formatter_Formatter.allowFalsish(data, "0x"),
topics: formatter_Formatter.arrayOf(hash),
transactionHash: hash,
logIndex: number,
};
return formats;
}
accessList(accessList) {
return accessListify(accessList || []);
}
// Requires a BigNumberish that is within the IEEE754 safe integer range; returns a number
// Strict! Used on input.
number(number) {
if (number === "0x") {
return 0;
}
return bignumber_BigNumber.from(number).toNumber();
}
type(number) {
if (number === "0x" || number == null) {
return 0;
}
return bignumber_BigNumber.from(number).toNumber();
}
// Strict! Used on input.
bigNumber(value) {
return bignumber_BigNumber.from(value);
}
// Requires a boolean, "true" or "false"; returns a boolean
boolean(value) {
if (typeof (value) === "boolean") {
return value;
}
if (typeof (value) === "string") {
value = value.toLowerCase();
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
}
throw new Error("invalid boolean - " + value);
}
hex(value, strict) {
if (typeof (value) === "string") {
if (!strict && value.substring(0, 2) !== "0x") {
value = "0x" + value;
}
if (isHexString(value)) {
return value.toLowerCase();
}
}
return formatter_logger.throwArgumentError("invalid hash", "value", value);
}
data(value, strict) {
const result = this.hex(value, strict);
if ((result.length % 2) !== 0) {
throw new Error("invalid data; odd-length - " + value);
}
return result;
}
// Requires an address
// Strict! Used on input.
address(value) {
return getAddress(value);
}
callAddress(value) {
if (!isHexString(value, 32)) {
return null;
}
const address = getAddress(hexDataSlice(value, 12));
return (address === AddressZero) ? null : address;
}
contractAddress(value) {
return getContractAddress(value);
}
// Strict! Used on input.
blockTag(blockTag) {
if (blockTag == null) {
return "latest";
}
if (blockTag === "earliest") {
return "0x0";
}
switch (blockTag) {
case "earliest": return "0x0";
case "latest":
case "pending":
case "safe":
case "finalized":
return blockTag;
}
if (typeof (blockTag) === "number" || isHexString(blockTag)) {
return hexValue(blockTag);
}
throw new Error("invalid blockTag");
}
// Requires a hash, optionally requires 0x prefix; returns prefixed lowercase hash.
hash(value, strict) {
const result = this.hex(value, strict);
if (hexDataLength(result) !== 32) {
return formatter_logger.throwArgumentError("invalid hash", "value", value);
}
return result;
}
// Returns the difficulty as a number, or if too large (i.e. PoA network) null
difficulty(value) {
if (value == null) {
return null;
}
const v = bignumber_BigNumber.from(value);
try {
return v.toNumber();
}
catch (error) { }
return null;
}
uint256(value) {
if (!isHexString(value)) {
throw new Error("invalid uint256");
}
return hexZeroPad(value, 32);
}
_block(value, format) {
if (value.author != null && value.miner == null) {
value.miner = value.author;
}
// The difficulty may need to come from _difficulty in recursed blocks
const difficulty = (value._difficulty != null) ? value._difficulty : value.difficulty;
const result = formatter_Formatter.check(format, value);
result._difficulty = ((difficulty == null) ? null : bignumber_BigNumber.from(difficulty));
return result;
}
block(value) {
return this._block(value, this.formats.block);
}
blockWithTransactions(value) {
return this._block(value, this.formats.blockWithTransactions);
}
// Strict! Used on input.
transactionRequest(value) {
return formatter_Formatter.check(this.formats.transactionRequest, value);
}
transactionResponse(transaction) {
// Rename gas to gasLimit
if (transaction.gas != null && transaction.gasLimit == null) {
transaction.gasLimit = transaction.gas;
}
// Some clients (TestRPC) do strange things like return 0x0 for the
// 0 address; correct this to be a real address
if (transaction.to && bignumber_BigNumber.from(transaction.to).isZero()) {
transaction.to = "0x0000000000000000000000000000000000000000";
}
// Rename input to data
if (transaction.input != null && transaction.data == null) {
transaction.data = transaction.input;
}
// If to and creates are empty, populate the creates from the transaction
if (transaction.to == null && transaction.creates == null) {
transaction.creates = this.contractAddress(transaction);
}
if ((transaction.type === 1 || transaction.type === 2) && transaction.accessList == null) {
transaction.accessList = [];
}
const result = formatter_Formatter.check(this.formats.transaction, transaction);
if (transaction.chainId != null) {
let chainId = transaction.chainId;
if (isHexString(chainId)) {
chainId = bignumber_BigNumber.from(chainId).toNumber();
}
result.chainId = chainId;
}
else {
let chainId = transaction.networkId;
// geth-etc returns chainId
if (chainId == null && result.v == null) {
chainId = transaction.chainId;
}
if (isHexString(chainId)) {
chainId = bignumber_BigNumber.from(chainId).toNumber();
}
if (typeof (chainId) !== "number" && result.v != null) {
chainId = (result.v - 35) / 2;
if (chainId < 0) {
chainId = 0;
}
chainId = parseInt(chainId);
}
if (typeof (chainId) !== "number") {
chainId = 0;
}
result.chainId = chainId;
}
// 0x0000... should actually be null
if (result.blockHash && result.blockHash.replace(/0/g, "") === "x") {
result.blockHash = null;
}
return result;
}
transaction(value) {
return parse(value);
}
receiptLog(value) {
return formatter_Formatter.check(this.formats.receiptLog, value);
}
receipt(value) {
const result = formatter_Formatter.check(this.formats.receipt, value);
// RSK incorrectly implemented EIP-658, so we munge things a bit here for it
if (result.root != null) {
if (result.root.length <= 4) {
// Could be 0x00, 0x0, 0x01 or 0x1
const value = bignumber_BigNumber.from(result.root).toNumber();
if (value === 0 || value === 1) {
// Make sure if both are specified, they match
if (result.status != null && (result.status !== value)) {
formatter_logger.throwArgumentError("alt-root-status/status mismatch", "value", { root: result.root, status: result.status });
}
result.status = value;
delete result.root;
}
else {
formatter_logger.throwArgumentError("invalid alt-root-status", "value.root", result.root);
}
}
else if (result.root.length !== 66) {
// Must be a valid bytes32
formatter_logger.throwArgumentError("invalid root hash", "value.root", result.root);
}
}
if (result.status != null) {
result.byzantium = true;
}
return result;
}
topics(value) {
if (Array.isArray(value)) {
return value.map((v) => this.topics(v));
}
else if (value != null) {
return this.hash(value, true);
}
return null;
}
filter(value) {
return formatter_Formatter.check(this.formats.filter, value);
}
filterLog(value) {
return formatter_Formatter.check(this.formats.filterLog, value);
}
static check(format, object) {
const result = {};
for (const key in format) {
try {
const value = format[key](object[key]);
if (value !== undefined) {
result[key] = value;
}
}
catch (error) {
error.checkKey = key;
error.checkValue = object[key];
throw error;
}
}
return result;
}
// if value is null-ish, nullValue is returned
static allowNull(format, nullValue) {
return (function (value) {
if (value == null) {
return nullValue;
}
return format(value);
});
}
// If value is false-ish, replaceValue is returned
static allowFalsish(format, replaceValue) {
return (function (value) {
if (!value) {
return replaceValue;
}
return format(value);
});
}
// Requires an Array satisfying check
static arrayOf(format) {
return (function (array) {
if (!Array.isArray(array)) {
throw new Error("not an array");
}
const result = [];
array.forEach(function (value) {
result.push(format(value));
});
return result;
});
}
}
function isCommunityResourcable(value) {
return (value && typeof (value.isCommunityResource) === "function");
}
function isCommunityResource(value) {
return (isCommunityResourcable(value) && value.isCommunityResource());
}
// Show the throttle message only once
let throttleMessage = false;
function showThrottleMessage() {
if (throttleMessage) {
return;
}
throttleMessage = true;
console.log("========= NOTICE =========");
console.log("Request-Rate Exceeded (this message will not be repeated)");
console.log("");
console.log("The default API keys for each service are provided as a highly-throttled,");
console.log("community resource for low-traffic projects and early prototyping.");
console.log("");
console.log("While your application will continue to function, we highly recommended");
console.log("signing up for your own API keys to improve performance, increase your");
console.log("request rate/limit and enable other perks, such as metrics and advanced APIs.");
console.log("");
console.log("For more details: https:/\/docs.ethers.io/api-keys/");
console.log("==========================");
}
//# sourceMappingURL=formatter.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/base-provider.js
var base_provider_awaiter = (undefined && undefined.__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());
});
};
const base_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
const MAX_CCIP_REDIRECTS = 10;
//////////////////////////////
// Event Serializeing
function checkTopic(topic) {
if (topic == null) {
return "null";
}
if (hexDataLength(topic) !== 32) {
base_provider_logger.throwArgumentError("invalid topic", "topic", topic);
}
return topic.toLowerCase();
}
function serializeTopics(topics) {
// Remove trailing null AND-topics; they are redundant
topics = topics.slice();
while (topics.length > 0 && topics[topics.length - 1] == null) {
topics.pop();
}
return topics.map((topic) => {
if (Array.isArray(topic)) {
// Only track unique OR-topics
const unique = {};
topic.forEach((topic) => {
unique[checkTopic(topic)] = true;
});
// The order of OR-topics does not matter
const sorted = Object.keys(unique);
sorted.sort();
return sorted.join("|");
}
else {
return checkTopic(topic);
}
}).join("&");
}
function deserializeTopics(data) {
if (data === "") {
return [];
}
return data.split(/&/g).map((topic) => {
if (topic === "") {
return [];
}
const comps = topic.split("|").map((topic) => {
return ((topic === "null") ? null : topic);
});
return ((comps.length === 1) ? comps[0] : comps);
});
}
function getEventTag(eventName) {
if (typeof (eventName) === "string") {
eventName = eventName.toLowerCase();
if (hexDataLength(eventName) === 32) {
return "tx:" + eventName;
}
if (eventName.indexOf(":") === -1) {
return eventName;
}
}
else if (Array.isArray(eventName)) {
return "filter:*:" + serializeTopics(eventName);
}
else if (lib_esm_ForkEvent.isForkEvent(eventName)) {
base_provider_logger.warn("not implemented");
throw new Error("not implemented");
}
else if (eventName && typeof (eventName) === "object") {
return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []);
}
throw new Error("invalid event - " + eventName);
}
//////////////////////////////
// Helper Object
function getTime() {
return (new Date()).getTime();
}
function stall(duration) {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}
//////////////////////////////
// Provider Object
/**
* EventType
* - "block"
* - "poll"
* - "didPoll"
* - "pending"
* - "error"
* - "network"
* - filter
* - topics array
* - transaction hash
*/
const PollableEvents = ["block", "network", "pending", "poll"];
class base_provider_Event {
constructor(tag, listener, once) {
defineReadOnly(this, "tag", tag);
defineReadOnly(this, "listener", listener);
defineReadOnly(this, "once", once);
this._lastBlockNumber = -2;
this._inflight = false;
}
get event() {
switch (this.type) {
case "tx":
return this.hash;
case "filter":
return this.filter;
}
return this.tag;
}
get type() {
return this.tag.split(":")[0];
}
get hash() {
const comps = this.tag.split(":");
if (comps[0] !== "tx") {
return null;
}
return comps[1];
}
get filter() {
const comps = this.tag.split(":");
if (comps[0] !== "filter") {
return null;
}
const address = comps[1];
const topics = deserializeTopics(comps[2]);
const filter = {};
if (topics.length > 0) {
filter.topics = topics;
}
if (address && address !== "*") {
filter.address = address;
}
return filter;
}
pollable() {
return (this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0);
}
}
;
// https://github.com/satoshilabs/slips/blob/master/slip-0044.md
const coinInfos = {
"0": { symbol: "btc", p2pkh: 0x00, p2sh: 0x05, prefix: "bc" },
"2": { symbol: "ltc", p2pkh: 0x30, p2sh: 0x32, prefix: "ltc" },
"3": { symbol: "doge", p2pkh: 0x1e, p2sh: 0x16 },
"60": { symbol: "eth", ilk: "eth" },
"61": { symbol: "etc", ilk: "eth" },
"700": { symbol: "xdai", ilk: "eth" },
};
function bytes32ify(value) {
return hexZeroPad(bignumber_BigNumber.from(value).toHexString(), 32);
}
// Compute the Base58Check encoded data (checksum is first 4 bytes of sha256d)
function base58Encode(data) {
return Base58.encode(concat([data, hexDataSlice(sha256(sha256(data)), 0, 4)]));
}
const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i");
const matchers = [
new RegExp("^(https):/\/(.*)$", "i"),
new RegExp("^(data):(.*)$", "i"),
matcherIpfs,
new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"),
];
function _parseString(result, start) {
try {
return toUtf8String(_parseBytes(result, start));
}
catch (error) { }
return null;
}
function _parseBytes(result, start) {
if (result === "0x") {
return null;
}
const offset = bignumber_BigNumber.from(hexDataSlice(result, start, start + 32)).toNumber();
const length = bignumber_BigNumber.from(hexDataSlice(result, offset, offset + 32)).toNumber();
return hexDataSlice(result, offset + 32, offset + 32 + length);
}
// Trim off the ipfs:// prefix and return the default gateway URL
function getIpfsLink(link) {
if (link.match(/^ipfs:\/\/ipfs\//i)) {
link = link.substring(12);
}
else if (link.match(/^ipfs:\/\//i)) {
link = link.substring(7);
}
else {
base_provider_logger.throwArgumentError("unsupported IPFS format", "link", link);
}
return `https:/\/gateway.ipfs.io/ipfs/${link}`;
}
function numPad(value) {
const result = arrayify(value);
if (result.length > 32) {
throw new Error("internal; should not happen");
}
const padded = new Uint8Array(32);
padded.set(result, 32 - result.length);
return padded;
}
function bytesPad(value) {
if ((value.length % 32) === 0) {
return value;
}
const result = new Uint8Array(Math.ceil(value.length / 32) * 32);
result.set(value);
return result;
}
// ABI Encodes a series of (bytes, bytes, ...)
function encodeBytes(datas) {
const result = [];
let byteCount = 0;
// Add place-holders for pointers as we add items
for (let i = 0; i < datas.length; i++) {
result.push(null);
byteCount += 32;
}
for (let i = 0; i < datas.length; i++) {
const data = arrayify(datas[i]);
// Update the bytes offset
result[i] = numPad(byteCount);
// The length and padded value of data
result.push(numPad(data.length));
result.push(bytesPad(data));
byteCount += 32 + Math.ceil(data.length / 32) * 32;
}
return hexConcat(result);
}
class base_provider_Resolver {
// The resolvedAddress is only for creating a ReverseLookup resolver
constructor(provider, address, name, resolvedAddress) {
defineReadOnly(this, "provider", provider);
defineReadOnly(this, "name", name);
defineReadOnly(this, "address", provider.formatter.address(address));
defineReadOnly(this, "_resolvedAddress", resolvedAddress);
}
supportsWildcard() {
if (!this._supportsEip2544) {
// supportsInterface(bytes4 = selector("resolve(bytes,bytes)"))
this._supportsEip2544 = this.provider.call({
to: this.address,
data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000"
}).then((result) => {
return bignumber_BigNumber.from(result).eq(1);
}).catch((error) => {
if (error.code === lib_esm_Logger.errors.CALL_EXCEPTION) {
return false;
}
// Rethrow the error: link is down, etc. Let future attempts retry.
this._supportsEip2544 = null;
throw error;
});
}
return this._supportsEip2544;
}
_fetch(selector, parameters) {
return base_provider_awaiter(this, void 0, void 0, function* () {
// e.g. keccak256("addr(bytes32,uint256)")
const tx = {
to: this.address,
ccipReadEnabled: true,
data: hexConcat([selector, namehash(this.name), (parameters || "0x")])
};
// Wildcard support; use EIP-2544 to resolve the request
let parseBytes = false;
if (yield this.supportsWildcard()) {
parseBytes = true;
// selector("resolve(bytes,bytes)")
tx.data = hexConcat(["0x9061b923", encodeBytes([dnsEncode(this.name), tx.data])]);
}
try {
let result = yield this.provider.call(tx);
if ((arrayify(result).length % 32) === 4) {
base_provider_logger.throwError("resolver threw error", lib_esm_Logger.errors.CALL_EXCEPTION, {
transaction: tx, data: result
});
}
if (parseBytes) {
result = _parseBytes(result, 0);
}
return result;
}
catch (error) {
if (error.code === lib_esm_Logger.errors.CALL_EXCEPTION) {
return null;
}
throw error;
}
});
}
_fetchBytes(selector, parameters) {
return base_provider_awaiter(this, void 0, void 0, function* () {
const result = yield this._fetch(selector, parameters);
if (result != null) {
return _parseBytes(result, 0);
}
return null;
});
}
_getAddress(coinType, hexBytes) {
const coinInfo = coinInfos[String(coinType)];
if (coinInfo == null) {
base_provider_logger.throwError(`unsupported coin type: ${coinType}`, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: `getAddress(${coinType})`
});
}
if (coinInfo.ilk === "eth") {
return this.provider.formatter.address(hexBytes);
}
const bytes = arrayify(hexBytes);
// P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
if (coinInfo.p2pkh != null) {
const p2pkh = hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);
if (p2pkh) {
const length = parseInt(p2pkh[1], 16);
if (p2pkh[2].length === length * 2 && length >= 1 && length <= 75) {
return base58Encode(concat([[coinInfo.p2pkh], ("0x" + p2pkh[2])]));
}
}
}
// P2SH: OP_HASH160 <scriptHash> OP_EQUAL
if (coinInfo.p2sh != null) {
const p2sh = hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);
if (p2sh) {
const length = parseInt(p2sh[1], 16);
if (p2sh[2].length === length * 2 && length >= 1 && length <= 75) {
return base58Encode(concat([[coinInfo.p2sh], ("0x" + p2sh[2])]));
}
}
}
// Bech32
if (coinInfo.prefix != null) {
const length = bytes[1];
// https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program
let version = bytes[0];
if (version === 0x00) {
if (length !== 20 && length !== 32) {
version = -1;
}
}
else {
version = -1;
}
if (version >= 0 && bytes.length === 2 + length && length >= 1 && length <= 75) {
const words = bech32_default.a.toWords(bytes.slice(2));
words.unshift(version);
return bech32_default.a.encode(coinInfo.prefix, words);
}
}
return null;
}
getAddress(coinType) {
return base_provider_awaiter(this, void 0, void 0, function* () {
if (coinType == null) {
coinType = 60;
}
// If Ethereum, use the standard `addr(bytes32)`
if (coinType === 60) {
try {
// keccak256("addr(bytes32)")
const result = yield this._fetch("0x3b3b57de");
// No address
if (result === "0x" || result === HashZero) {
return null;
}
return this.provider.formatter.callAddress(result);
}
catch (error) {
if (error.code === lib_esm_Logger.errors.CALL_EXCEPTION) {
return null;
}
throw error;
}
}
// keccak256("addr(bytes32,uint256")
const hexBytes = yield this._fetchBytes("0xf1cb7e06", bytes32ify(coinType));
// No address
if (hexBytes == null || hexBytes === "0x") {
return null;
}
// Compute the address
const address = this._getAddress(coinType, hexBytes);
if (address == null) {
base_provider_logger.throwError(`invalid or unsupported coin data`, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: `getAddress(${coinType})`,
coinType: coinType,
data: hexBytes
});
}
return address;
});
}
getAvatar() {
return base_provider_awaiter(this, void 0, void 0, function* () {
const linkage = [{ type: "name", content: this.name }];
try {
// test data for ricmoo.eth
//const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233";
const avatar = yield this.getText("avatar");
if (avatar == null) {
return null;
}
for (let i = 0; i < matchers.length; i++) {
const match = avatar.match(matchers[i]);
if (match == null) {
continue;
}
const scheme = match[1].toLowerCase();
switch (scheme) {
case "https":
linkage.push({ type: "url", content: avatar });
return { linkage, url: avatar };
case "data":
linkage.push({ type: "data", content: avatar });
return { linkage, url: avatar };
case "ipfs":
linkage.push({ type: "ipfs", content: avatar });
return { linkage, url: getIpfsLink(avatar) };
case "erc721":
case "erc1155": {
// Depending on the ERC type, use tokenURI(uint256) or url(uint256)
const selector = (scheme === "erc721") ? "0xc87b56dd" : "0x0e89341c";
linkage.push({ type: scheme, content: avatar });
// The owner of this name
const owner = (this._resolvedAddress || (yield this.getAddress()));
const comps = (match[2] || "").split("/");
if (comps.length !== 2) {
return null;
}
const addr = yield this.provider.formatter.address(comps[0]);
const tokenId = hexZeroPad(bignumber_BigNumber.from(comps[1]).toHexString(), 32);
// Check that this account owns the token
if (scheme === "erc721") {
// ownerOf(uint256 tokenId)
const tokenOwner = this.provider.formatter.callAddress(yield this.provider.call({
to: addr, data: hexConcat(["0x6352211e", tokenId])
}));
if (owner !== tokenOwner) {
return null;
}
linkage.push({ type: "owner", content: tokenOwner });
}
else if (scheme === "erc1155") {
// balanceOf(address owner, uint256 tokenId)
const balance = bignumber_BigNumber.from(yield this.provider.call({
to: addr, data: hexConcat(["0x00fdd58e", hexZeroPad(owner, 32), tokenId])
}));
if (balance.isZero()) {
return null;
}
linkage.push({ type: "balance", content: balance.toString() });
}
// Call the token contract for the metadata URL
const tx = {
to: this.provider.formatter.address(comps[0]),
data: hexConcat([selector, tokenId])
};
let metadataUrl = _parseString(yield this.provider.call(tx), 0);
if (metadataUrl == null) {
return null;
}
linkage.push({ type: "metadata-url-base", content: metadataUrl });
// ERC-1155 allows a generic {id} in the URL
if (scheme === "erc1155") {
metadataUrl = metadataUrl.replace("{id}", tokenId.substring(2));
linkage.push({ type: "metadata-url-expanded", content: metadataUrl });
}
// Transform IPFS metadata links
if (metadataUrl.match(/^ipfs:/i)) {
metadataUrl = getIpfsLink(metadataUrl);
}
linkage.push({ type: "metadata-url", content: metadataUrl });
// Get the token metadata
const metadata = yield fetchJson(metadataUrl);
if (!metadata) {
return null;
}
linkage.push({ type: "metadata", content: JSON.stringify(metadata) });
// Pull the image URL out
let imageUrl = metadata.image;
if (typeof (imageUrl) !== "string") {
return null;
}
if (imageUrl.match(/^(https:\/\/|data:)/i)) {
// Allow
}
else {
// Transform IPFS link to gateway
const ipfs = imageUrl.match(matcherIpfs);
if (ipfs == null) {
return null;
}
linkage.push({ type: "url-ipfs", content: imageUrl });
imageUrl = getIpfsLink(imageUrl);
}
linkage.push({ type: "url", content: imageUrl });
return { linkage, url: imageUrl };
}
}
}
}
catch (error) { }
return null;
});
}
getContentHash() {
return base_provider_awaiter(this, void 0, void 0, function* () {
// keccak256("contenthash()")
const hexBytes = yield this._fetchBytes("0xbc1c58d1");
// No contenthash
if (hexBytes == null || hexBytes === "0x") {
return null;
}
// IPFS (CID: 1, Type: DAG-PB)
const ipfs = hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
if (ipfs) {
const length = parseInt(ipfs[3], 16);
if (ipfs[4].length === length * 2) {
return "ipfs:/\/" + Base58.encode("0x" + ipfs[1]);
}
}
// IPNS (CID: 1, Type: libp2p-key)
const ipns = hexBytes.match(/^0xe5010172(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
if (ipns) {
const length = parseInt(ipns[3], 16);
if (ipns[4].length === length * 2) {
return "ipns:/\/" + Base58.encode("0x" + ipns[1]);
}
}
// Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32)
const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/);
if (swarm) {
if (swarm[1].length === (32 * 2)) {
return "bzz:/\/" + swarm[1];
}
}
const skynet = hexBytes.match(/^0x90b2c605([0-9a-f]*)$/);
if (skynet) {
if (skynet[1].length === (34 * 2)) {
// URL Safe base64; https://datatracker.ietf.org/doc/html/rfc4648#section-5
const urlSafe = { "=": "", "+": "-", "/": "_" };
const hash = encode("0x" + skynet[1]).replace(/[=+\/]/g, (a) => (urlSafe[a]));
return "sia:/\/" + hash;
}
}
return base_provider_logger.throwError(`invalid or unsupported content hash data`, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "getContentHash()",
data: hexBytes
});
});
}
getText(key) {
return base_provider_awaiter(this, void 0, void 0, function* () {
// The key encoded as parameter to fetchBytes
let keyBytes = toUtf8Bytes(key);
// The nodehash consumes the first slot, so the string pointer targets
// offset 64, with the length at offset 64 and data starting at offset 96
keyBytes = concat([bytes32ify(64), bytes32ify(keyBytes.length), keyBytes]);
// Pad to word-size (32 bytes)
if ((keyBytes.length % 32) !== 0) {
keyBytes = concat([keyBytes, hexZeroPad("0x", 32 - (key.length % 32))]);
}
const hexBytes = yield this._fetchBytes("0x59d1d43c", hexlify(keyBytes));
if (hexBytes == null || hexBytes === "0x") {
return null;
}
return toUtf8String(hexBytes);
});
}
}
let defaultFormatter = null;
let nextPollId = 1;
class base_provider_BaseProvider extends lib_esm_Provider {
/**
* ready
*
* A Promise<Network> that resolves only once the provider is ready.
*
* Sub-classes that call the super with a network without a chainId
* MUST set this. Standard named networks have a known chainId.
*
*/
constructor(network) {
super();
// Events being listened to
this._events = [];
this._emitted = { block: -2 };
this.disableCcipRead = false;
this.formatter = new.target.getFormatter();
// If network is any, this Provider allows the underlying
// network to change dynamically, and we auto-detect the
// current network
defineReadOnly(this, "anyNetwork", (network === "any"));
if (this.anyNetwork) {
network = this.detectNetwork();
}
if (network instanceof Promise) {
this._networkPromise = network;
// Squash any "unhandled promise" errors; that do not need to be handled
network.catch((error) => { });
// Trigger initial network setting (async)
this._ready().catch((error) => { });
}
else {
const knownNetwork = getStatic(new.target, "getNetwork")(network);
if (knownNetwork) {
defineReadOnly(this, "_network", knownNetwork);
this.emit("network", knownNetwork, null);
}
else {
base_provider_logger.throwArgumentError("invalid network", "network", network);
}
}
this._maxInternalBlockNumber = -1024;
this._lastBlockNumber = -2;
this._maxFilterBlockRange = 10;
this._pollingInterval = 4000;
this._fastQueryDate = 0;
}
_ready() {
return base_provider_awaiter(this, void 0, void 0, function* () {
if (this._network == null) {
let network = null;
if (this._networkPromise) {
try {
network = yield this._networkPromise;
}
catch (error) { }
}
// Try the Provider's network detection (this MUST throw if it cannot)
if (network == null) {
network = yield this.detectNetwork();
}
// This should never happen; every Provider sub-class should have
// suggested a network by here (or have thrown).
if (!network) {
base_provider_logger.throwError("no network detected", lib_esm_Logger.errors.UNKNOWN_ERROR, {});
}
// Possible this call stacked so do not call defineReadOnly again
if (this._network == null) {
if (this.anyNetwork) {
this._network = network;
}
else {
defineReadOnly(this, "_network", network);
}
this.emit("network", network, null);
}
}
return this._network;
});
}
// This will always return the most recently established network.
// For "any", this can change (a "network" event is emitted before
// any change is reflected); otherwise this cannot change
get ready() {
return lib_esm_poll(() => {
return this._ready().then((network) => {
return network;
}, (error) => {
// If the network isn't running yet, we will wait
if (error.code === lib_esm_Logger.errors.NETWORK_ERROR && error.event === "noNetwork") {
return undefined;
}
throw error;
});
});
}
// @TODO: Remove this and just create a singleton formatter
static getFormatter() {
if (defaultFormatter == null) {
defaultFormatter = new formatter_Formatter();
}
return defaultFormatter;
}
// @TODO: Remove this and just use getNetwork
static getNetwork(network) {
return lib_esm_getNetwork((network == null) ? "homestead" : network);
}
ccipReadFetch(tx, calldata, urls) {
return base_provider_awaiter(this, void 0, void 0, function* () {
if (this.disableCcipRead || urls.length === 0) {
return null;
}
const sender = tx.to.toLowerCase();
const data = calldata.toLowerCase();
const errorMessages = [];
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
// URL expansion
const href = url.replace("{sender}", sender).replace("{data}", data);
// If no {data} is present, use POST; otherwise GET
const json = (url.indexOf("{data}") >= 0) ? null : JSON.stringify({ data, sender });
const result = yield fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => {
value.status = response.statusCode;
return value;
});
if (result.data) {
return result.data;
}
const errorMessage = (result.message || "unknown error");
// 4xx indicates the result is not present; stop
if (result.status >= 400 && result.status < 500) {
return base_provider_logger.throwError(`response not found during CCIP fetch: ${errorMessage}`, lib_esm_Logger.errors.SERVER_ERROR, { url, errorMessage });
}
// 5xx indicates server issue; try the next url
errorMessages.push(errorMessage);
}
return base_provider_logger.throwError(`error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, lib_esm_Logger.errors.SERVER_ERROR, {
urls, errorMessages
});
});
}
// Fetches the blockNumber, but will reuse any result that is less
// than maxAge old or has been requested since the last request
_getInternalBlockNumber(maxAge) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this._ready();
// Allowing stale data up to maxAge old
if (maxAge > 0) {
// While there are pending internal block requests...
while (this._internalBlockNumber) {
// ..."remember" which fetch we started with
const internalBlockNumber = this._internalBlockNumber;
try {
// Check the result is not too stale
const result = yield internalBlockNumber;
if ((getTime() - result.respTime) <= maxAge) {
return result.blockNumber;
}
// Too old; fetch a new value
break;
}
catch (error) {
// The fetch rejected; if we are the first to get the
// rejection, drop through so we replace it with a new
// fetch; all others blocked will then get that fetch
// which won't match the one they "remembered" and loop
if (this._internalBlockNumber === internalBlockNumber) {
break;
}
}
}
}
const reqTime = getTime();
const checkInternalBlockNumber = resolveProperties({
blockNumber: this.perform("getBlockNumber", {}),
networkError: this.getNetwork().then((network) => (null), (error) => (error))
}).then(({ blockNumber, networkError }) => {
if (networkError) {
// Unremember this bad internal block number
if (this._internalBlockNumber === checkInternalBlockNumber) {
this._internalBlockNumber = null;
}
throw networkError;
}
const respTime = getTime();
blockNumber = bignumber_BigNumber.from(blockNumber).toNumber();
if (blockNumber < this._maxInternalBlockNumber) {
blockNumber = this._maxInternalBlockNumber;
}
this._maxInternalBlockNumber = blockNumber;
this._setFastBlockNumber(blockNumber); // @TODO: Still need this?
return { blockNumber, reqTime, respTime };
});
this._internalBlockNumber = checkInternalBlockNumber;
// Swallow unhandled exceptions; if needed they are handled else where
checkInternalBlockNumber.catch((error) => {
// Don't null the dead (rejected) fetch, if it has already been updated
if (this._internalBlockNumber === checkInternalBlockNumber) {
this._internalBlockNumber = null;
}
});
return (yield checkInternalBlockNumber).blockNumber;
});
}
poll() {
return base_provider_awaiter(this, void 0, void 0, function* () {
const pollId = nextPollId++;
// Track all running promises, so we can trigger a post-poll once they are complete
const runners = [];
let blockNumber = null;
try {
blockNumber = yield this._getInternalBlockNumber(100 + this.pollingInterval / 2);
}
catch (error) {
this.emit("error", error);
return;
}
this._setFastBlockNumber(blockNumber);
// Emit a poll event after we have the latest (fast) block number
this.emit("poll", pollId, blockNumber);
// If the block has not changed, meh.
if (blockNumber === this._lastBlockNumber) {
this.emit("didPoll", pollId);
return;
}
// First polling cycle, trigger a "block" events
if (this._emitted.block === -2) {
this._emitted.block = blockNumber - 1;
}
if (Math.abs((this._emitted.block) - blockNumber) > 1000) {
base_provider_logger.warn(`network block skew detected; skipping block events (emitted=${this._emitted.block} blockNumber${blockNumber})`);
this.emit("error", base_provider_logger.makeError("network block skew detected", lib_esm_Logger.errors.NETWORK_ERROR, {
blockNumber: blockNumber,
event: "blockSkew",
previousBlockNumber: this._emitted.block
}));
this.emit("block", blockNumber);
}
else {
// Notify all listener for each block that has passed
for (let i = this._emitted.block + 1; i <= blockNumber; i++) {
this.emit("block", i);
}
}
// The emitted block was updated, check for obsolete events
if (this._emitted.block !== blockNumber) {
this._emitted.block = blockNumber;
Object.keys(this._emitted).forEach((key) => {
// The block event does not expire
if (key === "block") {
return;
}
// The block we were at when we emitted this event
const eventBlockNumber = this._emitted[key];
// We cannot garbage collect pending transactions or blocks here
// They should be garbage collected by the Provider when setting
// "pending" events
if (eventBlockNumber === "pending") {
return;
}
// Evict any transaction hashes or block hashes over 12 blocks
// old, since they should not return null anyways
if (blockNumber - eventBlockNumber > 12) {
delete this._emitted[key];
}
});
}
// First polling cycle
if (this._lastBlockNumber === -2) {
this._lastBlockNumber = blockNumber - 1;
}
// Find all transaction hashes we are waiting on
this._events.forEach((event) => {
switch (event.type) {
case "tx": {
const hash = event.hash;
let runner = this.getTransactionReceipt(hash).then((receipt) => {
if (!receipt || receipt.blockNumber == null) {
return null;
}
this._emitted["t:" + hash] = receipt.blockNumber;
this.emit(hash, receipt);
return null;
}).catch((error) => { this.emit("error", error); });
runners.push(runner);
break;
}
case "filter": {
// We only allow a single getLogs to be in-flight at a time
if (!event._inflight) {
event._inflight = true;
// This is the first filter for this event, so we want to
// restrict events to events that happened no earlier than now
if (event._lastBlockNumber === -2) {
event._lastBlockNumber = blockNumber - 1;
}
// Filter from the last *known* event; due to load-balancing
// and some nodes returning updated block numbers before
// indexing events, a logs result with 0 entries cannot be
// trusted and we must retry a range which includes it again
const filter = event.filter;
filter.fromBlock = event._lastBlockNumber + 1;
filter.toBlock = blockNumber;
// Prevent fitler ranges from growing too wild, since it is quite
// likely there just haven't been any events to move the lastBlockNumber.
const minFromBlock = filter.toBlock - this._maxFilterBlockRange;
if (minFromBlock > filter.fromBlock) {
filter.fromBlock = minFromBlock;
}
if (filter.fromBlock < 0) {
filter.fromBlock = 0;
}
const runner = this.getLogs(filter).then((logs) => {
// Allow the next getLogs
event._inflight = false;
if (logs.length === 0) {
return;
}
logs.forEach((log) => {
// Only when we get an event for a given block number
// can we trust the events are indexed
if (log.blockNumber > event._lastBlockNumber) {
event._lastBlockNumber = log.blockNumber;
}
// Make sure we stall requests to fetch blocks and txs
this._emitted["b:" + log.blockHash] = log.blockNumber;
this._emitted["t:" + log.transactionHash] = log.blockNumber;
this.emit(filter, log);
});
}).catch((error) => {
this.emit("error", error);
// Allow another getLogs (the range was not updated)
event._inflight = false;
});
runners.push(runner);
}
break;
}
}
});
this._lastBlockNumber = blockNumber;
// Once all events for this loop have been processed, emit "didPoll"
Promise.all(runners).then(() => {
this.emit("didPoll", pollId);
}).catch((error) => { this.emit("error", error); });
return;
});
}
// Deprecated; do not use this
resetEventsBlock(blockNumber) {
this._lastBlockNumber = blockNumber - 1;
if (this.polling) {
this.poll();
}
}
get network() {
return this._network;
}
// This method should query the network if the underlying network
// can change, such as when connected to a JSON-RPC backend
detectNetwork() {
return base_provider_awaiter(this, void 0, void 0, function* () {
return base_provider_logger.throwError("provider does not support network detection", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "provider.detectNetwork"
});
});
}
getNetwork() {
return base_provider_awaiter(this, void 0, void 0, function* () {
const network = yield this._ready();
// Make sure we are still connected to the same network; this is
// only an external call for backends which can have the underlying
// network change spontaneously
const currentNetwork = yield this.detectNetwork();
if (network.chainId !== currentNetwork.chainId) {
// We are allowing network changes, things can get complex fast;
// make sure you know what you are doing if you use "any"
if (this.anyNetwork) {
this._network = currentNetwork;
// Reset all internal block number guards and caches
this._lastBlockNumber = -2;
this._fastBlockNumber = null;
this._fastBlockNumberPromise = null;
this._fastQueryDate = 0;
this._emitted.block = -2;
this._maxInternalBlockNumber = -1024;
this._internalBlockNumber = null;
// The "network" event MUST happen before this method resolves
// so any events have a chance to unregister, so we stall an
// additional event loop before returning from /this/ call
this.emit("network", currentNetwork, network);
yield stall(0);
return this._network;
}
const error = base_provider_logger.makeError("underlying network changed", lib_esm_Logger.errors.NETWORK_ERROR, {
event: "changed",
network: network,
detectedNetwork: currentNetwork
});
this.emit("error", error);
throw error;
}
return network;
});
}
get blockNumber() {
this._getInternalBlockNumber(100 + this.pollingInterval / 2).then((blockNumber) => {
this._setFastBlockNumber(blockNumber);
}, (error) => { });
return (this._fastBlockNumber != null) ? this._fastBlockNumber : -1;
}
get polling() {
return (this._poller != null);
}
set polling(value) {
if (value && !this._poller) {
this._poller = setInterval(() => { this.poll(); }, this.pollingInterval);
if (!this._bootstrapPoll) {
this._bootstrapPoll = setTimeout(() => {
this.poll();
// We block additional polls until the polling interval
// is done, to prevent overwhelming the poll function
this._bootstrapPoll = setTimeout(() => {
// If polling was disabled, something may require a poke
// since starting the bootstrap poll and it was disabled
if (!this._poller) {
this.poll();
}
// Clear out the bootstrap so we can do another
this._bootstrapPoll = null;
}, this.pollingInterval);
}, 0);
}
}
else if (!value && this._poller) {
clearInterval(this._poller);
this._poller = null;
}
}
get pollingInterval() {
return this._pollingInterval;
}
set pollingInterval(value) {
if (typeof (value) !== "number" || value <= 0 || parseInt(String(value)) != value) {
throw new Error("invalid polling interval");
}
this._pollingInterval = value;
if (this._poller) {
clearInterval(this._poller);
this._poller = setInterval(() => { this.poll(); }, this._pollingInterval);
}
}
_getFastBlockNumber() {
const now = getTime();
// Stale block number, request a newer value
if ((now - this._fastQueryDate) > 2 * this._pollingInterval) {
this._fastQueryDate = now;
this._fastBlockNumberPromise = this.getBlockNumber().then((blockNumber) => {
if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
this._fastBlockNumber = blockNumber;
}
return this._fastBlockNumber;
});
}
return this._fastBlockNumberPromise;
}
_setFastBlockNumber(blockNumber) {
// Older block, maybe a stale request
if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) {
return;
}
// Update the time we updated the blocknumber
this._fastQueryDate = getTime();
// Newer block number, use it
if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
this._fastBlockNumber = blockNumber;
this._fastBlockNumberPromise = Promise.resolve(blockNumber);
}
}
waitForTransaction(transactionHash, confirmations, timeout) {
return base_provider_awaiter(this, void 0, void 0, function* () {
return this._waitForTransaction(transactionHash, (confirmations == null) ? 1 : confirmations, timeout || 0, null);
});
}
_waitForTransaction(transactionHash, confirmations, timeout, replaceable) {
return base_provider_awaiter(this, void 0, void 0, function* () {
const receipt = yield this.getTransactionReceipt(transactionHash);
// Receipt is already good
if ((receipt ? receipt.confirmations : 0) >= confirmations) {
return receipt;
}
// Poll until the receipt is good...
return new Promise((resolve, reject) => {
const cancelFuncs = [];
let done = false;
const alreadyDone = function () {
if (done) {
return true;
}
done = true;
cancelFuncs.forEach((func) => { func(); });
return false;
};
const minedHandler = (receipt) => {
if (receipt.confirmations < confirmations) {
return;
}
if (alreadyDone()) {
return;
}
resolve(receipt);
};
this.on(transactionHash, minedHandler);
cancelFuncs.push(() => { this.removeListener(transactionHash, minedHandler); });
if (replaceable) {
let lastBlockNumber = replaceable.startBlock;
let scannedBlock = null;
const replaceHandler = (blockNumber) => base_provider_awaiter(this, void 0, void 0, function* () {
if (done) {
return;
}
// Wait 1 second; this is only used in the case of a fault, so
// we will trade off a little bit of latency for more consistent
// results and fewer JSON-RPC calls
yield stall(1000);
this.getTransactionCount(replaceable.from).then((nonce) => base_provider_awaiter(this, void 0, void 0, function* () {
if (done) {
return;
}
if (nonce <= replaceable.nonce) {
lastBlockNumber = blockNumber;
}
else {
// First check if the transaction was mined
{
const mined = yield this.getTransaction(transactionHash);
if (mined && mined.blockNumber != null) {
return;
}
}
// First time scanning. We start a little earlier for some
// wiggle room here to handle the eventually consistent nature
// of blockchain (e.g. the getTransactionCount was for a
// different block)
if (scannedBlock == null) {
scannedBlock = lastBlockNumber - 3;
if (scannedBlock < replaceable.startBlock) {
scannedBlock = replaceable.startBlock;
}
}
while (scannedBlock <= blockNumber) {
if (done) {
return;
}
const block = yield this.getBlockWithTransactions(scannedBlock);
for (let ti = 0; ti < block.transactions.length; ti++) {
const tx = block.transactions[ti];
// Successfully mined!
if (tx.hash === transactionHash) {
return;
}
// Matches our transaction from and nonce; its a replacement
if (tx.from === replaceable.from && tx.nonce === replaceable.nonce) {
if (done) {
return;
}
// Get the receipt of the replacement
const receipt = yield this.waitForTransaction(tx.hash, confirmations);
// Already resolved or rejected (prolly a timeout)
if (alreadyDone()) {
return;
}
// The reason we were replaced
let reason = "replaced";
if (tx.data === replaceable.data && tx.to === replaceable.to && tx.value.eq(replaceable.value)) {
reason = "repriced";
}
else if (tx.data === "0x" && tx.from === tx.to && tx.value.isZero()) {
reason = "cancelled";
}
// Explain why we were replaced
reject(base_provider_logger.makeError("transaction was replaced", lib_esm_Logger.errors.TRANSACTION_REPLACED, {
cancelled: (reason === "replaced" || reason === "cancelled"),
reason,
replacement: this._wrapTransaction(tx),
hash: transactionHash,
receipt
}));
return;
}
}
scannedBlock++;
}
}
if (done) {
return;
}
this.once("block", replaceHandler);
}), (error) => {
if (done) {
return;
}
this.once("block", replaceHandler);
});
});
if (done) {
return;
}
this.once("block", replaceHandler);
cancelFuncs.push(() => {
this.removeListener("block", replaceHandler);
});
}
if (typeof (timeout) === "number" && timeout > 0) {
const timer = setTimeout(() => {
if (alreadyDone()) {
return;
}
reject(base_provider_logger.makeError("timeout exceeded", lib_esm_Logger.errors.TIMEOUT, { timeout: timeout }));
}, timeout);
if (timer.unref) {
timer.unref();
}
cancelFuncs.push(() => { clearTimeout(timer); });
}
});
});
}
getBlockNumber() {
return base_provider_awaiter(this, void 0, void 0, function* () {
return this._getInternalBlockNumber(0);
});
}
getGasPrice() {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const result = yield this.perform("getGasPrice", {});
try {
return bignumber_BigNumber.from(result);
}
catch (error) {
return base_provider_logger.throwError("bad result from backend", lib_esm_Logger.errors.SERVER_ERROR, {
method: "getGasPrice",
result, error
});
}
});
}
getBalance(addressOrName, blockTag) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const params = yield resolveProperties({
address: this._getAddress(addressOrName),
blockTag: this._getBlockTag(blockTag)
});
const result = yield this.perform("getBalance", params);
try {
return bignumber_BigNumber.from(result);
}
catch (error) {
return base_provider_logger.throwError("bad result from backend", lib_esm_Logger.errors.SERVER_ERROR, {
method: "getBalance",
params, result, error
});
}
});
}
getTransactionCount(addressOrName, blockTag) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const params = yield resolveProperties({
address: this._getAddress(addressOrName),
blockTag: this._getBlockTag(blockTag)
});
const result = yield this.perform("getTransactionCount", params);
try {
return bignumber_BigNumber.from(result).toNumber();
}
catch (error) {
return base_provider_logger.throwError("bad result from backend", lib_esm_Logger.errors.SERVER_ERROR, {
method: "getTransactionCount",
params, result, error
});
}
});
}
getCode(addressOrName, blockTag) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const params = yield resolveProperties({
address: this._getAddress(addressOrName),
blockTag: this._getBlockTag(blockTag)
});
const result = yield this.perform("getCode", params);
try {
return hexlify(result);
}
catch (error) {
return base_provider_logger.throwError("bad result from backend", lib_esm_Logger.errors.SERVER_ERROR, {
method: "getCode",
params, result, error
});
}
});
}
getStorageAt(addressOrName, position, blockTag) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const params = yield resolveProperties({
address: this._getAddress(addressOrName),
blockTag: this._getBlockTag(blockTag),
position: Promise.resolve(position).then((p) => hexValue(p))
});
const result = yield this.perform("getStorageAt", params);
try {
return hexlify(result);
}
catch (error) {
return base_provider_logger.throwError("bad result from backend", lib_esm_Logger.errors.SERVER_ERROR, {
method: "getStorageAt",
params, result, error
});
}
});
}
// This should be called by any subclass wrapping a TransactionResponse
_wrapTransaction(tx, hash, startBlock) {
if (hash != null && hexDataLength(hash) !== 32) {
throw new Error("invalid response - sendTransaction");
}
const result = tx;
// Check the hash we expect is the same as the hash the server reported
if (hash != null && tx.hash !== hash) {
base_provider_logger.throwError("Transaction hash mismatch from Provider.sendTransaction.", lib_esm_Logger.errors.UNKNOWN_ERROR, { expectedHash: tx.hash, returnedHash: hash });
}
result.wait = (confirms, timeout) => base_provider_awaiter(this, void 0, void 0, function* () {
if (confirms == null) {
confirms = 1;
}
if (timeout == null) {
timeout = 0;
}
// Get the details to detect replacement
let replacement = undefined;
if (confirms !== 0 && startBlock != null) {
replacement = {
data: tx.data,
from: tx.from,
nonce: tx.nonce,
to: tx.to,
value: tx.value,
startBlock
};
}
const receipt = yield this._waitForTransaction(tx.hash, confirms, timeout, replacement);
if (receipt == null && confirms === 0) {
return null;
}
// No longer pending, allow the polling loop to garbage collect this
this._emitted["t:" + tx.hash] = receipt.blockNumber;
if (receipt.status === 0) {
base_provider_logger.throwError("transaction failed", lib_esm_Logger.errors.CALL_EXCEPTION, {
transactionHash: tx.hash,
transaction: tx,
receipt: receipt
});
}
return receipt;
});
return result;
}
sendTransaction(signedTransaction) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const hexTx = yield Promise.resolve(signedTransaction).then(t => hexlify(t));
const tx = this.formatter.transaction(signedTransaction);
if (tx.confirmations == null) {
tx.confirmations = 0;
}
const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
try {
const hash = yield this.perform("sendTransaction", { signedTransaction: hexTx });
return this._wrapTransaction(tx, hash, blockNumber);
}
catch (error) {
error.transaction = tx;
error.transactionHash = tx.hash;
throw error;
}
});
}
_getTransactionRequest(transaction) {
return base_provider_awaiter(this, void 0, void 0, function* () {
const values = yield transaction;
const tx = {};
["from", "to"].forEach((key) => {
if (values[key] == null) {
return;
}
tx[key] = Promise.resolve(values[key]).then((v) => (v ? this._getAddress(v) : null));
});
["gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "value"].forEach((key) => {
if (values[key] == null) {
return;
}
tx[key] = Promise.resolve(values[key]).then((v) => (v ? bignumber_BigNumber.from(v) : null));
});
["type"].forEach((key) => {
if (values[key] == null) {
return;
}
tx[key] = Promise.resolve(values[key]).then((v) => ((v != null) ? v : null));
});
if (values.accessList) {
tx.accessList = this.formatter.accessList(values.accessList);
}
["data"].forEach((key) => {
if (values[key] == null) {
return;
}
tx[key] = Promise.resolve(values[key]).then((v) => (v ? hexlify(v) : null));
});
return this.formatter.transactionRequest(yield resolveProperties(tx));
});
}
_getFilter(filter) {
return base_provider_awaiter(this, void 0, void 0, function* () {
filter = yield filter;
const result = {};
if (filter.address != null) {
result.address = this._getAddress(filter.address);
}
["blockHash", "topics"].forEach((key) => {
if (filter[key] == null) {
return;
}
result[key] = filter[key];
});
["fromBlock", "toBlock"].forEach((key) => {
if (filter[key] == null) {
return;
}
result[key] = this._getBlockTag(filter[key]);
});
return this.formatter.filter(yield resolveProperties(result));
});
}
_call(transaction, blockTag, attempt) {
return base_provider_awaiter(this, void 0, void 0, function* () {
if (attempt >= MAX_CCIP_REDIRECTS) {
base_provider_logger.throwError("CCIP read exceeded maximum redirections", lib_esm_Logger.errors.SERVER_ERROR, {
redirects: attempt, transaction
});
}
const txSender = transaction.to;
const result = yield this.perform("call", { transaction, blockTag });
// CCIP Read request via OffchainLookup(address,string[],bytes,bytes4,bytes)
if (attempt >= 0 && blockTag === "latest" && txSender != null && result.substring(0, 10) === "0x556f1830" && (hexDataLength(result) % 32 === 4)) {
try {
const data = hexDataSlice(result, 4);
// Check the sender of the OffchainLookup matches the transaction
const sender = hexDataSlice(data, 0, 32);
if (!bignumber_BigNumber.from(sender).eq(txSender)) {
base_provider_logger.throwError("CCIP Read sender did not match", lib_esm_Logger.errors.CALL_EXCEPTION, {
name: "OffchainLookup",
signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
transaction, data: result
});
}
// Read the URLs from the response
const urls = [];
const urlsOffset = bignumber_BigNumber.from(hexDataSlice(data, 32, 64)).toNumber();
const urlsLength = bignumber_BigNumber.from(hexDataSlice(data, urlsOffset, urlsOffset + 32)).toNumber();
const urlsData = hexDataSlice(data, urlsOffset + 32);
for (let u = 0; u < urlsLength; u++) {
const url = _parseString(urlsData, u * 32);
if (url == null) {
base_provider_logger.throwError("CCIP Read contained corrupt URL string", lib_esm_Logger.errors.CALL_EXCEPTION, {
name: "OffchainLookup",
signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
transaction, data: result
});
}
urls.push(url);
}
// Get the CCIP calldata to forward
const calldata = _parseBytes(data, 64);
// Get the callbackSelector (bytes4)
if (!bignumber_BigNumber.from(hexDataSlice(data, 100, 128)).isZero()) {
base_provider_logger.throwError("CCIP Read callback selector included junk", lib_esm_Logger.errors.CALL_EXCEPTION, {
name: "OffchainLookup",
signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
transaction, data: result
});
}
const callbackSelector = hexDataSlice(data, 96, 100);
// Get the extra data to send back to the contract as context
const extraData = _parseBytes(data, 128);
const ccipResult = yield this.ccipReadFetch(transaction, calldata, urls);
if (ccipResult == null) {
base_provider_logger.throwError("CCIP Read disabled or provided no URLs", lib_esm_Logger.errors.CALL_EXCEPTION, {
name: "OffchainLookup",
signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
transaction, data: result
});
}
const tx = {
to: txSender,
data: hexConcat([callbackSelector, encodeBytes([ccipResult, extraData])])
};
return this._call(tx, blockTag, attempt + 1);
}
catch (error) {
if (error.code === lib_esm_Logger.errors.SERVER_ERROR) {
throw error;
}
}
}
try {
return hexlify(result);
}
catch (error) {
return base_provider_logger.throwError("bad result from backend", lib_esm_Logger.errors.SERVER_ERROR, {
method: "call",
params: { transaction, blockTag }, result, error
});
}
});
}
call(transaction, blockTag) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const resolved = yield resolveProperties({
transaction: this._getTransactionRequest(transaction),
blockTag: this._getBlockTag(blockTag),
ccipReadEnabled: Promise.resolve(transaction.ccipReadEnabled)
});
return this._call(resolved.transaction, resolved.blockTag, resolved.ccipReadEnabled ? 0 : -1);
});
}
estimateGas(transaction) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const params = yield resolveProperties({
transaction: this._getTransactionRequest(transaction)
});
const result = yield this.perform("estimateGas", params);
try {
return bignumber_BigNumber.from(result);
}
catch (error) {
return base_provider_logger.throwError("bad result from backend", lib_esm_Logger.errors.SERVER_ERROR, {
method: "estimateGas",
params, result, error
});
}
});
}
_getAddress(addressOrName) {
return base_provider_awaiter(this, void 0, void 0, function* () {
addressOrName = yield addressOrName;
if (typeof (addressOrName) !== "string") {
base_provider_logger.throwArgumentError("invalid address or ENS name", "name", addressOrName);
}
const address = yield this.resolveName(addressOrName);
if (address == null) {
base_provider_logger.throwError("ENS name not configured", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: `resolveName(${JSON.stringify(addressOrName)})`
});
}
return address;
});
}
_getBlock(blockHashOrBlockTag, includeTransactions) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
blockHashOrBlockTag = yield blockHashOrBlockTag;
// If blockTag is a number (not "latest", etc), this is the block number
let blockNumber = -128;
const params = {
includeTransactions: !!includeTransactions
};
if (isHexString(blockHashOrBlockTag, 32)) {
params.blockHash = blockHashOrBlockTag;
}
else {
try {
params.blockTag = yield this._getBlockTag(blockHashOrBlockTag);
if (isHexString(params.blockTag)) {
blockNumber = parseInt(params.blockTag.substring(2), 16);
}
}
catch (error) {
base_provider_logger.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag);
}
}
return lib_esm_poll(() => base_provider_awaiter(this, void 0, void 0, function* () {
const block = yield this.perform("getBlock", params);
// Block was not found
if (block == null) {
// For blockhashes, if we didn't say it existed, that blockhash may
// not exist. If we did see it though, perhaps from a log, we know
// it exists, and this node is just not caught up yet.
if (params.blockHash != null) {
if (this._emitted["b:" + params.blockHash] == null) {
return null;
}
}
// For block tags, if we are asking for a future block, we return null
if (params.blockTag != null) {
if (blockNumber > this._emitted.block) {
return null;
}
}
// Retry on the next block
return undefined;
}
// Add transactions
if (includeTransactions) {
let blockNumber = null;
for (let i = 0; i < block.transactions.length; i++) {
const tx = block.transactions[i];
if (tx.blockNumber == null) {
tx.confirmations = 0;
}
else if (tx.confirmations == null) {
if (blockNumber == null) {
blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
}
// Add the confirmations using the fast block number (pessimistic)
let confirmations = (blockNumber - tx.blockNumber) + 1;
if (confirmations <= 0) {
confirmations = 1;
}
tx.confirmations = confirmations;
}
}
const blockWithTxs = this.formatter.blockWithTransactions(block);
blockWithTxs.transactions = blockWithTxs.transactions.map((tx) => this._wrapTransaction(tx));
return blockWithTxs;
}
return this.formatter.block(block);
}), { oncePoll: this });
});
}
getBlock(blockHashOrBlockTag) {
return (this._getBlock(blockHashOrBlockTag, false));
}
getBlockWithTransactions(blockHashOrBlockTag) {
return (this._getBlock(blockHashOrBlockTag, true));
}
getTransaction(transactionHash) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
transactionHash = yield transactionHash;
const params = { transactionHash: this.formatter.hash(transactionHash, true) };
return lib_esm_poll(() => base_provider_awaiter(this, void 0, void 0, function* () {
const result = yield this.perform("getTransaction", params);
if (result == null) {
if (this._emitted["t:" + transactionHash] == null) {
return null;
}
return undefined;
}
const tx = this.formatter.transactionResponse(result);
if (tx.blockNumber == null) {
tx.confirmations = 0;
}
else if (tx.confirmations == null) {
const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
// Add the confirmations using the fast block number (pessimistic)
let confirmations = (blockNumber - tx.blockNumber) + 1;
if (confirmations <= 0) {
confirmations = 1;
}
tx.confirmations = confirmations;
}
return this._wrapTransaction(tx);
}), { oncePoll: this });
});
}
getTransactionReceipt(transactionHash) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
transactionHash = yield transactionHash;
const params = { transactionHash: this.formatter.hash(transactionHash, true) };
return lib_esm_poll(() => base_provider_awaiter(this, void 0, void 0, function* () {
const result = yield this.perform("getTransactionReceipt", params);
if (result == null) {
if (this._emitted["t:" + transactionHash] == null) {
return null;
}
return undefined;
}
// "geth-etc" returns receipts before they are ready
if (result.blockHash == null) {
return undefined;
}
const receipt = this.formatter.receipt(result);
if (receipt.blockNumber == null) {
receipt.confirmations = 0;
}
else if (receipt.confirmations == null) {
const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
// Add the confirmations using the fast block number (pessimistic)
let confirmations = (blockNumber - receipt.blockNumber) + 1;
if (confirmations <= 0) {
confirmations = 1;
}
receipt.confirmations = confirmations;
}
return receipt;
}), { oncePoll: this });
});
}
getLogs(filter) {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
const params = yield resolveProperties({ filter: this._getFilter(filter) });
const logs = yield this.perform("getLogs", params);
logs.forEach((log) => {
if (log.removed == null) {
log.removed = false;
}
});
return formatter_Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs);
});
}
getEtherPrice() {
return base_provider_awaiter(this, void 0, void 0, function* () {
yield this.getNetwork();
return this.perform("getEtherPrice", {});
});
}
_getBlockTag(blockTag) {
return base_provider_awaiter(this, void 0, void 0, function* () {
blockTag = yield blockTag;
if (typeof (blockTag) === "number" && blockTag < 0) {
if (blockTag % 1) {
base_provider_logger.throwArgumentError("invalid BlockTag", "blockTag", blockTag);
}
let blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
blockNumber += blockTag;
if (blockNumber < 0) {
blockNumber = 0;
}
return this.formatter.blockTag(blockNumber);
}
return this.formatter.blockTag(blockTag);
});
}
getResolver(name) {
return base_provider_awaiter(this, void 0, void 0, function* () {
let currentName = name;
while (true) {
if (currentName === "" || currentName === ".") {
return null;
}
// Optimization since the eth node cannot change and does
// not have a wildcard resolver
if (name !== "eth" && currentName === "eth") {
return null;
}
// Check the current node for a resolver
const addr = yield this._getResolver(currentName, "getResolver");
// Found a resolver!
if (addr != null) {
const resolver = new base_provider_Resolver(this, addr, name);
// Legacy resolver found, using EIP-2544 so it isn't safe to use
if (currentName !== name && !(yield resolver.supportsWildcard())) {
return null;
}
return resolver;
}
// Get the parent node
currentName = currentName.split(".").slice(1).join(".");
}
});
}
_getResolver(name, operation) {
return base_provider_awaiter(this, void 0, void 0, function* () {
if (operation == null) {
operation = "ENS";
}
const network = yield this.getNetwork();
// No ENS...
if (!network.ensAddress) {
base_provider_logger.throwError("network does not support ENS", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { operation, network: network.name });
}
try {
// keccak256("resolver(bytes32)")
const addrData = yield this.call({
to: network.ensAddress,
data: ("0x0178b8bf" + namehash(name).substring(2))
});
return this.formatter.callAddress(addrData);
}
catch (error) {
// ENS registry cannot throw errors on resolver(bytes32)
}
return null;
});
}
resolveName(name) {
return base_provider_awaiter(this, void 0, void 0, function* () {
name = yield name;
// If it is already an address, nothing to resolve
try {
return Promise.resolve(this.formatter.address(name));
}
catch (error) {
// If is is a hexstring, the address is bad (See #694)
if (isHexString(name)) {
throw error;
}
}
if (typeof (name) !== "string") {
base_provider_logger.throwArgumentError("invalid ENS name", "name", name);
}
// Get the addr from the resolver
const resolver = yield this.getResolver(name);
if (!resolver) {
return null;
}
return yield resolver.getAddress();
});
}
lookupAddress(address) {
return base_provider_awaiter(this, void 0, void 0, function* () {
address = yield address;
address = this.formatter.address(address);
const node = address.substring(2).toLowerCase() + ".addr.reverse";
const resolverAddr = yield this._getResolver(node, "lookupAddress");
if (resolverAddr == null) {
return null;
}
// keccak("name(bytes32)")
const name = _parseString(yield this.call({
to: resolverAddr,
data: ("0x691f3431" + namehash(node).substring(2))
}), 0);
const addr = yield this.resolveName(name);
if (addr != address) {
return null;
}
return name;
});
}
getAvatar(nameOrAddress) {
return base_provider_awaiter(this, void 0, void 0, function* () {
let resolver = null;
if (isHexString(nameOrAddress)) {
// Address; reverse lookup
const address = this.formatter.address(nameOrAddress);
const node = address.substring(2).toLowerCase() + ".addr.reverse";
const resolverAddress = yield this._getResolver(node, "getAvatar");
if (!resolverAddress) {
return null;
}
// Try resolving the avatar against the addr.reverse resolver
resolver = new base_provider_Resolver(this, resolverAddress, node);
try {
const avatar = yield resolver.getAvatar();
if (avatar) {
return avatar.url;
}
}
catch (error) {
if (error.code !== lib_esm_Logger.errors.CALL_EXCEPTION) {
throw error;
}
}
// Try getting the name and performing forward lookup; allowing wildcards
try {
// keccak("name(bytes32)")
const name = _parseString(yield this.call({
to: resolverAddress,
data: ("0x691f3431" + namehash(node).substring(2))
}), 0);
resolver = yield this.getResolver(name);
}
catch (error) {
if (error.code !== lib_esm_Logger.errors.CALL_EXCEPTION) {
throw error;
}
return null;
}
}
else {
// ENS name; forward lookup with wildcard
resolver = yield this.getResolver(nameOrAddress);
if (!resolver) {
return null;
}
}
const avatar = yield resolver.getAvatar();
if (avatar == null) {
return null;
}
return avatar.url;
});
}
perform(method, params) {
return base_provider_logger.throwError(method + " not implemented", lib_esm_Logger.errors.NOT_IMPLEMENTED, { operation: method });
}
_startEvent(event) {
this.polling = (this._events.filter((e) => e.pollable()).length > 0);
}
_stopEvent(event) {
this.polling = (this._events.filter((e) => e.pollable()).length > 0);
}
_addEventListener(eventName, listener, once) {
const event = new base_provider_Event(getEventTag(eventName), listener, once);
this._events.push(event);
this._startEvent(event);
return this;
}
on(eventName, listener) {
return this._addEventListener(eventName, listener, false);
}
once(eventName, listener) {
return this._addEventListener(eventName, listener, true);
}
emit(eventName, ...args) {
let result = false;
let stopped = [];
let eventTag = getEventTag(eventName);
this._events = this._events.filter((event) => {
if (event.tag !== eventTag) {
return true;
}
setTimeout(() => {
event.listener.apply(this, args);
}, 0);
result = true;
if (event.once) {
stopped.push(event);
return false;
}
return true;
});
stopped.forEach((event) => { this._stopEvent(event); });
return result;
}
listenerCount(eventName) {
if (!eventName) {
return this._events.length;
}
let eventTag = getEventTag(eventName);
return this._events.filter((event) => {
return (event.tag === eventTag);
}).length;
}
listeners(eventName) {
if (eventName == null) {
return this._events.map((event) => event.listener);
}
let eventTag = getEventTag(eventName);
return this._events
.filter((event) => (event.tag === eventTag))
.map((event) => event.listener);
}
off(eventName, listener) {
if (listener == null) {
return this.removeAllListeners(eventName);
}
const stopped = [];
let found = false;
let eventTag = getEventTag(eventName);
this._events = this._events.filter((event) => {
if (event.tag !== eventTag || event.listener != listener) {
return true;
}
if (found) {
return true;
}
found = true;
stopped.push(event);
return false;
});
stopped.forEach((event) => { this._stopEvent(event); });
return this;
}
removeAllListeners(eventName) {
let stopped = [];
if (eventName == null) {
stopped = this._events;
this._events = [];
}
else {
const eventTag = getEventTag(eventName);
this._events = this._events.filter((event) => {
if (event.tag !== eventTag) {
return true;
}
stopped.push(event);
return false;
});
}
stopped.forEach((event) => { this._stopEvent(event); });
return this;
}
}
//# sourceMappingURL=base-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abstract-signer/lib.esm/_version.js
const abstract_signer_lib_esm_version_version = "abstract-signer/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abstract-signer/lib.esm/index.js
var abstract_signer_lib_esm_awaiter = (undefined && undefined.__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());
});
};
const abstract_signer_lib_esm_logger = new lib_esm_Logger(abstract_signer_lib_esm_version_version);
const lib_esm_allowedTransactionKeys = [
"accessList", "ccipReadEnabled", "chainId", "customData", "data", "from", "gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "to", "type", "value"
];
const forwardErrors = [
lib_esm_Logger.errors.INSUFFICIENT_FUNDS,
lib_esm_Logger.errors.NONCE_EXPIRED,
lib_esm_Logger.errors.REPLACEMENT_UNDERPRICED,
];
;
;
class lib_esm_Signer {
///////////////////
// Sub-classes MUST call super
constructor() {
abstract_signer_lib_esm_logger.checkAbstract(new.target, lib_esm_Signer);
defineReadOnly(this, "_isSigner", true);
}
///////////////////
// Sub-classes MAY override these
getBalance(blockTag) {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("getBalance");
return yield this.provider.getBalance(this.getAddress(), blockTag);
});
}
getTransactionCount(blockTag) {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("getTransactionCount");
return yield this.provider.getTransactionCount(this.getAddress(), blockTag);
});
}
// Populates "from" if unspecified, and estimates the gas for the transaction
estimateGas(transaction) {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("estimateGas");
const tx = yield resolveProperties(this.checkTransaction(transaction));
return yield this.provider.estimateGas(tx);
});
}
// Populates "from" if unspecified, and calls with the transaction
call(transaction, blockTag) {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("call");
const tx = yield resolveProperties(this.checkTransaction(transaction));
return yield this.provider.call(tx, blockTag);
});
}
// Populates all fields in a transaction, signs it and sends it to the network
sendTransaction(transaction) {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("sendTransaction");
const tx = yield this.populateTransaction(transaction);
const signedTx = yield this.signTransaction(tx);
return yield this.provider.sendTransaction(signedTx);
});
}
getChainId() {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("getChainId");
const network = yield this.provider.getNetwork();
return network.chainId;
});
}
getGasPrice() {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("getGasPrice");
return yield this.provider.getGasPrice();
});
}
getFeeData() {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("getFeeData");
return yield this.provider.getFeeData();
});
}
resolveName(name) {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
this._checkProvider("resolveName");
return yield this.provider.resolveName(name);
});
}
// Checks a transaction does not contain invalid keys and if
// no "from" is provided, populates it.
// - does NOT require a provider
// - adds "from" is not present
// - returns a COPY (safe to mutate the result)
// By default called from: (overriding these prevents it)
// - call
// - estimateGas
// - populateTransaction (and therefor sendTransaction)
checkTransaction(transaction) {
for (const key in transaction) {
if (lib_esm_allowedTransactionKeys.indexOf(key) === -1) {
abstract_signer_lib_esm_logger.throwArgumentError("invalid transaction key: " + key, "transaction", transaction);
}
}
const tx = shallowCopy(transaction);
if (tx.from == null) {
tx.from = this.getAddress();
}
else {
// Make sure any provided address matches this signer
tx.from = Promise.all([
Promise.resolve(tx.from),
this.getAddress()
]).then((result) => {
if (result[0].toLowerCase() !== result[1].toLowerCase()) {
abstract_signer_lib_esm_logger.throwArgumentError("from address mismatch", "transaction", transaction);
}
return result[0];
});
}
return tx;
}
// Populates ALL keys for a transaction and checks that "from" matches
// this Signer. Should be used by sendTransaction but NOT by signTransaction.
// By default called from: (overriding these prevents it)
// - sendTransaction
//
// Notes:
// - We allow gasPrice for EIP-1559 as long as it matches maxFeePerGas
populateTransaction(transaction) {
return abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
const tx = yield resolveProperties(this.checkTransaction(transaction));
if (tx.to != null) {
tx.to = Promise.resolve(tx.to).then((to) => abstract_signer_lib_esm_awaiter(this, void 0, void 0, function* () {
if (to == null) {
return null;
}
const address = yield this.resolveName(to);
if (address == null) {
abstract_signer_lib_esm_logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to);
}
return address;
}));
// Prevent this error from causing an UnhandledPromiseException
tx.to.catch((error) => { });
}
// Do not allow mixing pre-eip-1559 and eip-1559 properties
const hasEip1559 = (tx.maxFeePerGas != null || tx.maxPriorityFeePerGas != null);
if (tx.gasPrice != null && (tx.type === 2 || hasEip1559)) {
abstract_signer_lib_esm_logger.throwArgumentError("eip-1559 transaction do not support gasPrice", "transaction", transaction);
}
else if ((tx.type === 0 || tx.type === 1) && hasEip1559) {
abstract_signer_lib_esm_logger.throwArgumentError("pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "transaction", transaction);
}
if ((tx.type === 2 || tx.type == null) && (tx.maxFeePerGas != null && tx.maxPriorityFeePerGas != null)) {
// Fully-formed EIP-1559 transaction (skip getFeeData)
tx.type = 2;
}
else if (tx.type === 0 || tx.type === 1) {
// Explicit Legacy or EIP-2930 transaction
// Populate missing gasPrice
if (tx.gasPrice == null) {
tx.gasPrice = this.getGasPrice();
}
}
else {
// We need to get fee data to determine things
const feeData = yield this.getFeeData();
if (tx.type == null) {
// We need to auto-detect the intended type of this transaction...
if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) {
// The network supports EIP-1559!
// Upgrade transaction from null to eip-1559
tx.type = 2;
if (tx.gasPrice != null) {
// Using legacy gasPrice property on an eip-1559 network,
// so use gasPrice as both fee properties
const gasPrice = tx.gasPrice;
delete tx.gasPrice;
tx.maxFeePerGas = gasPrice;
tx.maxPriorityFeePerGas = gasPrice;
}
else {
// Populate missing fee data
if (tx.maxFeePerGas == null) {
tx.maxFeePerGas = feeData.maxFeePerGas;
}
if (tx.maxPriorityFeePerGas == null) {
tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
}
}
}
else if (feeData.gasPrice != null) {
// Network doesn't support EIP-1559...
// ...but they are trying to use EIP-1559 properties
if (hasEip1559) {
abstract_signer_lib_esm_logger.throwError("network does not support EIP-1559", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "populateTransaction"
});
}
// Populate missing fee data
if (tx.gasPrice == null) {
tx.gasPrice = feeData.gasPrice;
}
// Explicitly set untyped transaction to legacy
tx.type = 0;
}
else {
// getFeeData has failed us.
abstract_signer_lib_esm_logger.throwError("failed to get consistent fee data", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "signer.getFeeData"
});
}
}
else if (tx.type === 2) {
// Explicitly using EIP-1559
// Populate missing fee data
if (tx.maxFeePerGas == null) {
tx.maxFeePerGas = feeData.maxFeePerGas;
}
if (tx.maxPriorityFeePerGas == null) {
tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
}
}
}
if (tx.nonce == null) {
tx.nonce = this.getTransactionCount("pending");
}
if (tx.gasLimit == null) {
tx.gasLimit = this.estimateGas(tx).catch((error) => {
if (forwardErrors.indexOf(error.code) >= 0) {
throw error;
}
return abstract_signer_lib_esm_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", lib_esm_Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
error: error,
tx: tx
});
});
}
if (tx.chainId == null) {
tx.chainId = this.getChainId();
}
else {
tx.chainId = Promise.all([
Promise.resolve(tx.chainId),
this.getChainId()
]).then((results) => {
if (results[1] !== 0 && results[0] !== results[1]) {
abstract_signer_lib_esm_logger.throwArgumentError("chainId address mismatch", "transaction", transaction);
}
return results[0];
});
}
return yield resolveProperties(tx);
});
}
///////////////////
// Sub-classes SHOULD leave these alone
_checkProvider(operation) {
if (!this.provider) {
abstract_signer_lib_esm_logger.throwError("missing provider", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: (operation || "_checkProvider")
});
}
}
static isSigner(value) {
return !!(value && value._isSigner);
}
}
class lib_esm_VoidSigner extends lib_esm_Signer {
constructor(address, provider) {
super();
defineReadOnly(this, "address", address);
defineReadOnly(this, "provider", provider || null);
}
getAddress() {
return Promise.resolve(this.address);
}
_fail(message, operation) {
return Promise.resolve().then(() => {
abstract_signer_lib_esm_logger.throwError(message, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { operation: operation });
});
}
signMessage(message) {
return this._fail("VoidSigner cannot sign messages", "signMessage");
}
signTransaction(transaction) {
return this._fail("VoidSigner cannot sign transactions", "signTransaction");
}
_signTypedData(domain, types, value) {
return this._fail("VoidSigner cannot sign typed data", "signTypedData");
}
connect(provider) {
return new lib_esm_VoidSigner(this.address, provider);
}
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hash/lib.esm/id.js
function id_id(text) {
return keccak256(toUtf8Bytes(text));
}
//# sourceMappingURL=id.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hash/lib.esm/typed-data.js
var typed_data_awaiter = (undefined && undefined.__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());
});
};
const typed_data_logger = new lib_esm_Logger(hash_lib_esm_version_version);
const padding = new Uint8Array(32);
padding.fill(0);
const typed_data_NegativeOne = bignumber_BigNumber.from(-1);
const typed_data_Zero = bignumber_BigNumber.from(0);
const typed_data_One = bignumber_BigNumber.from(1);
const typed_data_MaxUint256 = bignumber_BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
function hexPadRight(value) {
const bytes = arrayify(value);
const padOffset = bytes.length % 32;
if (padOffset) {
return hexConcat([bytes, padding.slice(padOffset)]);
}
return hexlify(bytes);
}
const hexTrue = hexZeroPad(typed_data_One.toHexString(), 32);
const hexFalse = hexZeroPad(typed_data_Zero.toHexString(), 32);
const domainFieldTypes = {
name: "string",
version: "string",
chainId: "uint256",
verifyingContract: "address",
salt: "bytes32"
};
const domainFieldNames = [
"name", "version", "chainId", "verifyingContract", "salt"
];
function checkString(key) {
return function (value) {
if (typeof (value) !== "string") {
typed_data_logger.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value);
}
return value;
};
}
const domainChecks = {
name: checkString("name"),
version: checkString("version"),
chainId: function (value) {
try {
return bignumber_BigNumber.from(value).toString();
}
catch (error) { }
return typed_data_logger.throwArgumentError(`invalid domain value for "chainId"`, "domain.chainId", value);
},
verifyingContract: function (value) {
try {
return getAddress(value).toLowerCase();
}
catch (error) { }
return typed_data_logger.throwArgumentError(`invalid domain value "verifyingContract"`, "domain.verifyingContract", value);
},
salt: function (value) {
try {
const bytes = arrayify(value);
if (bytes.length !== 32) {
throw new Error("bad length");
}
return hexlify(bytes);
}
catch (error) { }
return typed_data_logger.throwArgumentError(`invalid domain value "salt"`, "domain.salt", value);
}
};
function getBaseEncoder(type) {
// intXX and uintXX
{
const match = type.match(/^(u?)int(\d*)$/);
if (match) {
const signed = (match[1] === "");
const width = parseInt(match[2] || "256");
if (width % 8 !== 0 || width > 256 || (match[2] && match[2] !== String(width))) {
typed_data_logger.throwArgumentError("invalid numeric width", "type", type);
}
const boundsUpper = typed_data_MaxUint256.mask(signed ? (width - 1) : width);
const boundsLower = signed ? boundsUpper.add(typed_data_One).mul(typed_data_NegativeOne) : typed_data_Zero;
return function (value) {
const v = bignumber_BigNumber.from(value);
if (v.lt(boundsLower) || v.gt(boundsUpper)) {
typed_data_logger.throwArgumentError(`value out-of-bounds for ${type}`, "value", value);
}
return hexZeroPad(v.toTwos(256).toHexString(), 32);
};
}
}
// bytesXX
{
const match = type.match(/^bytes(\d+)$/);
if (match) {
const width = parseInt(match[1]);
if (width === 0 || width > 32 || match[1] !== String(width)) {
typed_data_logger.throwArgumentError("invalid bytes width", "type", type);
}
return function (value) {
const bytes = arrayify(value);
if (bytes.length !== width) {
typed_data_logger.throwArgumentError(`invalid length for ${type}`, "value", value);
}
return hexPadRight(value);
};
}
}
switch (type) {
case "address": return function (value) {
return hexZeroPad(getAddress(value), 32);
};
case "bool": return function (value) {
return ((!value) ? hexFalse : hexTrue);
};
case "bytes": return function (value) {
return keccak256(value);
};
case "string": return function (value) {
return id_id(value);
};
}
return null;
}
function encodeType(name, fields) {
return `${name}(${fields.map(({ name, type }) => (type + " " + name)).join(",")})`;
}
class typed_data_TypedDataEncoder {
constructor(types) {
defineReadOnly(this, "types", Object.freeze(deepCopy(types)));
defineReadOnly(this, "_encoderCache", {});
defineReadOnly(this, "_types", {});
// Link struct types to their direct child structs
const links = {};
// Link structs to structs which contain them as a child
const parents = {};
// Link all subtypes within a given struct
const subtypes = {};
Object.keys(types).forEach((type) => {
links[type] = {};
parents[type] = [];
subtypes[type] = {};
});
for (const name in types) {
const uniqueNames = {};
types[name].forEach((field) => {
// Check each field has a unique name
if (uniqueNames[field.name]) {
typed_data_logger.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", types);
}
uniqueNames[field.name] = true;
// Get the base type (drop any array specifiers)
const baseType = field.type.match(/^([^\x5b]*)(\x5b|$)/)[1];
if (baseType === name) {
typed_data_logger.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`, "types", types);
}
// Is this a base encoding type?
const encoder = getBaseEncoder(baseType);
if (encoder) {
return;
}
if (!parents[baseType]) {
typed_data_logger.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`, "types", types);
}
// Add linkage
parents[baseType].push(name);
links[name][baseType] = true;
});
}
// Deduce the primary type
const primaryTypes = Object.keys(parents).filter((n) => (parents[n].length === 0));
if (primaryTypes.length === 0) {
typed_data_logger.throwArgumentError("missing primary type", "types", types);
}
else if (primaryTypes.length > 1) {
typed_data_logger.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(", ")}`, "types", types);
}
defineReadOnly(this, "primaryType", primaryTypes[0]);
// Check for circular type references
function checkCircular(type, found) {
if (found[type]) {
typed_data_logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, "types", types);
}
found[type] = true;
Object.keys(links[type]).forEach((child) => {
if (!parents[child]) {
return;
}
// Recursively check children
checkCircular(child, found);
// Mark all ancestors as having this decendant
Object.keys(found).forEach((subtype) => {
subtypes[subtype][child] = true;
});
});
delete found[type];
}
checkCircular(this.primaryType, {});
// Compute each fully describe type
for (const name in subtypes) {
const st = Object.keys(subtypes[name]);
st.sort();
this._types[name] = encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join("");
}
}
getEncoder(type) {
let encoder = this._encoderCache[type];
if (!encoder) {
encoder = this._encoderCache[type] = this._getEncoder(type);
}
return encoder;
}
_getEncoder(type) {
// Basic encoder type (address, bool, uint256, etc)
{
const encoder = getBaseEncoder(type);
if (encoder) {
return encoder;
}
}
// Array
const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/);
if (match) {
const subtype = match[1];
const subEncoder = this.getEncoder(subtype);
const length = parseInt(match[3]);
return (value) => {
if (length >= 0 && value.length !== length) {
typed_data_logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value);
}
let result = value.map(subEncoder);
if (this._types[subtype]) {
result = result.map(keccak256);
}
return keccak256(hexConcat(result));
};
}
// Struct
const fields = this.types[type];
if (fields) {
const encodedType = id_id(this._types[type]);
return (value) => {
const values = fields.map(({ name, type }) => {
const result = this.getEncoder(type)(value[name]);
if (this._types[type]) {
return keccak256(result);
}
return result;
});
values.unshift(encodedType);
return hexConcat(values);
};
}
return typed_data_logger.throwArgumentError(`unknown type: ${type}`, "type", type);
}
encodeType(name) {
const result = this._types[name];
if (!result) {
typed_data_logger.throwArgumentError(`unknown type: ${JSON.stringify(name)}`, "name", name);
}
return result;
}
encodeData(type, value) {
return this.getEncoder(type)(value);
}
hashStruct(name, value) {
return keccak256(this.encodeData(name, value));
}
encode(value) {
return this.encodeData(this.primaryType, value);
}
hash(value) {
return this.hashStruct(this.primaryType, value);
}
_visit(type, value, callback) {
// Basic encoder type (address, bool, uint256, etc)
{
const encoder = getBaseEncoder(type);
if (encoder) {
return callback(type, value);
}
}
// Array
const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/);
if (match) {
const subtype = match[1];
const length = parseInt(match[3]);
if (length >= 0 && value.length !== length) {
typed_data_logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value);
}
return value.map((v) => this._visit(subtype, v, callback));
}
// Struct
const fields = this.types[type];
if (fields) {
return fields.reduce((accum, { name, type }) => {
accum[name] = this._visit(type, value[name], callback);
return accum;
}, {});
}
return typed_data_logger.throwArgumentError(`unknown type: ${type}`, "type", type);
}
visit(value, callback) {
return this._visit(this.primaryType, value, callback);
}
static from(types) {
return new typed_data_TypedDataEncoder(types);
}
static getPrimaryType(types) {
return typed_data_TypedDataEncoder.from(types).primaryType;
}
static hashStruct(name, types, value) {
return typed_data_TypedDataEncoder.from(types).hashStruct(name, value);
}
static hashDomain(domain) {
const domainFields = [];
for (const name in domain) {
const type = domainFieldTypes[name];
if (!type) {
typed_data_logger.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain);
}
domainFields.push({ name, type });
}
domainFields.sort((a, b) => {
return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name);
});
return typed_data_TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain);
}
static encode(domain, types, value) {
return hexConcat([
"0x1901",
typed_data_TypedDataEncoder.hashDomain(domain),
typed_data_TypedDataEncoder.from(types).hash(value)
]);
}
static hash(domain, types, value) {
return keccak256(typed_data_TypedDataEncoder.encode(domain, types, value));
}
// Replaces all address types with ENS names with their looked up address
static resolveNames(domain, types, value, resolveName) {
return typed_data_awaiter(this, void 0, void 0, function* () {
// Make a copy to isolate it from the object passed in
domain = shallowCopy(domain);
// Look up all ENS names
const ensCache = {};
// Do we need to look up the domain's verifyingContract?
if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) {
ensCache[domain.verifyingContract] = "0x";
}
// We are going to use the encoder to visit all the base values
const encoder = typed_data_TypedDataEncoder.from(types);
// Get a list of all the addresses
encoder.visit(value, (type, value) => {
if (type === "address" && !isHexString(value, 20)) {
ensCache[value] = "0x";
}
return value;
});
// Lookup each name
for (const name in ensCache) {
ensCache[name] = yield resolveName(name);
}
// Replace the domain verifyingContract if needed
if (domain.verifyingContract && ensCache[domain.verifyingContract]) {
domain.verifyingContract = ensCache[domain.verifyingContract];
}
// Replace all ENS names with their address
value = encoder.visit(value, (type, value) => {
if (type === "address" && ensCache[value]) {
return ensCache[value];
}
return value;
});
return { domain, value };
});
}
static getPayload(domain, types, value) {
// Validate the domain fields
typed_data_TypedDataEncoder.hashDomain(domain);
// Derive the EIP712Domain Struct reference type
const domainValues = {};
const domainTypes = [];
domainFieldNames.forEach((name) => {
const value = domain[name];
if (value == null) {
return;
}
domainValues[name] = domainChecks[name](value);
domainTypes.push({ name, type: domainFieldTypes[name] });
});
const encoder = typed_data_TypedDataEncoder.from(types);
const typesWithDomain = shallowCopy(types);
if (typesWithDomain.EIP712Domain) {
typed_data_logger.throwArgumentError("types must not contain EIP712Domain type", "types.EIP712Domain", types);
}
else {
typesWithDomain.EIP712Domain = domainTypes;
}
// Validate the data structures and types
encoder.encode(value);
return {
types: typesWithDomain,
domain: domainValues,
primaryType: encoder.primaryType,
message: encoder.visit(value, (type, value) => {
// bytes
if (type.match(/^bytes(\d*)/)) {
return hexlify(arrayify(value));
}
// uint or int
if (type.match(/^u?int/)) {
return bignumber_BigNumber.from(value).toString();
}
switch (type) {
case "address":
return value.toLowerCase();
case "bool":
return !!value;
case "string":
if (typeof (value) !== "string") {
typed_data_logger.throwArgumentError(`invalid string`, "value", value);
}
return value;
}
return typed_data_logger.throwArgumentError("unsupported type", "type", type);
})
};
}
}
//# sourceMappingURL=typed-data.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/json-rpc-provider.js
var json_rpc_provider_awaiter = (undefined && undefined.__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());
});
};
const json_rpc_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
const errorGas = ["call", "estimateGas"];
function spelunk(value, requireData) {
if (value == null) {
return null;
}
// These *are* the droids we're looking for.
if (typeof (value.message) === "string" && value.message.match("reverted")) {
const data = isHexString(value.data) ? value.data : null;
if (!requireData || data) {
return { message: value.message, data };
}
}
// Spelunk further...
if (typeof (value) === "object") {
for (const key in value) {
const result = spelunk(value[key], requireData);
if (result) {
return result;
}
}
return null;
}
// Might be a JSON string we can further descend...
if (typeof (value) === "string") {
try {
return spelunk(JSON.parse(value), requireData);
}
catch (error) { }
}
return null;
}
function checkError(method, error, params) {
const transaction = params.transaction || params.signedTransaction;
// Undo the "convenience" some nodes are attempting to prevent backwards
// incompatibility; maybe for v6 consider forwarding reverts as errors
if (method === "call") {
const result = spelunk(error, true);
if (result) {
return result.data;
}
// Nothing descriptive..
json_rpc_provider_logger.throwError("missing revert data in call exception; Transaction reverted without a reason string", lib_esm_Logger.errors.CALL_EXCEPTION, {
data: "0x", transaction, error
});
}
if (method === "estimateGas") {
// Try to find something, with a preference on SERVER_ERROR body
let result = spelunk(error.body, false);
if (result == null) {
result = spelunk(error, false);
}
// Found "reverted", this is a CALL_EXCEPTION
if (result) {
json_rpc_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", lib_esm_Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
reason: result.message, method, transaction, error
});
}
}
// @TODO: Should we spelunk for message too?
let message = error.message;
if (error.code === lib_esm_Logger.errors.SERVER_ERROR && error.error && typeof (error.error.message) === "string") {
message = error.error.message;
}
else if (typeof (error.body) === "string") {
message = error.body;
}
else if (typeof (error.responseText) === "string") {
message = error.responseText;
}
message = (message || "").toLowerCase();
// "insufficient funds for gas * price + value + cost(data)"
if (message.match(/insufficient funds|base fee exceeds gas limit|InsufficientFunds/i)) {
json_rpc_provider_logger.throwError("insufficient funds for intrinsic transaction cost", lib_esm_Logger.errors.INSUFFICIENT_FUNDS, {
error, method, transaction
});
}
// "nonce too low"
if (message.match(/nonce (is )?too low/i)) {
json_rpc_provider_logger.throwError("nonce has already been used", lib_esm_Logger.errors.NONCE_EXPIRED, {
error, method, transaction
});
}
// "replacement transaction underpriced"
if (message.match(/replacement transaction underpriced|transaction gas price.*too low/i)) {
json_rpc_provider_logger.throwError("replacement fee too low", lib_esm_Logger.errors.REPLACEMENT_UNDERPRICED, {
error, method, transaction
});
}
// "replacement transaction underpriced"
if (message.match(/only replay-protected/i)) {
json_rpc_provider_logger.throwError("legacy pre-eip-155 transactions not supported", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
error, method, transaction
});
}
if (errorGas.indexOf(method) >= 0 && message.match(/gas required exceeds allowance|always failing transaction|execution reverted|revert/)) {
json_rpc_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", lib_esm_Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
error, method, transaction
});
}
throw error;
}
function json_rpc_provider_timer(timeout) {
return new Promise(function (resolve) {
setTimeout(resolve, timeout);
});
}
function json_rpc_provider_getResult(payload) {
if (payload.error) {
// @TODO: not any
const error = new Error(payload.error.message);
error.code = payload.error.code;
error.data = payload.error.data;
throw error;
}
return payload.result;
}
function getLowerCase(value) {
if (value) {
return value.toLowerCase();
}
return value;
}
const json_rpc_provider_constructorGuard = {};
class json_rpc_provider_JsonRpcSigner extends lib_esm_Signer {
constructor(constructorGuard, provider, addressOrIndex) {
super();
if (constructorGuard !== json_rpc_provider_constructorGuard) {
throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");
}
defineReadOnly(this, "provider", provider);
if (addressOrIndex == null) {
addressOrIndex = 0;
}
if (typeof (addressOrIndex) === "string") {
defineReadOnly(this, "_address", this.provider.formatter.address(addressOrIndex));
defineReadOnly(this, "_index", null);
}
else if (typeof (addressOrIndex) === "number") {
defineReadOnly(this, "_index", addressOrIndex);
defineReadOnly(this, "_address", null);
}
else {
json_rpc_provider_logger.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex);
}
}
connect(provider) {
return json_rpc_provider_logger.throwError("cannot alter JSON-RPC Signer connection", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "connect"
});
}
connectUnchecked() {
return new UncheckedJsonRpcSigner(json_rpc_provider_constructorGuard, this.provider, this._address || this._index);
}
getAddress() {
if (this._address) {
return Promise.resolve(this._address);
}
return this.provider.send("eth_accounts", []).then((accounts) => {
if (accounts.length <= this._index) {
json_rpc_provider_logger.throwError("unknown account #" + this._index, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "getAddress"
});
}
return this.provider.formatter.address(accounts[this._index]);
});
}
sendUncheckedTransaction(transaction) {
transaction = shallowCopy(transaction);
const fromAddress = this.getAddress().then((address) => {
if (address) {
address = address.toLowerCase();
}
return address;
});
// The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user
// wishes to use this, it is easy to specify explicitly, otherwise
// we look it up for them.
if (transaction.gasLimit == null) {
const estimate = shallowCopy(transaction);
estimate.from = fromAddress;
transaction.gasLimit = this.provider.estimateGas(estimate);
}
if (transaction.to != null) {
transaction.to = Promise.resolve(transaction.to).then((to) => json_rpc_provider_awaiter(this, void 0, void 0, function* () {
if (to == null) {
return null;
}
const address = yield this.provider.resolveName(to);
if (address == null) {
json_rpc_provider_logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to);
}
return address;
}));
}
return resolveProperties({
tx: resolveProperties(transaction),
sender: fromAddress
}).then(({ tx, sender }) => {
if (tx.from != null) {
if (tx.from.toLowerCase() !== sender) {
json_rpc_provider_logger.throwArgumentError("from address mismatch", "transaction", transaction);
}
}
else {
tx.from = sender;
}
const hexTx = this.provider.constructor.hexlifyTransaction(tx, { from: true });
return this.provider.send("eth_sendTransaction", [hexTx]).then((hash) => {
return hash;
}, (error) => {
if (typeof (error.message) === "string" && error.message.match(/user denied/i)) {
json_rpc_provider_logger.throwError("user rejected transaction", lib_esm_Logger.errors.ACTION_REJECTED, {
action: "sendTransaction",
transaction: tx
});
}
return checkError("sendTransaction", error, hexTx);
});
});
}
signTransaction(transaction) {
return json_rpc_provider_logger.throwError("signing transactions is unsupported", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "signTransaction"
});
}
sendTransaction(transaction) {
return json_rpc_provider_awaiter(this, void 0, void 0, function* () {
// This cannot be mined any earlier than any recent block
const blockNumber = yield this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval);
// Send the transaction
const hash = yield this.sendUncheckedTransaction(transaction);
try {
// Unfortunately, JSON-RPC only provides and opaque transaction hash
// for a response, and we need the actual transaction, so we poll
// for it; it should show up very quickly
return yield lib_esm_poll(() => json_rpc_provider_awaiter(this, void 0, void 0, function* () {
const tx = yield this.provider.getTransaction(hash);
if (tx === null) {
return undefined;
}
return this.provider._wrapTransaction(tx, hash, blockNumber);
}), { oncePoll: this.provider });
}
catch (error) {
error.transactionHash = hash;
throw error;
}
});
}
signMessage(message) {
return json_rpc_provider_awaiter(this, void 0, void 0, function* () {
const data = ((typeof (message) === "string") ? toUtf8Bytes(message) : message);
const address = yield this.getAddress();
try {
return yield this.provider.send("personal_sign", [hexlify(data), address.toLowerCase()]);
}
catch (error) {
if (typeof (error.message) === "string" && error.message.match(/user denied/i)) {
json_rpc_provider_logger.throwError("user rejected signing", lib_esm_Logger.errors.ACTION_REJECTED, {
action: "signMessage",
from: address,
messageData: message
});
}
throw error;
}
});
}
_legacySignMessage(message) {
return json_rpc_provider_awaiter(this, void 0, void 0, function* () {
const data = ((typeof (message) === "string") ? toUtf8Bytes(message) : message);
const address = yield this.getAddress();
try {
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
return yield this.provider.send("eth_sign", [address.toLowerCase(), hexlify(data)]);
}
catch (error) {
if (typeof (error.message) === "string" && error.message.match(/user denied/i)) {
json_rpc_provider_logger.throwError("user rejected signing", lib_esm_Logger.errors.ACTION_REJECTED, {
action: "_legacySignMessage",
from: address,
messageData: message
});
}
throw error;
}
});
}
_signTypedData(domain, types, value) {
return json_rpc_provider_awaiter(this, void 0, void 0, function* () {
// Populate any ENS names (in-place)
const populated = yield typed_data_TypedDataEncoder.resolveNames(domain, types, value, (name) => {
return this.provider.resolveName(name);
});
const address = yield this.getAddress();
try {
return yield this.provider.send("eth_signTypedData_v4", [
address.toLowerCase(),
JSON.stringify(typed_data_TypedDataEncoder.getPayload(populated.domain, types, populated.value))
]);
}
catch (error) {
if (typeof (error.message) === "string" && error.message.match(/user denied/i)) {
json_rpc_provider_logger.throwError("user rejected signing", lib_esm_Logger.errors.ACTION_REJECTED, {
action: "_signTypedData",
from: address,
messageData: { domain: populated.domain, types, value: populated.value }
});
}
throw error;
}
});
}
unlock(password) {
return json_rpc_provider_awaiter(this, void 0, void 0, function* () {
const provider = this.provider;
const address = yield this.getAddress();
return provider.send("personal_unlockAccount", [address.toLowerCase(), password, null]);
});
}
}
class UncheckedJsonRpcSigner extends json_rpc_provider_JsonRpcSigner {
sendTransaction(transaction) {
return this.sendUncheckedTransaction(transaction).then((hash) => {
return {
hash: hash,
nonce: null,
gasLimit: null,
gasPrice: null,
data: null,
value: null,
chainId: null,
confirmations: 0,
from: null,
wait: (confirmations) => { return this.provider.waitForTransaction(hash, confirmations); }
};
});
}
}
const json_rpc_provider_allowedTransactionKeys = {
chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true,
type: true, accessList: true,
maxFeePerGas: true, maxPriorityFeePerGas: true
};
class json_rpc_provider_JsonRpcProvider extends base_provider_BaseProvider {
constructor(url, network) {
let networkOrReady = network;
// The network is unknown, query the JSON-RPC for it
if (networkOrReady == null) {
networkOrReady = new Promise((resolve, reject) => {
setTimeout(() => {
this.detectNetwork().then((network) => {
resolve(network);
}, (error) => {
reject(error);
});
}, 0);
});
}
super(networkOrReady);
// Default URL
if (!url) {
url = getStatic(this.constructor, "defaultUrl")();
}
if (typeof (url) === "string") {
defineReadOnly(this, "connection", Object.freeze({
url: url
}));
}
else {
defineReadOnly(this, "connection", Object.freeze(shallowCopy(url)));
}
this._nextId = 42;
}
get _cache() {
if (this._eventLoopCache == null) {
this._eventLoopCache = {};
}
return this._eventLoopCache;
}
static defaultUrl() {
return "http:/\/localhost:8545";
}
detectNetwork() {
if (!this._cache["detectNetwork"]) {
this._cache["detectNetwork"] = this._uncachedDetectNetwork();
// Clear this cache at the beginning of the next event loop
setTimeout(() => {
this._cache["detectNetwork"] = null;
}, 0);
}
return this._cache["detectNetwork"];
}
_uncachedDetectNetwork() {
return json_rpc_provider_awaiter(this, void 0, void 0, function* () {
yield json_rpc_provider_timer(0);
let chainId = null;
try {
chainId = yield this.send("eth_chainId", []);
}
catch (error) {
try {
chainId = yield this.send("net_version", []);
}
catch (error) { }
}
if (chainId != null) {
const getNetwork = getStatic(this.constructor, "getNetwork");
try {
return getNetwork(bignumber_BigNumber.from(chainId).toNumber());
}
catch (error) {
return json_rpc_provider_logger.throwError("could not detect network", lib_esm_Logger.errors.NETWORK_ERROR, {
chainId: chainId,
event: "invalidNetwork",
serverError: error
});
}
}
return json_rpc_provider_logger.throwError("could not detect network", lib_esm_Logger.errors.NETWORK_ERROR, {
event: "noNetwork"
});
});
}
getSigner(addressOrIndex) {
return new json_rpc_provider_JsonRpcSigner(json_rpc_provider_constructorGuard, this, addressOrIndex);
}
getUncheckedSigner(addressOrIndex) {
return this.getSigner(addressOrIndex).connectUnchecked();
}
listAccounts() {
return this.send("eth_accounts", []).then((accounts) => {
return accounts.map((a) => this.formatter.address(a));
});
}
send(method, params) {
const request = {
method: method,
params: params,
id: (this._nextId++),
jsonrpc: "2.0"
};
this.emit("debug", {
action: "request",
request: deepCopy(request),
provider: this
});
// We can expand this in the future to any call, but for now these
// are the biggest wins and do not require any serializing parameters.
const cache = (["eth_chainId", "eth_blockNumber"].indexOf(method) >= 0);
if (cache && this._cache[method]) {
return this._cache[method];
}
const result = fetchJson(this.connection, JSON.stringify(request), json_rpc_provider_getResult).then((result) => {
this.emit("debug", {
action: "response",
request: request,
response: result,
provider: this
});
return result;
}, (error) => {
this.emit("debug", {
action: "response",
error: error,
request: request,
provider: this
});
throw error;
});
// Cache the fetch, but clear it on the next event loop
if (cache) {
this._cache[method] = result;
setTimeout(() => {
this._cache[method] = null;
}, 0);
}
return result;
}
prepareRequest(method, params) {
switch (method) {
case "getBlockNumber":
return ["eth_blockNumber", []];
case "getGasPrice":
return ["eth_gasPrice", []];
case "getBalance":
return ["eth_getBalance", [getLowerCase(params.address), params.blockTag]];
case "getTransactionCount":
return ["eth_getTransactionCount", [getLowerCase(params.address), params.blockTag]];
case "getCode":
return ["eth_getCode", [getLowerCase(params.address), params.blockTag]];
case "getStorageAt":
return ["eth_getStorageAt", [getLowerCase(params.address), hexZeroPad(params.position, 32), params.blockTag]];
case "sendTransaction":
return ["eth_sendRawTransaction", [params.signedTransaction]];
case "getBlock":
if (params.blockTag) {
return ["eth_getBlockByNumber", [params.blockTag, !!params.includeTransactions]];
}
else if (params.blockHash) {
return ["eth_getBlockByHash", [params.blockHash, !!params.includeTransactions]];
}
return null;
case "getTransaction":
return ["eth_getTransactionByHash", [params.transactionHash]];
case "getTransactionReceipt":
return ["eth_getTransactionReceipt", [params.transactionHash]];
case "call": {
const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction");
return ["eth_call", [hexlifyTransaction(params.transaction, { from: true }), params.blockTag]];
}
case "estimateGas": {
const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction");
return ["eth_estimateGas", [hexlifyTransaction(params.transaction, { from: true })]];
}
case "getLogs":
if (params.filter && params.filter.address != null) {
params.filter.address = getLowerCase(params.filter.address);
}
return ["eth_getLogs", [params.filter]];
default:
break;
}
return null;
}
perform(method, params) {
return json_rpc_provider_awaiter(this, void 0, void 0, function* () {
// Legacy networks do not like the type field being passed along (which
// is fair), so we delete type if it is 0 and a non-EIP-1559 network
if (method === "call" || method === "estimateGas") {
const tx = params.transaction;
if (tx && tx.type != null && bignumber_BigNumber.from(tx.type).isZero()) {
// If there are no EIP-1559 properties, it might be non-EIP-1559
if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {
const feeData = yield this.getFeeData();
if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {
// Network doesn't know about EIP-1559 (and hence type)
params = shallowCopy(params);
params.transaction = shallowCopy(tx);
delete params.transaction.type;
}
}
}
}
const args = this.prepareRequest(method, params);
if (args == null) {
json_rpc_provider_logger.throwError(method + " not implemented", lib_esm_Logger.errors.NOT_IMPLEMENTED, { operation: method });
}
try {
return yield this.send(args[0], args[1]);
}
catch (error) {
return checkError(method, error, params);
}
});
}
_startEvent(event) {
if (event.tag === "pending") {
this._startPending();
}
super._startEvent(event);
}
_startPending() {
if (this._pendingFilter != null) {
return;
}
const self = this;
const pendingFilter = this.send("eth_newPendingTransactionFilter", []);
this._pendingFilter = pendingFilter;
pendingFilter.then(function (filterId) {
function poll() {
self.send("eth_getFilterChanges", [filterId]).then(function (hashes) {
if (self._pendingFilter != pendingFilter) {
return null;
}
let seq = Promise.resolve();
hashes.forEach(function (hash) {
// @TODO: This should be garbage collected at some point... How? When?
self._emitted["t:" + hash.toLowerCase()] = "pending";
seq = seq.then(function () {
return self.getTransaction(hash).then(function (tx) {
self.emit("pending", tx);
return null;
});
});
});
return seq.then(function () {
return json_rpc_provider_timer(1000);
});
}).then(function () {
if (self._pendingFilter != pendingFilter) {
self.send("eth_uninstallFilter", [filterId]);
return;
}
setTimeout(function () { poll(); }, 0);
return null;
}).catch((error) => { });
}
poll();
return filterId;
}).catch((error) => { });
}
_stopEvent(event) {
if (event.tag === "pending" && this.listenerCount("pending") === 0) {
this._pendingFilter = null;
}
super._stopEvent(event);
}
// Convert an ethers.js transaction into a JSON-RPC transaction
// - gasLimit => gas
// - All values hexlified
// - All numeric values zero-striped
// - All addresses are lowercased
// NOTE: This allows a TransactionRequest, but all values should be resolved
// before this is called
// @TODO: This will likely be removed in future versions and prepareRequest
// will be the preferred method for this.
static hexlifyTransaction(transaction, allowExtra) {
// Check only allowed properties are given
const allowed = shallowCopy(json_rpc_provider_allowedTransactionKeys);
if (allowExtra) {
for (const key in allowExtra) {
if (allowExtra[key]) {
allowed[key] = true;
}
}
}
checkProperties(transaction, allowed);
const result = {};
// JSON-RPC now requires numeric values to be "quantity" values
["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach(function (key) {
if (transaction[key] == null) {
return;
}
const value = hexValue(bignumber_BigNumber.from(transaction[key]));
if (key === "gasLimit") {
key = "gas";
}
result[key] = value;
});
["from", "to", "data"].forEach(function (key) {
if (transaction[key] == null) {
return;
}
result[key] = hexlify(transaction[key]);
});
if (transaction.accessList) {
result["accessList"] = accessListify(transaction.accessList);
}
return result;
}
}
//# sourceMappingURL=json-rpc-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/ws.js
let WS = null;
try {
WS = WebSocket;
if (WS == null) {
throw new Error("inject please");
}
}
catch (error) {
const logger = new lib_esm_Logger(providers_lib_esm_version_version);
WS = function () {
logger.throwError("WebSockets not supported in this environment", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new WebSocket()"
});
};
}
//export default WS;
//module.exports = WS;
//# sourceMappingURL=ws.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/websocket-provider.js
var websocket_provider_awaiter = (undefined && undefined.__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());
});
};
const websocket_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
/**
* Notes:
*
* This provider differs a bit from the polling providers. One main
* difference is how it handles consistency. The polling providers
* will stall responses to ensure a consistent state, while this
* WebSocket provider assumes the connected backend will manage this.
*
* For example, if a polling provider emits an event which indicates
* the event occurred in blockhash XXX, a call to fetch that block by
* its hash XXX, if not present will retry until it is present. This
* can occur when querying a pool of nodes that are mildly out of sync
* with each other.
*/
let NextId = 1;
// For more info about the Real-time Event API see:
// https://geth.ethereum.org/docs/rpc/pubsub
class websocket_provider_WebSocketProvider extends json_rpc_provider_JsonRpcProvider {
constructor(url, network) {
// This will be added in the future; please open an issue to expedite
if (network === "any") {
websocket_provider_logger.throwError("WebSocketProvider does not support 'any' network yet", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "network:any"
});
}
if (typeof (url) === "string") {
super(url, network);
}
else {
super("_websocket", network);
}
this._pollingInterval = -1;
this._wsReady = false;
if (typeof (url) === "string") {
defineReadOnly(this, "_websocket", new WS(this.connection.url));
}
else {
defineReadOnly(this, "_websocket", url);
}
defineReadOnly(this, "_requests", {});
defineReadOnly(this, "_subs", {});
defineReadOnly(this, "_subIds", {});
defineReadOnly(this, "_detectNetwork", super.detectNetwork());
// Stall sending requests until the socket is open...
this.websocket.onopen = () => {
this._wsReady = true;
Object.keys(this._requests).forEach((id) => {
this.websocket.send(this._requests[id].payload);
});
};
this.websocket.onmessage = (messageEvent) => {
const data = messageEvent.data;
const result = JSON.parse(data);
if (result.id != null) {
const id = String(result.id);
const request = this._requests[id];
delete this._requests[id];
if (result.result !== undefined) {
request.callback(null, result.result);
this.emit("debug", {
action: "response",
request: JSON.parse(request.payload),
response: result.result,
provider: this
});
}
else {
let error = null;
if (result.error) {
error = new Error(result.error.message || "unknown error");
defineReadOnly(error, "code", result.error.code || null);
defineReadOnly(error, "response", data);
}
else {
error = new Error("unknown error");
}
request.callback(error, undefined);
this.emit("debug", {
action: "response",
error: error,
request: JSON.parse(request.payload),
provider: this
});
}
}
else if (result.method === "eth_subscription") {
// Subscription...
const sub = this._subs[result.params.subscription];
if (sub) {
//this.emit.apply(this, );
sub.processFunc(result.params.result);
}
}
else {
console.warn("this should not happen");
}
};
// This Provider does not actually poll, but we want to trigger
// poll events for things that depend on them (like stalling for
// block and transaction lookups)
const fauxPoll = setInterval(() => {
this.emit("poll");
}, 1000);
if (fauxPoll.unref) {
fauxPoll.unref();
}
}
// Cannot narrow the type of _websocket, as that is not backwards compatible
// so we add a getter and let the WebSocket be a public API.
get websocket() { return this._websocket; }
detectNetwork() {
return this._detectNetwork;
}
get pollingInterval() {
return 0;
}
resetEventsBlock(blockNumber) {
websocket_provider_logger.throwError("cannot reset events block on WebSocketProvider", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "resetEventBlock"
});
}
set pollingInterval(value) {
websocket_provider_logger.throwError("cannot set polling interval on WebSocketProvider", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "setPollingInterval"
});
}
poll() {
return websocket_provider_awaiter(this, void 0, void 0, function* () {
return null;
});
}
set polling(value) {
if (!value) {
return;
}
websocket_provider_logger.throwError("cannot set polling on WebSocketProvider", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "setPolling"
});
}
send(method, params) {
const rid = NextId++;
return new Promise((resolve, reject) => {
function callback(error, result) {
if (error) {
return reject(error);
}
return resolve(result);
}
const payload = JSON.stringify({
method: method,
params: params,
id: rid,
jsonrpc: "2.0"
});
this.emit("debug", {
action: "request",
request: JSON.parse(payload),
provider: this
});
this._requests[String(rid)] = { callback, payload };
if (this._wsReady) {
this.websocket.send(payload);
}
});
}
static defaultUrl() {
return "ws:/\/localhost:8546";
}
_subscribe(tag, param, processFunc) {
return websocket_provider_awaiter(this, void 0, void 0, function* () {
let subIdPromise = this._subIds[tag];
if (subIdPromise == null) {
subIdPromise = Promise.all(param).then((param) => {
return this.send("eth_subscribe", param);
});
this._subIds[tag] = subIdPromise;
}
const subId = yield subIdPromise;
this._subs[subId] = { tag, processFunc };
});
}
_startEvent(event) {
switch (event.type) {
case "block":
this._subscribe("block", ["newHeads"], (result) => {
const blockNumber = bignumber_BigNumber.from(result.number).toNumber();
this._emitted.block = blockNumber;
this.emit("block", blockNumber);
});
break;
case "pending":
this._subscribe("pending", ["newPendingTransactions"], (result) => {
this.emit("pending", result);
});
break;
case "filter":
this._subscribe(event.tag, ["logs", this._getFilter(event.filter)], (result) => {
if (result.removed == null) {
result.removed = false;
}
this.emit(event.filter, this.formatter.filterLog(result));
});
break;
case "tx": {
const emitReceipt = (event) => {
const hash = event.hash;
this.getTransactionReceipt(hash).then((receipt) => {
if (!receipt) {
return;
}
this.emit(hash, receipt);
});
};
// In case it is already mined
emitReceipt(event);
// To keep things simple, we start up a single newHeads subscription
// to keep an eye out for transactions we are watching for.
// Starting a subscription for an event (i.e. "tx") that is already
// running is (basically) a nop.
this._subscribe("tx", ["newHeads"], (result) => {
this._events.filter((e) => (e.type === "tx")).forEach(emitReceipt);
});
break;
}
// Nothing is needed
case "debug":
case "poll":
case "willPoll":
case "didPoll":
case "error":
break;
default:
console.log("unhandled:", event);
break;
}
}
_stopEvent(event) {
let tag = event.tag;
if (event.type === "tx") {
// There are remaining transaction event listeners
if (this._events.filter((e) => (e.type === "tx")).length) {
return;
}
tag = "tx";
}
else if (this.listenerCount(event.event)) {
// There are remaining event listeners
return;
}
const subId = this._subIds[tag];
if (!subId) {
return;
}
delete this._subIds[tag];
subId.then((subId) => {
if (!this._subs[subId]) {
return;
}
delete this._subs[subId];
this.send("eth_unsubscribe", [subId]);
});
}
destroy() {
return websocket_provider_awaiter(this, void 0, void 0, function* () {
// Wait until we have connected before trying to disconnect
if (this.websocket.readyState === WS.CONNECTING) {
yield (new Promise((resolve) => {
this.websocket.onopen = function () {
resolve(true);
};
this.websocket.onerror = function () {
resolve(false);
};
}));
}
// Hangup
// See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
this.websocket.close(1000);
});
}
}
//# sourceMappingURL=websocket-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/url-json-rpc-provider.js
var url_json_rpc_provider_awaiter = (undefined && undefined.__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());
});
};
const url_json_rpc_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
// A StaticJsonRpcProvider is useful when you *know* for certain that
// the backend will never change, as it never calls eth_chainId to
// verify its backend. However, if the backend does change, the effects
// are undefined and may include:
// - inconsistent results
// - locking up the UI
// - block skew warnings
// - wrong results
// If the network is not explicit (i.e. auto-detection is expected), the
// node MUST be running and available to respond to requests BEFORE this
// is instantiated.
class url_json_rpc_provider_StaticJsonRpcProvider extends json_rpc_provider_JsonRpcProvider {
detectNetwork() {
const _super = Object.create(null, {
detectNetwork: { get: () => super.detectNetwork }
});
return url_json_rpc_provider_awaiter(this, void 0, void 0, function* () {
let network = this.network;
if (network == null) {
network = yield _super.detectNetwork.call(this);
if (!network) {
url_json_rpc_provider_logger.throwError("no network detected", lib_esm_Logger.errors.UNKNOWN_ERROR, {});
}
// If still not set, set it
if (this._network == null) {
// A static network does not support "any"
defineReadOnly(this, "_network", network);
this.emit("network", network, null);
}
}
return network;
});
}
}
class url_json_rpc_provider_UrlJsonRpcProvider extends url_json_rpc_provider_StaticJsonRpcProvider {
constructor(network, apiKey) {
url_json_rpc_provider_logger.checkAbstract(new.target, url_json_rpc_provider_UrlJsonRpcProvider);
// Normalize the Network and API Key
network = getStatic(new.target, "getNetwork")(network);
apiKey = getStatic(new.target, "getApiKey")(apiKey);
const connection = getStatic(new.target, "getUrl")(network, apiKey);
super(connection, network);
if (typeof (apiKey) === "string") {
defineReadOnly(this, "apiKey", apiKey);
}
else if (apiKey != null) {
Object.keys(apiKey).forEach((key) => {
defineReadOnly(this, key, apiKey[key]);
});
}
}
_startPending() {
url_json_rpc_provider_logger.warn("WARNING: API provider does not support pending filters");
}
isCommunityResource() {
return false;
}
getSigner(address) {
return url_json_rpc_provider_logger.throwError("API provider does not support signing", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { operation: "getSigner" });
}
listAccounts() {
return Promise.resolve([]);
}
// Return a defaultApiKey if null, otherwise validate the API key
static getApiKey(apiKey) {
return apiKey;
}
// Returns the url or connection for the given network and API key. The
// API key will have been sanitized by the getApiKey first, so any validation
// or transformations can be done there.
static getUrl(network, apiKey) {
return url_json_rpc_provider_logger.throwError("not implemented; sub-classes must override getUrl", lib_esm_Logger.errors.NOT_IMPLEMENTED, {
operation: "getUrl"
});
}
}
//# sourceMappingURL=url-json-rpc-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/alchemy-provider.js
const alchemy_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
// This key was provided to ethers.js by Alchemy to be used by the
// default provider, but it is recommended that for your own
// production environments, that you acquire your own API key at:
// https://dashboard.alchemyapi.io
const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";
class alchemy_provider_AlchemyWebSocketProvider extends websocket_provider_WebSocketProvider {
constructor(network, apiKey) {
const provider = new alchemy_provider_AlchemyProvider(network, apiKey);
const url = provider.connection.url.replace(/^http/i, "ws")
.replace(".alchemyapi.", ".ws.alchemyapi.");
super(url, provider.network);
defineReadOnly(this, "apiKey", provider.apiKey);
}
isCommunityResource() {
return (this.apiKey === defaultApiKey);
}
}
class alchemy_provider_AlchemyProvider extends url_json_rpc_provider_UrlJsonRpcProvider {
static getWebSocketProvider(network, apiKey) {
return new alchemy_provider_AlchemyWebSocketProvider(network, apiKey);
}
static getApiKey(apiKey) {
if (apiKey == null) {
return defaultApiKey;
}
if (apiKey && typeof (apiKey) !== "string") {
alchemy_provider_logger.throwArgumentError("invalid apiKey", "apiKey", apiKey);
}
return apiKey;
}
static getUrl(network, apiKey) {
let host = null;
switch (network.name) {
case "homestead":
host = "eth-mainnet.alchemyapi.io/v2/";
break;
case "goerli":
host = "eth-goerli.g.alchemy.com/v2/";
break;
case "matic":
host = "polygon-mainnet.g.alchemy.com/v2/";
break;
case "maticmum":
host = "polygon-mumbai.g.alchemy.com/v2/";
break;
case "arbitrum":
host = "arb-mainnet.g.alchemy.com/v2/";
break;
case "arbitrum-goerli":
host = "arb-goerli.g.alchemy.com/v2/";
break;
case "optimism":
host = "opt-mainnet.g.alchemy.com/v2/";
break;
case "optimism-goerli":
host = "opt-goerli.g.alchemy.com/v2/";
break;
default:
alchemy_provider_logger.throwArgumentError("unsupported network", "network", arguments[0]);
}
return {
allowGzip: true,
url: ("https:/" + "/" + host + apiKey),
throttleCallback: (attempt, url) => {
if (apiKey === defaultApiKey) {
showThrottleMessage();
}
return Promise.resolve(true);
}
};
}
isCommunityResource() {
return (this.apiKey === defaultApiKey);
}
}
//# sourceMappingURL=alchemy-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/ankr-provider.js
const ankr_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
const ankr_provider_defaultApiKey = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972";
function getHost(name) {
switch (name) {
case "homestead":
return "rpc.ankr.com/eth/";
case "ropsten":
return "rpc.ankr.com/eth_ropsten/";
case "rinkeby":
return "rpc.ankr.com/eth_rinkeby/";
case "goerli":
return "rpc.ankr.com/eth_goerli/";
case "matic":
return "rpc.ankr.com/polygon/";
case "arbitrum":
return "rpc.ankr.com/arbitrum/";
}
return ankr_provider_logger.throwArgumentError("unsupported network", "name", name);
}
class ankr_provider_AnkrProvider extends url_json_rpc_provider_UrlJsonRpcProvider {
isCommunityResource() {
return (this.apiKey === ankr_provider_defaultApiKey);
}
static getApiKey(apiKey) {
if (apiKey == null) {
return ankr_provider_defaultApiKey;
}
return apiKey;
}
static getUrl(network, apiKey) {
if (apiKey == null) {
apiKey = ankr_provider_defaultApiKey;
}
const connection = {
allowGzip: true,
url: ("https:/\/" + getHost(network.name) + apiKey),
throttleCallback: (attempt, url) => {
if (apiKey.apiKey === ankr_provider_defaultApiKey) {
showThrottleMessage();
}
return Promise.resolve(true);
}
};
if (apiKey.projectSecret != null) {
connection.user = "";
connection.password = apiKey.projectSecret;
}
return connection;
}
}
//# sourceMappingURL=ankr-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/cloudflare-provider.js
var cloudflare_provider_awaiter = (undefined && undefined.__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());
});
};
const cloudflare_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
class cloudflare_provider_CloudflareProvider extends url_json_rpc_provider_UrlJsonRpcProvider {
static getApiKey(apiKey) {
if (apiKey != null) {
cloudflare_provider_logger.throwArgumentError("apiKey not supported for cloudflare", "apiKey", apiKey);
}
return null;
}
static getUrl(network, apiKey) {
let host = null;
switch (network.name) {
case "homestead":
host = "https://cloudflare-eth.com/";
break;
default:
cloudflare_provider_logger.throwArgumentError("unsupported network", "network", arguments[0]);
}
return host;
}
perform(method, params) {
const _super = Object.create(null, {
perform: { get: () => super.perform }
});
return cloudflare_provider_awaiter(this, void 0, void 0, function* () {
// The Cloudflare provider does not support eth_blockNumber,
// so we get the latest block and pull it from that
if (method === "getBlockNumber") {
const block = yield _super.perform.call(this, "getBlock", { blockTag: "latest" });
return block.number;
}
return _super.perform.call(this, method, params);
});
}
}
//# sourceMappingURL=cloudflare-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/etherscan-provider.js
var etherscan_provider_awaiter = (undefined && undefined.__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());
});
};
const etherscan_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
// The transaction has already been sanitized by the calls in Provider
function getTransactionPostData(transaction) {
const result = {};
for (let key in transaction) {
if (transaction[key] == null) {
continue;
}
let value = transaction[key];
if (key === "type" && value === 0) {
continue;
}
// Quantity-types require no leading zero, unless 0
if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) {
value = hexValue(hexlify(value));
}
else if (key === "accessList") {
value = "[" + accessListify(value).map((set) => {
return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`;
}).join(",") + "]";
}
else {
value = hexlify(value);
}
result[key] = value;
}
return result;
}
function etherscan_provider_getResult(result) {
// getLogs, getHistory have weird success responses
if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) {
return result.result;
}
if (result.status != 1 || typeof (result.message) !== "string" || !result.message.match(/^OK/)) {
const error = new Error("invalid response");
error.result = JSON.stringify(result);
if ((result.result || "").toLowerCase().indexOf("rate limit") >= 0) {
error.throttleRetry = true;
}
throw error;
}
return result.result;
}
function getJsonResult(result) {
// This response indicates we are being throttled
if (result && result.status == 0 && result.message == "NOTOK" && (result.result || "").toLowerCase().indexOf("rate limit") >= 0) {
const error = new Error("throttled response");
error.result = JSON.stringify(result);
error.throttleRetry = true;
throw error;
}
if (result.jsonrpc != "2.0") {
// @TODO: not any
const error = new Error("invalid response");
error.result = JSON.stringify(result);
throw error;
}
if (result.error) {
// @TODO: not any
const error = new Error(result.error.message || "unknown error");
if (result.error.code) {
error.code = result.error.code;
}
if (result.error.data) {
error.data = result.error.data;
}
throw error;
}
return result.result;
}
// The blockTag was normalized as a string by the Provider pre-perform operations
function checkLogTag(blockTag) {
if (blockTag === "pending") {
throw new Error("pending not supported");
}
if (blockTag === "latest") {
return blockTag;
}
return parseInt(blockTag.substring(2), 16);
}
function etherscan_provider_checkError(method, error, transaction) {
// Undo the "convenience" some nodes are attempting to prevent backwards
// incompatibility; maybe for v6 consider forwarding reverts as errors
if (method === "call" && error.code === lib_esm_Logger.errors.SERVER_ERROR) {
const e = error.error;
// Etherscan keeps changing their string
if (e && (e.message.match(/reverted/i) || e.message.match(/VM execution error/i))) {
// Etherscan prefixes the data like "Reverted 0x1234"
let data = e.data;
if (data) {
data = "0x" + data.replace(/^.*0x/i, "");
}
if (isHexString(data)) {
return data;
}
etherscan_provider_logger.throwError("missing revert data in call exception", lib_esm_Logger.errors.CALL_EXCEPTION, {
error, data: "0x"
});
}
}
// Get the message from any nested error structure
let message = error.message;
if (error.code === lib_esm_Logger.errors.SERVER_ERROR) {
if (error.error && typeof (error.error.message) === "string") {
message = error.error.message;
}
else if (typeof (error.body) === "string") {
message = error.body;
}
else if (typeof (error.responseText) === "string") {
message = error.responseText;
}
}
message = (message || "").toLowerCase();
// "Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 21464000000000 and got: 0"
if (message.match(/insufficient funds/)) {
etherscan_provider_logger.throwError("insufficient funds for intrinsic transaction cost", lib_esm_Logger.errors.INSUFFICIENT_FUNDS, {
error, method, transaction
});
}
// "Transaction with the same hash was already imported."
if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) {
etherscan_provider_logger.throwError("nonce has already been used", lib_esm_Logger.errors.NONCE_EXPIRED, {
error, method, transaction
});
}
// "Transaction gas price is too low. There is another transaction with same nonce in the queue. Try increasing the gas price or incrementing the nonce."
if (message.match(/another transaction with same nonce/)) {
etherscan_provider_logger.throwError("replacement fee too low", lib_esm_Logger.errors.REPLACEMENT_UNDERPRICED, {
error, method, transaction
});
}
if (message.match(/execution failed due to an exception|execution reverted/)) {
etherscan_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", lib_esm_Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
error, method, transaction
});
}
throw error;
}
class etherscan_provider_EtherscanProvider extends base_provider_BaseProvider {
constructor(network, apiKey) {
super(network);
defineReadOnly(this, "baseUrl", this.getBaseUrl());
defineReadOnly(this, "apiKey", apiKey || null);
}
getBaseUrl() {
switch (this.network ? this.network.name : "invalid") {
case "homestead":
return "https:/\/api.etherscan.io";
case "goerli":
return "https:/\/api-goerli.etherscan.io";
case "sepolia":
return "https:/\/api-sepolia.etherscan.io";
case "matic":
return "https:/\/api.polygonscan.com";
case "maticmum":
return "https:/\/api-testnet.polygonscan.com";
case "arbitrum":
return "https:/\/api.arbiscan.io";
case "arbitrum-goerli":
return "https:/\/api-goerli.arbiscan.io";
case "optimism":
return "https:/\/api-optimistic.etherscan.io";
case "optimism-goerli":
return "https:/\/api-goerli-optimistic.etherscan.io";
default:
}
return etherscan_provider_logger.throwArgumentError("unsupported network", "network", this.network.name);
}
getUrl(module, params) {
const query = Object.keys(params).reduce((accum, key) => {
const value = params[key];
if (value != null) {
accum += `&${key}=${value}`;
}
return accum;
}, "");
const apiKey = ((this.apiKey) ? `&apikey=${this.apiKey}` : "");
return `${this.baseUrl}/api?module=${module}${query}${apiKey}`;
}
getPostUrl() {
return `${this.baseUrl}/api`;
}
getPostData(module, params) {
params.module = module;
params.apikey = this.apiKey;
return params;
}
fetch(module, params, post) {
return etherscan_provider_awaiter(this, void 0, void 0, function* () {
const url = (post ? this.getPostUrl() : this.getUrl(module, params));
const payload = (post ? this.getPostData(module, params) : null);
const procFunc = (module === "proxy") ? getJsonResult : etherscan_provider_getResult;
this.emit("debug", {
action: "request",
request: url,
provider: this
});
const connection = {
url: url,
throttleSlotInterval: 1000,
throttleCallback: (attempt, url) => {
if (this.isCommunityResource()) {
showThrottleMessage();
}
return Promise.resolve(true);
}
};
let payloadStr = null;
if (payload) {
connection.headers = { "content-type": "application/x-www-form-urlencoded; charset=UTF-8" };
payloadStr = Object.keys(payload).map((key) => {
return `${key}=${payload[key]}`;
}).join("&");
}
const result = yield fetchJson(connection, payloadStr, procFunc || getJsonResult);
this.emit("debug", {
action: "response",
request: url,
response: deepCopy(result),
provider: this
});
return result;
});
}
detectNetwork() {
return etherscan_provider_awaiter(this, void 0, void 0, function* () {
return this.network;
});
}
perform(method, params) {
const _super = Object.create(null, {
perform: { get: () => super.perform }
});
return etherscan_provider_awaiter(this, void 0, void 0, function* () {
switch (method) {
case "getBlockNumber":
return this.fetch("proxy", { action: "eth_blockNumber" });
case "getGasPrice":
return this.fetch("proxy", { action: "eth_gasPrice" });
case "getBalance":
// Returns base-10 result
return this.fetch("account", {
action: "balance",
address: params.address,
tag: params.blockTag
});
case "getTransactionCount":
return this.fetch("proxy", {
action: "eth_getTransactionCount",
address: params.address,
tag: params.blockTag
});
case "getCode":
return this.fetch("proxy", {
action: "eth_getCode",
address: params.address,
tag: params.blockTag
});
case "getStorageAt":
return this.fetch("proxy", {
action: "eth_getStorageAt",
address: params.address,
position: params.position,
tag: params.blockTag
});
case "sendTransaction":
return this.fetch("proxy", {
action: "eth_sendRawTransaction",
hex: params.signedTransaction
}, true).catch((error) => {
return etherscan_provider_checkError("sendTransaction", error, params.signedTransaction);
});
case "getBlock":
if (params.blockTag) {
return this.fetch("proxy", {
action: "eth_getBlockByNumber",
tag: params.blockTag,
boolean: (params.includeTransactions ? "true" : "false")
});
}
throw new Error("getBlock by blockHash not implemented");
case "getTransaction":
return this.fetch("proxy", {
action: "eth_getTransactionByHash",
txhash: params.transactionHash
});
case "getTransactionReceipt":
return this.fetch("proxy", {
action: "eth_getTransactionReceipt",
txhash: params.transactionHash
});
case "call": {
if (params.blockTag !== "latest") {
throw new Error("EtherscanProvider does not support blockTag for call");
}
const postData = getTransactionPostData(params.transaction);
postData.module = "proxy";
postData.action = "eth_call";
try {
return yield this.fetch("proxy", postData, true);
}
catch (error) {
return etherscan_provider_checkError("call", error, params.transaction);
}
}
case "estimateGas": {
const postData = getTransactionPostData(params.transaction);
postData.module = "proxy";
postData.action = "eth_estimateGas";
try {
return yield this.fetch("proxy", postData, true);
}
catch (error) {
return etherscan_provider_checkError("estimateGas", error, params.transaction);
}
}
case "getLogs": {
const args = { action: "getLogs" };
if (params.filter.fromBlock) {
args.fromBlock = checkLogTag(params.filter.fromBlock);
}
if (params.filter.toBlock) {
args.toBlock = checkLogTag(params.filter.toBlock);
}
if (params.filter.address) {
args.address = params.filter.address;
}
// @TODO: We can handle slightly more complicated logs using the logs API
if (params.filter.topics && params.filter.topics.length > 0) {
if (params.filter.topics.length > 1) {
etherscan_provider_logger.throwError("unsupported topic count", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { topics: params.filter.topics });
}
if (params.filter.topics.length === 1) {
const topic0 = params.filter.topics[0];
if (typeof (topic0) !== "string" || topic0.length !== 66) {
etherscan_provider_logger.throwError("unsupported topic format", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { topic0: topic0 });
}
args.topic0 = topic0;
}
}
const logs = yield this.fetch("logs", args);
// Cache txHash => blockHash
let blocks = {};
// Add any missing blockHash to the logs
for (let i = 0; i < logs.length; i++) {
const log = logs[i];
if (log.blockHash != null) {
continue;
}
if (blocks[log.blockNumber] == null) {
const block = yield this.getBlock(log.blockNumber);
if (block) {
blocks[log.blockNumber] = block.hash;
}
}
log.blockHash = blocks[log.blockNumber];
}
return logs;
}
case "getEtherPrice":
if (this.network.name !== "homestead") {
return 0.0;
}
return parseFloat((yield this.fetch("stats", { action: "ethprice" })).ethusd);
default:
break;
}
return _super.perform.call(this, method, params);
});
}
// Note: The `page` page parameter only allows pagination within the
// 10,000 window available without a page and offset parameter
// Error: Result window is too large, PageNo x Offset size must
// be less than or equal to 10000
getHistory(addressOrName, startBlock, endBlock) {
return etherscan_provider_awaiter(this, void 0, void 0, function* () {
const params = {
action: "txlist",
address: (yield this.resolveName(addressOrName)),
startblock: ((startBlock == null) ? 0 : startBlock),
endblock: ((endBlock == null) ? 99999999 : endBlock),
sort: "asc"
};
const result = yield this.fetch("account", params);
return result.map((tx) => {
["contractAddress", "to"].forEach(function (key) {
if (tx[key] == "") {
delete tx[key];
}
});
if (tx.creates == null && tx.contractAddress != null) {
tx.creates = tx.contractAddress;
}
const item = this.formatter.transactionResponse(tx);
if (tx.timeStamp) {
item.timestamp = parseInt(tx.timeStamp);
}
return item;
});
});
}
isCommunityResource() {
return (this.apiKey == null);
}
}
//# sourceMappingURL=etherscan-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/random/lib.esm/shuffle.js
function shuffled(array) {
array = array.slice();
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
return array;
}
//# sourceMappingURL=shuffle.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/fallback-provider.js
var fallback_provider_awaiter = (undefined && undefined.__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());
});
};
const fallback_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
function fallback_provider_now() { return (new Date()).getTime(); }
// Returns to network as long as all agree, or null if any is null.
// Throws an error if any two networks do not match.
function checkNetworks(networks) {
let result = null;
for (let i = 0; i < networks.length; i++) {
const network = networks[i];
// Null! We do not know our network; bail.
if (network == null) {
return null;
}
if (result) {
// Make sure the network matches the previous networks
if (!(result.name === network.name && result.chainId === network.chainId &&
((result.ensAddress === network.ensAddress) || (result.ensAddress == null && network.ensAddress == null)))) {
fallback_provider_logger.throwArgumentError("provider mismatch", "networks", networks);
}
}
else {
result = network;
}
}
return result;
}
function median(values, maxDelta) {
values = values.slice().sort();
const middle = Math.floor(values.length / 2);
// Odd length; take the middle
if (values.length % 2) {
return values[middle];
}
// Even length; take the average of the two middle
const a = values[middle - 1], b = values[middle];
if (maxDelta != null && Math.abs(a - b) > maxDelta) {
return null;
}
return (a + b) / 2;
}
function fallback_provider_serialize(value) {
if (value === null) {
return "null";
}
else if (typeof (value) === "number" || typeof (value) === "boolean") {
return JSON.stringify(value);
}
else if (typeof (value) === "string") {
return value;
}
else if (bignumber_BigNumber.isBigNumber(value)) {
return value.toString();
}
else if (Array.isArray(value)) {
return JSON.stringify(value.map((i) => fallback_provider_serialize(i)));
}
else if (typeof (value) === "object") {
const keys = Object.keys(value);
keys.sort();
return "{" + keys.map((key) => {
let v = value[key];
if (typeof (v) === "function") {
v = "[function]";
}
else {
v = fallback_provider_serialize(v);
}
return JSON.stringify(key) + ":" + v;
}).join(",") + "}";
}
throw new Error("unknown value type: " + typeof (value));
}
// Next request ID to use for emitting debug info
let nextRid = 1;
;
function fallback_provider_stall(duration) {
let cancel = null;
let timer = null;
let promise = (new Promise((resolve) => {
cancel = function () {
if (timer) {
clearTimeout(timer);
timer = null;
}
resolve();
};
timer = setTimeout(cancel, duration);
}));
const wait = (func) => {
promise = promise.then(func);
return promise;
};
function getPromise() {
return promise;
}
return { cancel, getPromise, wait };
}
const ForwardErrors = [
lib_esm_Logger.errors.CALL_EXCEPTION,
lib_esm_Logger.errors.INSUFFICIENT_FUNDS,
lib_esm_Logger.errors.NONCE_EXPIRED,
lib_esm_Logger.errors.REPLACEMENT_UNDERPRICED,
lib_esm_Logger.errors.UNPREDICTABLE_GAS_LIMIT
];
const ForwardProperties = [
"address",
"args",
"errorArgs",
"errorSignature",
"method",
"transaction",
];
;
function exposeDebugConfig(config, now) {
const result = {
weight: config.weight
};
Object.defineProperty(result, "provider", { get: () => config.provider });
if (config.start) {
result.start = config.start;
}
if (now) {
result.duration = (now - config.start);
}
if (config.done) {
if (config.error) {
result.error = config.error;
}
else {
result.result = config.result || null;
}
}
return result;
}
function normalizedTally(normalize, quorum) {
return function (configs) {
// Count the votes for each result
const tally = {};
configs.forEach((c) => {
const value = normalize(c.result);
if (!tally[value]) {
tally[value] = { count: 0, result: c.result };
}
tally[value].count++;
});
// Check for a quorum on any given result
const keys = Object.keys(tally);
for (let i = 0; i < keys.length; i++) {
const check = tally[keys[i]];
if (check.count >= quorum) {
return check.result;
}
}
// No quroum
return undefined;
};
}
function getProcessFunc(provider, method, params) {
let normalize = fallback_provider_serialize;
switch (method) {
case "getBlockNumber":
// Return the median value, unless there is (median + 1) is also
// present, in which case that is probably true and the median
// is going to be stale soon. In the event of a malicious node,
// the lie will be true soon enough.
return function (configs) {
const values = configs.map((c) => c.result);
// Get the median block number
let blockNumber = median(configs.map((c) => c.result), 2);
if (blockNumber == null) {
return undefined;
}
blockNumber = Math.ceil(blockNumber);
// If the next block height is present, its prolly safe to use
if (values.indexOf(blockNumber + 1) >= 0) {
blockNumber++;
}
// Don't ever roll back the blockNumber
if (blockNumber >= provider._highestBlockNumber) {
provider._highestBlockNumber = blockNumber;
}
return provider._highestBlockNumber;
};
case "getGasPrice":
// Return the middle (round index up) value, similar to median
// but do not average even entries and choose the higher.
// Malicious actors must compromise 50% of the nodes to lie.
return function (configs) {
const values = configs.map((c) => c.result);
values.sort();
return values[Math.floor(values.length / 2)];
};
case "getEtherPrice":
// Returns the median price. Malicious actors must compromise at
// least 50% of the nodes to lie (in a meaningful way).
return function (configs) {
return median(configs.map((c) => c.result));
};
// No additional normalizing required; serialize is enough
case "getBalance":
case "getTransactionCount":
case "getCode":
case "getStorageAt":
case "call":
case "estimateGas":
case "getLogs":
break;
// We drop the confirmations from transactions as it is approximate
case "getTransaction":
case "getTransactionReceipt":
normalize = function (tx) {
if (tx == null) {
return null;
}
tx = shallowCopy(tx);
tx.confirmations = -1;
return fallback_provider_serialize(tx);
};
break;
// We drop the confirmations from transactions as it is approximate
case "getBlock":
// We drop the confirmations from transactions as it is approximate
if (params.includeTransactions) {
normalize = function (block) {
if (block == null) {
return null;
}
block = shallowCopy(block);
block.transactions = block.transactions.map((tx) => {
tx = shallowCopy(tx);
tx.confirmations = -1;
return tx;
});
return fallback_provider_serialize(block);
};
}
else {
normalize = function (block) {
if (block == null) {
return null;
}
return fallback_provider_serialize(block);
};
}
break;
default:
throw new Error("unknown method: " + method);
}
// Return the result if and only if the expected quorum is
// satisfied and agreed upon for the final result.
return normalizedTally(normalize, provider.quorum);
}
// If we are doing a blockTag query, we need to make sure the backend is
// caught up to the FallbackProvider, before sending a request to it.
function waitForSync(config, blockNumber) {
return fallback_provider_awaiter(this, void 0, void 0, function* () {
const provider = (config.provider);
if ((provider.blockNumber != null && provider.blockNumber >= blockNumber) || blockNumber === -1) {
return provider;
}
return lib_esm_poll(() => {
return new Promise((resolve, reject) => {
setTimeout(function () {
// We are synced
if (provider.blockNumber >= blockNumber) {
return resolve(provider);
}
// We're done; just quit
if (config.cancelled) {
return resolve(null);
}
// Try again, next block
return resolve(undefined);
}, 0);
});
}, { oncePoll: provider });
});
}
function getRunner(config, currentBlockNumber, method, params) {
return fallback_provider_awaiter(this, void 0, void 0, function* () {
let provider = config.provider;
switch (method) {
case "getBlockNumber":
case "getGasPrice":
return provider[method]();
case "getEtherPrice":
if (provider.getEtherPrice) {
return provider.getEtherPrice();
}
break;
case "getBalance":
case "getTransactionCount":
case "getCode":
if (params.blockTag && isHexString(params.blockTag)) {
provider = yield waitForSync(config, currentBlockNumber);
}
return provider[method](params.address, params.blockTag || "latest");
case "getStorageAt":
if (params.blockTag && isHexString(params.blockTag)) {
provider = yield waitForSync(config, currentBlockNumber);
}
return provider.getStorageAt(params.address, params.position, params.blockTag || "latest");
case "getBlock":
if (params.blockTag && isHexString(params.blockTag)) {
provider = yield waitForSync(config, currentBlockNumber);
}
return provider[(params.includeTransactions ? "getBlockWithTransactions" : "getBlock")](params.blockTag || params.blockHash);
case "call":
case "estimateGas":
if (params.blockTag && isHexString(params.blockTag)) {
provider = yield waitForSync(config, currentBlockNumber);
}
if (method === "call" && params.blockTag) {
return provider[method](params.transaction, params.blockTag);
}
return provider[method](params.transaction);
case "getTransaction":
case "getTransactionReceipt":
return provider[method](params.transactionHash);
case "getLogs": {
let filter = params.filter;
if ((filter.fromBlock && isHexString(filter.fromBlock)) || (filter.toBlock && isHexString(filter.toBlock))) {
provider = yield waitForSync(config, currentBlockNumber);
}
return provider.getLogs(filter);
}
}
return fallback_provider_logger.throwError("unknown method error", lib_esm_Logger.errors.UNKNOWN_ERROR, {
method: method,
params: params
});
});
}
class fallback_provider_FallbackProvider extends base_provider_BaseProvider {
constructor(providers, quorum) {
if (providers.length === 0) {
fallback_provider_logger.throwArgumentError("missing providers", "providers", providers);
}
const providerConfigs = providers.map((configOrProvider, index) => {
if (lib_esm_Provider.isProvider(configOrProvider)) {
const stallTimeout = isCommunityResource(configOrProvider) ? 2000 : 750;
const priority = 1;
return Object.freeze({ provider: configOrProvider, weight: 1, stallTimeout, priority });
}
const config = shallowCopy(configOrProvider);
if (config.priority == null) {
config.priority = 1;
}
if (config.stallTimeout == null) {
config.stallTimeout = isCommunityResource(configOrProvider) ? 2000 : 750;
}
if (config.weight == null) {
config.weight = 1;
}
const weight = config.weight;
if (weight % 1 || weight > 512 || weight < 1) {
fallback_provider_logger.throwArgumentError("invalid weight; must be integer in [1, 512]", `providers[${index}].weight`, weight);
}
return Object.freeze(config);
});
const total = providerConfigs.reduce((accum, c) => (accum + c.weight), 0);
if (quorum == null) {
quorum = total / 2;
}
else if (quorum > total) {
fallback_provider_logger.throwArgumentError("quorum will always fail; larger than total weight", "quorum", quorum);
}
// Are all providers' networks are known
let networkOrReady = checkNetworks(providerConfigs.map((c) => (c.provider).network));
// Not all networks are known; we must stall
if (networkOrReady == null) {
networkOrReady = new Promise((resolve, reject) => {
setTimeout(() => {
this.detectNetwork().then(resolve, reject);
}, 0);
});
}
super(networkOrReady);
// Preserve a copy, so we do not get mutated
defineReadOnly(this, "providerConfigs", Object.freeze(providerConfigs));
defineReadOnly(this, "quorum", quorum);
this._highestBlockNumber = -1;
}
detectNetwork() {
return fallback_provider_awaiter(this, void 0, void 0, function* () {
const networks = yield Promise.all(this.providerConfigs.map((c) => c.provider.getNetwork()));
return checkNetworks(networks);
});
}
perform(method, params) {
return fallback_provider_awaiter(this, void 0, void 0, function* () {
// Sending transactions is special; always broadcast it to all backends
if (method === "sendTransaction") {
const results = yield Promise.all(this.providerConfigs.map((c) => {
return c.provider.sendTransaction(params.signedTransaction).then((result) => {
return result.hash;
}, (error) => {
return error;
});
}));
// Any success is good enough (other errors are likely "already seen" errors
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (typeof (result) === "string") {
return result;
}
}
// They were all an error; pick the first error
throw results[0];
}
// We need to make sure we are in sync with our backends, so we need
// to know this before we can make a lot of calls
if (this._highestBlockNumber === -1 && method !== "getBlockNumber") {
yield this.getBlockNumber();
}
const processFunc = getProcessFunc(this, method, params);
// Shuffle the providers and then sort them by their priority; we
// shallowCopy them since we will store the result in them too
const configs = shuffled(this.providerConfigs.map(shallowCopy));
configs.sort((a, b) => (a.priority - b.priority));
const currentBlockNumber = this._highestBlockNumber;
let i = 0;
let first = true;
while (true) {
const t0 = fallback_provider_now();
// Compute the inflight weight (exclude anything past)
let inflightWeight = configs.filter((c) => (c.runner && ((t0 - c.start) < c.stallTimeout)))
.reduce((accum, c) => (accum + c.weight), 0);
// Start running enough to meet quorum
while (inflightWeight < this.quorum && i < configs.length) {
const config = configs[i++];
const rid = nextRid++;
config.start = fallback_provider_now();
config.staller = fallback_provider_stall(config.stallTimeout);
config.staller.wait(() => { config.staller = null; });
config.runner = getRunner(config, currentBlockNumber, method, params).then((result) => {
config.done = true;
config.result = result;
if (this.listenerCount("debug")) {
this.emit("debug", {
action: "request",
rid: rid,
backend: exposeDebugConfig(config, fallback_provider_now()),
request: { method: method, params: deepCopy(params) },
provider: this
});
}
}, (error) => {
config.done = true;
config.error = error;
if (this.listenerCount("debug")) {
this.emit("debug", {
action: "request",
rid: rid,
backend: exposeDebugConfig(config, fallback_provider_now()),
request: { method: method, params: deepCopy(params) },
provider: this
});
}
});
if (this.listenerCount("debug")) {
this.emit("debug", {
action: "request",
rid: rid,
backend: exposeDebugConfig(config, null),
request: { method: method, params: deepCopy(params) },
provider: this
});
}
inflightWeight += config.weight;
}
// Wait for anything meaningful to finish or stall out
const waiting = [];
configs.forEach((c) => {
if (c.done || !c.runner) {
return;
}
waiting.push(c.runner);
if (c.staller) {
waiting.push(c.staller.getPromise());
}
});
if (waiting.length) {
yield Promise.race(waiting);
}
// Check the quorum and process the results; the process function
// may additionally decide the quorum is not met
const results = configs.filter((c) => (c.done && c.error == null));
if (results.length >= this.quorum) {
const result = processFunc(results);
if (result !== undefined) {
// Shut down any stallers
configs.forEach(c => {
if (c.staller) {
c.staller.cancel();
}
c.cancelled = true;
});
return result;
}
if (!first) {
yield fallback_provider_stall(100).getPromise();
}
first = false;
}
// No result, check for errors that should be forwarded
const errors = configs.reduce((accum, c) => {
if (!c.done || c.error == null) {
return accum;
}
const code = (c.error).code;
if (ForwardErrors.indexOf(code) >= 0) {
if (!accum[code]) {
accum[code] = { error: c.error, weight: 0 };
}
accum[code].weight += c.weight;
}
return accum;
}, ({}));
Object.keys(errors).forEach((errorCode) => {
const tally = errors[errorCode];
if (tally.weight < this.quorum) {
return;
}
// Shut down any stallers
configs.forEach(c => {
if (c.staller) {
c.staller.cancel();
}
c.cancelled = true;
});
const e = (tally.error);
const props = {};
ForwardProperties.forEach((name) => {
if (e[name] == null) {
return;
}
props[name] = e[name];
});
fallback_provider_logger.throwError(e.reason || e.message, errorCode, props);
});
// All configs have run to completion; we will never get more data
if (configs.filter((c) => !c.done).length === 0) {
break;
}
}
// Shut down any stallers; shouldn't be any
configs.forEach(c => {
if (c.staller) {
c.staller.cancel();
}
c.cancelled = true;
});
return fallback_provider_logger.throwError("failed to meet quorum", lib_esm_Logger.errors.SERVER_ERROR, {
method: method,
params: params,
//results: configs.map((c) => c.result),
//errors: configs.map((c) => c.error),
results: configs.map((c) => exposeDebugConfig(c)),
provider: this
});
});
}
}
//# sourceMappingURL=fallback-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/ipc-provider.js
const IpcProvider = null;
//# sourceMappingURL=ipc-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/infura-provider.js
const infura_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
const defaultProjectId = "84842078b09946638c03157f83405213";
class infura_provider_InfuraWebSocketProvider extends websocket_provider_WebSocketProvider {
constructor(network, apiKey) {
const provider = new infura_provider_InfuraProvider(network, apiKey);
const connection = provider.connection;
if (connection.password) {
infura_provider_logger.throwError("INFURA WebSocket project secrets unsupported", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "InfuraProvider.getWebSocketProvider()"
});
}
const url = connection.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/");
super(url, network);
defineReadOnly(this, "apiKey", provider.projectId);
defineReadOnly(this, "projectId", provider.projectId);
defineReadOnly(this, "projectSecret", provider.projectSecret);
}
isCommunityResource() {
return (this.projectId === defaultProjectId);
}
}
class infura_provider_InfuraProvider extends url_json_rpc_provider_UrlJsonRpcProvider {
static getWebSocketProvider(network, apiKey) {
return new infura_provider_InfuraWebSocketProvider(network, apiKey);
}
static getApiKey(apiKey) {
const apiKeyObj = {
apiKey: defaultProjectId,
projectId: defaultProjectId,
projectSecret: null
};
if (apiKey == null) {
return apiKeyObj;
}
if (typeof (apiKey) === "string") {
apiKeyObj.projectId = apiKey;
}
else if (apiKey.projectSecret != null) {
infura_provider_logger.assertArgument((typeof (apiKey.projectId) === "string"), "projectSecret requires a projectId", "projectId", apiKey.projectId);
infura_provider_logger.assertArgument((typeof (apiKey.projectSecret) === "string"), "invalid projectSecret", "projectSecret", "[REDACTED]");
apiKeyObj.projectId = apiKey.projectId;
apiKeyObj.projectSecret = apiKey.projectSecret;
}
else if (apiKey.projectId) {
apiKeyObj.projectId = apiKey.projectId;
}
apiKeyObj.apiKey = apiKeyObj.projectId;
return apiKeyObj;
}
static getUrl(network, apiKey) {
let host = null;
switch (network ? network.name : "unknown") {
case "homestead":
host = "mainnet.infura.io";
break;
case "goerli":
host = "goerli.infura.io";
break;
case "sepolia":
host = "sepolia.infura.io";
break;
case "matic":
host = "polygon-mainnet.infura.io";
break;
case "maticmum":
host = "polygon-mumbai.infura.io";
break;
case "optimism":
host = "optimism-mainnet.infura.io";
break;
case "optimism-goerli":
host = "optimism-goerli.infura.io";
break;
case "arbitrum":
host = "arbitrum-mainnet.infura.io";
break;
case "arbitrum-goerli":
host = "arbitrum-goerli.infura.io";
break;
default:
infura_provider_logger.throwError("unsupported network", lib_esm_Logger.errors.INVALID_ARGUMENT, {
argument: "network",
value: network
});
}
const connection = {
allowGzip: true,
url: ("https:/" + "/" + host + "/v3/" + apiKey.projectId),
throttleCallback: (attempt, url) => {
if (apiKey.projectId === defaultProjectId) {
showThrottleMessage();
}
return Promise.resolve(true);
}
};
if (apiKey.projectSecret != null) {
connection.user = "";
connection.password = apiKey.projectSecret;
}
return connection;
}
isCommunityResource() {
return (this.projectId === defaultProjectId);
}
}
//# sourceMappingURL=infura-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/json-rpc-batch-provider.js
// Experimental
class json_rpc_batch_provider_JsonRpcBatchProvider extends json_rpc_provider_JsonRpcProvider {
send(method, params) {
const request = {
method: method,
params: params,
id: (this._nextId++),
jsonrpc: "2.0"
};
if (this._pendingBatch == null) {
this._pendingBatch = [];
}
const inflightRequest = { request, resolve: null, reject: null };
const promise = new Promise((resolve, reject) => {
inflightRequest.resolve = resolve;
inflightRequest.reject = reject;
});
this._pendingBatch.push(inflightRequest);
if (!this._pendingBatchAggregator) {
// Schedule batch for next event loop + short duration
this._pendingBatchAggregator = setTimeout(() => {
// Get teh current batch and clear it, so new requests
// go into the next batch
const batch = this._pendingBatch;
this._pendingBatch = null;
this._pendingBatchAggregator = null;
// Get the request as an array of requests
const request = batch.map((inflight) => inflight.request);
this.emit("debug", {
action: "requestBatch",
request: deepCopy(request),
provider: this
});
return fetchJson(this.connection, JSON.stringify(request)).then((result) => {
this.emit("debug", {
action: "response",
request: request,
response: result,
provider: this
});
// For each result, feed it to the correct Promise, depending
// on whether it was a success or error
batch.forEach((inflightRequest, index) => {
const payload = result[index];
if (payload.error) {
const error = new Error(payload.error.message);
error.code = payload.error.code;
error.data = payload.error.data;
inflightRequest.reject(error);
}
else {
inflightRequest.resolve(payload.result);
}
});
}, (error) => {
this.emit("debug", {
action: "response",
error: error,
request: request,
provider: this
});
batch.forEach((inflightRequest) => {
inflightRequest.reject(error);
});
});
}, 10);
}
return promise;
}
}
//# sourceMappingURL=json-rpc-batch-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/nodesmith-provider.js
/* istanbul ignore file */
const nodesmith_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
// Special API key provided by Nodesmith for ethers.js
const nodesmith_provider_defaultApiKey = "ETHERS_JS_SHARED";
class nodesmith_provider_NodesmithProvider extends url_json_rpc_provider_UrlJsonRpcProvider {
static getApiKey(apiKey) {
if (apiKey && typeof (apiKey) !== "string") {
nodesmith_provider_logger.throwArgumentError("invalid apiKey", "apiKey", apiKey);
}
return apiKey || nodesmith_provider_defaultApiKey;
}
static getUrl(network, apiKey) {
nodesmith_provider_logger.warn("NodeSmith will be discontinued on 2019-12-20; please migrate to another platform.");
let host = null;
switch (network.name) {
case "homestead":
host = "https://ethereum.api.nodesmith.io/v1/mainnet/jsonrpc";
break;
case "ropsten":
host = "https://ethereum.api.nodesmith.io/v1/ropsten/jsonrpc";
break;
case "rinkeby":
host = "https://ethereum.api.nodesmith.io/v1/rinkeby/jsonrpc";
break;
case "goerli":
host = "https://ethereum.api.nodesmith.io/v1/goerli/jsonrpc";
break;
case "kovan":
host = "https://ethereum.api.nodesmith.io/v1/kovan/jsonrpc";
break;
default:
nodesmith_provider_logger.throwArgumentError("unsupported network", "network", arguments[0]);
}
return (host + "?apiKey=" + apiKey);
}
}
//# sourceMappingURL=nodesmith-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/pocket-provider.js
const pocket_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
const defaultApplicationId = "62e1ad51b37b8e00394bda3b";
class pocket_provider_PocketProvider extends url_json_rpc_provider_UrlJsonRpcProvider {
static getApiKey(apiKey) {
const apiKeyObj = {
applicationId: null,
loadBalancer: true,
applicationSecretKey: null
};
// Parse applicationId and applicationSecretKey
if (apiKey == null) {
apiKeyObj.applicationId = defaultApplicationId;
}
else if (typeof (apiKey) === "string") {
apiKeyObj.applicationId = apiKey;
}
else if (apiKey.applicationSecretKey != null) {
apiKeyObj.applicationId = apiKey.applicationId;
apiKeyObj.applicationSecretKey = apiKey.applicationSecretKey;
}
else if (apiKey.applicationId) {
apiKeyObj.applicationId = apiKey.applicationId;
}
else {
pocket_provider_logger.throwArgumentError("unsupported PocketProvider apiKey", "apiKey", apiKey);
}
return apiKeyObj;
}
static getUrl(network, apiKey) {
let host = null;
switch (network ? network.name : "unknown") {
case "goerli":
host = "eth-goerli.gateway.pokt.network";
break;
case "homestead":
host = "eth-mainnet.gateway.pokt.network";
break;
case "kovan":
host = "poa-kovan.gateway.pokt.network";
break;
case "matic":
host = "poly-mainnet.gateway.pokt.network";
break;
case "maticmum":
host = "polygon-mumbai-rpc.gateway.pokt.network";
break;
case "rinkeby":
host = "eth-rinkeby.gateway.pokt.network";
break;
case "ropsten":
host = "eth-ropsten.gateway.pokt.network";
break;
default:
pocket_provider_logger.throwError("unsupported network", lib_esm_Logger.errors.INVALID_ARGUMENT, {
argument: "network",
value: network
});
}
const url = `https:/\/${host}/v1/lb/${apiKey.applicationId}`;
const connection = { headers: {}, url };
if (apiKey.applicationSecretKey != null) {
connection.user = "";
connection.password = apiKey.applicationSecretKey;
}
return connection;
}
isCommunityResource() {
return (this.applicationId === defaultApplicationId);
}
}
//# sourceMappingURL=pocket-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/web3-provider.js
const web3_provider_logger = new lib_esm_Logger(providers_lib_esm_version_version);
let _nextId = 1;
function buildWeb3LegacyFetcher(provider, sendFunc) {
const fetcher = "Web3LegacyFetcher";
return function (method, params) {
const request = {
method: method,
params: params,
id: (_nextId++),
jsonrpc: "2.0"
};
return new Promise((resolve, reject) => {
this.emit("debug", {
action: "request",
fetcher,
request: deepCopy(request),
provider: this
});
sendFunc(request, (error, response) => {
if (error) {
this.emit("debug", {
action: "response",
fetcher,
error,
request,
provider: this
});
return reject(error);
}
this.emit("debug", {
action: "response",
fetcher,
request,
response,
provider: this
});
if (response.error) {
const error = new Error(response.error.message);
error.code = response.error.code;
error.data = response.error.data;
return reject(error);
}
resolve(response.result);
});
});
};
}
function buildEip1193Fetcher(provider) {
return function (method, params) {
if (params == null) {
params = [];
}
const request = { method, params };
this.emit("debug", {
action: "request",
fetcher: "Eip1193Fetcher",
request: deepCopy(request),
provider: this
});
return provider.request(request).then((response) => {
this.emit("debug", {
action: "response",
fetcher: "Eip1193Fetcher",
request,
response,
provider: this
});
return response;
}, (error) => {
this.emit("debug", {
action: "response",
fetcher: "Eip1193Fetcher",
request,
error,
provider: this
});
throw error;
});
};
}
class web3_provider_Web3Provider extends json_rpc_provider_JsonRpcProvider {
constructor(provider, network) {
if (provider == null) {
web3_provider_logger.throwArgumentError("missing provider", "provider", provider);
}
let path = null;
let jsonRpcFetchFunc = null;
let subprovider = null;
if (typeof (provider) === "function") {
path = "unknown:";
jsonRpcFetchFunc = provider;
}
else {
path = provider.host || provider.path || "";
if (!path && provider.isMetaMask) {
path = "metamask";
}
subprovider = provider;
if (provider.request) {
if (path === "") {
path = "eip-1193:";
}
jsonRpcFetchFunc = buildEip1193Fetcher(provider);
}
else if (provider.sendAsync) {
jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.sendAsync.bind(provider));
}
else if (provider.send) {
jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.send.bind(provider));
}
else {
web3_provider_logger.throwArgumentError("unsupported provider", "provider", provider);
}
if (!path) {
path = "unknown:";
}
}
super(path, network);
defineReadOnly(this, "jsonRpcFetchFunc", jsonRpcFetchFunc);
defineReadOnly(this, "provider", subprovider);
}
send(method, params) {
return this.jsonRpcFetchFunc(method, params);
}
}
//# sourceMappingURL=web3-provider.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/providers/lib.esm/index.js
const providers_lib_esm_logger = new lib_esm_Logger(providers_lib_esm_version_version);
////////////////////////
// Helper Functions
function getDefaultProvider(network, options) {
if (network == null) {
network = "homestead";
}
// If passed a URL, figure out the right type of provider based on the scheme
if (typeof (network) === "string") {
// @TODO: Add support for IpcProvider; maybe if it ends in ".ipc"?
// Handle http and ws (and their secure variants)
const match = network.match(/^(ws|http)s?:/i);
if (match) {
switch (match[1].toLowerCase()) {
case "http":
case "https":
return new json_rpc_provider_JsonRpcProvider(network);
case "ws":
case "wss":
return new websocket_provider_WebSocketProvider(network);
default:
providers_lib_esm_logger.throwArgumentError("unsupported URL scheme", "network", network);
}
}
}
const n = lib_esm_getNetwork(network);
if (!n || !n._defaultProvider) {
providers_lib_esm_logger.throwError("unsupported getDefaultProvider network", lib_esm_Logger.errors.NETWORK_ERROR, {
operation: "getDefaultProvider",
network: network
});
}
return n._defaultProvider({
FallbackProvider: fallback_provider_FallbackProvider,
AlchemyProvider: alchemy_provider_AlchemyProvider,
AnkrProvider: ankr_provider_AnkrProvider,
CloudflareProvider: cloudflare_provider_CloudflareProvider,
EtherscanProvider: etherscan_provider_EtherscanProvider,
InfuraProvider: infura_provider_InfuraProvider,
JsonRpcProvider: json_rpc_provider_JsonRpcProvider,
NodesmithProvider: nodesmith_provider_NodesmithProvider,
PocketProvider: pocket_provider_PocketProvider,
Web3Provider: web3_provider_Web3Provider,
IpcProvider: IpcProvider,
}, options);
}
////////////////////////
// Exports
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/_version.js
const abi_lib_esm_version_version = "abi/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/abstract-coder.js
const abstract_coder_logger = new lib_esm_Logger(abi_lib_esm_version_version);
function checkResultErrors(result) {
// Find the first error (if any)
const errors = [];
const checkErrors = function (path, object) {
if (!Array.isArray(object)) {
return;
}
for (let key in object) {
const childPath = path.slice();
childPath.push(key);
try {
checkErrors(childPath, object[key]);
}
catch (error) {
errors.push({ path: childPath, error: error });
}
}
};
checkErrors([], result);
return errors;
}
class Coder {
constructor(name, type, localName, dynamic) {
// @TODO: defineReadOnly these
this.name = name;
this.type = type;
this.localName = localName;
this.dynamic = dynamic;
}
_throwError(message, value) {
abstract_coder_logger.throwArgumentError(message, this.localName, value);
}
}
class abstract_coder_Writer {
constructor(wordSize) {
defineReadOnly(this, "wordSize", wordSize || 32);
this._data = [];
this._dataLength = 0;
this._padding = new Uint8Array(wordSize);
}
get data() {
return hexConcat(this._data);
}
get length() { return this._dataLength; }
_writeData(data) {
this._data.push(data);
this._dataLength += data.length;
return data.length;
}
appendWriter(writer) {
return this._writeData(concat(writer._data));
}
// Arrayish items; padded on the right to wordSize
writeBytes(value) {
let bytes = arrayify(value);
const paddingOffset = bytes.length % this.wordSize;
if (paddingOffset) {
bytes = concat([bytes, this._padding.slice(paddingOffset)]);
}
return this._writeData(bytes);
}
_getValue(value) {
let bytes = arrayify(bignumber_BigNumber.from(value));
if (bytes.length > this.wordSize) {
abstract_coder_logger.throwError("value out-of-bounds", lib_esm_Logger.errors.BUFFER_OVERRUN, {
length: this.wordSize,
offset: bytes.length
});
}
if (bytes.length % this.wordSize) {
bytes = concat([this._padding.slice(bytes.length % this.wordSize), bytes]);
}
return bytes;
}
// BigNumberish items; padded on the left to wordSize
writeValue(value) {
return this._writeData(this._getValue(value));
}
writeUpdatableValue() {
const offset = this._data.length;
this._data.push(this._padding);
this._dataLength += this.wordSize;
return (value) => {
this._data[offset] = this._getValue(value);
};
}
}
class abstract_coder_Reader {
constructor(data, wordSize, coerceFunc, allowLoose) {
defineReadOnly(this, "_data", arrayify(data));
defineReadOnly(this, "wordSize", wordSize || 32);
defineReadOnly(this, "_coerceFunc", coerceFunc);
defineReadOnly(this, "allowLoose", allowLoose);
this._offset = 0;
}
get data() { return hexlify(this._data); }
get consumed() { return this._offset; }
// The default Coerce function
static coerce(name, value) {
let match = name.match("^u?int([0-9]+)$");
if (match && parseInt(match[1]) <= 48) {
value = value.toNumber();
}
return value;
}
coerce(name, value) {
if (this._coerceFunc) {
return this._coerceFunc(name, value);
}
return abstract_coder_Reader.coerce(name, value);
}
_peekBytes(offset, length, loose) {
let alignedLength = Math.ceil(length / this.wordSize) * this.wordSize;
if (this._offset + alignedLength > this._data.length) {
if (this.allowLoose && loose && this._offset + length <= this._data.length) {
alignedLength = length;
}
else {
abstract_coder_logger.throwError("data out-of-bounds", lib_esm_Logger.errors.BUFFER_OVERRUN, {
length: this._data.length,
offset: this._offset + alignedLength
});
}
}
return this._data.slice(this._offset, this._offset + alignedLength);
}
subReader(offset) {
return new abstract_coder_Reader(this._data.slice(this._offset + offset), this.wordSize, this._coerceFunc, this.allowLoose);
}
readBytes(length, loose) {
let bytes = this._peekBytes(0, length, !!loose);
this._offset += bytes.length;
// @TODO: Make sure the length..end bytes are all 0?
return bytes.slice(0, length);
}
readValue() {
return bignumber_BigNumber.from(this.readBytes(this.wordSize));
}
}
//# sourceMappingURL=abstract-coder.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/address.js
class address_AddressCoder extends Coder {
constructor(localName) {
super("address", "address", localName, false);
}
defaultValue() {
return "0x0000000000000000000000000000000000000000";
}
encode(writer, value) {
try {
value = getAddress(value);
}
catch (error) {
this._throwError(error.message, value);
}
return writer.writeValue(value);
}
decode(reader) {
return getAddress(hexZeroPad(reader.readValue().toHexString(), 20));
}
}
//# sourceMappingURL=address.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/anonymous.js
// Clones the functionality of an existing Coder, but without a localName
class anonymous_AnonymousCoder extends Coder {
constructor(coder) {
super(coder.name, coder.type, undefined, coder.dynamic);
this.coder = coder;
}
defaultValue() {
return this.coder.defaultValue();
}
encode(writer, value) {
return this.coder.encode(writer, value);
}
decode(reader) {
return this.coder.decode(reader);
}
}
//# sourceMappingURL=anonymous.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/array.js
const array_logger = new lib_esm_Logger(abi_lib_esm_version_version);
function pack(writer, coders, values) {
let arrayValues = null;
if (Array.isArray(values)) {
arrayValues = values;
}
else if (values && typeof (values) === "object") {
let unique = {};
arrayValues = coders.map((coder) => {
const name = coder.localName;
if (!name) {
array_logger.throwError("cannot encode object for signature with missing names", lib_esm_Logger.errors.INVALID_ARGUMENT, {
argument: "values",
coder: coder,
value: values
});
}
if (unique[name]) {
array_logger.throwError("cannot encode object for signature with duplicate names", lib_esm_Logger.errors.INVALID_ARGUMENT, {
argument: "values",
coder: coder,
value: values
});
}
unique[name] = true;
return values[name];
});
}
else {
array_logger.throwArgumentError("invalid tuple value", "tuple", values);
}
if (coders.length !== arrayValues.length) {
array_logger.throwArgumentError("types/value length mismatch", "tuple", values);
}
let staticWriter = new abstract_coder_Writer(writer.wordSize);
let dynamicWriter = new abstract_coder_Writer(writer.wordSize);
let updateFuncs = [];
coders.forEach((coder, index) => {
let value = arrayValues[index];
if (coder.dynamic) {
// Get current dynamic offset (for the future pointer)
let dynamicOffset = dynamicWriter.length;
// Encode the dynamic value into the dynamicWriter
coder.encode(dynamicWriter, value);
// Prepare to populate the correct offset once we are done
let updateFunc = staticWriter.writeUpdatableValue();
updateFuncs.push((baseOffset) => {
updateFunc(baseOffset + dynamicOffset);
});
}
else {
coder.encode(staticWriter, value);
}
});
// Backfill all the dynamic offsets, now that we know the static length
updateFuncs.forEach((func) => { func(staticWriter.length); });
let length = writer.appendWriter(staticWriter);
length += writer.appendWriter(dynamicWriter);
return length;
}
function unpack(reader, coders) {
let values = [];
// A reader anchored to this base
let baseReader = reader.subReader(0);
coders.forEach((coder) => {
let value = null;
if (coder.dynamic) {
let offset = reader.readValue();
let offsetReader = baseReader.subReader(offset.toNumber());
try {
value = coder.decode(offsetReader);
}
catch (error) {
// Cannot recover from this
if (error.code === lib_esm_Logger.errors.BUFFER_OVERRUN) {
throw error;
}
value = error;
value.baseType = coder.name;
value.name = coder.localName;
value.type = coder.type;
}
}
else {
try {
value = coder.decode(reader);
}
catch (error) {
// Cannot recover from this
if (error.code === lib_esm_Logger.errors.BUFFER_OVERRUN) {
throw error;
}
value = error;
value.baseType = coder.name;
value.name = coder.localName;
value.type = coder.type;
}
}
if (value != undefined) {
values.push(value);
}
});
// We only output named properties for uniquely named coders
const uniqueNames = coders.reduce((accum, coder) => {
const name = coder.localName;
if (name) {
if (!accum[name]) {
accum[name] = 0;
}
accum[name]++;
}
return accum;
}, {});
// Add any named parameters (i.e. tuples)
coders.forEach((coder, index) => {
let name = coder.localName;
if (!name || uniqueNames[name] !== 1) {
return;
}
if (name === "length") {
name = "_length";
}
if (values[name] != null) {
return;
}
const value = values[index];
if (value instanceof Error) {
Object.defineProperty(values, name, {
enumerable: true,
get: () => { throw value; }
});
}
else {
values[name] = value;
}
});
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (value instanceof Error) {
Object.defineProperty(values, i, {
enumerable: true,
get: () => { throw value; }
});
}
}
return Object.freeze(values);
}
class array_ArrayCoder extends Coder {
constructor(coder, length, localName) {
const type = (coder.type + "[" + (length >= 0 ? length : "") + "]");
const dynamic = (length === -1 || coder.dynamic);
super("array", type, localName, dynamic);
this.coder = coder;
this.length = length;
}
defaultValue() {
// Verifies the child coder is valid (even if the array is dynamic or 0-length)
const defaultChild = this.coder.defaultValue();
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(defaultChild);
}
return result;
}
encode(writer, value) {
if (!Array.isArray(value)) {
this._throwError("expected array value", value);
}
let count = this.length;
if (count === -1) {
count = value.length;
writer.writeValue(value.length);
}
array_logger.checkArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : ""));
let coders = [];
for (let i = 0; i < value.length; i++) {
coders.push(this.coder);
}
return pack(writer, coders, value);
}
decode(reader) {
let count = this.length;
if (count === -1) {
count = reader.readValue().toNumber();
// Check that there is *roughly* enough data to ensure
// stray random data is not being read as a length. Each
// slot requires at least 32 bytes for their value (or 32
// bytes as a link to the data). This could use a much
// tighter bound, but we are erroring on the side of safety.
if (count * 32 > reader._data.length) {
array_logger.throwError("insufficient data length", lib_esm_Logger.errors.BUFFER_OVERRUN, {
length: reader._data.length,
count: count
});
}
}
let coders = [];
for (let i = 0; i < count; i++) {
coders.push(new anonymous_AnonymousCoder(this.coder));
}
return reader.coerce(this.name, unpack(reader, coders));
}
}
//# sourceMappingURL=array.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/boolean.js
class boolean_BooleanCoder extends Coder {
constructor(localName) {
super("bool", "bool", localName, false);
}
defaultValue() {
return false;
}
encode(writer, value) {
return writer.writeValue(value ? 1 : 0);
}
decode(reader) {
return reader.coerce(this.type, !reader.readValue().isZero());
}
}
//# sourceMappingURL=boolean.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/bytes.js
class bytes_DynamicBytesCoder extends Coder {
constructor(type, localName) {
super(type, type, localName, true);
}
defaultValue() {
return "0x";
}
encode(writer, value) {
value = arrayify(value);
let length = writer.writeValue(value.length);
length += writer.writeBytes(value);
return length;
}
decode(reader) {
return reader.readBytes(reader.readValue().toNumber(), true);
}
}
class bytes_BytesCoder extends bytes_DynamicBytesCoder {
constructor(localName) {
super("bytes", localName);
}
decode(reader) {
return reader.coerce(this.name, hexlify(super.decode(reader)));
}
}
//# sourceMappingURL=bytes.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/fixed-bytes.js
// @TODO: Merge this with bytes
class fixed_bytes_FixedBytesCoder extends Coder {
constructor(size, localName) {
let name = "bytes" + String(size);
super(name, name, localName, false);
this.size = size;
}
defaultValue() {
return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2);
}
encode(writer, value) {
let data = arrayify(value);
if (data.length !== this.size) {
this._throwError("incorrect data length", value);
}
return writer.writeBytes(data);
}
decode(reader) {
return reader.coerce(this.name, hexlify(reader.readBytes(this.size)));
}
}
//# sourceMappingURL=fixed-bytes.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/null.js
class null_NullCoder extends Coder {
constructor(localName) {
super("null", "", localName, false);
}
defaultValue() {
return null;
}
encode(writer, value) {
if (value != null) {
this._throwError("not null", value);
}
return writer.writeBytes([]);
}
decode(reader) {
reader.readBytes(0);
return reader.coerce(this.name, null);
}
}
//# sourceMappingURL=null.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/number.js
class number_NumberCoder extends Coder {
constructor(size, signed, localName) {
const name = ((signed ? "int" : "uint") + (size * 8));
super(name, name, localName, false);
this.size = size;
this.signed = signed;
}
defaultValue() {
return 0;
}
encode(writer, value) {
let v = bignumber_BigNumber.from(value);
// Check bounds are safe for encoding
let maxUintValue = MaxUint256.mask(writer.wordSize * 8);
if (this.signed) {
let bounds = maxUintValue.mask(this.size * 8 - 1);
if (v.gt(bounds) || v.lt(bounds.add(One).mul(NegativeOne))) {
this._throwError("value out-of-bounds", value);
}
}
else if (v.lt(Zero) || v.gt(maxUintValue.mask(this.size * 8))) {
this._throwError("value out-of-bounds", value);
}
v = v.toTwos(this.size * 8).mask(this.size * 8);
if (this.signed) {
v = v.fromTwos(this.size * 8).toTwos(8 * writer.wordSize);
}
return writer.writeValue(v);
}
decode(reader) {
let value = reader.readValue().mask(this.size * 8);
if (this.signed) {
value = value.fromTwos(this.size * 8);
}
return reader.coerce(this.name, value);
}
}
//# sourceMappingURL=number.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/string.js
class string_StringCoder extends bytes_DynamicBytesCoder {
constructor(localName) {
super("string", localName);
}
defaultValue() {
return "";
}
encode(writer, value) {
return super.encode(writer, toUtf8Bytes(value));
}
decode(reader) {
return toUtf8String(super.decode(reader));
}
}
//# sourceMappingURL=string.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/coders/tuple.js
class tuple_TupleCoder extends Coder {
constructor(coders, localName) {
let dynamic = false;
const types = [];
coders.forEach((coder) => {
if (coder.dynamic) {
dynamic = true;
}
types.push(coder.type);
});
const type = ("tuple(" + types.join(",") + ")");
super("tuple", type, localName, dynamic);
this.coders = coders;
}
defaultValue() {
const values = [];
this.coders.forEach((coder) => {
values.push(coder.defaultValue());
});
// We only output named properties for uniquely named coders
const uniqueNames = this.coders.reduce((accum, coder) => {
const name = coder.localName;
if (name) {
if (!accum[name]) {
accum[name] = 0;
}
accum[name]++;
}
return accum;
}, {});
// Add named values
this.coders.forEach((coder, index) => {
let name = coder.localName;
if (!name || uniqueNames[name] !== 1) {
return;
}
if (name === "length") {
name = "_length";
}
if (values[name] != null) {
return;
}
values[name] = values[index];
});
return Object.freeze(values);
}
encode(writer, value) {
return pack(writer, this.coders, value);
}
decode(reader) {
return reader.coerce(this.name, unpack(reader, this.coders));
}
}
//# sourceMappingURL=tuple.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/fragments.js
const fragments_logger = new lib_esm_Logger(abi_lib_esm_version_version);
;
const fragments_constructorGuard = {};
let ModifiersBytes = { calldata: true, memory: true, storage: true };
let ModifiersNest = { calldata: true, memory: true };
function checkModifier(type, name) {
if (type === "bytes" || type === "string") {
if (ModifiersBytes[name]) {
return true;
}
}
else if (type === "address") {
if (name === "payable") {
return true;
}
}
else if (type.indexOf("[") >= 0 || type === "tuple") {
if (ModifiersNest[name]) {
return true;
}
}
if (ModifiersBytes[name] || name === "payable") {
fragments_logger.throwArgumentError("invalid modifier", "name", name);
}
return false;
}
// @TODO: Make sure that children of an indexed tuple are marked with a null indexed
function parseParamType(param, allowIndexed) {
let originalParam = param;
function throwError(i) {
fragments_logger.throwArgumentError(`unexpected character at position ${i}`, "param", param);
}
param = param.replace(/\s/g, " ");
function newNode(parent) {
let node = { type: "", name: "", parent: parent, state: { allowType: true } };
if (allowIndexed) {
node.indexed = false;
}
return node;
}
let parent = { type: "", name: "", state: { allowType: true } };
let node = parent;
for (let i = 0; i < param.length; i++) {
let c = param[i];
switch (c) {
case "(":
if (node.state.allowType && node.type === "") {
node.type = "tuple";
}
else if (!node.state.allowParams) {
throwError(i);
}
node.state.allowType = false;
node.type = verifyType(node.type);
node.components = [newNode(node)];
node = node.components[0];
break;
case ")":
delete node.state;
if (node.name === "indexed") {
if (!allowIndexed) {
throwError(i);
}
node.indexed = true;
node.name = "";
}
if (checkModifier(node.type, node.name)) {
node.name = "";
}
node.type = verifyType(node.type);
let child = node;
node = node.parent;
if (!node) {
throwError(i);
}
delete child.parent;
node.state.allowParams = false;
node.state.allowName = true;
node.state.allowArray = true;
break;
case ",":
delete node.state;
if (node.name === "indexed") {
if (!allowIndexed) {
throwError(i);
}
node.indexed = true;
node.name = "";
}
if (checkModifier(node.type, node.name)) {
node.name = "";
}
node.type = verifyType(node.type);
let sibling = newNode(node.parent);
//{ type: "", name: "", parent: node.parent, state: { allowType: true } };
node.parent.components.push(sibling);
delete node.parent;
node = sibling;
break;
// Hit a space...
case " ":
// If reading type, the type is done and may read a param or name
if (node.state.allowType) {
if (node.type !== "") {
node.type = verifyType(node.type);
delete node.state.allowType;
node.state.allowName = true;
node.state.allowParams = true;
}
}
// If reading name, the name is done
if (node.state.allowName) {
if (node.name !== "") {
if (node.name === "indexed") {
if (!allowIndexed) {
throwError(i);
}
if (node.indexed) {
throwError(i);
}
node.indexed = true;
node.name = "";
}
else if (checkModifier(node.type, node.name)) {
node.name = "";
}
else {
node.state.allowName = false;
}
}
}
break;
case "[":
if (!node.state.allowArray) {
throwError(i);
}
node.type += c;
node.state.allowArray = false;
node.state.allowName = false;
node.state.readArray = true;
break;
case "]":
if (!node.state.readArray) {
throwError(i);
}
node.type += c;
node.state.readArray = false;
node.state.allowArray = true;
node.state.allowName = true;
break;
default:
if (node.state.allowType) {
node.type += c;
node.state.allowParams = true;
node.state.allowArray = true;
}
else if (node.state.allowName) {
node.name += c;
delete node.state.allowArray;
}
else if (node.state.readArray) {
node.type += c;
}
else {
throwError(i);
}
}
}
if (node.parent) {
fragments_logger.throwArgumentError("unexpected eof", "param", param);
}
delete parent.state;
if (node.name === "indexed") {
if (!allowIndexed) {
throwError(originalParam.length - 7);
}
if (node.indexed) {
throwError(originalParam.length - 7);
}
node.indexed = true;
node.name = "";
}
else if (checkModifier(node.type, node.name)) {
node.name = "";
}
parent.type = verifyType(parent.type);
return parent;
}
function populate(object, params) {
for (let key in params) {
defineReadOnly(object, key, params[key]);
}
}
const FormatTypes = Object.freeze({
// Bare formatting, as is needed for computing a sighash of an event or function
sighash: "sighash",
// Human-Readable with Minimal spacing and without names (compact human-readable)
minimal: "minimal",
// Human-Readable with nice spacing, including all names
full: "full",
// JSON-format a la Solidity
json: "json"
});
const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/);
class fragments_ParamType {
constructor(constructorGuard, params) {
if (constructorGuard !== fragments_constructorGuard) {
fragments_logger.throwError("use fromString", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new ParamType()"
});
}
populate(this, params);
let match = this.type.match(paramTypeArray);
if (match) {
populate(this, {
arrayLength: parseInt(match[2] || "-1"),
arrayChildren: fragments_ParamType.fromObject({
type: match[1],
components: this.components
}),
baseType: "array"
});
}
else {
populate(this, {
arrayLength: null,
arrayChildren: null,
baseType: ((this.components != null) ? "tuple" : this.type)
});
}
this._isParamType = true;
Object.freeze(this);
}
// Format the parameter fragment
// - sighash: "(uint256,address)"
// - minimal: "tuple(uint256,address) indexed"
// - full: "tuple(uint256 foo, address bar) indexed baz"
format(format) {
if (!format) {
format = FormatTypes.sighash;
}
if (!FormatTypes[format]) {
fragments_logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
let result = {
type: ((this.baseType === "tuple") ? "tuple" : this.type),
name: (this.name || undefined)
};
if (typeof (this.indexed) === "boolean") {
result.indexed = this.indexed;
}
if (this.components) {
result.components = this.components.map((comp) => JSON.parse(comp.format(format)));
}
return JSON.stringify(result);
}
let result = "";
// Array
if (this.baseType === "array") {
result += this.arrayChildren.format(format);
result += "[" + (this.arrayLength < 0 ? "" : String(this.arrayLength)) + "]";
}
else {
if (this.baseType === "tuple") {
if (format !== FormatTypes.sighash) {
result += this.type;
}
result += "(" + this.components.map((comp) => comp.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ")";
}
else {
result += this.type;
}
}
if (format !== FormatTypes.sighash) {
if (this.indexed === true) {
result += " indexed";
}
if (format === FormatTypes.full && this.name) {
result += " " + this.name;
}
}
return result;
}
static from(value, allowIndexed) {
if (typeof (value) === "string") {
return fragments_ParamType.fromString(value, allowIndexed);
}
return fragments_ParamType.fromObject(value);
}
static fromObject(value) {
if (fragments_ParamType.isParamType(value)) {
return value;
}
return new fragments_ParamType(fragments_constructorGuard, {
name: (value.name || null),
type: verifyType(value.type),
indexed: ((value.indexed == null) ? null : !!value.indexed),
components: (value.components ? value.components.map(fragments_ParamType.fromObject) : null)
});
}
static fromString(value, allowIndexed) {
function ParamTypify(node) {
return fragments_ParamType.fromObject({
name: node.name,
type: node.type,
indexed: node.indexed,
components: node.components
});
}
return ParamTypify(parseParamType(value, !!allowIndexed));
}
static isParamType(value) {
return !!(value != null && value._isParamType);
}
}
;
function parseParams(value, allowIndex) {
return splitNesting(value).map((param) => fragments_ParamType.fromString(param, allowIndex));
}
class fragments_Fragment {
constructor(constructorGuard, params) {
if (constructorGuard !== fragments_constructorGuard) {
fragments_logger.throwError("use a static from method", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new Fragment()"
});
}
populate(this, params);
this._isFragment = true;
Object.freeze(this);
}
static from(value) {
if (fragments_Fragment.isFragment(value)) {
return value;
}
if (typeof (value) === "string") {
return fragments_Fragment.fromString(value);
}
return fragments_Fragment.fromObject(value);
}
static fromObject(value) {
if (fragments_Fragment.isFragment(value)) {
return value;
}
switch (value.type) {
case "function":
return fragments_FunctionFragment.fromObject(value);
case "event":
return EventFragment.fromObject(value);
case "constructor":
return fragments_ConstructorFragment.fromObject(value);
case "error":
return ErrorFragment.fromObject(value);
case "fallback":
case "receive":
// @TODO: Something? Maybe return a FunctionFragment? A custom DefaultFunctionFragment?
return null;
}
return fragments_logger.throwArgumentError("invalid fragment object", "value", value);
}
static fromString(value) {
// Make sure the "returns" is surrounded by a space and all whitespace is exactly one space
value = value.replace(/\s/g, " ");
value = value.replace(/\(/g, " (").replace(/\)/g, ") ").replace(/\s+/g, " ");
value = value.trim();
if (value.split(" ")[0] === "event") {
return EventFragment.fromString(value.substring(5).trim());
}
else if (value.split(" ")[0] === "function") {
return fragments_FunctionFragment.fromString(value.substring(8).trim());
}
else if (value.split("(")[0].trim() === "constructor") {
return fragments_ConstructorFragment.fromString(value.trim());
}
else if (value.split(" ")[0] === "error") {
return ErrorFragment.fromString(value.substring(5).trim());
}
return fragments_logger.throwArgumentError("unsupported fragment", "value", value);
}
static isFragment(value) {
return !!(value && value._isFragment);
}
}
class EventFragment extends fragments_Fragment {
format(format) {
if (!format) {
format = FormatTypes.sighash;
}
if (!FormatTypes[format]) {
fragments_logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
return JSON.stringify({
type: "event",
anonymous: this.anonymous,
name: this.name,
inputs: this.inputs.map((input) => JSON.parse(input.format(format)))
});
}
let result = "";
if (format !== FormatTypes.sighash) {
result += "event ";
}
result += this.name + "(" + this.inputs.map((input) => input.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ") ";
if (format !== FormatTypes.sighash) {
if (this.anonymous) {
result += "anonymous ";
}
}
return result.trim();
}
static from(value) {
if (typeof (value) === "string") {
return EventFragment.fromString(value);
}
return EventFragment.fromObject(value);
}
static fromObject(value) {
if (EventFragment.isEventFragment(value)) {
return value;
}
if (value.type !== "event") {
fragments_logger.throwArgumentError("invalid event object", "value", value);
}
const params = {
name: verifyIdentifier(value.name),
anonymous: value.anonymous,
inputs: (value.inputs ? value.inputs.map(fragments_ParamType.fromObject) : []),
type: "event"
};
return new EventFragment(fragments_constructorGuard, params);
}
static fromString(value) {
let match = value.match(regexParen);
if (!match) {
fragments_logger.throwArgumentError("invalid event string", "value", value);
}
let anonymous = false;
match[3].split(" ").forEach((modifier) => {
switch (modifier.trim()) {
case "anonymous":
anonymous = true;
break;
case "":
break;
default:
fragments_logger.warn("unknown modifier: " + modifier);
}
});
return EventFragment.fromObject({
name: match[1].trim(),
anonymous: anonymous,
inputs: parseParams(match[2], true),
type: "event"
});
}
static isEventFragment(value) {
return (value && value._isFragment && value.type === "event");
}
}
function parseGas(value, params) {
params.gas = null;
let comps = value.split("@");
if (comps.length !== 1) {
if (comps.length > 2) {
fragments_logger.throwArgumentError("invalid human-readable ABI signature", "value", value);
}
if (!comps[1].match(/^[0-9]+$/)) {
fragments_logger.throwArgumentError("invalid human-readable ABI signature gas", "value", value);
}
params.gas = bignumber_BigNumber.from(comps[1]);
return comps[0];
}
return value;
}
function parseModifiers(value, params) {
params.constant = false;
params.payable = false;
params.stateMutability = "nonpayable";
value.split(" ").forEach((modifier) => {
switch (modifier.trim()) {
case "constant":
params.constant = true;
break;
case "payable":
params.payable = true;
params.stateMutability = "payable";
break;
case "nonpayable":
params.payable = false;
params.stateMutability = "nonpayable";
break;
case "pure":
params.constant = true;
params.stateMutability = "pure";
break;
case "view":
params.constant = true;
params.stateMutability = "view";
break;
case "external":
case "public":
case "":
break;
default:
console.log("unknown modifier: " + modifier);
}
});
}
function verifyState(value) {
let result = {
constant: false,
payable: true,
stateMutability: "payable"
};
if (value.stateMutability != null) {
result.stateMutability = value.stateMutability;
// Set (and check things are consistent) the constant property
result.constant = (result.stateMutability === "view" || result.stateMutability === "pure");
if (value.constant != null) {
if ((!!value.constant) !== result.constant) {
fragments_logger.throwArgumentError("cannot have constant function with mutability " + result.stateMutability, "value", value);
}
}
// Set (and check things are consistent) the payable property
result.payable = (result.stateMutability === "payable");
if (value.payable != null) {
if ((!!value.payable) !== result.payable) {
fragments_logger.throwArgumentError("cannot have payable function with mutability " + result.stateMutability, "value", value);
}
}
}
else if (value.payable != null) {
result.payable = !!value.payable;
// If payable we can assume non-constant; otherwise we can't assume
if (value.constant == null && !result.payable && value.type !== "constructor") {
fragments_logger.throwArgumentError("unable to determine stateMutability", "value", value);
}
result.constant = !!value.constant;
if (result.constant) {
result.stateMutability = "view";
}
else {
result.stateMutability = (result.payable ? "payable" : "nonpayable");
}
if (result.payable && result.constant) {
fragments_logger.throwArgumentError("cannot have constant payable function", "value", value);
}
}
else if (value.constant != null) {
result.constant = !!value.constant;
result.payable = !result.constant;
result.stateMutability = (result.constant ? "view" : "payable");
}
else if (value.type !== "constructor") {
fragments_logger.throwArgumentError("unable to determine stateMutability", "value", value);
}
return result;
}
class fragments_ConstructorFragment extends fragments_Fragment {
format(format) {
if (!format) {
format = FormatTypes.sighash;
}
if (!FormatTypes[format]) {
fragments_logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
return JSON.stringify({
type: "constructor",
stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined),
payable: this.payable,
gas: (this.gas ? this.gas.toNumber() : undefined),
inputs: this.inputs.map((input) => JSON.parse(input.format(format)))
});
}
if (format === FormatTypes.sighash) {
fragments_logger.throwError("cannot format a constructor for sighash", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "format(sighash)"
});
}
let result = "constructor(" + this.inputs.map((input) => input.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ") ";
if (this.stateMutability && this.stateMutability !== "nonpayable") {
result += this.stateMutability + " ";
}
return result.trim();
}
static from(value) {
if (typeof (value) === "string") {
return fragments_ConstructorFragment.fromString(value);
}
return fragments_ConstructorFragment.fromObject(value);
}
static fromObject(value) {
if (fragments_ConstructorFragment.isConstructorFragment(value)) {
return value;
}
if (value.type !== "constructor") {
fragments_logger.throwArgumentError("invalid constructor object", "value", value);
}
let state = verifyState(value);
if (state.constant) {
fragments_logger.throwArgumentError("constructor cannot be constant", "value", value);
}
const params = {
name: null,
type: value.type,
inputs: (value.inputs ? value.inputs.map(fragments_ParamType.fromObject) : []),
payable: state.payable,
stateMutability: state.stateMutability,
gas: (value.gas ? bignumber_BigNumber.from(value.gas) : null)
};
return new fragments_ConstructorFragment(fragments_constructorGuard, params);
}
static fromString(value) {
let params = { type: "constructor" };
value = parseGas(value, params);
let parens = value.match(regexParen);
if (!parens || parens[1].trim() !== "constructor") {
fragments_logger.throwArgumentError("invalid constructor string", "value", value);
}
params.inputs = parseParams(parens[2].trim(), false);
parseModifiers(parens[3].trim(), params);
return fragments_ConstructorFragment.fromObject(params);
}
static isConstructorFragment(value) {
return (value && value._isFragment && value.type === "constructor");
}
}
class fragments_FunctionFragment extends fragments_ConstructorFragment {
format(format) {
if (!format) {
format = FormatTypes.sighash;
}
if (!FormatTypes[format]) {
fragments_logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
return JSON.stringify({
type: "function",
name: this.name,
constant: this.constant,
stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined),
payable: this.payable,
gas: (this.gas ? this.gas.toNumber() : undefined),
inputs: this.inputs.map((input) => JSON.parse(input.format(format))),
outputs: this.outputs.map((output) => JSON.parse(output.format(format))),
});
}
let result = "";
if (format !== FormatTypes.sighash) {
result += "function ";
}
result += this.name + "(" + this.inputs.map((input) => input.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ") ";
if (format !== FormatTypes.sighash) {
if (this.stateMutability) {
if (this.stateMutability !== "nonpayable") {
result += (this.stateMutability + " ");
}
}
else if (this.constant) {
result += "view ";
}
if (this.outputs && this.outputs.length) {
result += "returns (" + this.outputs.map((output) => output.format(format)).join(", ") + ") ";
}
if (this.gas != null) {
result += "@" + this.gas.toString() + " ";
}
}
return result.trim();
}
static from(value) {
if (typeof (value) === "string") {
return fragments_FunctionFragment.fromString(value);
}
return fragments_FunctionFragment.fromObject(value);
}
static fromObject(value) {
if (fragments_FunctionFragment.isFunctionFragment(value)) {
return value;
}
if (value.type !== "function") {
fragments_logger.throwArgumentError("invalid function object", "value", value);
}
let state = verifyState(value);
const params = {
type: value.type,
name: verifyIdentifier(value.name),
constant: state.constant,
inputs: (value.inputs ? value.inputs.map(fragments_ParamType.fromObject) : []),
outputs: (value.outputs ? value.outputs.map(fragments_ParamType.fromObject) : []),
payable: state.payable,
stateMutability: state.stateMutability,
gas: (value.gas ? bignumber_BigNumber.from(value.gas) : null)
};
return new fragments_FunctionFragment(fragments_constructorGuard, params);
}
static fromString(value) {
let params = { type: "function" };
value = parseGas(value, params);
let comps = value.split(" returns ");
if (comps.length > 2) {
fragments_logger.throwArgumentError("invalid function string", "value", value);
}
let parens = comps[0].match(regexParen);
if (!parens) {
fragments_logger.throwArgumentError("invalid function signature", "value", value);
}
params.name = parens[1].trim();
if (params.name) {
verifyIdentifier(params.name);
}
params.inputs = parseParams(parens[2], false);
parseModifiers(parens[3].trim(), params);
// We have outputs
if (comps.length > 1) {
let returns = comps[1].match(regexParen);
if (returns[1].trim() != "" || returns[3].trim() != "") {
fragments_logger.throwArgumentError("unexpected tokens", "value", value);
}
params.outputs = parseParams(returns[2], false);
}
else {
params.outputs = [];
}
return fragments_FunctionFragment.fromObject(params);
}
static isFunctionFragment(value) {
return (value && value._isFragment && value.type === "function");
}
}
//export class StructFragment extends Fragment {
//}
function checkForbidden(fragment) {
const sig = fragment.format();
if (sig === "Error(string)" || sig === "Panic(uint256)") {
fragments_logger.throwArgumentError(`cannot specify user defined ${sig} error`, "fragment", fragment);
}
return fragment;
}
class ErrorFragment extends fragments_Fragment {
format(format) {
if (!format) {
format = FormatTypes.sighash;
}
if (!FormatTypes[format]) {
fragments_logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
return JSON.stringify({
type: "error",
name: this.name,
inputs: this.inputs.map((input) => JSON.parse(input.format(format))),
});
}
let result = "";
if (format !== FormatTypes.sighash) {
result += "error ";
}
result += this.name + "(" + this.inputs.map((input) => input.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ") ";
return result.trim();
}
static from(value) {
if (typeof (value) === "string") {
return ErrorFragment.fromString(value);
}
return ErrorFragment.fromObject(value);
}
static fromObject(value) {
if (ErrorFragment.isErrorFragment(value)) {
return value;
}
if (value.type !== "error") {
fragments_logger.throwArgumentError("invalid error object", "value", value);
}
const params = {
type: value.type,
name: verifyIdentifier(value.name),
inputs: (value.inputs ? value.inputs.map(fragments_ParamType.fromObject) : [])
};
return checkForbidden(new ErrorFragment(fragments_constructorGuard, params));
}
static fromString(value) {
let params = { type: "error" };
let parens = value.match(regexParen);
if (!parens) {
fragments_logger.throwArgumentError("invalid error signature", "value", value);
}
params.name = parens[1].trim();
if (params.name) {
verifyIdentifier(params.name);
}
params.inputs = parseParams(parens[2], false);
return checkForbidden(ErrorFragment.fromObject(params));
}
static isErrorFragment(value) {
return (value && value._isFragment && value.type === "error");
}
}
function verifyType(type) {
// These need to be transformed to their full description
if (type.match(/^uint($|[^1-9])/)) {
type = "uint256" + type.substring(4);
}
else if (type.match(/^int($|[^1-9])/)) {
type = "int256" + type.substring(3);
}
// @TODO: more verification
return type;
}
// See: https://github.com/ethereum/solidity/blob/1f8f1a3db93a548d0555e3e14cfc55a10e25b60e/docs/grammar/SolidityLexer.g4#L234
const regexIdentifier = new RegExp("^[a-zA-Z$_][a-zA-Z0-9$_]*$");
function verifyIdentifier(value) {
if (!value || !value.match(regexIdentifier)) {
fragments_logger.throwArgumentError(`invalid identifier "${value}"`, "value", value);
}
return value;
}
const regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$");
function splitNesting(value) {
value = value.trim();
let result = [];
let accum = "";
let depth = 0;
for (let offset = 0; offset < value.length; offset++) {
let c = value[offset];
if (c === "," && depth === 0) {
result.push(accum);
accum = "";
}
else {
accum += c;
if (c === "(") {
depth++;
}
else if (c === ")") {
depth--;
if (depth === -1) {
fragments_logger.throwArgumentError("unbalanced parenthesis", "value", value);
}
}
}
}
if (accum) {
result.push(accum);
}
return result;
}
//# sourceMappingURL=fragments.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/abi-coder.js
// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
const abi_coder_logger = new lib_esm_Logger(abi_lib_esm_version_version);
const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
class abi_coder_AbiCoder {
constructor(coerceFunc) {
defineReadOnly(this, "coerceFunc", coerceFunc || null);
}
_getCoder(param) {
switch (param.baseType) {
case "address":
return new address_AddressCoder(param.name);
case "bool":
return new boolean_BooleanCoder(param.name);
case "string":
return new string_StringCoder(param.name);
case "bytes":
return new bytes_BytesCoder(param.name);
case "array":
return new array_ArrayCoder(this._getCoder(param.arrayChildren), param.arrayLength, param.name);
case "tuple":
return new tuple_TupleCoder((param.components || []).map((component) => {
return this._getCoder(component);
}), param.name);
case "":
return new null_NullCoder(param.name);
}
// u?int[0-9]*
let match = param.type.match(paramTypeNumber);
if (match) {
let size = parseInt(match[2] || "256");
if (size === 0 || size > 256 || (size % 8) !== 0) {
abi_coder_logger.throwArgumentError("invalid " + match[1] + " bit length", "param", param);
}
return new number_NumberCoder(size / 8, (match[1] === "int"), param.name);
}
// bytes[0-9]+
match = param.type.match(paramTypeBytes);
if (match) {
let size = parseInt(match[1]);
if (size === 0 || size > 32) {
abi_coder_logger.throwArgumentError("invalid bytes length", "param", param);
}
return new fixed_bytes_FixedBytesCoder(size, param.name);
}
return abi_coder_logger.throwArgumentError("invalid type", "type", param.type);
}
_getWordSize() { return 32; }
_getReader(data, allowLoose) {
return new abstract_coder_Reader(data, this._getWordSize(), this.coerceFunc, allowLoose);
}
_getWriter() {
return new abstract_coder_Writer(this._getWordSize());
}
getDefaultValue(types) {
const coders = types.map((type) => this._getCoder(fragments_ParamType.from(type)));
const coder = new tuple_TupleCoder(coders, "_");
return coder.defaultValue();
}
encode(types, values) {
if (types.length !== values.length) {
abi_coder_logger.throwError("types/values length mismatch", lib_esm_Logger.errors.INVALID_ARGUMENT, {
count: { types: types.length, values: values.length },
value: { types: types, values: values }
});
}
const coders = types.map((type) => this._getCoder(fragments_ParamType.from(type)));
const coder = (new tuple_TupleCoder(coders, "_"));
const writer = this._getWriter();
coder.encode(writer, values);
return writer.data;
}
decode(types, data, loose) {
const coders = types.map((type) => this._getCoder(fragments_ParamType.from(type)));
const coder = new tuple_TupleCoder(coders, "_");
return coder.decode(this._getReader(arrayify(data), loose));
}
}
const defaultAbiCoder = new abi_coder_AbiCoder();
//# sourceMappingURL=abi-coder.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/abi/lib.esm/interface.js
const interface_logger = new lib_esm_Logger(abi_lib_esm_version_version);
class interface_LogDescription extends Description {
}
class interface_TransactionDescription extends Description {
}
class interface_ErrorDescription extends Description {
}
class interface_Indexed extends Description {
static isIndexed(value) {
return !!(value && value._isIndexed);
}
}
const BuiltinErrors = {
"0x08c379a0": { signature: "Error(string)", name: "Error", inputs: ["string"], reason: true },
"0x4e487b71": { signature: "Panic(uint256)", name: "Panic", inputs: ["uint256"] }
};
function wrapAccessError(property, error) {
const wrap = new Error(`deferred error during ABI decoding triggered accessing ${property}`);
wrap.error = error;
return wrap;
}
/*
function checkNames(fragment: Fragment, type: "input" | "output", params: Array<ParamType>): void {
params.reduce((accum, param) => {
if (param.name) {
if (accum[param.name]) {
logger.throwArgumentError(`duplicate ${ type } parameter ${ JSON.stringify(param.name) } in ${ fragment.format("full") }`, "fragment", fragment);
}
accum[param.name] = true;
}
return accum;
}, <{ [ name: string ]: boolean }>{ });
}
*/
class interface_Interface {
constructor(fragments) {
let abi = [];
if (typeof (fragments) === "string") {
abi = JSON.parse(fragments);
}
else {
abi = fragments;
}
defineReadOnly(this, "fragments", abi.map((fragment) => {
return fragments_Fragment.from(fragment);
}).filter((fragment) => (fragment != null)));
defineReadOnly(this, "_abiCoder", getStatic(new.target, "getAbiCoder")());
defineReadOnly(this, "functions", {});
defineReadOnly(this, "errors", {});
defineReadOnly(this, "events", {});
defineReadOnly(this, "structs", {});
// Add all fragments by their signature
this.fragments.forEach((fragment) => {
let bucket = null;
switch (fragment.type) {
case "constructor":
if (this.deploy) {
interface_logger.warn("duplicate definition - constructor");
return;
}
//checkNames(fragment, "input", fragment.inputs);
defineReadOnly(this, "deploy", fragment);
return;
case "function":
//checkNames(fragment, "input", fragment.inputs);
//checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
bucket = this.functions;
break;
case "event":
//checkNames(fragment, "input", fragment.inputs);
bucket = this.events;
break;
case "error":
bucket = this.errors;
break;
default:
return;
}
let signature = fragment.format();
if (bucket[signature]) {
interface_logger.warn("duplicate definition - " + signature);
return;
}
bucket[signature] = fragment;
});
// If we do not have a constructor add a default
if (!this.deploy) {
defineReadOnly(this, "deploy", fragments_ConstructorFragment.from({
payable: false,
type: "constructor"
}));
}
defineReadOnly(this, "_isInterface", true);
}
format(format) {
if (!format) {
format = FormatTypes.full;
}
if (format === FormatTypes.sighash) {
interface_logger.throwArgumentError("interface does not support formatting sighash", "format", format);
}
const abi = this.fragments.map((fragment) => fragment.format(format));
// We need to re-bundle the JSON fragments a bit
if (format === FormatTypes.json) {
return JSON.stringify(abi.map((j) => JSON.parse(j)));
}
return abi;
}
// Sub-classes can override these to handle other blockchains
static getAbiCoder() {
return defaultAbiCoder;
}
static getAddress(address) {
return getAddress(address);
}
static getSighash(fragment) {
return hexDataSlice(id_id(fragment.format()), 0, 4);
}
static getEventTopic(eventFragment) {
return id_id(eventFragment.format());
}
// Find a function definition by any means necessary (unless it is ambiguous)
getFunction(nameOrSignatureOrSighash) {
if (isHexString(nameOrSignatureOrSighash)) {
for (const name in this.functions) {
if (nameOrSignatureOrSighash === this.getSighash(name)) {
return this.functions[name];
}
}
interface_logger.throwArgumentError("no matching function", "sighash", nameOrSignatureOrSighash);
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrSighash.indexOf("(") === -1) {
const name = nameOrSignatureOrSighash.trim();
const matching = Object.keys(this.functions).filter((f) => (f.split("(" /* fix:) */)[0] === name));
if (matching.length === 0) {
interface_logger.throwArgumentError("no matching function", "name", name);
}
else if (matching.length > 1) {
interface_logger.throwArgumentError("multiple matching functions", "name", name);
}
return this.functions[matching[0]];
}
// Normalize the signature and lookup the function
const result = this.functions[fragments_FunctionFragment.fromString(nameOrSignatureOrSighash).format()];
if (!result) {
interface_logger.throwArgumentError("no matching function", "signature", nameOrSignatureOrSighash);
}
return result;
}
// Find an event definition by any means necessary (unless it is ambiguous)
getEvent(nameOrSignatureOrTopic) {
if (isHexString(nameOrSignatureOrTopic)) {
const topichash = nameOrSignatureOrTopic.toLowerCase();
for (const name in this.events) {
if (topichash === this.getEventTopic(name)) {
return this.events[name];
}
}
interface_logger.throwArgumentError("no matching event", "topichash", topichash);
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrTopic.indexOf("(") === -1) {
const name = nameOrSignatureOrTopic.trim();
const matching = Object.keys(this.events).filter((f) => (f.split("(" /* fix:) */)[0] === name));
if (matching.length === 0) {
interface_logger.throwArgumentError("no matching event", "name", name);
}
else if (matching.length > 1) {
interface_logger.throwArgumentError("multiple matching events", "name", name);
}
return this.events[matching[0]];
}
// Normalize the signature and lookup the function
const result = this.events[EventFragment.fromString(nameOrSignatureOrTopic).format()];
if (!result) {
interface_logger.throwArgumentError("no matching event", "signature", nameOrSignatureOrTopic);
}
return result;
}
// Find a function definition by any means necessary (unless it is ambiguous)
getError(nameOrSignatureOrSighash) {
if (isHexString(nameOrSignatureOrSighash)) {
const getSighash = getStatic(this.constructor, "getSighash");
for (const name in this.errors) {
const error = this.errors[name];
if (nameOrSignatureOrSighash === getSighash(error)) {
return this.errors[name];
}
}
interface_logger.throwArgumentError("no matching error", "sighash", nameOrSignatureOrSighash);
}
// It is a bare name, look up the function (will return null if ambiguous)
if (nameOrSignatureOrSighash.indexOf("(") === -1) {
const name = nameOrSignatureOrSighash.trim();
const matching = Object.keys(this.errors).filter((f) => (f.split("(" /* fix:) */)[0] === name));
if (matching.length === 0) {
interface_logger.throwArgumentError("no matching error", "name", name);
}
else if (matching.length > 1) {
interface_logger.throwArgumentError("multiple matching errors", "name", name);
}
return this.errors[matching[0]];
}
// Normalize the signature and lookup the function
const result = this.errors[fragments_FunctionFragment.fromString(nameOrSignatureOrSighash).format()];
if (!result) {
interface_logger.throwArgumentError("no matching error", "signature", nameOrSignatureOrSighash);
}
return result;
}
// Get the sighash (the bytes4 selector) used by Solidity to identify a function
getSighash(fragment) {
if (typeof (fragment) === "string") {
try {
fragment = this.getFunction(fragment);
}
catch (error) {
try {
fragment = this.getError(fragment);
}
catch (_) {
throw error;
}
}
}
return getStatic(this.constructor, "getSighash")(fragment);
}
// Get the topic (the bytes32 hash) used by Solidity to identify an event
getEventTopic(eventFragment) {
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
return getStatic(this.constructor, "getEventTopic")(eventFragment);
}
_decodeParams(params, data) {
return this._abiCoder.decode(params, data);
}
_encodeParams(params, values) {
return this._abiCoder.encode(params, values);
}
encodeDeploy(values) {
return this._encodeParams(this.deploy.inputs, values || []);
}
decodeErrorResult(fragment, data) {
if (typeof (fragment) === "string") {
fragment = this.getError(fragment);
}
const bytes = arrayify(data);
if (hexlify(bytes.slice(0, 4)) !== this.getSighash(fragment)) {
interface_logger.throwArgumentError(`data signature does not match error ${fragment.name}.`, "data", hexlify(bytes));
}
return this._decodeParams(fragment.inputs, bytes.slice(4));
}
encodeErrorResult(fragment, values) {
if (typeof (fragment) === "string") {
fragment = this.getError(fragment);
}
return hexlify(concat([
this.getSighash(fragment),
this._encodeParams(fragment.inputs, values || [])
]));
}
// Decode the data for a function call (e.g. tx.data)
decodeFunctionData(functionFragment, data) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
const bytes = arrayify(data);
if (hexlify(bytes.slice(0, 4)) !== this.getSighash(functionFragment)) {
interface_logger.throwArgumentError(`data signature does not match function ${functionFragment.name}.`, "data", hexlify(bytes));
}
return this._decodeParams(functionFragment.inputs, bytes.slice(4));
}
// Encode the data for a function call (e.g. tx.data)
encodeFunctionData(functionFragment, values) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
return hexlify(concat([
this.getSighash(functionFragment),
this._encodeParams(functionFragment.inputs, values || [])
]));
}
// Decode the result from a function call (e.g. from eth_call)
decodeFunctionResult(functionFragment, data) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
let bytes = arrayify(data);
let reason = null;
let message = "";
let errorArgs = null;
let errorName = null;
let errorSignature = null;
switch (bytes.length % this._abiCoder._getWordSize()) {
case 0:
try {
return this._abiCoder.decode(functionFragment.outputs, bytes);
}
catch (error) { }
break;
case 4: {
const selector = hexlify(bytes.slice(0, 4));
const builtin = BuiltinErrors[selector];
if (builtin) {
errorArgs = this._abiCoder.decode(builtin.inputs, bytes.slice(4));
errorName = builtin.name;
errorSignature = builtin.signature;
if (builtin.reason) {
reason = errorArgs[0];
}
if (errorName === "Error") {
message = `; VM Exception while processing transaction: reverted with reason string ${JSON.stringify(errorArgs[0])}`;
}
else if (errorName === "Panic") {
message = `; VM Exception while processing transaction: reverted with panic code ${errorArgs[0]}`;
}
}
else {
try {
const error = this.getError(selector);
errorArgs = this._abiCoder.decode(error.inputs, bytes.slice(4));
errorName = error.name;
errorSignature = error.format();
}
catch (error) { }
}
break;
}
}
return interface_logger.throwError("call revert exception" + message, lib_esm_Logger.errors.CALL_EXCEPTION, {
method: functionFragment.format(),
data: hexlify(data), errorArgs, errorName, errorSignature, reason
});
}
// Encode the result for a function call (e.g. for eth_call)
encodeFunctionResult(functionFragment, values) {
if (typeof (functionFragment) === "string") {
functionFragment = this.getFunction(functionFragment);
}
return hexlify(this._abiCoder.encode(functionFragment.outputs, values || []));
}
// Create the filter for the event with search criteria (e.g. for eth_filterLog)
encodeFilterTopics(eventFragment, values) {
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
if (values.length > eventFragment.inputs.length) {
interface_logger.throwError("too many arguments for " + eventFragment.format(), lib_esm_Logger.errors.UNEXPECTED_ARGUMENT, {
argument: "values",
value: values
});
}
let topics = [];
if (!eventFragment.anonymous) {
topics.push(this.getEventTopic(eventFragment));
}
const encodeTopic = (param, value) => {
if (param.type === "string") {
return id_id(value);
}
else if (param.type === "bytes") {
return keccak256(hexlify(value));
}
if (param.type === "bool" && typeof (value) === "boolean") {
value = (value ? "0x01" : "0x00");
}
if (param.type.match(/^u?int/)) {
value = bignumber_BigNumber.from(value).toHexString();
}
// Check addresses are valid
if (param.type === "address") {
this._abiCoder.encode(["address"], [value]);
}
return hexZeroPad(hexlify(value), 32);
};
values.forEach((value, index) => {
let param = eventFragment.inputs[index];
if (!param.indexed) {
if (value != null) {
interface_logger.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
}
return;
}
if (value == null) {
topics.push(null);
}
else if (param.baseType === "array" || param.baseType === "tuple") {
interface_logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
}
else if (Array.isArray(value)) {
topics.push(value.map((value) => encodeTopic(param, value)));
}
else {
topics.push(encodeTopic(param, value));
}
});
// Trim off trailing nulls
while (topics.length && topics[topics.length - 1] === null) {
topics.pop();
}
return topics;
}
encodeEventLog(eventFragment, values) {
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
const topics = [];
const dataTypes = [];
const dataValues = [];
if (!eventFragment.anonymous) {
topics.push(this.getEventTopic(eventFragment));
}
if (values.length !== eventFragment.inputs.length) {
interface_logger.throwArgumentError("event arguments/values mismatch", "values", values);
}
eventFragment.inputs.forEach((param, index) => {
const value = values[index];
if (param.indexed) {
if (param.type === "string") {
topics.push(id_id(value));
}
else if (param.type === "bytes") {
topics.push(keccak256(value));
}
else if (param.baseType === "tuple" || param.baseType === "array") {
// @TODO
throw new Error("not implemented");
}
else {
topics.push(this._abiCoder.encode([param.type], [value]));
}
}
else {
dataTypes.push(param);
dataValues.push(value);
}
});
return {
data: this._abiCoder.encode(dataTypes, dataValues),
topics: topics
};
}
// Decode a filter for the event and the search criteria
decodeEventLog(eventFragment, data, topics) {
if (typeof (eventFragment) === "string") {
eventFragment = this.getEvent(eventFragment);
}
if (topics != null && !eventFragment.anonymous) {
let topicHash = this.getEventTopic(eventFragment);
if (!isHexString(topics[0], 32) || topics[0].toLowerCase() !== topicHash) {
interface_logger.throwError("fragment/topic mismatch", lib_esm_Logger.errors.INVALID_ARGUMENT, { argument: "topics[0]", expected: topicHash, value: topics[0] });
}
topics = topics.slice(1);
}
let indexed = [];
let nonIndexed = [];
let dynamic = [];
eventFragment.inputs.forEach((param, index) => {
if (param.indexed) {
if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
indexed.push(fragments_ParamType.fromObject({ type: "bytes32", name: param.name }));
dynamic.push(true);
}
else {
indexed.push(param);
dynamic.push(false);
}
}
else {
nonIndexed.push(param);
dynamic.push(false);
}
});
let resultIndexed = (topics != null) ? this._abiCoder.decode(indexed, concat(topics)) : null;
let resultNonIndexed = this._abiCoder.decode(nonIndexed, data, true);
let result = [];
let nonIndexedIndex = 0, indexedIndex = 0;
eventFragment.inputs.forEach((param, index) => {
if (param.indexed) {
if (resultIndexed == null) {
result[index] = new interface_Indexed({ _isIndexed: true, hash: null });
}
else if (dynamic[index]) {
result[index] = new interface_Indexed({ _isIndexed: true, hash: resultIndexed[indexedIndex++] });
}
else {
try {
result[index] = resultIndexed[indexedIndex++];
}
catch (error) {
result[index] = error;
}
}
}
else {
try {
result[index] = resultNonIndexed[nonIndexedIndex++];
}
catch (error) {
result[index] = error;
}
}
// Add the keyword argument if named and safe
if (param.name && result[param.name] == null) {
const value = result[index];
// Make error named values throw on access
if (value instanceof Error) {
Object.defineProperty(result, param.name, {
enumerable: true,
get: () => { throw wrapAccessError(`property ${JSON.stringify(param.name)}`, value); }
});
}
else {
result[param.name] = value;
}
}
});
// Make all error indexed values throw on access
for (let i = 0; i < result.length; i++) {
const value = result[i];
if (value instanceof Error) {
Object.defineProperty(result, i, {
enumerable: true,
get: () => { throw wrapAccessError(`index ${i}`, value); }
});
}
}
return Object.freeze(result);
}
// Given a transaction, find the matching function fragment (if any) and
// determine all its properties and call parameters
parseTransaction(tx) {
let fragment = this.getFunction(tx.data.substring(0, 10).toLowerCase());
if (!fragment) {
return null;
}
return new interface_TransactionDescription({
args: this._abiCoder.decode(fragment.inputs, "0x" + tx.data.substring(10)),
functionFragment: fragment,
name: fragment.name,
signature: fragment.format(),
sighash: this.getSighash(fragment),
value: bignumber_BigNumber.from(tx.value || "0"),
});
}
// @TODO
//parseCallResult(data: BytesLike): ??
// Given an event log, find the matching event fragment (if any) and
// determine all its properties and values
parseLog(log) {
let fragment = this.getEvent(log.topics[0]);
if (!fragment || fragment.anonymous) {
return null;
}
// @TODO: If anonymous, and the only method, and the input count matches, should we parse?
// Probably not, because just because it is the only event in the ABI does
// not mean we have the full ABI; maybe just a fragment?
return new interface_LogDescription({
eventFragment: fragment,
name: fragment.name,
signature: fragment.format(),
topic: this.getEventTopic(fragment),
args: this.decodeEventLog(fragment, log.data, log.topics)
});
}
parseError(data) {
const hexData = hexlify(data);
let fragment = this.getError(hexData.substring(0, 10).toLowerCase());
if (!fragment) {
return null;
}
return new interface_ErrorDescription({
args: this._abiCoder.decode(fragment.inputs, "0x" + hexData.substring(10)),
errorFragment: fragment,
name: fragment.name,
signature: fragment.format(),
sighash: this.getSighash(fragment),
});
}
/*
static from(value: Array<Fragment | string | JsonAbi> | string | Interface) {
if (Interface.isInterface(value)) {
return value;
}
if (typeof(value) === "string") {
return new Interface(JSON.parse(value));
}
return new Interface(value);
}
*/
static isInterface(value) {
return !!(value && value._isInterface);
}
}
//# sourceMappingURL=interface.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/base64/lib.esm/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hash/lib.esm/message.js
const messagePrefix = "\x19Ethereum Signed Message:\n";
function hashMessage(message) {
if (typeof (message) === "string") {
message = toUtf8Bytes(message);
}
return keccak256(concat([
toUtf8Bytes(messagePrefix),
toUtf8Bytes(String(message.length)),
message
]));
}
//# sourceMappingURL=message.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/pbkdf2/lib.esm/pbkdf2.js
function pbkdf2(password, salt, iterations, keylen, hashAlgorithm) {
password = arrayify(password);
salt = arrayify(salt);
let hLen;
let l = 1;
const DK = new Uint8Array(keylen);
const block1 = new Uint8Array(salt.length + 4);
block1.set(salt);
//salt.copy(block1, 0, 0, salt.length)
let r;
let T;
for (let i = 1; i <= l; i++) {
//block1.writeUInt32BE(i, salt.length)
block1[salt.length] = (i >> 24) & 0xff;
block1[salt.length + 1] = (i >> 16) & 0xff;
block1[salt.length + 2] = (i >> 8) & 0xff;
block1[salt.length + 3] = i & 0xff;
//let U = createHmac(password).update(block1).digest();
let U = arrayify(computeHmac(hashAlgorithm, password, block1));
if (!hLen) {
hLen = U.length;
T = new Uint8Array(hLen);
l = Math.ceil(keylen / hLen);
r = keylen - (l - 1) * hLen;
}
//U.copy(T, 0, 0, hLen)
T.set(U);
for (let j = 1; j < iterations; j++) {
//U = createHmac(password).update(U).digest();
U = arrayify(computeHmac(hashAlgorithm, password, U));
for (let k = 0; k < hLen; k++)
T[k] ^= U[k];
}
const destPos = (i - 1) * hLen;
const len = (i === l ? r : hLen);
//T.copy(DK, destPos, 0, len)
DK.set(arrayify(T).slice(0, len), destPos);
}
return hexlify(DK);
}
//# sourceMappingURL=pbkdf2.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/wordlists/lib.esm/_version.js
const wordlists_lib_esm_version_version = "wordlists/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/wordlists/lib.esm/wordlist.js
// This gets overridden by rollup
const exportWordlist = false;
const wordlist_logger = new lib_esm_Logger(wordlists_lib_esm_version_version);
class wordlist_Wordlist {
constructor(locale) {
wordlist_logger.checkAbstract(new.target, wordlist_Wordlist);
defineReadOnly(this, "locale", locale);
}
// Subclasses may override this
split(mnemonic) {
return mnemonic.toLowerCase().split(/ +/g);
}
// Subclasses may override this
join(words) {
return words.join(" ");
}
static check(wordlist) {
const words = [];
for (let i = 0; i < 2048; i++) {
const word = wordlist.getWord(i);
/* istanbul ignore if */
if (i !== wordlist.getWordIndex(word)) {
return "0x";
}
words.push(word);
}
return id_id(words.join("\n") + "\n");
}
static register(lang, name) {
if (!name) {
name = lang.locale;
}
/* istanbul ignore if */
if (exportWordlist) {
try {
const anyGlobal = window;
if (anyGlobal._ethers && anyGlobal._ethers.wordlists) {
if (!anyGlobal._ethers.wordlists[name]) {
defineReadOnly(anyGlobal._ethers.wordlists, name, lang);
}
}
}
catch (error) { }
}
}
}
//# sourceMappingURL=wordlist.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/wordlists/lib.esm/lang-en.js
const lang_en_words = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo";
let lang_en_wordlist = null;
function loadWords(lang) {
if (lang_en_wordlist != null) {
return;
}
lang_en_wordlist = lang_en_words.replace(/([A-Z])/g, " $1").toLowerCase().substring(1).split(" ");
// Verify the computed list matches the official list
/* istanbul ignore if */
if (wordlist_Wordlist.check(lang) !== "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60") {
lang_en_wordlist = null;
throw new Error("BIP39 Wordlist for en (English) FAILED");
}
}
class lang_en_LangEn extends wordlist_Wordlist {
constructor() {
super("en");
}
getWord(index) {
loadWords(this);
return lang_en_wordlist[index];
}
getWordIndex(word) {
loadWords(this);
return lang_en_wordlist.indexOf(word);
}
}
const langEn = new lang_en_LangEn();
wordlist_Wordlist.register(langEn);
//# sourceMappingURL=lang-en.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/wordlists/lib.esm/wordlists.js
const wordlists = {
en: langEn
};
//# sourceMappingURL=wordlists.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hdnode/lib.esm/_version.js
const hdnode_lib_esm_version_version = "hdnode/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/hdnode/lib.esm/index.js
const hdnode_lib_esm_logger = new lib_esm_Logger(hdnode_lib_esm_version_version);
const lib_esm_N = bignumber_BigNumber.from("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
// "Bitcoin seed"
const MasterSecret = toUtf8Bytes("Bitcoin seed");
const HardenedBit = 0x80000000;
// Returns a byte with the MSB bits set
function getUpperMask(bits) {
return ((1 << bits) - 1) << (8 - bits);
}
// Returns a byte with the LSB bits set
function getLowerMask(bits) {
return (1 << bits) - 1;
}
function bytes32(value) {
return hexZeroPad(hexlify(value), 32);
}
function base58check(data) {
return Base58.encode(concat([data, hexDataSlice(sha256(sha256(data)), 0, 4)]));
}
function getWordlist(wordlist) {
if (wordlist == null) {
return wordlists["en"];
}
if (typeof (wordlist) === "string") {
const words = wordlists[wordlist];
if (words == null) {
hdnode_lib_esm_logger.throwArgumentError("unknown locale", "wordlist", wordlist);
}
return words;
}
return wordlist;
}
const lib_esm_constructorGuard = {};
const defaultPath = "m/44'/60'/0'/0/0";
;
class lib_esm_HDNode {
/**
* This constructor should not be called directly.
*
* Please use:
* - fromMnemonic
* - fromSeed
*/
constructor(constructorGuard, privateKey, publicKey, parentFingerprint, chainCode, index, depth, mnemonicOrPath) {
/* istanbul ignore if */
if (constructorGuard !== lib_esm_constructorGuard) {
throw new Error("HDNode constructor cannot be called directly");
}
if (privateKey) {
const signingKey = new lib_esm_SigningKey(privateKey);
defineReadOnly(this, "privateKey", signingKey.privateKey);
defineReadOnly(this, "publicKey", signingKey.compressedPublicKey);
}
else {
defineReadOnly(this, "privateKey", null);
defineReadOnly(this, "publicKey", hexlify(publicKey));
}
defineReadOnly(this, "parentFingerprint", parentFingerprint);
defineReadOnly(this, "fingerprint", hexDataSlice(ripemd160(sha256(this.publicKey)), 0, 4));
defineReadOnly(this, "address", computeAddress(this.publicKey));
defineReadOnly(this, "chainCode", chainCode);
defineReadOnly(this, "index", index);
defineReadOnly(this, "depth", depth);
if (mnemonicOrPath == null) {
// From a source that does not preserve the path (e.g. extended keys)
defineReadOnly(this, "mnemonic", null);
defineReadOnly(this, "path", null);
}
else if (typeof (mnemonicOrPath) === "string") {
// From a source that does not preserve the mnemonic (e.g. neutered)
defineReadOnly(this, "mnemonic", null);
defineReadOnly(this, "path", mnemonicOrPath);
}
else {
// From a fully qualified source
defineReadOnly(this, "mnemonic", mnemonicOrPath);
defineReadOnly(this, "path", mnemonicOrPath.path);
}
}
get extendedKey() {
// We only support the mainnet values for now, but if anyone needs
// testnet values, let me know. I believe current sentiment is that
// we should always use mainnet, and use BIP-44 to derive the network
// - Mainnet: public=0x0488B21E, private=0x0488ADE4
// - Testnet: public=0x043587CF, private=0x04358394
if (this.depth >= 256) {
throw new Error("Depth too large!");
}
return base58check(concat([
((this.privateKey != null) ? "0x0488ADE4" : "0x0488B21E"),
hexlify(this.depth),
this.parentFingerprint,
hexZeroPad(hexlify(this.index), 4),
this.chainCode,
((this.privateKey != null) ? concat(["0x00", this.privateKey]) : this.publicKey),
]));
}
neuter() {
return new lib_esm_HDNode(lib_esm_constructorGuard, null, this.publicKey, this.parentFingerprint, this.chainCode, this.index, this.depth, this.path);
}
_derive(index) {
if (index > 0xffffffff) {
throw new Error("invalid index - " + String(index));
}
// Base path
let path = this.path;
if (path) {
path += "/" + (index & ~HardenedBit);
}
const data = new Uint8Array(37);
if (index & HardenedBit) {
if (!this.privateKey) {
throw new Error("cannot derive child of neutered node");
}
// Data = 0x00 || ser_256(k_par)
data.set(arrayify(this.privateKey), 1);
// Hardened path
if (path) {
path += "'";
}
}
else {
// Data = ser_p(point(k_par))
data.set(arrayify(this.publicKey));
}
// Data += ser_32(i)
for (let i = 24; i >= 0; i -= 8) {
data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff);
}
const I = arrayify(computeHmac(SupportedAlgorithm.sha512, this.chainCode, data));
const IL = I.slice(0, 32);
const IR = I.slice(32);
// The private key
let ki = null;
// The public key
let Ki = null;
if (this.privateKey) {
ki = bytes32(bignumber_BigNumber.from(IL).add(this.privateKey).mod(lib_esm_N));
}
else {
const ek = new lib_esm_SigningKey(hexlify(IL));
Ki = ek._addPoint(this.publicKey);
}
let mnemonicOrPath = path;
const srcMnemonic = this.mnemonic;
if (srcMnemonic) {
mnemonicOrPath = Object.freeze({
phrase: srcMnemonic.phrase,
path: path,
locale: (srcMnemonic.locale || "en")
});
}
return new lib_esm_HDNode(lib_esm_constructorGuard, ki, Ki, this.fingerprint, bytes32(IR), index, this.depth + 1, mnemonicOrPath);
}
derivePath(path) {
const components = path.split("/");
if (components.length === 0 || (components[0] === "m" && this.depth !== 0)) {
throw new Error("invalid path - " + path);
}
if (components[0] === "m") {
components.shift();
}
let result = this;
for (let i = 0; i < components.length; i++) {
const component = components[i];
if (component.match(/^[0-9]+'$/)) {
const index = parseInt(component.substring(0, component.length - 1));
if (index >= HardenedBit) {
throw new Error("invalid path index - " + component);
}
result = result._derive(HardenedBit + index);
}
else if (component.match(/^[0-9]+$/)) {
const index = parseInt(component);
if (index >= HardenedBit) {
throw new Error("invalid path index - " + component);
}
result = result._derive(index);
}
else {
throw new Error("invalid path component - " + component);
}
}
return result;
}
static _fromSeed(seed, mnemonic) {
const seedArray = arrayify(seed);
if (seedArray.length < 16 || seedArray.length > 64) {
throw new Error("invalid seed");
}
const I = arrayify(computeHmac(SupportedAlgorithm.sha512, MasterSecret, seedArray));
return new lib_esm_HDNode(lib_esm_constructorGuard, bytes32(I.slice(0, 32)), null, "0x00000000", bytes32(I.slice(32)), 0, 0, mnemonic);
}
static fromMnemonic(mnemonic, password, wordlist) {
// If a locale name was passed in, find the associated wordlist
wordlist = getWordlist(wordlist);
// Normalize the case and spacing in the mnemonic (throws if the mnemonic is invalid)
mnemonic = entropyToMnemonic(mnemonicToEntropy(mnemonic, wordlist), wordlist);
return lib_esm_HDNode._fromSeed(mnemonicToSeed(mnemonic, password), {
phrase: mnemonic,
path: "m",
locale: wordlist.locale
});
}
static fromSeed(seed) {
return lib_esm_HDNode._fromSeed(seed, null);
}
static fromExtendedKey(extendedKey) {
const bytes = Base58.decode(extendedKey);
if (bytes.length !== 82 || base58check(bytes.slice(0, 78)) !== extendedKey) {
hdnode_lib_esm_logger.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]");
}
const depth = bytes[4];
const parentFingerprint = hexlify(bytes.slice(5, 9));
const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16);
const chainCode = hexlify(bytes.slice(13, 45));
const key = bytes.slice(45, 78);
switch (hexlify(bytes.slice(0, 4))) {
// Public Key
case "0x0488b21e":
case "0x043587cf":
return new lib_esm_HDNode(lib_esm_constructorGuard, null, hexlify(key), parentFingerprint, chainCode, index, depth, null);
// Private Key
case "0x0488ade4":
case "0x04358394 ":
if (key[0] !== 0) {
break;
}
return new lib_esm_HDNode(lib_esm_constructorGuard, hexlify(key.slice(1)), null, parentFingerprint, chainCode, index, depth, null);
}
return hdnode_lib_esm_logger.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]");
}
}
function mnemonicToSeed(mnemonic, password) {
if (!password) {
password = "";
}
const salt = toUtf8Bytes("mnemonic" + password, UnicodeNormalizationForm.NFKD);
return pbkdf2(toUtf8Bytes(mnemonic, UnicodeNormalizationForm.NFKD), salt, 2048, 64, "sha512");
}
function mnemonicToEntropy(mnemonic, wordlist) {
wordlist = getWordlist(wordlist);
hdnode_lib_esm_logger.checkNormalize();
const words = wordlist.split(mnemonic);
if ((words.length % 3) !== 0) {
throw new Error("invalid mnemonic");
}
const entropy = arrayify(new Uint8Array(Math.ceil(11 * words.length / 8)));
let offset = 0;
for (let i = 0; i < words.length; i++) {
let index = wordlist.getWordIndex(words[i].normalize("NFKD"));
if (index === -1) {
throw new Error("invalid mnemonic");
}
for (let bit = 0; bit < 11; bit++) {
if (index & (1 << (10 - bit))) {
entropy[offset >> 3] |= (1 << (7 - (offset % 8)));
}
offset++;
}
}
const entropyBits = 32 * words.length / 3;
const checksumBits = words.length / 3;
const checksumMask = getUpperMask(checksumBits);
const checksum = arrayify(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
throw new Error("invalid checksum");
}
return hexlify(entropy.slice(0, entropyBits / 8));
}
function entropyToMnemonic(entropy, wordlist) {
wordlist = getWordlist(wordlist);
entropy = arrayify(entropy);
if ((entropy.length % 4) !== 0 || entropy.length < 16 || entropy.length > 32) {
throw new Error("invalid entropy");
}
const indices = [0];
let remainingBits = 11;
for (let i = 0; i < entropy.length; i++) {
// Consume the whole byte (with still more to go)
if (remainingBits > 8) {
indices[indices.length - 1] <<= 8;
indices[indices.length - 1] |= entropy[i];
remainingBits -= 8;
// This byte will complete an 11-bit index
}
else {
indices[indices.length - 1] <<= remainingBits;
indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits);
// Start the next word
indices.push(entropy[i] & getLowerMask(8 - remainingBits));
remainingBits += 3;
}
}
// Compute the checksum bits
const checksumBits = entropy.length / 4;
const checksum = arrayify(sha256(entropy))[0] & getUpperMask(checksumBits);
// Shift the checksum into the word indices
indices[indices.length - 1] <<= checksumBits;
indices[indices.length - 1] |= (checksum >> (8 - checksumBits));
return wordlist.join(indices.map((index) => wordlist.getWord(index)));
}
function isValidMnemonic(mnemonic, wordlist) {
try {
mnemonicToEntropy(mnemonic, wordlist);
return true;
}
catch (error) { }
return false;
}
function getAccountPath(index) {
if (typeof (index) !== "number" || index < 0 || index >= HardenedBit || index % 1) {
hdnode_lib_esm_logger.throwArgumentError("invalid account index", "index", index);
}
return `m/44'/60'/${index}'/0/0`;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/json-wallets/lib.esm/inspect.js
function isCrowdsaleWallet(json) {
let data = null;
try {
data = JSON.parse(json);
}
catch (error) {
return false;
}
return (data.encseed && data.ethaddr);
}
function isKeystoreWallet(json) {
let data = null;
try {
data = JSON.parse(json);
}
catch (error) {
return false;
}
if (!data.version || parseInt(data.version) !== data.version || parseInt(data.version) !== 3) {
return false;
}
// @TODO: Put more checks to make sure it has kdf, iv and all that good stuff
return true;
}
//export function isJsonWallet(json: string): boolean {
// return (isSecretStorageWallet(json) || isCrowdsaleWallet(json));
//}
function getJsonWalletAddress(json) {
if (isCrowdsaleWallet(json)) {
try {
return getAddress(JSON.parse(json).ethaddr);
}
catch (error) {
return null;
}
}
if (isKeystoreWallet(json)) {
try {
return getAddress(JSON.parse(json).address);
}
catch (error) {
return null;
}
}
return null;
}
//# sourceMappingURL=inspect.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/solidity/lib.esm/_version.js
const solidity_lib_esm_version_version = "solidity/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/solidity/lib.esm/index.js
const regexBytes = new RegExp("^bytes([0-9]+)$");
const regexNumber = new RegExp("^(u?int)([0-9]*)$");
const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$");
const lib_esm_Zeros = "0000000000000000000000000000000000000000000000000000000000000000";
const solidity_lib_esm_logger = new lib_esm_Logger(solidity_lib_esm_version_version);
function _pack(type, value, isArray) {
switch (type) {
case "address":
if (isArray) {
return zeroPad(value, 32);
}
return arrayify(value);
case "string":
return toUtf8Bytes(value);
case "bytes":
return arrayify(value);
case "bool":
value = (value ? "0x01" : "0x00");
if (isArray) {
return zeroPad(value, 32);
}
return arrayify(value);
}
let match = type.match(regexNumber);
if (match) {
//let signed = (match[1] === "int")
let size = parseInt(match[2] || "256");
if ((match[2] && String(size) !== match[2]) || (size % 8 !== 0) || size === 0 || size > 256) {
solidity_lib_esm_logger.throwArgumentError("invalid number type", "type", type);
}
if (isArray) {
size = 256;
}
value = bignumber_BigNumber.from(value).toTwos(size);
return zeroPad(value, size / 8);
}
match = type.match(regexBytes);
if (match) {
const size = parseInt(match[1]);
if (String(size) !== match[1] || size === 0 || size > 32) {
solidity_lib_esm_logger.throwArgumentError("invalid bytes type", "type", type);
}
if (arrayify(value).byteLength !== size) {
solidity_lib_esm_logger.throwArgumentError(`invalid value for ${type}`, "value", value);
}
if (isArray) {
return arrayify((value + lib_esm_Zeros).substring(0, 66));
}
return value;
}
match = type.match(regexArray);
if (match && Array.isArray(value)) {
const baseType = match[1];
const count = parseInt(match[2] || String(value.length));
if (count != value.length) {
solidity_lib_esm_logger.throwArgumentError(`invalid array length for ${type}`, "value", value);
}
const result = [];
value.forEach(function (value) {
result.push(_pack(baseType, value, true));
});
return concat(result);
}
return solidity_lib_esm_logger.throwArgumentError("invalid type", "type", type);
}
// @TODO: Array Enum
function lib_esm_pack(types, values) {
if (types.length != values.length) {
solidity_lib_esm_logger.throwArgumentError("wrong number of values; expected ${ types.length }", "values", values);
}
const tight = [];
types.forEach(function (type, index) {
tight.push(_pack(type, values[index]));
});
return hexlify(concat(tight));
}
function lib_esm_keccak256(types, values) {
return keccak256(lib_esm_pack(types, values));
}
function lib_esm_sha256(types, values) {
return sha256(lib_esm_pack(types, values));
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/random/lib.esm/_version.js
const random_lib_esm_version_version = "random/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/random/lib.esm/random.js
const random_logger = new lib_esm_Logger(random_lib_esm_version_version);
// Debugging line for testing browser lib in node
//const window = { crypto: { getRandomValues: () => { } } };
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
function getGlobal() {
if (typeof self !== 'undefined') {
return self;
}
if (typeof window !== 'undefined') {
return window;
}
if (typeof global !== 'undefined') {
return global;
}
throw new Error('unable to locate global object');
}
;
const random_anyGlobal = getGlobal();
let random_crypto = random_anyGlobal.crypto || random_anyGlobal.msCrypto;
if (!random_crypto || !random_crypto.getRandomValues) {
random_logger.warn("WARNING: Missing strong random number source");
random_crypto = {
getRandomValues: function (buffer) {
return random_logger.throwError("no secure random source avaialble", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "crypto.getRandomValues"
});
}
};
}
function random_randomBytes(length) {
if (length <= 0 || length > 1024 || (length % 1) || length != length) {
random_logger.throwArgumentError("invalid length", "length", length);
}
const result = new Uint8Array(length);
random_crypto.getRandomValues(result);
return arrayify(result);
}
;
//# sourceMappingURL=random.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/strings/lib.esm/idna.js
function bytes2(data) {
if ((data.length % 4) !== 0) {
throw new Error("bad data");
}
let result = [];
for (let i = 0; i < data.length; i += 4) {
result.push(parseInt(data.substring(i, i + 4), 16));
}
return result;
}
function createTable(data, func) {
if (!func) {
func = function (value) { return [parseInt(value, 16)]; };
}
let lo = 0;
let result = {};
data.split(",").forEach((pair) => {
let comps = pair.split(":");
lo += parseInt(comps[0], 16);
result[lo] = func(comps[1]);
});
return result;
}
function createRangeTable(data) {
let hi = 0;
return data.split(",").map((v) => {
let comps = v.split("-");
if (comps.length === 1) {
comps[1] = "0";
}
else if (comps[1] === "") {
comps[1] = "1";
}
let lo = hi + parseInt(comps[0], 16);
hi = parseInt(comps[1], 16);
return { l: lo, h: hi };
});
}
function matchMap(value, ranges) {
let lo = 0;
for (let i = 0; i < ranges.length; i++) {
let range = ranges[i];
lo += range.l;
if (value >= lo && value <= lo + range.h && ((value - lo) % (range.d || 1)) === 0) {
if (range.e && range.e.indexOf(value - lo) !== -1) {
continue;
}
return range;
}
}
return null;
}
const Table_A_1_ranges = createRangeTable("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d");
// @TODO: Make this relative...
const Table_B_1_flags = "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((v) => parseInt(v, 16));
const Table_B_2_ranges = [
{ h: 25, s: 32, l: 65 },
{ h: 30, s: 32, e: [23], l: 127 },
{ h: 54, s: 1, e: [48], l: 64, d: 2 },
{ h: 14, s: 1, l: 57, d: 2 },
{ h: 44, s: 1, l: 17, d: 2 },
{ h: 10, s: 1, e: [2, 6, 8], l: 61, d: 2 },
{ h: 16, s: 1, l: 68, d: 2 },
{ h: 84, s: 1, e: [18, 24, 66], l: 19, d: 2 },
{ h: 26, s: 32, e: [17], l: 435 },
{ h: 22, s: 1, l: 71, d: 2 },
{ h: 15, s: 80, l: 40 },
{ h: 31, s: 32, l: 16 },
{ h: 32, s: 1, l: 80, d: 2 },
{ h: 52, s: 1, l: 42, d: 2 },
{ h: 12, s: 1, l: 55, d: 2 },
{ h: 40, s: 1, e: [38], l: 15, d: 2 },
{ h: 14, s: 1, l: 48, d: 2 },
{ h: 37, s: 48, l: 49 },
{ h: 148, s: 1, l: 6351, d: 2 },
{ h: 88, s: 1, l: 160, d: 2 },
{ h: 15, s: 16, l: 704 },
{ h: 25, s: 26, l: 854 },
{ h: 25, s: 32, l: 55915 },
{ h: 37, s: 40, l: 1247 },
{ h: 25, s: -119711, l: 53248 },
{ h: 25, s: -119763, l: 52 },
{ h: 25, s: -119815, l: 52 },
{ h: 25, s: -119867, e: [1, 4, 5, 7, 8, 11, 12, 17], l: 52 },
{ h: 25, s: -119919, l: 52 },
{ h: 24, s: -119971, e: [2, 7, 8, 17], l: 52 },
{ h: 24, s: -120023, e: [2, 7, 13, 15, 16, 17], l: 52 },
{ h: 25, s: -120075, l: 52 },
{ h: 25, s: -120127, l: 52 },
{ h: 25, s: -120179, l: 52 },
{ h: 25, s: -120231, l: 52 },
{ h: 25, s: -120283, l: 52 },
{ h: 25, s: -120335, l: 52 },
{ h: 24, s: -119543, e: [17], l: 56 },
{ h: 24, s: -119601, e: [17], l: 58 },
{ h: 24, s: -119659, e: [17], l: 58 },
{ h: 24, s: -119717, e: [17], l: 58 },
{ h: 24, s: -119775, e: [17], l: 58 }
];
const Table_B_2_lut_abs = createTable("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3");
const Table_B_2_lut_rel = createTable("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7");
const Table_B_2_complex = createTable("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", bytes2);
const Table_C_ranges = createRangeTable("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");
function idna_flatten(values) {
return values.reduce((accum, value) => {
value.forEach((value) => { accum.push(value); });
return accum;
}, []);
}
function _nameprepTableA1(codepoint) {
return !!matchMap(codepoint, Table_A_1_ranges);
}
function _nameprepTableB2(codepoint) {
let range = matchMap(codepoint, Table_B_2_ranges);
if (range) {
return [codepoint + range.s];
}
let codes = Table_B_2_lut_abs[codepoint];
if (codes) {
return codes;
}
let shift = Table_B_2_lut_rel[codepoint];
if (shift) {
return [codepoint + shift[0]];
}
let complex = Table_B_2_complex[codepoint];
if (complex) {
return complex;
}
return null;
}
function _nameprepTableC(codepoint) {
return !!matchMap(codepoint, Table_C_ranges);
}
function nameprep(value) {
// This allows platforms with incomplete normalize to bypass
// it for very basic names which the built-in toLowerCase
// will certainly handle correctly
if (value.match(/^[a-z0-9-]*$/i) && value.length <= 59) {
return value.toLowerCase();
}
// Get the code points (keeping the current normalization)
let codes = toUtf8CodePoints(value);
codes = idna_flatten(codes.map((code) => {
// Substitute Table B.1 (Maps to Nothing)
if (Table_B_1_flags.indexOf(code) >= 0) {
return [];
}
if (code >= 0xfe00 && code <= 0xfe0f) {
return [];
}
// Substitute Table B.2 (Case Folding)
let codesTableB2 = _nameprepTableB2(code);
if (codesTableB2) {
return codesTableB2;
}
// No Substitution
return [code];
}));
// Normalize using form KC
codes = toUtf8CodePoints(_toUtf8String(codes), UnicodeNormalizationForm.NFKC);
// Prohibit Tables C.1.2, C.2.2, C.3, C.4, C.5, C.6, C.7, C.8, C.9
codes.forEach((code) => {
if (_nameprepTableC(code)) {
throw new Error("STRINGPREP_CONTAINS_PROHIBITED");
}
});
// Prohibit Unassigned Code Points (Table A.1)
codes.forEach((code) => {
if (_nameprepTableA1(code)) {
throw new Error("STRINGPREP_CONTAINS_UNASSIGNED");
}
});
// IDNA extras
let name = _toUtf8String(codes);
// IDNA: 4.2.3.1
if (name.substring(0, 1) === "-" || name.substring(2, 4) === "--" || name.substring(name.length - 1) === "-") {
throw new Error("invalid hyphen");
}
return name;
}
//# sourceMappingURL=idna.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/strings/lib.esm/bytes32.js
function formatBytes32String(text) {
// Get the bytes
const bytes = toUtf8Bytes(text);
// Check we have room for null-termination
if (bytes.length > 31) {
throw new Error("bytes32 string must be less than 32 bytes");
}
// Zero-pad (implicitly null-terminates)
return hexlify(concat([bytes, HashZero]).slice(0, 32));
}
function parseBytes32String(bytes) {
const data = arrayify(bytes);
// Must be 32 bytes with a null-termination
if (data.length !== 32) {
throw new Error("invalid bytes32 - not 32 bytes long");
}
if (data[31] !== 0) {
throw new Error("invalid bytes32 string - no null terminator");
}
// Find the null termination
let length = 31;
while (data[length - 1] === 0) {
length--;
}
// Determine the string value
return toUtf8String(data.slice(0, length));
}
//# sourceMappingURL=bytes32.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/bignumber/lib.esm/fixednumber.js
const fixednumber_logger = new lib_esm_Logger(bignumber_lib_esm_version_version);
const fixednumber_constructorGuard = {};
const fixednumber_Zero = bignumber_BigNumber.from(0);
const fixednumber_NegativeOne = bignumber_BigNumber.from(-1);
function fixednumber_throwFault(message, fault, operation, value) {
const params = { fault: fault, operation: operation };
if (value !== undefined) {
params.value = value;
}
return fixednumber_logger.throwError(message, lib_esm_Logger.errors.NUMERIC_FAULT, params);
}
// Constant to pull zeros from for multipliers
let zeros = "0";
while (zeros.length < 256) {
zeros += zeros;
}
// Returns a string "1" followed by decimal "0"s
function getMultiplier(decimals) {
if (typeof (decimals) !== "number") {
try {
decimals = bignumber_BigNumber.from(decimals).toNumber();
}
catch (e) { }
}
if (typeof (decimals) === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) {
return ("1" + zeros.substring(0, decimals));
}
return fixednumber_logger.throwArgumentError("invalid decimal size", "decimals", decimals);
}
function formatFixed(value, decimals) {
if (decimals == null) {
decimals = 0;
}
const multiplier = getMultiplier(decimals);
// Make sure wei is a big number (convert as necessary)
value = bignumber_BigNumber.from(value);
const negative = value.lt(fixednumber_Zero);
if (negative) {
value = value.mul(fixednumber_NegativeOne);
}
let fraction = value.mod(multiplier).toString();
while (fraction.length < multiplier.length - 1) {
fraction = "0" + fraction;
}
// Strip training 0
fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
const whole = value.div(multiplier).toString();
if (multiplier.length === 1) {
value = whole;
}
else {
value = whole + "." + fraction;
}
if (negative) {
value = "-" + value;
}
return value;
}
function parseFixed(value, decimals) {
if (decimals == null) {
decimals = 0;
}
const multiplier = getMultiplier(decimals);
if (typeof (value) !== "string" || !value.match(/^-?[0-9.]+$/)) {
fixednumber_logger.throwArgumentError("invalid decimal value", "value", value);
}
// Is it negative?
const negative = (value.substring(0, 1) === "-");
if (negative) {
value = value.substring(1);
}
if (value === ".") {
fixednumber_logger.throwArgumentError("missing value", "value", value);
}
// Split it into a whole and fractional part
const comps = value.split(".");
if (comps.length > 2) {
fixednumber_logger.throwArgumentError("too many decimal points", "value", value);
}
let whole = comps[0], fraction = comps[1];
if (!whole) {
whole = "0";
}
if (!fraction) {
fraction = "0";
}
// Trim trailing zeros
while (fraction[fraction.length - 1] === "0") {
fraction = fraction.substring(0, fraction.length - 1);
}
// Check the fraction doesn't exceed our decimals size
if (fraction.length > multiplier.length - 1) {
fixednumber_throwFault("fractional component exceeds decimals", "underflow", "parseFixed");
}
// If decimals is 0, we have an empty string for fraction
if (fraction === "") {
fraction = "0";
}
// Fully pad the string with zeros to get to wei
while (fraction.length < multiplier.length - 1) {
fraction += "0";
}
const wholeValue = bignumber_BigNumber.from(whole);
const fractionValue = bignumber_BigNumber.from(fraction);
let wei = (wholeValue.mul(multiplier)).add(fractionValue);
if (negative) {
wei = wei.mul(fixednumber_NegativeOne);
}
return wei;
}
class fixednumber_FixedFormat {
constructor(constructorGuard, signed, width, decimals) {
if (constructorGuard !== fixednumber_constructorGuard) {
fixednumber_logger.throwError("cannot use FixedFormat constructor; use FixedFormat.from", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new FixedFormat"
});
}
this.signed = signed;
this.width = width;
this.decimals = decimals;
this.name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
this._multiplier = getMultiplier(decimals);
Object.freeze(this);
}
static from(value) {
if (value instanceof fixednumber_FixedFormat) {
return value;
}
if (typeof (value) === "number") {
value = `fixed128x${value}`;
}
let signed = true;
let width = 128;
let decimals = 18;
if (typeof (value) === "string") {
if (value === "fixed") {
// defaults...
}
else if (value === "ufixed") {
signed = false;
}
else {
const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
if (!match) {
fixednumber_logger.throwArgumentError("invalid fixed format", "format", value);
}
signed = (match[1] !== "u");
width = parseInt(match[2]);
decimals = parseInt(match[3]);
}
}
else if (value) {
const check = (key, type, defaultValue) => {
if (value[key] == null) {
return defaultValue;
}
if (typeof (value[key]) !== type) {
fixednumber_logger.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]);
}
return value[key];
};
signed = check("signed", "boolean", signed);
width = check("width", "number", width);
decimals = check("decimals", "number", decimals);
}
if (width % 8) {
fixednumber_logger.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width);
}
if (decimals > 80) {
fixednumber_logger.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals);
}
return new fixednumber_FixedFormat(fixednumber_constructorGuard, signed, width, decimals);
}
}
class fixednumber_FixedNumber {
constructor(constructorGuard, hex, value, format) {
if (constructorGuard !== fixednumber_constructorGuard) {
fixednumber_logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new FixedFormat"
});
}
this.format = format;
this._hex = hex;
this._value = value;
this._isFixedNumber = true;
Object.freeze(this);
}
_checkFormat(other) {
if (this.format.name !== other.format.name) {
fixednumber_logger.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other);
}
}
addUnsafe(other) {
this._checkFormat(other);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return fixednumber_FixedNumber.fromValue(a.add(b), this.format.decimals, this.format);
}
subUnsafe(other) {
this._checkFormat(other);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return fixednumber_FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format);
}
mulUnsafe(other) {
this._checkFormat(other);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return fixednumber_FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format);
}
divUnsafe(other) {
this._checkFormat(other);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return fixednumber_FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format);
}
floor() {
const comps = this.toString().split(".");
if (comps.length === 1) {
comps.push("0");
}
let result = fixednumber_FixedNumber.from(comps[0], this.format);
const hasFraction = !comps[1].match(/^(0*)$/);
if (this.isNegative() && hasFraction) {
result = result.subUnsafe(ONE.toFormat(result.format));
}
return result;
}
ceiling() {
const comps = this.toString().split(".");
if (comps.length === 1) {
comps.push("0");
}
let result = fixednumber_FixedNumber.from(comps[0], this.format);
const hasFraction = !comps[1].match(/^(0*)$/);
if (!this.isNegative() && hasFraction) {
result = result.addUnsafe(ONE.toFormat(result.format));
}
return result;
}
// @TODO: Support other rounding algorithms
round(decimals) {
if (decimals == null) {
decimals = 0;
}
// If we are already in range, we're done
const comps = this.toString().split(".");
if (comps.length === 1) {
comps.push("0");
}
if (decimals < 0 || decimals > 80 || (decimals % 1)) {
fixednumber_logger.throwArgumentError("invalid decimal count", "decimals", decimals);
}
if (comps[1].length <= decimals) {
return this;
}
const factor = fixednumber_FixedNumber.from("1" + zeros.substring(0, decimals), this.format);
const bump = BUMP.toFormat(this.format);
return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor);
}
isZero() {
return (this._value === "0.0" || this._value === "0");
}
isNegative() {
return (this._value[0] === "-");
}
toString() { return this._value; }
toHexString(width) {
if (width == null) {
return this._hex;
}
if (width % 8) {
fixednumber_logger.throwArgumentError("invalid byte width", "width", width);
}
const hex = bignumber_BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();
return hexZeroPad(hex, width / 8);
}
toUnsafeFloat() { return parseFloat(this.toString()); }
toFormat(format) {
return fixednumber_FixedNumber.fromString(this._value, format);
}
static fromValue(value, decimals, format) {
// If decimals looks more like a format, and there is no format, shift the parameters
if (format == null && decimals != null && !isBigNumberish(decimals)) {
format = decimals;
decimals = null;
}
if (decimals == null) {
decimals = 0;
}
if (format == null) {
format = "fixed";
}
return fixednumber_FixedNumber.fromString(formatFixed(value, decimals), fixednumber_FixedFormat.from(format));
}
static fromString(value, format) {
if (format == null) {
format = "fixed";
}
const fixedFormat = fixednumber_FixedFormat.from(format);
const numeric = parseFixed(value, fixedFormat.decimals);
if (!fixedFormat.signed && numeric.lt(fixednumber_Zero)) {
fixednumber_throwFault("unsigned value cannot be negative", "overflow", "value", value);
}
let hex = null;
if (fixedFormat.signed) {
hex = numeric.toTwos(fixedFormat.width).toHexString();
}
else {
hex = numeric.toHexString();
hex = hexZeroPad(hex, fixedFormat.width / 8);
}
const decimal = formatFixed(numeric, fixedFormat.decimals);
return new fixednumber_FixedNumber(fixednumber_constructorGuard, hex, decimal, fixedFormat);
}
static fromBytes(value, format) {
if (format == null) {
format = "fixed";
}
const fixedFormat = fixednumber_FixedFormat.from(format);
if (arrayify(value).length > fixedFormat.width / 8) {
throw new Error("overflow");
}
let numeric = bignumber_BigNumber.from(value);
if (fixedFormat.signed) {
numeric = numeric.fromTwos(fixedFormat.width);
}
const hex = numeric.toTwos((fixedFormat.signed ? 0 : 1) + fixedFormat.width).toHexString();
const decimal = formatFixed(numeric, fixedFormat.decimals);
return new fixednumber_FixedNumber(fixednumber_constructorGuard, hex, decimal, fixedFormat);
}
static from(value, format) {
if (typeof (value) === "string") {
return fixednumber_FixedNumber.fromString(value, format);
}
if (isBytes(value)) {
return fixednumber_FixedNumber.fromBytes(value, format);
}
try {
return fixednumber_FixedNumber.fromValue(value, 0, format);
}
catch (error) {
// Allow NUMERIC_FAULT to bubble up
if (error.code !== lib_esm_Logger.errors.INVALID_ARGUMENT) {
throw error;
}
}
return fixednumber_logger.throwArgumentError("invalid FixedNumber value", "value", value);
}
static isFixedNumber(value) {
return !!(value && value._isFixedNumber);
}
}
const ONE = fixednumber_FixedNumber.from(1);
const BUMP = fixednumber_FixedNumber.from("0.5");
//# sourceMappingURL=fixednumber.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/units/lib.esm/_version.js
const units_lib_esm_version_version = "units/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/units/lib.esm/index.js
const units_lib_esm_logger = new lib_esm_Logger(units_lib_esm_version_version);
const lib_esm_names = [
"wei",
"kwei",
"mwei",
"gwei",
"szabo",
"finney",
"ether",
];
// Some environments have issues with RegEx that contain back-tracking, so we cannot
// use them.
function commify(value) {
const comps = String(value).split(".");
if (comps.length > 2 || !comps[0].match(/^-?[0-9]*$/) || (comps[1] && !comps[1].match(/^[0-9]*$/)) || value === "." || value === "-.") {
units_lib_esm_logger.throwArgumentError("invalid value", "value", value);
}
// Make sure we have at least one whole digit (0 if none)
let whole = comps[0];
let negative = "";
if (whole.substring(0, 1) === "-") {
negative = "-";
whole = whole.substring(1);
}
// Make sure we have at least 1 whole digit with no leading zeros
while (whole.substring(0, 1) === "0") {
whole = whole.substring(1);
}
if (whole === "") {
whole = "0";
}
let suffix = "";
if (comps.length === 2) {
suffix = "." + (comps[1] || "0");
}
while (suffix.length > 2 && suffix[suffix.length - 1] === "0") {
suffix = suffix.substring(0, suffix.length - 1);
}
const formatted = [];
while (whole.length) {
if (whole.length <= 3) {
formatted.unshift(whole);
break;
}
else {
const index = whole.length - 3;
formatted.unshift(whole.substring(index));
whole = whole.substring(0, index);
}
}
return negative + formatted.join(",") + suffix;
}
function formatUnits(value, unitName) {
if (typeof (unitName) === "string") {
const index = lib_esm_names.indexOf(unitName);
if (index !== -1) {
unitName = 3 * index;
}
}
return formatFixed(value, (unitName != null) ? unitName : 18);
}
function parseUnits(value, unitName) {
if (typeof (value) !== "string") {
units_lib_esm_logger.throwArgumentError("value must be a string", "value", value);
}
if (typeof (unitName) === "string") {
const index = lib_esm_names.indexOf(unitName);
if (index !== -1) {
unitName = 3 * index;
}
}
return parseFixed(value, (unitName != null) ? unitName : 18);
}
function formatEther(wei) {
return formatUnits(wei, 18);
}
function parseEther(ether) {
return parseUnits(ether, 18);
}
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: ./node_modules/aes-js/index.js
var aes_js = __webpack_require__(5);
var aes_js_default = /*#__PURE__*/__webpack_require__.n(aes_js);
// EXTERNAL MODULE: ./node_modules/scrypt-js/scrypt.js
var scrypt = __webpack_require__(15);
var scrypt_default = /*#__PURE__*/__webpack_require__.n(scrypt);
// CONCATENATED MODULE: ./node_modules/@ethersproject/json-wallets/lib.esm/utils.js
function looseArrayify(hexString) {
if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') {
hexString = '0x' + hexString;
}
return arrayify(hexString);
}
function zpad(value, length) {
value = String(value);
while (value.length < length) {
value = '0' + value;
}
return value;
}
function getPassword(password) {
if (typeof (password) === 'string') {
return toUtf8Bytes(password, UnicodeNormalizationForm.NFKC);
}
return arrayify(password);
}
function searchPath(object, path) {
let currentChild = object;
const comps = path.toLowerCase().split('/');
for (let i = 0; i < comps.length; i++) {
// Search for a child object with a case-insensitive matching key
let matchingChild = null;
for (const key in currentChild) {
if (key.toLowerCase() === comps[i]) {
matchingChild = currentChild[key];
break;
}
}
// Didn't find one. :'(
if (matchingChild === null) {
return null;
}
// Now check this child...
currentChild = matchingChild;
}
return currentChild;
}
// See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
function uuidV4(randomBytes) {
const bytes = arrayify(randomBytes);
// Section: 4.1.3:
// - time_hi_and_version[12:16] = 0b0100
bytes[6] = (bytes[6] & 0x0f) | 0x40;
// Section 4.4
// - clock_seq_hi_and_reserved[6] = 0b0
// - clock_seq_hi_and_reserved[7] = 0b1
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const value = hexlify(bytes);
return [
value.substring(2, 10),
value.substring(10, 14),
value.substring(14, 18),
value.substring(18, 22),
value.substring(22, 34),
].join("-");
}
//# sourceMappingURL=utils.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/json-wallets/lib.esm/_version.js
const json_wallets_lib_esm_version_version = "json-wallets/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/json-wallets/lib.esm/keystore.js
var keystore_awaiter = (undefined && undefined.__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());
});
};
const keystore_logger = new lib_esm_Logger(json_wallets_lib_esm_version_version);
// Exported Types
function hasMnemonic(value) {
return (value != null && value.mnemonic && value.mnemonic.phrase);
}
class keystore_KeystoreAccount extends Description {
isKeystoreAccount(value) {
return !!(value && value._isKeystoreAccount);
}
}
function _decrypt(data, key, ciphertext) {
const cipher = searchPath(data, "crypto/cipher");
if (cipher === "aes-128-ctr") {
const iv = looseArrayify(searchPath(data, "crypto/cipherparams/iv"));
const counter = new aes_js_default.a.Counter(iv);
const aesCtr = new aes_js_default.a.ModeOfOperation.ctr(key, counter);
return arrayify(aesCtr.decrypt(ciphertext));
}
return null;
}
function _getAccount(data, key) {
const ciphertext = looseArrayify(searchPath(data, "crypto/ciphertext"));
const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2);
if (computedMAC !== searchPath(data, "crypto/mac").toLowerCase()) {
throw new Error("invalid password");
}
const privateKey = _decrypt(data, key.slice(0, 16), ciphertext);
if (!privateKey) {
keystore_logger.throwError("unsupported cipher", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "decrypt"
});
}
const mnemonicKey = key.slice(32, 64);
const address = computeAddress(privateKey);
if (data.address) {
let check = data.address.toLowerCase();
if (check.substring(0, 2) !== "0x") {
check = "0x" + check;
}
if (getAddress(check) !== address) {
throw new Error("address mismatch");
}
}
const account = {
_isKeystoreAccount: true,
address: address,
privateKey: hexlify(privateKey)
};
// Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase
if (searchPath(data, "x-ethers/version") === "0.1") {
const mnemonicCiphertext = looseArrayify(searchPath(data, "x-ethers/mnemonicCiphertext"));
const mnemonicIv = looseArrayify(searchPath(data, "x-ethers/mnemonicCounter"));
const mnemonicCounter = new aes_js_default.a.Counter(mnemonicIv);
const mnemonicAesCtr = new aes_js_default.a.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
const path = searchPath(data, "x-ethers/path") || defaultPath;
const locale = searchPath(data, "x-ethers/locale") || "en";
const entropy = arrayify(mnemonicAesCtr.decrypt(mnemonicCiphertext));
try {
const mnemonic = entropyToMnemonic(entropy, locale);
const node = lib_esm_HDNode.fromMnemonic(mnemonic, null, locale).derivePath(path);
if (node.privateKey != account.privateKey) {
throw new Error("mnemonic mismatch");
}
account.mnemonic = node.mnemonic;
}
catch (error) {
// If we don't have the locale wordlist installed to
// read this mnemonic, just bail and don't set the
// mnemonic
if (error.code !== lib_esm_Logger.errors.INVALID_ARGUMENT || error.argument !== "wordlist") {
throw error;
}
}
}
return new keystore_KeystoreAccount(account);
}
function pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc) {
return arrayify(pbkdf2(passwordBytes, salt, count, dkLen, prfFunc));
}
function keystore_pbkdf2(passwordBytes, salt, count, dkLen, prfFunc) {
return Promise.resolve(pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc));
}
function _computeKdfKey(data, password, pbkdf2Func, scryptFunc, progressCallback) {
const passwordBytes = getPassword(password);
const kdf = searchPath(data, "crypto/kdf");
if (kdf && typeof (kdf) === "string") {
const throwError = function (name, value) {
return keystore_logger.throwArgumentError("invalid key-derivation function parameters", name, value);
};
if (kdf.toLowerCase() === "scrypt") {
const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt"));
const N = parseInt(searchPath(data, "crypto/kdfparams/n"));
const r = parseInt(searchPath(data, "crypto/kdfparams/r"));
const p = parseInt(searchPath(data, "crypto/kdfparams/p"));
// Check for all required parameters
if (!N || !r || !p) {
throwError("kdf", kdf);
}
// Make sure N is a power of 2
if ((N & (N - 1)) !== 0) {
throwError("N", N);
}
const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen"));
if (dkLen !== 32) {
throwError("dklen", dkLen);
}
return scryptFunc(passwordBytes, salt, N, r, p, 64, progressCallback);
}
else if (kdf.toLowerCase() === "pbkdf2") {
const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt"));
let prfFunc = null;
const prf = searchPath(data, "crypto/kdfparams/prf");
if (prf === "hmac-sha256") {
prfFunc = "sha256";
}
else if (prf === "hmac-sha512") {
prfFunc = "sha512";
}
else {
throwError("prf", prf);
}
const count = parseInt(searchPath(data, "crypto/kdfparams/c"));
const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen"));
if (dkLen !== 32) {
throwError("dklen", dkLen);
}
return pbkdf2Func(passwordBytes, salt, count, dkLen, prfFunc);
}
}
return keystore_logger.throwArgumentError("unsupported key-derivation function", "kdf", kdf);
}
function decryptSync(json, password) {
const data = JSON.parse(json);
const key = _computeKdfKey(data, password, pbkdf2Sync, scrypt_default.a.syncScrypt);
return _getAccount(data, key);
}
function decrypt(json, password, progressCallback) {
return keystore_awaiter(this, void 0, void 0, function* () {
const data = JSON.parse(json);
const key = yield _computeKdfKey(data, password, keystore_pbkdf2, scrypt_default.a.scrypt, progressCallback);
return _getAccount(data, key);
});
}
function encrypt(account, password, options, progressCallback) {
try {
// Check the address matches the private key
if (getAddress(account.address) !== computeAddress(account.privateKey)) {
throw new Error("address/privateKey mismatch");
}
// Check the mnemonic (if any) matches the private key
if (hasMnemonic(account)) {
const mnemonic = account.mnemonic;
const node = lib_esm_HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || defaultPath);
if (node.privateKey != account.privateKey) {
throw new Error("mnemonic mismatch");
}
}
}
catch (e) {
return Promise.reject(e);
}
// The options are optional, so adjust the call as needed
if (typeof (options) === "function" && !progressCallback) {
progressCallback = options;
options = {};
}
if (!options) {
options = {};
}
const privateKey = arrayify(account.privateKey);
const passwordBytes = getPassword(password);
let entropy = null;
let path = null;
let locale = null;
if (hasMnemonic(account)) {
const srcMnemonic = account.mnemonic;
entropy = arrayify(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en"));
path = srcMnemonic.path || defaultPath;
locale = srcMnemonic.locale || "en";
}
let client = options.client;
if (!client) {
client = "ethers.js";
}
// Check/generate the salt
let salt = null;
if (options.salt) {
salt = arrayify(options.salt);
}
else {
salt = random_randomBytes(32);
;
}
// Override initialization vector
let iv = null;
if (options.iv) {
iv = arrayify(options.iv);
if (iv.length !== 16) {
throw new Error("invalid iv");
}
}
else {
iv = random_randomBytes(16);
}
// Override the uuid
let uuidRandom = null;
if (options.uuid) {
uuidRandom = arrayify(options.uuid);
if (uuidRandom.length !== 16) {
throw new Error("invalid uuid");
}
}
else {
uuidRandom = random_randomBytes(16);
}
// Override the scrypt password-based key derivation function parameters
let N = (1 << 17), r = 8, p = 1;
if (options.scrypt) {
if (options.scrypt.N) {
N = options.scrypt.N;
}
if (options.scrypt.r) {
r = options.scrypt.r;
}
if (options.scrypt.p) {
p = options.scrypt.p;
}
}
// We take 64 bytes:
// - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix)
// - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet)
return scrypt_default.a.scrypt(passwordBytes, salt, N, r, p, 64, progressCallback).then((key) => {
key = arrayify(key);
// This will be used to encrypt the wallet (as per Web3 secret storage)
const derivedKey = key.slice(0, 16);
const macPrefix = key.slice(16, 32);
// This will be used to encrypt the mnemonic phrase (if any)
const mnemonicKey = key.slice(32, 64);
// Encrypt the private key
const counter = new aes_js_default.a.Counter(iv);
const aesCtr = new aes_js_default.a.ModeOfOperation.ctr(derivedKey, counter);
const ciphertext = arrayify(aesCtr.encrypt(privateKey));
// Compute the message authentication code, used to check the password
const mac = keccak256(concat([macPrefix, ciphertext]));
// See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
const data = {
address: account.address.substring(2).toLowerCase(),
id: uuidV4(uuidRandom),
version: 3,
crypto: {
cipher: "aes-128-ctr",
cipherparams: {
iv: hexlify(iv).substring(2),
},
ciphertext: hexlify(ciphertext).substring(2),
kdf: "scrypt",
kdfparams: {
salt: hexlify(salt).substring(2),
n: N,
dklen: 32,
p: p,
r: r
},
mac: mac.substring(2)
}
};
// If we have a mnemonic, encrypt it into the JSON wallet
if (entropy) {
const mnemonicIv = random_randomBytes(16);
const mnemonicCounter = new aes_js_default.a.Counter(mnemonicIv);
const mnemonicAesCtr = new aes_js_default.a.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
const mnemonicCiphertext = arrayify(mnemonicAesCtr.encrypt(entropy));
const now = new Date();
const timestamp = (now.getUTCFullYear() + "-" +
zpad(now.getUTCMonth() + 1, 2) + "-" +
zpad(now.getUTCDate(), 2) + "T" +
zpad(now.getUTCHours(), 2) + "-" +
zpad(now.getUTCMinutes(), 2) + "-" +
zpad(now.getUTCSeconds(), 2) + ".0Z");
data["x-ethers"] = {
client: client,
gethFilename: ("UTC--" + timestamp + "--" + data.address),
mnemonicCounter: hexlify(mnemonicIv).substring(2),
mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2),
path: path,
locale: locale,
version: "0.1"
};
}
return JSON.stringify(data);
});
}
//# sourceMappingURL=keystore.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/json-wallets/lib.esm/crowdsale.js
const crowdsale_logger = new lib_esm_Logger(json_wallets_lib_esm_version_version);
class crowdsale_CrowdsaleAccount extends Description {
isCrowdsaleAccount(value) {
return !!(value && value._isCrowdsaleAccount);
}
}
// See: https://github.com/ethereum/pyethsaletool
function crowdsale_decrypt(json, password) {
const data = JSON.parse(json);
password = getPassword(password);
// Ethereum Address
const ethaddr = getAddress(searchPath(data, "ethaddr"));
// Encrypted Seed
const encseed = looseArrayify(searchPath(data, "encseed"));
if (!encseed || (encseed.length % 16) !== 0) {
crowdsale_logger.throwArgumentError("invalid encseed", "json", json);
}
const key = arrayify(pbkdf2(password, password, 2000, 32, "sha256")).slice(0, 16);
const iv = encseed.slice(0, 16);
const encryptedSeed = encseed.slice(16);
// Decrypt the seed
const aesCbc = new aes_js_default.a.ModeOfOperation.cbc(key, iv);
const seed = aes_js_default.a.padding.pkcs7.strip(arrayify(aesCbc.decrypt(encryptedSeed)));
// This wallet format is weird... Convert the binary encoded hex to a string.
let seedHex = "";
for (let i = 0; i < seed.length; i++) {
seedHex += String.fromCharCode(seed[i]);
}
const seedHexBytes = toUtf8Bytes(seedHex);
const privateKey = keccak256(seedHexBytes);
return new crowdsale_CrowdsaleAccount({
_isCrowdsaleAccount: true,
address: ethaddr,
privateKey: privateKey
});
}
//# sourceMappingURL=crowdsale.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/json-wallets/lib.esm/index.js
function decryptJsonWallet(json, password, progressCallback) {
if (isCrowdsaleWallet(json)) {
if (progressCallback) {
progressCallback(0);
}
const account = crowdsale_decrypt(json, password);
if (progressCallback) {
progressCallback(1);
}
return Promise.resolve(account);
}
if (isKeystoreWallet(json)) {
return decrypt(json, password, progressCallback);
}
return Promise.reject(new Error("invalid JSON wallet"));
}
function decryptJsonWalletSync(json, password) {
if (isCrowdsaleWallet(json)) {
return crowdsale_decrypt(json, password);
}
if (isKeystoreWallet(json)) {
return decryptSync(json, password);
}
throw new Error("invalid JSON wallet");
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/wallet/lib.esm/_version.js
const wallet_lib_esm_version_version = "wallet/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/wallet/lib.esm/index.js
var wallet_lib_esm_awaiter = (undefined && undefined.__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());
});
};
const wallet_lib_esm_logger = new lib_esm_Logger(wallet_lib_esm_version_version);
function isAccount(value) {
return (value != null && isHexString(value.privateKey, 32) && value.address != null);
}
function lib_esm_hasMnemonic(value) {
const mnemonic = value.mnemonic;
return (mnemonic && mnemonic.phrase);
}
class lib_esm_Wallet extends lib_esm_Signer {
constructor(privateKey, provider) {
super();
if (isAccount(privateKey)) {
const signingKey = new lib_esm_SigningKey(privateKey.privateKey);
defineReadOnly(this, "_signingKey", () => signingKey);
defineReadOnly(this, "address", computeAddress(this.publicKey));
if (this.address !== getAddress(privateKey.address)) {
wallet_lib_esm_logger.throwArgumentError("privateKey/address mismatch", "privateKey", "[REDACTED]");
}
if (lib_esm_hasMnemonic(privateKey)) {
const srcMnemonic = privateKey.mnemonic;
defineReadOnly(this, "_mnemonic", () => ({
phrase: srcMnemonic.phrase,
path: srcMnemonic.path || defaultPath,
locale: srcMnemonic.locale || "en"
}));
const mnemonic = this.mnemonic;
const node = lib_esm_HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path);
if (computeAddress(node.privateKey) !== this.address) {
wallet_lib_esm_logger.throwArgumentError("mnemonic/address mismatch", "privateKey", "[REDACTED]");
}
}
else {
defineReadOnly(this, "_mnemonic", () => null);
}
}
else {
if (lib_esm_SigningKey.isSigningKey(privateKey)) {
/* istanbul ignore if */
if (privateKey.curve !== "secp256k1") {
wallet_lib_esm_logger.throwArgumentError("unsupported curve; must be secp256k1", "privateKey", "[REDACTED]");
}
defineReadOnly(this, "_signingKey", () => privateKey);
}
else {
// A lot of common tools do not prefix private keys with a 0x (see: #1166)
if (typeof (privateKey) === "string") {
if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) {
privateKey = "0x" + privateKey;
}
}
const signingKey = new lib_esm_SigningKey(privateKey);
defineReadOnly(this, "_signingKey", () => signingKey);
}
defineReadOnly(this, "_mnemonic", () => null);
defineReadOnly(this, "address", computeAddress(this.publicKey));
}
/* istanbul ignore if */
if (provider && !lib_esm_Provider.isProvider(provider)) {
wallet_lib_esm_logger.throwArgumentError("invalid provider", "provider", provider);
}
defineReadOnly(this, "provider", provider || null);
}
get mnemonic() { return this._mnemonic(); }
get privateKey() { return this._signingKey().privateKey; }
get publicKey() { return this._signingKey().publicKey; }
getAddress() {
return Promise.resolve(this.address);
}
connect(provider) {
return new lib_esm_Wallet(this, provider);
}
signTransaction(transaction) {
return resolveProperties(transaction).then((tx) => {
if (tx.from != null) {
if (getAddress(tx.from) !== this.address) {
wallet_lib_esm_logger.throwArgumentError("transaction from address mismatch", "transaction.from", transaction.from);
}
delete tx.from;
}
const signature = this._signingKey().signDigest(keccak256(lib_esm_serialize(tx)));
return lib_esm_serialize(tx, signature);
});
}
signMessage(message) {
return wallet_lib_esm_awaiter(this, void 0, void 0, function* () {
return joinSignature(this._signingKey().signDigest(hashMessage(message)));
});
}
_signTypedData(domain, types, value) {
return wallet_lib_esm_awaiter(this, void 0, void 0, function* () {
// Populate any ENS names
const populated = yield typed_data_TypedDataEncoder.resolveNames(domain, types, value, (name) => {
if (this.provider == null) {
wallet_lib_esm_logger.throwError("cannot resolve ENS names without a provider", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "resolveName",
value: name
});
}
return this.provider.resolveName(name);
});
return joinSignature(this._signingKey().signDigest(typed_data_TypedDataEncoder.hash(populated.domain, types, populated.value)));
});
}
encrypt(password, options, progressCallback) {
if (typeof (options) === "function" && !progressCallback) {
progressCallback = options;
options = {};
}
if (progressCallback && typeof (progressCallback) !== "function") {
throw new Error("invalid callback");
}
if (!options) {
options = {};
}
return encrypt(this, password, options, progressCallback);
}
/**
* Static methods to create Wallet instances.
*/
static createRandom(options) {
let entropy = random_randomBytes(16);
if (!options) {
options = {};
}
if (options.extraEntropy) {
entropy = arrayify(hexDataSlice(keccak256(concat([entropy, options.extraEntropy])), 0, 16));
}
const mnemonic = entropyToMnemonic(entropy, options.locale);
return lib_esm_Wallet.fromMnemonic(mnemonic, options.path, options.locale);
}
static fromEncryptedJson(json, password, progressCallback) {
return decryptJsonWallet(json, password, progressCallback).then((account) => {
return new lib_esm_Wallet(account);
});
}
static fromEncryptedJsonSync(json, password) {
return new lib_esm_Wallet(decryptJsonWalletSync(json, password));
}
static fromMnemonic(mnemonic, path, wordlist) {
if (!path) {
path = defaultPath;
}
return new lib_esm_Wallet(lib_esm_HDNode.fromMnemonic(mnemonic, null, wordlist).derivePath(path));
}
}
function verifyMessage(message, signature) {
return recoverAddress(hashMessage(message), signature);
}
function verifyTypedData(domain, types, value, signature) {
return recoverAddress(typed_data_TypedDataEncoder.hash(domain, types, value), signature);
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/utils.js
////////////////////////
// Enums
////////////////////////
// Exports
//# sourceMappingURL=utils.js.map
// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/_version.js
const ethers_lib_esm_version_version = "ethers/5.7.2";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/ethers/lib.esm/ethers.js
////////////////////////
// Compile-Time Constants
// This is generated by "npm run dist"
const ethers_logger = new lib_esm_Logger(ethers_lib_esm_version_version);
////////////////////////
// Exports
//# sourceMappingURL=ethers.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/contracts/lib.esm/_version.js
const contracts_lib_esm_version_version = "contracts/5.7.0";
//# sourceMappingURL=_version.js.map
// CONCATENATED MODULE: ./node_modules/@ethersproject/contracts/lib.esm/index.js
var contracts_lib_esm_awaiter = (undefined && undefined.__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());
});
};
const contracts_lib_esm_logger = new lib_esm_Logger(contracts_lib_esm_version_version);
;
;
///////////////////////////////
const contracts_lib_esm_allowedTransactionKeys = {
chainId: true, data: true, from: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true,
type: true, accessList: true,
maxFeePerGas: true, maxPriorityFeePerGas: true,
customData: true,
ccipReadEnabled: true
};
function lib_esm_resolveName(resolver, nameOrPromise) {
return contracts_lib_esm_awaiter(this, void 0, void 0, function* () {
const name = yield nameOrPromise;
if (typeof (name) !== "string") {
contracts_lib_esm_logger.throwArgumentError("invalid address or ENS name", "name", name);
}
// If it is already an address, just use it (after adding checksum)
try {
return getAddress(name);
}
catch (error) { }
if (!resolver) {
contracts_lib_esm_logger.throwError("a provider or signer is needed to resolve ENS names", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "resolveName"
});
}
const address = yield resolver.resolveName(name);
if (address == null) {
contracts_lib_esm_logger.throwArgumentError("resolver or addr is not configured for ENS name", "name", name);
}
return address;
});
}
// Recursively replaces ENS names with promises to resolve the name and resolves all properties
function resolveAddresses(resolver, value, paramType) {
return contracts_lib_esm_awaiter(this, void 0, void 0, function* () {
if (Array.isArray(paramType)) {
return yield Promise.all(paramType.map((paramType, index) => {
return resolveAddresses(resolver, ((Array.isArray(value)) ? value[index] : value[paramType.name]), paramType);
}));
}
if (paramType.type === "address") {
return yield lib_esm_resolveName(resolver, value);
}
if (paramType.type === "tuple") {
return yield resolveAddresses(resolver, value, paramType.components);
}
if (paramType.baseType === "array") {
if (!Array.isArray(value)) {
return Promise.reject(contracts_lib_esm_logger.makeError("invalid value for array", lib_esm_Logger.errors.INVALID_ARGUMENT, {
argument: "value",
value
}));
}
return yield Promise.all(value.map((v) => resolveAddresses(resolver, v, paramType.arrayChildren)));
}
return value;
});
}
function populateTransaction(contract, fragment, args) {
return contracts_lib_esm_awaiter(this, void 0, void 0, function* () {
// If an extra argument is given, it is overrides
let overrides = {};
if (args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object") {
overrides = shallowCopy(args.pop());
}
// Make sure the parameter count matches
contracts_lib_esm_logger.checkArgumentCount(args.length, fragment.inputs.length, "passed to contract");
// Populate "from" override (allow promises)
if (contract.signer) {
if (overrides.from) {
// Contracts with a Signer are from the Signer's frame-of-reference;
// but we allow overriding "from" if it matches the signer
overrides.from = resolveProperties({
override: lib_esm_resolveName(contract.signer, overrides.from),
signer: contract.signer.getAddress()
}).then((check) => contracts_lib_esm_awaiter(this, void 0, void 0, function* () {
if (getAddress(check.signer) !== check.override) {
contracts_lib_esm_logger.throwError("Contract with a Signer cannot override from", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "overrides.from"
});
}
return check.override;
}));
}
else {
overrides.from = contract.signer.getAddress();
}
}
else if (overrides.from) {
overrides.from = lib_esm_resolveName(contract.provider, overrides.from);
//} else {
// Contracts without a signer can override "from", and if
// unspecified the zero address is used
//overrides.from = AddressZero;
}
// Wait for all dependencies to be resolved (prefer the signer over the provider)
const resolved = yield resolveProperties({
args: resolveAddresses(contract.signer || contract.provider, args, fragment.inputs),
address: contract.resolvedAddress,
overrides: (resolveProperties(overrides) || {})
});
// The ABI coded transaction
const data = contract.interface.encodeFunctionData(fragment, resolved.args);
const tx = {
data: data,
to: resolved.address
};
// Resolved Overrides
const ro = resolved.overrides;
// Populate simple overrides
if (ro.nonce != null) {
tx.nonce = bignumber_BigNumber.from(ro.nonce).toNumber();
}
if (ro.gasLimit != null) {
tx.gasLimit = bignumber_BigNumber.from(ro.gasLimit);
}
if (ro.gasPrice != null) {
tx.gasPrice = bignumber_BigNumber.from(ro.gasPrice);
}
if (ro.maxFeePerGas != null) {
tx.maxFeePerGas = bignumber_BigNumber.from(ro.maxFeePerGas);
}
if (ro.maxPriorityFeePerGas != null) {
tx.maxPriorityFeePerGas = bignumber_BigNumber.from(ro.maxPriorityFeePerGas);
}
if (ro.from != null) {
tx.from = ro.from;
}
if (ro.type != null) {
tx.type = ro.type;
}
if (ro.accessList != null) {
tx.accessList = accessListify(ro.accessList);
}
// If there was no "gasLimit" override, but the ABI specifies a default, use it
if (tx.gasLimit == null && fragment.gas != null) {
// Compute the intrinsic gas cost for this transaction
// @TODO: This is based on the yellow paper as of Petersburg; this is something
// we may wish to parameterize in v6 as part of the Network object. Since this
// is always a non-nil to address, we can ignore G_create, but may wish to add
// similar logic to the ContractFactory.
let intrinsic = 21000;
const bytes = arrayify(data);
for (let i = 0; i < bytes.length; i++) {
intrinsic += 4;
if (bytes[i]) {
intrinsic += 64;
}
}
tx.gasLimit = bignumber_BigNumber.from(fragment.gas).add(intrinsic);
}
// Populate "value" override
if (ro.value) {
const roValue = bignumber_BigNumber.from(ro.value);
if (!roValue.isZero() && !fragment.payable) {
contracts_lib_esm_logger.throwError("non-payable method cannot override value", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "overrides.value",
value: overrides.value
});
}
tx.value = roValue;
}
if (ro.customData) {
tx.customData = shallowCopy(ro.customData);
}
if (ro.ccipReadEnabled) {
tx.ccipReadEnabled = !!ro.ccipReadEnabled;
}
// Remove the overrides
delete overrides.nonce;
delete overrides.gasLimit;
delete overrides.gasPrice;
delete overrides.from;
delete overrides.value;
delete overrides.type;
delete overrides.accessList;
delete overrides.maxFeePerGas;
delete overrides.maxPriorityFeePerGas;
delete overrides.customData;
delete overrides.ccipReadEnabled;
// Make sure there are no stray overrides, which may indicate a
// typo or using an unsupported key.
const leftovers = Object.keys(overrides).filter((key) => (overrides[key] != null));
if (leftovers.length) {
contracts_lib_esm_logger.throwError(`cannot override ${leftovers.map((l) => JSON.stringify(l)).join(",")}`, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "overrides",
overrides: leftovers
});
}
return tx;
});
}
function buildPopulate(contract, fragment) {
return function (...args) {
return populateTransaction(contract, fragment, args);
};
}
function buildEstimate(contract, fragment) {
const signerOrProvider = (contract.signer || contract.provider);
return function (...args) {
return contracts_lib_esm_awaiter(this, void 0, void 0, function* () {
if (!signerOrProvider) {
contracts_lib_esm_logger.throwError("estimate require a provider or signer", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "estimateGas"
});
}
const tx = yield populateTransaction(contract, fragment, args);
return yield signerOrProvider.estimateGas(tx);
});
};
}
function addContractWait(contract, tx) {
const wait = tx.wait.bind(tx);
tx.wait = (confirmations) => {
return wait(confirmations).then((receipt) => {
receipt.events = receipt.logs.map((log) => {
let event = deepCopy(log);
let parsed = null;
try {
parsed = contract.interface.parseLog(log);
}
catch (e) { }
// Successfully parsed the event log; include it
if (parsed) {
event.args = parsed.args;
event.decode = (data, topics) => {
return contract.interface.decodeEventLog(parsed.eventFragment, data, topics);
};
event.event = parsed.name;
event.eventSignature = parsed.signature;
}
// Useful operations
event.removeListener = () => { return contract.provider; };
event.getBlock = () => {
return contract.provider.getBlock(receipt.blockHash);
};
event.getTransaction = () => {
return contract.provider.getTransaction(receipt.transactionHash);
};
event.getTransactionReceipt = () => {
return Promise.resolve(receipt);
};
return event;
});
return receipt;
});
};
}
function buildCall(contract, fragment, collapseSimple) {
const signerOrProvider = (contract.signer || contract.provider);
return function (...args) {
return contracts_lib_esm_awaiter(this, void 0, void 0, function* () {
// Extract the "blockTag" override if present
let blockTag = undefined;
if (args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object") {
const overrides = shallowCopy(args.pop());
if (overrides.blockTag != null) {
blockTag = yield overrides.blockTag;
}
delete overrides.blockTag;
args.push(overrides);
}
// If the contract was just deployed, wait until it is mined
if (contract.deployTransaction != null) {
yield contract._deployed(blockTag);
}
// Call a node and get the result
const tx = yield populateTransaction(contract, fragment, args);
const result = yield signerOrProvider.call(tx, blockTag);
try {
let value = contract.interface.decodeFunctionResult(fragment, result);
if (collapseSimple && fragment.outputs.length === 1) {
value = value[0];
}
return value;
}
catch (error) {
if (error.code === lib_esm_Logger.errors.CALL_EXCEPTION) {
error.address = contract.address;
error.args = args;
error.transaction = tx;
}
throw error;
}
});
};
}
function buildSend(contract, fragment) {
return function (...args) {
return contracts_lib_esm_awaiter(this, void 0, void 0, function* () {
if (!contract.signer) {
contracts_lib_esm_logger.throwError("sending a transaction requires a signer", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "sendTransaction"
});
}
// If the contract was just deployed, wait until it is mined
if (contract.deployTransaction != null) {
yield contract._deployed();
}
const txRequest = yield populateTransaction(contract, fragment, args);
const tx = yield contract.signer.sendTransaction(txRequest);
// Tweak the tx.wait so the receipt has extra properties
addContractWait(contract, tx);
return tx;
});
};
}
function buildDefault(contract, fragment, collapseSimple) {
if (fragment.constant) {
return buildCall(contract, fragment, collapseSimple);
}
return buildSend(contract, fragment);
}
function lib_esm_getEventTag(filter) {
if (filter.address && (filter.topics == null || filter.topics.length === 0)) {
return "*";
}
return (filter.address || "*") + "@" + (filter.topics ? filter.topics.map((topic) => {
if (Array.isArray(topic)) {
return topic.join("|");
}
return topic;
}).join(":") : "");
}
class lib_esm_RunningEvent {
constructor(tag, filter) {
defineReadOnly(this, "tag", tag);
defineReadOnly(this, "filter", filter);
this._listeners = [];
}
addListener(listener, once) {
this._listeners.push({ listener: listener, once: once });
}
removeListener(listener) {
let done = false;
this._listeners = this._listeners.filter((item) => {
if (done || item.listener !== listener) {
return true;
}
done = true;
return false;
});
}
removeAllListeners() {
this._listeners = [];
}
listeners() {
return this._listeners.map((i) => i.listener);
}
listenerCount() {
return this._listeners.length;
}
run(args) {
const listenerCount = this.listenerCount();
this._listeners = this._listeners.filter((item) => {
const argsCopy = args.slice();
// Call the callback in the next event loop
setTimeout(() => {
item.listener.apply(this, argsCopy);
}, 0);
// Reschedule it if it not "once"
return !(item.once);
});
return listenerCount;
}
prepareEvent(event) {
}
// Returns the array that will be applied to an emit
getEmit(event) {
return [event];
}
}
class ErrorRunningEvent extends lib_esm_RunningEvent {
constructor() {
super("error", null);
}
}
// @TODO Fragment should inherit Wildcard? and just override getEmit?
// or have a common abstract super class, with enough constructor
// options to configure both.
// A Fragment Event will populate all the properties that Wildcard
// will, and additionally dereference the arguments when emitting
class lib_esm_FragmentRunningEvent extends lib_esm_RunningEvent {
constructor(address, contractInterface, fragment, topics) {
const filter = {
address: address
};
let topic = contractInterface.getEventTopic(fragment);
if (topics) {
if (topic !== topics[0]) {
contracts_lib_esm_logger.throwArgumentError("topic mismatch", "topics", topics);
}
filter.topics = topics.slice();
}
else {
filter.topics = [topic];
}
super(lib_esm_getEventTag(filter), filter);
defineReadOnly(this, "address", address);
defineReadOnly(this, "interface", contractInterface);
defineReadOnly(this, "fragment", fragment);
}
prepareEvent(event) {
super.prepareEvent(event);
event.event = this.fragment.name;
event.eventSignature = this.fragment.format();
event.decode = (data, topics) => {
return this.interface.decodeEventLog(this.fragment, data, topics);
};
try {
event.args = this.interface.decodeEventLog(this.fragment, event.data, event.topics);
}
catch (error) {
event.args = null;
event.decodeError = error;
}
}
getEmit(event) {
const errors = checkResultErrors(event.args);
if (errors.length) {
throw errors[0].error;
}
const args = (event.args || []).slice();
args.push(event);
return args;
}
}
// A Wildcard Event will attempt to populate:
// - event The name of the event name
// - eventSignature The full signature of the event
// - decode A function to decode data and topics
// - args The decoded data and topics
class lib_esm_WildcardRunningEvent extends lib_esm_RunningEvent {
constructor(address, contractInterface) {
super("*", { address: address });
defineReadOnly(this, "address", address);
defineReadOnly(this, "interface", contractInterface);
}
prepareEvent(event) {
super.prepareEvent(event);
try {
const parsed = this.interface.parseLog(event);
event.event = parsed.name;
event.eventSignature = parsed.signature;
event.decode = (data, topics) => {
return this.interface.decodeEventLog(parsed.eventFragment, data, topics);
};
event.args = parsed.args;
}
catch (error) {
// No matching event
}
}
}
class lib_esm_BaseContract {
constructor(addressOrName, contractInterface, signerOrProvider) {
// @TODO: Maybe still check the addressOrName looks like a valid address or name?
//address = getAddress(address);
defineReadOnly(this, "interface", getStatic(new.target, "getInterface")(contractInterface));
if (signerOrProvider == null) {
defineReadOnly(this, "provider", null);
defineReadOnly(this, "signer", null);
}
else if (lib_esm_Signer.isSigner(signerOrProvider)) {
defineReadOnly(this, "provider", signerOrProvider.provider || null);
defineReadOnly(this, "signer", signerOrProvider);
}
else if (lib_esm_Provider.isProvider(signerOrProvider)) {
defineReadOnly(this, "provider", signerOrProvider);
defineReadOnly(this, "signer", null);
}
else {
contracts_lib_esm_logger.throwArgumentError("invalid signer or provider", "signerOrProvider", signerOrProvider);
}
defineReadOnly(this, "callStatic", {});
defineReadOnly(this, "estimateGas", {});
defineReadOnly(this, "functions", {});
defineReadOnly(this, "populateTransaction", {});
defineReadOnly(this, "filters", {});
{
const uniqueFilters = {};
Object.keys(this.interface.events).forEach((eventSignature) => {
const event = this.interface.events[eventSignature];
defineReadOnly(this.filters, eventSignature, (...args) => {
return {
address: this.address,
topics: this.interface.encodeFilterTopics(event, args)
};
});
if (!uniqueFilters[event.name]) {
uniqueFilters[event.name] = [];
}
uniqueFilters[event.name].push(eventSignature);
});
Object.keys(uniqueFilters).forEach((name) => {
const filters = uniqueFilters[name];
if (filters.length === 1) {
defineReadOnly(this.filters, name, this.filters[filters[0]]);
}
else {
contracts_lib_esm_logger.warn(`Duplicate definition of ${name} (${filters.join(", ")})`);
}
});
}
defineReadOnly(this, "_runningEvents", {});
defineReadOnly(this, "_wrappedEmits", {});
if (addressOrName == null) {
contracts_lib_esm_logger.throwArgumentError("invalid contract address or ENS name", "addressOrName", addressOrName);
}
defineReadOnly(this, "address", addressOrName);
if (this.provider) {
defineReadOnly(this, "resolvedAddress", lib_esm_resolveName(this.provider, addressOrName));
}
else {
try {
defineReadOnly(this, "resolvedAddress", Promise.resolve(getAddress(addressOrName)));
}
catch (error) {
// Without a provider, we cannot use ENS names
contracts_lib_esm_logger.throwError("provider is required to use ENS name as contract address", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new Contract"
});
}
}
// Swallow bad ENS names to prevent Unhandled Exceptions
this.resolvedAddress.catch((e) => { });
const uniqueNames = {};
const uniqueSignatures = {};
Object.keys(this.interface.functions).forEach((signature) => {
const fragment = this.interface.functions[signature];
// Check that the signature is unique; if not the ABI generation has
// not been cleaned or may be incorrectly generated
if (uniqueSignatures[signature]) {
contracts_lib_esm_logger.warn(`Duplicate ABI entry for ${JSON.stringify(signature)}`);
return;
}
uniqueSignatures[signature] = true;
// Track unique names; we only expose bare named functions if they
// are ambiguous
{
const name = fragment.name;
if (!uniqueNames[`%${name}`]) {
uniqueNames[`%${name}`] = [];
}
uniqueNames[`%${name}`].push(signature);
}
if (this[signature] == null) {
defineReadOnly(this, signature, buildDefault(this, fragment, true));
}
// We do not collapse simple calls on this bucket, which allows
// frameworks to safely use this without introspection as well as
// allows decoding error recovery.
if (this.functions[signature] == null) {
defineReadOnly(this.functions, signature, buildDefault(this, fragment, false));
}
if (this.callStatic[signature] == null) {
defineReadOnly(this.callStatic, signature, buildCall(this, fragment, true));
}
if (this.populateTransaction[signature] == null) {
defineReadOnly(this.populateTransaction, signature, buildPopulate(this, fragment));
}
if (this.estimateGas[signature] == null) {
defineReadOnly(this.estimateGas, signature, buildEstimate(this, fragment));
}
});
Object.keys(uniqueNames).forEach((name) => {
// Ambiguous names to not get attached as bare names
const signatures = uniqueNames[name];
if (signatures.length > 1) {
return;
}
// Strip off the leading "%" used for prototype protection
name = name.substring(1);
const signature = signatures[0];
// If overwriting a member property that is null, swallow the error
try {
if (this[name] == null) {
defineReadOnly(this, name, this[signature]);
}
}
catch (e) { }
if (this.functions[name] == null) {
defineReadOnly(this.functions, name, this.functions[signature]);
}
if (this.callStatic[name] == null) {
defineReadOnly(this.callStatic, name, this.callStatic[signature]);
}
if (this.populateTransaction[name] == null) {
defineReadOnly(this.populateTransaction, name, this.populateTransaction[signature]);
}
if (this.estimateGas[name] == null) {
defineReadOnly(this.estimateGas, name, this.estimateGas[signature]);
}
});
}
static getContractAddress(transaction) {
return getContractAddress(transaction);
}
static getInterface(contractInterface) {
if (interface_Interface.isInterface(contractInterface)) {
return contractInterface;
}
return new interface_Interface(contractInterface);
}
// @TODO: Allow timeout?
deployed() {
return this._deployed();
}
_deployed(blockTag) {
if (!this._deployedPromise) {
// If we were just deployed, we know the transaction we should occur in
if (this.deployTransaction) {
this._deployedPromise = this.deployTransaction.wait().then(() => {
return this;
});
}
else {
// @TODO: Once we allow a timeout to be passed in, we will wait
// up to that many blocks for getCode
// Otherwise, poll for our code to be deployed
this._deployedPromise = this.provider.getCode(this.address, blockTag).then((code) => {
if (code === "0x") {
contracts_lib_esm_logger.throwError("contract not deployed", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
contractAddress: this.address,
operation: "getDeployed"
});
}
return this;
});
}
}
return this._deployedPromise;
}
// @TODO:
// estimateFallback(overrides?: TransactionRequest): Promise<BigNumber>
// @TODO:
// estimateDeploy(bytecode: string, ...args): Promise<BigNumber>
fallback(overrides) {
if (!this.signer) {
contracts_lib_esm_logger.throwError("sending a transactions require a signer", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { operation: "sendTransaction(fallback)" });
}
const tx = shallowCopy(overrides || {});
["from", "to"].forEach(function (key) {
if (tx[key] == null) {
return;
}
contracts_lib_esm_logger.throwError("cannot override " + key, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { operation: key });
});
tx.to = this.resolvedAddress;
return this.deployed().then(() => {
return this.signer.sendTransaction(tx);
});
}
// Reconnect to a different signer or provider
connect(signerOrProvider) {
if (typeof (signerOrProvider) === "string") {
signerOrProvider = new lib_esm_VoidSigner(signerOrProvider, this.provider);
}
const contract = new (this.constructor)(this.address, this.interface, signerOrProvider);
if (this.deployTransaction) {
defineReadOnly(contract, "deployTransaction", this.deployTransaction);
}
return contract;
}
// Re-attach to a different on-chain instance of this contract
attach(addressOrName) {
return new (this.constructor)(addressOrName, this.interface, this.signer || this.provider);
}
static isIndexed(value) {
return interface_Indexed.isIndexed(value);
}
_normalizeRunningEvent(runningEvent) {
// Already have an instance of this event running; we can re-use it
if (this._runningEvents[runningEvent.tag]) {
return this._runningEvents[runningEvent.tag];
}
return runningEvent;
}
_getRunningEvent(eventName) {
if (typeof (eventName) === "string") {
// Listen for "error" events (if your contract has an error event, include
// the full signature to bypass this special event keyword)
if (eventName === "error") {
return this._normalizeRunningEvent(new ErrorRunningEvent());
}
// Listen for any event that is registered
if (eventName === "event") {
return this._normalizeRunningEvent(new lib_esm_RunningEvent("event", null));
}
// Listen for any event
if (eventName === "*") {
return this._normalizeRunningEvent(new lib_esm_WildcardRunningEvent(this.address, this.interface));
}
// Get the event Fragment (throws if ambiguous/unknown event)
const fragment = this.interface.getEvent(eventName);
return this._normalizeRunningEvent(new lib_esm_FragmentRunningEvent(this.address, this.interface, fragment));
}
// We have topics to filter by...
if (eventName.topics && eventName.topics.length > 0) {
// Is it a known topichash? (throws if no matching topichash)
try {
const topic = eventName.topics[0];
if (typeof (topic) !== "string") {
throw new Error("invalid topic"); // @TODO: May happen for anonymous events
}
const fragment = this.interface.getEvent(topic);
return this._normalizeRunningEvent(new lib_esm_FragmentRunningEvent(this.address, this.interface, fragment, eventName.topics));
}
catch (error) { }
// Filter by the unknown topichash
const filter = {
address: this.address,
topics: eventName.topics
};
return this._normalizeRunningEvent(new lib_esm_RunningEvent(lib_esm_getEventTag(filter), filter));
}
return this._normalizeRunningEvent(new lib_esm_WildcardRunningEvent(this.address, this.interface));
}
_checkRunningEvents(runningEvent) {
if (runningEvent.listenerCount() === 0) {
delete this._runningEvents[runningEvent.tag];
// If we have a poller for this, remove it
const emit = this._wrappedEmits[runningEvent.tag];
if (emit && runningEvent.filter) {
this.provider.off(runningEvent.filter, emit);
delete this._wrappedEmits[runningEvent.tag];
}
}
}
// Subclasses can override this to gracefully recover
// from parse errors if they wish
_wrapEvent(runningEvent, log, listener) {
const event = deepCopy(log);
event.removeListener = () => {
if (!listener) {
return;
}
runningEvent.removeListener(listener);
this._checkRunningEvents(runningEvent);
};
event.getBlock = () => { return this.provider.getBlock(log.blockHash); };
event.getTransaction = () => { return this.provider.getTransaction(log.transactionHash); };
event.getTransactionReceipt = () => { return this.provider.getTransactionReceipt(log.transactionHash); };
// This may throw if the topics and data mismatch the signature
runningEvent.prepareEvent(event);
return event;
}
_addEventListener(runningEvent, listener, once) {
if (!this.provider) {
contracts_lib_esm_logger.throwError("events require a provider or a signer with a provider", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { operation: "once" });
}
runningEvent.addListener(listener, once);
// Track this running event and its listeners (may already be there; but no hard in updating)
this._runningEvents[runningEvent.tag] = runningEvent;
// If we are not polling the provider, start polling
if (!this._wrappedEmits[runningEvent.tag]) {
const wrappedEmit = (log) => {
let event = this._wrapEvent(runningEvent, log, listener);
// Try to emit the result for the parameterized event...
if (event.decodeError == null) {
try {
const args = runningEvent.getEmit(event);
this.emit(runningEvent.filter, ...args);
}
catch (error) {
event.decodeError = error.error;
}
}
// Always emit "event" for fragment-base events
if (runningEvent.filter != null) {
this.emit("event", event);
}
// Emit "error" if there was an error
if (event.decodeError != null) {
this.emit("error", event.decodeError, event);
}
};
this._wrappedEmits[runningEvent.tag] = wrappedEmit;
// Special events, like "error" do not have a filter
if (runningEvent.filter != null) {
this.provider.on(runningEvent.filter, wrappedEmit);
}
}
}
queryFilter(event, fromBlockOrBlockhash, toBlock) {
const runningEvent = this._getRunningEvent(event);
const filter = shallowCopy(runningEvent.filter);
if (typeof (fromBlockOrBlockhash) === "string" && isHexString(fromBlockOrBlockhash, 32)) {
if (toBlock != null) {
contracts_lib_esm_logger.throwArgumentError("cannot specify toBlock with blockhash", "toBlock", toBlock);
}
filter.blockHash = fromBlockOrBlockhash;
}
else {
filter.fromBlock = ((fromBlockOrBlockhash != null) ? fromBlockOrBlockhash : 0);
filter.toBlock = ((toBlock != null) ? toBlock : "latest");
}
return this.provider.getLogs(filter).then((logs) => {
return logs.map((log) => this._wrapEvent(runningEvent, log, null));
});
}
on(event, listener) {
this._addEventListener(this._getRunningEvent(event), listener, false);
return this;
}
once(event, listener) {
this._addEventListener(this._getRunningEvent(event), listener, true);
return this;
}
emit(eventName, ...args) {
if (!this.provider) {
return false;
}
const runningEvent = this._getRunningEvent(eventName);
const result = (runningEvent.run(args) > 0);
// May have drained all the "once" events; check for living events
this._checkRunningEvents(runningEvent);
return result;
}
listenerCount(eventName) {
if (!this.provider) {
return 0;
}
if (eventName == null) {
return Object.keys(this._runningEvents).reduce((accum, key) => {
return accum + this._runningEvents[key].listenerCount();
}, 0);
}
return this._getRunningEvent(eventName).listenerCount();
}
listeners(eventName) {
if (!this.provider) {
return [];
}
if (eventName == null) {
const result = [];
for (let tag in this._runningEvents) {
this._runningEvents[tag].listeners().forEach((listener) => {
result.push(listener);
});
}
return result;
}
return this._getRunningEvent(eventName).listeners();
}
removeAllListeners(eventName) {
if (!this.provider) {
return this;
}
if (eventName == null) {
for (const tag in this._runningEvents) {
const runningEvent = this._runningEvents[tag];
runningEvent.removeAllListeners();
this._checkRunningEvents(runningEvent);
}
return this;
}
// Delete any listeners
const runningEvent = this._getRunningEvent(eventName);
runningEvent.removeAllListeners();
this._checkRunningEvents(runningEvent);
return this;
}
off(eventName, listener) {
if (!this.provider) {
return this;
}
const runningEvent = this._getRunningEvent(eventName);
runningEvent.removeListener(listener);
this._checkRunningEvents(runningEvent);
return this;
}
removeListener(eventName, listener) {
return this.off(eventName, listener);
}
}
class Contract extends lib_esm_BaseContract {
}
class lib_esm_ContractFactory {
constructor(contractInterface, bytecode, signer) {
let bytecodeHex = null;
if (typeof (bytecode) === "string") {
bytecodeHex = bytecode;
}
else if (isBytes(bytecode)) {
bytecodeHex = hexlify(bytecode);
}
else if (bytecode && typeof (bytecode.object) === "string") {
// Allow the bytecode object from the Solidity compiler
bytecodeHex = bytecode.object;
}
else {
// Crash in the next verification step
bytecodeHex = "!";
}
// Make sure it is 0x prefixed
if (bytecodeHex.substring(0, 2) !== "0x") {
bytecodeHex = "0x" + bytecodeHex;
}
// Make sure the final result is valid bytecode
if (!isHexString(bytecodeHex) || (bytecodeHex.length % 2)) {
contracts_lib_esm_logger.throwArgumentError("invalid bytecode", "bytecode", bytecode);
}
// If we have a signer, make sure it is valid
if (signer && !lib_esm_Signer.isSigner(signer)) {
contracts_lib_esm_logger.throwArgumentError("invalid signer", "signer", signer);
}
defineReadOnly(this, "bytecode", bytecodeHex);
defineReadOnly(this, "interface", getStatic(new.target, "getInterface")(contractInterface));
defineReadOnly(this, "signer", signer || null);
}
// @TODO: Future; rename to populateTransaction?
getDeployTransaction(...args) {
let tx = {};
// If we have 1 additional argument, we allow transaction overrides
if (args.length === this.interface.deploy.inputs.length + 1 && typeof (args[args.length - 1]) === "object") {
tx = shallowCopy(args.pop());
for (const key in tx) {
if (!contracts_lib_esm_allowedTransactionKeys[key]) {
throw new Error("unknown transaction override " + key);
}
}
}
// Do not allow these to be overridden in a deployment transaction
["data", "from", "to"].forEach((key) => {
if (tx[key] == null) {
return;
}
contracts_lib_esm_logger.throwError("cannot override " + key, lib_esm_Logger.errors.UNSUPPORTED_OPERATION, { operation: key });
});
if (tx.value) {
const value = bignumber_BigNumber.from(tx.value);
if (!value.isZero() && !this.interface.deploy.payable) {
contracts_lib_esm_logger.throwError("non-payable constructor cannot override value", lib_esm_Logger.errors.UNSUPPORTED_OPERATION, {
operation: "overrides.value",
value: tx.value
});
}
}
// Make sure the call matches the constructor signature
contracts_lib_esm_logger.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor");
// Set the data to the bytecode + the encoded constructor arguments
tx.data = hexlify(concat([
this.bytecode,
this.interface.encodeDeploy(args)
]));
return tx;
}
deploy(...args) {
return contracts_lib_esm_awaiter(this, void 0, void 0, function* () {
let overrides = {};
// If 1 extra parameter was passed in, it contains overrides
if (args.length === this.interface.deploy.inputs.length + 1) {
overrides = args.pop();
}
// Make sure the call matches the constructor signature
contracts_lib_esm_logger.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor");
// Resolve ENS names and promises in the arguments
const params = yield resolveAddresses(this.signer, args, this.interface.deploy.inputs);
params.push(overrides);
// Get the deployment transaction (with optional overrides)
const unsignedTx = this.getDeployTransaction(...params);
// Send the deployment transaction
const tx = yield this.signer.sendTransaction(unsignedTx);
const address = getStatic(this.constructor, "getContractAddress")(tx);
const contract = getStatic(this.constructor, "getContract")(address, this.interface, this.signer);
// Add the modified wait that wraps events
addContractWait(contract, tx);
defineReadOnly(contract, "deployTransaction", tx);
return contract;
});
}
attach(address) {
return (this.constructor).getContract(address, this.interface, this.signer);
}
connect(signer) {
return new (this.constructor)(this.interface, this.bytecode, signer);
}
static fromSolidity(compilerOutput, signer) {
if (compilerOutput == null) {
contracts_lib_esm_logger.throwError("missing compiler output", lib_esm_Logger.errors.MISSING_ARGUMENT, { argument: "compilerOutput" });
}
if (typeof (compilerOutput) === "string") {
compilerOutput = JSON.parse(compilerOutput);
}
const abi = compilerOutput.abi;
let bytecode = null;
if (compilerOutput.bytecode) {
bytecode = compilerOutput.bytecode;
}
else if (compilerOutput.evm && compilerOutput.evm.bytecode) {
bytecode = compilerOutput.evm.bytecode;
}
return new this(abi, bytecode, signer);
}
static getInterface(contractInterface) {
return Contract.getInterface(contractInterface);
}
static getContractAddress(tx) {
return getContractAddress(tx);
}
static getContract(address, contractInterface, signer) {
return new Contract(address, contractInterface, signer);
}
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./assets/services/utilities.js
const ZERO_ELEMENT = 0
function getBatches(array, batchSize) {
const batches = []
while (array.length) {
batches.push(array.splice(ZERO_ELEMENT, batchSize))
}
return batches
}
async function sleep(ms) {
return await new Promise((resolve) => setTimeout(resolve, ms))
}
// CONCATENATED MODULE: ./assets/services/batch.js
class batch_BatchEventsService {
constructor({
provider,
contract,
concurrencySize = 10,
blocksPerRequest = 2000,
shouldRetry = true,
retryMax = 5,
retryOn = 500,
}) {
this.provider = provider;
this.contract = contract;
this.concurrencySize = concurrencySize;
this.blocksPerRequest = blocksPerRequest;
this.shouldRetry = shouldRetry;
this.retryMax = retryMax;
this.retryOn = retryOn;
}
async getPastEvents({ fromBlock, toBlock, type }) {
let err;
let retries = 0;
// eslint-disable-next-line no-unmodified-loop-condition
while ((!this.shouldRetry && retries === 0) || (this.shouldRetry && retries < this.retryMax)) {
try {
return (await this.contract.queryFilter(type, fromBlock, toBlock));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e) {
err = e;
retries++;
// If provider.getBlockNumber returned last block that isn't accepted (happened on Avalanche/Gnosis),
// get events to last accepted block
if (e.message.includes('after last accepted block')) {
const acceptedBlock = parseInt(e.message.split('after last accepted block ')[1]);
toBlock = acceptedBlock;
}
// retry on 0.5 seconds
await sleep(this.retryOn);
}
}
throw err;
}
createBatchRequest(batchArray) {
return batchArray.map(async (event, index) => {
await sleep(20 * index);
return this.getPastEvents(event);
});
}
async getBatchEvents({ fromBlock, toBlock, type = '*' }) {
if (!toBlock) {
toBlock = await this.provider.getBlockNumber();
}
const eventsToSync = [];
for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) {
const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1;
eventsToSync.push({ fromBlock: i, toBlock: j, type });
}
const events = [];
const eventChunk = getBatches(eventsToSync, this.concurrencySize);
let chunkCount = 0;
for (const chunk of eventChunk) {
chunkCount++;
const fetchedEvents = (await Promise.all(this.createBatchRequest(chunk))).flat();
events.push(...fetchedEvents);
}
return events;
}
}
// EXTERNAL MODULE: ./node_modules/lodash/lodash.js
var lodash = __webpack_require__(14);
// CONCATENATED MODULE: ./node_modules/@apollo/client/node_modules/tslib/tslib.es6.js
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
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);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(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);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
function __runInitializers(thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
function __propKey(x) {
return typeof x === "symbol" ? x : "".concat(x);
};
function __setFunctionName(f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function tslib_es6_awaiter(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());
});
}
function __generator(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 (g && (g = 0, op[0] && (_ = 0)), _) 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 __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(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.");
}
function __read(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;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
function __classPrivateFieldIn(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object") throw new TypeError("Object expected.");
var dispose;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
}
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function __disposeResources(env) {
function fail(e) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
catch (e) {
fail(e);
}
}
if (env.hasError) throw env.error;
}
return next();
}
/* harmony default export */ var tslib_es6 = ({
__extends,
__assign,
__rest,
__decorate,
__param,
__metadata,
__awaiter: tslib_es6_awaiter,
__generator,
__createBinding,
__exportStar,
__values,
__read,
__spread,
__spreadArrays,
__spreadArray,
__await,
__asyncGenerator,
__asyncDelegator,
__asyncValues,
__makeTemplateObject,
__importStar,
__importDefault,
__classPrivateFieldGet,
__classPrivateFieldSet,
__classPrivateFieldIn,
__addDisposableResource,
__disposeResources,
});
// CONCATENATED MODULE: ./node_modules/ts-invariant/node_modules/tslib/tslib.es6.js
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var tslib_es6_extendStatics = function(d, b) {
tslib_es6_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 tslib_es6_extendStatics(d, b);
};
function tslib_es6_extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
tslib_es6_extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var tslib_es6_assign = function() {
tslib_es6_assign = Object.assign || function __assign(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 tslib_es6_assign.apply(this, arguments);
}
function tslib_es6_rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function tslib_es6_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function tslib_es6_param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function tslib_es6_esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
function tslib_es6_runInitializers(thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
function tslib_es6_propKey(x) {
return typeof x === "symbol" ? x : "".concat(x);
};
function tslib_es6_setFunctionName(f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
function tslib_es6_metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function tslib_tslib_es6_awaiter(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());
});
}
function tslib_es6_generator(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 (g && (g = 0, op[0] && (_ = 0)), _) 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 tslib_es6_createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function tslib_es6_exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) tslib_es6_createBinding(o, m, p);
}
function tslib_es6_values(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.");
}
function tslib_es6_read(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;
}
/** @deprecated */
function tslib_es6_spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(tslib_es6_read(arguments[i]));
return ar;
}
/** @deprecated */
function tslib_es6_spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function tslib_es6_spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function tslib_es6_await(v) {
return this instanceof tslib_es6_await ? (this.v = v, this) : new tslib_es6_await(v);
}
function tslib_es6_asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof tslib_es6_await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function tslib_es6_asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: tslib_es6_await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}
function tslib_es6_asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof tslib_es6_values === "function" ? tslib_es6_values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function tslib_es6_makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var tslib_es6_setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function tslib_es6_importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) tslib_es6_createBinding(result, mod, k);
tslib_es6_setModuleDefault(result, mod);
return result;
}
function tslib_es6_importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function tslib_es6_classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function tslib_es6_classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
function tslib_es6_classPrivateFieldIn(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
}
function tslib_es6_addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object") throw new TypeError("Object expected.");
var dispose;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
}
var tslib_es6_SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function tslib_es6_disposeResources(env) {
function fail(e) {
env.error = env.hasError ? new tslib_es6_SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
catch (e) {
fail(e);
}
}
if (env.hasError) throw env.error;
}
return next();
}
/* harmony default export */ var tslib_tslib_es6 = ({
__extends: tslib_es6_extends,
__assign: tslib_es6_assign,
__rest: tslib_es6_rest,
__decorate: tslib_es6_decorate,
__param: tslib_es6_param,
__metadata: tslib_es6_metadata,
__awaiter: tslib_tslib_es6_awaiter,
__generator: tslib_es6_generator,
__createBinding: tslib_es6_createBinding,
__exportStar: tslib_es6_exportStar,
__values: tslib_es6_values,
__read: tslib_es6_read,
__spread: tslib_es6_spread,
__spreadArrays: tslib_es6_spreadArrays,
__spreadArray: tslib_es6_spreadArray,
__await: tslib_es6_await,
__asyncGenerator: tslib_es6_asyncGenerator,
__asyncDelegator: tslib_es6_asyncDelegator,
__asyncValues: tslib_es6_asyncValues,
__makeTemplateObject: tslib_es6_makeTemplateObject,
__importStar: tslib_es6_importStar,
__importDefault: tslib_es6_importDefault,
__classPrivateFieldGet: tslib_es6_classPrivateFieldGet,
__classPrivateFieldSet: tslib_es6_classPrivateFieldSet,
__classPrivateFieldIn: tslib_es6_classPrivateFieldIn,
__addDisposableResource: tslib_es6_addDisposableResource,
__disposeResources: tslib_es6_disposeResources,
});
// CONCATENATED MODULE: ./node_modules/ts-invariant/lib/invariant.js
var genericMessage = "Invariant Violation";
var invariant_a = Object.setPrototypeOf, setPrototypeOf = invariant_a === void 0 ? function (obj, proto) {
obj.__proto__ = proto;
return obj;
} : invariant_a;
var invariant_InvariantError = /** @class */ (function (_super) {
tslib_es6_extends(InvariantError, _super);
function InvariantError(message) {
if (message === void 0) { message = genericMessage; }
var _this = _super.call(this, typeof message === "number"
? genericMessage + ": " + message + " (see https://github.com/apollographql/invariant-packages)"
: message) || this;
_this.framesToPop = 1;
_this.name = genericMessage;
setPrototypeOf(_this, InvariantError.prototype);
return _this;
}
return InvariantError;
}(Error));
function invariant(condition, message) {
if (!condition) {
throw new invariant_InvariantError(message);
}
}
var verbosityLevels = ["debug", "log", "warn", "error", "silent"];
var verbosityLevel = verbosityLevels.indexOf("log");
function wrapConsoleMethod(name) {
return function () {
if (verbosityLevels.indexOf(name) >= verbosityLevel) {
// Default to console.log if this host environment happens not to provide
// all the console.* methods we need.
var method = console[name] || console.log;
return method.apply(console, arguments);
}
};
}
(function (invariant) {
invariant.debug = wrapConsoleMethod("debug");
invariant.log = wrapConsoleMethod("log");
invariant.warn = wrapConsoleMethod("warn");
invariant.error = wrapConsoleMethod("error");
})(invariant || (invariant = {}));
function setVerbosity(level) {
var old = verbosityLevels[verbosityLevel];
verbosityLevel = Math.max(0, verbosityLevels.indexOf(level));
return old;
}
/* harmony default export */ var lib_invariant = (invariant);
//# sourceMappingURL=invariant.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/globals/maybe.js
function maybe(thunk) {
try {
return thunk();
}
catch (_a) { }
}
//# sourceMappingURL=maybe.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/globals/global.js
/* harmony default export */ var globals_global = (maybe(function () { return globalThis; }) ||
maybe(function () { return window; }) ||
maybe(function () { return self; }) ||
maybe(function () { return global; }) || maybe(function () { return maybe.constructor("return this")(); }));
//# sourceMappingURL=global.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/globals/DEV.js
var DEV_ = "__";
var GLOBAL_KEY = [DEV_, DEV_].join("DEV");
function getDEV() {
try {
return Boolean(__DEV__);
}
catch (_a) {
Object.defineProperty(globals_global, GLOBAL_KEY, {
value: maybe(function () { return "production"; }) !== "production",
enumerable: false,
configurable: true,
writable: true,
});
return globals_global[GLOBAL_KEY];
}
}
/* harmony default export */ var DEV = (getDEV());
//# sourceMappingURL=DEV.js.map
// CONCATENATED MODULE: ./node_modules/ts-invariant/process/index.js
function process_maybe(thunk) {
try { return thunk() } catch (_) {}
}
var safeGlobal = (
process_maybe(function() { return globalThis }) ||
process_maybe(function() { return window }) ||
process_maybe(function() { return self }) ||
process_maybe(function() { return global }) ||
// We don't expect the Function constructor ever to be invoked at runtime, as
// long as at least one of globalThis, window, self, or global is defined, so
// we are under no obligation to make it easy for static analysis tools to
// detect syntactic usage of the Function constructor. If you think you can
// improve your static analysis to detect this obfuscation, think again. This
// is an arms race you cannot win, at least not in JavaScript.
process_maybe(function() { return process_maybe.constructor("return this")() })
);
var needToRemove = false;
function install() {
if (safeGlobal &&
!process_maybe(function() { return "production" }) &&
!process_maybe(function() { return process })) {
Object.defineProperty(safeGlobal, "process", {
value: {
env: {
// This default needs to be "production" instead of "development", to
// avoid the problem https://github.com/graphql/graphql-js/pull/2894
// will eventually solve, once merged and released.
NODE_ENV: "production",
},
},
// Let anyone else change global.process as they see fit, but hide it from
// Object.keys(global) enumeration.
configurable: true,
enumerable: false,
writable: true,
});
needToRemove = true;
}
}
// Call install() at least once, when this module is imported.
install();
function remove() {
if (needToRemove) {
delete safeGlobal.process;
needToRemove = false;
}
}
// CONCATENATED MODULE: ./node_modules/graphql/polyfills/symbols.mjs
// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator != null ? Symbol.iterator : '@@iterator'; // In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
var SYMBOL_ASYNC_ITERATOR = typeof Symbol === 'function' && Symbol.asyncIterator != null ? Symbol.asyncIterator : '@@asyncIterator'; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
var SYMBOL_TO_STRING_TAG = typeof Symbol === 'function' && Symbol.toStringTag != null ? Symbol.toStringTag : '@@toStringTag';
// CONCATENATED MODULE: ./node_modules/graphql/jsutils/nodejsCustomInspectSymbol.mjs
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;
/* harmony default export */ var jsutils_nodejsCustomInspectSymbol = (nodejsCustomInspectSymbol);
// CONCATENATED MODULE: ./node_modules/graphql/jsutils/inspect.mjs
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* eslint-disable flowtype/no-weak-types */
var MAX_ARRAY_LENGTH = 10;
var MAX_RECURSIVE_DEPTH = 2;
/**
* Used to print values in error messages.
*/
function inspect(value) {
return formatValue(value, []);
}
function formatValue(value, seenValues) {
switch (_typeof(value)) {
case 'string':
return JSON.stringify(value);
case 'function':
return value.name ? "[function ".concat(value.name, "]") : '[function]';
case 'object':
if (value === null) {
return 'null';
}
return formatObjectValue(value, seenValues);
default:
return String(value);
}
}
function formatObjectValue(value, previouslySeenValues) {
if (previouslySeenValues.indexOf(value) !== -1) {
return '[Circular]';
}
var seenValues = [].concat(previouslySeenValues, [value]);
var customInspectFn = getCustomFn(value);
if (customInspectFn !== undefined) {
var customValue = customInspectFn.call(value); // check for infinite recursion
if (customValue !== value) {
return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);
}
} else if (Array.isArray(value)) {
return formatArray(value, seenValues);
}
return formatObject(value, seenValues);
}
function formatObject(object, seenValues) {
var keys = Object.keys(object);
if (keys.length === 0) {
return '{}';
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return '[' + getObjectTag(object) + ']';
}
var properties = keys.map(function (key) {
var value = formatValue(object[key], seenValues);
return key + ': ' + value;
});
return '{ ' + properties.join(', ') + ' }';
}
function formatArray(array, seenValues) {
if (array.length === 0) {
return '[]';
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return '[Array]';
}
var len = Math.min(MAX_ARRAY_LENGTH, array.length);
var remaining = array.length - len;
var items = [];
for (var i = 0; i < len; ++i) {
items.push(formatValue(array[i], seenValues));
}
if (remaining === 1) {
items.push('... 1 more item');
} else if (remaining > 1) {
items.push("... ".concat(remaining, " more items"));
}
return '[' + items.join(', ') + ']';
}
function getCustomFn(object) {
var customInspectFn = object[String(jsutils_nodejsCustomInspectSymbol)];
if (typeof customInspectFn === 'function') {
return customInspectFn;
}
if (typeof object.inspect === 'function') {
return object.inspect;
}
}
function getObjectTag(object) {
var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, '');
if (tag === 'Object' && typeof object.constructor === 'function') {
var name = object.constructor.name;
if (typeof name === 'string' && name !== '') {
return name;
}
}
return tag;
}
// CONCATENATED MODULE: ./node_modules/graphql/jsutils/devAssert.mjs
function devAssert(condition, message) {
var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')
if (!booleanCondition) {
throw new Error(message);
}
}
// CONCATENATED MODULE: ./node_modules/graphql/jsutils/instanceOf.mjs
function instanceOf_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { instanceOf_typeof = function _typeof(obj) { return typeof obj; }; } else { instanceOf_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return instanceOf_typeof(obj); }
/**
* A replacement for instanceof which includes an error warning when multi-realm
* constructors are detected.
*/
// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
// See: https://webpack.js.org/guides/production/
/* harmony default export */ var instanceOf = ( true ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
// eslint-disable-next-line no-shadow
function instanceOf(value, constructor) {
return value instanceof constructor;
} : // eslint-disable-next-line no-shadow
undefined);
// CONCATENATED MODULE: ./node_modules/graphql/language/source.mjs
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* A representation of source input to GraphQL. The `name` and `locationOffset` parameters are
* optional, but they are useful for clients who store GraphQL documents in source files.
* For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might
* be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`.
* The `line` and `column` properties in `locationOffset` are 1-indexed.
*/
var source_Source = /*#__PURE__*/function () {
function Source(body) {
var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GraphQL request';
var locationOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
line: 1,
column: 1
};
typeof body === 'string' || devAssert(0, "Body must be a string. Received: ".concat(inspect(body), "."));
this.body = body;
this.name = name;
this.locationOffset = locationOffset;
this.locationOffset.line > 0 || devAssert(0, 'line in locationOffset is 1-indexed and must be positive.');
this.locationOffset.column > 0 || devAssert(0, 'column in locationOffset is 1-indexed and must be positive.');
} // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
_createClass(Source, [{
key: SYMBOL_TO_STRING_TAG,
get: function get() {
return 'Source';
}
}]);
return Source;
}();
/**
* Test if the given value is a Source object.
*
* @internal
*/
// eslint-disable-next-line no-redeclare
function isSource(source) {
return instanceOf(source, source_Source);
}
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/globals/fix-graphql.js
function removeTemporaryGlobals() {
return typeof source_Source === "function" ? remove() : remove();
}
//# sourceMappingURL=fix-graphql.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/globals/index.js
function checkDEV() {
__DEV__ ? invariant("boolean" === typeof DEV, DEV) : invariant("boolean" === typeof DEV, 39);
}
removeTemporaryGlobals();
checkDEV();
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/zen-observable-ts/module.js
function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function module_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function module_createClass(Constructor, protoProps, staticProps) { if (protoProps) module_defineProperties(Constructor.prototype, protoProps); if (staticProps) module_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
// === Symbol Support ===
var hasSymbols = function () {
return typeof Symbol === 'function';
};
var hasSymbol = function (name) {
return hasSymbols() && Boolean(Symbol[name]);
};
var getSymbol = function (name) {
return hasSymbol(name) ? Symbol[name] : '@@' + name;
};
if (hasSymbols() && !hasSymbol('observable')) {
Symbol.observable = Symbol('observable');
}
var SymbolIterator = getSymbol('iterator');
var SymbolObservable = getSymbol('observable');
var SymbolSpecies = getSymbol('species'); // === Abstract Operations ===
function getMethod(obj, key) {
var value = obj[key];
if (value == null) return undefined;
if (typeof value !== 'function') throw new TypeError(value + ' is not a function');
return value;
}
function getSpecies(obj) {
var ctor = obj.constructor;
if (ctor !== undefined) {
ctor = ctor[SymbolSpecies];
if (ctor === null) {
ctor = undefined;
}
}
return ctor !== undefined ? ctor : Observable;
}
function isObservable(x) {
return x instanceof Observable; // SPEC: Brand check
}
function hostReportError(e) {
if (hostReportError.log) {
hostReportError.log(e);
} else {
setTimeout(function () {
throw e;
});
}
}
function enqueue(fn) {
Promise.resolve().then(function () {
try {
fn();
} catch (e) {
hostReportError(e);
}
});
}
function cleanupSubscription(subscription) {
var cleanup = subscription._cleanup;
if (cleanup === undefined) return;
subscription._cleanup = undefined;
if (!cleanup) {
return;
}
try {
if (typeof cleanup === 'function') {
cleanup();
} else {
var unsubscribe = getMethod(cleanup, 'unsubscribe');
if (unsubscribe) {
unsubscribe.call(cleanup);
}
}
} catch (e) {
hostReportError(e);
}
}
function closeSubscription(subscription) {
subscription._observer = undefined;
subscription._queue = undefined;
subscription._state = 'closed';
}
function flushSubscription(subscription) {
var queue = subscription._queue;
if (!queue) {
return;
}
subscription._queue = undefined;
subscription._state = 'ready';
for (var i = 0; i < queue.length; ++i) {
notifySubscription(subscription, queue[i].type, queue[i].value);
if (subscription._state === 'closed') break;
}
}
function notifySubscription(subscription, type, value) {
subscription._state = 'running';
var observer = subscription._observer;
try {
var m = getMethod(observer, type);
switch (type) {
case 'next':
if (m) m.call(observer, value);
break;
case 'error':
closeSubscription(subscription);
if (m) m.call(observer, value);else throw value;
break;
case 'complete':
closeSubscription(subscription);
if (m) m.call(observer);
break;
}
} catch (e) {
hostReportError(e);
}
if (subscription._state === 'closed') cleanupSubscription(subscription);else if (subscription._state === 'running') subscription._state = 'ready';
}
function onNotify(subscription, type, value) {
if (subscription._state === 'closed') return;
if (subscription._state === 'buffering') {
subscription._queue.push({
type: type,
value: value
});
return;
}
if (subscription._state !== 'ready') {
subscription._state = 'buffering';
subscription._queue = [{
type: type,
value: value
}];
enqueue(function () {
return flushSubscription(subscription);
});
return;
}
notifySubscription(subscription, type, value);
}
var Subscription = /*#__PURE__*/function () {
function Subscription(observer, subscriber) {
// ASSERT: observer is an object
// ASSERT: subscriber is callable
this._cleanup = undefined;
this._observer = observer;
this._queue = undefined;
this._state = 'initializing';
var subscriptionObserver = new SubscriptionObserver(this);
try {
this._cleanup = subscriber.call(undefined, subscriptionObserver);
} catch (e) {
subscriptionObserver.error(e);
}
if (this._state === 'initializing') this._state = 'ready';
}
var _proto = Subscription.prototype;
_proto.unsubscribe = function unsubscribe() {
if (this._state !== 'closed') {
closeSubscription(this);
cleanupSubscription(this);
}
};
module_createClass(Subscription, [{
key: "closed",
get: function () {
return this._state === 'closed';
}
}]);
return Subscription;
}();
var SubscriptionObserver = /*#__PURE__*/function () {
function SubscriptionObserver(subscription) {
this._subscription = subscription;
}
var _proto2 = SubscriptionObserver.prototype;
_proto2.next = function next(value) {
onNotify(this._subscription, 'next', value);
};
_proto2.error = function error(value) {
onNotify(this._subscription, 'error', value);
};
_proto2.complete = function complete() {
onNotify(this._subscription, 'complete');
};
module_createClass(SubscriptionObserver, [{
key: "closed",
get: function () {
return this._subscription._state === 'closed';
}
}]);
return SubscriptionObserver;
}();
var Observable = /*#__PURE__*/function () {
function Observable(subscriber) {
if (!(this instanceof Observable)) throw new TypeError('Observable cannot be called as a function');
if (typeof subscriber !== 'function') throw new TypeError('Observable initializer must be a function');
this._subscriber = subscriber;
}
var _proto3 = Observable.prototype;
_proto3.subscribe = function subscribe(observer) {
if (typeof observer !== 'object' || observer === null) {
observer = {
next: observer,
error: arguments[1],
complete: arguments[2]
};
}
return new Subscription(observer, this._subscriber);
};
_proto3.forEach = function forEach(fn) {
var _this = this;
return new Promise(function (resolve, reject) {
if (typeof fn !== 'function') {
reject(new TypeError(fn + ' is not a function'));
return;
}
function done() {
subscription.unsubscribe();
resolve();
}
var subscription = _this.subscribe({
next: function (value) {
try {
fn(value, done);
} catch (e) {
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
};
_proto3.map = function map(fn) {
var _this2 = this;
if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');
var C = getSpecies(this);
return new C(function (observer) {
return _this2.subscribe({
next: function (value) {
try {
value = fn(value);
} catch (e) {
return observer.error(e);
}
observer.next(value);
},
error: function (e) {
observer.error(e);
},
complete: function () {
observer.complete();
}
});
});
};
_proto3.filter = function filter(fn) {
var _this3 = this;
if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');
var C = getSpecies(this);
return new C(function (observer) {
return _this3.subscribe({
next: function (value) {
try {
if (!fn(value)) return;
} catch (e) {
return observer.error(e);
}
observer.next(value);
},
error: function (e) {
observer.error(e);
},
complete: function () {
observer.complete();
}
});
});
};
_proto3.reduce = function reduce(fn) {
var _this4 = this;
if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');
var C = getSpecies(this);
var hasSeed = arguments.length > 1;
var hasValue = false;
var seed = arguments[1];
var acc = seed;
return new C(function (observer) {
return _this4.subscribe({
next: function (value) {
var first = !hasValue;
hasValue = true;
if (!first || hasSeed) {
try {
acc = fn(acc, value);
} catch (e) {
return observer.error(e);
}
} else {
acc = value;
}
},
error: function (e) {
observer.error(e);
},
complete: function () {
if (!hasValue && !hasSeed) return observer.error(new TypeError('Cannot reduce an empty sequence'));
observer.next(acc);
observer.complete();
}
});
});
};
_proto3.concat = function concat() {
var _this5 = this;
for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {
sources[_key] = arguments[_key];
}
var C = getSpecies(this);
return new C(function (observer) {
var subscription;
var index = 0;
function startNext(next) {
subscription = next.subscribe({
next: function (v) {
observer.next(v);
},
error: function (e) {
observer.error(e);
},
complete: function () {
if (index === sources.length) {
subscription = undefined;
observer.complete();
} else {
startNext(C.from(sources[index++]));
}
}
});
}
startNext(_this5);
return function () {
if (subscription) {
subscription.unsubscribe();
subscription = undefined;
}
};
});
};
_proto3.flatMap = function flatMap(fn) {
var _this6 = this;
if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');
var C = getSpecies(this);
return new C(function (observer) {
var subscriptions = [];
var outer = _this6.subscribe({
next: function (value) {
if (fn) {
try {
value = fn(value);
} catch (e) {
return observer.error(e);
}
}
var inner = C.from(value).subscribe({
next: function (value) {
observer.next(value);
},
error: function (e) {
observer.error(e);
},
complete: function () {
var i = subscriptions.indexOf(inner);
if (i >= 0) subscriptions.splice(i, 1);
completeIfDone();
}
});
subscriptions.push(inner);
},
error: function (e) {
observer.error(e);
},
complete: function () {
completeIfDone();
}
});
function completeIfDone() {
if (outer.closed && subscriptions.length === 0) observer.complete();
}
return function () {
subscriptions.forEach(function (s) {
return s.unsubscribe();
});
outer.unsubscribe();
};
});
};
_proto3[SymbolObservable] = function () {
return this;
};
Observable.from = function from(x) {
var C = typeof this === 'function' ? this : Observable;
if (x == null) throw new TypeError(x + ' is not an object');
var method = getMethod(x, SymbolObservable);
if (method) {
var observable = method.call(x);
if (Object(observable) !== observable) throw new TypeError(observable + ' is not an object');
if (isObservable(observable) && observable.constructor === C) return observable;
return new C(function (observer) {
return observable.subscribe(observer);
});
}
if (hasSymbol('iterator')) {
method = getMethod(x, SymbolIterator);
if (method) {
return new C(function (observer) {
enqueue(function () {
if (observer.closed) return;
for (var _iterator = _createForOfIteratorHelperLoose(method.call(x)), _step; !(_step = _iterator()).done;) {
var item = _step.value;
observer.next(item);
if (observer.closed) return;
}
observer.complete();
});
});
}
}
if (Array.isArray(x)) {
return new C(function (observer) {
enqueue(function () {
if (observer.closed) return;
for (var i = 0; i < x.length; ++i) {
observer.next(x[i]);
if (observer.closed) return;
}
observer.complete();
});
});
}
throw new TypeError(x + ' is not observable');
};
Observable.of = function of() {
for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
items[_key2] = arguments[_key2];
}
var C = typeof this === 'function' ? this : Observable;
return new C(function (observer) {
enqueue(function () {
if (observer.closed) return;
for (var i = 0; i < items.length; ++i) {
observer.next(items[i]);
if (observer.closed) return;
}
observer.complete();
});
});
};
module_createClass(Observable, null, [{
key: SymbolSpecies,
get: function () {
return this;
}
}]);
return Observable;
}();
if (hasSymbols()) {
Object.defineProperty(Observable, Symbol('extensions'), {
value: {
symbol: SymbolObservable,
hostReportError: hostReportError
},
configurable: true
});
}
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/utils/createOperation.js
function createOperation(starting, operation) {
var context = __assign({}, starting);
var setContext = function (next) {
if (typeof next === 'function') {
context = __assign(__assign({}, context), next(context));
}
else {
context = __assign(__assign({}, context), next);
}
};
var getContext = function () { return (__assign({}, context)); };
Object.defineProperty(operation, 'setContext', {
enumerable: false,
value: setContext,
});
Object.defineProperty(operation, 'getContext', {
enumerable: false,
value: getContext,
});
return operation;
}
//# sourceMappingURL=createOperation.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/objects.js
function isNonNullObject(obj) {
return obj !== null && typeof obj === 'object';
}
//# sourceMappingURL=objects.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/graphql/fragments.js
function getFragmentQueryDocument(document, fragmentName) {
var actualFragmentName = fragmentName;
var fragments = [];
document.definitions.forEach(function (definition) {
if (definition.kind === 'OperationDefinition') {
throw __DEV__ ? new invariant_InvariantError("Found a ".concat(definition.operation, " operation").concat(definition.name ? " named '".concat(definition.name.value, "'") : '', ". ") +
'No operations are allowed when using a fragment as a query. Only fragments are allowed.') : new invariant_InvariantError(44);
}
if (definition.kind === 'FragmentDefinition') {
fragments.push(definition);
}
});
if (typeof actualFragmentName === 'undefined') {
__DEV__ ? invariant(fragments.length === 1, "Found ".concat(fragments.length, " fragments. `fragmentName` must be provided when there is not exactly 1 fragment.")) : invariant(fragments.length === 1, 45);
actualFragmentName = fragments[0].name.value;
}
var query = __assign(__assign({}, document), { definitions: __spreadArray([
{
kind: 'OperationDefinition',
operation: 'query',
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'FragmentSpread',
name: {
kind: 'Name',
value: actualFragmentName,
},
},
],
},
}
], document.definitions, true) });
return query;
}
function createFragmentMap(fragments) {
if (fragments === void 0) { fragments = []; }
var symTable = {};
fragments.forEach(function (fragment) {
symTable[fragment.name.value] = fragment;
});
return symTable;
}
function getFragmentFromSelection(selection, fragmentMap) {
switch (selection.kind) {
case 'InlineFragment':
return selection;
case 'FragmentSpread': {
var fragmentName = selection.name.value;
if (typeof fragmentMap === "function") {
return fragmentMap(fragmentName);
}
var fragment = fragmentMap && fragmentMap[fragmentName];
__DEV__ ? invariant(fragment, "No fragment named ".concat(fragmentName)) : invariant(fragment, 46);
return fragment || null;
}
default:
return null;
}
}
//# sourceMappingURL=fragments.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/graphql/storeUtils.js
function makeReference(id) {
return { __ref: String(id) };
}
function isReference(obj) {
return Boolean(obj && typeof obj === 'object' && typeof obj.__ref === 'string');
}
function isDocumentNode(value) {
return (isNonNullObject(value) &&
value.kind === "Document" &&
Array.isArray(value.definitions));
}
function isStringValue(value) {
return value.kind === 'StringValue';
}
function isBooleanValue(value) {
return value.kind === 'BooleanValue';
}
function isIntValue(value) {
return value.kind === 'IntValue';
}
function isFloatValue(value) {
return value.kind === 'FloatValue';
}
function isVariable(value) {
return value.kind === 'Variable';
}
function isObjectValue(value) {
return value.kind === 'ObjectValue';
}
function isListValue(value) {
return value.kind === 'ListValue';
}
function isEnumValue(value) {
return value.kind === 'EnumValue';
}
function isNullValue(value) {
return value.kind === 'NullValue';
}
function valueToObjectRepresentation(argObj, name, value, variables) {
if (isIntValue(value) || isFloatValue(value)) {
argObj[name.value] = Number(value.value);
}
else if (isBooleanValue(value) || isStringValue(value)) {
argObj[name.value] = value.value;
}
else if (isObjectValue(value)) {
var nestedArgObj_1 = {};
value.fields.map(function (obj) {
return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables);
});
argObj[name.value] = nestedArgObj_1;
}
else if (isVariable(value)) {
var variableValue = (variables || {})[value.name.value];
argObj[name.value] = variableValue;
}
else if (isListValue(value)) {
argObj[name.value] = value.values.map(function (listValue) {
var nestedArgArrayObj = {};
valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
return nestedArgArrayObj[name.value];
});
}
else if (isEnumValue(value)) {
argObj[name.value] = value.value;
}
else if (isNullValue(value)) {
argObj[name.value] = null;
}
else {
throw __DEV__ ? new invariant_InvariantError("The inline argument \"".concat(name.value, "\" of kind \"").concat(value.kind, "\"") +
'is not supported. Use variables instead of inline arguments to ' +
'overcome this limitation.') : new invariant_InvariantError(55);
}
}
function storeKeyNameFromField(field, variables) {
var directivesObj = null;
if (field.directives) {
directivesObj = {};
field.directives.forEach(function (directive) {
directivesObj[directive.name.value] = {};
if (directive.arguments) {
directive.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables);
});
}
});
}
var argObj = null;
if (field.arguments && field.arguments.length) {
argObj = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj, name, value, variables);
});
}
return getStoreKeyName(field.name.value, argObj, directivesObj);
}
var KNOWN_DIRECTIVES = [
'connection',
'include',
'skip',
'client',
'rest',
'export',
];
var getStoreKeyName = Object.assign(function (fieldName, args, directives) {
if (args &&
directives &&
directives['connection'] &&
directives['connection']['key']) {
if (directives['connection']['filter'] &&
directives['connection']['filter'].length > 0) {
var filterKeys = directives['connection']['filter']
? directives['connection']['filter']
: [];
filterKeys.sort();
var filteredArgs_1 = {};
filterKeys.forEach(function (key) {
filteredArgs_1[key] = args[key];
});
return "".concat(directives['connection']['key'], "(").concat(stringify(filteredArgs_1), ")");
}
else {
return directives['connection']['key'];
}
}
var completeFieldName = fieldName;
if (args) {
var stringifiedArgs = stringify(args);
completeFieldName += "(".concat(stringifiedArgs, ")");
}
if (directives) {
Object.keys(directives).forEach(function (key) {
if (KNOWN_DIRECTIVES.indexOf(key) !== -1)
return;
if (directives[key] && Object.keys(directives[key]).length) {
completeFieldName += "@".concat(key, "(").concat(stringify(directives[key]), ")");
}
else {
completeFieldName += "@".concat(key);
}
});
}
return completeFieldName;
}, {
setStringify: function (s) {
var previous = stringify;
stringify = s;
return previous;
},
});
var stringify = function defaultStringify(value) {
return JSON.stringify(value, stringifyReplacer);
};
function stringifyReplacer(_key, value) {
if (isNonNullObject(value) && !Array.isArray(value)) {
value = Object.keys(value).sort().reduce(function (copy, key) {
copy[key] = value[key];
return copy;
}, {});
}
return value;
}
function argumentsObjectFromField(field, variables) {
if (field.arguments && field.arguments.length) {
var argObj_1 = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj_1, name, value, variables);
});
return argObj_1;
}
return null;
}
function resultKeyNameFromField(field) {
return field.alias ? field.alias.value : field.name.value;
}
function getTypenameFromResult(result, selectionSet, fragmentMap) {
var fragments;
for (var _i = 0, _a = selectionSet.selections; _i < _a.length; _i++) {
var selection = _a[_i];
if (isField(selection)) {
if (selection.name.value === '__typename') {
return result[resultKeyNameFromField(selection)];
}
}
else if (fragments) {
fragments.push(selection);
}
else {
fragments = [selection];
}
}
if (typeof result.__typename === 'string') {
return result.__typename;
}
if (fragments) {
for (var _b = 0, fragments_1 = fragments; _b < fragments_1.length; _b++) {
var selection = fragments_1[_b];
var typename = getTypenameFromResult(result, getFragmentFromSelection(selection, fragmentMap).selectionSet, fragmentMap);
if (typeof typename === 'string') {
return typename;
}
}
}
}
function isField(selection) {
return selection.kind === 'Field';
}
function isInlineFragment(selection) {
return selection.kind === 'InlineFragment';
}
//# sourceMappingURL=storeUtils.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/graphql/getFromAST.js
function checkDocument(doc) {
__DEV__ ? invariant(doc && doc.kind === 'Document', "Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql") : invariant(doc && doc.kind === 'Document', 47);
var operations = doc.definitions
.filter(function (d) { return d.kind !== 'FragmentDefinition'; })
.map(function (definition) {
if (definition.kind !== 'OperationDefinition') {
throw __DEV__ ? new invariant_InvariantError("Schema type definitions not allowed in queries. Found: \"".concat(definition.kind, "\"")) : new invariant_InvariantError(48);
}
return definition;
});
__DEV__ ? invariant(operations.length <= 1, "Ambiguous GraphQL document: contains ".concat(operations.length, " operations")) : invariant(operations.length <= 1, 49);
return doc;
}
function getOperationDefinition(doc) {
checkDocument(doc);
return doc.definitions.filter(function (definition) {
return definition.kind === 'OperationDefinition';
})[0];
}
function getOperationName(doc) {
return (doc.definitions
.filter(function (definition) {
return definition.kind === 'OperationDefinition' && !!definition.name;
})
.map(function (x) { return x.name.value; })[0] || null);
}
function getFragmentDefinitions(doc) {
return doc.definitions.filter(function (definition) {
return definition.kind === 'FragmentDefinition';
});
}
function getQueryDefinition(doc) {
var queryDef = getOperationDefinition(doc);
__DEV__ ? invariant(queryDef && queryDef.operation === 'query', 'Must contain a query definition.') : invariant(queryDef && queryDef.operation === 'query', 50);
return queryDef;
}
function getFragmentDefinition(doc) {
__DEV__ ? invariant(doc.kind === 'Document', "Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql") : invariant(doc.kind === 'Document', 51);
__DEV__ ? invariant(doc.definitions.length <= 1, 'Fragment must have exactly one definition.') : invariant(doc.definitions.length <= 1, 52);
var fragmentDef = doc.definitions[0];
__DEV__ ? invariant(fragmentDef.kind === 'FragmentDefinition', 'Must be a fragment definition.') : invariant(fragmentDef.kind === 'FragmentDefinition', 53);
return fragmentDef;
}
function getMainDefinition(queryDoc) {
checkDocument(queryDoc);
var fragmentDefinition;
for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {
var definition = _a[_i];
if (definition.kind === 'OperationDefinition') {
var operation = definition.operation;
if (operation === 'query' ||
operation === 'mutation' ||
operation === 'subscription') {
return definition;
}
}
if (definition.kind === 'FragmentDefinition' && !fragmentDefinition) {
fragmentDefinition = definition;
}
}
if (fragmentDefinition) {
return fragmentDefinition;
}
throw __DEV__ ? new invariant_InvariantError('Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.') : new invariant_InvariantError(54);
}
function getDefaultValues(definition) {
var defaultValues = Object.create(null);
var defs = definition && definition.variableDefinitions;
if (defs && defs.length) {
defs.forEach(function (def) {
if (def.defaultValue) {
valueToObjectRepresentation(defaultValues, def.variable.name, def.defaultValue);
}
});
}
return defaultValues;
}
//# sourceMappingURL=getFromAST.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/utils/transformOperation.js
function transformOperation(operation) {
var transformedOperation = {
variables: operation.variables || {},
extensions: operation.extensions || {},
operationName: operation.operationName,
query: operation.query,
};
if (!transformedOperation.operationName) {
transformedOperation.operationName =
typeof transformedOperation.query !== 'string'
? getOperationName(transformedOperation.query) || undefined
: '';
}
return transformedOperation;
}
//# sourceMappingURL=transformOperation.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/utils/validateOperation.js
function validateOperation(operation) {
var OPERATION_FIELDS = [
'query',
'operationName',
'variables',
'extensions',
'context',
];
for (var _i = 0, _a = Object.keys(operation); _i < _a.length; _i++) {
var key = _a[_i];
if (OPERATION_FIELDS.indexOf(key) < 0) {
throw __DEV__ ? new invariant_InvariantError("illegal argument: ".concat(key)) : new invariant_InvariantError(27);
}
}
return operation;
}
//# sourceMappingURL=validateOperation.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/core/ApolloLink.js
function passthrough(op, forward) {
return (forward ? forward(op) : Observable.of());
}
function toLink(handler) {
return typeof handler === 'function' ? new ApolloLink_ApolloLink(handler) : handler;
}
function isTerminating(link) {
return link.request.length <= 1;
}
var ApolloLink_LinkError = (function (_super) {
__extends(LinkError, _super);
function LinkError(message, link) {
var _this = _super.call(this, message) || this;
_this.link = link;
return _this;
}
return LinkError;
}(Error));
var ApolloLink_ApolloLink = (function () {
function ApolloLink(request) {
if (request)
this.request = request;
}
ApolloLink.empty = function () {
return new ApolloLink(function () { return Observable.of(); });
};
ApolloLink.from = function (links) {
if (links.length === 0)
return ApolloLink.empty();
return links.map(toLink).reduce(function (x, y) { return x.concat(y); });
};
ApolloLink.split = function (test, left, right) {
var leftLink = toLink(left);
var rightLink = toLink(right || new ApolloLink(passthrough));
if (isTerminating(leftLink) && isTerminating(rightLink)) {
return new ApolloLink(function (operation) {
return test(operation)
? leftLink.request(operation) || Observable.of()
: rightLink.request(operation) || Observable.of();
});
}
else {
return new ApolloLink(function (operation, forward) {
return test(operation)
? leftLink.request(operation, forward) || Observable.of()
: rightLink.request(operation, forward) || Observable.of();
});
}
};
ApolloLink.execute = function (link, operation) {
return (link.request(createOperation(operation.context, transformOperation(validateOperation(operation)))) || Observable.of());
};
ApolloLink.concat = function (first, second) {
var firstLink = toLink(first);
if (isTerminating(firstLink)) {
__DEV__ && invariant.warn(new ApolloLink_LinkError("You are calling concat on a terminating link, which will have no effect", firstLink));
return firstLink;
}
var nextLink = toLink(second);
if (isTerminating(nextLink)) {
return new ApolloLink(function (operation) {
return firstLink.request(operation, function (op) { return nextLink.request(op) || Observable.of(); }) || Observable.of();
});
}
else {
return new ApolloLink(function (operation, forward) {
return (firstLink.request(operation, function (op) {
return nextLink.request(op, forward) || Observable.of();
}) || Observable.of());
});
}
};
ApolloLink.prototype.split = function (test, left, right) {
return this.concat(ApolloLink.split(test, left, right || new ApolloLink(passthrough)));
};
ApolloLink.prototype.concat = function (next) {
return ApolloLink.concat(this, next);
};
ApolloLink.prototype.request = function (operation, forward) {
throw __DEV__ ? new invariant_InvariantError('request is not implemented') : new invariant_InvariantError(22);
};
ApolloLink.prototype.onError = function (error, observer) {
if (observer && observer.error) {
observer.error(error);
return false;
}
throw error;
};
ApolloLink.prototype.setOnError = function (fn) {
this.onError = fn;
return this;
};
return ApolloLink;
}());
//# sourceMappingURL=ApolloLink.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/core/execute.js
var execute_execute = ApolloLink_ApolloLink.execute;
//# sourceMappingURL=execute.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/version.js
var version_version = '3.7.16';
//# sourceMappingURL=version.js.map
// CONCATENATED MODULE: ./node_modules/graphql/jsutils/invariant.mjs
function invariant_invariant(condition, message) {
var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')
if (!booleanCondition) {
throw new Error(message != null ? message : 'Unexpected invariant triggered.');
}
}
// CONCATENATED MODULE: ./node_modules/graphql/jsutils/defineInspect.mjs
/**
* The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON`
*/
function defineInspect(classObject) {
var fn = classObject.prototype.toJSON;
typeof fn === 'function' || invariant_invariant(0);
classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317')
if (jsutils_nodejsCustomInspectSymbol) {
classObject.prototype[jsutils_nodejsCustomInspectSymbol] = fn;
}
}
// CONCATENATED MODULE: ./node_modules/graphql/language/ast.mjs
/**
* Contains a range of UTF-8 character offsets and token references that
* identify the region of the source from which the AST derived.
*/
var Location = /*#__PURE__*/function () {
/**
* The character offset at which this Node begins.
*/
/**
* The character offset at which this Node ends.
*/
/**
* The Token at which this Node begins.
*/
/**
* The Token at which this Node ends.
*/
/**
* The Source document the AST represents.
*/
function Location(startToken, endToken, source) {
this.start = startToken.start;
this.end = endToken.end;
this.startToken = startToken;
this.endToken = endToken;
this.source = source;
}
var _proto = Location.prototype;
_proto.toJSON = function toJSON() {
return {
start: this.start,
end: this.end
};
};
return Location;
}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
defineInspect(Location);
/**
* Represents a range of characters represented by a lexical token
* within a Source.
*/
var Token = /*#__PURE__*/function () {
/**
* The kind of Token.
*/
/**
* The character offset at which this Node begins.
*/
/**
* The character offset at which this Node ends.
*/
/**
* The 1-indexed line number on which this Token appears.
*/
/**
* The 1-indexed column number at which this Token begins.
*/
/**
* For non-punctuation tokens, represents the interpreted value of the token.
*/
/**
* Tokens exist as nodes in a double-linked-list amongst all tokens
* including ignored tokens. <SOF> is always the first node and <EOF>
* the last.
*/
function Token(kind, start, end, line, column, prev, value) {
this.kind = kind;
this.start = start;
this.end = end;
this.line = line;
this.column = column;
this.value = value;
this.prev = prev;
this.next = null;
}
var _proto2 = Token.prototype;
_proto2.toJSON = function toJSON() {
return {
kind: this.kind,
value: this.value,
line: this.line,
column: this.column
};
};
return Token;
}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
defineInspect(Token);
/**
* @internal
*/
function isNode(maybeNode) {
return maybeNode != null && typeof maybeNode.kind === 'string';
}
/**
* The list of all possible AST node types.
*/
// CONCATENATED MODULE: ./node_modules/graphql/language/visitor.mjs
/**
* A visitor is provided to visit, it contains the collection of
* relevant functions to be called during the visitor's traversal.
*/
var QueryDocumentKeys = {
Name: [],
Document: ['definitions'],
OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
Variable: ['name'],
SelectionSet: ['selections'],
Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
Argument: ['name', 'value'],
FragmentSpread: ['name', 'directives'],
InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed
// or removed in the future.
'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],
IntValue: [],
FloatValue: [],
StringValue: [],
BooleanValue: [],
NullValue: [],
EnumValue: [],
ListValue: ['values'],
ObjectValue: ['fields'],
ObjectField: ['name', 'value'],
Directive: ['name', 'arguments'],
NamedType: ['name'],
ListType: ['type'],
NonNullType: ['type'],
SchemaDefinition: ['description', 'directives', 'operationTypes'],
OperationTypeDefinition: ['type'],
ScalarTypeDefinition: ['description', 'name', 'directives'],
ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],
InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
EnumValueDefinition: ['description', 'name', 'directives'],
InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
SchemaExtension: ['directives', 'operationTypes'],
ScalarTypeExtension: ['name', 'directives'],
ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
UnionTypeExtension: ['name', 'directives', 'types'],
EnumTypeExtension: ['name', 'directives', 'values'],
InputObjectTypeExtension: ['name', 'directives', 'fields']
};
var BREAK = Object.freeze({});
/**
* visit() will walk through an AST using a depth-first traversal, calling
* the visitor's enter function at each node in the traversal, and calling the
* leave function after visiting that node and all of its child nodes.
*
* By returning different values from the enter and leave functions, the
* behavior of the visitor can be altered, including skipping over a sub-tree of
* the AST (by returning false), editing the AST by returning a value or null
* to remove the value, or to stop the whole traversal by returning BREAK.
*
* When using visit() to edit an AST, the original AST will not be modified, and
* a new version of the AST with the changes applied will be returned from the
* visit function.
*
* const editedAST = visit(ast, {
* enter(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: skip visiting this node
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* },
* leave(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: no action
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* }
* });
*
* Alternatively to providing enter() and leave() functions, a visitor can
* instead provide functions named the same as the kinds of AST nodes, or
* enter/leave visitors at a named key, leading to four permutations of the
* visitor API:
*
* 1) Named visitors triggered when entering a node of a specific kind.
*
* visit(ast, {
* Kind(node) {
* // enter the "Kind" node
* }
* })
*
* 2) Named visitors that trigger upon entering and leaving a node of
* a specific kind.
*
* visit(ast, {
* Kind: {
* enter(node) {
* // enter the "Kind" node
* }
* leave(node) {
* // leave the "Kind" node
* }
* }
* })
*
* 3) Generic visitors that trigger upon entering and leaving any node.
*
* visit(ast, {
* enter(node) {
* // enter any node
* },
* leave(node) {
* // leave any node
* }
* })
*
* 4) Parallel visitors for entering and leaving nodes of a specific kind.
*
* visit(ast, {
* enter: {
* Kind(node) {
* // enter the "Kind" node
* }
* },
* leave: {
* Kind(node) {
* // leave the "Kind" node
* }
* }
* })
*/
function visit(root, visitor) {
var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys;
/* eslint-disable no-undef-init */
var stack = undefined;
var inArray = Array.isArray(root);
var keys = [root];
var index = -1;
var edits = [];
var node = undefined;
var key = undefined;
var parent = undefined;
var path = [];
var ancestors = [];
var newRoot = root;
/* eslint-enable no-undef-init */
do {
index++;
var isLeaving = index === keys.length;
var isEdited = isLeaving && edits.length !== 0;
if (isLeaving) {
key = ancestors.length === 0 ? undefined : path[path.length - 1];
node = parent;
parent = ancestors.pop();
if (isEdited) {
if (inArray) {
node = node.slice();
} else {
var clone = {};
for (var _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) {
var k = _Object$keys2[_i2];
clone[k] = node[k];
}
node = clone;
}
var editOffset = 0;
for (var ii = 0; ii < edits.length; ii++) {
var editKey = edits[ii][0];
var editValue = edits[ii][1];
if (inArray) {
editKey -= editOffset;
}
if (inArray && editValue === null) {
node.splice(editKey, 1);
editOffset++;
} else {
node[editKey] = editValue;
}
}
}
index = stack.index;
keys = stack.keys;
edits = stack.edits;
inArray = stack.inArray;
stack = stack.prev;
} else {
key = parent ? inArray ? index : keys[index] : undefined;
node = parent ? parent[key] : newRoot;
if (node === null || node === undefined) {
continue;
}
if (parent) {
path.push(key);
}
}
var result = void 0;
if (!Array.isArray(node)) {
if (!isNode(node)) {
throw new Error("Invalid AST Node: ".concat(inspect(node), "."));
}
var visitFn = getVisitFn(visitor, node.kind, isLeaving);
if (visitFn) {
result = visitFn.call(visitor, node, key, parent, path, ancestors);
if (result === BREAK) {
break;
}
if (result === false) {
if (!isLeaving) {
path.pop();
continue;
}
} else if (result !== undefined) {
edits.push([key, result]);
if (!isLeaving) {
if (isNode(result)) {
node = result;
} else {
path.pop();
continue;
}
}
}
}
}
if (result === undefined && isEdited) {
edits.push([key, node]);
}
if (isLeaving) {
path.pop();
} else {
var _visitorKeys$node$kin;
stack = {
inArray: inArray,
index: index,
keys: keys,
edits: edits,
prev: stack
};
inArray = Array.isArray(node);
keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : [];
index = -1;
edits = [];
if (parent) {
ancestors.push(parent);
}
parent = node;
}
} while (stack !== undefined);
if (edits.length !== 0) {
newRoot = edits[edits.length - 1][1];
}
return newRoot;
}
/**
* Creates a new visitor instance which delegates to many visitors to run in
* parallel. Each visitor will be visited for each node before moving on.
*
* If a prior visitor edits a node, no following visitors will see that node.
*/
function visitInParallel(visitors) {
var skipping = new Array(visitors.length);
return {
enter: function enter(node) {
for (var i = 0; i < visitors.length; i++) {
if (skipping[i] == null) {
var fn = getVisitFn(visitors[i], node.kind,
/* isLeaving */
false);
if (fn) {
var result = fn.apply(visitors[i], arguments);
if (result === false) {
skipping[i] = node;
} else if (result === BREAK) {
skipping[i] = BREAK;
} else if (result !== undefined) {
return result;
}
}
}
}
},
leave: function leave(node) {
for (var i = 0; i < visitors.length; i++) {
if (skipping[i] == null) {
var fn = getVisitFn(visitors[i], node.kind,
/* isLeaving */
true);
if (fn) {
var result = fn.apply(visitors[i], arguments);
if (result === BREAK) {
skipping[i] = BREAK;
} else if (result !== undefined && result !== false) {
return result;
}
}
} else if (skipping[i] === node) {
skipping[i] = null;
}
}
}
};
}
/**
* Given a visitor instance, if it is leaving or not, and a node kind, return
* the function the visitor runtime should call.
*/
function getVisitFn(visitor, kind, isLeaving) {
var kindVisitor = visitor[kind];
if (kindVisitor) {
if (!isLeaving && typeof kindVisitor === 'function') {
// { Kind() {} }
return kindVisitor;
}
var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
if (typeof kindSpecificVisitor === 'function') {
// { Kind: { enter() {}, leave() {} } }
return kindSpecificVisitor;
}
} else {
var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
if (specificVisitor) {
if (typeof specificVisitor === 'function') {
// { enter() {}, leave() {} }
return specificVisitor;
}
var specificKindVisitor = specificVisitor[kind];
if (typeof specificKindVisitor === 'function') {
// { enter: { Kind() {} }, leave: { Kind() {} } }
return specificKindVisitor;
}
}
}
}
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/graphql/directives.js
function shouldInclude(_a, variables) {
var directives = _a.directives;
if (!directives || !directives.length) {
return true;
}
return getInclusionDirectives(directives).every(function (_a) {
var directive = _a.directive, ifArgument = _a.ifArgument;
var evaledValue = false;
if (ifArgument.value.kind === 'Variable') {
evaledValue = variables && variables[ifArgument.value.name.value];
__DEV__ ? invariant(evaledValue !== void 0, "Invalid variable referenced in @".concat(directive.name.value, " directive.")) : invariant(evaledValue !== void 0, 40);
}
else {
evaledValue = ifArgument.value.value;
}
return directive.name.value === 'skip' ? !evaledValue : evaledValue;
});
}
function getDirectiveNames(root) {
var names = [];
visit(root, {
Directive: function (node) {
names.push(node.name.value);
},
});
return names;
}
var hasAnyDirectives = function (names, root) { return hasDirectives(names, root, false); };
var hasAllDirectives = function (names, root) { return hasDirectives(names, root, true); };
function hasDirectives(names, root, all) {
var nameSet = new Set(names);
var uniqueCount = nameSet.size;
visit(root, {
Directive: function (node) {
if (nameSet.delete(node.name.value) &&
(!all || !nameSet.size)) {
return BREAK;
}
},
});
return all ? !nameSet.size : nameSet.size < uniqueCount;
}
function directives_hasClientExports(document) {
return document && hasDirectives(['client', 'export'], document, true);
}
function isInclusionDirective(_a) {
var value = _a.name.value;
return value === 'skip' || value === 'include';
}
function getInclusionDirectives(directives) {
var result = [];
if (directives && directives.length) {
directives.forEach(function (directive) {
if (!isInclusionDirective(directive))
return;
var directiveArguments = directive.arguments;
var directiveName = directive.name.value;
__DEV__ ? invariant(directiveArguments && directiveArguments.length === 1, "Incorrect number of arguments for the @".concat(directiveName, " directive.")) : invariant(directiveArguments && directiveArguments.length === 1, 41);
var ifArgument = directiveArguments[0];
__DEV__ ? invariant(ifArgument.name && ifArgument.name.value === 'if', "Invalid argument for the @".concat(directiveName, " directive.")) : invariant(ifArgument.name && ifArgument.name.value === 'if', 42);
var ifValue = ifArgument.value;
__DEV__ ? invariant(ifValue &&
(ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), "Argument for the @".concat(directiveName, " directive must be a variable or a boolean value.")) : invariant(ifValue &&
(ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), 43);
result.push({ directive: directive, ifArgument: ifArgument });
});
}
return result;
}
//# sourceMappingURL=directives.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/serializeFetchParameter.js
var serializeFetchParameter = function (p, label) {
var serialized;
try {
serialized = JSON.stringify(p);
}
catch (e) {
var parseError = __DEV__ ? new invariant_InvariantError("Network request failed. ".concat(label, " is not serializable: ").concat(e.message)) : new invariant_InvariantError(24);
parseError.parseError = e;
throw parseError;
}
return serialized;
};
//# sourceMappingURL=serializeFetchParameter.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/selectURI.js
var selectURI = function (operation, fallbackURI) {
var context = operation.getContext();
var contextURI = context.uri;
if (contextURI) {
return contextURI;
}
else if (typeof fallbackURI === 'function') {
return fallbackURI(operation);
}
else {
return fallbackURI || '/graphql';
}
};
//# sourceMappingURL=selectURI.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/canUse.js
var canUseWeakMap = typeof WeakMap === 'function' &&
maybe(function () { return navigator.product; }) !== 'ReactNative';
var canUseWeakSet = typeof WeakSet === 'function';
var canUseSymbol = typeof Symbol === 'function' &&
typeof Symbol.for === 'function';
var canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;
var canUseDOM = typeof maybe(function () { return window.document.createElement; }) === "function";
var usingJSDOM = maybe(function () { return navigator.userAgent.indexOf("jsdom") >= 0; }) || false;
var canUseLayoutEffect = canUseDOM && !usingJSDOM;
//# sourceMappingURL=canUse.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/responseIterator.js
function isNodeResponse(value) {
return !!value.body;
}
function isReadableStream(value) {
return !!value.getReader;
}
function isAsyncIterableIterator(value) {
return !!(canUseAsyncIteratorSymbol &&
value[Symbol.asyncIterator]);
}
function isStreamableBlob(value) {
return !!value.stream;
}
function isBlob(value) {
return !!value.arrayBuffer;
}
function isNodeReadableStream(value) {
return !!value.pipe;
}
//# sourceMappingURL=responseIterator.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/iterators/async.js
function asyncIterator(source) {
var _a;
var iterator = source[Symbol.asyncIterator]();
return _a = {
next: function () {
return iterator.next();
}
},
_a[Symbol.asyncIterator] = function () {
return this;
},
_a;
}
//# sourceMappingURL=async.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/iterators/nodeStream.js
function nodeStreamIterator(stream) {
var cleanup = null;
var error = null;
var done = false;
var data = [];
var waiting = [];
function onData(chunk) {
if (error)
return;
if (waiting.length) {
var shiftedArr = waiting.shift();
if (Array.isArray(shiftedArr) && shiftedArr[0]) {
return shiftedArr[0]({ value: chunk, done: false });
}
}
data.push(chunk);
}
function onError(err) {
error = err;
var all = waiting.slice();
all.forEach(function (pair) {
pair[1](err);
});
!cleanup || cleanup();
}
function onEnd() {
done = true;
var all = waiting.slice();
all.forEach(function (pair) {
pair[0]({ value: undefined, done: true });
});
!cleanup || cleanup();
}
cleanup = function () {
cleanup = null;
stream.removeListener("data", onData);
stream.removeListener("error", onError);
stream.removeListener("end", onEnd);
stream.removeListener("finish", onEnd);
stream.removeListener("close", onEnd);
};
stream.on("data", onData);
stream.on("error", onError);
stream.on("end", onEnd);
stream.on("finish", onEnd);
stream.on("close", onEnd);
function getNext() {
return new Promise(function (resolve, reject) {
if (error)
return reject(error);
if (data.length)
return resolve({ value: data.shift(), done: false });
if (done)
return resolve({ value: undefined, done: true });
waiting.push([resolve, reject]);
});
}
var iterator = {
next: function () {
return getNext();
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=nodeStream.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/iterators/promise.js
function promiseIterator(promise) {
var resolved = false;
var iterator = {
next: function () {
if (resolved)
return Promise.resolve({
value: undefined,
done: true,
});
resolved = true;
return new Promise(function (resolve, reject) {
promise
.then(function (value) {
resolve({ value: value, done: false });
})
.catch(reject);
});
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=promise.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/iterators/reader.js
function readerIterator(reader) {
var iterator = {
next: function () {
return reader.read();
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=reader.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/responseIterator.js
function responseIterator(response) {
var body = response;
if (isNodeResponse(response))
body = response.body;
if (isAsyncIterableIterator(body))
return asyncIterator(body);
if (isReadableStream(body))
return readerIterator(body.getReader());
if (isStreamableBlob(body)) {
return readerIterator(body.stream().getReader());
}
if (isBlob(body))
return promiseIterator(body.arrayBuffer());
if (isNodeReadableStream(body))
return nodeStreamIterator(body);
throw new Error("Unknown body type for responseIterator. Please pass a streamable response.");
}
//# sourceMappingURL=responseIterator.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/utils/throwServerError.js
var throwServerError = function (response, result, message) {
var error = new Error(message);
error.name = 'ServerError';
error.response = response;
error.statusCode = response.status;
error.result = result;
throw error;
};
//# sourceMappingURL=throwServerError.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/errors/index.js
var PROTOCOL_ERRORS_SYMBOL = Symbol();
function graphQLResultHasProtocolErrors(result) {
if (result.extensions) {
return Array.isArray(result.extensions[PROTOCOL_ERRORS_SYMBOL]);
}
return false;
}
function isApolloError(err) {
return err.hasOwnProperty('graphQLErrors');
}
var generateErrorMessage = function (err) {
var errors = __spreadArray(__spreadArray(__spreadArray([], err.graphQLErrors, true), err.clientErrors, true), err.protocolErrors, true);
if (err.networkError)
errors.push(err.networkError);
return errors
.map(function (err) { return isNonNullObject(err) && err.message || 'Error message not found.'; })
.join('\n');
};
var errors_ApolloError = (function (_super) {
__extends(ApolloError, _super);
function ApolloError(_a) {
var graphQLErrors = _a.graphQLErrors, protocolErrors = _a.protocolErrors, clientErrors = _a.clientErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;
var _this = _super.call(this, errorMessage) || this;
_this.name = 'ApolloError';
_this.graphQLErrors = graphQLErrors || [];
_this.protocolErrors = protocolErrors || [];
_this.clientErrors = clientErrors || [];
_this.networkError = networkError || null;
_this.message = errorMessage || generateErrorMessage(_this);
_this.extraInfo = extraInfo;
_this.__proto__ = ApolloError.prototype;
return _this;
}
return ApolloError;
}(Error));
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/arrays.js
var arrays_isArray = Array.isArray;
function isNonEmptyArray(value) {
return Array.isArray(value) && value.length > 0;
}
//# sourceMappingURL=arrays.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/mergeDeep.js
var mergeDeep_hasOwnProperty = Object.prototype.hasOwnProperty;
function mergeDeep() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
return mergeDeepArray(sources);
}
function mergeDeepArray(sources) {
var target = sources[0] || {};
var count = sources.length;
if (count > 1) {
var merger = new mergeDeep_DeepMerger();
for (var i = 1; i < count; ++i) {
target = merger.merge(target, sources[i]);
}
}
return target;
}
var defaultReconciler = function (target, source, property) {
return this.merge(target[property], source[property]);
};
var mergeDeep_DeepMerger = (function () {
function DeepMerger(reconciler) {
if (reconciler === void 0) { reconciler = defaultReconciler; }
this.reconciler = reconciler;
this.isObject = isNonNullObject;
this.pastCopies = new Set();
}
DeepMerger.prototype.merge = function (target, source) {
var _this = this;
var context = [];
for (var _i = 2; _i < arguments.length; _i++) {
context[_i - 2] = arguments[_i];
}
if (isNonNullObject(source) && isNonNullObject(target)) {
Object.keys(source).forEach(function (sourceKey) {
if (mergeDeep_hasOwnProperty.call(target, sourceKey)) {
var targetValue = target[sourceKey];
if (source[sourceKey] !== targetValue) {
var result = _this.reconciler.apply(_this, __spreadArray([target, source, sourceKey], context, false));
if (result !== targetValue) {
target = _this.shallowCopyForMerge(target);
target[sourceKey] = result;
}
}
}
else {
target = _this.shallowCopyForMerge(target);
target[sourceKey] = source[sourceKey];
}
});
return target;
}
return source;
};
DeepMerger.prototype.shallowCopyForMerge = function (value) {
if (isNonNullObject(value)) {
if (!this.pastCopies.has(value)) {
if (Array.isArray(value)) {
value = value.slice(0);
}
else {
value = __assign({ __proto__: Object.getPrototypeOf(value) }, value);
}
this.pastCopies.add(value);
}
}
return value;
};
return DeepMerger;
}());
//# sourceMappingURL=mergeDeep.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/incrementalResult.js
function isExecutionPatchIncrementalResult(value) {
return "incremental" in value;
}
function isExecutionPatchInitialResult(value) {
return "hasNext" in value && "data" in value;
}
function isExecutionPatchResult(value) {
return (isExecutionPatchIncrementalResult(value) ||
isExecutionPatchInitialResult(value));
}
function isApolloPayloadResult(value) {
return isNonNullObject(value) && "payload" in value;
}
function mergeIncrementalData(prevResult, result) {
var mergedData = prevResult;
var merger = new mergeDeep_DeepMerger();
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
result.incremental.forEach(function (_a) {
var data = _a.data, path = _a.path;
for (var i = path.length - 1; i >= 0; --i) {
var key = path[i];
var isNumericKey = !isNaN(+key);
var parent_1 = isNumericKey ? [] : {};
parent_1[key] = data;
data = parent_1;
}
mergedData = merger.merge(mergedData, data);
});
}
return mergedData;
}
//# sourceMappingURL=incrementalResult.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/parseAndCheckHttpResponse.js
var parseAndCheckHttpResponse_hasOwnProperty = Object.prototype.hasOwnProperty;
function readMultipartBody(response, observer) {
var _a, _b, _c, _d, _e;
return tslib_es6_awaiter(this, void 0, void 0, function () {
var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _f, value, done, chunk, searchFrom, bi, message, i, headers, contentType_1, body, result, next;
var _g, _h;
return __generator(this, function (_j) {
switch (_j.label) {
case 0:
if (TextDecoder === undefined) {
throw new Error("TextDecoder must be defined in the environment: please import a polyfill.");
}
decoder = new TextDecoder("utf-8");
contentType = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
delimiter = "boundary=";
boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter))
? contentType === null || contentType === void 0 ? void 0 : contentType.substring((contentType === null || contentType === void 0 ? void 0 : contentType.indexOf(delimiter)) + delimiter.length).replace(/['"]/g, "").replace(/\;(.*)/gm, "").trim()
: "-";
boundary = "\r\n--".concat(boundaryVal);
buffer = "";
iterator = responseIterator(response);
running = true;
_j.label = 1;
case 1:
if (!running) return [3, 3];
return [4, iterator.next()];
case 2:
_f = _j.sent(), value = _f.value, done = _f.done;
chunk = typeof value === "string" ? value : decoder.decode(value);
searchFrom = buffer.length - boundary.length + 1;
running = !done;
buffer += chunk;
bi = buffer.indexOf(boundary, searchFrom);
while (bi > -1) {
message = void 0;
_g = [
buffer.slice(0, bi),
buffer.slice(bi + boundary.length),
], message = _g[0], buffer = _g[1];
i = message.indexOf("\r\n\r\n");
headers = parseHeaders(message.slice(0, i));
contentType_1 = headers["content-type"];
if (contentType_1 &&
contentType_1.toLowerCase().indexOf("application/json") === -1) {
throw new Error("Unsupported patch content type: application/json is required.");
}
body = message.slice(i);
if (body) {
try {
result = parseJsonBody(response, body);
if (Object.keys(result).length > 1 ||
"data" in result ||
"incremental" in result ||
"errors" in result ||
"payload" in result) {
if (isApolloPayloadResult(result)) {
next = {};
if ("payload" in result) {
next = __assign({}, result.payload);
}
if ("errors" in result) {
next = __assign(__assign({}, next), { extensions: __assign(__assign({}, ("extensions" in next ? next.extensions : null)), (_h = {}, _h[PROTOCOL_ERRORS_SYMBOL] = result.errors, _h)) });
}
(_b = observer.next) === null || _b === void 0 ? void 0 : _b.call(observer, next);
}
else {
(_c = observer.next) === null || _c === void 0 ? void 0 : _c.call(observer, result);
}
}
else if (Object.keys(result).length === 1 &&
"hasNext" in result &&
!result.hasNext) {
(_d = observer.complete) === null || _d === void 0 ? void 0 : _d.call(observer);
}
}
catch (err) {
handleError(err, observer);
}
}
bi = buffer.indexOf(boundary);
}
return [3, 1];
case 3:
(_e = observer.complete) === null || _e === void 0 ? void 0 : _e.call(observer);
return [2];
}
});
});
}
function parseHeaders(headerText) {
var headersInit = {};
headerText.split("\n").forEach(function (line) {
var i = line.indexOf(":");
if (i > -1) {
var name_1 = line.slice(0, i).trim().toLowerCase();
var value = line.slice(i + 1).trim();
headersInit[name_1] = value;
}
});
return headersInit;
}
function parseJsonBody(response, bodyText) {
if (response.status >= 300) {
var getResult = function () {
try {
return JSON.parse(bodyText);
}
catch (err) {
return bodyText;
}
};
throwServerError(response, getResult(), "Response not successful: Received status code ".concat(response.status));
}
try {
return JSON.parse(bodyText);
}
catch (err) {
var parseError = err;
parseError.name = "ServerParseError";
parseError.response = response;
parseError.statusCode = response.status;
parseError.bodyText = bodyText;
throw parseError;
}
}
function handleError(err, observer) {
var _a, _b;
if (err.name === "AbortError")
return;
if (err.result && err.result.errors && err.result.data) {
(_a = observer.next) === null || _a === void 0 ? void 0 : _a.call(observer, err.result);
}
(_b = observer.error) === null || _b === void 0 ? void 0 : _b.call(observer, err);
}
function readJsonBody(response, operation, observer) {
parseAndCheckHttpResponse(operation)(response)
.then(function (result) {
var _a, _b;
(_a = observer.next) === null || _a === void 0 ? void 0 : _a.call(observer, result);
(_b = observer.complete) === null || _b === void 0 ? void 0 : _b.call(observer);
})
.catch(function (err) { return handleError(err, observer); });
}
function parseAndCheckHttpResponse(operations) {
return function (response) {
return response
.text()
.then(function (bodyText) { return parseJsonBody(response, bodyText); })
.then(function (result) {
if (response.status >= 300) {
throwServerError(response, result, "Response not successful: Received status code ".concat(response.status));
}
if (!Array.isArray(result) &&
!parseAndCheckHttpResponse_hasOwnProperty.call(result, "data") &&
!parseAndCheckHttpResponse_hasOwnProperty.call(result, "errors")) {
throwServerError(response, result, "Server response was missing for query '".concat(Array.isArray(operations)
? operations.map(function (op) { return op.operationName; })
: operations.operationName, "'."));
}
return result;
});
};
}
//# sourceMappingURL=parseAndCheckHttpResponse.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/checkFetcher.js
var checkFetcher = function (fetcher) {
if (!fetcher && typeof fetch === 'undefined') {
throw __DEV__ ? new invariant_InvariantError("\n\"fetch\" has not been found globally and no fetcher has been configured. To fix this, install a fetch package (like https://www.npmjs.com/package/cross-fetch), instantiate the fetcher, and pass it into your HttpLink constructor. For example:\n\nimport fetch from 'cross-fetch';\nimport { ApolloClient, HttpLink } from '@apollo/client';\nconst client = new ApolloClient({\n link: new HttpLink({ uri: '/graphql', fetch })\n});\n ") : new invariant_InvariantError(23);
}
};
//# sourceMappingURL=checkFetcher.js.map
// CONCATENATED MODULE: ./node_modules/graphql/language/blockString.mjs
/**
* Produces the value of a block string from its parsed raw value, similar to
* CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.
*
* This implements the GraphQL spec's BlockStringValue() static algorithm.
*
* @internal
*/
function dedentBlockStringValue(rawString) {
// Expand a block string's raw value into independent lines.
var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.
var commonIndent = getBlockStringIndentation(rawString);
if (commonIndent !== 0) {
for (var i = 1; i < lines.length; i++) {
lines[i] = lines[i].slice(commonIndent);
}
} // Remove leading and trailing blank lines.
var startLine = 0;
while (startLine < lines.length && isBlank(lines[startLine])) {
++startLine;
}
var endLine = lines.length;
while (endLine > startLine && isBlank(lines[endLine - 1])) {
--endLine;
} // Return a string of the lines joined with U+000A.
return lines.slice(startLine, endLine).join('\n');
}
function isBlank(str) {
for (var i = 0; i < str.length; ++i) {
if (str[i] !== ' ' && str[i] !== '\t') {
return false;
}
}
return true;
}
/**
* @internal
*/
function getBlockStringIndentation(value) {
var _commonIndent;
var isFirstLine = true;
var isEmptyLine = true;
var indent = 0;
var commonIndent = null;
for (var i = 0; i < value.length; ++i) {
switch (value.charCodeAt(i)) {
case 13:
// \r
if (value.charCodeAt(i + 1) === 10) {
++i; // skip \r\n as one symbol
}
// falls through
case 10:
// \n
isFirstLine = false;
isEmptyLine = true;
indent = 0;
break;
case 9: // \t
case 32:
// <space>
++indent;
break;
default:
if (isEmptyLine && !isFirstLine && (commonIndent === null || indent < commonIndent)) {
commonIndent = indent;
}
isEmptyLine = false;
}
}
return (_commonIndent = commonIndent) !== null && _commonIndent !== void 0 ? _commonIndent : 0;
}
/**
* Print a block string in the indented block form by adding a leading and
* trailing blank line. However, if a block string starts with whitespace and is
* a single-line, adding a leading blank line would strip that whitespace.
*
* @internal
*/
function printBlockString(value) {
var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var isSingleLine = value.indexOf('\n') === -1;
var hasLeadingSpace = value[0] === ' ' || value[0] === '\t';
var hasTrailingQuote = value[value.length - 1] === '"';
var hasTrailingSlash = value[value.length - 1] === '\\';
var printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines;
var result = ''; // Format a multi-line block quote to account for leading space.
if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) {
result += '\n' + indentation;
}
result += indentation ? value.replace(/\n/g, '\n' + indentation) : value;
if (printAsMultipleLines) {
result += '\n';
}
return '"""' + result.replace(/"""/g, '\\"""') + '"""';
}
// CONCATENATED MODULE: ./node_modules/graphql/language/printer.mjs
/**
* Converts an AST into a string, using one set of reasonable
* formatting rules.
*/
function printer_print(ast) {
return visit(ast, {
leave: printDocASTReducer
});
}
var MAX_LINE_LENGTH = 80; // TODO: provide better type coverage in future
var printDocASTReducer = {
Name: function Name(node) {
return node.value;
},
Variable: function Variable(node) {
return '$' + node.name;
},
// Document
Document: function Document(node) {
return join(node.definitions, '\n\n') + '\n';
},
OperationDefinition: function OperationDefinition(node) {
var op = node.operation;
var name = node.name;
var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
var directives = join(node.directives, ' ');
var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use
// the query short form.
return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' ');
},
VariableDefinition: function VariableDefinition(_ref) {
var variable = _ref.variable,
type = _ref.type,
defaultValue = _ref.defaultValue,
directives = _ref.directives;
return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' '));
},
SelectionSet: function SelectionSet(_ref2) {
var selections = _ref2.selections;
return printer_block(selections);
},
Field: function Field(_ref3) {
var alias = _ref3.alias,
name = _ref3.name,
args = _ref3.arguments,
directives = _ref3.directives,
selectionSet = _ref3.selectionSet;
var prefix = wrap('', alias, ': ') + name;
var argsLine = prefix + wrap('(', join(args, ', '), ')');
if (argsLine.length > MAX_LINE_LENGTH) {
argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)');
}
return join([argsLine, join(directives, ' '), selectionSet], ' ');
},
Argument: function Argument(_ref4) {
var name = _ref4.name,
value = _ref4.value;
return name + ': ' + value;
},
// Fragments
FragmentSpread: function FragmentSpread(_ref5) {
var name = _ref5.name,
directives = _ref5.directives;
return '...' + name + wrap(' ', join(directives, ' '));
},
InlineFragment: function InlineFragment(_ref6) {
var typeCondition = _ref6.typeCondition,
directives = _ref6.directives,
selectionSet = _ref6.selectionSet;
return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ');
},
FragmentDefinition: function FragmentDefinition(_ref7) {
var name = _ref7.name,
typeCondition = _ref7.typeCondition,
variableDefinitions = _ref7.variableDefinitions,
directives = _ref7.directives,
selectionSet = _ref7.selectionSet;
return (// Note: fragment variable definitions are experimental and may be changed
// or removed in the future.
"fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet
);
},
// Value
IntValue: function IntValue(_ref8) {
var value = _ref8.value;
return value;
},
FloatValue: function FloatValue(_ref9) {
var value = _ref9.value;
return value;
},
StringValue: function StringValue(_ref10, key) {
var value = _ref10.value,
isBlockString = _ref10.block;
return isBlockString ? printBlockString(value, key === 'description' ? '' : ' ') : JSON.stringify(value);
},
BooleanValue: function BooleanValue(_ref11) {
var value = _ref11.value;
return value ? 'true' : 'false';
},
NullValue: function NullValue() {
return 'null';
},
EnumValue: function EnumValue(_ref12) {
var value = _ref12.value;
return value;
},
ListValue: function ListValue(_ref13) {
var values = _ref13.values;
return '[' + join(values, ', ') + ']';
},
ObjectValue: function ObjectValue(_ref14) {
var fields = _ref14.fields;
return '{' + join(fields, ', ') + '}';
},
ObjectField: function ObjectField(_ref15) {
var name = _ref15.name,
value = _ref15.value;
return name + ': ' + value;
},
// Directive
Directive: function Directive(_ref16) {
var name = _ref16.name,
args = _ref16.arguments;
return '@' + name + wrap('(', join(args, ', '), ')');
},
// Type
NamedType: function NamedType(_ref17) {
var name = _ref17.name;
return name;
},
ListType: function ListType(_ref18) {
var type = _ref18.type;
return '[' + type + ']';
},
NonNullType: function NonNullType(_ref19) {
var type = _ref19.type;
return type + '!';
},
// Type System Definitions
SchemaDefinition: addDescription(function (_ref20) {
var directives = _ref20.directives,
operationTypes = _ref20.operationTypes;
return join(['schema', join(directives, ' '), printer_block(operationTypes)], ' ');
}),
OperationTypeDefinition: function OperationTypeDefinition(_ref21) {
var operation = _ref21.operation,
type = _ref21.type;
return operation + ': ' + type;
},
ScalarTypeDefinition: addDescription(function (_ref22) {
var name = _ref22.name,
directives = _ref22.directives;
return join(['scalar', name, join(directives, ' ')], ' ');
}),
ObjectTypeDefinition: addDescription(function (_ref23) {
var name = _ref23.name,
interfaces = _ref23.interfaces,
directives = _ref23.directives,
fields = _ref23.fields;
return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), printer_block(fields)], ' ');
}),
FieldDefinition: addDescription(function (_ref24) {
var name = _ref24.name,
args = _ref24.arguments,
type = _ref24.type,
directives = _ref24.directives;
return name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' '));
}),
InputValueDefinition: addDescription(function (_ref25) {
var name = _ref25.name,
type = _ref25.type,
defaultValue = _ref25.defaultValue,
directives = _ref25.directives;
return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ');
}),
InterfaceTypeDefinition: addDescription(function (_ref26) {
var name = _ref26.name,
interfaces = _ref26.interfaces,
directives = _ref26.directives,
fields = _ref26.fields;
return join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), printer_block(fields)], ' ');
}),
UnionTypeDefinition: addDescription(function (_ref27) {
var name = _ref27.name,
directives = _ref27.directives,
types = _ref27.types;
return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
}),
EnumTypeDefinition: addDescription(function (_ref28) {
var name = _ref28.name,
directives = _ref28.directives,
values = _ref28.values;
return join(['enum', name, join(directives, ' '), printer_block(values)], ' ');
}),
EnumValueDefinition: addDescription(function (_ref29) {
var name = _ref29.name,
directives = _ref29.directives;
return join([name, join(directives, ' ')], ' ');
}),
InputObjectTypeDefinition: addDescription(function (_ref30) {
var name = _ref30.name,
directives = _ref30.directives,
fields = _ref30.fields;
return join(['input', name, join(directives, ' '), printer_block(fields)], ' ');
}),
DirectiveDefinition: addDescription(function (_ref31) {
var name = _ref31.name,
args = _ref31.arguments,
repeatable = _ref31.repeatable,
locations = _ref31.locations;
return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | ');
}),
SchemaExtension: function SchemaExtension(_ref32) {
var directives = _ref32.directives,
operationTypes = _ref32.operationTypes;
return join(['extend schema', join(directives, ' '), printer_block(operationTypes)], ' ');
},
ScalarTypeExtension: function ScalarTypeExtension(_ref33) {
var name = _ref33.name,
directives = _ref33.directives;
return join(['extend scalar', name, join(directives, ' ')], ' ');
},
ObjectTypeExtension: function ObjectTypeExtension(_ref34) {
var name = _ref34.name,
interfaces = _ref34.interfaces,
directives = _ref34.directives,
fields = _ref34.fields;
return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), printer_block(fields)], ' ');
},
InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) {
var name = _ref35.name,
interfaces = _ref35.interfaces,
directives = _ref35.directives,
fields = _ref35.fields;
return join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), printer_block(fields)], ' ');
},
UnionTypeExtension: function UnionTypeExtension(_ref36) {
var name = _ref36.name,
directives = _ref36.directives,
types = _ref36.types;
return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
},
EnumTypeExtension: function EnumTypeExtension(_ref37) {
var name = _ref37.name,
directives = _ref37.directives,
values = _ref37.values;
return join(['extend enum', name, join(directives, ' '), printer_block(values)], ' ');
},
InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) {
var name = _ref38.name,
directives = _ref38.directives,
fields = _ref38.fields;
return join(['extend input', name, join(directives, ' '), printer_block(fields)], ' ');
}
};
function addDescription(cb) {
return function (node) {
return join([node.description, cb(node)], '\n');
};
}
/**
* Given maybeArray, print an empty string if it is null or empty, otherwise
* print all items together separated by separator if provided
*/
function join(maybeArray) {
var _maybeArray$filter$jo;
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(function (x) {
return x;
}).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : '';
}
/**
* Given array, print each item on its own line, wrapped in an
* indented "{ }" block.
*/
function printer_block(array) {
return wrap('{\n', indent(join(array, '\n')), '\n}');
}
/**
* If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string.
*/
function wrap(start, maybeString) {
var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
return maybeString != null && maybeString !== '' ? start + maybeString + end : '';
}
function indent(str) {
return wrap(' ', str.replace(/\n/g, '\n '));
}
function isMultiline(str) {
return str.indexOf('\n') !== -1;
}
function hasMultilineItems(maybeArray) {
return maybeArray != null && maybeArray.some(isMultiline);
}
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/selectHttpOptionsAndBody.js
;
var defaultHttpOptions = {
includeQuery: true,
includeExtensions: false,
preserveHeaderCase: false,
};
var defaultHeaders = {
accept: '*/*',
'content-type': 'application/json',
};
var selectHttpOptionsAndBody_defaultOptions = {
method: 'POST',
};
var fallbackHttpConfig = {
http: defaultHttpOptions,
headers: defaultHeaders,
options: selectHttpOptionsAndBody_defaultOptions,
};
var defaultPrinter = function (ast, printer) { return printer(ast); };
function selectHttpOptionsAndBody(operation, fallbackConfig) {
var configs = [];
for (var _i = 2; _i < arguments.length; _i++) {
configs[_i - 2] = arguments[_i];
}
configs.unshift(fallbackConfig);
return selectHttpOptionsAndBodyInternal.apply(void 0, __spreadArray([operation,
defaultPrinter], configs, false));
}
function selectHttpOptionsAndBodyInternal(operation, printer) {
var configs = [];
for (var _i = 2; _i < arguments.length; _i++) {
configs[_i - 2] = arguments[_i];
}
var options = {};
var http = {};
configs.forEach(function (config) {
options = __assign(__assign(__assign({}, options), config.options), { headers: __assign(__assign({}, options.headers), config.headers) });
if (config.credentials) {
options.credentials = config.credentials;
}
http = __assign(__assign({}, http), config.http);
});
if (options.headers) {
options.headers = removeDuplicateHeaders(options.headers, http.preserveHeaderCase);
}
var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;
var body = { operationName: operationName, variables: variables };
if (http.includeExtensions)
body.extensions = extensions;
if (http.includeQuery)
body.query = printer(query, printer_print);
return {
options: options,
body: body,
};
}
;
function removeDuplicateHeaders(headers, preserveHeaderCase) {
if (!preserveHeaderCase) {
var normalizedHeaders_1 = Object.create(null);
Object.keys(Object(headers)).forEach(function (name) {
normalizedHeaders_1[name.toLowerCase()] = headers[name];
});
return normalizedHeaders_1;
}
var headerData = Object.create(null);
Object.keys(Object(headers)).forEach(function (name) {
headerData[name.toLowerCase()] = { originalName: name, value: headers[name] };
});
var normalizedHeaders = Object.create(null);
Object.keys(headerData).forEach(function (name) {
normalizedHeaders[headerData[name].originalName] = headerData[name].value;
});
return normalizedHeaders;
}
//# sourceMappingURL=selectHttpOptionsAndBody.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/createSignalIfSupported.js
var createSignalIfSupported = function () {
if (typeof AbortController === 'undefined')
return { controller: false, signal: false };
var controller = new AbortController();
var signal = controller.signal;
return { controller: controller, signal: signal };
};
//# sourceMappingURL=createSignalIfSupported.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/rewriteURIForGET.js
function rewriteURIForGET(chosenURI, body) {
var queryParams = [];
var addQueryParam = function (key, value) {
queryParams.push("".concat(key, "=").concat(encodeURIComponent(value)));
};
if ('query' in body) {
addQueryParam('query', body.query);
}
if (body.operationName) {
addQueryParam('operationName', body.operationName);
}
if (body.variables) {
var serializedVariables = void 0;
try {
serializedVariables = serializeFetchParameter(body.variables, 'Variables map');
}
catch (parseError) {
return { parseError: parseError };
}
addQueryParam('variables', serializedVariables);
}
if (body.extensions) {
var serializedExtensions = void 0;
try {
serializedExtensions = serializeFetchParameter(body.extensions, 'Extensions map');
}
catch (parseError) {
return { parseError: parseError };
}
addQueryParam('extensions', serializedExtensions);
}
var fragment = '', preFragment = chosenURI;
var fragmentStart = chosenURI.indexOf('#');
if (fragmentStart !== -1) {
fragment = chosenURI.substr(fragmentStart);
preFragment = chosenURI.substr(0, fragmentStart);
}
var queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';
var newURI = preFragment + queryParamsPrefix + queryParams.join('&') + fragment;
return { newURI: newURI };
}
//# sourceMappingURL=rewriteURIForGET.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/utils/fromError.js
function fromError(errorValue) {
return new Observable(function (observer) {
observer.error(errorValue);
});
}
//# sourceMappingURL=fromError.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/createHttpLink.js
var backupFetch = maybe(function () { return fetch; });
var createHttpLink = function (linkOptions) {
if (linkOptions === void 0) { linkOptions = {}; }
var _a = linkOptions.uri, uri = _a === void 0 ? '/graphql' : _a, preferredFetch = linkOptions.fetch, _b = linkOptions.print, print = _b === void 0 ? defaultPrinter : _b, includeExtensions = linkOptions.includeExtensions, preserveHeaderCase = linkOptions.preserveHeaderCase, useGETForQueries = linkOptions.useGETForQueries, _c = linkOptions.includeUnusedVariables, includeUnusedVariables = _c === void 0 ? false : _c, requestOptions = __rest(linkOptions, ["uri", "fetch", "print", "includeExtensions", "preserveHeaderCase", "useGETForQueries", "includeUnusedVariables"]);
if (__DEV__) {
checkFetcher(preferredFetch || backupFetch);
}
var linkConfig = {
http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
return new ApolloLink_ApolloLink(function (operation) {
var chosenURI = selectURI(operation, uri);
var context = operation.getContext();
var clientAwarenessHeaders = {};
if (context.clientAwareness) {
var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
if (name_1) {
clientAwarenessHeaders['apollographql-client-name'] = name_1;
}
if (version) {
clientAwarenessHeaders['apollographql-client-version'] = version;
}
}
var contextHeaders = __assign(__assign({}, clientAwarenessHeaders), context.headers);
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: contextHeaders,
};
var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;
if (body.variables && !includeUnusedVariables) {
var unusedNames_1 = new Set(Object.keys(body.variables));
visit(operation.query, {
Variable: function (node, _key, parent) {
if (parent && parent.kind !== 'VariableDefinition') {
unusedNames_1.delete(node.name.value);
}
},
});
if (unusedNames_1.size) {
body.variables = __assign({}, body.variables);
unusedNames_1.forEach(function (name) {
delete body.variables[name];
});
}
}
var controller;
if (!options.signal) {
var _c = createSignalIfSupported(), _controller = _c.controller, signal = _c.signal;
controller = _controller;
if (controller)
options.signal = signal;
}
var definitionIsMutation = function (d) {
return d.kind === 'OperationDefinition' && d.operation === 'mutation';
};
var definitionIsSubscription = function (d) {
return d.kind === 'OperationDefinition' && d.operation === 'subscription';
};
var isSubscription = definitionIsSubscription(getMainDefinition(operation.query));
var hasDefer = hasDirectives(['defer'], operation.query);
if (useGETForQueries &&
!operation.query.definitions.some(definitionIsMutation)) {
options.method = 'GET';
}
if (hasDefer || isSubscription) {
options.headers = options.headers || {};
var acceptHeader = "multipart/mixed;";
if (isSubscription && hasDefer) {
__DEV__ && invariant.warn("Multipart-subscriptions do not support @defer");
}
if (isSubscription) {
acceptHeader += 'boundary=graphql;subscriptionSpec=1.0,application/json';
}
else if (hasDefer) {
acceptHeader += 'deferSpec=20220824,application/json';
}
options.headers.accept = acceptHeader;
}
if (options.method === 'GET') {
var _d = rewriteURIForGET(chosenURI, body), newURI = _d.newURI, parseError = _d.parseError;
if (parseError) {
return fromError(parseError);
}
chosenURI = newURI;
}
else {
try {
options.body = serializeFetchParameter(body, 'Payload');
}
catch (parseError) {
return fromError(parseError);
}
}
return new Observable(function (observer) {
var currentFetch = preferredFetch || maybe(function () { return fetch; }) || backupFetch;
currentFetch(chosenURI, options)
.then(function (response) {
var _a;
operation.setContext({ response: response });
var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get('content-type');
if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
return readMultipartBody(response, observer);
}
else {
return readJsonBody(response, operation, observer);
}
})
.catch(function (err) { return handleError(err, observer); });
return function () {
if (controller)
controller.abort();
};
});
});
};
//# sourceMappingURL=createHttpLink.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/link/http/HttpLink.js
var HttpLink_HttpLink = (function (_super) {
__extends(HttpLink, _super);
function HttpLink(options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, createHttpLink(options).request) || this;
_this.options = options;
return _this;
}
return HttpLink;
}(ApolloLink_ApolloLink));
//# sourceMappingURL=HttpLink.js.map
// CONCATENATED MODULE: ./node_modules/@wry/equality/lib/index.js
const { toString: lib_toString, hasOwnProperty: lib_hasOwnProperty } = Object.prototype;
const fnToStr = Function.prototype.toString;
const previousComparisons = new Map();
/**
* Performs a deep equality check on two JavaScript values, tolerating cycles.
*/
function equal(a, b) {
try {
return lib_check(a, b);
}
finally {
previousComparisons.clear();
}
}
// Allow default imports as well.
/* harmony default export */ var lib = (equal);
function lib_check(a, b) {
// If the two values are strictly equal, our job is easy.
if (a === b) {
return true;
}
// Object.prototype.toString returns a representation of the runtime type of
// the given value that is considerably more precise than typeof.
const aTag = lib_toString.call(a);
const bTag = lib_toString.call(b);
// If the runtime types of a and b are different, they could maybe be equal
// under some interpretation of equality, but for simplicity and performance
// we just return false instead.
if (aTag !== bTag) {
return false;
}
switch (aTag) {
case '[object Array]':
// Arrays are a lot like other objects, but we can cheaply compare their
// lengths as a short-cut before comparing their elements.
if (a.length !== b.length)
return false;
// Fall through to object case...
case '[object Object]': {
if (previouslyCompared(a, b))
return true;
const aKeys = definedKeys(a);
const bKeys = definedKeys(b);
// If `a` and `b` have a different number of enumerable keys, they
// must be different.
const keyCount = aKeys.length;
if (keyCount !== bKeys.length)
return false;
// Now make sure they have the same keys.
for (let k = 0; k < keyCount; ++k) {
if (!lib_hasOwnProperty.call(b, aKeys[k])) {
return false;
}
}
// Finally, check deep equality of all child properties.
for (let k = 0; k < keyCount; ++k) {
const key = aKeys[k];
if (!lib_check(a[key], b[key])) {
return false;
}
}
return true;
}
case '[object Error]':
return a.name === b.name && a.message === b.message;
case '[object Number]':
// Handle NaN, which is !== itself.
if (a !== a)
return b !== b;
// Fall through to shared +a === +b case...
case '[object Boolean]':
case '[object Date]':
return +a === +b;
case '[object RegExp]':
case '[object String]':
return a == `${b}`;
case '[object Map]':
case '[object Set]': {
if (a.size !== b.size)
return false;
if (previouslyCompared(a, b))
return true;
const aIterator = a.entries();
const isMap = aTag === '[object Map]';
while (true) {
const info = aIterator.next();
if (info.done)
break;
// If a instanceof Set, aValue === aKey.
const [aKey, aValue] = info.value;
// So this works the same way for both Set and Map.
if (!b.has(aKey)) {
return false;
}
// However, we care about deep equality of values only when dealing
// with Map structures.
if (isMap && !lib_check(aValue, b.get(aKey))) {
return false;
}
}
return true;
}
case '[object Uint16Array]':
case '[object Uint8Array]': // Buffer, in Node.js.
case '[object Uint32Array]':
case '[object Int32Array]':
case '[object Int8Array]':
case '[object Int16Array]':
case '[object ArrayBuffer]':
// DataView doesn't need these conversions, but the equality check is
// otherwise the same.
a = new Uint8Array(a);
b = new Uint8Array(b);
// Fall through...
case '[object DataView]': {
let len = a.byteLength;
if (len === b.byteLength) {
while (len-- && a[len] === b[len]) {
// Keep looping as long as the bytes are equal.
}
}
return len === -1;
}
case '[object AsyncFunction]':
case '[object GeneratorFunction]':
case '[object AsyncGeneratorFunction]':
case '[object Function]': {
const aCode = fnToStr.call(a);
if (aCode !== fnToStr.call(b)) {
return false;
}
// We consider non-native functions equal if they have the same code
// (native functions require === because their code is censored).
// Note that this behavior is not entirely sound, since !== function
// objects with the same code can behave differently depending on
// their closure scope. However, any function can behave differently
// depending on the values of its input arguments (including this)
// and its calling context (including its closure scope), even
// though the function object is === to itself; and it is entirely
// possible for functions that are not === to behave exactly the
// same under all conceivable circumstances. Because none of these
// factors are statically decidable in JavaScript, JS function
// equality is not well-defined. This ambiguity allows us to
// consider the best possible heuristic among various imperfect
// options, and equating non-native functions that have the same
// code has enormous practical benefits, such as when comparing
// functions that are repeatedly passed as fresh function
// expressions within objects that are otherwise deeply equal. Since
// any function created from the same syntactic expression (in the
// same code location) will always stringify to the same code
// according to fnToStr.call, we can reasonably expect these
// repeatedly passed function expressions to have the same code, and
// thus behave "the same" (with all the caveats mentioned above),
// even though the runtime function objects are !== to one another.
return !endsWith(aCode, nativeCodeSuffix);
}
}
// Otherwise the values are not equal.
return false;
}
function definedKeys(obj) {
// Remember that the second argument to Array.prototype.filter will be
// used as `this` within the callback function.
return Object.keys(obj).filter(isDefinedKey, obj);
}
function isDefinedKey(key) {
return this[key] !== void 0;
}
const nativeCodeSuffix = "{ [native code] }";
function endsWith(full, suffix) {
const fromIndex = full.length - suffix.length;
return fromIndex >= 0 &&
full.indexOf(suffix, fromIndex) === fromIndex;
}
function previouslyCompared(a, b) {
// Though cyclic references can make an object graph appear infinite from the
// perspective of a depth-first traversal, the graph still contains a finite
// number of distinct object references. We use the previousComparisons cache
// to avoid comparing the same pair of object references more than once, which
// guarantees termination (even if we end up comparing every object in one
// graph to every object in the other graph, which is extremely unlikely),
// while still allowing weird isomorphic structures (like rings with different
// lengths) a chance to pass the equality test.
let bSet = previousComparisons.get(a);
if (bSet) {
// Return true here because we can be sure false will be returned somewhere
// else if the objects are not equivalent.
if (bSet.has(b))
return true;
}
else {
previousComparisons.set(a, bSet = new Set);
}
bSet.add(b);
return false;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@wry/trie/lib/index.js
// A [trie](https://en.wikipedia.org/wiki/Trie) data structure that holds
// object keys weakly, yet can also hold non-object keys, unlike the
// native `WeakMap`.
// If no makeData function is supplied, the looked-up data will be an empty,
// null-prototype Object.
const defaultMakeData = () => Object.create(null);
// Useful for processing arguments objects as well as arrays.
const { forEach, slice } = Array.prototype;
const { hasOwnProperty: trie_lib_hasOwnProperty } = Object.prototype;
class Trie {
constructor(weakness = true, makeData = defaultMakeData) {
this.weakness = weakness;
this.makeData = makeData;
}
lookup(...array) {
return this.lookupArray(array);
}
lookupArray(array) {
let node = this;
forEach.call(array, key => node = node.getChildTrie(key));
return trie_lib_hasOwnProperty.call(node, "data")
? node.data
: node.data = this.makeData(slice.call(array));
}
peek(...array) {
return this.peekArray(array);
}
peekArray(array) {
let node = this;
for (let i = 0, len = array.length; node && i < len; ++i) {
const map = this.weakness && isObjRef(array[i]) ? node.weak : node.strong;
node = map && map.get(array[i]);
}
return node && node.data;
}
getChildTrie(key) {
const map = this.weakness && isObjRef(key)
? this.weak || (this.weak = new WeakMap())
: this.strong || (this.strong = new Map());
let child = map.get(key);
if (!child)
map.set(key, child = new Trie(this.weakness, this.makeData));
return child;
}
}
function isObjRef(value) {
switch (typeof value) {
case "object":
if (value === null)
break;
// Fall through to return true...
case "function":
return true;
}
return false;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/object-canon.js
function object_canon_shallowCopy(value) {
if (isNonNullObject(value)) {
return arrays_isArray(value)
? value.slice(0)
: __assign({ __proto__: Object.getPrototypeOf(value) }, value);
}
return value;
}
var object_canon_ObjectCanon = (function () {
function ObjectCanon() {
this.known = new (canUseWeakSet ? WeakSet : Set)();
this.pool = new Trie(canUseWeakMap);
this.passes = new WeakMap();
this.keysByJSON = new Map();
this.empty = this.admit({});
}
ObjectCanon.prototype.isKnown = function (value) {
return isNonNullObject(value) && this.known.has(value);
};
ObjectCanon.prototype.pass = function (value) {
if (isNonNullObject(value)) {
var copy = object_canon_shallowCopy(value);
this.passes.set(copy, value);
return copy;
}
return value;
};
ObjectCanon.prototype.admit = function (value) {
var _this = this;
if (isNonNullObject(value)) {
var original = this.passes.get(value);
if (original)
return original;
var proto = Object.getPrototypeOf(value);
switch (proto) {
case Array.prototype: {
if (this.known.has(value))
return value;
var array = value.map(this.admit, this);
var node = this.pool.lookupArray(array);
if (!node.array) {
this.known.add(node.array = array);
if (__DEV__) {
Object.freeze(array);
}
}
return node.array;
}
case null:
case Object.prototype: {
if (this.known.has(value))
return value;
var proto_1 = Object.getPrototypeOf(value);
var array_1 = [proto_1];
var keys = this.sortedKeys(value);
array_1.push(keys.json);
var firstValueIndex_1 = array_1.length;
keys.sorted.forEach(function (key) {
array_1.push(_this.admit(value[key]));
});
var node = this.pool.lookupArray(array_1);
if (!node.object) {
var obj_1 = node.object = Object.create(proto_1);
this.known.add(obj_1);
keys.sorted.forEach(function (key, i) {
obj_1[key] = array_1[firstValueIndex_1 + i];
});
if (__DEV__) {
Object.freeze(obj_1);
}
}
return node.object;
}
}
}
return value;
};
ObjectCanon.prototype.sortedKeys = function (obj) {
var keys = Object.keys(obj);
var node = this.pool.lookupArray(keys);
if (!node.keys) {
keys.sort();
var json = JSON.stringify(keys);
if (!(node.keys = this.keysByJSON.get(json))) {
this.keysByJSON.set(json, node.keys = { sorted: keys, json: json });
}
}
return node.keys;
};
return ObjectCanon;
}());
var canonicalStringify = Object.assign(function (value) {
if (isNonNullObject(value)) {
if (stringifyCanon === void 0) {
resetCanonicalStringify();
}
var canonical = stringifyCanon.admit(value);
var json = stringifyCache.get(canonical);
if (json === void 0) {
stringifyCache.set(canonical, json = JSON.stringify(canonical));
}
return json;
}
return JSON.stringify(value);
}, {
reset: resetCanonicalStringify,
});
var stringifyCanon;
var stringifyCache;
function resetCanonicalStringify() {
stringifyCanon = new object_canon_ObjectCanon;
stringifyCache = new (canUseWeakMap ? WeakMap : Map)();
}
//# sourceMappingURL=object-canon.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/observables/asyncMap.js
function asyncMap(observable, mapFn, catchFn) {
return new Observable(function (observer) {
var next = observer.next, error = observer.error, complete = observer.complete;
var activeCallbackCount = 0;
var completed = false;
var promiseQueue = {
then: function (callback) {
return new Promise(function (resolve) { return resolve(callback()); });
},
};
function makeCallback(examiner, delegate) {
if (examiner) {
return function (arg) {
++activeCallbackCount;
var both = function () { return examiner(arg); };
promiseQueue = promiseQueue.then(both, both).then(function (result) {
--activeCallbackCount;
next && next.call(observer, result);
if (completed) {
handler.complete();
}
}, function (error) {
--activeCallbackCount;
throw error;
}).catch(function (caught) {
error && error.call(observer, caught);
});
};
}
else {
return function (arg) { return delegate && delegate.call(observer, arg); };
}
}
var handler = {
next: makeCallback(mapFn, next),
error: makeCallback(catchFn, error),
complete: function () {
completed = true;
if (!activeCallbackCount) {
complete && complete.call(observer);
}
},
};
var sub = observable.subscribe(handler);
return function () { return sub.unsubscribe(); };
});
}
//# sourceMappingURL=asyncMap.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/errorHandling.js
function graphQLResultHasError(result) {
var errors = getGraphQLErrorsFromResult(result);
return isNonEmptyArray(errors);
}
function getGraphQLErrorsFromResult(result) {
var graphQLErrors = isNonEmptyArray(result.errors)
? result.errors.slice(0)
: [];
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
result.incremental.forEach(function (incrementalResult) {
if (incrementalResult.errors) {
graphQLErrors.push.apply(graphQLErrors, incrementalResult.errors);
}
});
}
return graphQLErrors;
}
//# sourceMappingURL=errorHandling.js.map
// CONCATENATED MODULE: ./node_modules/graphql/language/kinds.mjs
/**
* The set of allowed kind values for AST nodes.
*/
var Kind = Object.freeze({
// Name
NAME: 'Name',
// Document
DOCUMENT: 'Document',
OPERATION_DEFINITION: 'OperationDefinition',
VARIABLE_DEFINITION: 'VariableDefinition',
SELECTION_SET: 'SelectionSet',
FIELD: 'Field',
ARGUMENT: 'Argument',
// Fragments
FRAGMENT_SPREAD: 'FragmentSpread',
INLINE_FRAGMENT: 'InlineFragment',
FRAGMENT_DEFINITION: 'FragmentDefinition',
// Values
VARIABLE: 'Variable',
INT: 'IntValue',
FLOAT: 'FloatValue',
STRING: 'StringValue',
BOOLEAN: 'BooleanValue',
NULL: 'NullValue',
ENUM: 'EnumValue',
LIST: 'ListValue',
OBJECT: 'ObjectValue',
OBJECT_FIELD: 'ObjectField',
// Directives
DIRECTIVE: 'Directive',
// Types
NAMED_TYPE: 'NamedType',
LIST_TYPE: 'ListType',
NON_NULL_TYPE: 'NonNullType',
// Type System Definitions
SCHEMA_DEFINITION: 'SchemaDefinition',
OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',
// Type Definitions
SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',
OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',
FIELD_DEFINITION: 'FieldDefinition',
INPUT_VALUE_DEFINITION: 'InputValueDefinition',
INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',
UNION_TYPE_DEFINITION: 'UnionTypeDefinition',
ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',
ENUM_VALUE_DEFINITION: 'EnumValueDefinition',
INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',
// Directive Definitions
DIRECTIVE_DEFINITION: 'DirectiveDefinition',
// Type System Extensions
SCHEMA_EXTENSION: 'SchemaExtension',
// Type Extensions
SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',
OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',
INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',
UNION_TYPE_EXTENSION: 'UnionTypeExtension',
ENUM_TYPE_EXTENSION: 'EnumTypeExtension',
INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'
});
/**
* The enum type representing the possible kind values of AST nodes.
*/
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/graphql/transform.js
var TYPENAME_FIELD = {
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: '__typename',
},
};
function isEmpty(op, fragmentMap) {
return !op || op.selectionSet.selections.every(function (selection) { return selection.kind === Kind.FRAGMENT_SPREAD &&
isEmpty(fragmentMap[selection.name.value], fragmentMap); });
}
function nullIfDocIsEmpty(doc) {
return isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))
? null
: doc;
}
function getDirectiveMatcher(directives) {
var nameSet = new Set();
var tests = [];
directives.forEach(function (directive) {
if (directive.name) {
nameSet.add(directive.name);
}
else if (directive.test) {
tests.push(directive.test);
}
});
return function (directive) { return (nameSet.has(directive.name.value) ||
tests.some(function (test) { return test(directive); })); };
}
function makeInUseGetterFunction(defaultKey) {
var map = new Map();
return function inUseGetterFunction(key) {
if (key === void 0) { key = defaultKey; }
var inUse = map.get(key);
if (!inUse) {
map.set(key, inUse = {
variables: new Set,
fragmentSpreads: new Set,
});
}
return inUse;
};
}
function removeDirectivesFromDocument(directives, doc) {
var getInUseByOperationName = makeInUseGetterFunction("");
var getInUseByFragmentName = makeInUseGetterFunction("");
var getInUse = function (ancestors) {
for (var p = 0, ancestor = void 0; p < ancestors.length && (ancestor = ancestors[p]); ++p) {
if (arrays_isArray(ancestor))
continue;
if (ancestor.kind === Kind.OPERATION_DEFINITION) {
return getInUseByOperationName(ancestor.name && ancestor.name.value);
}
if (ancestor.kind === Kind.FRAGMENT_DEFINITION) {
return getInUseByFragmentName(ancestor.name.value);
}
}
__DEV__ && invariant.error("Could not find operation or fragment");
return null;
};
var operationCount = 0;
for (var i = doc.definitions.length - 1; i >= 0; --i) {
if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {
++operationCount;
}
}
var directiveMatcher = getDirectiveMatcher(directives);
var hasRemoveDirective = directives.some(function (directive) { return directive.remove; });
var shouldRemoveField = function (nodeDirectives) { return (hasRemoveDirective &&
nodeDirectives &&
nodeDirectives.some(directiveMatcher)); };
var originalFragmentDefsByPath = new Map();
var firstVisitMadeChanges = false;
var fieldOrInlineFragmentVisitor = {
enter: function (node) {
if (shouldRemoveField(node.directives)) {
firstVisitMadeChanges = true;
return null;
}
},
};
var docWithoutDirectiveSubtrees = visit(doc, {
Field: fieldOrInlineFragmentVisitor,
InlineFragment: fieldOrInlineFragmentVisitor,
VariableDefinition: {
enter: function () {
return false;
},
},
Variable: {
enter: function (node, _key, _parent, _path, ancestors) {
var inUse = getInUse(ancestors);
if (inUse) {
inUse.variables.add(node.name.value);
}
},
},
FragmentSpread: {
enter: function (node, _key, _parent, _path, ancestors) {
if (shouldRemoveField(node.directives)) {
firstVisitMadeChanges = true;
return null;
}
var inUse = getInUse(ancestors);
if (inUse) {
inUse.fragmentSpreads.add(node.name.value);
}
},
},
FragmentDefinition: {
enter: function (node, _key, _parent, path) {
originalFragmentDefsByPath.set(JSON.stringify(path), node);
},
leave: function (node, _key, _parent, path) {
var originalNode = originalFragmentDefsByPath.get(JSON.stringify(path));
if (node === originalNode) {
return node;
}
if (operationCount > 0 &&
node.selectionSet.selections.every(function (selection) { return (selection.kind === Kind.FIELD &&
selection.name.value === '__typename'); })) {
getInUseByFragmentName(node.name.value).removed = true;
firstVisitMadeChanges = true;
return null;
}
},
},
Directive: {
leave: function (node) {
if (directiveMatcher(node)) {
firstVisitMadeChanges = true;
return null;
}
},
},
});
if (!firstVisitMadeChanges) {
return doc;
}
var populateTransitiveVars = function (inUse) {
if (!inUse.transitiveVars) {
inUse.transitiveVars = new Set(inUse.variables);
if (!inUse.removed) {
inUse.fragmentSpreads.forEach(function (childFragmentName) {
populateTransitiveVars(getInUseByFragmentName(childFragmentName)).transitiveVars.forEach(function (varName) {
inUse.transitiveVars.add(varName);
});
});
}
}
return inUse;
};
var allFragmentNamesUsed = new Set();
docWithoutDirectiveSubtrees.definitions.forEach(function (def) {
if (def.kind === Kind.OPERATION_DEFINITION) {
populateTransitiveVars(getInUseByOperationName(def.name && def.name.value)).fragmentSpreads.forEach(function (childFragmentName) {
allFragmentNamesUsed.add(childFragmentName);
});
}
else if (def.kind === Kind.FRAGMENT_DEFINITION &&
operationCount === 0 &&
!getInUseByFragmentName(def.name.value).removed) {
allFragmentNamesUsed.add(def.name.value);
}
});
allFragmentNamesUsed.forEach(function (fragmentName) {
populateTransitiveVars(getInUseByFragmentName(fragmentName)).fragmentSpreads.forEach(function (childFragmentName) {
allFragmentNamesUsed.add(childFragmentName);
});
});
var fragmentWillBeRemoved = function (fragmentName) { return !!(!allFragmentNamesUsed.has(fragmentName) ||
getInUseByFragmentName(fragmentName).removed); };
var enterVisitor = {
enter: function (node) {
if (fragmentWillBeRemoved(node.name.value)) {
return null;
}
},
};
return nullIfDocIsEmpty(visit(docWithoutDirectiveSubtrees, {
FragmentSpread: enterVisitor,
FragmentDefinition: enterVisitor,
OperationDefinition: {
leave: function (node) {
if (node.variableDefinitions) {
var usedVariableNames_1 = populateTransitiveVars(getInUseByOperationName(node.name && node.name.value)).transitiveVars;
if (usedVariableNames_1.size < node.variableDefinitions.length) {
return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions.filter(function (varDef) { return usedVariableNames_1.has(varDef.variable.name.value); }) });
}
}
},
},
}));
}
var addTypenameToDocument = Object.assign(function (doc) {
return visit(doc, {
SelectionSet: {
enter: function (node, _key, parent) {
if (parent &&
parent.kind === Kind.OPERATION_DEFINITION) {
return;
}
var selections = node.selections;
if (!selections) {
return;
}
var skip = selections.some(function (selection) {
return (isField(selection) &&
(selection.name.value === '__typename' ||
selection.name.value.lastIndexOf('__', 0) === 0));
});
if (skip) {
return;
}
var field = parent;
if (isField(field) &&
field.directives &&
field.directives.some(function (d) { return d.name.value === 'export'; })) {
return;
}
return __assign(__assign({}, node), { selections: __spreadArray(__spreadArray([], selections, true), [TYPENAME_FIELD], false) });
},
},
});
}, {
added: function (field) {
return field === TYPENAME_FIELD;
},
});
var connectionRemoveConfig = {
test: function (directive) {
var willRemove = directive.name.value === 'connection';
if (willRemove) {
if (!directive.arguments ||
!directive.arguments.some(function (arg) { return arg.name.value === 'key'; })) {
__DEV__ && invariant.warn('Removing an @connection directive even though it does not have a key. ' +
'You may want to use the key parameter to specify a store key.');
}
}
return willRemove;
},
};
function removeConnectionDirectiveFromDocument(doc) {
return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));
}
function hasDirectivesInSelectionSet(directives, selectionSet, nestedCheck) {
if (nestedCheck === void 0) { nestedCheck = true; }
return (!!selectionSet &&
selectionSet.selections &&
selectionSet.selections.some(function (selection) {
return hasDirectivesInSelection(directives, selection, nestedCheck);
}));
}
function hasDirectivesInSelection(directives, selection, nestedCheck) {
if (nestedCheck === void 0) { nestedCheck = true; }
if (!isField(selection)) {
return true;
}
if (!selection.directives) {
return false;
}
return (selection.directives.some(getDirectiveMatcher(directives)) ||
(nestedCheck &&
hasDirectivesInSelectionSet(directives, selection.selectionSet, nestedCheck)));
}
function getArgumentMatcher(config) {
return function argumentMatcher(argument) {
return config.some(function (aConfig) {
return argument.value &&
argument.value.kind === Kind.VARIABLE &&
argument.value.name &&
(aConfig.name === argument.value.name.value ||
(aConfig.test && aConfig.test(argument)));
});
};
}
function removeArgumentsFromDocument(config, doc) {
var argMatcher = getArgumentMatcher(config);
return nullIfDocIsEmpty(visit(doc, {
OperationDefinition: {
enter: function (node) {
return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions ? node.variableDefinitions.filter(function (varDef) {
return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });
}) : [] });
},
},
Field: {
enter: function (node) {
var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });
if (shouldRemoveField) {
var argMatchCount_1 = 0;
if (node.arguments) {
node.arguments.forEach(function (arg) {
if (argMatcher(arg)) {
argMatchCount_1 += 1;
}
});
}
if (argMatchCount_1 === 1) {
return null;
}
}
},
},
Argument: {
enter: function (node) {
if (argMatcher(node)) {
return null;
}
},
},
}));
}
function removeFragmentSpreadFromDocument(config, doc) {
function enter(node) {
if (config.some(function (def) { return def.name === node.name.value; })) {
return null;
}
}
return nullIfDocIsEmpty(visit(doc, {
FragmentSpread: { enter: enter },
FragmentDefinition: { enter: enter },
}));
}
function buildQueryFromSelectionSet(document) {
var definition = getMainDefinition(document);
var definitionOperation = definition.operation;
if (definitionOperation === 'query') {
return document;
}
var modifiedDoc = visit(document, {
OperationDefinition: {
enter: function (node) {
return __assign(__assign({}, node), { operation: 'query' });
},
},
});
return modifiedDoc;
}
function removeClientSetsFromDocument(document) {
checkDocument(document);
var modifiedDoc = removeDirectivesFromDocument([
{
test: function (directive) { return directive.name.value === 'client'; },
remove: true,
},
], document);
return modifiedDoc;
}
//# sourceMappingURL=transform.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/makeUniqueId.js
var prefixCounts = new Map();
function makeUniqueId(prefix) {
var count = prefixCounts.get(prefix) || 1;
prefixCounts.set(prefix, count + 1);
return "".concat(prefix, ":").concat(count, ":").concat(Math.random().toString(36).slice(2));
}
//# sourceMappingURL=makeUniqueId.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/observables/iteration.js
function iterateObserversSafely(observers, method, argument) {
var observersWithMethod = [];
observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });
observersWithMethod.forEach(function (obs) { return obs[method](argument); });
}
//# sourceMappingURL=iteration.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/observables/subclassing.js
function fixObservableSubclass(subclass) {
function set(key) {
Object.defineProperty(subclass, key, { value: Observable });
}
if (canUseSymbol && Symbol.species) {
set(Symbol.species);
}
set("@@species");
return subclass;
}
//# sourceMappingURL=subclassing.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/observables/Concast.js
function isPromiseLike(value) {
return value && typeof value.then === "function";
}
var Concast_Concast = (function (_super) {
__extends(Concast, _super);
function Concast(sources) {
var _this = _super.call(this, function (observer) {
_this.addObserver(observer);
return function () { return _this.removeObserver(observer); };
}) || this;
_this.observers = new Set();
_this.promise = new Promise(function (resolve, reject) {
_this.resolve = resolve;
_this.reject = reject;
});
_this.handlers = {
next: function (result) {
if (_this.sub !== null) {
_this.latest = ["next", result];
_this.notify("next", result);
iterateObserversSafely(_this.observers, "next", result);
}
},
error: function (error) {
var sub = _this.sub;
if (sub !== null) {
if (sub)
setTimeout(function () { return sub.unsubscribe(); });
_this.sub = null;
_this.latest = ["error", error];
_this.reject(error);
_this.notify("error", error);
iterateObserversSafely(_this.observers, "error", error);
}
},
complete: function () {
var _a = _this, sub = _a.sub, _b = _a.sources, sources = _b === void 0 ? [] : _b;
if (sub !== null) {
var value = sources.shift();
if (!value) {
if (sub)
setTimeout(function () { return sub.unsubscribe(); });
_this.sub = null;
if (_this.latest &&
_this.latest[0] === "next") {
_this.resolve(_this.latest[1]);
}
else {
_this.resolve();
}
_this.notify("complete");
iterateObserversSafely(_this.observers, "complete");
}
else if (isPromiseLike(value)) {
value.then(function (obs) { return _this.sub = obs.subscribe(_this.handlers); });
}
else {
_this.sub = value.subscribe(_this.handlers);
}
}
},
};
_this.nextResultListeners = new Set();
_this.cancel = function (reason) {
_this.reject(reason);
_this.sources = [];
_this.handlers.complete();
};
_this.promise.catch(function (_) { });
if (typeof sources === "function") {
sources = [new Observable(sources)];
}
if (isPromiseLike(sources)) {
sources.then(function (iterable) { return _this.start(iterable); }, _this.handlers.error);
}
else {
_this.start(sources);
}
return _this;
}
Concast.prototype.start = function (sources) {
if (this.sub !== void 0)
return;
this.sources = Array.from(sources);
this.handlers.complete();
};
Concast.prototype.deliverLastMessage = function (observer) {
if (this.latest) {
var nextOrError = this.latest[0];
var method = observer[nextOrError];
if (method) {
method.call(observer, this.latest[1]);
}
if (this.sub === null &&
nextOrError === "next" &&
observer.complete) {
observer.complete();
}
}
};
Concast.prototype.addObserver = function (observer) {
if (!this.observers.has(observer)) {
this.deliverLastMessage(observer);
this.observers.add(observer);
}
};
Concast.prototype.removeObserver = function (observer) {
if (this.observers.delete(observer) &&
this.observers.size < 1) {
this.handlers.complete();
}
};
Concast.prototype.notify = function (method, arg) {
var nextResultListeners = this.nextResultListeners;
if (nextResultListeners.size) {
this.nextResultListeners = new Set;
nextResultListeners.forEach(function (listener) { return listener(method, arg); });
}
};
Concast.prototype.beforeNext = function (callback) {
var called = false;
this.nextResultListeners.add(function (method, arg) {
if (!called) {
called = true;
callback(method, arg);
}
});
};
return Concast;
}(Observable));
fixObservableSubclass(Concast_Concast);
//# sourceMappingURL=Concast.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/core/networkStatus.js
var NetworkStatus;
(function (NetworkStatus) {
NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
NetworkStatus[NetworkStatus["error"] = 8] = "error";
})(NetworkStatus || (NetworkStatus = {}));
function isNetworkRequestInFlight(networkStatus) {
return networkStatus ? networkStatus < 7 : false;
}
//# sourceMappingURL=networkStatus.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/cloneDeep.js
var cloneDeep_toString = Object.prototype.toString;
function cloneDeep(value) {
return cloneDeepHelper(value);
}
function cloneDeepHelper(val, seen) {
switch (cloneDeep_toString.call(val)) {
case "[object Array]": {
seen = seen || new Map;
if (seen.has(val))
return seen.get(val);
var copy_1 = val.slice(0);
seen.set(val, copy_1);
copy_1.forEach(function (child, i) {
copy_1[i] = cloneDeepHelper(child, seen);
});
return copy_1;
}
case "[object Object]": {
seen = seen || new Map;
if (seen.has(val))
return seen.get(val);
var copy_2 = Object.create(Object.getPrototypeOf(val));
seen.set(val, copy_2);
Object.keys(val).forEach(function (key) {
copy_2[key] = cloneDeepHelper(val[key], seen);
});
return copy_2;
}
default:
return val;
}
}
//# sourceMappingURL=cloneDeep.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/compact.js
function compact() {
var objects = [];
for (var _i = 0; _i < arguments.length; _i++) {
objects[_i] = arguments[_i];
}
var result = Object.create(null);
objects.forEach(function (obj) {
if (!obj)
return;
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (value !== void 0) {
result[key] = value;
}
});
});
return result;
}
//# sourceMappingURL=compact.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/core/ObservableQuery.js
var ObservableQuery_assign = Object.assign, ObservableQuery_hasOwnProperty = Object.hasOwnProperty;
var ObservableQuery_ObservableQuery = (function (_super) {
__extends(ObservableQuery, _super);
function ObservableQuery(_a) {
var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;
var _this = _super.call(this, function (observer) {
try {
var subObserver = observer._subscription._observer;
if (subObserver && !subObserver.error) {
subObserver.error = defaultSubscriptionObserverErrorCallback;
}
}
catch (_a) { }
var first = !_this.observers.size;
_this.observers.add(observer);
var last = _this.last;
if (last && last.error) {
observer.error && observer.error(last.error);
}
else if (last && last.result) {
observer.next && observer.next(last.result);
}
if (first) {
_this.reobserve().catch(function () { });
}
return function () {
if (_this.observers.delete(observer) && !_this.observers.size) {
_this.tearDownQuery();
}
};
}) || this;
_this.observers = new Set();
_this.subscriptions = new Set();
_this.queryInfo = queryInfo;
_this.queryManager = queryManager;
_this.isTornDown = false;
var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? "cache-first" : _d;
var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e, _f = options.initialFetchPolicy, initialFetchPolicy = _f === void 0 ? (fetchPolicy === "standby" ? defaultFetchPolicy : fetchPolicy) : _f;
_this.options = __assign(__assign({}, options), { initialFetchPolicy: initialFetchPolicy, fetchPolicy: fetchPolicy });
_this.queryId = queryInfo.queryId || queryManager.generateQueryId();
var opDef = getOperationDefinition(_this.query);
_this.queryName = opDef && opDef.name && opDef.name.value;
return _this;
}
Object.defineProperty(ObservableQuery.prototype, "query", {
get: function () {
return this.queryManager.transform(this.options.query).document;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ObservableQuery.prototype, "variables", {
get: function () {
return this.options.variables;
},
enumerable: false,
configurable: true
});
ObservableQuery.prototype.result = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var observer = {
next: function (result) {
resolve(result);
_this.observers.delete(observer);
if (!_this.observers.size) {
_this.queryManager.removeQuery(_this.queryId);
}
setTimeout(function () {
subscription.unsubscribe();
}, 0);
},
error: reject,
};
var subscription = _this.subscribe(observer);
});
};
ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {
if (saveAsLastResult === void 0) { saveAsLastResult = true; }
var lastResult = this.getLastResult(true);
var networkStatus = this.queryInfo.networkStatus ||
(lastResult && lastResult.networkStatus) ||
NetworkStatus.ready;
var result = __assign(__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });
var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a;
if (fetchPolicy === 'network-only' ||
fetchPolicy === 'no-cache' ||
fetchPolicy === 'standby' ||
this.queryManager.transform(this.options.query).hasForcedResolvers) {
}
else {
var diff = this.queryInfo.getDiff();
if (diff.complete || this.options.returnPartialData) {
result.data = diff.result;
}
if (equal(result.data, {})) {
result.data = void 0;
}
if (diff.complete) {
delete result.partial;
if (diff.complete &&
result.networkStatus === NetworkStatus.loading &&
(fetchPolicy === 'cache-first' ||
fetchPolicy === 'cache-only')) {
result.networkStatus = NetworkStatus.ready;
result.loading = false;
}
}
else {
result.partial = true;
}
if (__DEV__ &&
!diff.complete &&
!this.options.partialRefetch &&
!result.loading &&
!result.data &&
!result.error) {
logMissingFieldErrors(diff.missing);
}
}
if (saveAsLastResult) {
this.updateLastResult(result);
}
return result;
};
ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {
return (!this.last ||
!equal(this.last.result, newResult) ||
(variables && !equal(this.last.variables, variables)));
};
ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {
var last = this.last;
if (last &&
last[key] &&
(!variablesMustMatch || equal(last.variables, this.variables))) {
return last[key];
}
};
ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {
return this.getLast("result", variablesMustMatch);
};
ObservableQuery.prototype.getLastError = function (variablesMustMatch) {
return this.getLast("error", variablesMustMatch);
};
ObservableQuery.prototype.resetLastResults = function () {
delete this.last;
this.isTornDown = false;
};
ObservableQuery.prototype.resetQueryStoreErrors = function () {
this.queryManager.resetErrors(this.queryId);
};
ObservableQuery.prototype.refetch = function (variables) {
var _a;
var reobserveOptions = {
pollInterval: 0,
};
var fetchPolicy = this.options.fetchPolicy;
if (fetchPolicy === 'cache-and-network') {
reobserveOptions.fetchPolicy = fetchPolicy;
}
else if (fetchPolicy === 'no-cache') {
reobserveOptions.fetchPolicy = 'no-cache';
}
else {
reobserveOptions.fetchPolicy = 'network-only';
}
if (__DEV__ && variables && ObservableQuery_hasOwnProperty.call(variables, "variables")) {
var queryDef = getQueryDefinition(this.query);
var vars = queryDef.variableDefinitions;
if (!vars || !vars.some(function (v) { return v.variable.name.value === "variables"; })) {
__DEV__ && invariant.warn("Called refetch(".concat(JSON.stringify(variables), ") for query ").concat(((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || JSON.stringify(queryDef), ", which does not declare a $variables variable.\nDid you mean to call refetch(variables) instead of refetch({ variables })?"));
}
}
if (variables && !equal(this.options.variables, variables)) {
reobserveOptions.variables = this.options.variables = __assign(__assign({}, this.options.variables), variables);
}
this.queryInfo.resetLastWrite();
return this.reobserve(reobserveOptions, NetworkStatus.refetch);
};
ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
var _this = this;
var combinedOptions = __assign(__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : __assign(__assign(__assign(__assign({}, this.options), { query: this.query }), fetchMoreOptions), { variables: __assign(__assign({}, this.options.variables), fetchMoreOptions.variables) }))), { fetchPolicy: "no-cache" });
var qid = this.queryManager.generateQueryId();
var queryInfo = this.queryInfo;
var originalNetworkStatus = queryInfo.networkStatus;
queryInfo.networkStatus = NetworkStatus.fetchMore;
if (combinedOptions.notifyOnNetworkStatusChange) {
this.observe();
}
var updatedQuerySet = new Set();
return this.queryManager.fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore).then(function (fetchMoreResult) {
_this.queryManager.removeQuery(qid);
if (queryInfo.networkStatus === NetworkStatus.fetchMore) {
queryInfo.networkStatus = originalNetworkStatus;
}
_this.queryManager.cache.batch({
update: function (cache) {
var updateQuery = fetchMoreOptions.updateQuery;
if (updateQuery) {
cache.updateQuery({
query: _this.query,
variables: _this.variables,
returnPartialData: true,
optimistic: false,
}, function (previous) { return updateQuery(previous, {
fetchMoreResult: fetchMoreResult.data,
variables: combinedOptions.variables,
}); });
}
else {
cache.writeQuery({
query: combinedOptions.query,
variables: combinedOptions.variables,
data: fetchMoreResult.data,
});
}
},
onWatchUpdated: function (watch) {
updatedQuerySet.add(watch.query);
},
});
return fetchMoreResult;
}).finally(function () {
if (!updatedQuerySet.has(_this.query)) {
reobserveCacheFirst(_this);
}
});
};
ObservableQuery.prototype.subscribeToMore = function (options) {
var _this = this;
var subscription = this.queryManager
.startGraphQLSubscription({
query: options.document,
variables: options.variables,
context: options.context,
})
.subscribe({
next: function (subscriptionData) {
var updateQuery = options.updateQuery;
if (updateQuery) {
_this.updateQuery(function (previous, _a) {
var variables = _a.variables;
return updateQuery(previous, {
subscriptionData: subscriptionData,
variables: variables,
});
});
}
},
error: function (err) {
if (options.onError) {
options.onError(err);
return;
}
__DEV__ && invariant.error('Unhandled GraphQL subscription error', err);
},
});
this.subscriptions.add(subscription);
return function () {
if (_this.subscriptions.delete(subscription)) {
subscription.unsubscribe();
}
};
};
ObservableQuery.prototype.setOptions = function (newOptions) {
return this.reobserve(newOptions);
};
ObservableQuery.prototype.setVariables = function (variables) {
if (equal(this.variables, variables)) {
return this.observers.size
? this.result()
: Promise.resolve();
}
this.options.variables = variables;
if (!this.observers.size) {
return Promise.resolve();
}
return this.reobserve({
fetchPolicy: this.options.initialFetchPolicy,
variables: variables,
}, NetworkStatus.setVariables);
};
ObservableQuery.prototype.updateQuery = function (mapFn) {
var queryManager = this.queryManager;
var result = queryManager.cache.diff({
query: this.options.query,
variables: this.variables,
returnPartialData: true,
optimistic: false,
}).result;
var newResult = mapFn(result, {
variables: this.variables,
});
if (newResult) {
queryManager.cache.writeQuery({
query: this.options.query,
data: newResult,
variables: this.variables,
});
queryManager.broadcastQueries();
}
};
ObservableQuery.prototype.startPolling = function (pollInterval) {
this.options.pollInterval = pollInterval;
this.updatePolling();
};
ObservableQuery.prototype.stopPolling = function () {
this.options.pollInterval = 0;
this.updatePolling();
};
ObservableQuery.prototype.applyNextFetchPolicy = function (reason, options) {
if (options.nextFetchPolicy) {
var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;
if (fetchPolicy === "standby") {
}
else if (typeof options.nextFetchPolicy === "function") {
options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {
reason: reason,
options: options,
observable: this,
initialFetchPolicy: initialFetchPolicy,
});
}
else if (reason === "variables-changed") {
options.fetchPolicy = initialFetchPolicy;
}
else {
options.fetchPolicy = options.nextFetchPolicy;
}
}
return options.fetchPolicy;
};
ObservableQuery.prototype.fetch = function (options, newNetworkStatus) {
this.queryManager.setObservableQuery(this);
return this.queryManager['fetchConcastWithInfo'](this.queryId, options, newNetworkStatus);
};
ObservableQuery.prototype.updatePolling = function () {
var _this = this;
if (this.queryManager.ssrMode) {
return;
}
var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;
if (!pollInterval) {
if (pollingInfo) {
clearTimeout(pollingInfo.timeout);
delete this.pollingInfo;
}
return;
}
if (pollingInfo &&
pollingInfo.interval === pollInterval) {
return;
}
__DEV__ ? invariant(pollInterval, 'Attempted to start a polling query without a polling interval.') : invariant(pollInterval, 13);
var info = pollingInfo || (this.pollingInfo = {});
info.interval = pollInterval;
var maybeFetch = function () {
if (_this.pollingInfo) {
if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus)) {
_this.reobserve({
fetchPolicy: _this.options.initialFetchPolicy === 'no-cache' ? 'no-cache' : 'network-only',
}, NetworkStatus.poll).then(poll, poll);
}
else {
poll();
}
}
;
};
var poll = function () {
var info = _this.pollingInfo;
if (info) {
clearTimeout(info.timeout);
info.timeout = setTimeout(maybeFetch, info.interval);
}
};
poll();
};
ObservableQuery.prototype.updateLastResult = function (newResult, variables) {
if (variables === void 0) { variables = this.variables; }
this.last = __assign(__assign({}, this.last), { result: this.queryManager.assumeImmutableResults
? newResult
: cloneDeep(newResult), variables: variables });
if (!isNonEmptyArray(newResult.errors)) {
delete this.last.error;
}
return this.last;
};
ObservableQuery.prototype.reobserveAsConcast = function (newOptions, newNetworkStatus) {
var _this = this;
this.isTornDown = false;
var useDisposableConcast = newNetworkStatus === NetworkStatus.refetch ||
newNetworkStatus === NetworkStatus.fetchMore ||
newNetworkStatus === NetworkStatus.poll;
var oldVariables = this.options.variables;
var oldFetchPolicy = this.options.fetchPolicy;
var mergedOptions = compact(this.options, newOptions || {});
var options = useDisposableConcast
? mergedOptions
: ObservableQuery_assign(this.options, mergedOptions);
if (!useDisposableConcast) {
this.updatePolling();
if (newOptions &&
newOptions.variables &&
!equal(newOptions.variables, oldVariables) &&
options.fetchPolicy !== "standby" &&
options.fetchPolicy === oldFetchPolicy) {
this.applyNextFetchPolicy("variables-changed", options);
if (newNetworkStatus === void 0) {
newNetworkStatus = NetworkStatus.setVariables;
}
}
}
var variables = options.variables && __assign({}, options.variables);
var _a = this.fetch(options, newNetworkStatus), concast = _a.concast, fromLink = _a.fromLink;
var observer = {
next: function (result) {
_this.reportResult(result, variables);
},
error: function (error) {
_this.reportError(error, variables);
},
};
if (!useDisposableConcast && fromLink) {
if (this.concast && this.observer) {
this.concast.removeObserver(this.observer);
}
this.concast = concast;
this.observer = observer;
}
concast.addObserver(observer);
return concast;
};
ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {
return this.reobserveAsConcast(newOptions, newNetworkStatus).promise;
};
ObservableQuery.prototype.observe = function () {
this.reportResult(this.getCurrentResult(false), this.variables);
};
ObservableQuery.prototype.reportResult = function (result, variables) {
var lastError = this.getLastError();
if (lastError || this.isDifferentFromLastResult(result, variables)) {
if (lastError || !result.partial || this.options.returnPartialData) {
this.updateLastResult(result, variables);
}
iterateObserversSafely(this.observers, 'next', result);
}
};
ObservableQuery.prototype.reportError = function (error, variables) {
var errorResult = __assign(__assign({}, this.getLastResult()), { error: error, errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false });
this.updateLastResult(errorResult, variables);
iterateObserversSafely(this.observers, 'error', this.last.error = error);
};
ObservableQuery.prototype.hasObservers = function () {
return this.observers.size > 0;
};
ObservableQuery.prototype.tearDownQuery = function () {
if (this.isTornDown)
return;
if (this.concast && this.observer) {
this.concast.removeObserver(this.observer);
delete this.concast;
delete this.observer;
}
this.stopPolling();
this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
this.subscriptions.clear();
this.queryManager.stopQuery(this.queryId);
this.observers.clear();
this.isTornDown = true;
};
return ObservableQuery;
}(Observable));
fixObservableSubclass(ObservableQuery_ObservableQuery);
function reobserveCacheFirst(obsQuery) {
var _a = obsQuery.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;
if (fetchPolicy === "cache-and-network" ||
fetchPolicy === "network-only") {
return obsQuery.reobserve({
fetchPolicy: "cache-first",
nextFetchPolicy: function () {
this.nextFetchPolicy = nextFetchPolicy;
if (typeof nextFetchPolicy === "function") {
return nextFetchPolicy.apply(this, arguments);
}
return fetchPolicy;
},
});
}
return obsQuery.reobserve();
}
function defaultSubscriptionObserverErrorCallback(error) {
__DEV__ && invariant.error('Unhandled error', error.message, error.stack);
}
function logMissingFieldErrors(missing) {
if (__DEV__ && missing) {
__DEV__ && invariant.debug("Missing cache result fields: ".concat(JSON.stringify(missing)), missing);
}
}
//# sourceMappingURL=ObservableQuery.js.map
// CONCATENATED MODULE: ./node_modules/graphql/language/predicates.mjs
function isDefinitionNode(node) {
return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node);
}
function isExecutableDefinitionNode(node) {
return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION;
}
function isSelectionNode(node) {
return node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_SPREAD || node.kind === Kind.INLINE_FRAGMENT;
}
function isValueNode(node) {
return node.kind === Kind.VARIABLE || node.kind === Kind.INT || node.kind === Kind.FLOAT || node.kind === Kind.STRING || node.kind === Kind.BOOLEAN || node.kind === Kind.NULL || node.kind === Kind.ENUM || node.kind === Kind.LIST || node.kind === Kind.OBJECT;
}
function isTypeNode(node) {
return node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || node.kind === Kind.NON_NULL_TYPE;
}
function isTypeSystemDefinitionNode(node) {
return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION;
}
function isTypeDefinitionNode(node) {
return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION;
}
function isTypeSystemExtensionNode(node) {
return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);
}
function isTypeExtensionNode(node) {
return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION;
}
// CONCATENATED MODULE: ./node_modules/optimism/node_modules/@wry/trie/lib/trie.esm.js
// A [trie](https://en.wikipedia.org/wiki/Trie) data structure that holds
// object keys weakly, yet can also hold non-object keys, unlike the
// native `WeakMap`.
// If no makeData function is supplied, the looked-up data will be an empty,
// null-prototype Object.
var trie_esm_defaultMakeData = function () { return Object.create(null); };
// Useful for processing arguments objects as well as arrays.
var trie_esm_a = Array.prototype, trie_esm_forEach = trie_esm_a.forEach, trie_esm_slice = trie_esm_a.slice;
var trie_esm_Trie = /** @class */ (function () {
function Trie(weakness, makeData) {
if (weakness === void 0) { weakness = true; }
if (makeData === void 0) { makeData = trie_esm_defaultMakeData; }
this.weakness = weakness;
this.makeData = makeData;
}
Trie.prototype.lookup = function () {
var array = [];
for (var _i = 0; _i < arguments.length; _i++) {
array[_i] = arguments[_i];
}
return this.lookupArray(array);
};
Trie.prototype.lookupArray = function (array) {
var node = this;
trie_esm_forEach.call(array, function (key) { return node = node.getChildTrie(key); });
return node.data || (node.data = this.makeData(trie_esm_slice.call(array)));
};
Trie.prototype.getChildTrie = function (key) {
var map = this.weakness && trie_esm_isObjRef(key)
? this.weak || (this.weak = new WeakMap())
: this.strong || (this.strong = new Map());
var child = map.get(key);
if (!child)
map.set(key, child = new Trie(this.weakness, this.makeData));
return child;
};
return Trie;
}());
function trie_esm_isObjRef(value) {
switch (typeof value) {
case "object":
if (value === null)
break;
// Fall through to return true...
case "function":
return true;
}
return false;
}
//# sourceMappingURL=trie.esm.js.map
// CONCATENATED MODULE: ./node_modules/@wry/context/lib/slot.js
// This currentContext variable will only be used if the makeSlotClass
// function is called, which happens only if this is the first copy of the
// @wry/context package to be imported.
let currentContext = null;
// This unique internal object is used to denote the absence of a value
// for a given Slot, and is never exposed to outside code.
const MISSING_VALUE = {};
let idCounter = 1;
// Although we can't do anything about the cost of duplicated code from
// accidentally bundling multiple copies of the @wry/context package, we can
// avoid creating the Slot class more than once using makeSlotClass.
const makeSlotClass = () => class Slot {
constructor() {
// If you have a Slot object, you can find out its slot.id, but you cannot
// guess the slot.id of a Slot you don't have access to, thanks to the
// randomized suffix.
this.id = [
"slot",
idCounter++,
Date.now(),
Math.random().toString(36).slice(2),
].join(":");
}
hasValue() {
for (let context = currentContext; context; context = context.parent) {
// We use the Slot object iself as a key to its value, which means the
// value cannot be obtained without a reference to the Slot object.
if (this.id in context.slots) {
const value = context.slots[this.id];
if (value === MISSING_VALUE)
break;
if (context !== currentContext) {
// Cache the value in currentContext.slots so the next lookup will
// be faster. This caching is safe because the tree of contexts and
// the values of the slots are logically immutable.
currentContext.slots[this.id] = value;
}
return true;
}
}
if (currentContext) {
// If a value was not found for this Slot, it's never going to be found
// no matter how many times we look it up, so we might as well cache
// the absence of the value, too.
currentContext.slots[this.id] = MISSING_VALUE;
}
return false;
}
getValue() {
if (this.hasValue()) {
return currentContext.slots[this.id];
}
}
withValue(value, callback,
// Given the prevalence of arrow functions, specifying arguments is likely
// to be much more common than specifying `this`, hence this ordering:
args, thisArg) {
const slots = {
__proto__: null,
[this.id]: value,
};
const parent = currentContext;
currentContext = { parent, slots };
try {
// Function.prototype.apply allows the arguments array argument to be
// omitted or undefined, so args! is fine here.
return callback.apply(thisArg, args);
}
finally {
currentContext = parent;
}
}
// Capture the current context and wrap a callback function so that it
// reestablishes the captured context when called.
static bind(callback) {
const context = currentContext;
return function () {
const saved = currentContext;
try {
currentContext = context;
return callback.apply(this, arguments);
}
finally {
currentContext = saved;
}
};
}
// Immediately run a callback function without any captured context.
static noContext(callback,
// Given the prevalence of arrow functions, specifying arguments is likely
// to be much more common than specifying `this`, hence this ordering:
args, thisArg) {
if (currentContext) {
const saved = currentContext;
try {
currentContext = null;
// Function.prototype.apply allows the arguments array argument to be
// omitted or undefined, so args! is fine here.
return callback.apply(thisArg, args);
}
finally {
currentContext = saved;
}
}
else {
return callback.apply(thisArg, args);
}
}
};
function slot_maybe(fn) {
try {
return fn();
}
catch (ignored) { }
}
// We store a single global implementation of the Slot class as a permanent
// non-enumerable property of the globalThis object. This obfuscation does
// nothing to prevent access to the Slot class, but at least it ensures the
// implementation (i.e. currentContext) cannot be tampered with, and all copies
// of the @wry/context package (hopefully just one) will share the same Slot
// implementation. Since the first copy of the @wry/context package to be
// imported wins, this technique imposes a steep cost for any future breaking
// changes to the Slot class.
const globalKey = "@wry/context:Slot";
const slot_host =
// Prefer globalThis when available.
// https://github.com/benjamn/wryware/issues/347
slot_maybe(() => globalThis) ||
// Fall back to global, which works in Node.js and may be converted by some
// bundlers to the appropriate identifier (window, self, ...) depending on the
// bundling target. https://github.com/endojs/endo/issues/576#issuecomment-1178515224
slot_maybe(() => global) ||
// Otherwise, use a dummy host that's local to this module. We used to fall
// back to using the Array constructor as a namespace, but that was flagged in
// https://github.com/benjamn/wryware/issues/347, and can be avoided.
Object.create(null);
// Whichever globalHost we're using, make TypeScript happy about the additional
// globalKey property.
const globalHost = slot_host;
const Slot = globalHost[globalKey] ||
// Earlier versions of this package stored the globalKey property on the Array
// constructor, so we check there as well, to prevent Slot class duplication.
Array[globalKey] ||
(function (Slot) {
try {
Object.defineProperty(globalHost, globalKey, {
value: Slot,
enumerable: false,
writable: false,
// When it was possible for globalHost to be the Array constructor (a
// legacy Slot dedup strategy), it was important for the property to be
// configurable:true so it could be deleted. That does not seem to be as
// important when globalHost is the global object, but I don't want to
// cause similar problems again, and configurable:true seems safest.
// https://github.com/endojs/endo/issues/576#issuecomment-1178274008
configurable: true
});
}
finally {
return Slot;
}
})(makeSlotClass());
//# sourceMappingURL=slot.js.map
// CONCATENATED MODULE: ./node_modules/@wry/context/lib/index.js
const { bind, noContext } = Slot;
// Like global.setTimeout, except the callback runs with captured context.
function setTimeoutWithContext(callback, delay) {
return setTimeout(bind(callback), delay);
}
// Turn any generator function into an async function (using yield instead
// of await), with context automatically preserved across yields.
function asyncFromGen(genFn) {
return function () {
const gen = genFn.apply(this, arguments);
const boundNext = bind(gen.next);
const boundThrow = bind(gen.throw);
return new Promise((resolve, reject) => {
function invoke(method, argument) {
try {
var result = method.call(gen, argument);
}
catch (error) {
return reject(error);
}
const next = result.done ? resolve : invokeNext;
if (lib_isPromiseLike(result.value)) {
result.value.then(next, result.done ? reject : invokeThrow);
}
else {
next(result.value);
}
}
const invokeNext = (value) => invoke(boundNext, value);
const invokeThrow = (error) => invoke(boundThrow, error);
invokeNext();
});
};
}
function lib_isPromiseLike(value) {
return value && typeof value.then === "function";
}
// If you use the fibers npm package to implement coroutines in Node.js,
// you should call this function at least once to ensure context management
// remains coherent across any yields.
const wrappedFibers = [];
function wrapYieldingFiberMethods(Fiber) {
// There can be only one implementation of Fiber per process, so this array
// should never grow longer than one element.
if (wrappedFibers.indexOf(Fiber) < 0) {
const wrap = (obj, method) => {
const fn = obj[method];
obj[method] = function () {
return noContext(fn, arguments, this);
};
};
// These methods can yield, according to
// https://github.com/laverdet/node-fibers/blob/ddebed9b8ae3883e57f822e2108e6943e5c8d2a8/fibers.js#L97-L100
wrap(Fiber, "yield");
wrap(Fiber.prototype, "run");
wrap(Fiber.prototype, "throwInto");
wrappedFibers.push(Fiber);
}
return Fiber;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/optimism/lib/bundle.esm.js
function defaultDispose() { }
var Cache = /** @class */ (function () {
function Cache(max, dispose) {
if (max === void 0) { max = Infinity; }
if (dispose === void 0) { dispose = defaultDispose; }
this.max = max;
this.dispose = dispose;
this.map = new Map();
this.newest = null;
this.oldest = null;
}
Cache.prototype.has = function (key) {
return this.map.has(key);
};
Cache.prototype.get = function (key) {
var node = this.getNode(key);
return node && node.value;
};
Cache.prototype.getNode = function (key) {
var node = this.map.get(key);
if (node && node !== this.newest) {
var older = node.older, newer = node.newer;
if (newer) {
newer.older = older;
}
if (older) {
older.newer = newer;
}
node.older = this.newest;
node.older.newer = node;
node.newer = null;
this.newest = node;
if (node === this.oldest) {
this.oldest = newer;
}
}
return node;
};
Cache.prototype.set = function (key, value) {
var node = this.getNode(key);
if (node) {
return node.value = value;
}
node = {
key: key,
value: value,
newer: null,
older: this.newest
};
if (this.newest) {
this.newest.newer = node;
}
this.newest = node;
this.oldest = this.oldest || node;
this.map.set(key, node);
return node.value;
};
Cache.prototype.clean = function () {
while (this.oldest && this.map.size > this.max) {
this.delete(this.oldest.key);
}
};
Cache.prototype.delete = function (key) {
var node = this.map.get(key);
if (node) {
if (node === this.newest) {
this.newest = node.older;
}
if (node === this.oldest) {
this.oldest = node.newer;
}
if (node.newer) {
node.newer.older = node.older;
}
if (node.older) {
node.older.newer = node.newer;
}
this.map.delete(key);
this.dispose(node.value, key);
return true;
}
return false;
};
return Cache;
}());
var parentEntrySlot = new Slot();
var bundle_esm_a;
var bundle_esm_hasOwnProperty = Object.prototype.hasOwnProperty;
var
// This Array.from polyfill is restricted to working with Set<any> for now,
// but we can improve the polyfill and add other input types, as needed. Note
// that this fallback implementation will only be used if the host environment
// does not support a native Array.from function. In most modern JS runtimes,
// the toArray function exported here will be === Array.from.
toArray = (bundle_esm_a = Array.from, bundle_esm_a === void 0 ? function (collection) {
var array = [];
collection.forEach(function (item) { return array.push(item); });
return array;
} : bundle_esm_a);
function maybeUnsubscribe(entryOrDep) {
var unsubscribe = entryOrDep.unsubscribe;
if (typeof unsubscribe === "function") {
entryOrDep.unsubscribe = void 0;
unsubscribe();
}
}
var emptySetPool = [];
var POOL_TARGET_SIZE = 100;
// Since this package might be used browsers, we should avoid using the
// Node built-in assert module.
function bundle_esm_assert(condition, optionalMessage) {
if (!condition) {
throw new Error(optionalMessage || "assertion failure");
}
}
function valueIs(a, b) {
var len = a.length;
return (
// Unknown values are not equal to each other.
len > 0 &&
// Both values must be ordinary (or both exceptional) to be equal.
len === b.length &&
// The underlying value or exception must be the same.
a[len - 1] === b[len - 1]);
}
function valueGet(value) {
switch (value.length) {
case 0: throw new Error("unknown value");
case 1: return value[0];
case 2: throw value[1];
}
}
function valueCopy(value) {
return value.slice(0);
}
var Entry = /** @class */ (function () {
function Entry(fn) {
this.fn = fn;
this.parents = new Set();
this.childValues = new Map();
// When this Entry has children that are dirty, this property becomes
// a Set containing other Entry objects, borrowed from emptySetPool.
// When the set becomes empty, it gets recycled back to emptySetPool.
this.dirtyChildren = null;
this.dirty = true;
this.recomputing = false;
this.value = [];
this.deps = null;
++Entry.count;
}
Entry.prototype.peek = function () {
if (this.value.length === 1 && !mightBeDirty(this)) {
rememberParent(this);
return this.value[0];
}
};
// This is the most important method of the Entry API, because it
// determines whether the cached this.value can be returned immediately,
// or must be recomputed. The overall performance of the caching system
// depends on the truth of the following observations: (1) this.dirty is
// usually false, (2) this.dirtyChildren is usually null/empty, and thus
// (3) valueGet(this.value) is usually returned without recomputation.
Entry.prototype.recompute = function (args) {
bundle_esm_assert(!this.recomputing, "already recomputing");
rememberParent(this);
return mightBeDirty(this)
? reallyRecompute(this, args)
: valueGet(this.value);
};
Entry.prototype.setDirty = function () {
if (this.dirty)
return;
this.dirty = true;
this.value.length = 0;
reportDirty(this);
// We can go ahead and unsubscribe here, since any further dirty
// notifications we receive will be redundant, and unsubscribing may
// free up some resources, e.g. file watchers.
maybeUnsubscribe(this);
};
Entry.prototype.dispose = function () {
var _this = this;
this.setDirty();
// Sever any dependency relationships with our own children, so those
// children don't retain this parent Entry in their child.parents sets,
// thereby preventing it from being fully garbage collected.
forgetChildren(this);
// Because this entry has been kicked out of the cache (in index.js),
// we've lost the ability to find out if/when this entry becomes dirty,
// whether that happens through a subscription, because of a direct call
// to entry.setDirty(), or because one of its children becomes dirty.
// Because of this loss of future information, we have to assume the
// worst (that this entry might have become dirty very soon), so we must
// immediately mark this entry's parents as dirty. Normally we could
// just call entry.setDirty() rather than calling parent.setDirty() for
// each parent, but that would leave this entry in parent.childValues
// and parent.dirtyChildren, which would prevent the child from being
// truly forgotten.
eachParent(this, function (parent, child) {
parent.setDirty();
forgetChild(parent, _this);
});
};
Entry.prototype.forget = function () {
// The code that creates Entry objects in index.ts will replace this method
// with one that actually removes the Entry from the cache, which will also
// trigger the entry.dispose method.
this.dispose();
};
Entry.prototype.dependOn = function (dep) {
dep.add(this);
if (!this.deps) {
this.deps = emptySetPool.pop() || new Set();
}
this.deps.add(dep);
};
Entry.prototype.forgetDeps = function () {
var _this = this;
if (this.deps) {
toArray(this.deps).forEach(function (dep) { return dep.delete(_this); });
this.deps.clear();
emptySetPool.push(this.deps);
this.deps = null;
}
};
Entry.count = 0;
return Entry;
}());
function rememberParent(child) {
var parent = parentEntrySlot.getValue();
if (parent) {
child.parents.add(parent);
if (!parent.childValues.has(child)) {
parent.childValues.set(child, []);
}
if (mightBeDirty(child)) {
reportDirtyChild(parent, child);
}
else {
reportCleanChild(parent, child);
}
return parent;
}
}
function reallyRecompute(entry, args) {
forgetChildren(entry);
// Set entry as the parent entry while calling recomputeNewValue(entry).
parentEntrySlot.withValue(entry, recomputeNewValue, [entry, args]);
if (maybeSubscribe(entry, args)) {
// If we successfully recomputed entry.value and did not fail to
// (re)subscribe, then this Entry is no longer explicitly dirty.
setClean(entry);
}
return valueGet(entry.value);
}
function recomputeNewValue(entry, args) {
entry.recomputing = true;
// Set entry.value as unknown.
entry.value.length = 0;
try {
// If entry.fn succeeds, entry.value will become a normal Value.
entry.value[0] = entry.fn.apply(null, args);
}
catch (e) {
// If entry.fn throws, entry.value will become exceptional.
entry.value[1] = e;
}
// Either way, this line is always reached.
entry.recomputing = false;
}
function mightBeDirty(entry) {
return entry.dirty || !!(entry.dirtyChildren && entry.dirtyChildren.size);
}
function setClean(entry) {
entry.dirty = false;
if (mightBeDirty(entry)) {
// This Entry may still have dirty children, in which case we can't
// let our parents know we're clean just yet.
return;
}
reportClean(entry);
}
function reportDirty(child) {
eachParent(child, reportDirtyChild);
}
function reportClean(child) {
eachParent(child, reportCleanChild);
}
function eachParent(child, callback) {
var parentCount = child.parents.size;
if (parentCount) {
var parents = toArray(child.parents);
for (var i = 0; i < parentCount; ++i) {
callback(parents[i], child);
}
}
}
// Let a parent Entry know that one of its children may be dirty.
function reportDirtyChild(parent, child) {
// Must have called rememberParent(child) before calling
// reportDirtyChild(parent, child).
bundle_esm_assert(parent.childValues.has(child));
bundle_esm_assert(mightBeDirty(child));
var parentWasClean = !mightBeDirty(parent);
if (!parent.dirtyChildren) {
parent.dirtyChildren = emptySetPool.pop() || new Set;
}
else if (parent.dirtyChildren.has(child)) {
// If we already know this child is dirty, then we must have already
// informed our own parents that we are dirty, so we can terminate
// the recursion early.
return;
}
parent.dirtyChildren.add(child);
// If parent was clean before, it just became (possibly) dirty (according to
// mightBeDirty), since we just added child to parent.dirtyChildren.
if (parentWasClean) {
reportDirty(parent);
}
}
// Let a parent Entry know that one of its children is no longer dirty.
function reportCleanChild(parent, child) {
// Must have called rememberChild(child) before calling
// reportCleanChild(parent, child).
bundle_esm_assert(parent.childValues.has(child));
bundle_esm_assert(!mightBeDirty(child));
var childValue = parent.childValues.get(child);
if (childValue.length === 0) {
parent.childValues.set(child, valueCopy(child.value));
}
else if (!valueIs(childValue, child.value)) {
parent.setDirty();
}
removeDirtyChild(parent, child);
if (mightBeDirty(parent)) {
return;
}
reportClean(parent);
}
function removeDirtyChild(parent, child) {
var dc = parent.dirtyChildren;
if (dc) {
dc.delete(child);
if (dc.size === 0) {
if (emptySetPool.length < POOL_TARGET_SIZE) {
emptySetPool.push(dc);
}
parent.dirtyChildren = null;
}
}
}
// Removes all children from this entry and returns an array of the
// removed children.
function forgetChildren(parent) {
if (parent.childValues.size > 0) {
parent.childValues.forEach(function (_value, child) {
forgetChild(parent, child);
});
}
// Remove this parent Entry from any sets to which it was added by the
// addToSet method.
parent.forgetDeps();
// After we forget all our children, this.dirtyChildren must be empty
// and therefore must have been reset to null.
bundle_esm_assert(parent.dirtyChildren === null);
}
function forgetChild(parent, child) {
child.parents.delete(parent);
parent.childValues.delete(child);
removeDirtyChild(parent, child);
}
function maybeSubscribe(entry, args) {
if (typeof entry.subscribe === "function") {
try {
maybeUnsubscribe(entry); // Prevent double subscriptions.
entry.unsubscribe = entry.subscribe.apply(null, args);
}
catch (e) {
// If this Entry has a subscribe function and it threw an exception
// (or an unsubscribe function it previously returned now throws),
// return false to indicate that we were not able to subscribe (or
// unsubscribe), and this Entry should remain dirty.
entry.setDirty();
return false;
}
}
// Returning true indicates either that there was no entry.subscribe
// function or that it succeeded.
return true;
}
var EntryMethods = {
setDirty: true,
dispose: true,
forget: true, // Fully remove parent Entry from LRU cache and computation graph
};
function dep(options) {
var depsByKey = new Map();
var subscribe = options && options.subscribe;
function depend(key) {
var parent = parentEntrySlot.getValue();
if (parent) {
var dep_1 = depsByKey.get(key);
if (!dep_1) {
depsByKey.set(key, dep_1 = new Set);
}
parent.dependOn(dep_1);
if (typeof subscribe === "function") {
maybeUnsubscribe(dep_1);
dep_1.unsubscribe = subscribe(key);
}
}
}
depend.dirty = function dirty(key, entryMethodName) {
var dep = depsByKey.get(key);
if (dep) {
var m_1 = (entryMethodName &&
bundle_esm_hasOwnProperty.call(EntryMethods, entryMethodName)) ? entryMethodName : "setDirty";
// We have to use toArray(dep).forEach instead of dep.forEach, because
// modifying a Set while iterating over it can cause elements in the Set
// to be removed from the Set before they've been iterated over.
toArray(dep).forEach(function (entry) { return entry[m_1](); });
depsByKey.delete(key);
maybeUnsubscribe(dep);
}
};
return depend;
}
function makeDefaultMakeCacheKeyFunction() {
var keyTrie = new trie_esm_Trie(typeof WeakMap === "function");
return function () {
return keyTrie.lookupArray(arguments);
};
}
// The defaultMakeCacheKey function is remarkably powerful, because it gives
// a unique object for any shallow-identical list of arguments. If you need
// to implement a custom makeCacheKey function, you may find it helpful to
// delegate the final work to defaultMakeCacheKey, which is why we export it
// here. However, you may want to avoid defaultMakeCacheKey if your runtime
// does not support WeakMap, or you have the ability to return a string key.
// In those cases, just write your own custom makeCacheKey functions.
var defaultMakeCacheKey = makeDefaultMakeCacheKeyFunction();
var caches = new Set();
function bundle_esm_wrap(originalFunction, options) {
if (options === void 0) { options = Object.create(null); }
var cache = new Cache(options.max || Math.pow(2, 16), function (entry) { return entry.dispose(); });
var keyArgs = options.keyArgs;
var makeCacheKey = options.makeCacheKey ||
makeDefaultMakeCacheKeyFunction();
var optimistic = function () {
var key = makeCacheKey.apply(null, keyArgs ? keyArgs.apply(null, arguments) : arguments);
if (key === void 0) {
return originalFunction.apply(null, arguments);
}
var entry = cache.get(key);
if (!entry) {
cache.set(key, entry = new Entry(originalFunction));
entry.subscribe = options.subscribe;
// Give the Entry the ability to trigger cache.delete(key), even though
// the Entry itself does not know about key or cache.
entry.forget = function () { return cache.delete(key); };
}
var value = entry.recompute(Array.prototype.slice.call(arguments));
// Move this entry to the front of the least-recently used queue,
// since we just finished computing its value.
cache.set(key, entry);
caches.add(cache);
// Clean up any excess entries in the cache, but only if there is no
// active parent entry, meaning we're not in the middle of a larger
// computation that might be flummoxed by the cleaning.
if (!parentEntrySlot.hasValue()) {
caches.forEach(function (cache) { return cache.clean(); });
caches.clear();
}
return value;
};
Object.defineProperty(optimistic, "size", {
get: function () {
return cache["map"].size;
},
configurable: false,
enumerable: false,
});
function dirtyKey(key) {
var entry = cache.get(key);
if (entry) {
entry.setDirty();
}
}
optimistic.dirtyKey = dirtyKey;
optimistic.dirty = function dirty() {
dirtyKey(makeCacheKey.apply(null, arguments));
};
function peekKey(key) {
var entry = cache.get(key);
if (entry) {
return entry.peek();
}
}
optimistic.peekKey = peekKey;
optimistic.peek = function peek() {
return peekKey(makeCacheKey.apply(null, arguments));
};
function forgetKey(key) {
return cache.delete(key);
}
optimistic.forgetKey = forgetKey;
optimistic.forget = function forget() {
return forgetKey(makeCacheKey.apply(null, arguments));
};
optimistic.makeCacheKey = makeCacheKey;
optimistic.getKey = keyArgs ? function getKey() {
return makeCacheKey.apply(null, keyArgs.apply(null, arguments));
} : makeCacheKey;
return Object.freeze(optimistic);
}
//# sourceMappingURL=bundle.esm.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/reactiveVars.js
var cacheSlot = new Slot();
var cacheInfoMap = new WeakMap();
function getCacheInfo(cache) {
var info = cacheInfoMap.get(cache);
if (!info) {
cacheInfoMap.set(cache, info = {
vars: new Set,
dep: dep(),
});
}
return info;
}
function forgetCache(cache) {
getCacheInfo(cache).vars.forEach(function (rv) { return rv.forgetCache(cache); });
}
function recallCache(cache) {
getCacheInfo(cache).vars.forEach(function (rv) { return rv.attachCache(cache); });
}
function makeVar(value) {
var caches = new Set();
var listeners = new Set();
var rv = function (newValue) {
if (arguments.length > 0) {
if (value !== newValue) {
value = newValue;
caches.forEach(function (cache) {
getCacheInfo(cache).dep.dirty(rv);
broadcast(cache);
});
var oldListeners = Array.from(listeners);
listeners.clear();
oldListeners.forEach(function (listener) { return listener(value); });
}
}
else {
var cache = cacheSlot.getValue();
if (cache) {
attach(cache);
getCacheInfo(cache).dep(rv);
}
}
return value;
};
rv.onNextChange = function (listener) {
listeners.add(listener);
return function () {
listeners.delete(listener);
};
};
var attach = rv.attachCache = function (cache) {
caches.add(cache);
getCacheInfo(cache).vars.add(rv);
return rv;
};
rv.forgetCache = function (cache) { return caches.delete(cache); };
return rv;
}
function broadcast(cache) {
if (cache.broadcastWatches) {
cache.broadcastWatches();
}
}
//# sourceMappingURL=reactiveVars.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/core/LocalState.js
var LocalState_LocalState = (function () {
function LocalState(_a) {
var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
this.selectionsToResolveCache = new WeakMap();
this.cache = cache;
if (client) {
this.client = client;
}
if (resolvers) {
this.addResolvers(resolvers);
}
if (fragmentMatcher) {
this.setFragmentMatcher(fragmentMatcher);
}
}
LocalState.prototype.addResolvers = function (resolvers) {
var _this = this;
this.resolvers = this.resolvers || {};
if (Array.isArray(resolvers)) {
resolvers.forEach(function (resolverGroup) {
_this.resolvers = mergeDeep(_this.resolvers, resolverGroup);
});
}
else {
this.resolvers = mergeDeep(this.resolvers, resolvers);
}
};
LocalState.prototype.setResolvers = function (resolvers) {
this.resolvers = {};
this.addResolvers(resolvers);
};
LocalState.prototype.getResolvers = function () {
return this.resolvers || {};
};
LocalState.prototype.runResolvers = function (_a) {
var document = _a.document, remoteResult = _a.remoteResult, context = _a.context, variables = _a.variables, _b = _a.onlyRunForcedResolvers, onlyRunForcedResolvers = _b === void 0 ? false : _b;
return tslib_es6_awaiter(this, void 0, void 0, function () {
return __generator(this, function (_c) {
if (document) {
return [2, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (__assign(__assign({}, remoteResult), { data: localResult.result })); })];
}
return [2, remoteResult];
});
});
};
LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
this.fragmentMatcher = fragmentMatcher;
};
LocalState.prototype.getFragmentMatcher = function () {
return this.fragmentMatcher;
};
LocalState.prototype.clientQuery = function (document) {
if (hasDirectives(['client'], document)) {
if (this.resolvers) {
return document;
}
}
return null;
};
LocalState.prototype.serverQuery = function (document) {
return removeClientSetsFromDocument(document);
};
LocalState.prototype.prepareContext = function (context) {
var cache = this.cache;
return __assign(__assign({}, context), { cache: cache, getCacheKey: function (obj) {
return cache.identify(obj);
} });
};
LocalState.prototype.addExportedVariables = function (document, variables, context) {
if (variables === void 0) { variables = {}; }
if (context === void 0) { context = {}; }
return tslib_es6_awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (document) {
return [2, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (__assign(__assign({}, variables), data.exportedVariables)); })];
}
return [2, __assign({}, variables)];
});
});
};
LocalState.prototype.shouldForceResolvers = function (document) {
var forceResolvers = false;
visit(document, {
Directive: {
enter: function (node) {
if (node.name.value === 'client' && node.arguments) {
forceResolvers = node.arguments.some(function (arg) {
return arg.name.value === 'always' &&
arg.value.kind === 'BooleanValue' &&
arg.value.value === true;
});
if (forceResolvers) {
return BREAK;
}
}
},
},
});
return forceResolvers;
};
LocalState.prototype.buildRootValueFromCache = function (document, variables) {
return this.cache.diff({
query: buildQueryFromSelectionSet(document),
variables: variables,
returnPartialData: true,
optimistic: false,
}).result;
};
LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
if (context === void 0) { context = {}; }
if (variables === void 0) { variables = {}; }
if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
return tslib_es6_awaiter(this, void 0, void 0, function () {
var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;
return __generator(this, function (_b) {
mainDefinition = getMainDefinition(document);
fragments = getFragmentDefinitions(document);
fragmentMap = createFragmentMap(fragments);
selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);
definitionOperation = mainDefinition.operation;
defaultOperationType = definitionOperation
? definitionOperation.charAt(0).toUpperCase() +
definitionOperation.slice(1)
: 'Query';
_a = this, cache = _a.cache, client = _a.client;
execContext = {
fragmentMap: fragmentMap,
context: __assign(__assign({}, context), { cache: cache, client: client }),
variables: variables,
fragmentMatcher: fragmentMatcher,
defaultOperationType: defaultOperationType,
exportedVariables: {},
selectionsToResolve: selectionsToResolve,
onlyRunForcedResolvers: onlyRunForcedResolvers,
};
isClientFieldDescendant = false;
return [2, this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({
result: result,
exportedVariables: execContext.exportedVariables,
}); })];
});
});
};
LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {
return tslib_es6_awaiter(this, void 0, void 0, function () {
var fragmentMap, context, variables, resultsToMerge, execute;
var _this = this;
return __generator(this, function (_a) {
fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
resultsToMerge = [rootValue];
execute = function (selection) { return tslib_es6_awaiter(_this, void 0, void 0, function () {
var fragment, typeCondition;
return __generator(this, function (_a) {
if (!isClientFieldDescendant && !execContext.selectionsToResolve.has(selection)) {
return [2];
}
if (!shouldInclude(selection, variables)) {
return [2];
}
if (isField(selection)) {
return [2, this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {
var _a;
if (typeof fieldResult !== 'undefined') {
resultsToMerge.push((_a = {},
_a[resultKeyNameFromField(selection)] = fieldResult,
_a));
}
})];
}
if (isInlineFragment(selection)) {
fragment = selection;
}
else {
fragment = fragmentMap[selection.name.value];
__DEV__ ? invariant(fragment, "No fragment named ".concat(selection.name.value)) : invariant(fragment, 11);
}
if (fragment && fragment.typeCondition) {
typeCondition = fragment.typeCondition.name.value;
if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
return [2, this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {
resultsToMerge.push(fragmentResult);
})];
}
}
return [2];
});
}); };
return [2, Promise.all(selectionSet.selections.map(execute)).then(function () {
return mergeDeepArray(resultsToMerge);
})];
});
});
};
LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {
return tslib_es6_awaiter(this, void 0, void 0, function () {
var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
var _this = this;
return __generator(this, function (_a) {
if (!rootValue) {
return [2, null];
}
variables = execContext.variables;
fieldName = field.name.value;
aliasedFieldName = resultKeyNameFromField(field);
aliasUsed = fieldName !== aliasedFieldName;
defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
resultPromise = Promise.resolve(defaultResult);
if (!execContext.onlyRunForcedResolvers ||
this.shouldForceResolvers(field)) {
resolverType = rootValue.__typename || execContext.defaultOperationType;
resolverMap = this.resolvers && this.resolvers[resolverType];
if (resolverMap) {
resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
if (resolve) {
resultPromise = Promise.resolve(cacheSlot.withValue(this.cache, resolve, [
rootValue,
argumentsObjectFromField(field, variables),
execContext.context,
{ field: field, fragmentMap: execContext.fragmentMap },
]));
}
}
}
return [2, resultPromise.then(function (result) {
var _a, _b;
if (result === void 0) { result = defaultResult; }
if (field.directives) {
field.directives.forEach(function (directive) {
if (directive.name.value === 'export' && directive.arguments) {
directive.arguments.forEach(function (arg) {
if (arg.name.value === 'as' && arg.value.kind === 'StringValue') {
execContext.exportedVariables[arg.value.value] = result;
}
});
}
});
}
if (!field.selectionSet) {
return result;
}
if (result == null) {
return result;
}
var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === 'client'; })) !== null && _b !== void 0 ? _b : false;
if (Array.isArray(result)) {
return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);
}
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);
}
})];
});
});
};
LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {
var _this = this;
return Promise.all(result.map(function (item) {
if (item === null) {
return null;
}
if (Array.isArray(item)) {
return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);
}
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);
}
}));
};
LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {
var isSingleASTNode = function (node) { return !Array.isArray(node); };
var selectionsToResolveCache = this.selectionsToResolveCache;
function collectByDefinition(definitionNode) {
if (!selectionsToResolveCache.has(definitionNode)) {
var matches_1 = new Set();
selectionsToResolveCache.set(definitionNode, matches_1);
visit(definitionNode, {
Directive: function (node, _, __, ___, ancestors) {
if (node.name.value === 'client') {
ancestors.forEach(function (node) {
if (isSingleASTNode(node) && isSelectionNode(node)) {
matches_1.add(node);
}
});
}
},
FragmentSpread: function (spread, _, __, ___, ancestors) {
var fragment = fragmentMap[spread.name.value];
__DEV__ ? invariant(fragment, "No fragment named ".concat(spread.name.value)) : invariant(fragment, 12);
var fragmentSelections = collectByDefinition(fragment);
if (fragmentSelections.size > 0) {
ancestors.forEach(function (node) {
if (isSingleASTNode(node) && isSelectionNode(node)) {
matches_1.add(node);
}
});
matches_1.add(spread);
fragmentSelections.forEach(function (selection) {
matches_1.add(selection);
});
}
}
});
}
return selectionsToResolveCache.get(definitionNode);
}
return collectByDefinition(mainDefinition);
};
return LocalState;
}());
//# sourceMappingURL=LocalState.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/core/QueryInfo.js
;
var destructiveMethodCounts = new (canUseWeakMap ? WeakMap : Map)();
function wrapDestructiveCacheMethod(cache, methodName) {
var original = cache[methodName];
if (typeof original === "function") {
cache[methodName] = function () {
destructiveMethodCounts.set(cache, (destructiveMethodCounts.get(cache) + 1) % 1e15);
return original.apply(this, arguments);
};
}
}
function cancelNotifyTimeout(info) {
if (info["notifyTimeout"]) {
clearTimeout(info["notifyTimeout"]);
info["notifyTimeout"] = void 0;
}
}
var QueryInfo_QueryInfo = (function () {
function QueryInfo(queryManager, queryId) {
if (queryId === void 0) { queryId = queryManager.generateQueryId(); }
this.queryId = queryId;
this.listeners = new Set();
this.document = null;
this.lastRequestId = 1;
this.subscriptions = new Set();
this.stopped = false;
this.dirty = false;
this.observableQuery = null;
var cache = this.cache = queryManager.cache;
if (!destructiveMethodCounts.has(cache)) {
destructiveMethodCounts.set(cache, 0);
wrapDestructiveCacheMethod(cache, "evict");
wrapDestructiveCacheMethod(cache, "modify");
wrapDestructiveCacheMethod(cache, "reset");
}
}
QueryInfo.prototype.init = function (query) {
var networkStatus = query.networkStatus || NetworkStatus.loading;
if (this.variables &&
this.networkStatus !== NetworkStatus.loading &&
!equal(this.variables, query.variables)) {
networkStatus = NetworkStatus.setVariables;
}
if (!equal(query.variables, this.variables)) {
this.lastDiff = void 0;
}
Object.assign(this, {
document: query.document,
variables: query.variables,
networkError: null,
graphQLErrors: this.graphQLErrors || [],
networkStatus: networkStatus,
});
if (query.observableQuery) {
this.setObservableQuery(query.observableQuery);
}
if (query.lastRequestId) {
this.lastRequestId = query.lastRequestId;
}
return this;
};
QueryInfo.prototype.reset = function () {
cancelNotifyTimeout(this);
this.dirty = false;
};
QueryInfo.prototype.getDiff = function (variables) {
if (variables === void 0) { variables = this.variables; }
var options = this.getDiffOptions(variables);
if (this.lastDiff && equal(options, this.lastDiff.options)) {
return this.lastDiff.diff;
}
this.updateWatch(this.variables = variables);
var oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return { complete: false };
}
var diff = this.cache.diff(options);
this.updateLastDiff(diff, options);
return diff;
};
QueryInfo.prototype.updateLastDiff = function (diff, options) {
this.lastDiff = diff ? {
diff: diff,
options: options || this.getDiffOptions(),
} : void 0;
};
QueryInfo.prototype.getDiffOptions = function (variables) {
var _a;
if (variables === void 0) { variables = this.variables; }
return {
query: this.document,
variables: variables,
returnPartialData: true,
optimistic: true,
canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,
};
};
QueryInfo.prototype.setDiff = function (diff) {
var _this = this;
var oldDiff = this.lastDiff && this.lastDiff.diff;
this.updateLastDiff(diff);
if (!this.dirty &&
!equal(oldDiff && oldDiff.result, diff && diff.result)) {
this.dirty = true;
if (!this.notifyTimeout) {
this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);
}
}
};
QueryInfo.prototype.setObservableQuery = function (oq) {
var _this = this;
if (oq === this.observableQuery)
return;
if (this.oqListener) {
this.listeners.delete(this.oqListener);
}
this.observableQuery = oq;
if (oq) {
oq["queryInfo"] = this;
this.listeners.add(this.oqListener = function () {
var diff = _this.getDiff();
if (diff.fromOptimisticTransaction) {
oq["observe"]();
}
else {
reobserveCacheFirst(oq);
}
});
}
else {
delete this.oqListener;
}
};
QueryInfo.prototype.notify = function () {
var _this = this;
cancelNotifyTimeout(this);
if (this.shouldNotify()) {
this.listeners.forEach(function (listener) { return listener(_this); });
}
this.dirty = false;
};
QueryInfo.prototype.shouldNotify = function () {
if (!this.dirty || !this.listeners.size) {
return false;
}
if (isNetworkRequestInFlight(this.networkStatus) &&
this.observableQuery) {
var fetchPolicy = this.observableQuery.options.fetchPolicy;
if (fetchPolicy !== "cache-only" &&
fetchPolicy !== "cache-and-network") {
return false;
}
}
return true;
};
QueryInfo.prototype.stop = function () {
if (!this.stopped) {
this.stopped = true;
this.reset();
this.cancel();
this.cancel = QueryInfo.prototype.cancel;
this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
var oq = this.observableQuery;
if (oq)
oq.stopPolling();
}
};
QueryInfo.prototype.cancel = function () { };
QueryInfo.prototype.updateWatch = function (variables) {
var _this = this;
if (variables === void 0) { variables = this.variables; }
var oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return;
}
var watchOptions = __assign(__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });
if (!this.lastWatch ||
!equal(watchOptions, this.lastWatch)) {
this.cancel();
this.cancel = this.cache.watch(this.lastWatch = watchOptions);
}
};
QueryInfo.prototype.resetLastWrite = function () {
this.lastWrite = void 0;
};
QueryInfo.prototype.shouldWrite = function (result, variables) {
var lastWrite = this.lastWrite;
return !(lastWrite &&
lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
equal(variables, lastWrite.variables) &&
equal(result.data, lastWrite.result.data));
};
QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {
var _this = this;
var merger = new mergeDeep_DeepMerger();
var graphQLErrors = isNonEmptyArray(result.errors)
? result.errors.slice(0)
: [];
this.reset();
if ('incremental' in result && isNonEmptyArray(result.incremental)) {
var mergedData = mergeIncrementalData(this.getDiff().result, result);
result.data = mergedData;
}
else if ('hasNext' in result && result.hasNext) {
var diff = this.getDiff();
result.data = merger.merge(diff.result, result.data);
}
this.graphQLErrors = graphQLErrors;
if (options.fetchPolicy === 'no-cache') {
this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));
}
else if (cacheWriteBehavior !== 0) {
if (shouldWriteResult(result, options.errorPolicy)) {
this.cache.performTransaction(function (cache) {
if (_this.shouldWrite(result, options.variables)) {
cache.writeQuery({
query: document,
data: result.data,
variables: options.variables,
overwrite: cacheWriteBehavior === 1,
});
_this.lastWrite = {
result: result,
variables: options.variables,
dmCount: destructiveMethodCounts.get(_this.cache),
};
}
else {
if (_this.lastDiff &&
_this.lastDiff.diff.complete) {
result.data = _this.lastDiff.diff.result;
return;
}
}
var diffOptions = _this.getDiffOptions(options.variables);
var diff = cache.diff(diffOptions);
if (!_this.stopped) {
_this.updateWatch(options.variables);
}
_this.updateLastDiff(diff, diffOptions);
if (diff.complete) {
result.data = diff.result;
}
});
}
else {
this.lastWrite = void 0;
}
}
};
QueryInfo.prototype.markReady = function () {
this.networkError = null;
return this.networkStatus = NetworkStatus.ready;
};
QueryInfo.prototype.markError = function (error) {
this.networkStatus = NetworkStatus.error;
this.lastWrite = void 0;
this.reset();
if (error.graphQLErrors) {
this.graphQLErrors = error.graphQLErrors;
}
if (error.networkError) {
this.networkError = error.networkError;
}
return error;
};
return QueryInfo;
}());
function shouldWriteResult(result, errorPolicy) {
if (errorPolicy === void 0) { errorPolicy = "none"; }
var ignoreErrors = errorPolicy === "ignore" ||
errorPolicy === "all";
var writeWithErrors = !graphQLResultHasError(result);
if (!writeWithErrors && ignoreErrors && result.data) {
writeWithErrors = true;
}
return writeWithErrors;
}
//# sourceMappingURL=QueryInfo.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/core/QueryManager.js
var QueryManager_hasOwnProperty = Object.prototype.hasOwnProperty;
var QueryManager_QueryManager = (function () {
function QueryManager(_a) {
var cache = _a.cache, link = _a.link, defaultOptions = _a.defaultOptions, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, onBroadcast = _a.onBroadcast, _c = _a.ssrMode, ssrMode = _c === void 0 ? false : _c, _d = _a.clientAwareness, clientAwareness = _d === void 0 ? {} : _d, localState = _a.localState, assumeImmutableResults = _a.assumeImmutableResults;
this.clientAwareness = {};
this.queries = new Map();
this.fetchCancelFns = new Map();
this.transformCache = new (canUseWeakMap ? WeakMap : Map)();
this.queryIdCounter = 1;
this.requestIdCounter = 1;
this.mutationIdCounter = 1;
this.inFlightLinkObservables = new Map();
this.cache = cache;
this.link = link;
this.defaultOptions = defaultOptions || Object.create(null);
this.queryDeduplication = queryDeduplication;
this.clientAwareness = clientAwareness;
this.localState = localState || new LocalState_LocalState({ cache: cache });
this.ssrMode = ssrMode;
this.assumeImmutableResults = !!assumeImmutableResults;
if ((this.onBroadcast = onBroadcast)) {
this.mutationStore = Object.create(null);
}
}
QueryManager.prototype.stop = function () {
var _this = this;
this.queries.forEach(function (_info, queryId) {
_this.stopQueryNoBroadcast(queryId);
});
this.cancelPendingFetches(__DEV__ ? new invariant_InvariantError('QueryManager stopped while query was in flight') : new invariant_InvariantError(14));
};
QueryManager.prototype.cancelPendingFetches = function (error) {
this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
this.fetchCancelFns.clear();
};
QueryManager.prototype.mutate = function (_a) {
var _b, _c;
var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueries = _a.updateQueries, _d = _a.refetchQueries, refetchQueries = _d === void 0 ? [] : _d, _e = _a.awaitRefetchQueries, awaitRefetchQueries = _e === void 0 ? false : _e, updateWithProxyFn = _a.update, onQueryUpdated = _a.onQueryUpdated, _f = _a.fetchPolicy, fetchPolicy = _f === void 0 ? ((_b = this.defaultOptions.mutate) === null || _b === void 0 ? void 0 : _b.fetchPolicy) || "network-only" : _f, _g = _a.errorPolicy, errorPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.errorPolicy) || "none" : _g, keepRootFields = _a.keepRootFields, context = _a.context;
return tslib_es6_awaiter(this, void 0, void 0, function () {
var mutationId, _h, document, hasClientExports, mutationStoreValue, self;
return __generator(this, function (_j) {
switch (_j.label) {
case 0:
__DEV__ ? invariant(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.') : invariant(mutation, 15);
__DEV__ ? invariant(fetchPolicy === 'network-only' ||
fetchPolicy === 'no-cache', "Mutations support only 'network-only' or 'no-cache' fetchPolicy strings. The default `network-only` behavior automatically writes mutation results to the cache. Passing `no-cache` skips the cache write.") : invariant(fetchPolicy === 'network-only' ||
fetchPolicy === 'no-cache', 16);
mutationId = this.generateMutationId();
_h = this.transform(mutation), document = _h.document, hasClientExports = _h.hasClientExports;
mutation = this.cache.transformForLink(document);
variables = this.getVariables(mutation, variables);
if (!hasClientExports) return [3, 2];
return [4, this.localState.addExportedVariables(mutation, variables, context)];
case 1:
variables = (_j.sent());
_j.label = 2;
case 2:
mutationStoreValue = this.mutationStore &&
(this.mutationStore[mutationId] = {
mutation: mutation,
variables: variables,
loading: true,
error: null,
});
if (optimisticResponse) {
this.markMutationOptimistic(optimisticResponse, {
mutationId: mutationId,
document: mutation,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
context: context,
updateQueries: updateQueries,
update: updateWithProxyFn,
keepRootFields: keepRootFields,
});
}
this.broadcastQueries();
self = this;
return [2, new Promise(function (resolve, reject) {
return asyncMap(self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: optimisticResponse }), variables, false), function (result) {
if (graphQLResultHasError(result) && errorPolicy === 'none') {
throw new errors_ApolloError({
graphQLErrors: getGraphQLErrorsFromResult(result),
});
}
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = null;
}
var storeResult = __assign({}, result);
if (typeof refetchQueries === "function") {
refetchQueries = refetchQueries(storeResult);
}
if (errorPolicy === 'ignore' &&
graphQLResultHasError(storeResult)) {
delete storeResult.errors;
}
return self.markMutationResult({
mutationId: mutationId,
result: storeResult,
document: mutation,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
context: context,
update: updateWithProxyFn,
updateQueries: updateQueries,
awaitRefetchQueries: awaitRefetchQueries,
refetchQueries: refetchQueries,
removeOptimistic: optimisticResponse ? mutationId : void 0,
onQueryUpdated: onQueryUpdated,
keepRootFields: keepRootFields,
});
}).subscribe({
next: function (storeResult) {
self.broadcastQueries();
if (!('hasNext' in storeResult) || storeResult.hasNext === false) {
resolve(storeResult);
}
},
error: function (err) {
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = err;
}
if (optimisticResponse) {
self.cache.removeOptimistic(mutationId);
}
self.broadcastQueries();
reject(err instanceof errors_ApolloError ? err : new errors_ApolloError({
networkError: err,
}));
},
});
})];
}
});
});
};
QueryManager.prototype.markMutationResult = function (mutation, cache) {
var _this = this;
if (cache === void 0) { cache = this.cache; }
var result = mutation.result;
var cacheWrites = [];
var skipCache = mutation.fetchPolicy === "no-cache";
if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
if (!isExecutionPatchIncrementalResult(result)) {
cacheWrites.push({
result: result.data,
dataId: 'ROOT_MUTATION',
query: mutation.document,
variables: mutation.variables,
});
}
if (isExecutionPatchIncrementalResult(result) && isNonEmptyArray(result.incremental)) {
var diff = cache.diff({
id: "ROOT_MUTATION",
query: this.transform(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
var mergedData = void 0;
if (diff.result) {
mergedData = mergeIncrementalData(diff.result, result);
}
if (typeof mergedData !== 'undefined') {
result.data = mergedData;
cacheWrites.push({
result: mergedData,
dataId: 'ROOT_MUTATION',
query: mutation.document,
variables: mutation.variables,
});
}
}
var updateQueries_1 = mutation.updateQueries;
if (updateQueries_1) {
this.queries.forEach(function (_a, queryId) {
var observableQuery = _a.observableQuery;
var queryName = observableQuery && observableQuery.queryName;
if (!queryName || !QueryManager_hasOwnProperty.call(updateQueries_1, queryName)) {
return;
}
var updater = updateQueries_1[queryName];
var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;
var _c = cache.diff({
query: document,
variables: variables,
returnPartialData: true,
optimistic: false,
}), currentQueryResult = _c.result, complete = _c.complete;
if (complete && currentQueryResult) {
var nextQueryResult = updater(currentQueryResult, {
mutationResult: result,
queryName: document && getOperationName(document) || void 0,
queryVariables: variables,
});
if (nextQueryResult) {
cacheWrites.push({
result: nextQueryResult,
dataId: 'ROOT_QUERY',
query: document,
variables: variables,
});
}
}
});
}
}
if (cacheWrites.length > 0 ||
mutation.refetchQueries ||
mutation.update ||
mutation.onQueryUpdated ||
mutation.removeOptimistic) {
var results_1 = [];
this.refetchQueries({
updateCache: function (cache) {
if (!skipCache) {
cacheWrites.forEach(function (write) { return cache.write(write); });
}
var update = mutation.update;
var isFinalResult = !isExecutionPatchResult(result) ||
(isExecutionPatchIncrementalResult(result) && !result.hasNext);
if (update) {
if (!skipCache) {
var diff = cache.diff({
id: "ROOT_MUTATION",
query: _this.transform(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
if (diff.complete) {
result = __assign(__assign({}, result), { data: diff.result });
if ('incremental' in result) {
delete result.incremental;
}
if ('hasNext' in result) {
delete result.hasNext;
}
}
}
if (isFinalResult) {
update(cache, result, {
context: mutation.context,
variables: mutation.variables,
});
}
}
if (!skipCache && !mutation.keepRootFields && isFinalResult) {
cache.modify({
id: 'ROOT_MUTATION',
fields: function (value, _a) {
var fieldName = _a.fieldName, DELETE = _a.DELETE;
return fieldName === "__typename" ? value : DELETE;
},
});
}
},
include: mutation.refetchQueries,
optimistic: false,
removeOptimistic: mutation.removeOptimistic,
onQueryUpdated: mutation.onQueryUpdated || null,
}).forEach(function (result) { return results_1.push(result); });
if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
return Promise.all(results_1).then(function () { return result; });
}
}
return Promise.resolve(result);
};
QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {
var _this = this;
var data = typeof optimisticResponse === "function"
? optimisticResponse(mutation.variables)
: optimisticResponse;
return this.cache.recordOptimisticTransaction(function (cache) {
try {
_this.markMutationResult(__assign(__assign({}, mutation), { result: { data: data } }), cache);
}
catch (error) {
__DEV__ && invariant.error(error);
}
}, mutation.mutationId);
};
QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
return this.fetchQueryObservable(queryId, options, networkStatus).promise;
};
QueryManager.prototype.getQueryStore = function () {
var store = Object.create(null);
this.queries.forEach(function (info, queryId) {
store[queryId] = {
variables: info.variables,
networkStatus: info.networkStatus,
networkError: info.networkError,
graphQLErrors: info.graphQLErrors,
};
});
return store;
};
QueryManager.prototype.resetErrors = function (queryId) {
var queryInfo = this.queries.get(queryId);
if (queryInfo) {
queryInfo.networkError = undefined;
queryInfo.graphQLErrors = [];
}
};
QueryManager.prototype.transform = function (document) {
var transformCache = this.transformCache;
if (!transformCache.has(document)) {
var transformed = this.cache.transformDocument(document);
var noConnection = removeConnectionDirectiveFromDocument(transformed);
var clientQuery = this.localState.clientQuery(transformed);
var serverQuery = noConnection && this.localState.serverQuery(noConnection);
var cacheEntry_1 = {
document: transformed,
hasClientExports: directives_hasClientExports(transformed),
hasForcedResolvers: this.localState.shouldForceResolvers(transformed),
clientQuery: clientQuery,
serverQuery: serverQuery,
defaultVars: getDefaultValues(getOperationDefinition(transformed)),
asQuery: __assign(__assign({}, transformed), { definitions: transformed.definitions.map(function (def) {
if (def.kind === "OperationDefinition" &&
def.operation !== "query") {
return __assign(__assign({}, def), { operation: "query" });
}
return def;
}) })
};
var add = function (doc) {
if (doc && !transformCache.has(doc)) {
transformCache.set(doc, cacheEntry_1);
}
};
add(document);
add(transformed);
add(clientQuery);
add(serverQuery);
}
return transformCache.get(document);
};
QueryManager.prototype.getVariables = function (document, variables) {
return __assign(__assign({}, this.transform(document).defaultVars), variables);
};
QueryManager.prototype.watchQuery = function (options) {
options = __assign(__assign({}, options), { variables: this.getVariables(options.query, options.variables) });
if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
options.notifyOnNetworkStatusChange = false;
}
var queryInfo = new QueryInfo_QueryInfo(this);
var observable = new ObservableQuery_ObservableQuery({
queryManager: this,
queryInfo: queryInfo,
options: options,
});
this.queries.set(observable.queryId, queryInfo);
queryInfo.init({
document: observable.query,
observableQuery: observable,
variables: observable.variables,
});
return observable;
};
QueryManager.prototype.query = function (options, queryId) {
var _this = this;
if (queryId === void 0) { queryId = this.generateQueryId(); }
__DEV__ ? invariant(options.query, 'query option is required. You must specify your GraphQL document ' +
'in the query option.') : invariant(options.query, 17);
__DEV__ ? invariant(options.query.kind === 'Document', 'You must wrap the query string in a "gql" tag.') : invariant(options.query.kind === 'Document', 18);
__DEV__ ? invariant(!options.returnPartialData, 'returnPartialData option only supported on watchQuery.') : invariant(!options.returnPartialData, 19);
__DEV__ ? invariant(!options.pollInterval, 'pollInterval option only supported on watchQuery.') : invariant(!options.pollInterval, 20);
return this.fetchQuery(queryId, options).finally(function () { return _this.stopQuery(queryId); });
};
QueryManager.prototype.generateQueryId = function () {
return String(this.queryIdCounter++);
};
QueryManager.prototype.generateRequestId = function () {
return this.requestIdCounter++;
};
QueryManager.prototype.generateMutationId = function () {
return String(this.mutationIdCounter++);
};
QueryManager.prototype.stopQueryInStore = function (queryId) {
this.stopQueryInStoreNoBroadcast(queryId);
this.broadcastQueries();
};
QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
var queryInfo = this.queries.get(queryId);
if (queryInfo)
queryInfo.stop();
};
QueryManager.prototype.clearStore = function (options) {
if (options === void 0) { options = {
discardWatches: true,
}; }
this.cancelPendingFetches(__DEV__ ? new invariant_InvariantError('Store reset while query was in flight (not completed in link chain)') : new invariant_InvariantError(21));
this.queries.forEach(function (queryInfo) {
if (queryInfo.observableQuery) {
queryInfo.networkStatus = NetworkStatus.loading;
}
else {
queryInfo.stop();
}
});
if (this.mutationStore) {
this.mutationStore = Object.create(null);
}
return this.cache.reset(options);
};
QueryManager.prototype.getObservableQueries = function (include) {
var _this = this;
if (include === void 0) { include = "active"; }
var queries = new Map();
var queryNamesAndDocs = new Map();
var legacyQueryOptions = new Set();
if (Array.isArray(include)) {
include.forEach(function (desc) {
if (typeof desc === "string") {
queryNamesAndDocs.set(desc, false);
}
else if (isDocumentNode(desc)) {
queryNamesAndDocs.set(_this.transform(desc).document, false);
}
else if (isNonNullObject(desc) && desc.query) {
legacyQueryOptions.add(desc);
}
});
}
this.queries.forEach(function (_a, queryId) {
var oq = _a.observableQuery, document = _a.document;
if (oq) {
if (include === "all") {
queries.set(queryId, oq);
return;
}
var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;
if (fetchPolicy === "standby" ||
(include === "active" && !oq.hasObservers())) {
return;
}
if (include === "active" ||
(queryName && queryNamesAndDocs.has(queryName)) ||
(document && queryNamesAndDocs.has(document))) {
queries.set(queryId, oq);
if (queryName)
queryNamesAndDocs.set(queryName, true);
if (document)
queryNamesAndDocs.set(document, true);
}
}
});
if (legacyQueryOptions.size) {
legacyQueryOptions.forEach(function (options) {
var queryId = makeUniqueId("legacyOneTimeQuery");
var queryInfo = _this.getQuery(queryId).init({
document: options.query,
variables: options.variables,
});
var oq = new ObservableQuery_ObservableQuery({
queryManager: _this,
queryInfo: queryInfo,
options: __assign(__assign({}, options), { fetchPolicy: "network-only" }),
});
invariant(oq.queryId === queryId);
queryInfo.setObservableQuery(oq);
queries.set(queryId, oq);
});
}
if (__DEV__ && queryNamesAndDocs.size) {
queryNamesAndDocs.forEach(function (included, nameOrDoc) {
if (!included) {
__DEV__ && invariant.warn("Unknown query ".concat(typeof nameOrDoc === "string" ? "named " : "").concat(JSON.stringify(nameOrDoc, null, 2), " requested in refetchQueries options.include array"));
}
});
}
return queries;
};
QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
var _this = this;
if (includeStandby === void 0) { includeStandby = false; }
var observableQueryPromises = [];
this.getObservableQueries(includeStandby ? "all" : "active").forEach(function (observableQuery, queryId) {
var fetchPolicy = observableQuery.options.fetchPolicy;
observableQuery.resetLastResults();
if (includeStandby ||
(fetchPolicy !== "standby" &&
fetchPolicy !== "cache-only")) {
observableQueryPromises.push(observableQuery.refetch());
}
_this.getQuery(queryId).setDiff(null);
});
this.broadcastQueries();
return Promise.all(observableQueryPromises);
};
QueryManager.prototype.setObservableQuery = function (observableQuery) {
this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);
};
QueryManager.prototype.startGraphQLSubscription = function (_a) {
var _this = this;
var query = _a.query, fetchPolicy = _a.fetchPolicy, errorPolicy = _a.errorPolicy, variables = _a.variables, _b = _a.context, context = _b === void 0 ? {} : _b;
query = this.transform(query).document;
variables = this.getVariables(query, variables);
var makeObservable = function (variables) {
return _this.getObservableFromLink(query, context, variables).map(function (result) {
if (fetchPolicy !== 'no-cache') {
if (shouldWriteResult(result, errorPolicy)) {
_this.cache.write({
query: query,
result: result.data,
dataId: 'ROOT_SUBSCRIPTION',
variables: variables,
});
}
_this.broadcastQueries();
}
var hasErrors = graphQLResultHasError(result);
var hasProtocolErrors = graphQLResultHasProtocolErrors(result);
if (hasErrors || hasProtocolErrors) {
var errors = {};
if (hasErrors) {
errors.graphQLErrors = result.errors;
}
if (hasProtocolErrors) {
errors.protocolErrors = result.extensions[PROTOCOL_ERRORS_SYMBOL];
}
throw new errors_ApolloError(errors);
}
return result;
});
};
if (this.transform(query).hasClientExports) {
var observablePromise_1 = this.localState.addExportedVariables(query, variables, context).then(makeObservable);
return new Observable(function (observer) {
var sub = null;
observablePromise_1.then(function (observable) { return sub = observable.subscribe(observer); }, observer.error);
return function () { return sub && sub.unsubscribe(); };
});
}
return makeObservable(variables);
};
QueryManager.prototype.stopQuery = function (queryId) {
this.stopQueryNoBroadcast(queryId);
this.broadcastQueries();
};
QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
this.stopQueryInStoreNoBroadcast(queryId);
this.removeQuery(queryId);
};
QueryManager.prototype.removeQuery = function (queryId) {
this.fetchCancelFns.delete(queryId);
if (this.queries.has(queryId)) {
this.getQuery(queryId).stop();
this.queries.delete(queryId);
}
};
QueryManager.prototype.broadcastQueries = function () {
if (this.onBroadcast)
this.onBroadcast();
this.queries.forEach(function (info) { return info.notify(); });
};
QueryManager.prototype.getLocalState = function () {
return this.localState;
};
QueryManager.prototype.getObservableFromLink = function (query, context, variables, deduplication) {
var _this = this;
var _a;
if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
var observable;
var serverQuery = this.transform(query).serverQuery;
if (serverQuery) {
var _b = this, inFlightLinkObservables_1 = _b.inFlightLinkObservables, link = _b.link;
var operation = {
query: serverQuery,
variables: variables,
operationName: getOperationName(serverQuery) || void 0,
context: this.prepareContext(__assign(__assign({}, context), { forceFetch: !deduplication })),
};
context = operation.context;
if (deduplication) {
var byVariables_1 = inFlightLinkObservables_1.get(serverQuery) || new Map();
inFlightLinkObservables_1.set(serverQuery, byVariables_1);
var varJson_1 = canonicalStringify(variables);
observable = byVariables_1.get(varJson_1);
if (!observable) {
var concast = new Concast_Concast([
execute_execute(link, operation)
]);
byVariables_1.set(varJson_1, observable = concast);
concast.beforeNext(function () {
if (byVariables_1.delete(varJson_1) &&
byVariables_1.size < 1) {
inFlightLinkObservables_1.delete(serverQuery);
}
});
}
}
else {
observable = new Concast_Concast([
execute_execute(link, operation)
]);
}
}
else {
observable = new Concast_Concast([
Observable.of({ data: {} })
]);
context = this.prepareContext(context);
}
var clientQuery = this.transform(query).clientQuery;
if (clientQuery) {
observable = asyncMap(observable, function (result) {
return _this.localState.runResolvers({
document: clientQuery,
remoteResult: result,
context: context,
variables: variables,
});
});
}
return observable;
};
QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {
var requestId = queryInfo.lastRequestId = this.generateRequestId();
var linkDocument = this.cache.transformForLink(this.transform(queryInfo.document).document);
return asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {
var graphQLErrors = getGraphQLErrorsFromResult(result);
var hasErrors = graphQLErrors.length > 0;
if (requestId >= queryInfo.lastRequestId) {
if (hasErrors && options.errorPolicy === "none") {
throw queryInfo.markError(new errors_ApolloError({
graphQLErrors: graphQLErrors,
}));
}
queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);
queryInfo.markReady();
}
var aqr = {
data: result.data,
loading: false,
networkStatus: NetworkStatus.ready,
};
if (hasErrors && options.errorPolicy !== "ignore") {
aqr.errors = graphQLErrors;
aqr.networkStatus = NetworkStatus.error;
}
return aqr;
}, function (networkError) {
var error = isApolloError(networkError)
? networkError
: new errors_ApolloError({ networkError: networkError });
if (requestId >= queryInfo.lastRequestId) {
queryInfo.markError(error);
}
throw error;
});
};
QueryManager.prototype.fetchQueryObservable = function (queryId, options, networkStatus) {
return this.fetchConcastWithInfo(queryId, options, networkStatus).concast;
};
QueryManager.prototype.fetchConcastWithInfo = function (queryId, options, networkStatus) {
var _this = this;
if (networkStatus === void 0) { networkStatus = NetworkStatus.loading; }
var query = this.transform(options.query).document;
var variables = this.getVariables(query, options.variables);
var queryInfo = this.getQuery(queryId);
var defaults = this.defaultOptions.watchQuery;
var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? defaults && defaults.fetchPolicy || "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? defaults && defaults.errorPolicy || "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
var normalized = Object.assign({}, options, {
query: query,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
returnPartialData: returnPartialData,
notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
context: context,
});
var fromVariables = function (variables) {
normalized.variables = variables;
var sourcesWithInfo = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
if (normalized.fetchPolicy !== "standby" &&
sourcesWithInfo.sources.length > 0 &&
queryInfo.observableQuery) {
queryInfo.observableQuery["applyNextFetchPolicy"]("after-fetch", options);
}
return sourcesWithInfo;
};
var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };
this.fetchCancelFns.set(queryId, function (reason) {
cleanupCancelFn();
setTimeout(function () { return concast.cancel(reason); });
});
var concast, containsDataFromLink;
if (this.transform(normalized.query).hasClientExports) {
concast = new Concast_Concast(this.localState
.addExportedVariables(normalized.query, normalized.variables, normalized.context)
.then(fromVariables).then(function (sourcesWithInfo) { return sourcesWithInfo.sources; }));
containsDataFromLink = true;
}
else {
var sourcesWithInfo = fromVariables(normalized.variables);
containsDataFromLink = sourcesWithInfo.fromLink;
concast = new Concast_Concast(sourcesWithInfo.sources);
}
concast.promise.then(cleanupCancelFn, cleanupCancelFn);
return {
concast: concast,
fromLink: containsDataFromLink,
};
};
QueryManager.prototype.refetchQueries = function (_a) {
var _this = this;
var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? makeUniqueId("refetchQueries") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;
var includedQueriesById = new Map();
if (include) {
this.getObservableQueries(include).forEach(function (oq, queryId) {
includedQueriesById.set(queryId, {
oq: oq,
lastDiff: _this.getQuery(queryId).getDiff(),
});
});
}
var results = new Map;
if (updateCache) {
this.cache.batch({
update: updateCache,
optimistic: optimistic && removeOptimistic || false,
removeOptimistic: removeOptimistic,
onWatchUpdated: function (watch, diff, lastDiff) {
var oq = watch.watcher instanceof QueryInfo_QueryInfo &&
watch.watcher.observableQuery;
if (oq) {
if (onQueryUpdated) {
includedQueriesById.delete(oq.queryId);
var result = onQueryUpdated(oq, diff, lastDiff);
if (result === true) {
result = oq.refetch();
}
if (result !== false) {
results.set(oq, result);
}
return result;
}
if (onQueryUpdated !== null) {
includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });
}
}
},
});
}
if (includedQueriesById.size) {
includedQueriesById.forEach(function (_a, queryId) {
var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;
var result;
if (onQueryUpdated) {
if (!diff) {
var info = oq["queryInfo"];
info.reset();
diff = info.getDiff();
}
result = onQueryUpdated(oq, diff, lastDiff);
}
if (!onQueryUpdated || result === true) {
result = oq.refetch();
}
if (result !== false) {
results.set(oq, result);
}
if (queryId.indexOf("legacyOneTimeQuery") >= 0) {
_this.stopQueryNoBroadcast(queryId);
}
});
}
if (removeOptimistic) {
this.cache.removeOptimistic(removeOptimistic);
}
return results;
};
QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a, networkStatus) {
var _this = this;
var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;
var oldNetworkStatus = queryInfo.networkStatus;
queryInfo.init({
document: this.transform(query).document,
variables: variables,
networkStatus: networkStatus,
});
var readCache = function () { return queryInfo.getDiff(variables); };
var resultsFromCache = function (diff, networkStatus) {
if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || NetworkStatus.loading; }
var data = diff.result;
if (__DEV__ &&
!returnPartialData &&
!equal(data, {})) {
logMissingFieldErrors(diff.missing);
}
var fromData = function (data) { return Observable.of(__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true }))); };
if (data && _this.transform(query).hasForcedResolvers) {
return _this.localState.runResolvers({
document: query,
remoteResult: { data: data },
context: context,
variables: variables,
onlyRunForcedResolvers: true,
}).then(function (resolved) { return fromData(resolved.data || void 0); });
}
if (errorPolicy === 'none' &&
networkStatus === NetworkStatus.refetch &&
Array.isArray(diff.missing)) {
return fromData(void 0);
}
return fromData(data);
};
var cacheWriteBehavior = fetchPolicy === "no-cache" ? 0 :
(networkStatus === NetworkStatus.refetch &&
refetchWritePolicy !== "merge") ? 1
: 2;
var resultsFromLink = function () { return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {
variables: variables,
context: context,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
}); };
var shouldNotify = notifyOnNetworkStatusChange &&
typeof oldNetworkStatus === "number" &&
oldNetworkStatus !== networkStatus &&
isNetworkRequestInFlight(networkStatus);
switch (fetchPolicy) {
default:
case "cache-first": {
var diff = readCache();
if (diff.complete) {
return { fromLink: false, sources: [resultsFromCache(diff, queryInfo.markReady())] };
}
if (returnPartialData || shouldNotify) {
return { fromLink: true, sources: [resultsFromCache(diff), resultsFromLink()] };
}
return { fromLink: true, sources: [resultsFromLink()] };
}
case "cache-and-network": {
var diff = readCache();
if (diff.complete || returnPartialData || shouldNotify) {
return { fromLink: true, sources: [resultsFromCache(diff), resultsFromLink()] };
}
return { fromLink: true, sources: [resultsFromLink()] };
}
case "cache-only":
return { fromLink: false, sources: [resultsFromCache(readCache(), queryInfo.markReady())] };
case "network-only":
if (shouldNotify) {
return { fromLink: true, sources: [resultsFromCache(readCache()), resultsFromLink()] };
}
return { fromLink: true, sources: [resultsFromLink()] };
case "no-cache":
if (shouldNotify) {
return {
fromLink: true,
sources: [
resultsFromCache(queryInfo.getDiff()),
resultsFromLink(),
],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
case "standby":
return { fromLink: false, sources: [] };
}
};
QueryManager.prototype.getQuery = function (queryId) {
if (queryId && !this.queries.has(queryId)) {
this.queries.set(queryId, new QueryInfo_QueryInfo(this, queryId));
}
return this.queries.get(queryId);
};
QueryManager.prototype.prepareContext = function (context) {
if (context === void 0) { context = {}; }
var newContext = this.localState.prepareContext(context);
return __assign(__assign({}, newContext), { clientAwareness: this.clientAwareness });
};
return QueryManager;
}());
//# sourceMappingURL=QueryManager.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/mergeOptions.js
function mergeOptions(defaults, options) {
return compact(defaults, options, options.variables && {
variables: __assign(__assign({}, (defaults && defaults.variables)), options.variables),
});
}
//# sourceMappingURL=mergeOptions.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/core/ApolloClient.js
var hasSuggestedDevtools = false;
var ApolloClient_ApolloClient = (function () {
function ApolloClient(options) {
var _this = this;
this.resetStoreCallbacks = [];
this.clearStoreCallbacks = [];
var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, _c = options.connectToDevTools, connectToDevTools = _c === void 0 ? typeof window === 'object' &&
!window.__APOLLO_CLIENT__ &&
__DEV__ : _c, _d = options.queryDeduplication, queryDeduplication = _d === void 0 ? true : _d, defaultOptions = options.defaultOptions, _e = options.assumeImmutableResults, assumeImmutableResults = _e === void 0 ? false : _e, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version;
var link = options.link;
if (!link) {
link = uri
? new HttpLink_HttpLink({ uri: uri, credentials: credentials, headers: headers })
: ApolloLink_ApolloLink.empty();
}
if (!cache) {
throw __DEV__ ? new invariant_InvariantError("To initialize Apollo Client, you must specify a 'cache' property " +
"in the options object. \n" +
"For more information, please visit: https://go.apollo.dev/c/docs") : new invariant_InvariantError(9);
}
this.link = link;
this.cache = cache;
this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
this.queryDeduplication = queryDeduplication;
this.defaultOptions = defaultOptions || Object.create(null);
this.typeDefs = typeDefs;
if (ssrForceFetchDelay) {
setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
}
this.watchQuery = this.watchQuery.bind(this);
this.query = this.query.bind(this);
this.mutate = this.mutate.bind(this);
this.resetStore = this.resetStore.bind(this);
this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
if (connectToDevTools && typeof window === 'object') {
window.__APOLLO_CLIENT__ = this;
}
if (!hasSuggestedDevtools && connectToDevTools && __DEV__) {
hasSuggestedDevtools = true;
if (typeof window !== 'undefined' &&
window.document &&
window.top === window.self &&
!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {
var nav = window.navigator;
var ua = nav && nav.userAgent;
var url = void 0;
if (typeof ua === "string") {
if (ua.indexOf("Chrome/") > -1) {
url = "https://chrome.google.com/webstore/detail/" +
"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm";
}
else if (ua.indexOf("Firefox/") > -1) {
url = "https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/";
}
}
if (url) {
__DEV__ && invariant.log("Download the Apollo DevTools for a better development " +
"experience: " + url);
}
}
}
this.version = version_version;
this.localState = new LocalState_LocalState({
cache: cache,
client: this,
resolvers: resolvers,
fragmentMatcher: fragmentMatcher,
});
this.queryManager = new QueryManager_QueryManager({
cache: this.cache,
link: this.link,
defaultOptions: this.defaultOptions,
queryDeduplication: queryDeduplication,
ssrMode: ssrMode,
clientAwareness: {
name: clientAwarenessName,
version: clientAwarenessVersion,
},
localState: this.localState,
assumeImmutableResults: assumeImmutableResults,
onBroadcast: connectToDevTools ? function () {
if (_this.devToolsHookCb) {
_this.devToolsHookCb({
action: {},
state: {
queries: _this.queryManager.getQueryStore(),
mutations: _this.queryManager.mutationStore || {},
},
dataWithOptimisticResults: _this.cache.extract(true),
});
}
} : void 0,
});
}
ApolloClient.prototype.stop = function () {
this.queryManager.stop();
};
ApolloClient.prototype.watchQuery = function (options) {
if (this.defaultOptions.watchQuery) {
options = mergeOptions(this.defaultOptions.watchQuery, options);
}
if (this.disableNetworkFetches &&
(options.fetchPolicy === 'network-only' ||
options.fetchPolicy === 'cache-and-network')) {
options = __assign(__assign({}, options), { fetchPolicy: 'cache-first' });
}
return this.queryManager.watchQuery(options);
};
ApolloClient.prototype.query = function (options) {
if (this.defaultOptions.query) {
options = mergeOptions(this.defaultOptions.query, options);
}
__DEV__ ? invariant(options.fetchPolicy !== 'cache-and-network', 'The cache-and-network fetchPolicy does not work with client.query, because ' +
'client.query can only return a single result. Please use client.watchQuery ' +
'to receive multiple results from the cache and the network, or consider ' +
'using a different fetchPolicy, such as cache-first or network-only.') : invariant(options.fetchPolicy !== 'cache-and-network', 10);
if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
options = __assign(__assign({}, options), { fetchPolicy: 'cache-first' });
}
return this.queryManager.query(options);
};
ApolloClient.prototype.mutate = function (options) {
if (this.defaultOptions.mutate) {
options = mergeOptions(this.defaultOptions.mutate, options);
}
return this.queryManager.mutate(options);
};
ApolloClient.prototype.subscribe = function (options) {
return this.queryManager.startGraphQLSubscription(options);
};
ApolloClient.prototype.readQuery = function (options, optimistic) {
if (optimistic === void 0) { optimistic = false; }
return this.cache.readQuery(options, optimistic);
};
ApolloClient.prototype.readFragment = function (options, optimistic) {
if (optimistic === void 0) { optimistic = false; }
return this.cache.readFragment(options, optimistic);
};
ApolloClient.prototype.writeQuery = function (options) {
var ref = this.cache.writeQuery(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
};
ApolloClient.prototype.writeFragment = function (options) {
var ref = this.cache.writeFragment(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
};
ApolloClient.prototype.__actionHookForDevTools = function (cb) {
this.devToolsHookCb = cb;
};
ApolloClient.prototype.__requestRaw = function (payload) {
return execute_execute(this.link, payload);
};
ApolloClient.prototype.resetStore = function () {
var _this = this;
return Promise.resolve()
.then(function () { return _this.queryManager.clearStore({
discardWatches: false,
}); })
.then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
.then(function () { return _this.reFetchObservableQueries(); });
};
ApolloClient.prototype.clearStore = function () {
var _this = this;
return Promise.resolve()
.then(function () { return _this.queryManager.clearStore({
discardWatches: true,
}); })
.then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
};
ApolloClient.prototype.onResetStore = function (cb) {
var _this = this;
this.resetStoreCallbacks.push(cb);
return function () {
_this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
};
};
ApolloClient.prototype.onClearStore = function (cb) {
var _this = this;
this.clearStoreCallbacks.push(cb);
return function () {
_this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
};
};
ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
return this.queryManager.reFetchObservableQueries(includeStandby);
};
ApolloClient.prototype.refetchQueries = function (options) {
var map = this.queryManager.refetchQueries(options);
var queries = [];
var results = [];
map.forEach(function (result, obsQuery) {
queries.push(obsQuery);
results.push(result);
});
var result = Promise.all(results);
result.queries = queries;
result.results = results;
result.catch(function (error) {
__DEV__ && invariant.debug("In client.refetchQueries, Promise.all promise rejected with error ".concat(error));
});
return result;
};
ApolloClient.prototype.getObservableQueries = function (include) {
if (include === void 0) { include = "active"; }
return this.queryManager.getObservableQueries(include);
};
ApolloClient.prototype.extract = function (optimistic) {
return this.cache.extract(optimistic);
};
ApolloClient.prototype.restore = function (serializedState) {
return this.cache.restore(serializedState);
};
ApolloClient.prototype.addResolvers = function (resolvers) {
this.localState.addResolvers(resolvers);
};
ApolloClient.prototype.setResolvers = function (resolvers) {
this.localState.setResolvers(resolvers);
};
ApolloClient.prototype.getResolvers = function () {
return this.localState.getResolvers();
};
ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
this.localState.setFragmentMatcher(fragmentMatcher);
};
ApolloClient.prototype.setLink = function (newLink) {
this.link = this.queryManager.link = newLink;
};
return ApolloClient;
}());
//# sourceMappingURL=ApolloClient.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/core/cache.js
var cache_ApolloCache = (function () {
function ApolloCache() {
this.getFragmentDoc = bundle_esm_wrap(getFragmentQueryDocument);
}
ApolloCache.prototype.batch = function (options) {
var _this = this;
var optimisticId = typeof options.optimistic === "string" ? options.optimistic :
options.optimistic === false ? null : void 0;
var updateResult;
this.performTransaction(function () { return updateResult = options.update(_this); }, optimisticId);
return updateResult;
};
ApolloCache.prototype.recordOptimisticTransaction = function (transaction, optimisticId) {
this.performTransaction(transaction, optimisticId);
};
ApolloCache.prototype.transformDocument = function (document) {
return document;
};
ApolloCache.prototype.transformForLink = function (document) {
return document;
};
ApolloCache.prototype.identify = function (object) {
return;
};
ApolloCache.prototype.gc = function () {
return [];
};
ApolloCache.prototype.modify = function (options) {
return false;
};
ApolloCache.prototype.readQuery = function (options, optimistic) {
if (optimistic === void 0) { optimistic = !!options.optimistic; }
return this.read(__assign(__assign({}, options), { rootId: options.id || 'ROOT_QUERY', optimistic: optimistic }));
};
ApolloCache.prototype.readFragment = function (options, optimistic) {
if (optimistic === void 0) { optimistic = !!options.optimistic; }
return this.read(__assign(__assign({}, options), { query: this.getFragmentDoc(options.fragment, options.fragmentName), rootId: options.id, optimistic: optimistic }));
};
ApolloCache.prototype.writeQuery = function (_a) {
var id = _a.id, data = _a.data, options = __rest(_a, ["id", "data"]);
return this.write(Object.assign(options, {
dataId: id || 'ROOT_QUERY',
result: data,
}));
};
ApolloCache.prototype.writeFragment = function (_a) {
var id = _a.id, data = _a.data, fragment = _a.fragment, fragmentName = _a.fragmentName, options = __rest(_a, ["id", "data", "fragment", "fragmentName"]);
return this.write(Object.assign(options, {
query: this.getFragmentDoc(fragment, fragmentName),
dataId: id,
result: data,
}));
};
ApolloCache.prototype.updateQuery = function (options, update) {
return this.batch({
update: function (cache) {
var value = cache.readQuery(options);
var data = update(value);
if (data === void 0 || data === null)
return value;
cache.writeQuery(__assign(__assign({}, options), { data: data }));
return data;
},
});
};
ApolloCache.prototype.updateFragment = function (options, update) {
return this.batch({
update: function (cache) {
var value = cache.readFragment(options);
var data = update(value);
if (data === void 0 || data === null)
return value;
cache.writeFragment(__assign(__assign({}, options), { data: data }));
return data;
},
});
};
return ApolloCache;
}());
//# sourceMappingURL=cache.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/core/types/common.js
var common_MissingFieldError = (function (_super) {
__extends(MissingFieldError, _super);
function MissingFieldError(message, path, query, variables) {
var _a;
var _this = _super.call(this, message) || this;
_this.message = message;
_this.path = path;
_this.query = query;
_this.variables = variables;
if (Array.isArray(_this.path)) {
_this.missing = _this.message;
for (var i = _this.path.length - 1; i >= 0; --i) {
_this.missing = (_a = {}, _a[_this.path[i]] = _this.missing, _a);
}
}
else {
_this.missing = _this.path;
}
_this.__proto__ = MissingFieldError.prototype;
return _this;
}
return MissingFieldError;
}(Error));
//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/maybeDeepFreeze.js
function deepFreeze(value) {
var workSet = new Set([value]);
workSet.forEach(function (obj) {
if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {
Object.getOwnPropertyNames(obj).forEach(function (name) {
if (isNonNullObject(obj[name]))
workSet.add(obj[name]);
});
}
});
return value;
}
function shallowFreeze(obj) {
if (__DEV__ && !Object.isFrozen(obj)) {
try {
Object.freeze(obj);
}
catch (e) {
if (e instanceof TypeError)
return null;
throw e;
}
}
return obj;
}
function maybeDeepFreeze(obj) {
if (__DEV__) {
deepFreeze(obj);
}
return obj;
}
//# sourceMappingURL=maybeDeepFreeze.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/helpers.js
var hasOwn = Object.prototype.hasOwnProperty;
function isNullish(value) {
return value === null || value === void 0;
}
function defaultDataIdFromObject(_a, context) {
var __typename = _a.__typename, id = _a.id, _id = _a._id;
if (typeof __typename === "string") {
if (context) {
context.keyObject =
!isNullish(id) ? { id: id } :
!isNullish(_id) ? { _id: _id } :
void 0;
}
if (isNullish(id) && !isNullish(_id)) {
id = _id;
}
if (!isNullish(id)) {
return "".concat(__typename, ":").concat((typeof id === "number" ||
typeof id === "string") ? id : JSON.stringify(id));
}
}
}
var defaultConfig = {
dataIdFromObject: defaultDataIdFromObject,
addTypename: true,
resultCaching: true,
canonizeResults: false,
};
function normalizeConfig(config) {
return compact(defaultConfig, config);
}
function shouldCanonizeResults(config) {
var value = config.canonizeResults;
return value === void 0 ? defaultConfig.canonizeResults : value;
}
function getTypenameFromStoreObject(store, objectOrReference) {
return isReference(objectOrReference)
? store.get(objectOrReference.__ref, "__typename")
: objectOrReference && objectOrReference.__typename;
}
var TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;
function fieldNameFromStoreName(storeFieldName) {
var match = storeFieldName.match(TypeOrFieldNameRegExp);
return match ? match[0] : storeFieldName;
}
function selectionSetMatchesResult(selectionSet, result, variables) {
if (isNonNullObject(result)) {
return arrays_isArray(result)
? result.every(function (item) { return selectionSetMatchesResult(selectionSet, item, variables); })
: selectionSet.selections.every(function (field) {
if (isField(field) && shouldInclude(field, variables)) {
var key = resultKeyNameFromField(field);
return hasOwn.call(result, key) &&
(!field.selectionSet ||
selectionSetMatchesResult(field.selectionSet, result[key], variables));
}
return true;
});
}
return false;
}
function storeValueIsStoreObject(value) {
return isNonNullObject(value) &&
!isReference(value) &&
!arrays_isArray(value);
}
function makeProcessedFieldsMerger() {
return new mergeDeep_DeepMerger;
}
function extractFragmentContext(document, fragments) {
var fragmentMap = createFragmentMap(getFragmentDefinitions(document));
return {
fragmentMap: fragmentMap,
lookupFragment: function (name) {
var def = fragmentMap[name];
if (!def && fragments) {
def = fragments.lookup(name);
}
return def || null;
},
};
}
//# sourceMappingURL=helpers.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/entityStore.js
var DELETE = Object.create(null);
var delModifier = function () { return DELETE; };
var INVALIDATE = Object.create(null);
var entityStore_EntityStore = (function () {
function EntityStore(policies, group) {
var _this = this;
this.policies = policies;
this.group = group;
this.data = Object.create(null);
this.rootIds = Object.create(null);
this.refs = Object.create(null);
this.getFieldValue = function (objectOrReference, storeFieldName) { return maybeDeepFreeze(isReference(objectOrReference)
? _this.get(objectOrReference.__ref, storeFieldName)
: objectOrReference && objectOrReference[storeFieldName]); };
this.canRead = function (objOrRef) {
return isReference(objOrRef)
? _this.has(objOrRef.__ref)
: typeof objOrRef === "object";
};
this.toReference = function (objOrIdOrRef, mergeIntoStore) {
if (typeof objOrIdOrRef === "string") {
return makeReference(objOrIdOrRef);
}
if (isReference(objOrIdOrRef)) {
return objOrIdOrRef;
}
var id = _this.policies.identify(objOrIdOrRef)[0];
if (id) {
var ref = makeReference(id);
if (mergeIntoStore) {
_this.merge(id, objOrIdOrRef);
}
return ref;
}
};
}
EntityStore.prototype.toObject = function () {
return __assign({}, this.data);
};
EntityStore.prototype.has = function (dataId) {
return this.lookup(dataId, true) !== void 0;
};
EntityStore.prototype.get = function (dataId, fieldName) {
this.group.depend(dataId, fieldName);
if (hasOwn.call(this.data, dataId)) {
var storeObject = this.data[dataId];
if (storeObject && hasOwn.call(storeObject, fieldName)) {
return storeObject[fieldName];
}
}
if (fieldName === "__typename" &&
hasOwn.call(this.policies.rootTypenamesById, dataId)) {
return this.policies.rootTypenamesById[dataId];
}
if (this instanceof entityStore_Layer) {
return this.parent.get(dataId, fieldName);
}
};
EntityStore.prototype.lookup = function (dataId, dependOnExistence) {
if (dependOnExistence)
this.group.depend(dataId, "__exists");
if (hasOwn.call(this.data, dataId)) {
return this.data[dataId];
}
if (this instanceof entityStore_Layer) {
return this.parent.lookup(dataId, dependOnExistence);
}
if (this.policies.rootTypenamesById[dataId]) {
return Object.create(null);
}
};
EntityStore.prototype.merge = function (older, newer) {
var _this = this;
var dataId;
if (isReference(older))
older = older.__ref;
if (isReference(newer))
newer = newer.__ref;
var existing = typeof older === "string"
? this.lookup(dataId = older)
: older;
var incoming = typeof newer === "string"
? this.lookup(dataId = newer)
: newer;
if (!incoming)
return;
__DEV__ ? invariant(typeof dataId === "string", "store.merge expects a string ID") : invariant(typeof dataId === "string", 1);
var merged = new mergeDeep_DeepMerger(storeObjectReconciler).merge(existing, incoming);
this.data[dataId] = merged;
if (merged !== existing) {
delete this.refs[dataId];
if (this.group.caching) {
var fieldsToDirty_1 = Object.create(null);
if (!existing)
fieldsToDirty_1.__exists = 1;
Object.keys(incoming).forEach(function (storeFieldName) {
if (!existing || existing[storeFieldName] !== merged[storeFieldName]) {
fieldsToDirty_1[storeFieldName] = 1;
var fieldName = fieldNameFromStoreName(storeFieldName);
if (fieldName !== storeFieldName &&
!_this.policies.hasKeyArgs(merged.__typename, fieldName)) {
fieldsToDirty_1[fieldName] = 1;
}
if (merged[storeFieldName] === void 0 && !(_this instanceof entityStore_Layer)) {
delete merged[storeFieldName];
}
}
});
if (fieldsToDirty_1.__typename &&
!(existing && existing.__typename) &&
this.policies.rootTypenamesById[dataId] === merged.__typename) {
delete fieldsToDirty_1.__typename;
}
Object.keys(fieldsToDirty_1).forEach(function (fieldName) { return _this.group.dirty(dataId, fieldName); });
}
}
};
EntityStore.prototype.modify = function (dataId, fields) {
var _this = this;
var storeObject = this.lookup(dataId);
if (storeObject) {
var changedFields_1 = Object.create(null);
var needToMerge_1 = false;
var allDeleted_1 = true;
var sharedDetails_1 = {
DELETE: DELETE,
INVALIDATE: INVALIDATE,
isReference: isReference,
toReference: this.toReference,
canRead: this.canRead,
readField: function (fieldNameOrOptions, from) { return _this.policies.readField(typeof fieldNameOrOptions === "string" ? {
fieldName: fieldNameOrOptions,
from: from || makeReference(dataId),
} : fieldNameOrOptions, { store: _this }); },
};
Object.keys(storeObject).forEach(function (storeFieldName) {
var fieldName = fieldNameFromStoreName(storeFieldName);
var fieldValue = storeObject[storeFieldName];
if (fieldValue === void 0)
return;
var modify = typeof fields === "function"
? fields
: fields[storeFieldName] || fields[fieldName];
if (modify) {
var newValue = modify === delModifier ? DELETE :
modify(maybeDeepFreeze(fieldValue), __assign(__assign({}, sharedDetails_1), { fieldName: fieldName, storeFieldName: storeFieldName, storage: _this.getStorage(dataId, storeFieldName) }));
if (newValue === INVALIDATE) {
_this.group.dirty(dataId, storeFieldName);
}
else {
if (newValue === DELETE)
newValue = void 0;
if (newValue !== fieldValue) {
changedFields_1[storeFieldName] = newValue;
needToMerge_1 = true;
fieldValue = newValue;
}
}
}
if (fieldValue !== void 0) {
allDeleted_1 = false;
}
});
if (needToMerge_1) {
this.merge(dataId, changedFields_1);
if (allDeleted_1) {
if (this instanceof entityStore_Layer) {
this.data[dataId] = void 0;
}
else {
delete this.data[dataId];
}
this.group.dirty(dataId, "__exists");
}
return true;
}
}
return false;
};
EntityStore.prototype.delete = function (dataId, fieldName, args) {
var _a;
var storeObject = this.lookup(dataId);
if (storeObject) {
var typename = this.getFieldValue(storeObject, "__typename");
var storeFieldName = fieldName && args
? this.policies.getStoreFieldName({ typename: typename, fieldName: fieldName, args: args })
: fieldName;
return this.modify(dataId, storeFieldName ? (_a = {},
_a[storeFieldName] = delModifier,
_a) : delModifier);
}
return false;
};
EntityStore.prototype.evict = function (options, limit) {
var evicted = false;
if (options.id) {
if (hasOwn.call(this.data, options.id)) {
evicted = this.delete(options.id, options.fieldName, options.args);
}
if (this instanceof entityStore_Layer && this !== limit) {
evicted = this.parent.evict(options, limit) || evicted;
}
if (options.fieldName || evicted) {
this.group.dirty(options.id, options.fieldName || "__exists");
}
}
return evicted;
};
EntityStore.prototype.clear = function () {
this.replace(null);
};
EntityStore.prototype.extract = function () {
var _this = this;
var obj = this.toObject();
var extraRootIds = [];
this.getRootIdSet().forEach(function (id) {
if (!hasOwn.call(_this.policies.rootTypenamesById, id)) {
extraRootIds.push(id);
}
});
if (extraRootIds.length) {
obj.__META = { extraRootIds: extraRootIds.sort() };
}
return obj;
};
EntityStore.prototype.replace = function (newData) {
var _this = this;
Object.keys(this.data).forEach(function (dataId) {
if (!(newData && hasOwn.call(newData, dataId))) {
_this.delete(dataId);
}
});
if (newData) {
var __META = newData.__META, rest_1 = __rest(newData, ["__META"]);
Object.keys(rest_1).forEach(function (dataId) {
_this.merge(dataId, rest_1[dataId]);
});
if (__META) {
__META.extraRootIds.forEach(this.retain, this);
}
}
};
EntityStore.prototype.retain = function (rootId) {
return this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1;
};
EntityStore.prototype.release = function (rootId) {
if (this.rootIds[rootId] > 0) {
var count = --this.rootIds[rootId];
if (!count)
delete this.rootIds[rootId];
return count;
}
return 0;
};
EntityStore.prototype.getRootIdSet = function (ids) {
if (ids === void 0) { ids = new Set(); }
Object.keys(this.rootIds).forEach(ids.add, ids);
if (this instanceof entityStore_Layer) {
this.parent.getRootIdSet(ids);
}
else {
Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);
}
return ids;
};
EntityStore.prototype.gc = function () {
var _this = this;
var ids = this.getRootIdSet();
var snapshot = this.toObject();
ids.forEach(function (id) {
if (hasOwn.call(snapshot, id)) {
Object.keys(_this.findChildRefIds(id)).forEach(ids.add, ids);
delete snapshot[id];
}
});
var idsToRemove = Object.keys(snapshot);
if (idsToRemove.length) {
var root_1 = this;
while (root_1 instanceof entityStore_Layer)
root_1 = root_1.parent;
idsToRemove.forEach(function (id) { return root_1.delete(id); });
}
return idsToRemove;
};
EntityStore.prototype.findChildRefIds = function (dataId) {
if (!hasOwn.call(this.refs, dataId)) {
var found_1 = this.refs[dataId] = Object.create(null);
var root = this.data[dataId];
if (!root)
return found_1;
var workSet_1 = new Set([root]);
workSet_1.forEach(function (obj) {
if (isReference(obj)) {
found_1[obj.__ref] = true;
}
if (isNonNullObject(obj)) {
Object.keys(obj).forEach(function (key) {
var child = obj[key];
if (isNonNullObject(child)) {
workSet_1.add(child);
}
});
}
});
}
return this.refs[dataId];
};
EntityStore.prototype.makeCacheKey = function () {
return this.group.keyMaker.lookupArray(arguments);
};
return EntityStore;
}());
var entityStore_CacheGroup = (function () {
function CacheGroup(caching, parent) {
if (parent === void 0) { parent = null; }
this.caching = caching;
this.parent = parent;
this.d = null;
this.resetCaching();
}
CacheGroup.prototype.resetCaching = function () {
this.d = this.caching ? dep() : null;
this.keyMaker = new Trie(canUseWeakMap);
};
CacheGroup.prototype.depend = function (dataId, storeFieldName) {
if (this.d) {
this.d(makeDepKey(dataId, storeFieldName));
var fieldName = fieldNameFromStoreName(storeFieldName);
if (fieldName !== storeFieldName) {
this.d(makeDepKey(dataId, fieldName));
}
if (this.parent) {
this.parent.depend(dataId, storeFieldName);
}
}
};
CacheGroup.prototype.dirty = function (dataId, storeFieldName) {
if (this.d) {
this.d.dirty(makeDepKey(dataId, storeFieldName), storeFieldName === "__exists" ? "forget" : "setDirty");
}
};
return CacheGroup;
}());
function makeDepKey(dataId, storeFieldName) {
return storeFieldName + '#' + dataId;
}
function maybeDependOnExistenceOfEntity(store, entityId) {
if (supportsResultCaching(store)) {
store.group.depend(entityId, "__exists");
}
}
(function (EntityStore) {
var Root = (function (_super) {
__extends(Root, _super);
function Root(_a) {
var policies = _a.policies, _b = _a.resultCaching, resultCaching = _b === void 0 ? true : _b, seed = _a.seed;
var _this = _super.call(this, policies, new entityStore_CacheGroup(resultCaching)) || this;
_this.stump = new entityStore_Stump(_this);
_this.storageTrie = new Trie(canUseWeakMap);
if (seed)
_this.replace(seed);
return _this;
}
Root.prototype.addLayer = function (layerId, replay) {
return this.stump.addLayer(layerId, replay);
};
Root.prototype.removeLayer = function () {
return this;
};
Root.prototype.getStorage = function () {
return this.storageTrie.lookupArray(arguments);
};
return Root;
}(EntityStore));
EntityStore.Root = Root;
})(entityStore_EntityStore || (entityStore_EntityStore = {}));
var entityStore_Layer = (function (_super) {
__extends(Layer, _super);
function Layer(id, parent, replay, group) {
var _this = _super.call(this, parent.policies, group) || this;
_this.id = id;
_this.parent = parent;
_this.replay = replay;
_this.group = group;
replay(_this);
return _this;
}
Layer.prototype.addLayer = function (layerId, replay) {
return new Layer(layerId, this, replay, this.group);
};
Layer.prototype.removeLayer = function (layerId) {
var _this = this;
var parent = this.parent.removeLayer(layerId);
if (layerId === this.id) {
if (this.group.caching) {
Object.keys(this.data).forEach(function (dataId) {
var ownStoreObject = _this.data[dataId];
var parentStoreObject = parent["lookup"](dataId);
if (!parentStoreObject) {
_this.delete(dataId);
}
else if (!ownStoreObject) {
_this.group.dirty(dataId, "__exists");
Object.keys(parentStoreObject).forEach(function (storeFieldName) {
_this.group.dirty(dataId, storeFieldName);
});
}
else if (ownStoreObject !== parentStoreObject) {
Object.keys(ownStoreObject).forEach(function (storeFieldName) {
if (!equal(ownStoreObject[storeFieldName], parentStoreObject[storeFieldName])) {
_this.group.dirty(dataId, storeFieldName);
}
});
}
});
}
return parent;
}
if (parent === this.parent)
return this;
return parent.addLayer(this.id, this.replay);
};
Layer.prototype.toObject = function () {
return __assign(__assign({}, this.parent.toObject()), this.data);
};
Layer.prototype.findChildRefIds = function (dataId) {
var fromParent = this.parent.findChildRefIds(dataId);
return hasOwn.call(this.data, dataId) ? __assign(__assign({}, fromParent), _super.prototype.findChildRefIds.call(this, dataId)) : fromParent;
};
Layer.prototype.getStorage = function () {
var p = this.parent;
while (p.parent)
p = p.parent;
return p.getStorage.apply(p, arguments);
};
return Layer;
}(entityStore_EntityStore));
var entityStore_Stump = (function (_super) {
__extends(Stump, _super);
function Stump(root) {
return _super.call(this, "EntityStore.Stump", root, function () { }, new entityStore_CacheGroup(root.group.caching, root.group)) || this;
}
Stump.prototype.removeLayer = function () {
return this;
};
Stump.prototype.merge = function () {
return this.parent.merge.apply(this.parent, arguments);
};
return Stump;
}(entityStore_Layer));
function storeObjectReconciler(existingObject, incomingObject, property) {
var existingValue = existingObject[property];
var incomingValue = incomingObject[property];
return equal(existingValue, incomingValue) ? existingValue : incomingValue;
}
function supportsResultCaching(store) {
return !!(store instanceof entityStore_EntityStore && store.group.caching);
}
//# sourceMappingURL=entityStore.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/readFromStore.js
;
function execSelectionSetKeyArgs(options) {
return [
options.selectionSet,
options.objectOrReference,
options.context,
options.context.canonizeResults,
];
}
var readFromStore_StoreReader = (function () {
function StoreReader(config) {
var _this = this;
this.knownResults = new (canUseWeakMap ? WeakMap : Map)();
this.config = compact(config, {
addTypename: config.addTypename !== false,
canonizeResults: shouldCanonizeResults(config),
});
this.canon = config.canon || new object_canon_ObjectCanon;
this.executeSelectionSet = bundle_esm_wrap(function (options) {
var _a;
var canonizeResults = options.context.canonizeResults;
var peekArgs = execSelectionSetKeyArgs(options);
peekArgs[3] = !canonizeResults;
var other = (_a = _this.executeSelectionSet).peek.apply(_a, peekArgs);
if (other) {
if (canonizeResults) {
return __assign(__assign({}, other), { result: _this.canon.admit(other.result) });
}
return other;
}
maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);
return _this.execSelectionSetImpl(options);
}, {
max: this.config.resultCacheMaxSize,
keyArgs: execSelectionSetKeyArgs,
makeCacheKey: function (selectionSet, parent, context, canonizeResults) {
if (supportsResultCaching(context.store)) {
return context.store.makeCacheKey(selectionSet, isReference(parent) ? parent.__ref : parent, context.varString, canonizeResults);
}
}
});
this.executeSubSelectedArray = bundle_esm_wrap(function (options) {
maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);
return _this.execSubSelectedArrayImpl(options);
}, {
max: this.config.resultCacheMaxSize,
makeCacheKey: function (_a) {
var field = _a.field, array = _a.array, context = _a.context;
if (supportsResultCaching(context.store)) {
return context.store.makeCacheKey(field, array, context.varString);
}
}
});
}
StoreReader.prototype.resetCanon = function () {
this.canon = new object_canon_ObjectCanon;
};
StoreReader.prototype.diffQueryAgainstStore = function (_a) {
var store = _a.store, query = _a.query, _b = _a.rootId, rootId = _b === void 0 ? 'ROOT_QUERY' : _b, variables = _a.variables, _c = _a.returnPartialData, returnPartialData = _c === void 0 ? true : _c, _d = _a.canonizeResults, canonizeResults = _d === void 0 ? this.config.canonizeResults : _d;
var policies = this.config.cache.policies;
variables = __assign(__assign({}, getDefaultValues(getQueryDefinition(query))), variables);
var rootRef = makeReference(rootId);
var execResult = this.executeSelectionSet({
selectionSet: getMainDefinition(query).selectionSet,
objectOrReference: rootRef,
enclosingRef: rootRef,
context: __assign({ store: store, query: query, policies: policies, variables: variables, varString: canonicalStringify(variables), canonizeResults: canonizeResults }, extractFragmentContext(query, this.config.fragments)),
});
var missing;
if (execResult.missing) {
missing = [new common_MissingFieldError(firstMissing(execResult.missing), execResult.missing, query, variables)];
if (!returnPartialData) {
throw missing[0];
}
}
return {
result: execResult.result,
complete: !missing,
missing: missing,
};
};
StoreReader.prototype.isFresh = function (result, parent, selectionSet, context) {
if (supportsResultCaching(context.store) &&
this.knownResults.get(result) === selectionSet) {
var latest = this.executeSelectionSet.peek(selectionSet, parent, context, this.canon.isKnown(result));
if (latest && result === latest.result) {
return true;
}
}
return false;
};
StoreReader.prototype.execSelectionSetImpl = function (_a) {
var _this = this;
var selectionSet = _a.selectionSet, objectOrReference = _a.objectOrReference, enclosingRef = _a.enclosingRef, context = _a.context;
if (isReference(objectOrReference) &&
!context.policies.rootTypenamesById[objectOrReference.__ref] &&
!context.store.has(objectOrReference.__ref)) {
return {
result: this.canon.empty,
missing: "Dangling reference to missing ".concat(objectOrReference.__ref, " object"),
};
}
var variables = context.variables, policies = context.policies, store = context.store;
var typename = store.getFieldValue(objectOrReference, "__typename");
var objectsToMerge = [];
var missing;
var missingMerger = new mergeDeep_DeepMerger();
if (this.config.addTypename &&
typeof typename === "string" &&
!policies.rootIdsByTypename[typename]) {
objectsToMerge.push({ __typename: typename });
}
function handleMissing(result, resultName) {
var _a;
if (result.missing) {
missing = missingMerger.merge(missing, (_a = {}, _a[resultName] = result.missing, _a));
}
return result.result;
}
var workSet = new Set(selectionSet.selections);
workSet.forEach(function (selection) {
var _a, _b;
if (!shouldInclude(selection, variables))
return;
if (isField(selection)) {
var fieldValue = policies.readField({
fieldName: selection.name.value,
field: selection,
variables: context.variables,
from: objectOrReference,
}, context);
var resultName = resultKeyNameFromField(selection);
if (fieldValue === void 0) {
if (!addTypenameToDocument.added(selection)) {
missing = missingMerger.merge(missing, (_a = {},
_a[resultName] = "Can't find field '".concat(selection.name.value, "' on ").concat(isReference(objectOrReference)
? objectOrReference.__ref + " object"
: "object " + JSON.stringify(objectOrReference, null, 2)),
_a));
}
}
else if (arrays_isArray(fieldValue)) {
fieldValue = handleMissing(_this.executeSubSelectedArray({
field: selection,
array: fieldValue,
enclosingRef: enclosingRef,
context: context,
}), resultName);
}
else if (!selection.selectionSet) {
if (context.canonizeResults) {
fieldValue = _this.canon.pass(fieldValue);
}
}
else if (fieldValue != null) {
fieldValue = handleMissing(_this.executeSelectionSet({
selectionSet: selection.selectionSet,
objectOrReference: fieldValue,
enclosingRef: isReference(fieldValue) ? fieldValue : enclosingRef,
context: context,
}), resultName);
}
if (fieldValue !== void 0) {
objectsToMerge.push((_b = {}, _b[resultName] = fieldValue, _b));
}
}
else {
var fragment = getFragmentFromSelection(selection, context.lookupFragment);
if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {
throw __DEV__ ? new invariant_InvariantError("No fragment named ".concat(selection.name.value)) : new invariant_InvariantError(5);
}
if (fragment && policies.fragmentMatches(fragment, typename)) {
fragment.selectionSet.selections.forEach(workSet.add, workSet);
}
}
});
var result = mergeDeepArray(objectsToMerge);
var finalResult = { result: result, missing: missing };
var frozen = context.canonizeResults
? this.canon.admit(finalResult)
: maybeDeepFreeze(finalResult);
if (frozen.result) {
this.knownResults.set(frozen.result, selectionSet);
}
return frozen;
};
StoreReader.prototype.execSubSelectedArrayImpl = function (_a) {
var _this = this;
var field = _a.field, array = _a.array, enclosingRef = _a.enclosingRef, context = _a.context;
var missing;
var missingMerger = new mergeDeep_DeepMerger();
function handleMissing(childResult, i) {
var _a;
if (childResult.missing) {
missing = missingMerger.merge(missing, (_a = {}, _a[i] = childResult.missing, _a));
}
return childResult.result;
}
if (field.selectionSet) {
array = array.filter(context.store.canRead);
}
array = array.map(function (item, i) {
if (item === null) {
return null;
}
if (arrays_isArray(item)) {
return handleMissing(_this.executeSubSelectedArray({
field: field,
array: item,
enclosingRef: enclosingRef,
context: context,
}), i);
}
if (field.selectionSet) {
return handleMissing(_this.executeSelectionSet({
selectionSet: field.selectionSet,
objectOrReference: item,
enclosingRef: isReference(item) ? item : enclosingRef,
context: context,
}), i);
}
if (__DEV__) {
assertSelectionSetForIdValue(context.store, field, item);
}
return item;
});
return {
result: context.canonizeResults ? this.canon.admit(array) : array,
missing: missing,
};
};
return StoreReader;
}());
function firstMissing(tree) {
try {
JSON.stringify(tree, function (_, value) {
if (typeof value === "string")
throw value;
return value;
});
}
catch (result) {
return result;
}
}
function assertSelectionSetForIdValue(store, field, fieldValue) {
if (!field.selectionSet) {
var workSet_1 = new Set([fieldValue]);
workSet_1.forEach(function (value) {
if (isNonNullObject(value)) {
__DEV__ ? invariant(!isReference(value), "Missing selection set for object of type ".concat(getTypenameFromStoreObject(store, value), " returned for query field ").concat(field.name.value)) : invariant(!isReference(value), 6);
Object.values(value).forEach(workSet_1.add, workSet_1);
}
});
}
}
//# sourceMappingURL=readFromStore.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/utilities/common/stringifyForDisplay.js
function stringifyForDisplay(value) {
var undefId = makeUniqueId("stringifyForDisplay");
return JSON.stringify(value, function (key, value) {
return value === void 0 ? undefId : value;
}).split(JSON.stringify(undefId)).join("<undefined>");
}
//# sourceMappingURL=stringifyForDisplay.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/key-extractor.js
var specifierInfoCache = Object.create(null);
function lookupSpecifierInfo(spec) {
var cacheKey = JSON.stringify(spec);
return specifierInfoCache[cacheKey] ||
(specifierInfoCache[cacheKey] = Object.create(null));
}
function keyFieldsFnFromSpecifier(specifier) {
var info = lookupSpecifierInfo(specifier);
return info.keyFieldsFn || (info.keyFieldsFn = function (object, context) {
var extract = function (from, key) { return context.readField(key, from); };
var keyObject = context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {
var extracted = extractKeyPath(context.storeObject, schemaKeyPath, extract);
if (extracted === void 0 &&
object !== context.storeObject &&
hasOwn.call(object, schemaKeyPath[0])) {
extracted = extractKeyPath(object, schemaKeyPath, extractKey);
}
__DEV__ ? invariant(extracted !== void 0, "Missing field '".concat(schemaKeyPath.join('.'), "' while extracting keyFields from ").concat(JSON.stringify(object))) : invariant(extracted !== void 0, 2);
return extracted;
});
return "".concat(context.typename, ":").concat(JSON.stringify(keyObject));
});
}
function keyArgsFnFromSpecifier(specifier) {
var info = lookupSpecifierInfo(specifier);
return info.keyArgsFn || (info.keyArgsFn = function (args, _a) {
var field = _a.field, variables = _a.variables, fieldName = _a.fieldName;
var collected = collectSpecifierPaths(specifier, function (keyPath) {
var firstKey = keyPath[0];
var firstChar = firstKey.charAt(0);
if (firstChar === "@") {
if (field && isNonEmptyArray(field.directives)) {
var directiveName_1 = firstKey.slice(1);
var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });
var directiveArgs = d && argumentsObjectFromField(d, variables);
return directiveArgs && extractKeyPath(directiveArgs, keyPath.slice(1));
}
return;
}
if (firstChar === "$") {
var variableName = firstKey.slice(1);
if (variables && hasOwn.call(variables, variableName)) {
var varKeyPath = keyPath.slice(0);
varKeyPath[0] = variableName;
return extractKeyPath(variables, varKeyPath);
}
return;
}
if (args) {
return extractKeyPath(args, keyPath);
}
});
var suffix = JSON.stringify(collected);
if (args || suffix !== "{}") {
fieldName += ":" + suffix;
}
return fieldName;
});
}
function collectSpecifierPaths(specifier, extractor) {
var merger = new mergeDeep_DeepMerger;
return getSpecifierPaths(specifier).reduce(function (collected, path) {
var _a;
var toMerge = extractor(path);
if (toMerge !== void 0) {
for (var i = path.length - 1; i >= 0; --i) {
toMerge = (_a = {}, _a[path[i]] = toMerge, _a);
}
collected = merger.merge(collected, toMerge);
}
return collected;
}, Object.create(null));
}
function getSpecifierPaths(spec) {
var info = lookupSpecifierInfo(spec);
if (!info.paths) {
var paths_1 = info.paths = [];
var currentPath_1 = [];
spec.forEach(function (s, i) {
if (arrays_isArray(s)) {
getSpecifierPaths(s).forEach(function (p) { return paths_1.push(currentPath_1.concat(p)); });
currentPath_1.length = 0;
}
else {
currentPath_1.push(s);
if (!arrays_isArray(spec[i + 1])) {
paths_1.push(currentPath_1.slice(0));
currentPath_1.length = 0;
}
}
});
}
return info.paths;
}
function extractKey(object, key) {
return object[key];
}
function extractKeyPath(object, path, extract) {
extract = extract || extractKey;
return key_extractor_normalize(path.reduce(function reducer(obj, key) {
return arrays_isArray(obj)
? obj.map(function (child) { return reducer(child, key); })
: obj && extract(obj, key);
}, object));
}
function key_extractor_normalize(value) {
if (isNonNullObject(value)) {
if (arrays_isArray(value)) {
return value.map(key_extractor_normalize);
}
return collectSpecifierPaths(Object.keys(value).sort(), function (path) { return extractKeyPath(value, path); });
}
return value;
}
//# sourceMappingURL=key-extractor.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/policies.js
getStoreKeyName.setStringify(canonicalStringify);
function argsFromFieldSpecifier(spec) {
return spec.args !== void 0 ? spec.args :
spec.field ? argumentsObjectFromField(spec.field, spec.variables) : null;
}
var nullKeyFieldsFn = function () { return void 0; };
var simpleKeyArgsFn = function (_args, context) { return context.fieldName; };
var mergeTrueFn = function (existing, incoming, _a) {
var mergeObjects = _a.mergeObjects;
return mergeObjects(existing, incoming);
};
var mergeFalseFn = function (_, incoming) { return incoming; };
var policies_Policies = (function () {
function Policies(config) {
this.config = config;
this.typePolicies = Object.create(null);
this.toBeAdded = Object.create(null);
this.supertypeMap = new Map();
this.fuzzySubtypes = new Map();
this.rootIdsByTypename = Object.create(null);
this.rootTypenamesById = Object.create(null);
this.usingPossibleTypes = false;
this.config = __assign({ dataIdFromObject: defaultDataIdFromObject }, config);
this.cache = this.config.cache;
this.setRootTypename("Query");
this.setRootTypename("Mutation");
this.setRootTypename("Subscription");
if (config.possibleTypes) {
this.addPossibleTypes(config.possibleTypes);
}
if (config.typePolicies) {
this.addTypePolicies(config.typePolicies);
}
}
Policies.prototype.identify = function (object, partialContext) {
var _a;
var policies = this;
var typename = partialContext && (partialContext.typename ||
((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename)) || object.__typename;
if (typename === this.rootTypenamesById.ROOT_QUERY) {
return ["ROOT_QUERY"];
}
var storeObject = partialContext && partialContext.storeObject || object;
var context = __assign(__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: partialContext && partialContext.readField || function () {
var options = normalizeReadFieldOptions(arguments, storeObject);
return policies.readField(options, {
store: policies.cache["data"],
variables: options.variables,
});
} });
var id;
var policy = typename && this.getTypePolicy(typename);
var keyFn = policy && policy.keyFn || this.config.dataIdFromObject;
while (keyFn) {
var specifierOrId = keyFn(__assign(__assign({}, object), storeObject), context);
if (arrays_isArray(specifierOrId)) {
keyFn = keyFieldsFnFromSpecifier(specifierOrId);
}
else {
id = specifierOrId;
break;
}
}
id = id ? String(id) : void 0;
return context.keyObject ? [id, context.keyObject] : [id];
};
Policies.prototype.addTypePolicies = function (typePolicies) {
var _this = this;
Object.keys(typePolicies).forEach(function (typename) {
var _a = typePolicies[typename], queryType = _a.queryType, mutationType = _a.mutationType, subscriptionType = _a.subscriptionType, incoming = __rest(_a, ["queryType", "mutationType", "subscriptionType"]);
if (queryType)
_this.setRootTypename("Query", typename);
if (mutationType)
_this.setRootTypename("Mutation", typename);
if (subscriptionType)
_this.setRootTypename("Subscription", typename);
if (hasOwn.call(_this.toBeAdded, typename)) {
_this.toBeAdded[typename].push(incoming);
}
else {
_this.toBeAdded[typename] = [incoming];
}
});
};
Policies.prototype.updateTypePolicy = function (typename, incoming) {
var _this = this;
var existing = this.getTypePolicy(typename);
var keyFields = incoming.keyFields, fields = incoming.fields;
function setMerge(existing, merge) {
existing.merge =
typeof merge === "function" ? merge :
merge === true ? mergeTrueFn :
merge === false ? mergeFalseFn :
existing.merge;
}
setMerge(existing, incoming.merge);
existing.keyFn =
keyFields === false ? nullKeyFieldsFn :
arrays_isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields) :
typeof keyFields === "function" ? keyFields :
existing.keyFn;
if (fields) {
Object.keys(fields).forEach(function (fieldName) {
var existing = _this.getFieldPolicy(typename, fieldName, true);
var incoming = fields[fieldName];
if (typeof incoming === "function") {
existing.read = incoming;
}
else {
var keyArgs = incoming.keyArgs, read = incoming.read, merge = incoming.merge;
existing.keyFn =
keyArgs === false ? simpleKeyArgsFn :
arrays_isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs) :
typeof keyArgs === "function" ? keyArgs :
existing.keyFn;
if (typeof read === "function") {
existing.read = read;
}
setMerge(existing, merge);
}
if (existing.read && existing.merge) {
existing.keyFn = existing.keyFn || simpleKeyArgsFn;
}
});
}
};
Policies.prototype.setRootTypename = function (which, typename) {
if (typename === void 0) { typename = which; }
var rootId = "ROOT_" + which.toUpperCase();
var old = this.rootTypenamesById[rootId];
if (typename !== old) {
__DEV__ ? invariant(!old || old === which, "Cannot change root ".concat(which, " __typename more than once")) : invariant(!old || old === which, 3);
if (old)
delete this.rootIdsByTypename[old];
this.rootIdsByTypename[typename] = rootId;
this.rootTypenamesById[rootId] = typename;
}
};
Policies.prototype.addPossibleTypes = function (possibleTypes) {
var _this = this;
this.usingPossibleTypes = true;
Object.keys(possibleTypes).forEach(function (supertype) {
_this.getSupertypeSet(supertype, true);
possibleTypes[supertype].forEach(function (subtype) {
_this.getSupertypeSet(subtype, true).add(supertype);
var match = subtype.match(TypeOrFieldNameRegExp);
if (!match || match[0] !== subtype) {
_this.fuzzySubtypes.set(subtype, new RegExp(subtype));
}
});
});
};
Policies.prototype.getTypePolicy = function (typename) {
var _this = this;
if (!hasOwn.call(this.typePolicies, typename)) {
var policy_1 = this.typePolicies[typename] = Object.create(null);
policy_1.fields = Object.create(null);
var supertypes = this.supertypeMap.get(typename);
if (supertypes && supertypes.size) {
supertypes.forEach(function (supertype) {
var _a = _this.getTypePolicy(supertype), fields = _a.fields, rest = __rest(_a, ["fields"]);
Object.assign(policy_1, rest);
Object.assign(policy_1.fields, fields);
});
}
}
var inbox = this.toBeAdded[typename];
if (inbox && inbox.length) {
inbox.splice(0).forEach(function (policy) {
_this.updateTypePolicy(typename, policy);
});
}
return this.typePolicies[typename];
};
Policies.prototype.getFieldPolicy = function (typename, fieldName, createIfMissing) {
if (typename) {
var fieldPolicies = this.getTypePolicy(typename).fields;
return fieldPolicies[fieldName] || (createIfMissing && (fieldPolicies[fieldName] = Object.create(null)));
}
};
Policies.prototype.getSupertypeSet = function (subtype, createIfMissing) {
var supertypeSet = this.supertypeMap.get(subtype);
if (!supertypeSet && createIfMissing) {
this.supertypeMap.set(subtype, supertypeSet = new Set());
}
return supertypeSet;
};
Policies.prototype.fragmentMatches = function (fragment, typename, result, variables) {
var _this = this;
if (!fragment.typeCondition)
return true;
if (!typename)
return false;
var supertype = fragment.typeCondition.name.value;
if (typename === supertype)
return true;
if (this.usingPossibleTypes &&
this.supertypeMap.has(supertype)) {
var typenameSupertypeSet = this.getSupertypeSet(typename, true);
var workQueue_1 = [typenameSupertypeSet];
var maybeEnqueue_1 = function (subtype) {
var supertypeSet = _this.getSupertypeSet(subtype, false);
if (supertypeSet &&
supertypeSet.size &&
workQueue_1.indexOf(supertypeSet) < 0) {
workQueue_1.push(supertypeSet);
}
};
var needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);
var checkingFuzzySubtypes = false;
for (var i = 0; i < workQueue_1.length; ++i) {
var supertypeSet = workQueue_1[i];
if (supertypeSet.has(supertype)) {
if (!typenameSupertypeSet.has(supertype)) {
if (checkingFuzzySubtypes) {
__DEV__ && invariant.warn("Inferring subtype ".concat(typename, " of supertype ").concat(supertype));
}
typenameSupertypeSet.add(supertype);
}
return true;
}
supertypeSet.forEach(maybeEnqueue_1);
if (needToCheckFuzzySubtypes &&
i === workQueue_1.length - 1 &&
selectionSetMatchesResult(fragment.selectionSet, result, variables)) {
needToCheckFuzzySubtypes = false;
checkingFuzzySubtypes = true;
this.fuzzySubtypes.forEach(function (regExp, fuzzyString) {
var match = typename.match(regExp);
if (match && match[0] === typename) {
maybeEnqueue_1(fuzzyString);
}
});
}
}
}
return false;
};
Policies.prototype.hasKeyArgs = function (typename, fieldName) {
var policy = this.getFieldPolicy(typename, fieldName, false);
return !!(policy && policy.keyFn);
};
Policies.prototype.getStoreFieldName = function (fieldSpec) {
var typename = fieldSpec.typename, fieldName = fieldSpec.fieldName;
var policy = this.getFieldPolicy(typename, fieldName, false);
var storeFieldName;
var keyFn = policy && policy.keyFn;
if (keyFn && typename) {
var context = {
typename: typename,
fieldName: fieldName,
field: fieldSpec.field || null,
variables: fieldSpec.variables,
};
var args = argsFromFieldSpecifier(fieldSpec);
while (keyFn) {
var specifierOrString = keyFn(args, context);
if (arrays_isArray(specifierOrString)) {
keyFn = keyArgsFnFromSpecifier(specifierOrString);
}
else {
storeFieldName = specifierOrString || fieldName;
break;
}
}
}
if (storeFieldName === void 0) {
storeFieldName = fieldSpec.field
? storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)
: getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));
}
if (storeFieldName === false) {
return fieldName;
}
return fieldName === fieldNameFromStoreName(storeFieldName)
? storeFieldName
: fieldName + ":" + storeFieldName;
};
Policies.prototype.readField = function (options, context) {
var objectOrReference = options.from;
if (!objectOrReference)
return;
var nameOrField = options.field || options.fieldName;
if (!nameOrField)
return;
if (options.typename === void 0) {
var typename = context.store.getFieldValue(objectOrReference, "__typename");
if (typename)
options.typename = typename;
}
var storeFieldName = this.getStoreFieldName(options);
var fieldName = fieldNameFromStoreName(storeFieldName);
var existing = context.store.getFieldValue(objectOrReference, storeFieldName);
var policy = this.getFieldPolicy(options.typename, fieldName, false);
var read = policy && policy.read;
if (read) {
var readOptions = makeFieldFunctionOptions(this, objectOrReference, options, context, context.store.getStorage(isReference(objectOrReference)
? objectOrReference.__ref
: objectOrReference, storeFieldName));
return cacheSlot.withValue(this.cache, read, [existing, readOptions]);
}
return existing;
};
Policies.prototype.getReadFunction = function (typename, fieldName) {
var policy = this.getFieldPolicy(typename, fieldName, false);
return policy && policy.read;
};
Policies.prototype.getMergeFunction = function (parentTypename, fieldName, childTypename) {
var policy = this.getFieldPolicy(parentTypename, fieldName, false);
var merge = policy && policy.merge;
if (!merge && childTypename) {
policy = this.getTypePolicy(childTypename);
merge = policy && policy.merge;
}
return merge;
};
Policies.prototype.runMergeFunction = function (existing, incoming, _a, context, storage) {
var field = _a.field, typename = _a.typename, merge = _a.merge;
if (merge === mergeTrueFn) {
return makeMergeObjectsFunction(context.store)(existing, incoming);
}
if (merge === mergeFalseFn) {
return incoming;
}
if (context.overwrite) {
existing = void 0;
}
return merge(existing, incoming, makeFieldFunctionOptions(this, void 0, { typename: typename, fieldName: field.name.value, field: field, variables: context.variables }, context, storage || Object.create(null)));
};
return Policies;
}());
function makeFieldFunctionOptions(policies, objectOrReference, fieldSpec, context, storage) {
var storeFieldName = policies.getStoreFieldName(fieldSpec);
var fieldName = fieldNameFromStoreName(storeFieldName);
var variables = fieldSpec.variables || context.variables;
var _a = context.store, toReference = _a.toReference, canRead = _a.canRead;
return {
args: argsFromFieldSpecifier(fieldSpec),
field: fieldSpec.field || null,
fieldName: fieldName,
storeFieldName: storeFieldName,
variables: variables,
isReference: isReference,
toReference: toReference,
storage: storage,
cache: policies.cache,
canRead: canRead,
readField: function () {
return policies.readField(normalizeReadFieldOptions(arguments, objectOrReference, variables), context);
},
mergeObjects: makeMergeObjectsFunction(context.store),
};
}
function normalizeReadFieldOptions(readFieldArgs, objectOrReference, variables) {
var fieldNameOrOptions = readFieldArgs[0], from = readFieldArgs[1], argc = readFieldArgs.length;
var options;
if (typeof fieldNameOrOptions === "string") {
options = {
fieldName: fieldNameOrOptions,
from: argc > 1 ? from : objectOrReference,
};
}
else {
options = __assign({}, fieldNameOrOptions);
if (!hasOwn.call(options, "from")) {
options.from = objectOrReference;
}
}
if (__DEV__ && options.from === void 0) {
__DEV__ && invariant.warn("Undefined 'from' passed to readField with arguments ".concat(stringifyForDisplay(Array.from(readFieldArgs))));
}
if (void 0 === options.variables) {
options.variables = variables;
}
return options;
}
function makeMergeObjectsFunction(store) {
return function mergeObjects(existing, incoming) {
if (arrays_isArray(existing) || arrays_isArray(incoming)) {
throw __DEV__ ? new invariant_InvariantError("Cannot automatically merge arrays") : new invariant_InvariantError(4);
}
if (isNonNullObject(existing) &&
isNonNullObject(incoming)) {
var eType = store.getFieldValue(existing, "__typename");
var iType = store.getFieldValue(incoming, "__typename");
var typesDiffer = eType && iType && eType !== iType;
if (typesDiffer) {
return incoming;
}
if (isReference(existing) &&
storeValueIsStoreObject(incoming)) {
store.merge(existing.__ref, incoming);
return existing;
}
if (storeValueIsStoreObject(existing) &&
isReference(incoming)) {
store.merge(existing, incoming.__ref);
return incoming;
}
if (storeValueIsStoreObject(existing) &&
storeValueIsStoreObject(incoming)) {
return __assign(__assign({}, existing), incoming);
}
}
return incoming;
};
}
//# sourceMappingURL=policies.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/writeToStore.js
;
function getContextFlavor(context, clientOnly, deferred) {
var key = "".concat(clientOnly).concat(deferred);
var flavored = context.flavors.get(key);
if (!flavored) {
context.flavors.set(key, flavored = (context.clientOnly === clientOnly &&
context.deferred === deferred) ? context : __assign(__assign({}, context), { clientOnly: clientOnly, deferred: deferred }));
}
return flavored;
}
var writeToStore_StoreWriter = (function () {
function StoreWriter(cache, reader, fragments) {
this.cache = cache;
this.reader = reader;
this.fragments = fragments;
}
StoreWriter.prototype.writeToStore = function (store, _a) {
var _this = this;
var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;
var operationDefinition = getOperationDefinition(query);
var merger = makeProcessedFieldsMerger();
variables = __assign(__assign({}, getDefaultValues(operationDefinition)), variables);
var context = __assign(__assign({ store: store, written: Object.create(null), merge: function (existing, incoming) {
return merger.merge(existing, incoming);
}, variables: variables, varString: canonicalStringify(variables) }, extractFragmentContext(query, this.fragments)), { overwrite: !!overwrite, incomingById: new Map, clientOnly: false, deferred: false, flavors: new Map });
var ref = this.processSelectionSet({
result: result || Object.create(null),
dataId: dataId,
selectionSet: operationDefinition.selectionSet,
mergeTree: { map: new Map },
context: context,
});
if (!isReference(ref)) {
throw __DEV__ ? new invariant_InvariantError("Could not identify object ".concat(JSON.stringify(result))) : new invariant_InvariantError(7);
}
context.incomingById.forEach(function (_a, dataId) {
var storeObject = _a.storeObject, mergeTree = _a.mergeTree, fieldNodeSet = _a.fieldNodeSet;
var entityRef = makeReference(dataId);
if (mergeTree && mergeTree.map.size) {
var applied = _this.applyMerges(mergeTree, entityRef, storeObject, context);
if (isReference(applied)) {
return;
}
storeObject = applied;
}
if (__DEV__ && !context.overwrite) {
var fieldsWithSelectionSets_1 = Object.create(null);
fieldNodeSet.forEach(function (field) {
if (field.selectionSet) {
fieldsWithSelectionSets_1[field.name.value] = true;
}
});
var hasSelectionSet_1 = function (storeFieldName) {
return fieldsWithSelectionSets_1[fieldNameFromStoreName(storeFieldName)] === true;
};
var hasMergeFunction_1 = function (storeFieldName) {
var childTree = mergeTree && mergeTree.map.get(storeFieldName);
return Boolean(childTree && childTree.info && childTree.info.merge);
};
Object.keys(storeObject).forEach(function (storeFieldName) {
if (hasSelectionSet_1(storeFieldName) &&
!hasMergeFunction_1(storeFieldName)) {
warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);
}
});
}
store.merge(dataId, storeObject);
});
store.retain(ref.__ref);
return ref;
};
StoreWriter.prototype.processSelectionSet = function (_a) {
var _this = this;
var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context, mergeTree = _a.mergeTree;
var policies = this.cache.policies;
var incoming = Object.create(null);
var typename = (dataId && policies.rootTypenamesById[dataId]) ||
getTypenameFromResult(result, selectionSet, context.fragmentMap) ||
(dataId && context.store.get(dataId, "__typename"));
if ("string" === typeof typename) {
incoming.__typename = typename;
}
var readField = function () {
var options = normalizeReadFieldOptions(arguments, incoming, context.variables);
if (isReference(options.from)) {
var info = context.incomingById.get(options.from.__ref);
if (info) {
var result_1 = policies.readField(__assign(__assign({}, options), { from: info.storeObject }), context);
if (result_1 !== void 0) {
return result_1;
}
}
}
return policies.readField(options, context);
};
var fieldNodeSet = new Set();
this.flattenFields(selectionSet, result, context, typename).forEach(function (context, field) {
var _a;
var resultFieldKey = resultKeyNameFromField(field);
var value = result[resultFieldKey];
fieldNodeSet.add(field);
if (value !== void 0) {
var storeFieldName = policies.getStoreFieldName({
typename: typename,
fieldName: field.name.value,
field: field,
variables: context.variables,
});
var childTree = getChildMergeTree(mergeTree, storeFieldName);
var incomingValue = _this.processFieldValue(value, field, field.selectionSet
? getContextFlavor(context, false, false)
: context, childTree);
var childTypename = void 0;
if (field.selectionSet &&
(isReference(incomingValue) ||
storeValueIsStoreObject(incomingValue))) {
childTypename = readField("__typename", incomingValue);
}
var merge = policies.getMergeFunction(typename, field.name.value, childTypename);
if (merge) {
childTree.info = {
field: field,
typename: typename,
merge: merge,
};
}
else {
maybeRecycleChildMergeTree(mergeTree, storeFieldName);
}
incoming = context.merge(incoming, (_a = {},
_a[storeFieldName] = incomingValue,
_a));
}
else if (__DEV__ &&
!context.clientOnly &&
!context.deferred &&
!addTypenameToDocument.added(field) &&
!policies.getReadFunction(typename, field.name.value)) {
__DEV__ && invariant.error("Missing field '".concat(resultKeyNameFromField(field), "' while writing result ").concat(JSON.stringify(result, null, 2)).substring(0, 1000));
}
});
try {
var _b = policies.identify(result, {
typename: typename,
selectionSet: selectionSet,
fragmentMap: context.fragmentMap,
storeObject: incoming,
readField: readField,
}), id = _b[0], keyObject = _b[1];
dataId = dataId || id;
if (keyObject) {
incoming = context.merge(incoming, keyObject);
}
}
catch (e) {
if (!dataId)
throw e;
}
if ("string" === typeof dataId) {
var dataRef = makeReference(dataId);
var sets = context.written[dataId] || (context.written[dataId] = []);
if (sets.indexOf(selectionSet) >= 0)
return dataRef;
sets.push(selectionSet);
if (this.reader && this.reader.isFresh(result, dataRef, selectionSet, context)) {
return dataRef;
}
var previous_1 = context.incomingById.get(dataId);
if (previous_1) {
previous_1.storeObject = context.merge(previous_1.storeObject, incoming);
previous_1.mergeTree = mergeMergeTrees(previous_1.mergeTree, mergeTree);
fieldNodeSet.forEach(function (field) { return previous_1.fieldNodeSet.add(field); });
}
else {
context.incomingById.set(dataId, {
storeObject: incoming,
mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,
fieldNodeSet: fieldNodeSet,
});
}
return dataRef;
}
return incoming;
};
StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {
var _this = this;
if (!field.selectionSet || value === null) {
return __DEV__ ? cloneDeep(value) : value;
}
if (arrays_isArray(value)) {
return value.map(function (item, i) {
var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));
maybeRecycleChildMergeTree(mergeTree, i);
return value;
});
}
return this.processSelectionSet({
result: value,
selectionSet: field.selectionSet,
context: context,
mergeTree: mergeTree,
});
};
StoreWriter.prototype.flattenFields = function (selectionSet, result, context, typename) {
if (typename === void 0) { typename = getTypenameFromResult(result, selectionSet, context.fragmentMap); }
var fieldMap = new Map();
var policies = this.cache.policies;
var limitingTrie = new Trie(false);
(function flatten(selectionSet, inheritedContext) {
var visitedNode = limitingTrie.lookup(selectionSet, inheritedContext.clientOnly, inheritedContext.deferred);
if (visitedNode.visited)
return;
visitedNode.visited = true;
selectionSet.selections.forEach(function (selection) {
if (!shouldInclude(selection, context.variables))
return;
var clientOnly = inheritedContext.clientOnly, deferred = inheritedContext.deferred;
if (!(clientOnly && deferred) &&
isNonEmptyArray(selection.directives)) {
selection.directives.forEach(function (dir) {
var name = dir.name.value;
if (name === "client")
clientOnly = true;
if (name === "defer") {
var args = argumentsObjectFromField(dir, context.variables);
if (!args || args.if !== false) {
deferred = true;
}
}
});
}
if (isField(selection)) {
var existing = fieldMap.get(selection);
if (existing) {
clientOnly = clientOnly && existing.clientOnly;
deferred = deferred && existing.deferred;
}
fieldMap.set(selection, getContextFlavor(context, clientOnly, deferred));
}
else {
var fragment = getFragmentFromSelection(selection, context.lookupFragment);
if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {
throw __DEV__ ? new invariant_InvariantError("No fragment named ".concat(selection.name.value)) : new invariant_InvariantError(8);
}
if (fragment &&
policies.fragmentMatches(fragment, typename, result, context.variables)) {
flatten(fragment.selectionSet, getContextFlavor(context, clientOnly, deferred));
}
}
});
})(selectionSet, context);
return fieldMap;
};
StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {
var _a;
var _this = this;
if (mergeTree.map.size && !isReference(incoming)) {
var e_1 = (!arrays_isArray(incoming) &&
(isReference(existing) || storeValueIsStoreObject(existing))) ? existing : void 0;
var i_1 = incoming;
if (e_1 && !getStorageArgs) {
getStorageArgs = [isReference(e_1) ? e_1.__ref : e_1];
}
var changedFields_1;
var getValue_1 = function (from, name) {
return arrays_isArray(from)
? (typeof name === "number" ? from[name] : void 0)
: context.store.getFieldValue(from, String(name));
};
mergeTree.map.forEach(function (childTree, storeFieldName) {
var eVal = getValue_1(e_1, storeFieldName);
var iVal = getValue_1(i_1, storeFieldName);
if (void 0 === iVal)
return;
if (getStorageArgs) {
getStorageArgs.push(storeFieldName);
}
var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);
if (aVal !== iVal) {
changedFields_1 = changedFields_1 || new Map;
changedFields_1.set(storeFieldName, aVal);
}
if (getStorageArgs) {
invariant(getStorageArgs.pop() === storeFieldName);
}
});
if (changedFields_1) {
incoming = (arrays_isArray(i_1) ? i_1.slice(0) : __assign({}, i_1));
changedFields_1.forEach(function (value, name) {
incoming[name] = value;
});
}
}
if (mergeTree.info) {
return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));
}
return incoming;
};
return StoreWriter;
}());
var emptyMergeTreePool = [];
function getChildMergeTree(_a, name) {
var map = _a.map;
if (!map.has(name)) {
map.set(name, emptyMergeTreePool.pop() || { map: new Map });
}
return map.get(name);
}
function mergeMergeTrees(left, right) {
if (left === right || !right || mergeTreeIsEmpty(right))
return left;
if (!left || mergeTreeIsEmpty(left))
return right;
var info = left.info && right.info ? __assign(__assign({}, left.info), right.info) : left.info || right.info;
var needToMergeMaps = left.map.size && right.map.size;
var map = needToMergeMaps ? new Map :
left.map.size ? left.map : right.map;
var merged = { info: info, map: map };
if (needToMergeMaps) {
var remainingRightKeys_1 = new Set(right.map.keys());
left.map.forEach(function (leftTree, key) {
merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));
remainingRightKeys_1.delete(key);
});
remainingRightKeys_1.forEach(function (key) {
merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));
});
}
return merged;
}
function mergeTreeIsEmpty(tree) {
return !tree || !(tree.info || tree.map.size);
}
function maybeRecycleChildMergeTree(_a, name) {
var map = _a.map;
var childTree = map.get(name);
if (childTree && mergeTreeIsEmpty(childTree)) {
emptyMergeTreePool.push(childTree);
map.delete(name);
}
}
var warnings = new Set();
function warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {
var getChild = function (objOrRef) {
var child = store.getFieldValue(objOrRef, storeFieldName);
return typeof child === "object" && child;
};
var existing = getChild(existingRef);
if (!existing)
return;
var incoming = getChild(incomingObj);
if (!incoming)
return;
if (isReference(existing))
return;
if (equal(existing, incoming))
return;
if (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {
return;
}
var parentType = store.getFieldValue(existingRef, "__typename") ||
store.getFieldValue(incomingObj, "__typename");
var fieldName = fieldNameFromStoreName(storeFieldName);
var typeDotName = "".concat(parentType, ".").concat(fieldName);
if (warnings.has(typeDotName))
return;
warnings.add(typeDotName);
var childTypenames = [];
if (!arrays_isArray(existing) &&
!arrays_isArray(incoming)) {
[existing, incoming].forEach(function (child) {
var typename = store.getFieldValue(child, "__typename");
if (typeof typename === "string" &&
!childTypenames.includes(typename)) {
childTypenames.push(typename);
}
});
}
__DEV__ && invariant.warn("Cache data may be lost when replacing the ".concat(fieldName, " field of a ").concat(parentType, " object.\n\nTo address this problem (which is not a bug in Apollo Client), ").concat(childTypenames.length
? "either ensure all objects of type " +
childTypenames.join(" and ") + " have an ID or a custom merge function, or "
: "", "define a custom merge function for the ").concat(typeDotName, " field, so InMemoryCache can safely merge these objects:\n\n existing: ").concat(JSON.stringify(existing).slice(0, 1000), "\n incoming: ").concat(JSON.stringify(incoming).slice(0, 1000), "\n\nFor more information about these options, please refer to the documentation:\n\n * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n"));
}
//# sourceMappingURL=writeToStore.js.map
// CONCATENATED MODULE: ./node_modules/@apollo/client/cache/inmemory/inMemoryCache.js
var inMemoryCache_InMemoryCache = (function (_super) {
__extends(InMemoryCache, _super);
function InMemoryCache(config) {
if (config === void 0) { config = {}; }
var _this = _super.call(this) || this;
_this.watches = new Set();
_this.typenameDocumentCache = new Map();
_this.makeVar = makeVar;
_this.txCount = 0;
_this.config = normalizeConfig(config);
_this.addTypename = !!_this.config.addTypename;
_this.policies = new policies_Policies({
cache: _this,
dataIdFromObject: _this.config.dataIdFromObject,
possibleTypes: _this.config.possibleTypes,
typePolicies: _this.config.typePolicies,
});
_this.init();
return _this;
}
InMemoryCache.prototype.init = function () {
var rootStore = this.data = new entityStore_EntityStore.Root({
policies: this.policies,
resultCaching: this.config.resultCaching,
});
this.optimisticData = rootStore.stump;
this.resetResultCache();
};
InMemoryCache.prototype.resetResultCache = function (resetResultIdentities) {
var _this = this;
var previousReader = this.storeReader;
var fragments = this.config.fragments;
this.storeWriter = new writeToStore_StoreWriter(this, this.storeReader = new readFromStore_StoreReader({
cache: this,
addTypename: this.addTypename,
resultCacheMaxSize: this.config.resultCacheMaxSize,
canonizeResults: shouldCanonizeResults(this.config),
canon: resetResultIdentities
? void 0
: previousReader && previousReader.canon,
fragments: fragments,
}), fragments);
this.maybeBroadcastWatch = bundle_esm_wrap(function (c, options) {
return _this.broadcastWatch(c, options);
}, {
max: this.config.resultCacheMaxSize,
makeCacheKey: function (c) {
var store = c.optimistic ? _this.optimisticData : _this.data;
if (supportsResultCaching(store)) {
var optimistic = c.optimistic, id = c.id, variables = c.variables;
return store.makeCacheKey(c.query, c.callback, canonicalStringify({ optimistic: optimistic, id: id, variables: variables }));
}
}
});
new Set([
this.data.group,
this.optimisticData.group,
]).forEach(function (group) { return group.resetCaching(); });
};
InMemoryCache.prototype.restore = function (data) {
this.init();
if (data)
this.data.replace(data);
return this;
};
InMemoryCache.prototype.extract = function (optimistic) {
if (optimistic === void 0) { optimistic = false; }
return (optimistic ? this.optimisticData : this.data).extract();
};
InMemoryCache.prototype.read = function (options) {
var _a = options.returnPartialData, returnPartialData = _a === void 0 ? false : _a;
try {
return this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, config: this.config, returnPartialData: returnPartialData })).result || null;
}
catch (e) {
if (e instanceof common_MissingFieldError) {
return null;
}
throw e;
}
};
InMemoryCache.prototype.write = function (options) {
try {
++this.txCount;
return this.storeWriter.writeToStore(this.data, options);
}
finally {
if (!--this.txCount && options.broadcast !== false) {
this.broadcastWatches();
}
}
};
InMemoryCache.prototype.modify = function (options) {
if (hasOwn.call(options, "id") && !options.id) {
return false;
}
var store = options.optimistic
? this.optimisticData
: this.data;
try {
++this.txCount;
return store.modify(options.id || "ROOT_QUERY", options.fields);
}
finally {
if (!--this.txCount && options.broadcast !== false) {
this.broadcastWatches();
}
}
};
InMemoryCache.prototype.diff = function (options) {
return this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, rootId: options.id || "ROOT_QUERY", config: this.config }));
};
InMemoryCache.prototype.watch = function (watch) {
var _this = this;
if (!this.watches.size) {
recallCache(this);
}
this.watches.add(watch);
if (watch.immediate) {
this.maybeBroadcastWatch(watch);
}
return function () {
if (_this.watches.delete(watch) && !_this.watches.size) {
forgetCache(_this);
}
_this.maybeBroadcastWatch.forget(watch);
};
};
InMemoryCache.prototype.gc = function (options) {
canonicalStringify.reset();
var ids = this.optimisticData.gc();
if (options && !this.txCount) {
if (options.resetResultCache) {
this.resetResultCache(options.resetResultIdentities);
}
else if (options.resetResultIdentities) {
this.storeReader.resetCanon();
}
}
return ids;
};
InMemoryCache.prototype.retain = function (rootId, optimistic) {
return (optimistic ? this.optimisticData : this.data).retain(rootId);
};
InMemoryCache.prototype.release = function (rootId, optimistic) {
return (optimistic ? this.optimisticData : this.data).release(rootId);
};
InMemoryCache.prototype.identify = function (object) {
if (isReference(object))
return object.__ref;
try {
return this.policies.identify(object)[0];
}
catch (e) {
__DEV__ && invariant.warn(e);
}
};
InMemoryCache.prototype.evict = function (options) {
if (!options.id) {
if (hasOwn.call(options, "id")) {
return false;
}
options = __assign(__assign({}, options), { id: "ROOT_QUERY" });
}
try {
++this.txCount;
return this.optimisticData.evict(options, this.data);
}
finally {
if (!--this.txCount && options.broadcast !== false) {
this.broadcastWatches();
}
}
};
InMemoryCache.prototype.reset = function (options) {
var _this = this;
this.init();
canonicalStringify.reset();
if (options && options.discardWatches) {
this.watches.forEach(function (watch) { return _this.maybeBroadcastWatch.forget(watch); });
this.watches.clear();
forgetCache(this);
}
else {
this.broadcastWatches();
}
return Promise.resolve();
};
InMemoryCache.prototype.removeOptimistic = function (idToRemove) {
var newOptimisticData = this.optimisticData.removeLayer(idToRemove);
if (newOptimisticData !== this.optimisticData) {
this.optimisticData = newOptimisticData;
this.broadcastWatches();
}
};
InMemoryCache.prototype.batch = function (options) {
var _this = this;
var update = options.update, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, removeOptimistic = options.removeOptimistic, onWatchUpdated = options.onWatchUpdated;
var updateResult;
var perform = function (layer) {
var _a = _this, data = _a.data, optimisticData = _a.optimisticData;
++_this.txCount;
if (layer) {
_this.data = _this.optimisticData = layer;
}
try {
return updateResult = update(_this);
}
finally {
--_this.txCount;
_this.data = data;
_this.optimisticData = optimisticData;
}
};
var alreadyDirty = new Set();
if (onWatchUpdated && !this.txCount) {
this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch) {
alreadyDirty.add(watch);
return false;
} }));
}
if (typeof optimistic === 'string') {
this.optimisticData = this.optimisticData.addLayer(optimistic, perform);
}
else if (optimistic === false) {
perform(this.data);
}
else {
perform();
}
if (typeof removeOptimistic === "string") {
this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);
}
if (onWatchUpdated && alreadyDirty.size) {
this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch, diff) {
var result = onWatchUpdated.call(this, watch, diff);
if (result !== false) {
alreadyDirty.delete(watch);
}
return result;
} }));
if (alreadyDirty.size) {
alreadyDirty.forEach(function (watch) { return _this.maybeBroadcastWatch.dirty(watch); });
}
}
else {
this.broadcastWatches(options);
}
return updateResult;
};
InMemoryCache.prototype.performTransaction = function (update, optimisticId) {
return this.batch({
update: update,
optimistic: optimisticId || (optimisticId !== null),
});
};
InMemoryCache.prototype.transformDocument = function (document) {
if (this.addTypename) {
var result = this.typenameDocumentCache.get(document);
if (!result) {
result = addTypenameToDocument(document);
this.typenameDocumentCache.set(document, result);
this.typenameDocumentCache.set(result, result);
}
return result;
}
return document;
};
InMemoryCache.prototype.transformForLink = function (document) {
var fragments = this.config.fragments;
return fragments
? fragments.transform(document)
: document;
};
InMemoryCache.prototype.broadcastWatches = function (options) {
var _this = this;
if (!this.txCount) {
this.watches.forEach(function (c) { return _this.maybeBroadcastWatch(c, options); });
}
};
InMemoryCache.prototype.broadcastWatch = function (c, options) {
var lastDiff = c.lastDiff;
var diff = this.diff(c);
if (options) {
if (c.optimistic &&
typeof options.optimistic === "string") {
diff.fromOptimisticTransaction = true;
}
if (options.onWatchUpdated &&
options.onWatchUpdated.call(this, c, diff, lastDiff) === false) {
return;
}
}
if (!lastDiff || !equal(lastDiff.result, diff.result)) {
c.callback(c.lastDiff = diff, lastDiff);
}
};
return InMemoryCache;
}(cache_ApolloCache));
//# sourceMappingURL=inMemoryCache.js.map
// CONCATENATED MODULE: ./node_modules/graphql-tag/node_modules/tslib/tslib.es6.js
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var tslib_tslib_es6_extendStatics = function(d, b) {
tslib_tslib_es6_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 tslib_tslib_es6_extendStatics(d, b);
};
function tslib_tslib_es6_extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
tslib_tslib_es6_extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var tslib_tslib_es6_assign = function() {
tslib_tslib_es6_assign = Object.assign || function __assign(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 tslib_tslib_es6_assign.apply(this, arguments);
}
function tslib_tslib_es6_rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function tslib_tslib_es6_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function tslib_tslib_es6_param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function tslib_tslib_es6_esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
function tslib_tslib_es6_runInitializers(thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
function tslib_tslib_es6_propKey(x) {
return typeof x === "symbol" ? x : "".concat(x);
};
function tslib_tslib_es6_setFunctionName(f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
function tslib_tslib_es6_metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function node_modules_tslib_tslib_es6_awaiter(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());
});
}
function tslib_tslib_es6_generator(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 (g && (g = 0, op[0] && (_ = 0)), _) 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 tslib_tslib_es6_createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function tslib_tslib_es6_exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) tslib_tslib_es6_createBinding(o, m, p);
}
function tslib_tslib_es6_values(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.");
}
function tslib_tslib_es6_read(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;
}
/** @deprecated */
function tslib_tslib_es6_spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(tslib_tslib_es6_read(arguments[i]));
return ar;
}
/** @deprecated */
function tslib_tslib_es6_spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function tslib_tslib_es6_spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function tslib_tslib_es6_await(v) {
return this instanceof tslib_tslib_es6_await ? (this.v = v, this) : new tslib_tslib_es6_await(v);
}
function tslib_tslib_es6_asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof tslib_tslib_es6_await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function tslib_tslib_es6_asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: tslib_tslib_es6_await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}
function tslib_tslib_es6_asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof tslib_tslib_es6_values === "function" ? tslib_tslib_es6_values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function tslib_tslib_es6_makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var tslib_tslib_es6_setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function tslib_tslib_es6_importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) tslib_tslib_es6_createBinding(result, mod, k);
tslib_tslib_es6_setModuleDefault(result, mod);
return result;
}
function tslib_tslib_es6_importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function tslib_tslib_es6_classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function tslib_tslib_es6_classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
function tslib_tslib_es6_classPrivateFieldIn(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
}
function tslib_tslib_es6_addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object") throw new TypeError("Object expected.");
var dispose;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
}
var tslib_tslib_es6_SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function tslib_tslib_es6_disposeResources(env) {
function fail(e) {
env.error = env.hasError ? new tslib_tslib_es6_SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
catch (e) {
fail(e);
}
}
if (env.hasError) throw env.error;
}
return next();
}
/* harmony default export */ var node_modules_tslib_tslib_es6 = ({
__extends: tslib_tslib_es6_extends,
__assign: tslib_tslib_es6_assign,
__rest: tslib_tslib_es6_rest,
__decorate: tslib_tslib_es6_decorate,
__param: tslib_tslib_es6_param,
__metadata: tslib_tslib_es6_metadata,
__awaiter: node_modules_tslib_tslib_es6_awaiter,
__generator: tslib_tslib_es6_generator,
__createBinding: tslib_tslib_es6_createBinding,
__exportStar: tslib_tslib_es6_exportStar,
__values: tslib_tslib_es6_values,
__read: tslib_tslib_es6_read,
__spread: tslib_tslib_es6_spread,
__spreadArrays: tslib_tslib_es6_spreadArrays,
__spreadArray: tslib_tslib_es6_spreadArray,
__await: tslib_tslib_es6_await,
__asyncGenerator: tslib_tslib_es6_asyncGenerator,
__asyncDelegator: tslib_tslib_es6_asyncDelegator,
__asyncValues: tslib_tslib_es6_asyncValues,
__makeTemplateObject: tslib_tslib_es6_makeTemplateObject,
__importStar: tslib_tslib_es6_importStar,
__importDefault: tslib_tslib_es6_importDefault,
__classPrivateFieldGet: tslib_tslib_es6_classPrivateFieldGet,
__classPrivateFieldSet: tslib_tslib_es6_classPrivateFieldSet,
__classPrivateFieldIn: tslib_tslib_es6_classPrivateFieldIn,
__addDisposableResource: tslib_tslib_es6_addDisposableResource,
__disposeResources: tslib_tslib_es6_disposeResources,
});
// CONCATENATED MODULE: ./node_modules/graphql/jsutils/isObjectLike.mjs
function isObjectLike_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { isObjectLike_typeof = function _typeof(obj) { return typeof obj; }; } else { isObjectLike_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return isObjectLike_typeof(obj); }
/**
* Return true if `value` is object-like. A value is object-like if it's not
* `null` and has a `typeof` result of "object".
*/
function isObjectLike(value) {
return isObjectLike_typeof(value) == 'object' && value !== null;
}
// CONCATENATED MODULE: ./node_modules/graphql/language/location.mjs
/**
* Represents a location in a Source.
*/
/**
* Takes a Source and a UTF-8 character offset, and returns the corresponding
* line and column as a SourceLocation.
*/
function getLocation(source, position) {
var lineRegexp = /\r\n|[\n\r]/g;
var line = 1;
var column = position + 1;
var match;
while ((match = lineRegexp.exec(source.body)) && match.index < position) {
line += 1;
column = position + 1 - (match.index + match[0].length);
}
return {
line: line,
column: column
};
}
// CONCATENATED MODULE: ./node_modules/graphql/language/printLocation.mjs
/**
* Render a helpful description of the location in the GraphQL Source document.
*/
function printLocation(location) {
return printSourceLocation(location.source, getLocation(location.source, location.start));
}
/**
* Render a helpful description of the location in the GraphQL Source document.
*/
function printSourceLocation(source, sourceLocation) {
var firstLineColumnOffset = source.locationOffset.column - 1;
var body = whitespace(firstLineColumnOffset) + source.body;
var lineIndex = sourceLocation.line - 1;
var lineOffset = source.locationOffset.line - 1;
var lineNum = sourceLocation.line + lineOffset;
var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
var columnNum = sourceLocation.column + columnOffset;
var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");
var lines = body.split(/\r\n|[\n\r]/g);
var locationLine = lines[lineIndex]; // Special case for minified documents
if (locationLine.length > 120) {
var subLineIndex = Math.floor(columnNum / 80);
var subLineColumnNum = columnNum % 80;
var subLines = [];
for (var i = 0; i < locationLine.length; i += 80) {
subLines.push(locationLine.slice(i, i + 80));
}
return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {
return ['', subLine];
}), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));
}
return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]);
}
function printPrefixedLines(lines) {
var existingLines = lines.filter(function (_ref) {
var _ = _ref[0],
line = _ref[1];
return line !== undefined;
});
var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {
var prefix = _ref2[0];
return prefix.length;
}));
return existingLines.map(function (_ref3) {
var prefix = _ref3[0],
line = _ref3[1];
return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');
}).join('\n');
}
function whitespace(len) {
return Array(len + 1).join(' ');
}
function leftPad(len, str) {
return whitespace(len - str.length) + str;
}
// CONCATENATED MODULE: ./node_modules/graphql/error/GraphQLError.mjs
function GraphQLError_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { GraphQLError_typeof = function _typeof(obj) { return typeof obj; }; } else { GraphQLError_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return GraphQLError_typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function GraphQLError_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function GraphQLError_createClass(Constructor, protoProps, staticProps) { if (protoProps) GraphQLError_defineProperties(Constructor.prototype, protoProps); if (staticProps) GraphQLError_defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (GraphQLError_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
/**
* A GraphQLError describes an Error found during the parse, validate, or
* execute phases of performing a GraphQL operation. In addition to a message
* and stack trace, it also includes information about the locations in a
* GraphQL document and/or execution result that correspond to the Error.
*/
var GraphQLError_GraphQLError = /*#__PURE__*/function (_Error) {
_inherits(GraphQLError, _Error);
var _super = _createSuper(GraphQLError);
/**
* An array of { line, column } locations within the source GraphQL document
* which correspond to this error.
*
* Errors during validation often contain multiple locations, for example to
* point out two things with the same name. Errors during execution include a
* single location, the field which produced the error.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array describing the JSON-path into the execution response which
* corresponds to this error. Only included for errors during execution.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array of GraphQL AST Nodes corresponding to this error.
*/
/**
* The source GraphQL document for the first location of this error.
*
* Note that if this Error represents more than one node, the source may not
* represent nodes after the first node.
*/
/**
* An array of character offsets within the source GraphQL document
* which correspond to this error.
*/
/**
* The original error thrown from a field resolver during execution.
*/
/**
* Extension fields to add to the formatted error.
*/
function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {
var _nodeLocations, _nodeLocations2, _nodeLocations3;
var _this;
_classCallCheck(this, GraphQLError);
_this = _super.call(this, message);
_this.name = 'GraphQLError';
_this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes.
_this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined);
var nodeLocations = [];
for (var _i2 = 0, _ref3 = (_this$nodes = _this.nodes) !== null && _this$nodes !== void 0 ? _this$nodes : []; _i2 < _ref3.length; _i2++) {
var _this$nodes;
var _ref4 = _ref3[_i2];
var loc = _ref4.loc;
if (loc != null) {
nodeLocations.push(loc);
}
}
nodeLocations = undefinedIfEmpty(nodeLocations); // Compute locations in the source for the given nodes/positions.
_this.source = source !== null && source !== void 0 ? source : (_nodeLocations = nodeLocations) === null || _nodeLocations === void 0 ? void 0 : _nodeLocations[0].source;
_this.positions = positions !== null && positions !== void 0 ? positions : (_nodeLocations2 = nodeLocations) === null || _nodeLocations2 === void 0 ? void 0 : _nodeLocations2.map(function (loc) {
return loc.start;
});
_this.locations = positions && source ? positions.map(function (pos) {
return getLocation(source, pos);
}) : (_nodeLocations3 = nodeLocations) === null || _nodeLocations3 === void 0 ? void 0 : _nodeLocations3.map(function (loc) {
return getLocation(loc.source, loc.start);
});
_this.path = path !== null && path !== void 0 ? path : undefined;
var originalExtensions = originalError === null || originalError === void 0 ? void 0 : originalError.extensions;
if (extensions == null && isObjectLike(originalExtensions)) {
_this.extensions = _objectSpread({}, originalExtensions);
} else {
_this.extensions = extensions !== null && extensions !== void 0 ? extensions : {};
} // By being enumerable, JSON.stringify will include bellow properties in the resulting output.
// This ensures that the simplest possible GraphQL service adheres to the spec.
Object.defineProperties(_assertThisInitialized(_this), {
message: {
enumerable: true
},
locations: {
enumerable: _this.locations != null
},
path: {
enumerable: _this.path != null
},
extensions: {
enumerable: _this.extensions != null && Object.keys(_this.extensions).length > 0
},
name: {
enumerable: false
},
nodes: {
enumerable: false
},
source: {
enumerable: false
},
positions: {
enumerable: false
},
originalError: {
enumerable: false
}
}); // Include (non-enumerable) stack trace.
if (originalError !== null && originalError !== void 0 && originalError.stack) {
Object.defineProperty(_assertThisInitialized(_this), 'stack', {
value: originalError.stack,
writable: true,
configurable: true
});
return _possibleConstructorReturn(_this);
} // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);
} else {
Object.defineProperty(_assertThisInitialized(_this), 'stack', {
value: Error().stack,
writable: true,
configurable: true
});
}
return _this;
}
GraphQLError_createClass(GraphQLError, [{
key: "toString",
value: function toString() {
return printError(this);
} // FIXME: workaround to not break chai comparisons, should be remove in v16
// $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
}, {
key: SYMBOL_TO_STRING_TAG,
get: function get() {
return 'Object';
}
}]);
return GraphQLError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
function undefinedIfEmpty(array) {
return array === undefined || array.length === 0 ? undefined : array;
}
/**
* Prints a GraphQLError to a string, representing useful location information
* about the error's position in the source.
*/
function printError(error) {
var output = error.message;
if (error.nodes) {
for (var _i4 = 0, _error$nodes2 = error.nodes; _i4 < _error$nodes2.length; _i4++) {
var node = _error$nodes2[_i4];
if (node.loc) {
output += '\n\n' + printLocation(node.loc);
}
}
} else if (error.source && error.locations) {
for (var _i6 = 0, _error$locations2 = error.locations; _i6 < _error$locations2.length; _i6++) {
var location = _error$locations2[_i6];
output += '\n\n' + printSourceLocation(error.source, location);
}
}
return output;
}
// CONCATENATED MODULE: ./node_modules/graphql/error/syntaxError.mjs
/**
* Produces a GraphQLError representing a syntax error, containing useful
* descriptive information about the syntax error's position in the source.
*/
function syntaxError(source, position, description) {
return new GraphQLError_GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);
}
// CONCATENATED MODULE: ./node_modules/graphql/language/tokenKind.mjs
/**
* An exported enum describing the different kinds of tokens that the
* lexer emits.
*/
var TokenKind = Object.freeze({
SOF: '<SOF>',
EOF: '<EOF>',
BANG: '!',
DOLLAR: '$',
AMP: '&',
PAREN_L: '(',
PAREN_R: ')',
SPREAD: '...',
COLON: ':',
EQUALS: '=',
AT: '@',
BRACKET_L: '[',
BRACKET_R: ']',
BRACE_L: '{',
PIPE: '|',
BRACE_R: '}',
NAME: 'Name',
INT: 'Int',
FLOAT: 'Float',
STRING: 'String',
BLOCK_STRING: 'BlockString',
COMMENT: 'Comment'
});
/**
* The enum type representing the token kinds values.
*/
// CONCATENATED MODULE: ./node_modules/graphql/language/directiveLocation.mjs
/**
* The set of allowed directive location values.
*/
var DirectiveLocation = Object.freeze({
// Request Definitions
QUERY: 'QUERY',
MUTATION: 'MUTATION',
SUBSCRIPTION: 'SUBSCRIPTION',
FIELD: 'FIELD',
FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',
FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',
INLINE_FRAGMENT: 'INLINE_FRAGMENT',
VARIABLE_DEFINITION: 'VARIABLE_DEFINITION',
// Type System Definitions
SCHEMA: 'SCHEMA',
SCALAR: 'SCALAR',
OBJECT: 'OBJECT',
FIELD_DEFINITION: 'FIELD_DEFINITION',
ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',
INTERFACE: 'INTERFACE',
UNION: 'UNION',
ENUM: 'ENUM',
ENUM_VALUE: 'ENUM_VALUE',
INPUT_OBJECT: 'INPUT_OBJECT',
INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'
});
/**
* The enum type representing the directive location values.
*/
// CONCATENATED MODULE: ./node_modules/graphql/language/lexer.mjs
/**
* Given a Source object, creates a Lexer for that source.
* A Lexer is a stateful stream generator in that every time
* it is advanced, it returns the next token in the Source. Assuming the
* source lexes, the final Token emitted by the lexer will be of kind
* EOF, after which the lexer will repeatedly return the same EOF token
* whenever called.
*/
var lexer_Lexer = /*#__PURE__*/function () {
/**
* The previously focused non-ignored token.
*/
/**
* The currently focused non-ignored token.
*/
/**
* The (1-indexed) line containing the current token.
*/
/**
* The character offset at which the current line begins.
*/
function Lexer(source) {
var startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0, null);
this.source = source;
this.lastToken = startOfFileToken;
this.token = startOfFileToken;
this.line = 1;
this.lineStart = 0;
}
/**
* Advances the token stream to the next non-ignored token.
*/
var _proto = Lexer.prototype;
_proto.advance = function advance() {
this.lastToken = this.token;
var token = this.token = this.lookahead();
return token;
}
/**
* Looks ahead and returns the next non-ignored token, but does not change
* the state of Lexer.
*/
;
_proto.lookahead = function lookahead() {
var token = this.token;
if (token.kind !== TokenKind.EOF) {
do {
var _token$next;
// Note: next is only mutable during parsing, so we cast to allow this.
token = (_token$next = token.next) !== null && _token$next !== void 0 ? _token$next : token.next = readToken(this, token);
} while (token.kind === TokenKind.COMMENT);
}
return token;
};
return Lexer;
}();
/**
* @internal
*/
function isPunctuatorTokenKind(kind) {
return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;
}
function printCharCode(code) {
return (// NaN/undefined represents access beyond the end of the file.
isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.
code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.
"\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"")
);
}
/**
* Gets the next token from the source starting at the given position.
*
* This skips over whitespace until it finds the next lexable token, then lexes
* punctuators immediately or calls the appropriate helper function for more
* complicated tokens.
*/
function readToken(lexer, prev) {
var source = lexer.source;
var body = source.body;
var bodyLength = body.length;
var pos = prev.end;
while (pos < bodyLength) {
var code = body.charCodeAt(pos);
var _line = lexer.line;
var _col = 1 + pos - lexer.lineStart; // SourceCharacter
switch (code) {
case 0xfeff: // <BOM>
case 9: // \t
case 32: // <space>
case 44:
// ,
++pos;
continue;
case 10:
// \n
++pos;
++lexer.line;
lexer.lineStart = pos;
continue;
case 13:
// \r
if (body.charCodeAt(pos + 1) === 10) {
pos += 2;
} else {
++pos;
}
++lexer.line;
lexer.lineStart = pos;
continue;
case 33:
// !
return new Token(TokenKind.BANG, pos, pos + 1, _line, _col, prev);
case 35:
// #
return readComment(source, pos, _line, _col, prev);
case 36:
// $
return new Token(TokenKind.DOLLAR, pos, pos + 1, _line, _col, prev);
case 38:
// &
return new Token(TokenKind.AMP, pos, pos + 1, _line, _col, prev);
case 40:
// (
return new Token(TokenKind.PAREN_L, pos, pos + 1, _line, _col, prev);
case 41:
// )
return new Token(TokenKind.PAREN_R, pos, pos + 1, _line, _col, prev);
case 46:
// .
if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) {
return new Token(TokenKind.SPREAD, pos, pos + 3, _line, _col, prev);
}
break;
case 58:
// :
return new Token(TokenKind.COLON, pos, pos + 1, _line, _col, prev);
case 61:
// =
return new Token(TokenKind.EQUALS, pos, pos + 1, _line, _col, prev);
case 64:
// @
return new Token(TokenKind.AT, pos, pos + 1, _line, _col, prev);
case 91:
// [
return new Token(TokenKind.BRACKET_L, pos, pos + 1, _line, _col, prev);
case 93:
// ]
return new Token(TokenKind.BRACKET_R, pos, pos + 1, _line, _col, prev);
case 123:
// {
return new Token(TokenKind.BRACE_L, pos, pos + 1, _line, _col, prev);
case 124:
// |
return new Token(TokenKind.PIPE, pos, pos + 1, _line, _col, prev);
case 125:
// }
return new Token(TokenKind.BRACE_R, pos, pos + 1, _line, _col, prev);
case 34:
// "
if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) {
return readBlockString(source, pos, _line, _col, prev, lexer);
}
return readString(source, pos, _line, _col, prev);
case 45: // -
case 48: // 0
case 49: // 1
case 50: // 2
case 51: // 3
case 52: // 4
case 53: // 5
case 54: // 6
case 55: // 7
case 56: // 8
case 57:
// 9
return readNumber(source, pos, code, _line, _col, prev);
case 65: // A
case 66: // B
case 67: // C
case 68: // D
case 69: // E
case 70: // F
case 71: // G
case 72: // H
case 73: // I
case 74: // J
case 75: // K
case 76: // L
case 77: // M
case 78: // N
case 79: // O
case 80: // P
case 81: // Q
case 82: // R
case 83: // S
case 84: // T
case 85: // U
case 86: // V
case 87: // W
case 88: // X
case 89: // Y
case 90: // Z
case 95: // _
case 97: // a
case 98: // b
case 99: // c
case 100: // d
case 101: // e
case 102: // f
case 103: // g
case 104: // h
case 105: // i
case 106: // j
case 107: // k
case 108: // l
case 109: // m
case 110: // n
case 111: // o
case 112: // p
case 113: // q
case 114: // r
case 115: // s
case 116: // t
case 117: // u
case 118: // v
case 119: // w
case 120: // x
case 121: // y
case 122:
// z
return readName(source, pos, _line, _col, prev);
}
throw syntaxError(source, pos, unexpectedCharacterMessage(code));
}
var line = lexer.line;
var col = 1 + pos - lexer.lineStart;
return new Token(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);
}
/**
* Report a message that an unexpected character was encountered.
*/
function unexpectedCharacterMessage(code) {
if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
return "Cannot contain the invalid character ".concat(printCharCode(code), ".");
}
if (code === 39) {
// '
return 'Unexpected single quote character (\'), did you mean to use a double quote (")?';
}
return "Cannot parse the unexpected character ".concat(printCharCode(code), ".");
}
/**
* Reads a comment token from the source file.
*
* #[\u0009\u0020-\uFFFF]*
*/
function readComment(source, start, line, col, prev) {
var body = source.body;
var code;
var position = start;
do {
code = body.charCodeAt(++position);
} while (!isNaN(code) && ( // SourceCharacter but not LineTerminator
code > 0x001f || code === 0x0009));
return new Token(TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position));
}
/**
* Reads a number token from the source file, either a float
* or an int depending on whether a decimal point appears.
*
* Int: -?(0|[1-9][0-9]*)
* Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?
*/
function readNumber(source, start, firstCode, line, col, prev) {
var body = source.body;
var code = firstCode;
var position = start;
var isFloat = false;
if (code === 45) {
// -
code = body.charCodeAt(++position);
}
if (code === 48) {
// 0
code = body.charCodeAt(++position);
if (code >= 48 && code <= 57) {
throw syntaxError(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), "."));
}
} else {
position = readDigits(source, position, code);
code = body.charCodeAt(position);
}
if (code === 46) {
// .
isFloat = true;
code = body.charCodeAt(++position);
position = readDigits(source, position, code);
code = body.charCodeAt(position);
}
if (code === 69 || code === 101) {
// E e
isFloat = true;
code = body.charCodeAt(++position);
if (code === 43 || code === 45) {
// + -
code = body.charCodeAt(++position);
}
position = readDigits(source, position, code);
code = body.charCodeAt(position);
} // Numbers cannot be followed by . or NameStart
if (code === 46 || isNameStart(code)) {
throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));
}
return new Token(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, body.slice(start, position));
}
/**
* Returns the new position in the source after reading digits.
*/
function readDigits(source, start, firstCode) {
var body = source.body;
var position = start;
var code = firstCode;
if (code >= 48 && code <= 57) {
// 0 - 9
do {
code = body.charCodeAt(++position);
} while (code >= 48 && code <= 57); // 0 - 9
return position;
}
throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));
}
/**
* Reads a string token from the source file.
*
* "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
*/
function readString(source, start, line, col, prev) {
var body = source.body;
var position = start + 1;
var chunkStart = position;
var code = 0;
var value = '';
while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator
code !== 0x000a && code !== 0x000d) {
// Closing Quote (")
if (code === 34) {
value += body.slice(chunkStart, position);
return new Token(TokenKind.STRING, start, position + 1, line, col, prev, value);
} // SourceCharacter
if (code < 0x0020 && code !== 0x0009) {
throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));
}
++position;
if (code === 92) {
// \
value += body.slice(chunkStart, position - 1);
code = body.charCodeAt(position);
switch (code) {
case 34:
value += '"';
break;
case 47:
value += '/';
break;
case 92:
value += '\\';
break;
case 98:
value += '\b';
break;
case 102:
value += '\f';
break;
case 110:
value += '\n';
break;
case 114:
value += '\r';
break;
case 116:
value += '\t';
break;
case 117:
{
// uXXXX
var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4));
if (charCode < 0) {
var invalidSequence = body.slice(position + 1, position + 5);
throw syntaxError(source, position, "Invalid character escape sequence: \\u".concat(invalidSequence, "."));
}
value += String.fromCharCode(charCode);
position += 4;
break;
}
default:
throw syntaxError(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), "."));
}
++position;
chunkStart = position;
}
}
throw syntaxError(source, position, 'Unterminated string.');
}
/**
* Reads a block string token from the source file.
*
* """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""
*/
function readBlockString(source, start, line, col, prev, lexer) {
var body = source.body;
var position = start + 3;
var chunkStart = position;
var code = 0;
var rawValue = '';
while (position < body.length && !isNaN(code = body.charCodeAt(position))) {
// Closing Triple-Quote (""")
if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
rawValue += body.slice(chunkStart, position);
return new Token(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, dedentBlockStringValue(rawValue));
} // SourceCharacter
if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));
}
if (code === 10) {
// new line
++position;
++lexer.line;
lexer.lineStart = position;
} else if (code === 13) {
// carriage return
if (body.charCodeAt(position + 1) === 10) {
position += 2;
} else {
++position;
}
++lexer.line;
lexer.lineStart = position;
} else if ( // Escape Triple-Quote (\""")
code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {
rawValue += body.slice(chunkStart, position) + '"""';
position += 4;
chunkStart = position;
} else {
++position;
}
}
throw syntaxError(source, position, 'Unterminated string.');
}
/**
* Converts four hexadecimal chars to the integer that the
* string represents. For example, uniCharCode('0','0','0','f')
* will return 15, and uniCharCode('0','0','f','f') returns 255.
*
* Returns a negative number on error, if a char was invalid.
*
* This is implemented by noting that char2hex() returns -1 on error,
* which means the result of ORing the char2hex() will also be negative.
*/
function uniCharCode(a, b, c, d) {
return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);
}
/**
* Converts a hex character to its integer value.
* '0' becomes 0, '9' becomes 9
* 'A' becomes 10, 'F' becomes 15
* 'a' becomes 10, 'f' becomes 15
*
* Returns -1 on error.
*/
function char2hex(a) {
return a >= 48 && a <= 57 ? a - 48 // 0-9
: a >= 65 && a <= 70 ? a - 55 // A-F
: a >= 97 && a <= 102 ? a - 87 // a-f
: -1;
}
/**
* Reads an alphanumeric + underscore name from the source.
*
* [_A-Za-z][_0-9A-Za-z]*
*/
function readName(source, start, line, col, prev) {
var body = source.body;
var bodyLength = body.length;
var position = start + 1;
var code = 0;
while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _
code >= 48 && code <= 57 || // 0-9
code >= 65 && code <= 90 || // A-Z
code >= 97 && code <= 122) // a-z
) {
++position;
}
return new Token(TokenKind.NAME, start, position, line, col, prev, body.slice(start, position));
} // _ A-Z a-z
function isNameStart(code) {
return code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
}
// CONCATENATED MODULE: ./node_modules/graphql/language/parser.mjs
/**
* Configuration options to control parser behavior
*/
/**
* Given a GraphQL source, parses it into a Document.
* Throws GraphQLError if a syntax error is encountered.
*/
function parser_parse(source, options) {
var parser = new parser_Parser(source, options);
return parser.parseDocument();
}
/**
* Given a string containing a GraphQL value (ex. `[42]`), parse the AST for
* that value.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Values directly and
* in isolation of complete GraphQL documents.
*
* Consider providing the results to the utility function: valueFromAST().
*/
function parseValue(source, options) {
var parser = new parser_Parser(source, options);
parser.expectToken(TokenKind.SOF);
var value = parser.parseValueLiteral(false);
parser.expectToken(TokenKind.EOF);
return value;
}
/**
* Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for
* that type.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Types directly and
* in isolation of complete GraphQL documents.
*
* Consider providing the results to the utility function: typeFromAST().
*/
function parseType(source, options) {
var parser = new parser_Parser(source, options);
parser.expectToken(TokenKind.SOF);
var type = parser.parseTypeReference();
parser.expectToken(TokenKind.EOF);
return type;
}
/**
* This class is exported only to assist people in implementing their own parsers
* without duplicating too much code and should be used only as last resort for cases
* such as experimental syntax or if certain features could not be contributed upstream.
*
* It is still part of the internal API and is versioned, so any changes to it are never
* considered breaking changes. If you still need to support multiple versions of the
* library, please use the `versionInfo` variable for version detection.
*
* @internal
*/
var parser_Parser = /*#__PURE__*/function () {
function Parser(source, options) {
var sourceObj = isSource(source) ? source : new source_Source(source);
this._lexer = new lexer_Lexer(sourceObj);
this._options = options;
}
/**
* Converts a name lex token into a name parse node.
*/
var _proto = Parser.prototype;
_proto.parseName = function parseName() {
var token = this.expectToken(TokenKind.NAME);
return {
kind: Kind.NAME,
value: token.value,
loc: this.loc(token)
};
} // Implements the parsing rules in the Document section.
/**
* Document : Definition+
*/
;
_proto.parseDocument = function parseDocument() {
var start = this._lexer.token;
return {
kind: Kind.DOCUMENT,
definitions: this.many(TokenKind.SOF, this.parseDefinition, TokenKind.EOF),
loc: this.loc(start)
};
}
/**
* Definition :
* - ExecutableDefinition
* - TypeSystemDefinition
* - TypeSystemExtension
*
* ExecutableDefinition :
* - OperationDefinition
* - FragmentDefinition
*/
;
_proto.parseDefinition = function parseDefinition() {
if (this.peek(TokenKind.NAME)) {
switch (this._lexer.token.value) {
case 'query':
case 'mutation':
case 'subscription':
return this.parseOperationDefinition();
case 'fragment':
return this.parseFragmentDefinition();
case 'schema':
case 'scalar':
case 'type':
case 'interface':
case 'union':
case 'enum':
case 'input':
case 'directive':
return this.parseTypeSystemDefinition();
case 'extend':
return this.parseTypeSystemExtension();
}
} else if (this.peek(TokenKind.BRACE_L)) {
return this.parseOperationDefinition();
} else if (this.peekDescription()) {
return this.parseTypeSystemDefinition();
}
throw this.unexpected();
} // Implements the parsing rules in the Operations section.
/**
* OperationDefinition :
* - SelectionSet
* - OperationType Name? VariableDefinitions? Directives? SelectionSet
*/
;
_proto.parseOperationDefinition = function parseOperationDefinition() {
var start = this._lexer.token;
if (this.peek(TokenKind.BRACE_L)) {
return {
kind: Kind.OPERATION_DEFINITION,
operation: 'query',
name: undefined,
variableDefinitions: [],
directives: [],
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
var operation = this.parseOperationType();
var name;
if (this.peek(TokenKind.NAME)) {
name = this.parseName();
}
return {
kind: Kind.OPERATION_DEFINITION,
operation: operation,
name: name,
variableDefinitions: this.parseVariableDefinitions(),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
/**
* OperationType : one of query mutation subscription
*/
;
_proto.parseOperationType = function parseOperationType() {
var operationToken = this.expectToken(TokenKind.NAME);
switch (operationToken.value) {
case 'query':
return 'query';
case 'mutation':
return 'mutation';
case 'subscription':
return 'subscription';
}
throw this.unexpected(operationToken);
}
/**
* VariableDefinitions : ( VariableDefinition+ )
*/
;
_proto.parseVariableDefinitions = function parseVariableDefinitions() {
return this.optionalMany(TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R);
}
/**
* VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
*/
;
_proto.parseVariableDefinition = function parseVariableDefinition() {
var start = this._lexer.token;
return {
kind: Kind.VARIABLE_DEFINITION,
variable: this.parseVariable(),
type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),
defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined,
directives: this.parseDirectives(true),
loc: this.loc(start)
};
}
/**
* Variable : $ Name
*/
;
_proto.parseVariable = function parseVariable() {
var start = this._lexer.token;
this.expectToken(TokenKind.DOLLAR);
return {
kind: Kind.VARIABLE,
name: this.parseName(),
loc: this.loc(start)
};
}
/**
* SelectionSet : { Selection+ }
*/
;
_proto.parseSelectionSet = function parseSelectionSet() {
var start = this._lexer.token;
return {
kind: Kind.SELECTION_SET,
selections: this.many(TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R),
loc: this.loc(start)
};
}
/**
* Selection :
* - Field
* - FragmentSpread
* - InlineFragment
*/
;
_proto.parseSelection = function parseSelection() {
return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();
}
/**
* Field : Alias? Name Arguments? Directives? SelectionSet?
*
* Alias : Name :
*/
;
_proto.parseField = function parseField() {
var start = this._lexer.token;
var nameOrAlias = this.parseName();
var alias;
var name;
if (this.expectOptionalToken(TokenKind.COLON)) {
alias = nameOrAlias;
name = this.parseName();
} else {
name = nameOrAlias;
}
return {
kind: Kind.FIELD,
alias: alias,
name: name,
arguments: this.parseArguments(false),
directives: this.parseDirectives(false),
selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined,
loc: this.loc(start)
};
}
/**
* Arguments[Const] : ( Argument[?Const]+ )
*/
;
_proto.parseArguments = function parseArguments(isConst) {
var item = isConst ? this.parseConstArgument : this.parseArgument;
return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
}
/**
* Argument[Const] : Name : Value[?Const]
*/
;
_proto.parseArgument = function parseArgument() {
var start = this._lexer.token;
var name = this.parseName();
this.expectToken(TokenKind.COLON);
return {
kind: Kind.ARGUMENT,
name: name,
value: this.parseValueLiteral(false),
loc: this.loc(start)
};
};
_proto.parseConstArgument = function parseConstArgument() {
var start = this._lexer.token;
return {
kind: Kind.ARGUMENT,
name: this.parseName(),
value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)),
loc: this.loc(start)
};
} // Implements the parsing rules in the Fragments section.
/**
* Corresponds to both FragmentSpread and InlineFragment in the spec.
*
* FragmentSpread : ... FragmentName Directives?
*
* InlineFragment : ... TypeCondition? Directives? SelectionSet
*/
;
_proto.parseFragment = function parseFragment() {
var start = this._lexer.token;
this.expectToken(TokenKind.SPREAD);
var hasTypeCondition = this.expectOptionalKeyword('on');
if (!hasTypeCondition && this.peek(TokenKind.NAME)) {
return {
kind: Kind.FRAGMENT_SPREAD,
name: this.parseFragmentName(),
directives: this.parseDirectives(false),
loc: this.loc(start)
};
}
return {
kind: Kind.INLINE_FRAGMENT,
typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
/**
* FragmentDefinition :
* - fragment FragmentName on TypeCondition Directives? SelectionSet
*
* TypeCondition : NamedType
*/
;
_proto.parseFragmentDefinition = function parseFragmentDefinition() {
var _this$_options;
var start = this._lexer.token;
this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes
// the grammar of FragmentDefinition:
// - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet
if (((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.experimentalFragmentVariables) === true) {
return {
kind: Kind.FRAGMENT_DEFINITION,
name: this.parseFragmentName(),
variableDefinitions: this.parseVariableDefinitions(),
typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
return {
kind: Kind.FRAGMENT_DEFINITION,
name: this.parseFragmentName(),
typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
/**
* FragmentName : Name but not `on`
*/
;
_proto.parseFragmentName = function parseFragmentName() {
if (this._lexer.token.value === 'on') {
throw this.unexpected();
}
return this.parseName();
} // Implements the parsing rules in the Values section.
/**
* Value[Const] :
* - [~Const] Variable
* - IntValue
* - FloatValue
* - StringValue
* - BooleanValue
* - NullValue
* - EnumValue
* - ListValue[?Const]
* - ObjectValue[?Const]
*
* BooleanValue : one of `true` `false`
*
* NullValue : `null`
*
* EnumValue : Name but not `true`, `false` or `null`
*/
;
_proto.parseValueLiteral = function parseValueLiteral(isConst) {
var token = this._lexer.token;
switch (token.kind) {
case TokenKind.BRACKET_L:
return this.parseList(isConst);
case TokenKind.BRACE_L:
return this.parseObject(isConst);
case TokenKind.INT:
this._lexer.advance();
return {
kind: Kind.INT,
value: token.value,
loc: this.loc(token)
};
case TokenKind.FLOAT:
this._lexer.advance();
return {
kind: Kind.FLOAT,
value: token.value,
loc: this.loc(token)
};
case TokenKind.STRING:
case TokenKind.BLOCK_STRING:
return this.parseStringLiteral();
case TokenKind.NAME:
this._lexer.advance();
switch (token.value) {
case 'true':
return {
kind: Kind.BOOLEAN,
value: true,
loc: this.loc(token)
};
case 'false':
return {
kind: Kind.BOOLEAN,
value: false,
loc: this.loc(token)
};
case 'null':
return {
kind: Kind.NULL,
loc: this.loc(token)
};
default:
return {
kind: Kind.ENUM,
value: token.value,
loc: this.loc(token)
};
}
case TokenKind.DOLLAR:
if (!isConst) {
return this.parseVariable();
}
break;
}
throw this.unexpected();
};
_proto.parseStringLiteral = function parseStringLiteral() {
var token = this._lexer.token;
this._lexer.advance();
return {
kind: Kind.STRING,
value: token.value,
block: token.kind === TokenKind.BLOCK_STRING,
loc: this.loc(token)
};
}
/**
* ListValue[Const] :
* - [ ]
* - [ Value[?Const]+ ]
*/
;
_proto.parseList = function parseList(isConst) {
var _this = this;
var start = this._lexer.token;
var item = function item() {
return _this.parseValueLiteral(isConst);
};
return {
kind: Kind.LIST,
values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),
loc: this.loc(start)
};
}
/**
* ObjectValue[Const] :
* - { }
* - { ObjectField[?Const]+ }
*/
;
_proto.parseObject = function parseObject(isConst) {
var _this2 = this;
var start = this._lexer.token;
var item = function item() {
return _this2.parseObjectField(isConst);
};
return {
kind: Kind.OBJECT,
fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),
loc: this.loc(start)
};
}
/**
* ObjectField[Const] : Name : Value[?Const]
*/
;
_proto.parseObjectField = function parseObjectField(isConst) {
var start = this._lexer.token;
var name = this.parseName();
this.expectToken(TokenKind.COLON);
return {
kind: Kind.OBJECT_FIELD,
name: name,
value: this.parseValueLiteral(isConst),
loc: this.loc(start)
};
} // Implements the parsing rules in the Directives section.
/**
* Directives[Const] : Directive[?Const]+
*/
;
_proto.parseDirectives = function parseDirectives(isConst) {
var directives = [];
while (this.peek(TokenKind.AT)) {
directives.push(this.parseDirective(isConst));
}
return directives;
}
/**
* Directive[Const] : @ Name Arguments[?Const]?
*/
;
_proto.parseDirective = function parseDirective(isConst) {
var start = this._lexer.token;
this.expectToken(TokenKind.AT);
return {
kind: Kind.DIRECTIVE,
name: this.parseName(),
arguments: this.parseArguments(isConst),
loc: this.loc(start)
};
} // Implements the parsing rules in the Types section.
/**
* Type :
* - NamedType
* - ListType
* - NonNullType
*/
;
_proto.parseTypeReference = function parseTypeReference() {
var start = this._lexer.token;
var type;
if (this.expectOptionalToken(TokenKind.BRACKET_L)) {
type = this.parseTypeReference();
this.expectToken(TokenKind.BRACKET_R);
type = {
kind: Kind.LIST_TYPE,
type: type,
loc: this.loc(start)
};
} else {
type = this.parseNamedType();
}
if (this.expectOptionalToken(TokenKind.BANG)) {
return {
kind: Kind.NON_NULL_TYPE,
type: type,
loc: this.loc(start)
};
}
return type;
}
/**
* NamedType : Name
*/
;
_proto.parseNamedType = function parseNamedType() {
var start = this._lexer.token;
return {
kind: Kind.NAMED_TYPE,
name: this.parseName(),
loc: this.loc(start)
};
} // Implements the parsing rules in the Type Definition section.
/**
* TypeSystemDefinition :
* - SchemaDefinition
* - TypeDefinition
* - DirectiveDefinition
*
* TypeDefinition :
* - ScalarTypeDefinition
* - ObjectTypeDefinition
* - InterfaceTypeDefinition
* - UnionTypeDefinition
* - EnumTypeDefinition
* - InputObjectTypeDefinition
*/
;
_proto.parseTypeSystemDefinition = function parseTypeSystemDefinition() {
// Many definitions begin with a description and require a lookahead.
var keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token;
if (keywordToken.kind === TokenKind.NAME) {
switch (keywordToken.value) {
case 'schema':
return this.parseSchemaDefinition();
case 'scalar':
return this.parseScalarTypeDefinition();
case 'type':
return this.parseObjectTypeDefinition();
case 'interface':
return this.parseInterfaceTypeDefinition();
case 'union':
return this.parseUnionTypeDefinition();
case 'enum':
return this.parseEnumTypeDefinition();
case 'input':
return this.parseInputObjectTypeDefinition();
case 'directive':
return this.parseDirectiveDefinition();
}
}
throw this.unexpected(keywordToken);
};
_proto.peekDescription = function peekDescription() {
return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);
}
/**
* Description : StringValue
*/
;
_proto.parseDescription = function parseDescription() {
if (this.peekDescription()) {
return this.parseStringLiteral();
}
}
/**
* SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
*/
;
_proto.parseSchemaDefinition = function parseSchemaDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('schema');
var directives = this.parseDirectives(true);
var operationTypes = this.many(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);
return {
kind: Kind.SCHEMA_DEFINITION,
description: description,
directives: directives,
operationTypes: operationTypes,
loc: this.loc(start)
};
}
/**
* OperationTypeDefinition : OperationType : NamedType
*/
;
_proto.parseOperationTypeDefinition = function parseOperationTypeDefinition() {
var start = this._lexer.token;
var operation = this.parseOperationType();
this.expectToken(TokenKind.COLON);
var type = this.parseNamedType();
return {
kind: Kind.OPERATION_TYPE_DEFINITION,
operation: operation,
type: type,
loc: this.loc(start)
};
}
/**
* ScalarTypeDefinition : Description? scalar Name Directives[Const]?
*/
;
_proto.parseScalarTypeDefinition = function parseScalarTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('scalar');
var name = this.parseName();
var directives = this.parseDirectives(true);
return {
kind: Kind.SCALAR_TYPE_DEFINITION,
description: description,
name: name,
directives: directives,
loc: this.loc(start)
};
}
/**
* ObjectTypeDefinition :
* Description?
* type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
*/
;
_proto.parseObjectTypeDefinition = function parseObjectTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('type');
var name = this.parseName();
var interfaces = this.parseImplementsInterfaces();
var directives = this.parseDirectives(true);
var fields = this.parseFieldsDefinition();
return {
kind: Kind.OBJECT_TYPE_DEFINITION,
description: description,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* ImplementsInterfaces :
* - implements `&`? NamedType
* - ImplementsInterfaces & NamedType
*/
;
_proto.parseImplementsInterfaces = function parseImplementsInterfaces() {
var _this$_options2;
if (!this.expectOptionalKeyword('implements')) {
return [];
}
if (((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.allowLegacySDLImplementsInterfaces) === true) {
var types = []; // Optional leading ampersand
this.expectOptionalToken(TokenKind.AMP);
do {
types.push(this.parseNamedType());
} while (this.expectOptionalToken(TokenKind.AMP) || this.peek(TokenKind.NAME));
return types;
}
return this.delimitedMany(TokenKind.AMP, this.parseNamedType);
}
/**
* FieldsDefinition : { FieldDefinition+ }
*/
;
_proto.parseFieldsDefinition = function parseFieldsDefinition() {
var _this$_options3;
// Legacy support for the SDL?
if (((_this$_options3 = this._options) === null || _this$_options3 === void 0 ? void 0 : _this$_options3.allowLegacySDLEmptyFields) === true && this.peek(TokenKind.BRACE_L) && this._lexer.lookahead().kind === TokenKind.BRACE_R) {
this._lexer.advance();
this._lexer.advance();
return [];
}
return this.optionalMany(TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R);
}
/**
* FieldDefinition :
* - Description? Name ArgumentsDefinition? : Type Directives[Const]?
*/
;
_proto.parseFieldDefinition = function parseFieldDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
var name = this.parseName();
var args = this.parseArgumentDefs();
this.expectToken(TokenKind.COLON);
var type = this.parseTypeReference();
var directives = this.parseDirectives(true);
return {
kind: Kind.FIELD_DEFINITION,
description: description,
name: name,
arguments: args,
type: type,
directives: directives,
loc: this.loc(start)
};
}
/**
* ArgumentsDefinition : ( InputValueDefinition+ )
*/
;
_proto.parseArgumentDefs = function parseArgumentDefs() {
return this.optionalMany(TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R);
}
/**
* InputValueDefinition :
* - Description? Name : Type DefaultValue? Directives[Const]?
*/
;
_proto.parseInputValueDef = function parseInputValueDef() {
var start = this._lexer.token;
var description = this.parseDescription();
var name = this.parseName();
this.expectToken(TokenKind.COLON);
var type = this.parseTypeReference();
var defaultValue;
if (this.expectOptionalToken(TokenKind.EQUALS)) {
defaultValue = this.parseValueLiteral(true);
}
var directives = this.parseDirectives(true);
return {
kind: Kind.INPUT_VALUE_DEFINITION,
description: description,
name: name,
type: type,
defaultValue: defaultValue,
directives: directives,
loc: this.loc(start)
};
}
/**
* InterfaceTypeDefinition :
* - Description? interface Name Directives[Const]? FieldsDefinition?
*/
;
_proto.parseInterfaceTypeDefinition = function parseInterfaceTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('interface');
var name = this.parseName();
var interfaces = this.parseImplementsInterfaces();
var directives = this.parseDirectives(true);
var fields = this.parseFieldsDefinition();
return {
kind: Kind.INTERFACE_TYPE_DEFINITION,
description: description,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* UnionTypeDefinition :
* - Description? union Name Directives[Const]? UnionMemberTypes?
*/
;
_proto.parseUnionTypeDefinition = function parseUnionTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('union');
var name = this.parseName();
var directives = this.parseDirectives(true);
var types = this.parseUnionMemberTypes();
return {
kind: Kind.UNION_TYPE_DEFINITION,
description: description,
name: name,
directives: directives,
types: types,
loc: this.loc(start)
};
}
/**
* UnionMemberTypes :
* - = `|`? NamedType
* - UnionMemberTypes | NamedType
*/
;
_proto.parseUnionMemberTypes = function parseUnionMemberTypes() {
return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : [];
}
/**
* EnumTypeDefinition :
* - Description? enum Name Directives[Const]? EnumValuesDefinition?
*/
;
_proto.parseEnumTypeDefinition = function parseEnumTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('enum');
var name = this.parseName();
var directives = this.parseDirectives(true);
var values = this.parseEnumValuesDefinition();
return {
kind: Kind.ENUM_TYPE_DEFINITION,
description: description,
name: name,
directives: directives,
values: values,
loc: this.loc(start)
};
}
/**
* EnumValuesDefinition : { EnumValueDefinition+ }
*/
;
_proto.parseEnumValuesDefinition = function parseEnumValuesDefinition() {
return this.optionalMany(TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R);
}
/**
* EnumValueDefinition : Description? EnumValue Directives[Const]?
*
* EnumValue : Name
*/
;
_proto.parseEnumValueDefinition = function parseEnumValueDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
var name = this.parseName();
var directives = this.parseDirectives(true);
return {
kind: Kind.ENUM_VALUE_DEFINITION,
description: description,
name: name,
directives: directives,
loc: this.loc(start)
};
}
/**
* InputObjectTypeDefinition :
* - Description? input Name Directives[Const]? InputFieldsDefinition?
*/
;
_proto.parseInputObjectTypeDefinition = function parseInputObjectTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('input');
var name = this.parseName();
var directives = this.parseDirectives(true);
var fields = this.parseInputFieldsDefinition();
return {
kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
description: description,
name: name,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* InputFieldsDefinition : { InputValueDefinition+ }
*/
;
_proto.parseInputFieldsDefinition = function parseInputFieldsDefinition() {
return this.optionalMany(TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R);
}
/**
* TypeSystemExtension :
* - SchemaExtension
* - TypeExtension
*
* TypeExtension :
* - ScalarTypeExtension
* - ObjectTypeExtension
* - InterfaceTypeExtension
* - UnionTypeExtension
* - EnumTypeExtension
* - InputObjectTypeDefinition
*/
;
_proto.parseTypeSystemExtension = function parseTypeSystemExtension() {
var keywordToken = this._lexer.lookahead();
if (keywordToken.kind === TokenKind.NAME) {
switch (keywordToken.value) {
case 'schema':
return this.parseSchemaExtension();
case 'scalar':
return this.parseScalarTypeExtension();
case 'type':
return this.parseObjectTypeExtension();
case 'interface':
return this.parseInterfaceTypeExtension();
case 'union':
return this.parseUnionTypeExtension();
case 'enum':
return this.parseEnumTypeExtension();
case 'input':
return this.parseInputObjectTypeExtension();
}
}
throw this.unexpected(keywordToken);
}
/**
* SchemaExtension :
* - extend schema Directives[Const]? { OperationTypeDefinition+ }
* - extend schema Directives[Const]
*/
;
_proto.parseSchemaExtension = function parseSchemaExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('schema');
var directives = this.parseDirectives(true);
var operationTypes = this.optionalMany(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);
if (directives.length === 0 && operationTypes.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.SCHEMA_EXTENSION,
directives: directives,
operationTypes: operationTypes,
loc: this.loc(start)
};
}
/**
* ScalarTypeExtension :
* - extend scalar Name Directives[Const]
*/
;
_proto.parseScalarTypeExtension = function parseScalarTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('scalar');
var name = this.parseName();
var directives = this.parseDirectives(true);
if (directives.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.SCALAR_TYPE_EXTENSION,
name: name,
directives: directives,
loc: this.loc(start)
};
}
/**
* ObjectTypeExtension :
* - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
* - extend type Name ImplementsInterfaces? Directives[Const]
* - extend type Name ImplementsInterfaces
*/
;
_proto.parseObjectTypeExtension = function parseObjectTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('type');
var name = this.parseName();
var interfaces = this.parseImplementsInterfaces();
var directives = this.parseDirectives(true);
var fields = this.parseFieldsDefinition();
if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.OBJECT_TYPE_EXTENSION,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* InterfaceTypeExtension :
* - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
* - extend interface Name ImplementsInterfaces? Directives[Const]
* - extend interface Name ImplementsInterfaces
*/
;
_proto.parseInterfaceTypeExtension = function parseInterfaceTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('interface');
var name = this.parseName();
var interfaces = this.parseImplementsInterfaces();
var directives = this.parseDirectives(true);
var fields = this.parseFieldsDefinition();
if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.INTERFACE_TYPE_EXTENSION,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* UnionTypeExtension :
* - extend union Name Directives[Const]? UnionMemberTypes
* - extend union Name Directives[Const]
*/
;
_proto.parseUnionTypeExtension = function parseUnionTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('union');
var name = this.parseName();
var directives = this.parseDirectives(true);
var types = this.parseUnionMemberTypes();
if (directives.length === 0 && types.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.UNION_TYPE_EXTENSION,
name: name,
directives: directives,
types: types,
loc: this.loc(start)
};
}
/**
* EnumTypeExtension :
* - extend enum Name Directives[Const]? EnumValuesDefinition
* - extend enum Name Directives[Const]
*/
;
_proto.parseEnumTypeExtension = function parseEnumTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('enum');
var name = this.parseName();
var directives = this.parseDirectives(true);
var values = this.parseEnumValuesDefinition();
if (directives.length === 0 && values.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.ENUM_TYPE_EXTENSION,
name: name,
directives: directives,
values: values,
loc: this.loc(start)
};
}
/**
* InputObjectTypeExtension :
* - extend input Name Directives[Const]? InputFieldsDefinition
* - extend input Name Directives[Const]
*/
;
_proto.parseInputObjectTypeExtension = function parseInputObjectTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('input');
var name = this.parseName();
var directives = this.parseDirectives(true);
var fields = this.parseInputFieldsDefinition();
if (directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,
name: name,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* DirectiveDefinition :
* - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
*/
;
_proto.parseDirectiveDefinition = function parseDirectiveDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('directive');
this.expectToken(TokenKind.AT);
var name = this.parseName();
var args = this.parseArgumentDefs();
var repeatable = this.expectOptionalKeyword('repeatable');
this.expectKeyword('on');
var locations = this.parseDirectiveLocations();
return {
kind: Kind.DIRECTIVE_DEFINITION,
description: description,
name: name,
arguments: args,
repeatable: repeatable,
locations: locations,
loc: this.loc(start)
};
}
/**
* DirectiveLocations :
* - `|`? DirectiveLocation
* - DirectiveLocations | DirectiveLocation
*/
;
_proto.parseDirectiveLocations = function parseDirectiveLocations() {
return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);
}
/*
* DirectiveLocation :
* - ExecutableDirectiveLocation
* - TypeSystemDirectiveLocation
*
* ExecutableDirectiveLocation : one of
* `QUERY`
* `MUTATION`
* `SUBSCRIPTION`
* `FIELD`
* `FRAGMENT_DEFINITION`
* `FRAGMENT_SPREAD`
* `INLINE_FRAGMENT`
*
* TypeSystemDirectiveLocation : one of
* `SCHEMA`
* `SCALAR`
* `OBJECT`
* `FIELD_DEFINITION`
* `ARGUMENT_DEFINITION`
* `INTERFACE`
* `UNION`
* `ENUM`
* `ENUM_VALUE`
* `INPUT_OBJECT`
* `INPUT_FIELD_DEFINITION`
*/
;
_proto.parseDirectiveLocation = function parseDirectiveLocation() {
var start = this._lexer.token;
var name = this.parseName();
if (DirectiveLocation[name.value] !== undefined) {
return name;
}
throw this.unexpected(start);
} // Core parsing utility functions
/**
* Returns a location object, used to identify the place in the source that created a given parsed object.
*/
;
_proto.loc = function loc(startToken) {
var _this$_options4;
if (((_this$_options4 = this._options) === null || _this$_options4 === void 0 ? void 0 : _this$_options4.noLocation) !== true) {
return new Location(startToken, this._lexer.lastToken, this._lexer.source);
}
}
/**
* Determines if the next token is of a given kind
*/
;
_proto.peek = function peek(kind) {
return this._lexer.token.kind === kind;
}
/**
* If the next token is of the given kind, return that token after advancing the lexer.
* Otherwise, do not change the parser state and throw an error.
*/
;
_proto.expectToken = function expectToken(kind) {
var token = this._lexer.token;
if (token.kind === kind) {
this._lexer.advance();
return token;
}
throw syntaxError(this._lexer.source, token.start, "Expected ".concat(getTokenKindDesc(kind), ", found ").concat(getTokenDesc(token), "."));
}
/**
* If the next token is of the given kind, return that token after advancing the lexer.
* Otherwise, do not change the parser state and return undefined.
*/
;
_proto.expectOptionalToken = function expectOptionalToken(kind) {
var token = this._lexer.token;
if (token.kind === kind) {
this._lexer.advance();
return token;
}
return undefined;
}
/**
* If the next token is a given keyword, advance the lexer.
* Otherwise, do not change the parser state and throw an error.
*/
;
_proto.expectKeyword = function expectKeyword(value) {
var token = this._lexer.token;
if (token.kind === TokenKind.NAME && token.value === value) {
this._lexer.advance();
} else {
throw syntaxError(this._lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token), "."));
}
}
/**
* If the next token is a given keyword, return "true" after advancing the lexer.
* Otherwise, do not change the parser state and return "false".
*/
;
_proto.expectOptionalKeyword = function expectOptionalKeyword(value) {
var token = this._lexer.token;
if (token.kind === TokenKind.NAME && token.value === value) {
this._lexer.advance();
return true;
}
return false;
}
/**
* Helper function for creating an error when an unexpected lexed token is encountered.
*/
;
_proto.unexpected = function unexpected(atToken) {
var token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;
return syntaxError(this._lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token), "."));
}
/**
* Returns a possibly empty list of parse nodes, determined by the parseFn.
* This list begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
;
_proto.any = function any(openKind, parseFn, closeKind) {
this.expectToken(openKind);
var nodes = [];
while (!this.expectOptionalToken(closeKind)) {
nodes.push(parseFn.call(this));
}
return nodes;
}
/**
* Returns a list of parse nodes, determined by the parseFn.
* It can be empty only if open token is missing otherwise it will always return non-empty list
* that begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
;
_proto.optionalMany = function optionalMany(openKind, parseFn, closeKind) {
if (this.expectOptionalToken(openKind)) {
var nodes = [];
do {
nodes.push(parseFn.call(this));
} while (!this.expectOptionalToken(closeKind));
return nodes;
}
return [];
}
/**
* Returns a non-empty list of parse nodes, determined by the parseFn.
* This list begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
;
_proto.many = function many(openKind, parseFn, closeKind) {
this.expectToken(openKind);
var nodes = [];
do {
nodes.push(parseFn.call(this));
} while (!this.expectOptionalToken(closeKind));
return nodes;
}
/**
* Returns a non-empty list of parse nodes, determined by the parseFn.
* This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.
* Advances the parser to the next lex token after last item in the list.
*/
;
_proto.delimitedMany = function delimitedMany(delimiterKind, parseFn) {
this.expectOptionalToken(delimiterKind);
var nodes = [];
do {
nodes.push(parseFn.call(this));
} while (this.expectOptionalToken(delimiterKind));
return nodes;
};
return Parser;
}();
/**
* A helper function to describe a token as a string for debugging.
*/
function getTokenDesc(token) {
var value = token.value;
return getTokenKindDesc(token.kind) + (value != null ? " \"".concat(value, "\"") : '');
}
/**
* A helper function to describe a token kind as a string for debugging.
*/
function getTokenKindDesc(kind) {
return isPunctuatorTokenKind(kind) ? "\"".concat(kind, "\"") : kind;
}
// CONCATENATED MODULE: ./node_modules/graphql-tag/lib/index.js
var docCache = new Map();
var fragmentSourceMap = new Map();
var printFragmentWarnings = true;
var experimentalFragmentVariables = false;
function graphql_tag_lib_normalize(string) {
return string.replace(/[\s,]+/g, ' ').trim();
}
function cacheKeyFromLoc(loc) {
return graphql_tag_lib_normalize(loc.source.body.substring(loc.start, loc.end));
}
function processFragments(ast) {
var seenKeys = new Set();
var definitions = [];
ast.definitions.forEach(function (fragmentDefinition) {
if (fragmentDefinition.kind === 'FragmentDefinition') {
var fragmentName = fragmentDefinition.name.value;
var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);
var sourceKeySet = fragmentSourceMap.get(fragmentName);
if (sourceKeySet && !sourceKeySet.has(sourceKey)) {
if (printFragmentWarnings) {
console.warn("Warning: fragment with name " + fragmentName + " already exists.\n"
+ "graphql-tag enforces all fragment names across your application to be unique; read more about\n"
+ "this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names");
}
}
else if (!sourceKeySet) {
fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);
}
sourceKeySet.add(sourceKey);
if (!seenKeys.has(sourceKey)) {
seenKeys.add(sourceKey);
definitions.push(fragmentDefinition);
}
}
else {
definitions.push(fragmentDefinition);
}
});
return tslib_tslib_es6_assign(tslib_tslib_es6_assign({}, ast), { definitions: definitions });
}
function stripLoc(doc) {
var workSet = new Set(doc.definitions);
workSet.forEach(function (node) {
if (node.loc)
delete node.loc;
Object.keys(node).forEach(function (key) {
var value = node[key];
if (value && typeof value === 'object') {
workSet.add(value);
}
});
});
var loc = doc.loc;
if (loc) {
delete loc.startToken;
delete loc.endToken;
}
return doc;
}
function lib_parseDocument(source) {
var cacheKey = graphql_tag_lib_normalize(source);
if (!docCache.has(cacheKey)) {
var parsed = parser_parse(source, {
experimentalFragmentVariables: experimentalFragmentVariables,
allowLegacyFragmentVariables: experimentalFragmentVariables
});
if (!parsed || parsed.kind !== 'Document') {
throw new Error('Not a valid GraphQL document.');
}
docCache.set(cacheKey, stripLoc(processFragments(parsed)));
}
return docCache.get(cacheKey);
}
function gql(literals) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (typeof literals === 'string') {
literals = [literals];
}
var result = literals[0];
args.forEach(function (arg, i) {
if (arg && arg.kind === 'Document') {
result += arg.loc.source.body;
}
else {
result += arg;
}
result += literals[i + 1];
});
return lib_parseDocument(result);
}
function resetCaches() {
docCache.clear();
fragmentSourceMap.clear();
}
function disableFragmentWarnings() {
printFragmentWarnings = false;
}
function enableExperimentalFragmentVariables() {
experimentalFragmentVariables = true;
}
function disableExperimentalFragmentVariables() {
experimentalFragmentVariables = false;
}
var extras = {
gql: gql,
resetCaches: resetCaches,
disableFragmentWarnings: disableFragmentWarnings,
enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,
disableExperimentalFragmentVariables: disableExperimentalFragmentVariables
};
(function (gql_1) {
gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;
})(gql || (gql = {}));
gql["default"] = gql;
/* harmony default export */ var graphql_tag_lib = (gql);
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./assets/services/graph/queries.js
const GET_ACCOUNTS = `
query getAccounts($first: Int, $fromBlock: Int) {
accounts(first: $first, orderBy: blockNumber, orderDirection: asc, where: {
blockNumber_gte: $fromBlock
}) {
id
key
owner
blockNumber
}
_meta {
block {
number
}
hasIndexingErrors
}
}
`
const GET_COMMITMENT = `
query getCommitment($first: Int, $fromBlock: Int) {
commitments(first: $first, orderBy: blockNumber, orderDirection: asc, where: {
blockNumber_gte: $fromBlock
}) {
index
commitment
blockNumber
encryptedOutput
transactionHash
}
_meta {
block {
number
}
hasIndexingErrors
}
}
`
const GET_NULLIFIER = `
query getNullifier($first: Int, $fromBlock: Int) {
nullifiers(first: $first, orderBy: blockNumber, orderDirection: asc, where: {
blockNumber_gte: $fromBlock
}) {
nullifier
blockNumber
transactionHash
}
_meta {
block {
number
}
hasIndexingErrors
}
}
`
// CONCATENATED MODULE: ./assets/services/constants.js
const BSC_CHAIN_ID = 56
const XDAI_CHAIN_ID = 100
const MAINNET_CHAIN_ID = 1
const ChainId = {
BSC: BSC_CHAIN_ID,
XDAI: XDAI_CHAIN_ID,
MAINNET: MAINNET_CHAIN_ID,
}
const OFFCHAIN_ORACLE_CONTRACT = '0x07D91f5fb9Bf7798734C3f606dB065549F6893bb'
const POOL_CONTRACT = {
[ChainId.XDAI]: '0xD692Fd2D0b2Fbd2e52CFa5B5b9424bC981C30696', // ETH
// [ChainId.XDAI]: '0x772F007F13604ac286312C85b9Cd9B2D691B353E', // BNB
}
const REDGISTRY_CONTRACT = {
[ChainId.MAINNET]: '0x58E8dCC13BE9780fC42E8723D8EaD4CF46943dF2',
}
const AGGREGATOR_FACTORY = {
[ChainId.MAINNET]: '0xE8F47A78A6D52D317D0D2FFFac56739fE14D1b49',
}
const WRAPPED_TOKEN = {
[ChainId.MAINNET]: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // WETH on mainnet
[ChainId.XDAI]: '0x6A023CCd1ff6F2045C3309768eAd9E68F978f6e1', // WETH on xdai
[ChainId.BSC]: '0xCa8d20f3e0144a72C6B5d576e9Bd3Fd8557E2B04', // WBNB on xdai
}
const RPC_LIST = {
[ChainId.BSC]: 'https://tornadocash-rpc.com/bsc',
[ChainId.MAINNET]: 'https://tornadocash-rpc.com/mainnet',
[ChainId.XDAI]: 'https://tornadocash-rpc.com/gnosis',
}
const FALLBACK_RPC_LIST = {
[ChainId.BSC]: [
'https://binance.nodereal.io',
// 'https://rpc.ankr.com/bsc/dbe08b852ba176a8aeac783cc1fa8becaf4f107235dfdae79241063fbf52ca4a',
],
[ChainId.MAINNET]: [
'https://rpc.mevblocker.io',
// 'https://rpc.ankr.com/eth/dbe08b852ba176a8aeac783cc1fa8becaf4f107235dfdae79241063fbf52ca4a',
],
[ChainId.XDAI]: [
// 'https://rpc.ankr.com/gnosis/dbe08b852ba176a8aeac783cc1fa8becaf4f107235dfdae79241063fbf52ca4a',
'https://tornadocash-rpc.com/gnosis',
],
}
const RPC_WS_LIST = {
[ChainId.MAINNET]: 'wss://mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607',
[ChainId.BSC]: 'wss://bsc-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607',
[ChainId.XDAI]: 'wss://gnosis-mainnet.chainnodes.org/d692ae63-0a7e-43e0-9da9-fe4f4cc6c607',
}
const MULTICALL = {
[ChainId.BSC]: '0xf072f255A3324198C7F653237B44E1C4e66f8C42',
[ChainId.XDAI]: '0x8677b93D543d0217B32B8FDc20F2316E138D619B',
[ChainId.MAINNET]: '0x1F98415757620B543A52E61c46B32eB19261F984',
}
const BRIDGE_PROXY = {
[ChainId.BSC]: '0x05185872898b6f94AA600177EF41B9334B1FA48B',
[ChainId.MAINNET]: '0x4c36d2919e407f0cc2ee3c993ccf8ac26d9ce64e',
}
const AMB_BRIDGE = {
[ChainId.XDAI]: '0x75Df5AF045d91108662D8080fD1FEFAd6aA0bb59', // ETH
// [ChainId.XDAI]: '0x162E898bD0aacB578C8D5F8d6ca588c13d2A383F', // BNB
[ChainId.MAINNET]: '0x162E898bD0aacB578C8D5F8d6ca588c13d2A383F',
}
const BRIDGE_HELPER = {
[ChainId.MAINNET]: '0xCa0840578f57fE71599D29375e16783424023357',
[ChainId.BSC]: '0x8845F740F8B01bC7D9A4C82a6fD4A60320c07AF1',
}
const BRIDGE_FEE_MANAGER = {
[ChainId.XDAI]: '0x5dbC897aEf6B18394D845A922BF107FA98E3AC55',
}
const FOREIGN_OMNIBRIDGE = {
[ChainId.MAINNET]: '0x88ad09518695c6c3712AC10a214bE5109a655671',
}
const OMNIBRIDGE = {
[ChainId.XDAI]: '0xf6A78083ca3e2a662D6dd1703c939c8aCE2e268d',
}
const SANCTION_LIST = {
[ChainId.MAINNET]: '0x40C57923924B5c5c5455c48D93317139ADDaC8fb',
}
const CHAINS = {
[ChainId.XDAI]: {
symbol: 'XDAI',
name: 'xdai',
shortName: 'xdai',
icon: 'ethereum',
network: 'XDAI',
blockDuration: 3000, // ms
deployBlock: 19097755, // ETH
// deployBlock: 20446605, // BNB
blockGasLimit: 144000000, // rpc block gas limit
hexChainId: '0x64',
isEipSupported: false,
ensSubdomainKey: 'gnosis-nova',
blockExplorerUrl: 'https://gnosisscan.io'
},
[ChainId.MAINNET]: {
symbol: 'ETH',
name: 'ethereum',
shortName: 'eth',
icon: 'ethereum',
network: 'Mainnet',
deployBlock: 13494216,
blockDuration: 15000,
blockGasLimit: 144000000,
hexChainId: '0x1',
isEipSupported: true,
ensSubdomainKey: 'mainnet-tornado',
blockExplorerUrl: 'https://etherscan.io'
},
[ChainId.BSC]: {
symbol: 'BNB',
name: 'bsc',
shortName: 'bsc',
icon: 'binance',
network: 'BSC',
deployBlock: 14931075,
blockDuration: 3000,
blockGasLimit: 144000000,
hexChainId: '0x38',
isEipSupported: false,
ensSubdomainKey: 'bsc-tornado',
blockExplorerUrl: 'https://bscscan.com'
},
}
const workerEvents = {
INIT_WORKER: 'initWorker',
GET_COMMITMENT_EVENTS: 'get_commitment_events',
// nullifier
GET_UNSPENT_EVENTS: 'get_unspent_events',
GET_NULLIFIER_EVENT: 'get_nullifier_event',
GET_NULLIFIER_EVENTS_FROM_TX_HASH: 'get_nullifier_events_from_tx_hash',
UPDATE_NULLIFIER_EVENTS: 'update_nullifier_events',
// events
GET_BATCH_EVENTS: 'get_batch_events',
GET_BATCH_COMMITMENTS_EVENTS: 'get_batch_commitments_events',
GET_EVENTS_FROM_TX_HASH: 'get_events_from_tx_hash',
SAVE_EVENTS: 'save_events',
GET_CACHED_EVENTS: 'get_cached_events',
GET_CACHED_COMMITMENTS_EVENTS: 'get_cached_commitments_events',
SAVE_LAST_SYNC_BLOCK: 'save_last_sync_block',
}
const numbers = {
ZERO: 0,
TWO: 2,
ONE: 1,
BYTES_31: 31,
BYTES_62: 62,
IS_SPENT_INDEX: 1,
OX_LENGTH: 2,
RECALL_DELAY: 500,
NULLIFIER_LENGTH: 66,
NONCE_BUF_LENGTH: 24,
COMMITMENTS_CHAIN: 100,
DEPLOYED_BLOCK: 19097755,
DECRYPT_WORKERS_COUNT: 8,
MIN_BLOCKS_INTERVAL_LINE: 200000,
EPHEM_PUBLIC_KEY_BUF_LENGTH: 56,
}
// CONCATENATED MODULE: ./assets/services/graph/index.js
const { getAddress: graph_getAddress } = lib_esm_utils_namespaceObject
const graph_first = 1000
const breakLength = 900
const CHAIN_GRAPH_URLS = {
[ChainId.BSC]: 'https://api.thegraph.com/subgraphs/name/dan1kov/bsc-tornado-pool-subgraph',
[ChainId.MAINNET]: 'https://tornadocash-rpc.com/subgraphs/name/tornadocash/mainnet-tornado-pool-subgraph',
[ChainId.XDAI]: 'https://tornadocash-rpc.com/subgraphs/name/tornadocash/gnosis-tornado-nova-subgraph',
}
const graph_link = (operation) => {
const { chainId } = operation.getContext()
return CHAIN_GRAPH_URLS[chainId]
}
const graph_client = new ApolloClient_ApolloClient({
uri: graph_link,
cache: new inMemoryCache_InMemoryCache(),
})
async function getAccounts({ fromBlock, chainId }) {
const { data } = await graph_client.query({
context: {
chainId,
},
query: gql(GET_ACCOUNTS),
variables: { first: graph_first, fromBlock },
})
if (!data) {
return {
results: [],
lastSyncBlock: data._meta.block.number
}
}
return {
results: data.accounts,
lastSyncBlock: data._meta.block.number
}
}
async function getAllAccounts({ fromBlock, toBlock, chainId }) {
try {
let accounts = []
let lastSyncBlock
while (true) {
let { results, lastSyncBlock: lastBlock } = await getAccounts({ fromBlock, chainId })
lastSyncBlock = lastBlock
if (Object(lodash["isEmpty"])(results)) {
break
}
if (results.length < breakLength) {
accounts = accounts.concat(results)
break
}
const [lastEvent] = results.slice(-numbers.ONE)
results = results.filter((e) => e.blockNumber !== lastEvent.blockNumber)
fromBlock = Number(lastEvent.blockNumber)
accounts = accounts.concat(results)
if (toBlock && fromBlock >= Number(toBlock)) {
break
}
}
if (!accounts) {
return {
lastSyncBlock,
events: [],
}
}
const data = accounts.map((e) => ({
key: e.key,
owner: graph_getAddress(e.owner),
blockNumber: Number(e.blockNumber),
}))
const [lastEvent] = data.slice(-numbers.ONE)
return {
events: data,
lastSyncBlock: (lastEvent && lastEvent.blockNumber >= lastSyncBlock)
? lastEvent.blockNumber + numbers.ONE
: lastSyncBlock,
}
} catch (err) {
console.log('Error from getAllAccounts')
console.log(err)
return {
lastSyncBlock: '',
events: [],
}
}
}
async function getCommitments({ fromBlock, chainId }) {
const { data } = await graph_client.query({
context: {
chainId,
},
query: gql(GET_COMMITMENT),
variables: { first: graph_first, fromBlock },
})
if (!data) {
return {
results: [],
lastSyncBlock: data._meta.block.number
}
}
return {
results: data.commitments,
lastSyncBlock: data._meta.block.number
}
}
async function getAllCommitments({ fromBlock, toBlock, chainId }) {
try {
let commitments = []
let lastSyncBlock
while (true) {
let { results, lastSyncBlock: lastBlock } = await getCommitments({ fromBlock, chainId })
lastSyncBlock = lastBlock
if (Object(lodash["isEmpty"])(results)) {
break
}
if (results.length < breakLength) {
commitments = commitments.concat(results)
break
}
const [lastEvent] = results.slice(-numbers.ONE)
results = results.filter((e) => e.blockNumber !== lastEvent.blockNumber)
fromBlock = Number(lastEvent.blockNumber)
commitments = commitments.concat(results)
if (toBlock && fromBlock >= Number(toBlock)) {
break
}
}
if (!commitments) {
return {
lastSyncBlock,
events: [],
}
}
const data = commitments.map((e) => ({
blockNumber: Number(e.blockNumber),
transactionHash: e.transactionHash,
index: Number(e.index),
commitment: e.commitment,
encryptedOutput: e.encryptedOutput
}))
const [lastEvent] = data.slice(-numbers.ONE)
return {
events: data,
lastSyncBlock: (lastEvent && lastEvent.blockNumber >= lastSyncBlock)
? lastEvent.blockNumber + numbers.ONE
: lastSyncBlock,
}
} catch (err) {
console.log('Error from getAllCommitments')
console.log(err)
return {
lastSyncBlock: '',
events: [],
}
}
}
async function getNullifiers({ fromBlock, chainId }) {
const { data } = await graph_client.query({
context: {
chainId,
},
query: gql(GET_NULLIFIER),
variables: { first: graph_first, fromBlock },
})
if (!data) {
return {
results: [],
lastSyncBlock: data._meta.block.number
}
}
return {
results: data.nullifiers,
lastSyncBlock: data._meta.block.number
}
}
async function getAllNullifiers({ fromBlock, chainId }) {
try {
let nullifiers = []
let lastSyncBlock
while (true) {
let { results, lastSyncBlock: lastBlock } = await getNullifiers({ fromBlock, chainId })
lastSyncBlock = lastBlock
if (Object(lodash["isEmpty"])(results)) {
break
}
if (results.length < breakLength) {
nullifiers = nullifiers.concat(results)
break
}
const [lastEvent] = results.slice(-numbers.ONE)
results = results.filter((e) => e.blockNumber !== lastEvent.blockNumber)
fromBlock = Number(lastEvent.blockNumber)
nullifiers = nullifiers.concat(results)
}
if (!nullifiers) {
return {
lastSyncBlock,
events: [],
}
}
const data = nullifiers.map((e) => ({
nullifier: e.nullifier,
blockNumber: Number(e.blockNumber),
transactionHash: e.transactionHash
}))
const [lastEvent] = data.slice(-numbers.ONE)
return {
events: data,
lastSyncBlock: (lastEvent && lastEvent.blockNumber >= lastSyncBlock)
? lastEvent.blockNumber + numbers.ONE
: lastSyncBlock,
}
} catch (err) {
console.log('Error from getAllNullifiers')
console.log(err)
return {
lastSyncBlock: '',
events: [],
}
}
}
// EXTERNAL MODULE: external "module"
var external_module_ = __webpack_require__(30);
// CONCATENATED MODULE: ./node_modules/fflate/esm/index.mjs
var require = Object(external_module_["createRequire"])('/');
// DEFLATE is a complex format; to read this code, you should probably check the RFC first:
// https://tools.ietf.org/html/rfc1951
// You may also wish to take a look at the guide I made about this program:
// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
// Some of the following code is similar to that of UZIP.js:
// https://github.com/photopea/UZIP.js
// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
// is better for memory in most engines (I *think*).
// Mediocre shim
var Worker;
var workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";
try {
Worker = require('worker_threads').Worker;
}
catch (e) {
}
var wk = Worker ? function (c, _, msg, transfer, cb) {
var done = false;
var w = new Worker(c + workerAdd, { eval: true })
.on('error', function (e) { return cb(e, null); })
.on('message', function (m) { return cb(null, m); })
.on('exit', function (c) {
if (c && !done)
cb(new Error('exited with code ' + c), null);
});
w.postMessage(msg, transfer);
w.terminate = function () {
done = true;
return Worker.prototype.terminate.call(w);
};
return w;
} : function (_, __, ___, ____, cb) {
setImmediate(function () { return cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null); });
var NOP = function () { };
return {
terminate: NOP,
postMessage: NOP
};
};
// aliases for shorter compressed code (most minifers don't do this)
var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
// fixed length extra bits
var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
// fixed distance extra bits
var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
// code length index map
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
// get base, reverse index map from extra bits
var freb = function (eb, start) {
var b = new u16(31);
for (var i = 0; i < 31; ++i) {
b[i] = start += 1 << eb[i - 1];
}
// numbers here are at max 18 bits
var r = new i32(b[30]);
for (var i = 1; i < 30; ++i) {
for (var j = b[i]; j < b[i + 1]; ++j) {
r[j] = ((j - b[i]) << 5) | i;
}
}
return { b: b, r: r };
};
var esm_a = freb(fleb, 2), fl = esm_a.b, revfl = esm_a.r;
// we can ignore the fact that the other numbers are wrong; they never happen anyway
fl[28] = 258, revfl[258] = 28;
var esm_b = freb(fdeb, 0), fd = esm_b.b, revfd = esm_b.r;
// map of value to reverse (assuming 16 bits)
var rev = new u16(32768);
for (var esm_i = 0; esm_i < 32768; ++esm_i) {
// reverse table algorithm from SO
var esm_x = ((esm_i & 0xAAAA) >> 1) | ((esm_i & 0x5555) << 1);
esm_x = ((esm_x & 0xCCCC) >> 2) | ((esm_x & 0x3333) << 2);
esm_x = ((esm_x & 0xF0F0) >> 4) | ((esm_x & 0x0F0F) << 4);
rev[esm_i] = (((esm_x & 0xFF00) >> 8) | ((esm_x & 0x00FF) << 8)) >> 1;
}
// create huffman tree from u8 "map": index -> code length for code index
// mb (max bits) must be at most 15
// TODO: optimize/split up?
var hMap = (function (cd, mb, r) {
var s = cd.length;
// index
var i = 0;
// u16 "map": index -> # of codes with bit length = index
var l = new u16(mb);
// length of cd must be 288 (total # of codes)
for (; i < s; ++i) {
if (cd[i])
++l[cd[i] - 1];
}
// u16 "map": index -> minimum code for bit length = index
var le = new u16(mb);
for (i = 1; i < mb; ++i) {
le[i] = (le[i - 1] + l[i - 1]) << 1;
}
var co;
if (r) {
// u16 "map": index -> number of actual bits, symbol for code
co = new u16(1 << mb);
// bits to remove for reverser
var rvb = 15 - mb;
for (i = 0; i < s; ++i) {
// ignore 0 lengths
if (cd[i]) {
// num encoding both symbol and bits read
var sv = (i << 4) | cd[i];
// free bits
var r_1 = mb - cd[i];
// start value
var v = le[cd[i] - 1]++ << r_1;
// m is end value
for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
// every 16 bit value starting with the code yields the same result
co[rev[v] >> rvb] = sv;
}
}
}
}
else {
co = new u16(s);
for (i = 0; i < s; ++i) {
if (cd[i]) {
co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);
}
}
}
return co;
});
// fixed length tree
var flt = new u8(288);
for (var esm_i = 0; esm_i < 144; ++esm_i)
flt[esm_i] = 8;
for (var esm_i = 144; esm_i < 256; ++esm_i)
flt[esm_i] = 9;
for (var esm_i = 256; esm_i < 280; ++esm_i)
flt[esm_i] = 7;
for (var esm_i = 280; esm_i < 288; ++esm_i)
flt[esm_i] = 8;
// fixed distance tree
var fdt = new u8(32);
for (var esm_i = 0; esm_i < 32; ++esm_i)
fdt[esm_i] = 5;
// fixed length map
var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);
// fixed distance map
var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
// find max of array
var max = function (a) {
var m = a[0];
for (var i = 1; i < a.length; ++i) {
if (a[i] > m)
m = a[i];
}
return m;
};
// read d, starting at bit p and mask with m
var bits = function (d, p, m) {
var o = (p / 8) | 0;
return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
};
// read d, starting at bit p continuing for at least 16 bits
var bits16 = function (d, p) {
var o = (p / 8) | 0;
return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
};
// get end of byte
var shft = function (p) { return ((p + 7) / 8) | 0; };
// typed array slice - allows garbage collector to free original reference,
// while being more compatible than .slice
var slc = function (v, s, e) {
if (s == null || s < 0)
s = 0;
if (e == null || e > v.length)
e = v.length;
// can't use .constructor in case user-supplied
return new u8(v.subarray(s, e));
};
/**
* Codes for errors generated within this library
*/
var FlateErrorCode = {
UnexpectedEOF: 0,
InvalidBlockType: 1,
InvalidLengthLiteral: 2,
InvalidDistance: 3,
StreamFinished: 4,
NoStreamHandler: 5,
InvalidHeader: 6,
NoCallback: 7,
InvalidUTF8: 8,
ExtraFieldTooLong: 9,
InvalidDate: 10,
FilenameTooLong: 11,
StreamFinishing: 12,
InvalidZipData: 13,
UnknownCompressionMethod: 14
};
// error codes
var esm_ec = [
'unexpected EOF',
'invalid block type',
'invalid length/literal',
'invalid distance',
'stream finished',
'no stream handler',
,
'no callback',
'invalid UTF-8 data',
'extra field too long',
'date not in range 1980-2099',
'filename too long',
'stream finishing',
'invalid zip data'
// determined by unknown compression method
];
;
var esm_err = function (ind, msg, nt) {
var e = new Error(msg || esm_ec[ind]);
e.code = ind;
if (Error.captureStackTrace)
Error.captureStackTrace(e, esm_err);
if (!nt)
throw e;
return e;
};
// expands raw DEFLATE data
var inflt = function (dat, st, buf, dict) {
// source length dict length
var sl = dat.length, dl = dict ? dict.length : 0;
if (!sl || st.f && !st.l)
return buf || new u8(0);
var noBuf = !buf;
// have to estimate size
var resize = noBuf || st.i != 2;
// no state
var noSt = st.i;
// Assumes roughly 33% compression ratio average
if (noBuf)
buf = new u8(sl * 3);
// ensure buffer can fit at least l elements
var cbuf = function (l) {
var bl = buf.length;
// need to increase size to fit
if (l > bl) {
// Double or set to necessary, whichever is greater
var nbuf = new u8(Math.max(bl * 2, l));
nbuf.set(buf);
buf = nbuf;
}
};
// last chunk bitpos bytes
var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
// total bits
var tbts = sl * 8;
do {
if (!lm) {
// BFINAL - this is only 1 when last chunk is next
final = bits(dat, pos, 1);
// type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
var type = bits(dat, pos + 1, 3);
pos += 3;
if (!type) {
// go to end of byte boundary
var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
if (t > sl) {
if (noSt)
esm_err(0);
break;
}
// ensure size
if (resize)
cbuf(bt + l);
// Copy over uncompressed data
buf.set(dat.subarray(s, t), bt);
// Get new bitpos, update byte count
st.b = bt += l, st.p = pos = t * 8, st.f = final;
continue;
}
else if (type == 1)
lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
else if (type == 2) {
// literal lengths
var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
var tl = hLit + bits(dat, pos + 5, 31) + 1;
pos += 14;
// length+distance tree
var ldt = new u8(tl);
// code length tree
var clt = new u8(19);
for (var i = 0; i < hcLen; ++i) {
// use index map to get real code
clt[clim[i]] = bits(dat, pos + i * 3, 7);
}
pos += hcLen * 3;
// code lengths bits
var clb = max(clt), clbmsk = (1 << clb) - 1;
// code lengths map
var clm = hMap(clt, clb, 1);
for (var i = 0; i < tl;) {
var r = clm[bits(dat, pos, clbmsk)];
// bits read
pos += r & 15;
// symbol
var s = r >> 4;
// code length to copy
if (s < 16) {
ldt[i++] = s;
}
else {
// copy count
var c = 0, n = 0;
if (s == 16)
n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
else if (s == 17)
n = 3 + bits(dat, pos, 7), pos += 3;
else if (s == 18)
n = 11 + bits(dat, pos, 127), pos += 7;
while (n--)
ldt[i++] = c;
}
}
// length tree distance tree
var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
// max length bits
lbt = max(lt);
// max dist bits
dbt = max(dt);
lm = hMap(lt, lbt, 1);
dm = hMap(dt, dbt, 1);
}
else
esm_err(1);
if (pos > tbts) {
if (noSt)
esm_err(0);
break;
}
}
// Make sure the buffer can hold this + the largest possible addition
// Maximum chunk size (practically, theoretically infinite) is 2^17
if (resize)
cbuf(bt + 131072);
var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
var lpos = pos;
for (;; lpos = pos) {
// bits read, code
var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
pos += c & 15;
if (pos > tbts) {
if (noSt)
esm_err(0);
break;
}
if (!c)
esm_err(2);
if (sym < 256)
buf[bt++] = sym;
else if (sym == 256) {
lpos = pos, lm = null;
break;
}
else {
var add = sym - 254;
// no extra bits needed if less
if (sym > 264) {
// index
var i = sym - 257, b = fleb[i];
add = bits(dat, pos, (1 << b) - 1) + fl[i];
pos += b;
}
// dist
var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
if (!d)
esm_err(3);
pos += d & 15;
var dt = fd[dsym];
if (dsym > 3) {
var b = fdeb[dsym];
dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
}
if (pos > tbts) {
if (noSt)
esm_err(0);
break;
}
if (resize)
cbuf(bt + 131072);
var end = bt + add;
if (bt < dt) {
var shift = dl - dt, dend = Math.min(dt, end);
if (shift + bt < 0)
esm_err(3);
for (; bt < dend; ++bt)
buf[bt] = dict[shift + bt];
}
for (; bt < end; ++bt)
buf[bt] = buf[bt - dt];
}
}
st.l = lm, st.p = lpos, st.b = bt, st.f = final;
if (lm)
final = 1, st.m = lbt, st.d = dm, st.n = dbt;
} while (!final);
// don't reallocate for streams or user buffers
return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
// starting at p, write the minimum number of bits that can hold v to d
var wbits = function (d, p, v) {
v <<= p & 7;
var o = (p / 8) | 0;
d[o] |= v;
d[o + 1] |= v >> 8;
};
// starting at p, write the minimum number of bits (>8) that can hold v to d
var wbits16 = function (d, p, v) {
v <<= p & 7;
var o = (p / 8) | 0;
d[o] |= v;
d[o + 1] |= v >> 8;
d[o + 2] |= v >> 16;
};
// creates code lengths from a frequency table
var hTree = function (d, mb) {
// Need extra info to make a tree
var t = [];
for (var i = 0; i < d.length; ++i) {
if (d[i])
t.push({ s: i, f: d[i] });
}
var s = t.length;
var t2 = t.slice();
if (!s)
return { t: et, l: 0 };
if (s == 1) {
var v = new u8(t[0].s + 1);
v[t[0].s] = 1;
return { t: v, l: 1 };
}
t.sort(function (a, b) { return a.f - b.f; });
// after i2 reaches last ind, will be stopped
// freq must be greater than largest possible number of symbols
t.push({ s: -1, f: 25001 });
var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
t[0] = { s: -1, f: l.f + r.f, l: l, r: r };
// efficient algorithm from UZIP.js
// i0 is lookbehind, i2 is lookahead - after processing two low-freq
// symbols that combined have high freq, will start processing i2 (high-freq,
// non-composite) symbols instead
// see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
while (i1 != s - 1) {
l = t[t[i0].f < t[i2].f ? i0++ : i2++];
r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };
}
var maxSym = t2[0].s;
for (var i = 1; i < s; ++i) {
if (t2[i].s > maxSym)
maxSym = t2[i].s;
}
// code lengths
var tr = new u16(maxSym + 1);
// max bits in tree
var mbt = ln(t[i1 - 1], tr, 0);
if (mbt > mb) {
// more algorithms from UZIP.js
// TODO: find out how this code works (debt)
// ind debt
var i = 0, dt = 0;
// left cost
var lft = mbt - mb, cst = 1 << lft;
t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });
for (; i < s; ++i) {
var i2_1 = t2[i].s;
if (tr[i2_1] > mb) {
dt += cst - (1 << (mbt - tr[i2_1]));
tr[i2_1] = mb;
}
else
break;
}
dt >>= lft;
while (dt > 0) {
var i2_2 = t2[i].s;
if (tr[i2_2] < mb)
dt -= 1 << (mb - tr[i2_2]++ - 1);
else
++i;
}
for (; i >= 0 && dt; --i) {
var i2_3 = t2[i].s;
if (tr[i2_3] == mb) {
--tr[i2_3];
++dt;
}
}
mbt = mb;
}
return { t: new u8(tr), l: mbt };
};
// get the max length and assign length codes
var ln = function (n, l, d) {
return n.s == -1
? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))
: (l[n.s] = d);
};
// length codes generation
var lc = function (c) {
var s = c.length;
// Note that the semicolon was intentional
while (s && !c[--s])
;
var cl = new u16(++s);
// ind num streak
var cli = 0, cln = c[0], cls = 1;
var w = function (v) { cl[cli++] = v; };
for (var i = 1; i <= s; ++i) {
if (c[i] == cln && i != s)
++cls;
else {
if (!cln && cls > 2) {
for (; cls > 138; cls -= 138)
w(32754);
if (cls > 2) {
w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);
cls = 0;
}
}
else if (cls > 3) {
w(cln), --cls;
for (; cls > 6; cls -= 6)
w(8304);
if (cls > 2)
w(((cls - 3) << 5) | 8208), cls = 0;
}
while (cls--)
w(cln);
cls = 1;
cln = c[i];
}
}
return { c: cl.subarray(0, cli), n: s };
};
// calculate the length of output from tree, code lengths
var clen = function (cf, cl) {
var l = 0;
for (var i = 0; i < cl.length; ++i)
l += cf[i] * cl[i];
return l;
};
// writes a fixed block
// returns the new bit pos
var wfblk = function (out, pos, dat) {
// no need to write 00 as type: TypedArray defaults to 0
var s = dat.length;
var o = shft(pos + 2);
out[o] = s & 255;
out[o + 1] = s >> 8;
out[o + 2] = out[o] ^ 255;
out[o + 3] = out[o + 1] ^ 255;
for (var i = 0; i < s; ++i)
out[o + i + 4] = dat[i];
return (o + 4 + s) * 8;
};
// writes a block
var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
wbits(out, p++, final);
++lf[256];
var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;
var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;
var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
var lcfreq = new u16(19);
for (var i = 0; i < lclt.length; ++i)
++lcfreq[lclt[i] & 31];
for (var i = 0; i < lcdt.length; ++i)
++lcfreq[lcdt[i] & 31];
var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
var nlcc = 19;
for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
;
var flen = (bl + 5) << 3;
var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
if (bs >= 0 && flen <= ftlen && flen <= dtlen)
return wfblk(out, p, dat.subarray(bs, bs + bl));
var lm, ll, dm, dl;
wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
if (dtlen < ftlen) {
lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
var llm = hMap(lct, mlcb, 0);
wbits(out, p, nlc - 257);
wbits(out, p + 5, ndc - 1);
wbits(out, p + 10, nlcc - 4);
p += 14;
for (var i = 0; i < nlcc; ++i)
wbits(out, p + 3 * i, lct[clim[i]]);
p += 3 * nlcc;
var lcts = [lclt, lcdt];
for (var it = 0; it < 2; ++it) {
var clct = lcts[it];
for (var i = 0; i < clct.length; ++i) {
var len = clct[i] & 31;
wbits(out, p, llm[len]), p += lct[len];
if (len > 15)
wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;
}
}
}
else {
lm = flm, ll = flt, dm = fdm, dl = fdt;
}
for (var i = 0; i < li; ++i) {
var sym = syms[i];
if (sym > 255) {
var len = (sym >> 18) & 31;
wbits16(out, p, lm[len + 257]), p += ll[len + 257];
if (len > 7)
wbits(out, p, (sym >> 23) & 31), p += fleb[len];
var dst = sym & 31;
wbits16(out, p, dm[dst]), p += dl[dst];
if (dst > 3)
wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];
}
else {
wbits16(out, p, lm[sym]), p += ll[sym];
}
}
wbits16(out, p, lm[256]);
return p + ll[256];
};
// deflate options (nice << 13) | chain
var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
// empty
var et = /*#__PURE__*/ new u8(0);
// compresses data into a raw DEFLATE buffer
var dflt = function (dat, lvl, plvl, pre, post, st) {
var s = st.z || dat.length;
var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
// writing to this writes to the output buffer
var w = o.subarray(pre, o.length - post);
var lst = st.l;
var pos = (st.r || 0) & 7;
if (lvl) {
if (pos)
w[0] = st.r >> 3;
var opt = deo[lvl - 1];
var n = opt >> 13, c = opt & 8191;
var msk_1 = (1 << plvl) - 1;
// prev 2-byte val map curr 2-byte val map
var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };
// 24576 is an arbitrary number of maximum symbols per block
// 424 buffer for last block
var syms = new i32(25000);
// length/literal freq distance freq
var lf = new u16(288), df = new u16(32);
// l/lcnt exbits index l/lind waitdx blkpos
var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
for (; i + 2 < s; ++i) {
// hash value
var hv = hsh(i);
// index mod 32768 previous index mod
var imod = i & 32767, pimod = head[hv];
prev[imod] = pimod;
head[hv] = imod;
// We always should modify head and prev, but only add symbols if
// this data is not yet processed ("wait" for wait index)
if (wi <= i) {
// bytes remaining
var rem = s - i;
if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
li = lc_1 = eb = 0, bs = i;
for (var j = 0; j < 286; ++j)
lf[j] = 0;
for (var j = 0; j < 30; ++j)
df[j] = 0;
}
// len dist chain
var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
if (rem > 2 && hv == hsh(i - dif)) {
var maxn = Math.min(n, rem) - 1;
var maxd = Math.min(32767, i);
// max possible length
// not capped at dif because decompressors implement "rolling" index population
var ml = Math.min(258, rem);
while (dif <= maxd && --ch_1 && imod != pimod) {
if (dat[i + l] == dat[i + l - dif]) {
var nl = 0;
for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
;
if (nl > l) {
l = nl, d = dif;
// break out early when we reach "nice" (we are satisfied enough)
if (nl > maxn)
break;
// now, find the rarest 2-byte sequence within this
// length of literals and search for that instead.
// Much faster than just using the start
var mmd = Math.min(dif, nl - 2);
var md = 0;
for (var j = 0; j < mmd; ++j) {
var ti = i - dif + j & 32767;
var pti = prev[ti];
var cd = ti - pti & 32767;
if (cd > md)
md = cd, pimod = ti;
}
}
}
// check the previous match
imod = pimod, pimod = prev[imod];
dif += imod - pimod & 32767;
}
}
// d will be nonzero only when a match was found
if (d) {
// store both dist and len data in one int32
// Make sure this is recognized as a len/dist with 28th bit (2^28)
syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];
var lin = revfl[l] & 31, din = revfd[d] & 31;
eb += fleb[lin] + fdeb[din];
++lf[257 + lin];
++df[din];
wi = i + l;
++lc_1;
}
else {
syms[li++] = dat[i];
++lf[dat[i]];
}
}
}
for (i = Math.max(i, wi); i < s; ++i) {
syms[li++] = dat[i];
++lf[dat[i]];
}
pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
if (!lst) {
st.r = (pos & 7) | w[(pos / 8) | 0] << 3;
// shft(pos) now 1 less if pos & 7 != 0
pos -= 7;
st.h = head, st.p = prev, st.i = i, st.w = wi;
}
}
else {
for (var i = st.w || 0; i < s + lst; i += 65535) {
// end
var e = i + 65535;
if (e >= s) {
// write final block
w[(pos / 8) | 0] = lst;
e = s;
}
pos = wfblk(w, pos + 1, dat.subarray(i, e));
}
st.i = s;
}
return slc(o, 0, pre + shft(pos) + post);
};
// CRC32 table
var crct = /*#__PURE__*/ (function () {
var t = new Int32Array(256);
for (var i = 0; i < 256; ++i) {
var c = i, k = 9;
while (--k)
c = ((c & 1) && -306674912) ^ (c >>> 1);
t[i] = c;
}
return t;
})();
// CRC32
var crc = function () {
var c = -1;
return {
p: function (d) {
// closures have awful performance
var cr = c;
for (var i = 0; i < d.length; ++i)
cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);
c = cr;
},
d: function () { return ~c; }
};
};
// Adler32
var adler = function () {
var a = 1, b = 0;
return {
p: function (d) {
// closures have awful performance
var n = a, m = b;
var l = d.length | 0;
for (var i = 0; i != l;) {
var e = Math.min(i + 2655, l);
for (; i < e; ++i)
m += n += d[i];
n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
}
a = n, b = m;
},
d: function () {
a %= 65521, b %= 65521;
return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);
}
};
};
;
// deflate with opts
var dopt = function (dat, opt, pre, post, st) {
if (!st) {
st = { l: 1 };
if (opt.dictionary) {
var dict = opt.dictionary.subarray(-32768);
var newDat = new u8(dict.length + dat.length);
newDat.set(dict);
newDat.set(dat, dict.length);
dat = newDat;
st.w = dict.length;
}
}
return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);
};
// Walmart object spread
var mrg = function (a, b) {
var o = {};
for (var k in a)
o[k] = a[k];
for (var k in b)
o[k] = b[k];
return o;
};
// worker clone
// This is possibly the craziest part of the entire codebase, despite how simple it may seem.
// The only parameter to this function is a closure that returns an array of variables outside of the function scope.
// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
// This took me three weeks to figure out how to do.
var wcln = function (fn, fnStr, td) {
var dt = fn();
var st = fn.toString();
var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(',');
for (var i = 0; i < dt.length; ++i) {
var v = dt[i], k = ks[i];
if (typeof v == 'function') {
fnStr += ';' + k + '=';
var st_1 = v.toString();
if (v.prototype) {
// for global objects
if (st_1.indexOf('[native code]') != -1) {
var spInd = st_1.indexOf(' ', 8) + 1;
fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
}
else {
fnStr += st_1;
for (var t in v.prototype)
fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
}
}
else
fnStr += st_1;
}
else
td[k] = v;
}
return fnStr;
};
var ch = [];
// clone bufs
var cbfs = function (v) {
var tl = [];
for (var k in v) {
if (v[k].buffer) {
tl.push((v[k] = new v[k].constructor(v[k])).buffer);
}
}
return tl;
};
// use a worker to execute code
var wrkr = function (fns, init, id, cb) {
if (!ch[id]) {
var fnStr = '', td_1 = {}, m = fns.length - 1;
for (var i = 0; i < m; ++i)
fnStr = wcln(fns[i], fnStr, td_1);
ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };
}
var td = mrg({}, ch[id].e);
return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
};
// base async inflate fn
var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, esm_ec, hMap, max, bits, bits16, shft, slc, esm_err, inflt, inflateSync, pbf, gopt]; };
var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };
// gzip extra
var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };
// gunzip extra
var guze = function () { return [gzs, gzl]; };
// zlib extra
var zle = function () { return [zlh, wbytes, adler]; };
// unzlib extra
var zule = function () { return [zls]; };
// post buf
var pbf = function (msg) { return postMessage(msg, [msg.buffer]); };
// get opts
var gopt = function (o) { return o && {
out: o.size && new u8(o.size),
dictionary: o.dictionary
}; };
// async helper
var cbify = function (dat, opts, fns, init, id, cb) {
var w = wrkr(fns, init, id, function (err, dat) {
w.terminate();
cb(err, dat);
});
w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
return function () { w.terminate(); };
};
// auto stream
var astrm = function (strm) {
strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };
return function (ev) {
if (ev.data.length) {
strm.push(ev.data[0], ev.data[1]);
postMessage([ev.data[0].length]);
}
else
strm.flush();
};
};
// async stream attach
var astrmify = function (fns, strm, opts, init, id, flush, ext) {
var t;
var w = wrkr(fns, init, id, function (err, dat) {
if (err)
w.terminate(), strm.ondata.call(strm, err);
else if (!Array.isArray(dat))
ext(dat);
else if (dat.length == 1) {
strm.queuedSize -= dat[0];
if (strm.ondrain)
strm.ondrain(dat[0]);
}
else {
if (dat[1])
w.terminate();
strm.ondata.call(strm, err, dat[0], dat[1]);
}
});
w.postMessage(opts);
strm.queuedSize = 0;
strm.push = function (d, f) {
if (!strm.ondata)
esm_err(5);
if (t)
strm.ondata(esm_err(4, 0, 1), null, !!f);
strm.queuedSize += d.length;
w.postMessage([d, t = f], [d.buffer]);
};
strm.terminate = function () { w.terminate(); };
if (flush) {
strm.flush = function () { w.postMessage([]); };
}
};
// read 2 bytes
var esm_b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };
// read 4 bytes
var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };
var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };
// write bytes
var wbytes = function (d, b, v) {
for (; v; ++b)
d[b] = v, v >>>= 8;
};
// gzip header
var gzh = function (c, o) {
var fn = o.filename;
c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix
if (o.mtime != 0)
wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));
if (fn) {
c[3] = 8;
for (var i = 0; i <= fn.length; ++i)
c[i + 10] = fn.charCodeAt(i);
}
};
// gzip footer: -8 to -4 = CRC, -4 to -0 is length
// gzip start
var gzs = function (d) {
if (d[0] != 31 || d[1] != 139 || d[2] != 8)
esm_err(6, 'invalid gzip data');
var flg = d[3];
var st = 10;
if (flg & 4)
st += (d[10] | d[11] << 8) + 2;
for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
;
return st + (flg & 2);
};
// gzip length
var gzl = function (d) {
var l = d.length;
return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
};
// gzip header length
var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); };
// zlib header
var zlh = function (c, o) {
var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);
c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;
if (o.dictionary) {
var h = adler();
h.p(o.dictionary);
wbytes(c, 2, h.d());
}
};
// zlib start
var zls = function (d, dict) {
if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
esm_err(6, 'invalid zlib data');
if ((d[1] >> 5 & 1) == +!dict)
esm_err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
return (d[1] >> 3 & 4) + 2;
};
function StrmOpt(opts, cb) {
if (typeof opts == 'function')
cb = opts, opts = {};
this.ondata = cb;
return opts;
}
/**
* Streaming DEFLATE compression
*/
var Deflate = /*#__PURE__*/ (function () {
function Deflate(opts, cb) {
if (typeof opts == 'function')
cb = opts, opts = {};
this.ondata = cb;
this.o = opts || {};
this.s = { l: 0, i: 32768, w: 32768, z: 32768 };
// Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev
// 98304 = 32768 (lookback) + 65536 (common chunk size)
this.b = new u8(98304);
if (this.o.dictionary) {
var dict = this.o.dictionary.subarray(-32768);
this.b.set(dict, 32768 - dict.length);
this.s.i = 32768 - dict.length;
}
}
Deflate.prototype.p = function (c, f) {
this.ondata(dopt(c, this.o, 0, 0, this.s), f);
};
/**
* Pushes a chunk to be deflated
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
Deflate.prototype.push = function (chunk, final) {
if (!this.ondata)
esm_err(5);
if (this.s.l)
esm_err(4);
var endLen = chunk.length + this.s.z;
if (endLen > this.b.length) {
if (endLen > 2 * this.b.length - 32768) {
var newBuf = new u8(endLen & -32768);
newBuf.set(this.b.subarray(0, this.s.z));
this.b = newBuf;
}
var split = this.b.length - this.s.z;
this.b.set(chunk.subarray(0, split), this.s.z);
this.s.z = this.b.length;
this.p(this.b, false);
this.b.set(this.b.subarray(-32768));
this.b.set(chunk.subarray(split), 32768);
this.s.z = chunk.length - split + 32768;
this.s.i = 32766, this.s.w = 32768;
}
else {
this.b.set(chunk, this.s.z);
this.s.z += chunk.length;
}
this.s.l = final & 1;
if (this.s.z > this.s.w + 8191 || final) {
this.p(this.b, final || false);
this.s.w = this.s.i, this.s.i -= 2;
}
};
/**
* Flushes buffered uncompressed data. Useful to immediately retrieve the
* deflated output for small inputs.
*/
Deflate.prototype.flush = function () {
if (!this.ondata)
esm_err(5);
if (this.s.l)
esm_err(4);
this.p(this.b, false);
this.s.w = this.s.i, this.s.i -= 2;
};
return Deflate;
}());
/**
* Asynchronous streaming DEFLATE compression
*/
var AsyncDeflate = /*#__PURE__*/ (function () {
function AsyncDeflate(opts, cb) {
astrmify([
bDflt,
function () { return [astrm, Deflate]; }
], this, StrmOpt.call(this, opts, cb), function (ev) {
var strm = new Deflate(ev.data);
onmessage = astrm(strm);
}, 6, 1);
}
return AsyncDeflate;
}());
function deflate(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
return cbify(data, opts, [
bDflt,
], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);
}
/**
* Compresses data with DEFLATE without any wrapper
* @param data The data to compress
* @param opts The compression options
* @returns The deflated version of the data
*/
function deflateSync(data, opts) {
return dopt(data, opts || {}, 0, 0);
}
/**
* Streaming DEFLATE decompression
*/
var Inflate = /*#__PURE__*/ (function () {
function Inflate(opts, cb) {
// no StrmOpt here to avoid adding to workerizer
if (typeof opts == 'function')
cb = opts, opts = {};
this.ondata = cb;
var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
this.s = { i: 0, b: dict ? dict.length : 0 };
this.o = new u8(32768);
this.p = new u8(0);
if (dict)
this.o.set(dict);
}
Inflate.prototype.e = function (c) {
if (!this.ondata)
esm_err(5);
if (this.d)
esm_err(4);
if (!this.p.length)
this.p = c;
else if (c.length) {
var n = new u8(this.p.length + c.length);
n.set(this.p), n.set(c, this.p.length), this.p = n;
}
};
Inflate.prototype.c = function (final) {
this.s.i = +(this.d = final || false);
var bts = this.s.b;
var dt = inflt(this.p, this.s, this.o);
this.ondata(slc(dt, bts, this.s.b), this.d);
this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;
};
/**
* Pushes a chunk to be inflated
* @param chunk The chunk to push
* @param final Whether this is the final chunk
*/
Inflate.prototype.push = function (chunk, final) {
this.e(chunk), this.c(final);
};
return Inflate;
}());
/**
* Asynchronous streaming DEFLATE decompression
*/
var AsyncInflate = /*#__PURE__*/ (function () {
function AsyncInflate(opts, cb) {
astrmify([
bInflt,
function () { return [astrm, Inflate]; }
], this, StrmOpt.call(this, opts, cb), function (ev) {
var strm = new Inflate(ev.data);
onmessage = astrm(strm);
}, 7, 0);
}
return AsyncInflate;
}());
function inflate(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
return cbify(data, opts, [
bInflt
], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb);
}
/**
* Expands DEFLATE data with no wrapper
* @param data The data to decompress
* @param opts The decompression options
* @returns The decompressed version of the data
*/
function inflateSync(data, opts) {
return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.
/**
* Streaming GZIP compression
*/
var Gzip = /*#__PURE__*/ (function () {
function Gzip(opts, cb) {
this.c = crc();
this.l = 0;
this.v = 1;
Deflate.call(this, opts, cb);
}
/**
* Pushes a chunk to be GZIPped
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
Gzip.prototype.push = function (chunk, final) {
this.c.p(chunk);
this.l += chunk.length;
Deflate.prototype.push.call(this, chunk, final);
};
Gzip.prototype.p = function (c, f) {
var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);
if (this.v)
gzh(raw, this.o), this.v = 0;
if (f)
wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
this.ondata(raw, f);
};
/**
* Flushes buffered uncompressed data. Useful to immediately retrieve the
* GZIPped output for small inputs.
*/
Gzip.prototype.flush = function () {
Deflate.prototype.flush.call(this);
};
return Gzip;
}());
/**
* Asynchronous streaming GZIP compression
*/
var AsyncGzip = /*#__PURE__*/ (function () {
function AsyncGzip(opts, cb) {
astrmify([
bDflt,
gze,
function () { return [astrm, Deflate, Gzip]; }
], this, StrmOpt.call(this, opts, cb), function (ev) {
var strm = new Gzip(ev.data);
onmessage = astrm(strm);
}, 8, 1);
}
return AsyncGzip;
}());
function gzip(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
return cbify(data, opts, [
bDflt,
gze,
function () { return [gzipSync]; }
], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);
}
/**
* Compresses data with GZIP
* @param data The data to compress
* @param opts The compression options
* @returns The gzipped version of the data
*/
function gzipSync(data, opts) {
if (!opts)
opts = {};
var c = crc(), l = data.length;
c.p(data);
var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
}
/**
* Streaming single or multi-member GZIP decompression
*/
var Gunzip = /*#__PURE__*/ (function () {
function Gunzip(opts, cb) {
this.v = 1;
this.r = 0;
Inflate.call(this, opts, cb);
}
/**
* Pushes a chunk to be GUNZIPped
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
Gunzip.prototype.push = function (chunk, final) {
Inflate.prototype.e.call(this, chunk);
this.r += chunk.length;
if (this.v) {
var p = this.p.subarray(this.v - 1);
var s = p.length > 3 ? gzs(p) : 4;
if (s > p.length) {
if (!final)
return;
}
else if (this.v > 1 && this.onmember) {
this.onmember(this.r - p.length);
}
this.p = p.subarray(s), this.v = 0;
}
// necessary to prevent TS from using the closure value
// This allows for workerization to function correctly
Inflate.prototype.c.call(this, final);
// process concatenated GZIP
if (this.s.f && !this.s.l && !final) {
this.v = shft(this.s.p) + 9;
this.s = { i: 0 };
this.o = new u8(0);
this.push(new u8(0), final);
}
};
return Gunzip;
}());
/**
* Asynchronous streaming single or multi-member GZIP decompression
*/
var AsyncGunzip = /*#__PURE__*/ (function () {
function AsyncGunzip(opts, cb) {
var _this = this;
astrmify([
bInflt,
guze,
function () { return [astrm, Inflate, Gunzip]; }
], this, StrmOpt.call(this, opts, cb), function (ev) {
var strm = new Gunzip(ev.data);
strm.onmember = function (offset) { return postMessage(offset); };
onmessage = astrm(strm);
}, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });
}
return AsyncGunzip;
}());
function gunzip(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
return cbify(data, opts, [
bInflt,
guze,
function () { return [gunzipSync]; }
], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb);
}
/**
* Expands GZIP data
* @param data The data to decompress
* @param opts The decompression options
* @returns The decompressed version of the data
*/
function gunzipSync(data, opts) {
var st = gzs(data);
if (st + 8 > data.length)
esm_err(6, 'invalid gzip data');
return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
}
/**
* Streaming Zlib compression
*/
var Zlib = /*#__PURE__*/ (function () {
function Zlib(opts, cb) {
this.c = adler();
this.v = 1;
Deflate.call(this, opts, cb);
}
/**
* Pushes a chunk to be zlibbed
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
Zlib.prototype.push = function (chunk, final) {
this.c.p(chunk);
Deflate.prototype.push.call(this, chunk, final);
};
Zlib.prototype.p = function (c, f) {
var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);
if (this.v)
zlh(raw, this.o), this.v = 0;
if (f)
wbytes(raw, raw.length - 4, this.c.d());
this.ondata(raw, f);
};
/**
* Flushes buffered uncompressed data. Useful to immediately retrieve the
* zlibbed output for small inputs.
*/
Zlib.prototype.flush = function () {
Deflate.prototype.flush.call(this);
};
return Zlib;
}());
/**
* Asynchronous streaming Zlib compression
*/
var AsyncZlib = /*#__PURE__*/ (function () {
function AsyncZlib(opts, cb) {
astrmify([
bDflt,
zle,
function () { return [astrm, Deflate, Zlib]; }
], this, StrmOpt.call(this, opts, cb), function (ev) {
var strm = new Zlib(ev.data);
onmessage = astrm(strm);
}, 10, 1);
}
return AsyncZlib;
}());
function zlib(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
return cbify(data, opts, [
bDflt,
zle,
function () { return [zlibSync]; }
], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);
}
/**
* Compress data with Zlib
* @param data The data to compress
* @param opts The compression options
* @returns The zlib-compressed version of the data
*/
function zlibSync(data, opts) {
if (!opts)
opts = {};
var a = adler();
a.p(data);
var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
}
/**
* Streaming Zlib decompression
*/
var Unzlib = /*#__PURE__*/ (function () {
function Unzlib(opts, cb) {
Inflate.call(this, opts, cb);
this.v = opts && opts.dictionary ? 2 : 1;
}
/**
* Pushes a chunk to be unzlibbed
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
Unzlib.prototype.push = function (chunk, final) {
Inflate.prototype.e.call(this, chunk);
if (this.v) {
if (this.p.length < 6 && !final)
return;
this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
}
if (final) {
if (this.p.length < 4)
esm_err(6, 'invalid zlib data');
this.p = this.p.subarray(0, -4);
}
// necessary to prevent TS from using the closure value
// This allows for workerization to function correctly
Inflate.prototype.c.call(this, final);
};
return Unzlib;
}());
/**
* Asynchronous streaming Zlib decompression
*/
var AsyncUnzlib = /*#__PURE__*/ (function () {
function AsyncUnzlib(opts, cb) {
astrmify([
bInflt,
zule,
function () { return [astrm, Inflate, Unzlib]; }
], this, StrmOpt.call(this, opts, cb), function (ev) {
var strm = new Unzlib(ev.data);
onmessage = astrm(strm);
}, 11, 0);
}
return AsyncUnzlib;
}());
function unzlib(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
return cbify(data, opts, [
bInflt,
zule,
function () { return [unzlibSync]; }
], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb);
}
/**
* Expands Zlib data
* @param data The data to decompress
* @param opts The decompression options
* @returns The decompressed version of the data
*/
function unzlibSync(data, opts) {
return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
// Default algorithm for compression (used because having a known output size allows faster decompression)
/**
* Streaming GZIP, Zlib, or raw DEFLATE decompression
*/
var Decompress = /*#__PURE__*/ (function () {
function Decompress(opts, cb) {
this.o = StrmOpt.call(this, opts, cb) || {};
this.G = Gunzip;
this.I = Inflate;
this.Z = Unzlib;
}
// init substream
// overriden by AsyncDecompress
Decompress.prototype.i = function () {
var _this = this;
this.s.ondata = function (dat, final) {
_this.ondata(dat, final);
};
};
/**
* Pushes a chunk to be decompressed
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
Decompress.prototype.push = function (chunk, final) {
if (!this.ondata)
esm_err(5);
if (!this.s) {
if (this.p && this.p.length) {
var n = new u8(this.p.length + chunk.length);
n.set(this.p), n.set(chunk, this.p.length);
}
else
this.p = chunk;
if (this.p.length > 2) {
this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)
? new this.G(this.o)
: ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))
? new this.I(this.o)
: new this.Z(this.o);
this.i();
this.s.push(this.p, final);
this.p = null;
}
}
else
this.s.push(chunk, final);
};
return Decompress;
}());
/**
* Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression
*/
var AsyncDecompress = /*#__PURE__*/ (function () {
function AsyncDecompress(opts, cb) {
Decompress.call(this, opts, cb);
this.queuedSize = 0;
this.G = AsyncGunzip;
this.I = AsyncInflate;
this.Z = AsyncUnzlib;
}
AsyncDecompress.prototype.i = function () {
var _this = this;
this.s.ondata = function (err, dat, final) {
_this.ondata(err, dat, final);
};
this.s.ondrain = function (size) {
_this.queuedSize -= size;
if (_this.ondrain)
_this.ondrain(size);
};
};
/**
* Pushes a chunk to be decompressed
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
AsyncDecompress.prototype.push = function (chunk, final) {
this.queuedSize += chunk.length;
Decompress.prototype.push.call(this, chunk, final);
};
return AsyncDecompress;
}());
function decompress(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
return (data[0] == 31 && data[1] == 139 && data[2] == 8)
? gunzip(data, opts, cb)
: ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
? inflate(data, opts, cb)
: unzlib(data, opts, cb);
}
/**
* Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
* @param data The data to decompress
* @param opts The decompression options
* @returns The decompressed version of the data
*/
function decompressSync(data, opts) {
return (data[0] == 31 && data[1] == 139 && data[2] == 8)
? gunzipSync(data, opts)
: ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
? inflateSync(data, opts)
: unzlibSync(data, opts);
}
// flatten a directory structure
var fltn = function (d, p, t, o) {
for (var k in d) {
var val = d[k], n = p + k, op = o;
if (Array.isArray(val))
op = mrg(o, val[1]), val = val[0];
if (val instanceof u8)
t[n] = [val, op];
else {
t[n += '/'] = [new u8(0), op];
fltn(val, n, t, o);
}
}
};
// text encoder
var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();
// text decoder
var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
// text decoder stream
var tds = 0;
try {
td.decode(et, { stream: true });
tds = 1;
}
catch (e) { }
// decode UTF8
var dutf8 = function (d) {
for (var r = '', i = 0;;) {
var c = d[i++];
var eb = (c > 127) + (c > 223) + (c > 239);
if (i + eb > d.length)
return { s: r, r: slc(d, i - 1) };
if (!eb)
r += String.fromCharCode(c);
else if (eb == 3) {
c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,
r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));
}
else if (eb & 1)
r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));
else
r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));
}
};
/**
* Streaming UTF-8 decoding
*/
var DecodeUTF8 = /*#__PURE__*/ (function () {
/**
* Creates a UTF-8 decoding stream
* @param cb The callback to call whenever data is decoded
*/
function DecodeUTF8(cb) {
this.ondata = cb;
if (tds)
this.t = new TextDecoder();
else
this.p = et;
}
/**
* Pushes a chunk to be decoded from UTF-8 binary
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
DecodeUTF8.prototype.push = function (chunk, final) {
if (!this.ondata)
esm_err(5);
final = !!final;
if (this.t) {
this.ondata(this.t.decode(chunk, { stream: true }), final);
if (final) {
if (this.t.decode().length)
esm_err(8);
this.t = null;
}
return;
}
if (!this.p)
esm_err(4);
var dat = new u8(this.p.length + chunk.length);
dat.set(this.p);
dat.set(chunk, this.p.length);
var _a = dutf8(dat), s = _a.s, r = _a.r;
if (final) {
if (r.length)
esm_err(8);
this.p = null;
}
else
this.p = r;
this.ondata(s, final);
};
return DecodeUTF8;
}());
/**
* Streaming UTF-8 encoding
*/
var EncodeUTF8 = /*#__PURE__*/ (function () {
/**
* Creates a UTF-8 decoding stream
* @param cb The callback to call whenever data is encoded
*/
function EncodeUTF8(cb) {
this.ondata = cb;
}
/**
* Pushes a chunk to be encoded to UTF-8
* @param chunk The string data to push
* @param final Whether this is the last chunk
*/
EncodeUTF8.prototype.push = function (chunk, final) {
if (!this.ondata)
esm_err(5);
if (this.d)
esm_err(4);
this.ondata(strToU8(chunk), this.d = final || false);
};
return EncodeUTF8;
}());
/**
* Converts a string into a Uint8Array for use with compression/decompression methods
* @param str The string to encode
* @param latin1 Whether or not to interpret the data as Latin-1. This should
* not need to be true unless decoding a binary string.
* @returns The string encoded in UTF-8/Latin-1 binary
*/
function strToU8(str, latin1) {
if (latin1) {
var ar_1 = new u8(str.length);
for (var i = 0; i < str.length; ++i)
ar_1[i] = str.charCodeAt(i);
return ar_1;
}
if (te)
return te.encode(str);
var l = str.length;
var ar = new u8(str.length + (str.length >> 1));
var ai = 0;
var w = function (v) { ar[ai++] = v; };
for (var i = 0; i < l; ++i) {
if (ai + 5 > ar.length) {
var n = new u8(ai + 8 + ((l - i) << 1));
n.set(ar);
ar = n;
}
var c = str.charCodeAt(i);
if (c < 128 || latin1)
w(c);
else if (c < 2048)
w(192 | (c >> 6)), w(128 | (c & 63));
else if (c > 55295 && c < 57344)
c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),
w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
else
w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
}
return slc(ar, 0, ai);
}
/**
* Converts a Uint8Array to a string
* @param dat The data to decode to string
* @param latin1 Whether or not to interpret the data as Latin-1. This should
* not need to be true unless encoding to binary string.
* @returns The original UTF-8/Latin-1 string
*/
function strFromU8(dat, latin1) {
if (latin1) {
var r = '';
for (var i = 0; i < dat.length; i += 16384)
r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
return r;
}
else if (td) {
return td.decode(dat);
}
else {
var _a = dutf8(dat), s = _a.s, r = _a.r;
if (r.length)
esm_err(8);
return s;
}
}
;
// deflate bit flag
var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };
// skip local zip header
var slzh = function (d, b) { return b + 30 + esm_b2(d, b + 26) + esm_b2(d, b + 28); };
// read zip header
var zh = function (d, b, z) {
var fnl = esm_b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(esm_b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];
return [esm_b2(d, b + 10), sc, su, fn, es + esm_b2(d, b + 30) + esm_b2(d, b + 32), off];
};
// read zip64 extra field
var z64e = function (d, b) {
for (; esm_b2(d, b) != 1; b += 4 + esm_b2(d, b + 2))
;
return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
};
// extra field length
var exfl = function (ex) {
var le = 0;
if (ex) {
for (var k in ex) {
var l = ex[k].length;
if (l > 65535)
esm_err(9);
le += l + 4;
}
}
return le;
};
// write zip header
var wzh = function (d, b, f, fn, u, c, ce, co) {
var fl = fn.length, ex = f.extra, col = co && co.length;
var exl = exfl(ex);
wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;
if (ce != null)
d[b++] = 20, d[b++] = f.os;
d[b] = 20, b += 2; // spec compliance? what's that?
d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;
d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
if (y < 0 || y > 119)
esm_err(10);
wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4;
if (c != -1) {
wbytes(d, b, f.crc);
wbytes(d, b + 4, c < 0 ? -c - 2 : c);
wbytes(d, b + 8, f.size);
}
wbytes(d, b + 12, fl);
wbytes(d, b + 14, exl), b += 16;
if (ce != null) {
wbytes(d, b, col);
wbytes(d, b + 6, f.attrs);
wbytes(d, b + 10, ce), b += 14;
}
d.set(fn, b);
b += fl;
if (exl) {
for (var k in ex) {
var exf = ex[k], l = exf.length;
wbytes(d, b, +k);
wbytes(d, b + 2, l);
d.set(exf, b + 4), b += 4 + l;
}
}
if (col)
d.set(co, b), b += col;
return b;
};
// write zip footer (end of central directory)
var wzf = function (o, b, c, d, e) {
wbytes(o, b, 0x6054B50); // skip disk
wbytes(o, b + 8, c);
wbytes(o, b + 10, c);
wbytes(o, b + 12, d);
wbytes(o, b + 16, e);
};
/**
* A pass-through stream to keep data uncompressed in a ZIP archive.
*/
var ZipPassThrough = /*#__PURE__*/ (function () {
/**
* Creates a pass-through stream that can be added to ZIP archives
* @param filename The filename to associate with this data stream
*/
function ZipPassThrough(filename) {
this.filename = filename;
this.c = crc();
this.size = 0;
this.compression = 0;
}
/**
* Processes a chunk and pushes to the output stream. You can override this
* method in a subclass for custom behavior, but by default this passes
* the data through. You must call this.ondata(err, chunk, final) at some
* point in this method.
* @param chunk The chunk to process
* @param final Whether this is the last chunk
*/
ZipPassThrough.prototype.process = function (chunk, final) {
this.ondata(null, chunk, final);
};
/**
* Pushes a chunk to be added. If you are subclassing this with a custom
* compression algorithm, note that you must push data from the source
* file only, pre-compression.
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
ZipPassThrough.prototype.push = function (chunk, final) {
if (!this.ondata)
esm_err(5);
this.c.p(chunk);
this.size += chunk.length;
if (final)
this.crc = this.c.d();
this.process(chunk, final || false);
};
return ZipPassThrough;
}());
// I don't extend because TypeScript extension adds 1kB of runtime bloat
/**
* Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate
* for better performance
*/
var ZipDeflate = /*#__PURE__*/ (function () {
/**
* Creates a DEFLATE stream that can be added to ZIP archives
* @param filename The filename to associate with this data stream
* @param opts The compression options
*/
function ZipDeflate(filename, opts) {
var _this = this;
if (!opts)
opts = {};
ZipPassThrough.call(this, filename);
this.d = new Deflate(opts, function (dat, final) {
_this.ondata(null, dat, final);
});
this.compression = 8;
this.flag = dbf(opts.level);
}
ZipDeflate.prototype.process = function (chunk, final) {
try {
this.d.push(chunk, final);
}
catch (e) {
this.ondata(e, null, final);
}
};
/**
* Pushes a chunk to be deflated
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
ZipDeflate.prototype.push = function (chunk, final) {
ZipPassThrough.prototype.push.call(this, chunk, final);
};
return ZipDeflate;
}());
/**
* Asynchronous streaming DEFLATE compression for ZIP archives
*/
var AsyncZipDeflate = /*#__PURE__*/ (function () {
/**
* Creates an asynchronous DEFLATE stream that can be added to ZIP archives
* @param filename The filename to associate with this data stream
* @param opts The compression options
*/
function AsyncZipDeflate(filename, opts) {
var _this = this;
if (!opts)
opts = {};
ZipPassThrough.call(this, filename);
this.d = new AsyncDeflate(opts, function (err, dat, final) {
_this.ondata(err, dat, final);
});
this.compression = 8;
this.flag = dbf(opts.level);
this.terminate = this.d.terminate;
}
AsyncZipDeflate.prototype.process = function (chunk, final) {
this.d.push(chunk, final);
};
/**
* Pushes a chunk to be deflated
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
AsyncZipDeflate.prototype.push = function (chunk, final) {
ZipPassThrough.prototype.push.call(this, chunk, final);
};
return AsyncZipDeflate;
}());
// TODO: Better tree shaking
/**
* A zippable archive to which files can incrementally be added
*/
var Zip = /*#__PURE__*/ (function () {
/**
* Creates an empty ZIP archive to which files can be added
* @param cb The callback to call whenever data for the generated ZIP archive
* is available
*/
function Zip(cb) {
this.ondata = cb;
this.u = [];
this.d = 1;
}
/**
* Adds a file to the ZIP archive
* @param file The file stream to add
*/
Zip.prototype.add = function (file) {
var _this = this;
if (!this.ondata)
esm_err(5);
// finishing or finished
if (this.d & 2)
this.ondata(esm_err(4 + (this.d & 1) * 8, 0, 1), null, false);
else {
var f = strToU8(file.filename), fl_1 = f.length;
var com = file.comment, o = com && strToU8(com);
var u = fl_1 != file.filename.length || (o && (com.length != o.length));
var hl_1 = fl_1 + exfl(file.extra) + 30;
if (fl_1 > 65535)
this.ondata(esm_err(11, 0, 1), null, false);
var header = new u8(hl_1);
wzh(header, 0, file, f, u, -1);
var chks_1 = [header];
var pAll_1 = function () {
for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {
var chk = chks_2[_i];
_this.ondata(null, chk, false);
}
chks_1 = [];
};
var tr_1 = this.d;
this.d = 0;
var ind_1 = this.u.length;
var uf_1 = mrg(file, {
f: f,
u: u,
o: o,
t: function () {
if (file.terminate)
file.terminate();
},
r: function () {
pAll_1();
if (tr_1) {
var nxt = _this.u[ind_1 + 1];
if (nxt)
nxt.r();
else
_this.d = 1;
}
tr_1 = 1;
}
});
var cl_1 = 0;
file.ondata = function (err, dat, final) {
if (err) {
_this.ondata(err, dat, final);
_this.terminate();
}
else {
cl_1 += dat.length;
chks_1.push(dat);
if (final) {
var dd = new u8(16);
wbytes(dd, 0, 0x8074B50);
wbytes(dd, 4, file.crc);
wbytes(dd, 8, cl_1);
wbytes(dd, 12, file.size);
chks_1.push(dd);
uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;
if (tr_1)
uf_1.r();
tr_1 = 1;
}
else if (tr_1)
pAll_1();
}
};
this.u.push(uf_1);
}
};
/**
* Ends the process of adding files and prepares to emit the final chunks.
* This *must* be called after adding all desired files for the resulting
* ZIP file to work properly.
*/
Zip.prototype.end = function () {
var _this = this;
if (this.d & 2) {
this.ondata(esm_err(4 + (this.d & 1) * 8, 0, 1), null, true);
return;
}
if (this.d)
this.e();
else
this.u.push({
r: function () {
if (!(_this.d & 1))
return;
_this.u.splice(-1, 1);
_this.e();
},
t: function () { }
});
this.d = 3;
};
Zip.prototype.e = function () {
var bt = 0, l = 0, tl = 0;
for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
var f = _a[_i];
tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
}
var out = new u8(tl + 22);
for (var _b = 0, _c = this.u; _b < _c.length; _b++) {
var f = _c[_b];
wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);
bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
}
wzf(out, bt, this.u.length, tl, l);
this.ondata(null, out, true);
this.d = 2;
};
/**
* A method to terminate any internal workers used by the stream. Subsequent
* calls to add() will fail.
*/
Zip.prototype.terminate = function () {
for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
var f = _a[_i];
f.t();
}
this.d = 2;
};
return Zip;
}());
function zip(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
var r = {};
fltn(data, '', r, opts);
var k = Object.keys(r);
var lft = k.length, o = 0, tot = 0;
var slft = lft, files = new Array(lft);
var term = [];
var tAll = function () {
for (var i = 0; i < term.length; ++i)
term[i]();
};
var cbd = function (a, b) {
mt(function () { cb(a, b); });
};
mt(function () { cbd = cb; });
var cbf = function () {
var out = new u8(tot + 22), oe = o, cdl = tot - o;
tot = 0;
for (var i = 0; i < slft; ++i) {
var f = files[i];
try {
var l = f.c.length;
wzh(out, tot, f, f.f, f.u, l);
var badd = 30 + f.f.length + exfl(f.extra);
var loc = tot + badd;
out.set(f.c, loc);
wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
}
catch (e) {
return cbd(e, null);
}
}
wzf(out, o, files.length, cdl, oe);
cbd(null, out);
};
if (!lft)
cbf();
var _loop_1 = function (i) {
var fn = k[i];
var _a = r[fn], file = _a[0], p = _a[1];
var c = crc(), size = file.length;
c.p(file);
var f = strToU8(fn), s = f.length;
var com = p.comment, m = com && strToU8(com), ms = m && m.length;
var exl = exfl(p.extra);
var compression = p.level == 0 ? 0 : 8;
var cbl = function (e, d) {
if (e) {
tAll();
cbd(e, null);
}
else {
var l = d.length;
files[i] = mrg(p, {
size: size,
crc: c.d(),
c: d,
f: f,
m: m,
u: s != fn.length || (m && (com.length != ms)),
compression: compression
});
o += 30 + s + exl + l;
tot += 76 + 2 * (s + exl) + (ms || 0) + l;
if (!--lft)
cbf();
}
};
if (s > 65535)
cbl(esm_err(11, 0, 1), null);
if (!compression)
cbl(null, file);
else if (size < 160000) {
try {
cbl(null, deflateSync(file, p));
}
catch (e) {
cbl(e, null);
}
}
else
term.push(deflate(file, p, cbl));
};
// Cannot use lft because it can decrease
for (var i = 0; i < slft; ++i) {
_loop_1(i);
}
return tAll;
}
/**
* Synchronously creates a ZIP file. Prefer using `zip` for better performance
* with more than one file.
* @param data The directory structure for the ZIP archive
* @param opts The main options, merged with per-file options
* @returns The generated ZIP archive
*/
function zipSync(data, opts) {
if (!opts)
opts = {};
var r = {};
var files = [];
fltn(data, '', r, opts);
var o = 0;
var tot = 0;
for (var fn in r) {
var _a = r[fn], file = _a[0], p = _a[1];
var compression = p.level == 0 ? 0 : 8;
var f = strToU8(fn), s = f.length;
var com = p.comment, m = com && strToU8(com), ms = m && m.length;
var exl = exfl(p.extra);
if (s > 65535)
esm_err(11);
var d = compression ? deflateSync(file, p) : file, l = d.length;
var c = crc();
c.p(file);
files.push(mrg(p, {
size: file.length,
crc: c.d(),
c: d,
f: f,
m: m,
u: s != fn.length || (m && (com.length != ms)),
o: o,
compression: compression
}));
o += 30 + s + exl + l;
tot += 76 + 2 * (s + exl) + (ms || 0) + l;
}
var out = new u8(tot + 22), oe = o, cdl = tot - o;
for (var i = 0; i < files.length; ++i) {
var f = files[i];
wzh(out, f.o, f, f.f, f.u, f.c.length);
var badd = 30 + f.f.length + exfl(f.extra);
out.set(f.c, f.o + badd);
wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
}
wzf(out, o, files.length, cdl, oe);
return out;
}
/**
* Streaming pass-through decompression for ZIP archives
*/
var UnzipPassThrough = /*#__PURE__*/ (function () {
function UnzipPassThrough() {
}
UnzipPassThrough.prototype.push = function (data, final) {
this.ondata(null, data, final);
};
UnzipPassThrough.compression = 0;
return UnzipPassThrough;
}());
/**
* Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for
* better performance.
*/
var UnzipInflate = /*#__PURE__*/ (function () {
/**
* Creates a DEFLATE decompression that can be used in ZIP archives
*/
function UnzipInflate() {
var _this = this;
this.i = new Inflate(function (dat, final) {
_this.ondata(null, dat, final);
});
}
UnzipInflate.prototype.push = function (data, final) {
try {
this.i.push(data, final);
}
catch (e) {
this.ondata(e, null, final);
}
};
UnzipInflate.compression = 8;
return UnzipInflate;
}());
/**
* Asynchronous streaming DEFLATE decompression for ZIP archives
*/
var AsyncUnzipInflate = /*#__PURE__*/ (function () {
/**
* Creates a DEFLATE decompression that can be used in ZIP archives
*/
function AsyncUnzipInflate(_, sz) {
var _this = this;
if (sz < 320000) {
this.i = new Inflate(function (dat, final) {
_this.ondata(null, dat, final);
});
}
else {
this.i = new AsyncInflate(function (err, dat, final) {
_this.ondata(err, dat, final);
});
this.terminate = this.i.terminate;
}
}
AsyncUnzipInflate.prototype.push = function (data, final) {
if (this.i.terminate)
data = slc(data, 0);
this.i.push(data, final);
};
AsyncUnzipInflate.compression = 8;
return AsyncUnzipInflate;
}());
/**
* A ZIP archive decompression stream that emits files as they are discovered
*/
var Unzip = /*#__PURE__*/ (function () {
/**
* Creates a ZIP decompression stream
* @param cb The callback to call whenever a file in the ZIP archive is found
*/
function Unzip(cb) {
this.onfile = cb;
this.k = [];
this.o = {
0: UnzipPassThrough
};
this.p = et;
}
/**
* Pushes a chunk to be unzipped
* @param chunk The chunk to push
* @param final Whether this is the last chunk
*/
Unzip.prototype.push = function (chunk, final) {
var _this = this;
if (!this.onfile)
esm_err(5);
if (!this.p)
esm_err(4);
if (this.c > 0) {
var len = Math.min(this.c, chunk.length);
var toAdd = chunk.subarray(0, len);
this.c -= len;
if (this.d)
this.d.push(toAdd, !this.c);
else
this.k[0].push(toAdd);
chunk = chunk.subarray(len);
if (chunk.length)
return this.push(chunk, final);
}
else {
var f = 0, i = 0, is = void 0, buf = void 0;
if (!this.p.length)
buf = chunk;
else if (!chunk.length)
buf = this.p;
else {
buf = new u8(this.p.length + chunk.length);
buf.set(this.p), buf.set(chunk, this.p.length);
}
var l = buf.length, oc = this.c, add = oc && this.d;
var _loop_2 = function () {
var _a;
var sig = b4(buf, i);
if (sig == 0x4034B50) {
f = 1, is = i;
this_1.d = null;
this_1.c = 0;
var bf = esm_b2(buf, i + 6), cmp_1 = esm_b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = esm_b2(buf, i + 26), es = esm_b2(buf, i + 28);
if (l > i + 30 + fnl + es) {
var chks_3 = [];
this_1.k.unshift(chks_3);
f = 2;
var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);
var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);
if (sc_1 == 4294967295) {
_a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];
}
else if (dd)
sc_1 = -1;
i += es;
this_1.c = sc_1;
var d_1;
var file_1 = {
name: fn_1,
compression: cmp_1,
start: function () {
if (!file_1.ondata)
esm_err(5);
if (!sc_1)
file_1.ondata(null, et, true);
else {
var ctr = _this.o[cmp_1];
if (!ctr)
file_1.ondata(esm_err(14, 'unknown compression type ' + cmp_1, 1), null, false);
d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };
for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {
var dat = chks_4[_i];
d_1.push(dat, false);
}
if (_this.k[0] == chks_3 && _this.c)
_this.d = d_1;
else
d_1.push(et, true);
}
},
terminate: function () {
if (d_1 && d_1.terminate)
d_1.terminate();
}
};
if (sc_1 >= 0)
file_1.size = sc_1, file_1.originalSize = su_1;
this_1.onfile(file_1);
}
return "break";
}
else if (oc) {
if (sig == 0x8074B50) {
is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
return "break";
}
else if (sig == 0x2014B50) {
is = i -= 4, f = 3, this_1.c = 0;
return "break";
}
}
};
var this_1 = this;
for (; i < l - 4; ++i) {
var state_1 = _loop_2();
if (state_1 === "break")
break;
}
this.p = et;
if (oc < 0) {
var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);
if (add)
add.push(dat, !!f);
else
this.k[+(f == 2)].push(dat);
}
if (f & 2)
return this.push(buf.subarray(i), final);
this.p = buf.subarray(i);
}
if (final) {
if (this.c)
esm_err(13);
this.p = null;
}
};
/**
* Registers a decoder with the stream, allowing for files compressed with
* the compression type provided to be expanded correctly
* @param decoder The decoder constructor
*/
Unzip.prototype.register = function (decoder) {
this.o[decoder.compression] = decoder;
};
return Unzip;
}());
var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };
function unzip(data, opts, cb) {
if (!cb)
cb = opts, opts = {};
if (typeof cb != 'function')
esm_err(7);
var term = [];
var tAll = function () {
for (var i = 0; i < term.length; ++i)
term[i]();
};
var files = {};
var cbd = function (a, b) {
mt(function () { cb(a, b); });
};
mt(function () { cbd = cb; });
var e = data.length - 22;
for (; b4(data, e) != 0x6054B50; --e) {
if (!e || data.length - e > 65558) {
cbd(esm_err(13, 0, 1), null);
return tAll;
}
}
;
var lft = esm_b2(data, e + 8);
if (lft) {
var c = lft;
var o = b4(data, e + 16);
var z = o == 4294967295 || c == 65535;
if (z) {
var ze = b4(data, e - 12);
z = b4(data, ze) == 0x6064B50;
if (z) {
c = lft = b4(data, ze + 32);
o = b4(data, ze + 48);
}
}
var fltr = opts && opts.filter;
var _loop_3 = function (i) {
var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
o = no;
var cbl = function (e, d) {
if (e) {
tAll();
cbd(e, null);
}
else {
if (d)
files[fn] = d;
if (!--lft)
cbd(null, files);
}
};
if (!fltr || fltr({
name: fn,
size: sc,
originalSize: su,
compression: c_1
})) {
if (!c_1)
cbl(null, slc(data, b, b + sc));
else if (c_1 == 8) {
var infl = data.subarray(b, b + sc);
// Synchronously decompress under 512KB, or barely-compressed data
if (su < 524288 || sc > 0.8 * su) {
try {
cbl(null, inflateSync(infl, { out: new u8(su) }));
}
catch (e) {
cbl(e, null);
}
}
else
term.push(inflate(infl, { size: su }, cbl));
}
else
cbl(esm_err(14, 'unknown compression type ' + c_1, 1), null);
}
else
cbl(null, null);
};
for (var i = 0; i < c; ++i) {
_loop_3(i);
}
}
else
cbd(null, {});
return tAll;
}
/**
* Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
* performance with more than one file.
* @param data The raw compressed ZIP file
* @param opts The ZIP extraction options
* @returns The decompressed files
*/
function unzipSync(data, opts) {
var files = {};
var e = data.length - 22;
for (; b4(data, e) != 0x6054B50; --e) {
if (!e || data.length - e > 65558)
esm_err(13);
}
;
var c = esm_b2(data, e + 8);
if (!c)
return {};
var o = b4(data, e + 16);
var z = o == 4294967295 || c == 65535;
if (z) {
var ze = b4(data, e - 12);
z = b4(data, ze) == 0x6064B50;
if (z) {
c = b4(data, ze + 32);
o = b4(data, ze + 48);
}
}
var fltr = opts && opts.filter;
for (var i = 0; i < c; ++i) {
var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
o = no;
if (!fltr || fltr({
name: fn,
size: sc,
originalSize: su,
compression: c_2
})) {
if (!c_2)
files[fn] = slc(data, b, b + sc);
else if (c_2 == 8)
files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
else
esm_err(14, 'unknown compression type ' + c_2);
}
}
return files;
}
// CONCATENATED MODULE: ./assets/services/zip.js
function zipAsync(file) {
return new Promise((res, rej) => {
zip(file, { mtime: new Date('1/1/1980') }, (err, data) => {
if (err) {
rej(err);
return;
}
res(data);
});
});
}
function unzipAsync(data) {
return new Promise((res, rej) => {
unzip(data, {}, (err, data) => {
if (err) {
rej(err);
return;
}
res(data);
});
});
}
// CONCATENATED MODULE: ./assets/services/pool.js
const poolAbi = [
{
inputs: [
{
internalType: "contract IVerifier",
name: "_verifier2",
type: "address",
},
{
internalType: "contract IVerifier",
name: "_verifier16",
type: "address",
},
{
internalType: "uint32",
name: "_levels",
type: "uint32",
},
{
internalType: "address",
name: "_hasher",
type: "address",
},
{
internalType: "contract IERC6777",
name: "_token",
type: "address",
},
{
internalType: "address",
name: "_omniBridge",
type: "address",
},
{
internalType: "address",
name: "_l1Unwrapper",
type: "address",
},
{
internalType: "address",
name: "_governance",
type: "address",
},
{
internalType: "uint256",
name: "_l1ChainId",
type: "uint256",
},
{
internalType: "address",
name: "_multisig",
type: "address",
},
],
stateMutability: "nonpayable",
type: "constructor",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "bytes32",
name: "commitment",
type: "bytes32",
},
{
indexed: false,
internalType: "uint256",
name: "index",
type: "uint256",
},
{
indexed: false,
internalType: "bytes",
name: "encryptedOutput",
type: "bytes",
},
],
name: "NewCommitment",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "bytes32",
name: "nullifier",
type: "bytes32",
},
],
name: "NewNullifier",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "address",
name: "owner",
type: "address",
},
{
indexed: false,
internalType: "bytes",
name: "key",
type: "bytes",
},
],
name: "PublicKey",
type: "event",
},
{
inputs: [],
name: "FIELD_SIZE",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "MAX_EXT_AMOUNT",
outputs: [
{
internalType: "int256",
name: "",
type: "int256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "MAX_FEE",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "MIN_EXT_AMOUNT_LIMIT",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "ROOT_HISTORY_SIZE",
outputs: [
{
internalType: "uint32",
name: "",
type: "uint32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "ZERO_VALUE",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "ambBridge",
outputs: [
{
internalType: "contract IAMB",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "int256",
name: "_extAmount",
type: "int256",
},
{
internalType: "uint256",
name: "_fee",
type: "uint256",
},
],
name: "calculatePublicAmount",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "pure",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "_minimalWithdrawalAmount",
type: "uint256",
},
{
internalType: "uint256",
name: "_maximumDepositAmount",
type: "uint256",
},
],
name: "configureLimits",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "currentRootIndex",
outputs: [
{
internalType: "uint32",
name: "",
type: "uint32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
name: "filledSubtrees",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "getLastRoot",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "bytes32",
name: "_left",
type: "bytes32",
},
{
internalType: "bytes32",
name: "_right",
type: "bytes32",
},
],
name: "hashLeftRight",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "hasher",
outputs: [
{
internalType: "contract IHasher",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "_minimalWithdrawalAmount",
type: "uint256",
},
{
internalType: "uint256",
name: "_maximumDepositAmount",
type: "uint256",
},
],
name: "initialize",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "isCalledByOwner",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "bytes32",
name: "_root",
type: "bytes32",
},
],
name: "isKnownRoot",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "bytes32",
name: "_nullifierHash",
type: "bytes32",
},
],
name: "isSpent",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "l1Unwrapper",
outputs: [
{
internalType: "address",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "lastBalance",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "levels",
outputs: [
{
internalType: "uint32",
name: "",
type: "uint32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "maximumDepositAmount",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "minimalWithdrawalAmount",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "multisig",
outputs: [
{
internalType: "address",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "nextIndex",
outputs: [
{
internalType: "uint32",
name: "",
type: "uint32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
name: "nullifierHashes",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "omniBridge",
outputs: [
{
internalType: "address",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract IERC6777",
name: "_token",
type: "address",
},
{
internalType: "uint256",
name: "_amount",
type: "uint256",
},
{
internalType: "bytes",
name: "_data",
type: "bytes",
},
],
name: "onTokenBridged",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
components: [
{
internalType: "bytes",
name: "proof",
type: "bytes",
},
{
internalType: "bytes32",
name: "root",
type: "bytes32",
},
{
internalType: "bytes32[]",
name: "inputNullifiers",
type: "bytes32[]",
},
{
internalType: "bytes32[2]",
name: "outputCommitments",
type: "bytes32[2]",
},
{
internalType: "uint256",
name: "publicAmount",
type: "uint256",
},
{
internalType: "bytes32",
name: "extDataHash",
type: "bytes32",
},
],
internalType: "struct TornadoPool.Proof",
name: "_args",
type: "tuple",
},
{
components: [
{
internalType: "address",
name: "recipient",
type: "address",
},
{
internalType: "int256",
name: "extAmount",
type: "int256",
},
{
internalType: "address",
name: "relayer",
type: "address",
},
{
internalType: "uint256",
name: "fee",
type: "uint256",
},
{
internalType: "bytes",
name: "encryptedOutput1",
type: "bytes",
},
{
internalType: "bytes",
name: "encryptedOutput2",
type: "bytes",
},
{
internalType: "bool",
name: "isL1Withdrawal",
type: "bool",
},
{
internalType: "uint256",
name: "l1Fee",
type: "uint256",
},
],
internalType: "struct TornadoPool.ExtData",
name: "_extData",
type: "tuple",
},
],
name: "onTransact",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "owner",
outputs: [
{
internalType: "address",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "ownerChainId",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
components: [
{
internalType: "address",
name: "owner",
type: "address",
},
{
internalType: "bytes",
name: "publicKey",
type: "bytes",
},
],
internalType: "struct TornadoPool.Account",
name: "_account",
type: "tuple",
},
],
name: "register",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
components: [
{
internalType: "address",
name: "owner",
type: "address",
},
{
internalType: "bytes",
name: "publicKey",
type: "bytes",
},
],
internalType: "struct TornadoPool.Account",
name: "_account",
type: "tuple",
},
{
components: [
{
internalType: "bytes",
name: "proof",
type: "bytes",
},
{
internalType: "bytes32",
name: "root",
type: "bytes32",
},
{
internalType: "bytes32[]",
name: "inputNullifiers",
type: "bytes32[]",
},
{
internalType: "bytes32[2]",
name: "outputCommitments",
type: "bytes32[2]",
},
{
internalType: "uint256",
name: "publicAmount",
type: "uint256",
},
{
internalType: "bytes32",
name: "extDataHash",
type: "bytes32",
},
],
internalType: "struct TornadoPool.Proof",
name: "_proofArgs",
type: "tuple",
},
{
components: [
{
internalType: "address",
name: "recipient",
type: "address",
},
{
internalType: "int256",
name: "extAmount",
type: "int256",
},
{
internalType: "address",
name: "relayer",
type: "address",
},
{
internalType: "uint256",
name: "fee",
type: "uint256",
},
{
internalType: "bytes",
name: "encryptedOutput1",
type: "bytes",
},
{
internalType: "bytes",
name: "encryptedOutput2",
type: "bytes",
},
{
internalType: "bool",
name: "isL1Withdrawal",
type: "bool",
},
{
internalType: "uint256",
name: "l1Fee",
type: "uint256",
},
],
internalType: "struct TornadoPool.ExtData",
name: "_extData",
type: "tuple",
},
],
name: "registerAndTransact",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract IERC6777",
name: "_token",
type: "address",
},
{
internalType: "address payable",
name: "_to",
type: "address",
},
{
internalType: "uint256",
name: "_balance",
type: "uint256",
},
],
name: "rescueTokens",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
name: "roots",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "token",
outputs: [
{
internalType: "contract IERC6777",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
components: [
{
internalType: "bytes",
name: "proof",
type: "bytes",
},
{
internalType: "bytes32",
name: "root",
type: "bytes32",
},
{
internalType: "bytes32[]",
name: "inputNullifiers",
type: "bytes32[]",
},
{
internalType: "bytes32[2]",
name: "outputCommitments",
type: "bytes32[2]",
},
{
internalType: "uint256",
name: "publicAmount",
type: "uint256",
},
{
internalType: "bytes32",
name: "extDataHash",
type: "bytes32",
},
],
internalType: "struct TornadoPool.Proof",
name: "_args",
type: "tuple",
},
{
components: [
{
internalType: "address",
name: "recipient",
type: "address",
},
{
internalType: "int256",
name: "extAmount",
type: "int256",
},
{
internalType: "address",
name: "relayer",
type: "address",
},
{
internalType: "uint256",
name: "fee",
type: "uint256",
},
{
internalType: "bytes",
name: "encryptedOutput1",
type: "bytes",
},
{
internalType: "bytes",
name: "encryptedOutput2",
type: "bytes",
},
{
internalType: "bool",
name: "isL1Withdrawal",
type: "bool",
},
{
internalType: "uint256",
name: "l1Fee",
type: "uint256",
},
],
internalType: "struct TornadoPool.ExtData",
name: "_extData",
type: "tuple",
},
],
name: "transact",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "verifier16",
outputs: [
{
internalType: "contract IVerifier",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "verifier2",
outputs: [
{
internalType: "contract IVerifier",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
components: [
{
internalType: "bytes",
name: "proof",
type: "bytes",
},
{
internalType: "bytes32",
name: "root",
type: "bytes32",
},
{
internalType: "bytes32[]",
name: "inputNullifiers",
type: "bytes32[]",
},
{
internalType: "bytes32[2]",
name: "outputCommitments",
type: "bytes32[2]",
},
{
internalType: "uint256",
name: "publicAmount",
type: "uint256",
},
{
internalType: "bytes32",
name: "extDataHash",
type: "bytes32",
},
],
internalType: "struct TornadoPool.Proof",
name: "_args",
type: "tuple",
},
],
name: "verifyProof",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "i",
type: "uint256",
},
],
name: "zeros",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
stateMutability: "pure",
type: "function",
},
]
// CONCATENATED MODULE: ./assets/services/bridgeHelper.js
const bridgeAbi = [
{
inputs: [
{
internalType: "contract IOmnibridge",
name: "_bridge",
type: "address",
},
{
internalType: "contract IWETH",
name: "_weth",
type: "address",
},
{
internalType: "address",
name: "_owner",
type: "address",
},
],
stateMutability: "nonpayable",
type: "constructor",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "address",
name: "owner",
type: "address",
},
{
indexed: false,
internalType: "bytes",
name: "key",
type: "bytes",
},
],
name: "PublicKey",
type: "event",
},
{
inputs: [],
name: "WETH",
outputs: [
{
internalType: "contract IWETH",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "bridge",
outputs: [
{
internalType: "contract IOmnibridge",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "address",
name: "_token",
type: "address",
},
{
internalType: "address",
name: "_to",
type: "address",
},
],
name: "claimTokens",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "address",
name: "_token",
type: "address",
},
{
internalType: "uint256",
name: "_value",
type: "uint256",
},
{
internalType: "bytes",
name: "_data",
type: "bytes",
},
],
name: "onTokenBridged",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "owner",
outputs: [
{
internalType: "address",
name: "",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
components: [
{
internalType: "address",
name: "owner",
type: "address",
},
{
internalType: "bytes",
name: "publicKey",
type: "bytes",
},
],
internalType: "struct L1Helper.Account",
name: "_account",
type: "tuple",
},
],
name: "register",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "address",
name: "_newOwner",
type: "address",
},
],
name: "transferOwnership",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "wrapAndRelayTokens",
outputs: [],
stateMutability: "payable",
type: "function",
},
{
inputs: [
{
internalType: "address",
name: "_receiver",
type: "address",
},
{
internalType: "bytes",
name: "_data",
type: "bytes",
},
],
name: "wrapAndRelayTokens",
outputs: [],
stateMutability: "payable",
type: "function",
},
{
inputs: [
{
internalType: "address",
name: "_receiver",
type: "address",
},
{
internalType: "bytes",
name: "_data",
type: "bytes",
},
{
components: [
{
internalType: "address",
name: "owner",
type: "address",
},
{
internalType: "bytes",
name: "publicKey",
type: "bytes",
},
],
internalType: "struct L1Helper.Account",
name: "_account",
type: "tuple",
},
],
name: "wrapAndRelayTokens",
outputs: [],
stateMutability: "payable",
type: "function",
},
{
inputs: [
{
internalType: "address",
name: "_receiver",
type: "address",
},
],
name: "wrapAndRelayTokens",
outputs: [],
stateMutability: "payable",
type: "function",
},
{
stateMutability: "payable",
type: "receive",
},
]
// CONCATENATED MODULE: ./assets/syncEvents.js
const { getAddress: syncEvents_getAddress } = lib_esm_utils_namespaceObject
const { StaticJsonRpcProvider: syncEvents_StaticJsonRpcProvider } = providers_lib_esm_namespaceObject
const EVENT_PATH = './static'
async function existsAsync(fileOrDir) {
try {
await Object(promises_["stat"])(fileOrDir);
return true;
} catch {
return false;
}
}
const getProvider = (chainId) => {
return new syncEvents_StaticJsonRpcProvider({ skipFetchSetup: true, url: RPC_LIST[chainId] }, chainId)
}
const getTornadoPool = (chainId, provider) => {
const TornadoPool = new Contract(POOL_CONTRACT[chainId], poolAbi, provider)
return {
TornadoPool,
BatchEventsService: new batch_BatchEventsService({
provider,
contract: TornadoPool
})
}
}
const getBridgeHelper = (chainId, provider) => {
const BridgeHelper = new Contract(BRIDGE_HELPER[chainId], bridgeAbi, provider)
return {
BridgeHelper,
BridgeEventsService: new batch_BatchEventsService({
provider,
contract: BridgeHelper
})
}
}
const loadEvents = async (fileName, deployedBlock) => {
fileName = fileName.toLowerCase()
const filePath = external_path_default.a.join(EVENT_PATH, fileName + '.zip')
if (!(await existsAsync(filePath))) {
return {
events: [],
lastBlock: deployedBlock
}
}
try {
const data = await Object(promises_["readFile"])(filePath)
const { [fileName]: content } = await unzipAsync(data)
const events = JSON.parse(new TextDecoder().decode(content))
const lastBlock = events && Array.isArray(events) && events[events.length - 1]
? events[events.length - 1].blockNumber
: deployedBlock
return {
events,
lastBlock
}
} catch {
return {
events: [],
lastBlock: deployedBlock
}
}
}
const saveEvents = async (fileName, events) => {
fileName = fileName.toLowerCase()
const filePath = external_path_default.a.join(EVENT_PATH, fileName + '.zip')
const payload = await zipAsync({
[fileName]: new TextEncoder().encode(JSON.stringify(events, null, 2) + '\n')
})
await Object(promises_["writeFile"])(filePath, payload)
}
const syncAccounts = async (chainId, BatchEventsService) => {
const fileName = `accounts_${chainId}.json`
console.log(`Syncing ${fileName}`)
const cachedEvents = await loadEvents(fileName, CHAINS[chainId].deployBlock)
const events = [...cachedEvents.events]
let fromBlock = cachedEvents.lastBlock + numbers.ONE
console.log({
cachedEvents: events.length,
cachedBlock: fromBlock
})
const { events: graphEvents, lastSyncBlock } = await getAllAccounts({
fromBlock,
chainId
})
console.log({
graphEvents: graphEvents.length,
graphBlock: lastSyncBlock
})
if (lastSyncBlock) {
events.push(...graphEvents)
fromBlock = lastSyncBlock
}
let nodeEvents = await BatchEventsService.getBatchEvents({
fromBlock,
type: 'PublicKey'
})
console.log({
nodeEvents: nodeEvents.length,
nodeBlock: nodeEvents && nodeEvents[nodeEvents.length - 1] ? nodeEvents[nodeEvents.length - 1].blockNumber : undefined
})
if (nodeEvents && nodeEvents.length) {
nodeEvents = nodeEvents.map(({ blockNumber, args }) => ({
key: args.key,
owner: syncEvents_getAddress(args.owner),
blockNumber,
}))
events.push(...nodeEvents)
}
await saveEvents(fileName, events)
}
const syncCommitments = async (chainId, BatchEventsService) => {
const fileName = `commitments_${chainId}.json`
console.log(`Syncing ${fileName}`)
const cachedEvents = await loadEvents(fileName, CHAINS[chainId].deployBlock)
const events = [...cachedEvents.events]
let fromBlock = cachedEvents.lastBlock + numbers.ONE
console.log({
cachedEvents: events.length,
cachedBlock: fromBlock
})
const { events: graphEvents, lastSyncBlock } = await getAllCommitments({
fromBlock,
chainId
})
console.log({
graphEvents: graphEvents.length,
graphBlock: lastSyncBlock
})
if (lastSyncBlock) {
events.push(...graphEvents)
fromBlock = lastSyncBlock
}
let nodeEvents = await BatchEventsService.getBatchEvents({
fromBlock,
type: 'NewCommitment'
})
console.log({
nodeEvents: nodeEvents.length,
nodeBlock: nodeEvents && nodeEvents[nodeEvents.length - 1] ? nodeEvents[nodeEvents.length - 1].blockNumber : undefined
})
if (nodeEvents && nodeEvents.length) {
nodeEvents = nodeEvents.map(({ blockNumber, transactionHash, args }) => ({
blockNumber,
transactionHash,
index: Number(args.index),
commitment: args.commitment,
encryptedOutput: args.encryptedOutput,
}))
events.push(...nodeEvents)
}
await saveEvents(fileName, events)
}
const syncNullifiers = async (chainId, BatchEventsService) => {
const fileName = `nullifiers_${chainId}.json`
console.log(`Syncing ${fileName}`)
const cachedEvents = await loadEvents(fileName, CHAINS[chainId].deployBlock)
const events = [...cachedEvents.events]
let fromBlock = cachedEvents.lastBlock + numbers.ONE
console.log({
cachedEvents: events.length,
cachedBlock: fromBlock
})
const { events: graphEvents, lastSyncBlock } = await getAllNullifiers({
fromBlock,
chainId
})
console.log({
graphEvents: graphEvents.length,
graphBlock: lastSyncBlock
})
if (lastSyncBlock) {
events.push(...graphEvents)
fromBlock = lastSyncBlock
}
let nodeEvents = await BatchEventsService.getBatchEvents({
fromBlock,
type: 'NewNullifier'
})
console.log({
nodeEvents: nodeEvents.length,
nodeBlock: nodeEvents && nodeEvents[nodeEvents.length - 1] ? nodeEvents[nodeEvents.length - 1].blockNumber : undefined
})
if (nodeEvents && nodeEvents.length) {
nodeEvents = nodeEvents.map(({ blockNumber, transactionHash, args }) => ({
blockNumber,
transactionHash,
nullifier: args.nullifier,
}))
events.push(...nodeEvents)
}
await saveEvents(fileName, events)
}
const main = async () => {
const chainId = ChainId.XDAI
const ethChainId = ChainId.MAINNET
const provider = getProvider(chainId)
const ethProvider = getProvider(ethChainId)
const { BatchEventsService } = getTornadoPool(chainId, provider)
const { BridgeEventsService } = getBridgeHelper(ethChainId, ethProvider)
console.log(`Connected with ${chainId}: (block: ${await provider.getBlockNumber()})`)
console.log(`Connected with ${ethChainId}: (block: ${await ethProvider.getBlockNumber()})`)
await syncAccounts(ethChainId, BridgeEventsService)
await syncCommitments(chainId, BatchEventsService)
await syncNullifiers(chainId, BatchEventsService)
}
main()
/***/ })
/******/ ]);