webpackJsonp([7],{ /***/ "../../../../amazon-cognito-identity-js/es/AuthenticationDetails.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var AuthenticationDetails = function () { /** * Constructs a new AuthenticationDetails object * @param {object=} data Creation options. * @param {string} data.Username User being authenticated. * @param {string} data.Password Plain-text password to authenticate with. * @param {(AttributeArg[])?} data.ValidationData Application extra metadata. */ function AuthenticationDetails(data) { _classCallCheck(this, AuthenticationDetails); var _ref = data || {}, ValidationData = _ref.ValidationData, Username = _ref.Username, Password = _ref.Password; this.validationData = ValidationData || []; this.username = Username; this.password = Password; } /** * @returns {string} the record's username */ AuthenticationDetails.prototype.getUsername = function getUsername() { return this.username; }; /** * @returns {string} the record's password */ AuthenticationDetails.prototype.getPassword = function getPassword() { return this.password; }; /** * @returns {Array} the record's validationData */ AuthenticationDetails.prototype.getValidationData = function getValidationData() { return this.validationData; }; return AuthenticationDetails; }(); /* harmony default export */ __webpack_exports__["a"] = (AuthenticationDetails); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/AuthenticationHelper.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__ = __webpack_require__("../../../../aws-sdk/browser.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BigInteger__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/BigInteger.js"); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF'; var newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.'; /** @class */ var AuthenticationHelper = function () { /** * Constructs a new AuthenticationHelper object * @param {string} PoolName Cognito user pool name. */ function AuthenticationHelper(PoolName) { _classCallCheck(this, AuthenticationHelper); this.N = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](initN, 16); this.g = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */]('2', 16); this.k = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](this.hexHash('00' + this.N.toString(16) + '0' + this.g.toString(16)), 16); this.smallAValue = this.generateRandomSmallA(); this.largeAValue = this.calculateA(this.smallAValue); this.infoBits = new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer('Caldera Derived Key', 'utf8'); this.poolName = PoolName; } /** * @returns {BigInteger} small A, a random number */ AuthenticationHelper.prototype.getSmallAValue = function getSmallAValue() { return this.smallAValue; }; /** * @returns {BigInteger} large A, a value generated from small A */ AuthenticationHelper.prototype.getLargeAValue = function getLargeAValue() { return this.largeAValue; }; /** * helper function to generate a random big integer * @returns {BigInteger} a random value. * @private */ AuthenticationHelper.prototype.generateRandomSmallA = function generateRandomSmallA() { var hexRandom = __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].crypto.lib.randomBytes(128).toString('hex'); var randomBigInt = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](hexRandom, 16); var smallABigInt = randomBigInt.mod(this.N); return smallABigInt; }; /** * helper function to generate a random string * @returns {string} a random value. * @private */ AuthenticationHelper.prototype.generateRandomString = function generateRandomString() { return __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].crypto.lib.randomBytes(40).toString('base64'); }; /** * @returns {string} Generated random value included in password hash. */ AuthenticationHelper.prototype.getRandomPassword = function getRandomPassword() { return this.randomPassword; }; /** * @returns {string} Generated random value included in devices hash. */ AuthenticationHelper.prototype.getSaltDevices = function getSaltDevices() { return this.SaltToHashDevices; }; /** * @returns {string} Value used to verify devices. */ AuthenticationHelper.prototype.getVerifierDevices = function getVerifierDevices() { return this.verifierDevices; }; /** * Generate salts and compute verifier. * @param {string} deviceGroupKey Devices to generate verifier for. * @param {string} username User to generate verifier for. * @returns {void} */ AuthenticationHelper.prototype.generateHashDevice = function generateHashDevice(deviceGroupKey, username) { this.randomPassword = this.generateRandomString(); var combinedString = '' + deviceGroupKey + username + ':' + this.randomPassword; var hashedString = this.hash(combinedString); var hexRandom = __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].crypto.lib.randomBytes(16).toString('hex'); this.SaltToHashDevices = this.padHex(new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](hexRandom, 16)); var verifierDevicesNotPadded = this.g.modPow(new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N); this.verifierDevices = this.padHex(verifierDevicesNotPadded); }; /** * Calculate the client's public value A = g^a%N * with the generated random number a * @param {BigInteger} a Randomly generated small A. * @returns {BigInteger} Computed large A. * @private */ AuthenticationHelper.prototype.calculateA = function calculateA(a) { var A = this.g.modPow(a, this.N); if (A.mod(this.N).equals(__WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */].ZERO)) { throw new Error('Illegal paramater. A mod N cannot be 0.'); } return A; }; /** * Calculate the client's value U which is the hash of A and B * @param {BigInteger} A Large A value. * @param {BigInteger} B Server B value. * @returns {BigInteger} Computed U value. * @private */ AuthenticationHelper.prototype.calculateU = function calculateU(A, B) { this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B)); var finalU = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](this.UHexHash, 16); return finalU; }; /** * Calculate a hash from a bitArray * @param {Buffer} buf Value to hash. * @returns {String} Hex-encoded hash. * @private */ AuthenticationHelper.prototype.hash = function hash(buf) { var hashHex = __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].crypto.sha256(buf, 'hex'); return new Array(64 - hashHex.length).join('0') + hashHex; }; /** * Calculate a hash from a hex string * @param {String} hexStr Value to hash. * @returns {String} Hex-encoded hash. * @private */ AuthenticationHelper.prototype.hexHash = function hexHash(hexStr) { return this.hash(new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(hexStr, 'hex')); }; /** * Standard hkdf algorithm * @param {Buffer} ikm Input key material. * @param {Buffer} salt Salt value. * @returns {Buffer} Strong key material. * @private */ AuthenticationHelper.prototype.computehkdf = function computehkdf(ikm, salt) { var prk = __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].crypto.hmac(salt, ikm, 'buffer', 'sha256'); var infoBitsUpdate = __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].buffer.concat([this.infoBits, new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(String.fromCharCode(1), 'utf8')]); var hmac = __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].crypto.hmac(prk, infoBitsUpdate, 'buffer', 'sha256'); return hmac.slice(0, 16); }; /** * Calculates the final hkdf based on computed S value, and computed U value and the key * @param {String} username Username. * @param {String} password Password. * @param {BigInteger} serverBValue Server B value. * @param {BigInteger} salt Generated salt. * @returns {Buffer} Computed HKDF value. */ AuthenticationHelper.prototype.getPasswordAuthenticationKey = function getPasswordAuthenticationKey(username, password, serverBValue, salt) { if (serverBValue.mod(this.N).equals(__WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */].ZERO)) { throw new Error('B cannot be zero.'); } this.UValue = this.calculateU(this.largeAValue, serverBValue); if (this.UValue.equals(__WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */].ZERO)) { throw new Error('U cannot be zero.'); } var usernamePassword = '' + this.poolName + username + ':' + password; var usernamePasswordHash = this.hash(usernamePassword); var xValue = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](this.hexHash(this.padHex(salt) + usernamePasswordHash), 16); var gModPowXN = this.g.modPow(xValue, this.N); var intValue2 = serverBValue.subtract(this.k.multiply(gModPowXN)); var sValue = intValue2.modPow(this.smallAValue.add(this.UValue.multiply(xValue)), this.N).mod(this.N); var hkdf = this.computehkdf(new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(this.padHex(sValue), 'hex'), new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(this.padHex(this.UValue.toString(16)), 'hex')); return hkdf; }; /** * Return constant newPasswordRequiredChallengeUserAttributePrefix * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value */ AuthenticationHelper.prototype.getNewPasswordRequiredChallengeUserAttributePrefix = function getNewPasswordRequiredChallengeUserAttributePrefix() { return newPasswordRequiredChallengeUserAttributePrefix; }; /** * Converts a BigInteger (or hex string) to hex format padded with zeroes for hashing * @param {BigInteger|String} bigInt Number or string to pad. * @returns {String} Padded hex string. */ AuthenticationHelper.prototype.padHex = function padHex(bigInt) { var hashStr = bigInt.toString(16); if (hashStr.length % 2 === 1) { hashStr = '0' + hashStr; } else if ('89ABCDEFabcdef'.indexOf(hashStr[0]) !== -1) { hashStr = '00' + hashStr; } return hashStr; }; return AuthenticationHelper; }(); /* harmony default export */ __webpack_exports__["a"] = (AuthenticationHelper); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/BigInteger.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/ // // All public methods have been removed except the following: // new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported) // toString (only radix 2, 4, 8, 16 and 32 supported) // negate // abs // compareTo // bitLength // mod // equals // add // subtract // multiply // divide // modPow /* harmony default export */ __webpack_exports__["a"] = (BigInteger); /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * 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" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ // (public) Constructor function BigInteger(a, b) { if (a != null) this.fromString(a, b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = (canary & 0xffffff) == 0xefcafe; // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i, x, w, j, c, n) { while (--n >= 0) { var v = x * this[i++] + w[j] + c; c = Math.floor(v / 0x4000000); w[j++] = v & 0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { var xl = x & 0x7fff, xh = x >> 15; while (--n >= 0) { var l = this[i] & 0x7fff; var h = this[i++] >> 15; var m = xh * l + h * xl; l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); w[j++] = l & 0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { var xl = x & 0x3fff, xh = x >> 14; while (--n >= 0) { var l = this[i] & 0x3fff; var h = this[i++] >> 14; var m = xh * l + h * xl; l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; c = (l >> 28) + (m >> 14) + xh * h; w[j++] = l & 0xfffffff; } return c; } var inBrowser = typeof navigator !== "undefined"; if (inBrowser && j_lm && navigator.appName == "Microsoft Internet Explorer") { BigInteger.prototype.am = am2; dbits = 30; } else if (inBrowser && j_lm && navigator.appName != "Netscape") { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = (1 << dbits) - 1; BigInteger.prototype.DV = 1 << dbits; var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = new Array(); var rr, vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) { BI_RC[rr++] = vv; }rr = "a".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; }rr = "A".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; }function int2char(n) { return BI_RM.charAt(n); } function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)]; return c == null ? -1 : c; } // (protected) copy this to r function bnpCopyTo(r) { for (var i = this.t - 1; i >= 0; --i) { r[i] = this[i]; }r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = x < 0 ? -1 : 0; if (x > 0) this[0] = x;else if (x < -1) this[0] = x + this.DV;else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s, b) { var k; if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while (--i >= 0) { var x = intAt(s, i); if (x < 0) { if (s.charAt(i) == "-") mi = true; continue; } mi = false; if (sh == 0) this[this.t++] = x;else if (sh + k > this.DB) { this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; this[this.t++] = x >> this.DB - sh; } else this[this.t - 1] |= x << sh; sh += k; if (sh >= this.DB) sh -= this.DB; } this.clamp(); if (mi) BigInteger.ZERO.subTo(this, this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) { --this.t; } } // (public) return string representation in given radix function bnToString(b) { if (this.s < 0) return "-" + this.negate().toString(); var k; if (b == 16) k = 4;else if (b == 8) k = 3;else if (b == 2) k = 1;else if (b == 32) k = 5;else if (b == 4) k = 2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); var km = (1 << k) - 1, d, m = false, r = "", i = this.t; var p = this.DB - i * this.DB % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { m = true; r = int2char(d); } while (i >= 0) { if (p < k) { d = (this[i] & (1 << p) - 1) << k - p; d |= this[--i] >> (p += this.DB - k); } else { d = this[i] >> (p -= k) & km; if (p <= 0) { p += this.DB; --i; } } if (d > 0) m = true; if (m) r += int2char(d); } } return m ? r : "0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; } // (public) |this| function bnAbs() { return this.s < 0 ? this.negate() : this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s - a.s; if (r != 0) return r; var i = this.t; r = i - a.t; if (r != 0) return this.s < 0 ? -r : r; while (--i >= 0) { if ((r = this[i] - a[i]) != 0) return r; }return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if ((t = x >>> 16) != 0) { x = t; r += 16; } if ((t = x >> 8) != 0) { x = t; r += 8; } if ((t = x >> 4) != 0) { x = t; r += 4; } if ((t = x >> 2) != 0) { x = t; r += 2; } if ((t = x >> 1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if (this.t <= 0) return 0; return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM); } // (protected) r = this << n*DB function bnpDLShiftTo(n, r) { var i; for (i = this.t - 1; i >= 0; --i) { r[i + n] = this[i]; }for (i = n - 1; i >= 0; --i) { r[i] = 0; }r.t = this.t + n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n, r) { for (var i = n; i < this.t; ++i) { r[i - n] = this[i]; }r.t = Math.max(this.t - n, 0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n, r) { var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << cbs) - 1; var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; for (i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = this[i] >> cbs | c; c = (this[i] & bm) << bs; } for (i = ds - 1; i >= 0; --i) { r[i] = 0; }r[ds] = c; r.t = this.t + ds + 1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; return; } var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << bs) - 1; r[0] = this[ds] >> bs; for (var i = ds + 1; i < this.t; ++i) { r[i - ds - 1] |= (this[i] & bm) << cbs; r[i - ds] = this[i] >> bs; } if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; r.t = this.t - ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c -= a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c -= a[i]; r[i++] = c & this.DM; c >>= this.DB; } c -= a.s; } r.s = c < 0 ? -1 : 0; if (c < -1) r[i++] = this.DV + c;else if (c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i + y.t; while (--i >= 0) { r[i] = 0; }for (i = 0; i < y.t; ++i) { r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); }r.s = 0; r.clamp(); if (this.s != a.s) BigInteger.ZERO.subTo(r, r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2 * x.t; while (--i >= 0) { r[i] = 0; }for (i = 0; i < x.t - 1; ++i) { var c = x.am(i, x[i], r, 2 * i, 0, 1); if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { r[i + x.t] -= x.DV; r[i + x.t + 1] = 1; } } if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m, q, r) { var pm = m.abs(); if (pm.t <= 0) return; var pt = this.abs(); if (pt.t < pm.t) { if (q != null) q.fromInt(0); if (r != null) this.copyTo(r); return; } if (r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys - 1]; if (y0 == 0) return; var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; var i = r.t, j = i - ys, t = q == null ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t, r); } BigInteger.ONE.dlShiftTo(ys, t); t.subTo(y, y); // "negative" y so we can replace sub with am later while (y.t < ys) { y[y.t++] = 0; }while (--j >= 0) { // Estimate quotient digit var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t); r.subTo(t, r); while (r[i] < --qd) { r.subTo(t, r); } } } if (q != null) { r.drShiftTo(ys, q); if (ts != ms) BigInteger.ZERO.subTo(q, q); } r.t = ys; r.clamp(); if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder if (ts < 0) BigInteger.ZERO.subTo(r, r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); return r; } // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if (this.t < 1) return 0; var x = this[0]; if ((x & 1) == 0) return 0; var y = x & 3; // y == 1/x mod 2^2 y = y * (2 - (x & 0xf) * y) & 0xf; // y == 1/x mod 2^4 y = y * (2 - (x & 0xff) * y) & 0xff; // y == 1/x mod 2^8 y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = y * (2 - x * y % this.DV) % this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return y > 0 ? this.DV - y : -y; } function bnEquals(a) { return this.compareTo(a) == 0; } // (protected) r = this + a function bnpAddTo(a, r) { var i = 0, c = 0, m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c += a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c += a[i]; r[i++] = c & this.DM; c >>= this.DB; } c += a.s; } r.s = c < 0 ? -1 : 0; if (c > 0) r[i++] = c;else if (c < -1) r[i++] = this.DV + c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a, r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a, r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a, r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a, r, null); return r; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp & 0x7fff; this.mph = this.mp >> 15; this.um = (1 << m.DB - 15) - 1; this.mt2 = 2 * m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while (x.t <= this.mt2) { // pad x so am has enough room later x[x.t++] = 0; }for (var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff; var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM; // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t, x); if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); } // r = "x^2/R mod m"; x != r function montSqrTo(x, r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x, y, r) { x.multiplyTo(y, r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e, m) { var i = e.bitLength(), k, r = nbv(1), z = new Montgomery(m); if (i <= 0) return r;else if (i < 18) k = 1;else if (i < 48) k = 3;else if (i < 144) k = 4;else if (i < 768) k = 5;else k = 6; // precomputation var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { var g2 = nbi(); z.sqrTo(g[1], g2); while (n <= km) { g[n] = nbi(); z.mulTo(g2, g[n - 2], g[n]); n += 2; } } var j = e.t - 1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) w = e[j] >> i - k1 & km;else { w = (e[j] & (1 << i + 1) - 1) << k1 - i; if (j > 0) w |= e[j - 1] >> this.DB + i - k1; } n = k; while ((w & 1) == 0) { w >>= 1; --n; } if ((i -= n) < 0) { i += this.DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n > 1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n > 0) z.sqrTo(r, r2);else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j >= 0 && (e[j] & 1 << i) == 0) { z.sqrTo(r, r2); t = r; r = r2; r2 = t; if (--i < 0) { i = this.DB - 1; --j; } } } return z.revert(r); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.addTo = bnpAddTo; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.modPow = bnModPow; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/CognitoAccessToken.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__ = __webpack_require__("../../../../aws-sdk/browser.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /* * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoAccessToken = function () { /** * Constructs a new CognitoAccessToken object * @param {string=} AccessToken The JWT access token. */ function CognitoAccessToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, AccessToken = _ref.AccessToken; _classCallCheck(this, CognitoAccessToken); // Assign object this.jwtToken = AccessToken || ''; } /** * @returns {string} the record's token. */ CognitoAccessToken.prototype.getJwtToken = function getJwtToken() { return this.jwtToken; }; /** * @returns {int} the token's expiration (exp member). */ CognitoAccessToken.prototype.getExpiration = function getExpiration() { var payload = this.jwtToken.split('.')[1]; var expiration = JSON.parse(__WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].base64.decode(payload).toString('utf8')); return expiration.exp; }; return CognitoAccessToken; }(); /* harmony default export */ __webpack_exports__["a"] = (CognitoAccessToken); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/CognitoIdToken.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__ = __webpack_require__("../../../../aws-sdk/browser.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoIdToken = function () { /** * Constructs a new CognitoIdToken object * @param {string=} IdToken The JWT Id token */ function CognitoIdToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, IdToken = _ref.IdToken; _classCallCheck(this, CognitoIdToken); // Assign object this.jwtToken = IdToken || ''; } /** * @returns {string} the record's token. */ CognitoIdToken.prototype.getJwtToken = function getJwtToken() { return this.jwtToken; }; /** * @returns {int} the token's expiration (exp member). */ CognitoIdToken.prototype.getExpiration = function getExpiration() { var payload = this.jwtToken.split('.')[1]; var expiration = JSON.parse(__WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].base64.decode(payload).toString('utf8')); return expiration.exp; }; return CognitoIdToken; }(); /* harmony default export */ __webpack_exports__["a"] = (CognitoIdToken); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/CognitoRefreshToken.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoRefreshToken = function () { /** * Constructs a new CognitoRefreshToken object * @param {string=} RefreshToken The JWT refresh token. */ function CognitoRefreshToken() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, RefreshToken = _ref.RefreshToken; _classCallCheck(this, CognitoRefreshToken); // Assign object this.token = RefreshToken || ''; } /** * @returns {string} the record's token. */ CognitoRefreshToken.prototype.getToken = function getToken() { return this.token; }; return CognitoRefreshToken; }(); /* harmony default export */ __webpack_exports__["a"] = (CognitoRefreshToken); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/CognitoUser.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__ = __webpack_require__("../../../../aws-sdk/browser.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BigInteger__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/BigInteger.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__AuthenticationHelper__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/AuthenticationHelper.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__CognitoAccessToken__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoAccessToken.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CognitoIdToken__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoIdToken.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__CognitoRefreshToken__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoRefreshToken.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__CognitoUserSession__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoUserSession.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__DateHelper__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/DateHelper.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__CognitoUserAttribute__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoUserAttribute.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__StorageHelper__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/StorageHelper.js"); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** * @callback nodeCallback * @template T result * @param {*} err The operation failure reason, or null. * @param {T} result The operation result. */ /** * @callback onFailure * @param {*} err Failure reason. */ /** * @callback onSuccess * @template T result * @param {T} result The operation result. */ /** * @callback mfaRequired * @param {*} details MFA challenge details. */ /** * @callback customChallenge * @param {*} details Custom challenge details. */ /** * @callback inputVerificationCode * @param {*} data Server response. */ /** * @callback authSuccess * @param {CognitoUserSession} session The new session. * @param {bool=} userConfirmationNecessary User must be confirmed. */ /** @class */ var CognitoUser = function () { /** * Constructs a new CognitoUser object * @param {object} data Creation options * @param {string} data.Username The user's username. * @param {CognitoUserPool} data.Pool Pool containing the user. * @param {object} data.Storage Optional storage object. */ function CognitoUser(data) { _classCallCheck(this, CognitoUser); if (data == null || data.Username == null || data.Pool == null) { throw new Error('Username and pool information are required.'); } this.username = data.Username || ''; this.pool = data.Pool; this.Session = null; this.client = data.Pool.client; this.signInUserSession = null; this.authenticationFlowType = 'USER_SRP_AUTH'; this.storage = data.Storage || new __WEBPACK_IMPORTED_MODULE_9__StorageHelper__["a" /* default */]().getStorage(); } /** * @returns {CognitoUserSession} the current session for this user */ CognitoUser.prototype.getSignInUserSession = function getSignInUserSession() { return this.signInUserSession; }; /** * @returns {string} the user's username */ CognitoUser.prototype.getUsername = function getUsername() { return this.username; }; /** * @returns {String} the authentication flow type */ CognitoUser.prototype.getAuthenticationFlowType = function getAuthenticationFlowType() { return this.authenticationFlowType; }; /** * sets authentication flow type * @param {string} authenticationFlowType New value. * @returns {void} */ CognitoUser.prototype.setAuthenticationFlowType = function setAuthenticationFlowType(authenticationFlowType) { this.authenticationFlowType = authenticationFlowType; }; /** * This is used for authenticating the user. it calls the AuthenticationHelper for SRP related * stuff * @param {AuthenticationDetails} authDetails Contains the authentication data * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {newPasswordRequired} callback.newPasswordRequired new * password and any required attributes are required to continue * @param {mfaRequired} callback.mfaRequired MFA code * required to continue. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.authenticateUser = function authenticateUser(authDetails, callback) { var _this = this; var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_2__AuthenticationHelper__["a" /* default */](this.pool.getUserPoolId().split('_')[1]); var dateHelper = new __WEBPACK_IMPORTED_MODULE_7__DateHelper__["a" /* default */](); var serverBValue = void 0; var salt = void 0; var authParameters = {}; if (this.deviceKey != null) { authParameters.DEVICE_KEY = this.deviceKey; } authParameters.USERNAME = this.username; authParameters.SRP_A = authenticationHelper.getLargeAValue().toString(16); if (this.authenticationFlowType === 'CUSTOM_AUTH') { authParameters.CHALLENGE_NAME = 'SRP_A'; } this.client.makeUnauthenticatedRequest('initiateAuth', { AuthFlow: this.authenticationFlowType, ClientId: this.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: authDetails.getValidationData() }, function (err, data) { if (err) { return callback.onFailure(err); } var challengeParameters = data.ChallengeParameters; _this.username = challengeParameters.USER_ID_FOR_SRP; serverBValue = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](challengeParameters.SRP_B, 16); salt = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](challengeParameters.SALT, 16); _this.getCachedDeviceKeyAndPassword(); var hkdf = authenticationHelper.getPasswordAuthenticationKey(_this.username, authDetails.getPassword(), serverBValue, salt); var dateNow = dateHelper.getNowString(); var signatureString = __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].crypto.hmac(hkdf, __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].buffer.concat([new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(_this.pool.getUserPoolId().split('_')[1], 'utf8'), new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(_this.username, 'utf8'), new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(challengeParameters.SECRET_BLOCK, 'base64'), new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(dateNow, 'utf8')]), 'base64', 'sha256'); var challengeResponses = {}; challengeResponses.USERNAME = _this.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; if (_this.deviceKey != null) { challengeResponses.DEVICE_KEY = _this.deviceKey; } var respondToAuthChallenge = function respondToAuthChallenge(challenge, challengeCallback) { return _this.client.makeUnauthenticatedRequest('respondToAuthChallenge', challenge, function (errChallenge, dataChallenge) { if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) { challengeResponses.DEVICE_KEY = null; _this.deviceKey = null; _this.randomPassword = null; _this.deviceGroupKey = null; _this.clearCachedDeviceKeyAndPassword(); return respondToAuthChallenge(challenge, challengeCallback); } return challengeCallback(errChallenge, dataChallenge); }); }; respondToAuthChallenge({ ChallengeName: 'PASSWORD_VERIFIER', ClientId: _this.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session }, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } var challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'NEW_PASSWORD_REQUIRED') { _this.Session = dataAuthenticate.Session; var userAttributes = null; var rawRequiredAttributes = null; var requiredAttributes = []; var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix(); if (dataAuthenticate.ChallengeParameters) { userAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.userAttributes); rawRequiredAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.requiredAttributes); } if (rawRequiredAttributes) { for (var i = 0; i < rawRequiredAttributes.length; i++) { requiredAttributes[i] = rawRequiredAttributes[i].substr(userAttributesPrefix.length); } } return callback.newPasswordRequired(userAttributes, requiredAttributes); } return _this.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback); }); return undefined; }); }; /** * PRIVATE ONLY: This is an internal only method and should not * be directly called by the consumers. * @param {object} dataAuthenticate authentication data * @param {object} authenticationHelper helper created * @param {callback} callback passed on from caller * @returns {void} */ CognitoUser.prototype.authenticateUserInternal = function authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) { var _this2 = this; var challengeName = dataAuthenticate.ChallengeName; var challengeParameters = dataAuthenticate.ChallengeParameters; if (challengeName === 'SMS_MFA') { this.Session = dataAuthenticate.Session; return callback.mfaRequired(challengeName, challengeParameters); } if (challengeName === 'CUSTOM_CHALLENGE') { this.Session = dataAuthenticate.Session; return callback.customChallenge(challengeParameters); } if (challengeName === 'DEVICE_SRP_AUTH') { this.getDeviceResponse(callback); return undefined; } this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult); this.cacheTokens(); var newDeviceMetadata = dataAuthenticate.AuthenticationResult.NewDeviceMetadata; if (newDeviceMetadata == null) { return callback.onSuccess(this.signInUserSession); } authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey); var deviceSecretVerifierConfig = { Salt: new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(authenticationHelper.getSaltDevices(), 'hex').toString('base64'), PasswordVerifier: new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(authenticationHelper.getVerifierDevices(), 'hex').toString('base64') }; this.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; this.deviceGroupKey = newDeviceMetadata.DeviceGroupKey; this.randomPassword = authenticationHelper.getRandomPassword(); this.client.makeUnauthenticatedRequest('confirmDevice', { DeviceKey: newDeviceMetadata.DeviceKey, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent }, function (errConfirm, dataConfirm) { if (errConfirm) { return callback.onFailure(errConfirm); } _this2.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; _this2.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess(_this2.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(_this2.signInUserSession); }); return undefined; }; /** * This method is user to complete the NEW_PASSWORD_REQUIRED challenge. * Pass the new password with any new user attributes to be updated. * User attribute keys must be of format userAttributes.. * @param {string} newPassword new password for this user * @param {object} requiredAttributeData map with values for all required attributes * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {mfaRequired} callback.mfaRequired MFA code required to continue. * @param {customChallenge} callback.customChallenge Custom challenge * response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.completeNewPasswordChallenge = function completeNewPasswordChallenge(newPassword, requiredAttributeData, callback) { var _this3 = this; if (!newPassword) { return callback.onFailure(new Error('New password is required.')); } var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_2__AuthenticationHelper__["a" /* default */](this.pool.getUserPoolId().split('_')[1]); var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix(); var finalUserAttributes = {}; if (requiredAttributeData) { Object.keys(requiredAttributeData).forEach(function (key) { finalUserAttributes[userAttributesPrefix + key] = requiredAttributeData[key]; }); } finalUserAttributes.NEW_PASSWORD = newPassword; finalUserAttributes.USERNAME = this.username; this.client.makeUnauthenticatedRequest('respondToAuthChallenge', { ChallengeName: 'NEW_PASSWORD_REQUIRED', ClientId: this.pool.getClientId(), ChallengeResponses: finalUserAttributes, Session: this.Session }, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } return _this3.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback); }); return undefined; }; /** * This is used to get a session using device authentication. It is called at the end of user * authentication * * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} * @private */ CognitoUser.prototype.getDeviceResponse = function getDeviceResponse(callback) { var _this4 = this; var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_2__AuthenticationHelper__["a" /* default */](this.deviceGroupKey); var dateHelper = new __WEBPACK_IMPORTED_MODULE_7__DateHelper__["a" /* default */](); var authParameters = {}; authParameters.USERNAME = this.username; authParameters.DEVICE_KEY = this.deviceKey; authParameters.SRP_A = authenticationHelper.getLargeAValue().toString(16); this.client.makeUnauthenticatedRequest('respondToAuthChallenge', { ChallengeName: 'DEVICE_SRP_AUTH', ClientId: this.pool.getClientId(), ChallengeResponses: authParameters }, function (err, data) { if (err) { return callback.onFailure(err); } var challengeParameters = data.ChallengeParameters; var serverBValue = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](challengeParameters.SRP_B, 16); var salt = new __WEBPACK_IMPORTED_MODULE_1__BigInteger__["a" /* default */](challengeParameters.SALT, 16); var hkdf = authenticationHelper.getPasswordAuthenticationKey(_this4.deviceKey, _this4.randomPassword, serverBValue, salt); var dateNow = dateHelper.getNowString(); var signatureString = __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].crypto.hmac(hkdf, __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].buffer.concat([new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(_this4.deviceGroupKey, 'utf8'), new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(_this4.deviceKey, 'utf8'), new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(challengeParameters.SECRET_BLOCK, 'base64'), new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(dateNow, 'utf8')]), 'base64', 'sha256'); var challengeResponses = {}; challengeResponses.USERNAME = _this4.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; challengeResponses.DEVICE_KEY = _this4.deviceKey; _this4.client.makeUnauthenticatedRequest('respondToAuthChallenge', { ChallengeName: 'DEVICE_PASSWORD_VERIFIER', ClientId: _this4.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session }, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } _this4.signInUserSession = _this4.getCognitoUserSession(dataAuthenticate.AuthenticationResult); _this4.cacheTokens(); return callback.onSuccess(_this4.signInUserSession); }); return undefined; }); }; /** * This is used for a certain user to confirm the registration by using a confirmation code * @param {string} confirmationCode Code entered by user. * @param {bool} forceAliasCreation Allow migrating from an existing email / phone number. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.confirmRegistration = function confirmRegistration(confirmationCode, forceAliasCreation, callback) { this.client.makeUnauthenticatedRequest('confirmSignUp', { ClientId: this.pool.getClientId(), ConfirmationCode: confirmationCode, Username: this.username, ForceAliasCreation: forceAliasCreation }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); }; /** * This is used by the user once he has the responses to a custom challenge * @param {string} answerChallenge The custom challange answer. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {customChallenge} callback.customChallenge * Custom challenge response required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.sendCustomChallengeAnswer = function sendCustomChallengeAnswer(answerChallenge, callback) { var _this5 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; this.client.makeUnauthenticatedRequest('respondToAuthChallenge', { ChallengeName: 'CUSTOM_CHALLENGE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }, function (err, data) { if (err) { return callback.onFailure(err); } var challengeName = data.ChallengeName; if (challengeName === 'CUSTOM_CHALLENGE') { _this5.Session = data.Session; return callback.customChallenge(data.ChallengeParameters); } _this5.signInUserSession = _this5.getCognitoUserSession(data.AuthenticationResult); _this5.cacheTokens(); return callback.onSuccess(_this5.signInUserSession); }); }; /** * This is used by the user once he has an MFA code * @param {string} confirmationCode The MFA code entered by the user. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ CognitoUser.prototype.sendMFACode = function sendMFACode(confirmationCode, callback) { var _this6 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.SMS_MFA_CODE = confirmationCode; if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } this.client.makeUnauthenticatedRequest('respondToAuthChallenge', { ChallengeName: 'SMS_MFA', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }, function (err, dataAuthenticate) { if (err) { return callback.onFailure(err); } var challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'DEVICE_SRP_AUTH') { _this6.getDeviceResponse(callback); return undefined; } _this6.signInUserSession = _this6.getCognitoUserSession(dataAuthenticate.AuthenticationResult); _this6.cacheTokens(); if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) { return callback.onSuccess(_this6.signInUserSession); } var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_2__AuthenticationHelper__["a" /* default */](_this6.pool.getUserPoolId().split('_')[1]); authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey); var deviceSecretVerifierConfig = { Salt: new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(authenticationHelper.getSaltDevices(), 'hex').toString('base64'), PasswordVerifier: new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__["util"].Buffer(authenticationHelper.getVerifierDevices(), 'hex').toString('base64') }; _this6.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; _this6.deviceGroupKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey; _this6.randomPassword = authenticationHelper.getRandomPassword(); _this6.client.makeUnauthenticatedRequest('confirmDevice', { DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, AccessToken: _this6.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent }, function (errConfirm, dataConfirm) { if (errConfirm) { return callback.onFailure(errConfirm); } _this6.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; _this6.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess(_this6.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(_this6.signInUserSession); }); return undefined; }); }; /** * This is used by an authenticated user to change the current password * @param {string} oldUserPassword The current password. * @param {string} newUserPassword The requested new password. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.changePassword = function changePassword(oldUserPassword, newUserPassword, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('changePassword', { PreviousPassword: oldUserPassword, ProposedPassword: newUserPassword, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to enable MFA for himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.enableMFA = function enableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } var mfaOptions = []; var mfaEnabled = { DeliveryMedium: 'SMS', AttributeName: 'phone_number' }; mfaOptions.push(mfaEnabled); this.client.makeUnauthenticatedRequest('setUserSettings', { MFAOptions: mfaOptions, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to disable MFA for himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.disableMFA = function disableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } var mfaOptions = []; this.client.makeUnauthenticatedRequest('setUserSettings', { MFAOptions: mfaOptions, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to delete himself * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.deleteUser = function deleteUser(callback) { var _this7 = this; if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('deleteUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } _this7.clearCachedTokens(); return callback(null, 'SUCCESS'); }); return undefined; }; /** * @typedef {CognitoUserAttribute | { Name:string, Value:string }} AttributeArg */ /** * This is used by an authenticated user to change a list of attributes * @param {AttributeArg[]} attributes A list of the new user attributes. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.updateAttributes = function updateAttributes(attributes, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('updateUserAttributes', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserAttributes: attributes }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by an authenticated user to get a list of attributes * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getUserAttributes = function getUserAttributes(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('getUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, userData) { if (err) { return callback(err, null); } var attributeList = []; for (var i = 0; i < userData.UserAttributes.length; i++) { var attribute = { Name: userData.UserAttributes[i].Name, Value: userData.UserAttributes[i].Value }; var userAttribute = new __WEBPACK_IMPORTED_MODULE_8__CognitoUserAttribute__["a" /* default */](attribute); attributeList.push(userAttribute); } return callback(null, attributeList); }); return undefined; }; /** * This is used by an authenticated user to get the MFAOptions * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getMFAOptions = function getMFAOptions(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('getUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, userData) { if (err) { return callback(err, null); } return callback(null, userData.MFAOptions); }); return undefined; }; /** * This is used by an authenticated user to delete a list of attributes * @param {string[]} attributeList Names of the attributes to delete. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.deleteAttributes = function deleteAttributes(attributeList, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.makeUnauthenticatedRequest('deleteUserAttributes', { UserAttributeNames: attributeList, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback(err, null); } return callback(null, 'SUCCESS'); }); return undefined; }; /** * This is used by a user to resend a confirmation code * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.resendConfirmationCode = function resendConfirmationCode(callback) { this.client.makeUnauthenticatedRequest('resendConfirmationCode', { ClientId: this.pool.getClientId(), Username: this.username }, function (err, result) { if (err) { return callback(err, null); } return callback(null, result); }); }; /** * This is used to get a session, either from the session object * or from the local storage, or by using a refresh token * * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.getSession = function getSession(callback) { if (this.username == null) { return callback(new Error('Username is null. Cannot retrieve a new session'), null); } if (this.signInUserSession != null && this.signInUserSession.isValid()) { return callback(null, this.signInUserSession); } var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var idTokenKey = keyPrefix + '.idToken'; var accessTokenKey = keyPrefix + '.accessToken'; var refreshTokenKey = keyPrefix + '.refreshToken'; if (this.storage.getItem(idTokenKey)) { var idToken = new __WEBPACK_IMPORTED_MODULE_4__CognitoIdToken__["a" /* default */]({ IdToken: this.storage.getItem(idTokenKey) }); var accessToken = new __WEBPACK_IMPORTED_MODULE_3__CognitoAccessToken__["a" /* default */]({ AccessToken: this.storage.getItem(accessTokenKey) }); var refreshToken = new __WEBPACK_IMPORTED_MODULE_5__CognitoRefreshToken__["a" /* default */]({ RefreshToken: this.storage.getItem(refreshTokenKey) }); var sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken }; var cachedSession = new __WEBPACK_IMPORTED_MODULE_6__CognitoUserSession__["a" /* default */](sessionData); if (cachedSession.isValid()) { this.signInUserSession = cachedSession; return callback(null, this.signInUserSession); } if (refreshToken.getToken() == null) { return callback(new Error('Cannot retrieve a new session. Please authenticate.'), null); } this.refreshSession(refreshToken, callback); } else { callback(new Error('Local storage is missing an ID Token, Please authenticate'), null); } return undefined; }; /** * This uses the refreshToken to retrieve a new session * @param {CognitoRefreshToken} refreshToken A previous session's refresh token. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ CognitoUser.prototype.refreshSession = function refreshSession(refreshToken, callback) { var _this8 = this; var authParameters = {}; authParameters.REFRESH_TOKEN = refreshToken.getToken(); var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var lastUserKey = keyPrefix + '.LastAuthUser'; if (this.storage.getItem(lastUserKey)) { this.username = this.storage.getItem(lastUserKey); var deviceKeyKey = keyPrefix + '.' + this.username + '.deviceKey'; this.deviceKey = this.storage.getItem(deviceKeyKey); authParameters.DEVICE_KEY = this.deviceKey; } this.client.makeUnauthenticatedRequest('initiateAuth', { ClientId: this.pool.getClientId(), AuthFlow: 'REFRESH_TOKEN_AUTH', AuthParameters: authParameters }, function (err, authResult) { if (err) { if (err.code === 'NotAuthorizedException') { _this8.clearCachedTokens(); } return callback(err, null); } if (authResult) { var authenticationResult = authResult.AuthenticationResult; if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) { authenticationResult.RefreshToken = refreshToken.getToken(); } _this8.signInUserSession = _this8.getCognitoUserSession(authenticationResult); _this8.cacheTokens(); return callback(null, _this8.signInUserSession); } return undefined; }); }; /** * This is used to save the session tokens to local storage * @returns {void} */ CognitoUser.prototype.cacheTokens = function cacheTokens() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var idTokenKey = keyPrefix + '.' + this.username + '.idToken'; var accessTokenKey = keyPrefix + '.' + this.username + '.accessToken'; var refreshTokenKey = keyPrefix + '.' + this.username + '.refreshToken'; var lastUserKey = keyPrefix + '.LastAuthUser'; this.storage.setItem(idTokenKey, this.signInUserSession.getIdToken().getJwtToken()); this.storage.setItem(accessTokenKey, this.signInUserSession.getAccessToken().getJwtToken()); this.storage.setItem(refreshTokenKey, this.signInUserSession.getRefreshToken().getToken()); this.storage.setItem(lastUserKey, this.username); }; /** * This is used to cache the device key and device group and device password * @returns {void} */ CognitoUser.prototype.cacheDeviceKeyAndPassword = function cacheDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; this.storage.setItem(deviceKeyKey, this.deviceKey); this.storage.setItem(randomPasswordKey, this.randomPassword); this.storage.setItem(deviceGroupKeyKey, this.deviceGroupKey); }; /** * This is used to get current device key and device group and device password * @returns {void} */ CognitoUser.prototype.getCachedDeviceKeyAndPassword = function getCachedDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; if (this.storage.getItem(deviceKeyKey)) { this.deviceKey = this.storage.getItem(deviceKeyKey); this.randomPassword = this.storage.getItem(randomPasswordKey); this.deviceGroupKey = this.storage.getItem(deviceGroupKeyKey); } }; /** * This is used to clear the device key info from local storage * @returns {void} */ CognitoUser.prototype.clearCachedDeviceKeyAndPassword = function clearCachedDeviceKeyAndPassword() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId() + '.' + this.username; var deviceKeyKey = keyPrefix + '.deviceKey'; var randomPasswordKey = keyPrefix + '.randomPasswordKey'; var deviceGroupKeyKey = keyPrefix + '.deviceGroupKey'; this.storage.removeItem(deviceKeyKey); this.storage.removeItem(randomPasswordKey); this.storage.removeItem(deviceGroupKeyKey); }; /** * This is used to clear the session tokens from local storage * @returns {void} */ CognitoUser.prototype.clearCachedTokens = function clearCachedTokens() { var keyPrefix = 'CognitoIdentityServiceProvider.' + this.pool.getClientId(); var idTokenKey = keyPrefix + '.' + this.username + '.idToken'; var accessTokenKey = keyPrefix + '.' + this.username + '.accessToken'; var refreshTokenKey = keyPrefix + '.' + this.username + '.refreshToken'; var lastUserKey = keyPrefix + '.LastAuthUser'; this.storage.removeItem(idTokenKey); this.storage.removeItem(accessTokenKey); this.storage.removeItem(refreshTokenKey); this.storage.removeItem(lastUserKey); }; /** * This is used to build a user session from tokens retrieved in the authentication result * @param {object} authResult Successful auth response from server. * @returns {CognitoUserSession} The new user session. * @private */ CognitoUser.prototype.getCognitoUserSession = function getCognitoUserSession(authResult) { var idToken = new __WEBPACK_IMPORTED_MODULE_4__CognitoIdToken__["a" /* default */](authResult); var accessToken = new __WEBPACK_IMPORTED_MODULE_3__CognitoAccessToken__["a" /* default */](authResult); var refreshToken = new __WEBPACK_IMPORTED_MODULE_5__CognitoRefreshToken__["a" /* default */](authResult); var sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken }; return new __WEBPACK_IMPORTED_MODULE_6__CognitoUserSession__["a" /* default */](sessionData); }; /** * This is used to initiate a forgot password request * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {inputVerificationCode?} callback.inputVerificationCode * Optional callback raised instead of onSuccess with response data. * @param {onSuccess?} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgotPassword = function forgotPassword(callback) { this.client.makeUnauthenticatedRequest('forgotPassword', { ClientId: this.pool.getClientId(), Username: this.username }, function (err, data) { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(); }); }; /** * This is used to confirm a new password using a confirmationCode * @param {string} confirmationCode Code entered by user. * @param {string} newPassword Confirm new password. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.confirmPassword = function confirmPassword(confirmationCode, newPassword, callback) { this.client.makeUnauthenticatedRequest('confirmForgotPassword', { ClientId: this.pool.getClientId(), Username: this.username, ConfirmationCode: confirmationCode, Password: newPassword }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess(); }); }; /** * This is used to initiate an attribute confirmation request * @param {string} attributeName User attribute that needs confirmation. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {inputVerificationCode} callback.inputVerificationCode Called on success. * @returns {void} */ CognitoUser.prototype.getAttributeVerificationCode = function getAttributeVerificationCode(attributeName, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('getUserAttributeVerificationCode', { AttributeName: attributeName, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, data) { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(); }); return undefined; }; /** * This is used to confirm an attribute using a confirmation code * @param {string} attributeName Attribute being confirmed. * @param {string} confirmationCode Code entered by user. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.verifyAttribute = function verifyAttribute(attributeName, confirmationCode, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('verifyUserAttribute', { AttributeName: attributeName, Code: confirmationCode, AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to get the device information using the current device key * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess<*>} callback.onSuccess Called on success with device data. * @returns {void} */ CognitoUser.prototype.getDevice = function getDevice(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('getDevice', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); return undefined; }; /** * This is used to forget a specific device * @param {string} deviceKey Device key. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgetSpecificDevice = function forgetSpecificDevice(deviceKey, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('forgetDevice', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: deviceKey }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to forget the current device * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.forgetDevice = function forgetDevice(callback) { var _this9 = this; this.forgetSpecificDevice(this.deviceKey, { onFailure: callback.onFailure, onSuccess: function onSuccess(result) { _this9.deviceKey = null; _this9.deviceGroupKey = null; _this9.randomPassword = null; _this9.clearCachedDeviceKeyAndPassword(); return callback.onSuccess(result); } }); }; /** * This is used to set the device status as remembered * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.setDeviceStatusRemembered = function setDeviceStatusRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('updateDeviceStatus', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, DeviceRememberedStatus: 'remembered' }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to set the device status as not remembered * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.setDeviceStatusNotRemembered = function setDeviceStatusNotRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('updateDeviceStatus', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), DeviceKey: this.deviceKey, DeviceRememberedStatus: 'not_remembered' }, function (err) { if (err) { return callback.onFailure(err); } return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used to list all devices for a user * * @param {int} limit the number of devices returned in a call * @param {string} paginationToken the pagination token in case any was returned before * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess<*>} callback.onSuccess Called on success with device list. * @returns {void} */ CognitoUser.prototype.listDevices = function listDevices(limit, paginationToken, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('listDevices', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), Limit: limit, PaginationToken: paginationToken }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); return undefined; }; /** * This is used to globally revoke all tokens issued to a user * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {onSuccess} callback.onSuccess Called on success. * @returns {void} */ CognitoUser.prototype.globalSignOut = function globalSignOut(callback) { var _this10 = this; if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.makeUnauthenticatedRequest('globalSignOut', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback.onFailure(err); } _this10.clearCachedTokens(); return callback.onSuccess('SUCCESS'); }); return undefined; }; /** * This is used for the user to signOut of the application and clear the cached tokens. * @returns {void} */ CognitoUser.prototype.signOut = function signOut() { this.signInUserSession = null; this.clearCachedTokens(); }; return CognitoUser; }(); /* harmony default export */ __webpack_exports__["a"] = (CognitoUser); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/CognitoUserAttribute.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserAttribute = function () { /** * Constructs a new CognitoUserAttribute object * @param {string=} Name The record's name * @param {string=} Value The record's value */ function CognitoUserAttribute() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, Name = _ref.Name, Value = _ref.Value; _classCallCheck(this, CognitoUserAttribute); this.Name = Name || ''; this.Value = Value || ''; } /** * @returns {string} the record's value. */ CognitoUserAttribute.prototype.getValue = function getValue() { return this.Value; }; /** * Sets the record's value. * @param {string} value The new value. * @returns {CognitoUserAttribute} The record for method chaining. */ CognitoUserAttribute.prototype.setValue = function setValue(value) { this.Value = value; return this; }; /** * @returns {string} the record's name. */ CognitoUserAttribute.prototype.getName = function getName() { return this.Name; }; /** * Sets the record's name * @param {string} name The new name. * @returns {CognitoUserAttribute} The record for method chaining. */ CognitoUserAttribute.prototype.setName = function setName(name) { this.Name = name; return this; }; /** * @returns {string} a string representation of the record. */ CognitoUserAttribute.prototype.toString = function toString() { return JSON.stringify(this); }; /** * @returns {object} a flat object representing the record. */ CognitoUserAttribute.prototype.toJSON = function toJSON() { return { Name: this.Name, Value: this.Value }; }; return CognitoUserAttribute; }(); /* harmony default export */ __webpack_exports__["a"] = (CognitoUserAttribute); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/CognitoUserPool.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_clients_cognitoidentityserviceprovider__ = __webpack_require__("../../../../aws-sdk/clients/cognitoidentityserviceprovider.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_aws_sdk_clients_cognitoidentityserviceprovider___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_aws_sdk_clients_cognitoidentityserviceprovider__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__CognitoUser__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoUser.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__StorageHelper__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/StorageHelper.js"); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserPool = function () { /** * Constructs a new CognitoUserPool object * @param {object} data Creation options. * @param {string} data.UserPoolId Cognito user pool id. * @param {string} data.ClientId User pool application client id. * @param {object} data.Storage Optional storage object. */ function CognitoUserPool(data) { _classCallCheck(this, CognitoUserPool); var _ref = data || {}, UserPoolId = _ref.UserPoolId, ClientId = _ref.ClientId; if (!UserPoolId || !ClientId) { throw new Error('Both UserPoolId and ClientId are required.'); } if (!/^[\w-]+_.+$/.test(UserPoolId)) { throw new Error('Invalid UserPoolId format.'); } var region = UserPoolId.split('_')[0]; this.userPoolId = UserPoolId; this.clientId = ClientId; this.client = new __WEBPACK_IMPORTED_MODULE_0_aws_sdk_clients_cognitoidentityserviceprovider___default.a({ apiVersion: '2016-04-19', region: region }); this.storage = data.Storage || new __WEBPACK_IMPORTED_MODULE_2__StorageHelper__["a" /* default */]().getStorage(); } /** * @returns {string} the user pool id */ CognitoUserPool.prototype.getUserPoolId = function getUserPoolId() { return this.userPoolId; }; /** * @returns {string} the client id */ CognitoUserPool.prototype.getClientId = function getClientId() { return this.clientId; }; /** * @typedef {object} SignUpResult * @property {CognitoUser} user New user. * @property {bool} userConfirmed If the user is already confirmed. */ /** * method for signing up a user * @param {string} username User's username. * @param {string} password Plain-text initial password entered by user. * @param {(AttributeArg[])=} userAttributes New user attributes. * @param {(AttributeArg[])=} validationData Application metadata. * @param {nodeCallback} callback Called on error or with the new user. * @returns {void} */ CognitoUserPool.prototype.signUp = function signUp(username, password, userAttributes, validationData, callback) { var _this = this; this.client.makeUnauthenticatedRequest('signUp', { ClientId: this.clientId, Username: username, Password: password, UserAttributes: userAttributes, ValidationData: validationData }, function (err, data) { if (err) { return callback(err, null); } var cognitoUser = { Username: username, Pool: _this, Storage: _this.storage }; var returnData = { user: new __WEBPACK_IMPORTED_MODULE_1__CognitoUser__["a" /* default */](cognitoUser), userConfirmed: data.UserConfirmed, userSub: data.UserSub }; return callback(null, returnData); }); }; /** * method for getting the current user of the application from the local storage * * @returns {CognitoUser} the user retrieved from storage */ CognitoUserPool.prototype.getCurrentUser = function getCurrentUser() { var lastUserKey = 'CognitoIdentityServiceProvider.' + this.clientId + '.LastAuthUser'; var lastAuthUser = this.storage.getItem(lastUserKey); if (lastAuthUser) { var cognitoUser = { Username: lastAuthUser, Pool: this, Storage: this.storage }; return new __WEBPACK_IMPORTED_MODULE_1__CognitoUser__["a" /* default */](cognitoUser); } return null; }; return CognitoUserPool; }(); /* harmony default export */ __webpack_exports__["a"] = (CognitoUserPool); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/CognitoUserSession.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /** @class */ var CognitoUserSession = function () { /** * Constructs a new CognitoUserSession object * @param {string} IdToken The session's Id token. * @param {string=} RefreshToken The session's refresh token. * @param {string} AccessToken The session's access token. */ function CognitoUserSession() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, IdToken = _ref.IdToken, RefreshToken = _ref.RefreshToken, AccessToken = _ref.AccessToken; _classCallCheck(this, CognitoUserSession); if (AccessToken == null || IdToken == null) { throw new Error('Id token and Access Token must be present.'); } this.idToken = IdToken; this.refreshToken = RefreshToken; this.accessToken = AccessToken; } /** * @returns {CognitoIdToken} the session's Id token */ CognitoUserSession.prototype.getIdToken = function getIdToken() { return this.idToken; }; /** * @returns {CognitoRefreshToken} the session's refresh token */ CognitoUserSession.prototype.getRefreshToken = function getRefreshToken() { return this.refreshToken; }; /** * @returns {CognitoAccessToken} the session's access token */ CognitoUserSession.prototype.getAccessToken = function getAccessToken() { return this.accessToken; }; /** * Checks to see if the session is still valid based on session expiry information found * in tokens and the current time * @returns {boolean} if the session is still valid */ CognitoUserSession.prototype.isValid = function isValid() { var now = Math.floor(new Date() / 1000); return now < this.accessToken.getExpiration() && now < this.idToken.getExpiration(); }; return CognitoUserSession; }(); /* harmony default export */ __webpack_exports__["a"] = (CognitoUserSession); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/DateHelper.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; /** @class */ var DateHelper = function () { function DateHelper() { _classCallCheck(this, DateHelper); } /** * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format. */ DateHelper.prototype.getNowString = function getNowString() { var now = new Date(); var weekDay = weekNames[now.getUTCDay()]; var month = monthNames[now.getUTCMonth()]; var day = now.getUTCDate(); var hours = now.getUTCHours(); if (hours < 10) { hours = '0' + hours; } var minutes = now.getUTCMinutes(); if (minutes < 10) { minutes = '0' + minutes; } var seconds = now.getUTCSeconds(); if (seconds < 10) { seconds = '0' + seconds; } var year = now.getUTCFullYear(); // ddd MMM D HH:mm:ss UTC YYYY var dateNow = weekDay + ' ' + month + ' ' + day + ' ' + hours + ':' + minutes + ':' + seconds + ' UTC ' + year; return dateNow; }; return DateHelper; }(); /* harmony default export */ __webpack_exports__["a"] = (DateHelper); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/StorageHelper.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ var dataMemory = {}; /** @class */ var MemoryStorage = function () { function MemoryStorage() { _classCallCheck(this, MemoryStorage); } /** * This is used to set a specific item in storage * @param {string} key - the key for the item * @param {object} value - the value * @returns {string} value that was set */ MemoryStorage.setItem = function setItem(key, value) { dataMemory[key] = value; return dataMemory[key]; }; /** * This is used to get a specific key from storage * @param {string} key - the key for the item * This is used to clear the storage * @returns {string} the data item */ MemoryStorage.getItem = function getItem(key) { return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined; }; /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ MemoryStorage.removeItem = function removeItem(key) { return delete dataMemory[key]; }; /** * This is used to clear the storage * @returns {string} nothing */ MemoryStorage.clear = function clear() { dataMemory = {}; return dataMemory; }; return MemoryStorage; }(); /** @class */ var StorageHelper = function () { /** * This is used to get a storage object * @returns {object} the storage */ function StorageHelper() { _classCallCheck(this, StorageHelper); try { this.storageWindow = window.localStorage; this.storageWindow.setItem('aws.cognito.test-ls', 1); this.storageWindow.removeItem('aws.cognito.test-ls'); } catch (exception) { this.storageWindow = MemoryStorage; } } /** * This is used to return the storage * @returns {object} the storage */ StorageHelper.prototype.getStorage = function getStorage() { return this.storageWindow; }; return StorageHelper; }(); /* harmony default export */ __webpack_exports__["a"] = (StorageHelper); /***/ }), /***/ "../../../../amazon-cognito-identity-js/es/index.js": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__AuthenticationDetails__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/AuthenticationDetails.js"); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __WEBPACK_IMPORTED_MODULE_0__AuthenticationDetails__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__AuthenticationHelper__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/AuthenticationHelper.js"); /* unused harmony reexport AuthenticationHelper */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__CognitoAccessToken__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoAccessToken.js"); /* unused harmony reexport CognitoAccessToken */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__CognitoIdToken__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoIdToken.js"); /* unused harmony reexport CognitoIdToken */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CognitoRefreshToken__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoRefreshToken.js"); /* unused harmony reexport CognitoRefreshToken */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__CognitoUser__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoUser.js"); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __WEBPACK_IMPORTED_MODULE_5__CognitoUser__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__CognitoUserAttribute__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoUserAttribute.js"); /* unused harmony reexport CognitoUserAttribute */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__CognitoUserPool__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoUserPool.js"); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_7__CognitoUserPool__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__CognitoUserSession__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/CognitoUserSession.js"); /* unused harmony reexport CognitoUserSession */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__DateHelper__ = __webpack_require__("../../../../amazon-cognito-identity-js/es/DateHelper.js"); /* unused harmony reexport DateHelper */ /*! * Copyright 2016 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the * License. A copy of the License is located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, express or implied. See the License * for the specific language governing permissions and * limitations under the License. */ /***/ }), /***/ "../../../../aws-sdk/apis/cognito-identity-2014-06-30.min.json": /***/ (function(module, exports) { module.exports = {"version":"2.0","metadata":{"apiVersion":"2014-06-30","endpointPrefix":"cognito-identity","jsonVersion":"1.1","protocol":"json","serviceFullName":"Amazon Cognito Identity","signatureVersion":"v4","targetPrefix":"AWSCognitoIdentityService","uid":"cognito-identity-2014-06-30"},"operations":{"CreateIdentityPool":{"input":{"type":"structure","required":["IdentityPoolName","AllowUnauthenticatedIdentities"],"members":{"IdentityPoolName":{},"AllowUnauthenticatedIdentities":{"type":"boolean"},"SupportedLoginProviders":{"shape":"S4"},"DeveloperProviderName":{},"OpenIdConnectProviderARNs":{"shape":"S8"},"CognitoIdentityProviders":{"shape":"Sa"},"SamlProviderARNs":{"shape":"Sf"}}},"output":{"shape":"Sg"}},"DeleteIdentities":{"input":{"type":"structure","required":["IdentityIdsToDelete"],"members":{"IdentityIdsToDelete":{"type":"list","member":{}}}},"output":{"type":"structure","members":{"UnprocessedIdentityIds":{"type":"list","member":{"type":"structure","members":{"IdentityId":{},"ErrorCode":{}}}}}}},"DeleteIdentityPool":{"input":{"type":"structure","required":["IdentityPoolId"],"members":{"IdentityPoolId":{}}}},"DescribeIdentity":{"input":{"type":"structure","required":["IdentityId"],"members":{"IdentityId":{}}},"output":{"shape":"Sr"}},"DescribeIdentityPool":{"input":{"type":"structure","required":["IdentityPoolId"],"members":{"IdentityPoolId":{}}},"output":{"shape":"Sg"}},"GetCredentialsForIdentity":{"input":{"type":"structure","required":["IdentityId"],"members":{"IdentityId":{},"Logins":{"shape":"Sw"},"CustomRoleArn":{}}},"output":{"type":"structure","members":{"IdentityId":{},"Credentials":{"type":"structure","members":{"AccessKeyId":{},"SecretKey":{},"SessionToken":{},"Expiration":{"type":"timestamp"}}}}}},"GetId":{"input":{"type":"structure","required":["IdentityPoolId"],"members":{"AccountId":{},"IdentityPoolId":{},"Logins":{"shape":"Sw"}}},"output":{"type":"structure","members":{"IdentityId":{}}}},"GetIdentityPoolRoles":{"input":{"type":"structure","required":["IdentityPoolId"],"members":{"IdentityPoolId":{}}},"output":{"type":"structure","members":{"IdentityPoolId":{},"Roles":{"shape":"S18"},"RoleMappings":{"shape":"S1a"}}}},"GetOpenIdToken":{"input":{"type":"structure","required":["IdentityId"],"members":{"IdentityId":{},"Logins":{"shape":"Sw"}}},"output":{"type":"structure","members":{"IdentityId":{},"Token":{}}}},"GetOpenIdTokenForDeveloperIdentity":{"input":{"type":"structure","required":["IdentityPoolId","Logins"],"members":{"IdentityPoolId":{},"IdentityId":{},"Logins":{"shape":"Sw"},"TokenDuration":{"type":"long"}}},"output":{"type":"structure","members":{"IdentityId":{},"Token":{}}}},"ListIdentities":{"input":{"type":"structure","required":["IdentityPoolId","MaxResults"],"members":{"IdentityPoolId":{},"MaxResults":{"type":"integer"},"NextToken":{},"HideDisabled":{"type":"boolean"}}},"output":{"type":"structure","members":{"IdentityPoolId":{},"Identities":{"type":"list","member":{"shape":"Sr"}},"NextToken":{}}}},"ListIdentityPools":{"input":{"type":"structure","required":["MaxResults"],"members":{"MaxResults":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","members":{"IdentityPools":{"type":"list","member":{"type":"structure","members":{"IdentityPoolId":{},"IdentityPoolName":{}}}},"NextToken":{}}}},"LookupDeveloperIdentity":{"input":{"type":"structure","required":["IdentityPoolId"],"members":{"IdentityPoolId":{},"IdentityId":{},"DeveloperUserIdentifier":{},"MaxResults":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","members":{"IdentityId":{},"DeveloperUserIdentifierList":{"type":"list","member":{}},"NextToken":{}}}},"MergeDeveloperIdentities":{"input":{"type":"structure","required":["SourceUserIdentifier","DestinationUserIdentifier","DeveloperProviderName","IdentityPoolId"],"members":{"SourceUserIdentifier":{},"DestinationUserIdentifier":{},"DeveloperProviderName":{},"IdentityPoolId":{}}},"output":{"type":"structure","members":{"IdentityId":{}}}},"SetIdentityPoolRoles":{"input":{"type":"structure","required":["IdentityPoolId","Roles"],"members":{"IdentityPoolId":{},"Roles":{"shape":"S18"},"RoleMappings":{"shape":"S1a"}}}},"UnlinkDeveloperIdentity":{"input":{"type":"structure","required":["IdentityId","IdentityPoolId","DeveloperProviderName","DeveloperUserIdentifier"],"members":{"IdentityId":{},"IdentityPoolId":{},"DeveloperProviderName":{},"DeveloperUserIdentifier":{}}}},"UnlinkIdentity":{"input":{"type":"structure","required":["IdentityId","Logins","LoginsToRemove"],"members":{"IdentityId":{},"Logins":{"shape":"Sw"},"LoginsToRemove":{"shape":"Ss"}}}},"UpdateIdentityPool":{"input":{"shape":"Sg"},"output":{"shape":"Sg"}}},"shapes":{"S4":{"type":"map","key":{},"value":{}},"S8":{"type":"list","member":{}},"Sa":{"type":"list","member":{"type":"structure","members":{"ProviderName":{},"ClientId":{},"ServerSideTokenCheck":{"type":"boolean"}}}},"Sf":{"type":"list","member":{}},"Sg":{"type":"structure","required":["IdentityPoolId","IdentityPoolName","AllowUnauthenticatedIdentities"],"members":{"IdentityPoolId":{},"IdentityPoolName":{},"AllowUnauthenticatedIdentities":{"type":"boolean"},"SupportedLoginProviders":{"shape":"S4"},"DeveloperProviderName":{},"OpenIdConnectProviderARNs":{"shape":"S8"},"CognitoIdentityProviders":{"shape":"Sa"},"SamlProviderARNs":{"shape":"Sf"}}},"Sr":{"type":"structure","members":{"IdentityId":{},"Logins":{"shape":"Ss"},"CreationDate":{"type":"timestamp"},"LastModifiedDate":{"type":"timestamp"}}},"Ss":{"type":"list","member":{}},"Sw":{"type":"map","key":{},"value":{}},"S18":{"type":"map","key":{},"value":{}},"S1a":{"type":"map","key":{},"value":{"type":"structure","required":["Type"],"members":{"Type":{},"AmbiguousRoleResolution":{},"RulesConfiguration":{"type":"structure","required":["Rules"],"members":{"Rules":{"type":"list","member":{"type":"structure","required":["Claim","MatchType","Value","RoleARN"],"members":{"Claim":{},"MatchType":{},"Value":{},"RoleARN":{}}}}}}}}}}} /***/ }), /***/ "../../../../aws-sdk/apis/cognito-identity-2014-06-30.paginators.json": /***/ (function(module, exports) { module.exports = {"pagination":{}} /***/ }), /***/ "../../../../aws-sdk/apis/cognito-idp-2016-04-18.min.json": /***/ (function(module, exports) { module.exports = {"version":"2.0","metadata":{"apiVersion":"2016-04-18","endpointPrefix":"cognito-idp","jsonVersion":"1.1","protocol":"json","serviceFullName":"Amazon Cognito Identity Provider","signatureVersion":"v4","targetPrefix":"AWSCognitoIdentityProviderService","uid":"cognito-idp-2016-04-18"},"operations":{"AddCustomAttributes":{"input":{"type":"structure","required":["UserPoolId","CustomAttributes"],"members":{"UserPoolId":{},"CustomAttributes":{"type":"list","member":{"shape":"S4"}}}},"output":{"type":"structure","members":{}}},"AdminAddUserToGroup":{"input":{"type":"structure","required":["UserPoolId","Username","GroupName"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"GroupName":{}}}},"AdminConfirmSignUp":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}}},"AdminCreateUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"UserAttributes":{"shape":"Si"},"ValidationData":{"shape":"Si"},"TemporaryPassword":{"shape":"Sm"},"ForceAliasCreation":{"type":"boolean"},"MessageAction":{},"DesiredDeliveryMediums":{"type":"list","member":{}}}},"output":{"type":"structure","members":{"User":{"shape":"Ss"}}}},"AdminDeleteUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}}},"AdminDeleteUserAttributes":{"input":{"type":"structure","required":["UserPoolId","Username","UserAttributeNames"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"UserAttributeNames":{"shape":"Sz"}}},"output":{"type":"structure","members":{}}},"AdminDisableProviderForUser":{"input":{"type":"structure","required":["UserPoolId","User"],"members":{"UserPoolId":{},"User":{"shape":"S12"}}},"output":{"type":"structure","members":{}}},"AdminDisableUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}}},"AdminEnableUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}}},"AdminForgetDevice":{"input":{"type":"structure","required":["UserPoolId","Username","DeviceKey"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"DeviceKey":{}}}},"AdminGetDevice":{"input":{"type":"structure","required":["DeviceKey","UserPoolId","Username"],"members":{"DeviceKey":{},"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","required":["Device"],"members":{"Device":{"shape":"S1d"}}}},"AdminGetUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","required":["Username"],"members":{"Username":{"shape":"Sd"},"UserAttributes":{"shape":"Si"},"UserCreateDate":{"type":"timestamp"},"UserLastModifiedDate":{"type":"timestamp"},"Enabled":{"type":"boolean"},"UserStatus":{},"MFAOptions":{"shape":"Sv"}}}},"AdminInitiateAuth":{"input":{"type":"structure","required":["UserPoolId","ClientId","AuthFlow"],"members":{"UserPoolId":{},"ClientId":{"shape":"S1h"},"AuthFlow":{},"AuthParameters":{"shape":"S1j"},"ClientMetadata":{"shape":"S1k"}}},"output":{"type":"structure","members":{"ChallengeName":{},"Session":{},"ChallengeParameters":{"shape":"S1o"},"AuthenticationResult":{"shape":"S1p"}}}},"AdminLinkProviderForUser":{"input":{"type":"structure","required":["UserPoolId","DestinationUser","SourceUser"],"members":{"UserPoolId":{},"DestinationUser":{"shape":"S12"},"SourceUser":{"shape":"S12"}}},"output":{"type":"structure","members":{}}},"AdminListDevices":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"Limit":{"type":"integer"},"PaginationToken":{}}},"output":{"type":"structure","members":{"Devices":{"shape":"S1z"},"PaginationToken":{}}}},"AdminListGroupsForUser":{"input":{"type":"structure","required":["Username","UserPoolId"],"members":{"Username":{"shape":"Sd"},"UserPoolId":{},"Limit":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","members":{"Groups":{"shape":"S23"},"NextToken":{}}}},"AdminRemoveUserFromGroup":{"input":{"type":"structure","required":["UserPoolId","Username","GroupName"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"GroupName":{}}}},"AdminResetUserPassword":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}}},"AdminRespondToAuthChallenge":{"input":{"type":"structure","required":["UserPoolId","ClientId","ChallengeName"],"members":{"UserPoolId":{},"ClientId":{"shape":"S1h"},"ChallengeName":{},"ChallengeResponses":{"shape":"S2c"},"Session":{}}},"output":{"type":"structure","members":{"ChallengeName":{},"Session":{},"ChallengeParameters":{"shape":"S1o"},"AuthenticationResult":{"shape":"S1p"}}}},"AdminSetUserSettings":{"input":{"type":"structure","required":["UserPoolId","Username","MFAOptions"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"MFAOptions":{"shape":"Sv"}}},"output":{"type":"structure","members":{}}},"AdminUpdateDeviceStatus":{"input":{"type":"structure","required":["UserPoolId","Username","DeviceKey"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"DeviceKey":{},"DeviceRememberedStatus":{}}},"output":{"type":"structure","members":{}}},"AdminUpdateUserAttributes":{"input":{"type":"structure","required":["UserPoolId","Username","UserAttributes"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"UserAttributes":{"shape":"Si"}}},"output":{"type":"structure","members":{}}},"AdminUserGlobalSignOut":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}}},"ChangePassword":{"input":{"type":"structure","required":["PreviousPassword","ProposedPassword","AccessToken"],"members":{"PreviousPassword":{"shape":"Sm"},"ProposedPassword":{"shape":"Sm"},"AccessToken":{"shape":"S1q"}}},"output":{"type":"structure","members":{}},"authtype":"none"},"ConfirmDevice":{"input":{"type":"structure","required":["AccessToken","DeviceKey"],"members":{"AccessToken":{"shape":"S1q"},"DeviceKey":{},"DeviceSecretVerifierConfig":{"type":"structure","members":{"PasswordVerifier":{},"Salt":{}}},"DeviceName":{}}},"output":{"type":"structure","members":{"UserConfirmationNecessary":{"type":"boolean"}}}},"ConfirmForgotPassword":{"input":{"type":"structure","required":["ClientId","Username","ConfirmationCode","Password"],"members":{"ClientId":{"shape":"S1h"},"SecretHash":{"shape":"S2u"},"Username":{"shape":"Sd"},"ConfirmationCode":{},"Password":{"shape":"Sm"}}},"output":{"type":"structure","members":{}},"authtype":"none"},"ConfirmSignUp":{"input":{"type":"structure","required":["ClientId","Username","ConfirmationCode"],"members":{"ClientId":{"shape":"S1h"},"SecretHash":{"shape":"S2u"},"Username":{"shape":"Sd"},"ConfirmationCode":{},"ForceAliasCreation":{"type":"boolean"}}},"output":{"type":"structure","members":{}},"authtype":"none"},"CreateGroup":{"input":{"type":"structure","required":["GroupName","UserPoolId"],"members":{"GroupName":{},"UserPoolId":{},"Description":{},"RoleArn":{},"Precedence":{"type":"integer"}}},"output":{"type":"structure","members":{"Group":{"shape":"S24"}}}},"CreateIdentityProvider":{"input":{"type":"structure","required":["UserPoolId","ProviderName","ProviderType","ProviderDetails"],"members":{"UserPoolId":{},"ProviderName":{},"ProviderType":{},"ProviderDetails":{"shape":"S34"},"AttributeMapping":{"shape":"S35"},"IdpIdentifiers":{"shape":"S37"}}},"output":{"type":"structure","required":["IdentityProvider"],"members":{"IdentityProvider":{"shape":"S3a"}}}},"CreateResourceServer":{"input":{"type":"structure","required":["UserPoolId","Identifier","Name"],"members":{"UserPoolId":{},"Identifier":{},"Name":{},"Scopes":{"shape":"S3e"}}},"output":{"type":"structure","required":["ResourceServer"],"members":{"ResourceServer":{"shape":"S3j"}}}},"CreateUserImportJob":{"input":{"type":"structure","required":["JobName","UserPoolId","CloudWatchLogsRoleArn"],"members":{"JobName":{},"UserPoolId":{},"CloudWatchLogsRoleArn":{}}},"output":{"type":"structure","members":{"UserImportJob":{"shape":"S3n"}}}},"CreateUserPool":{"input":{"type":"structure","required":["PoolName"],"members":{"PoolName":{},"Policies":{"shape":"S3v"},"LambdaConfig":{"shape":"S3y"},"AutoVerifiedAttributes":{"shape":"S3z"},"AliasAttributes":{"shape":"S41"},"UsernameAttributes":{"shape":"S43"},"SmsVerificationMessage":{},"EmailVerificationMessage":{},"EmailVerificationSubject":{},"VerificationMessageTemplate":{"shape":"S48"},"SmsAuthenticationMessage":{},"MfaConfiguration":{},"DeviceConfiguration":{"shape":"S4d"},"EmailConfiguration":{"shape":"S4e"},"SmsConfiguration":{"shape":"S4g"},"UserPoolTags":{"shape":"S4h"},"AdminCreateUserConfig":{"shape":"S4i"},"Schema":{"shape":"S4l"}}},"output":{"type":"structure","members":{"UserPool":{"shape":"S4n"}}}},"CreateUserPoolClient":{"input":{"type":"structure","required":["UserPoolId","ClientName"],"members":{"UserPoolId":{},"ClientName":{},"GenerateSecret":{"type":"boolean"},"RefreshTokenValidity":{"type":"integer"},"ReadAttributes":{"shape":"S4t"},"WriteAttributes":{"shape":"S4t"},"ExplicitAuthFlows":{"shape":"S4v"},"SupportedIdentityProviders":{"shape":"S4x"},"CallbackURLs":{"shape":"S4y"},"LogoutURLs":{"shape":"S50"},"DefaultRedirectURI":{},"AllowedOAuthFlows":{"shape":"S51"},"AllowedOAuthScopes":{"shape":"S53"},"AllowedOAuthFlowsUserPoolClient":{"type":"boolean"}}},"output":{"type":"structure","members":{"UserPoolClient":{"shape":"S56"}}}},"CreateUserPoolDomain":{"input":{"type":"structure","required":["Domain","UserPoolId"],"members":{"Domain":{},"UserPoolId":{}}},"output":{"type":"structure","members":{}}},"DeleteGroup":{"input":{"type":"structure","required":["GroupName","UserPoolId"],"members":{"GroupName":{},"UserPoolId":{}}}},"DeleteIdentityProvider":{"input":{"type":"structure","required":["UserPoolId","ProviderName"],"members":{"UserPoolId":{},"ProviderName":{}}}},"DeleteResourceServer":{"input":{"type":"structure","required":["UserPoolId","Identifier"],"members":{"UserPoolId":{},"Identifier":{}}}},"DeleteUser":{"input":{"type":"structure","required":["AccessToken"],"members":{"AccessToken":{"shape":"S1q"}}},"authtype":"none"},"DeleteUserAttributes":{"input":{"type":"structure","required":["UserAttributeNames","AccessToken"],"members":{"UserAttributeNames":{"shape":"Sz"},"AccessToken":{"shape":"S1q"}}},"output":{"type":"structure","members":{}},"authtype":"none"},"DeleteUserPool":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{}}}},"DeleteUserPoolClient":{"input":{"type":"structure","required":["UserPoolId","ClientId"],"members":{"UserPoolId":{},"ClientId":{"shape":"S1h"}}}},"DeleteUserPoolDomain":{"input":{"type":"structure","required":["Domain","UserPoolId"],"members":{"Domain":{},"UserPoolId":{}}},"output":{"type":"structure","members":{}}},"DescribeIdentityProvider":{"input":{"type":"structure","required":["UserPoolId","ProviderName"],"members":{"UserPoolId":{},"ProviderName":{}}},"output":{"type":"structure","required":["IdentityProvider"],"members":{"IdentityProvider":{"shape":"S3a"}}}},"DescribeResourceServer":{"input":{"type":"structure","required":["UserPoolId","Identifier"],"members":{"UserPoolId":{},"Identifier":{}}},"output":{"type":"structure","required":["ResourceServer"],"members":{"ResourceServer":{"shape":"S3j"}}}},"DescribeUserImportJob":{"input":{"type":"structure","required":["UserPoolId","JobId"],"members":{"UserPoolId":{},"JobId":{}}},"output":{"type":"structure","members":{"UserImportJob":{"shape":"S3n"}}}},"DescribeUserPool":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{}}},"output":{"type":"structure","members":{"UserPool":{"shape":"S4n"}}}},"DescribeUserPoolClient":{"input":{"type":"structure","required":["UserPoolId","ClientId"],"members":{"UserPoolId":{},"ClientId":{"shape":"S1h"}}},"output":{"type":"structure","members":{"UserPoolClient":{"shape":"S56"}}}},"DescribeUserPoolDomain":{"input":{"type":"structure","required":["Domain"],"members":{"Domain":{}}},"output":{"type":"structure","members":{"DomainDescription":{"type":"structure","members":{"UserPoolId":{},"AWSAccountId":{},"Domain":{},"S3Bucket":{},"CloudFrontDistribution":{},"Version":{},"Status":{}}}}}},"ForgetDevice":{"input":{"type":"structure","required":["DeviceKey"],"members":{"AccessToken":{"shape":"S1q"},"DeviceKey":{}}}},"ForgotPassword":{"input":{"type":"structure","required":["ClientId","Username"],"members":{"ClientId":{"shape":"S1h"},"SecretHash":{"shape":"S2u"},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{"CodeDeliveryDetails":{"shape":"S65"}}},"authtype":"none"},"GetCSVHeader":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{}}},"output":{"type":"structure","members":{"UserPoolId":{},"CSVHeader":{"type":"list","member":{}}}}},"GetDevice":{"input":{"type":"structure","required":["DeviceKey"],"members":{"DeviceKey":{},"AccessToken":{"shape":"S1q"}}},"output":{"type":"structure","required":["Device"],"members":{"Device":{"shape":"S1d"}}}},"GetGroup":{"input":{"type":"structure","required":["GroupName","UserPoolId"],"members":{"GroupName":{},"UserPoolId":{}}},"output":{"type":"structure","members":{"Group":{"shape":"S24"}}}},"GetIdentityProviderByIdentifier":{"input":{"type":"structure","required":["UserPoolId","IdpIdentifier"],"members":{"UserPoolId":{},"IdpIdentifier":{}}},"output":{"type":"structure","required":["IdentityProvider"],"members":{"IdentityProvider":{"shape":"S3a"}}}},"GetUICustomization":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"ClientId":{"shape":"S1h"}}},"output":{"type":"structure","required":["UICustomization"],"members":{"UICustomization":{"shape":"S6h"}}}},"GetUser":{"input":{"type":"structure","required":["AccessToken"],"members":{"AccessToken":{"shape":"S1q"}}},"output":{"type":"structure","required":["Username","UserAttributes"],"members":{"Username":{"shape":"Sd"},"UserAttributes":{"shape":"Si"},"MFAOptions":{"shape":"Sv"}}},"authtype":"none"},"GetUserAttributeVerificationCode":{"input":{"type":"structure","required":["AccessToken","AttributeName"],"members":{"AccessToken":{"shape":"S1q"},"AttributeName":{}}},"output":{"type":"structure","members":{"CodeDeliveryDetails":{"shape":"S65"}}},"authtype":"none"},"GlobalSignOut":{"input":{"type":"structure","required":["AccessToken"],"members":{"AccessToken":{"shape":"S1q"}}},"output":{"type":"structure","members":{}}},"InitiateAuth":{"input":{"type":"structure","required":["AuthFlow","ClientId"],"members":{"AuthFlow":{},"AuthParameters":{"shape":"S1j"},"ClientMetadata":{"shape":"S1k"},"ClientId":{"shape":"S1h"}}},"output":{"type":"structure","members":{"ChallengeName":{},"Session":{},"ChallengeParameters":{"shape":"S1o"},"AuthenticationResult":{"shape":"S1p"}}}},"ListDevices":{"input":{"type":"structure","required":["AccessToken"],"members":{"AccessToken":{"shape":"S1q"},"Limit":{"type":"integer"},"PaginationToken":{}}},"output":{"type":"structure","members":{"Devices":{"shape":"S1z"},"PaginationToken":{}}}},"ListGroups":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"Limit":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","members":{"Groups":{"shape":"S23"},"NextToken":{}}}},"ListIdentityProviders":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"MaxResults":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","required":["Providers"],"members":{"Providers":{"type":"list","member":{"type":"structure","members":{"ProviderName":{},"ProviderType":{},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"}}}},"NextToken":{}}}},"ListResourceServers":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"MaxResults":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","required":["ResourceServers"],"members":{"ResourceServers":{"type":"list","member":{"shape":"S3j"}},"NextToken":{}}}},"ListUserImportJobs":{"input":{"type":"structure","required":["UserPoolId","MaxResults"],"members":{"UserPoolId":{},"MaxResults":{"type":"integer"},"PaginationToken":{}}},"output":{"type":"structure","members":{"UserImportJobs":{"type":"list","member":{"shape":"S3n"}},"PaginationToken":{}}}},"ListUserPoolClients":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"MaxResults":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","members":{"UserPoolClients":{"type":"list","member":{"type":"structure","members":{"ClientId":{"shape":"S1h"},"UserPoolId":{},"ClientName":{}}}},"NextToken":{}}}},"ListUserPools":{"input":{"type":"structure","required":["MaxResults"],"members":{"NextToken":{},"MaxResults":{"type":"integer"}}},"output":{"type":"structure","members":{"UserPools":{"type":"list","member":{"type":"structure","members":{"Id":{},"Name":{},"LambdaConfig":{"shape":"S3y"},"Status":{},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"}}}},"NextToken":{}}}},"ListUsers":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"AttributesToGet":{"type":"list","member":{}},"Limit":{"type":"integer"},"PaginationToken":{},"Filter":{}}},"output":{"type":"structure","members":{"Users":{"shape":"S7o"},"PaginationToken":{}}}},"ListUsersInGroup":{"input":{"type":"structure","required":["UserPoolId","GroupName"],"members":{"UserPoolId":{},"GroupName":{},"Limit":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","members":{"Users":{"shape":"S7o"},"NextToken":{}}}},"ResendConfirmationCode":{"input":{"type":"structure","required":["ClientId","Username"],"members":{"ClientId":{"shape":"S1h"},"SecretHash":{"shape":"S2u"},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{"CodeDeliveryDetails":{"shape":"S65"}}},"authtype":"none"},"RespondToAuthChallenge":{"input":{"type":"structure","required":["ClientId","ChallengeName"],"members":{"ClientId":{"shape":"S1h"},"ChallengeName":{},"Session":{},"ChallengeResponses":{"shape":"S2c"}}},"output":{"type":"structure","members":{"ChallengeName":{},"Session":{},"ChallengeParameters":{"shape":"S1o"},"AuthenticationResult":{"shape":"S1p"}}}},"SetUICustomization":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"ClientId":{"shape":"S1h"},"CSS":{},"ImageFile":{"type":"blob"}}},"output":{"type":"structure","required":["UICustomization"],"members":{"UICustomization":{"shape":"S6h"}}}},"SetUserSettings":{"input":{"type":"structure","required":["AccessToken","MFAOptions"],"members":{"AccessToken":{"shape":"S1q"},"MFAOptions":{"shape":"Sv"}}},"output":{"type":"structure","members":{}},"authtype":"none"},"SignUp":{"input":{"type":"structure","required":["ClientId","Username","Password"],"members":{"ClientId":{"shape":"S1h"},"SecretHash":{"shape":"S2u"},"Username":{"shape":"Sd"},"Password":{"shape":"Sm"},"UserAttributes":{"shape":"Si"},"ValidationData":{"shape":"Si"}}},"output":{"type":"structure","required":["UserConfirmed","UserSub"],"members":{"UserConfirmed":{"type":"boolean"},"CodeDeliveryDetails":{"shape":"S65"},"UserSub":{}}},"authtype":"none"},"StartUserImportJob":{"input":{"type":"structure","required":["UserPoolId","JobId"],"members":{"UserPoolId":{},"JobId":{}}},"output":{"type":"structure","members":{"UserImportJob":{"shape":"S3n"}}}},"StopUserImportJob":{"input":{"type":"structure","required":["UserPoolId","JobId"],"members":{"UserPoolId":{},"JobId":{}}},"output":{"type":"structure","members":{"UserImportJob":{"shape":"S3n"}}}},"UpdateDeviceStatus":{"input":{"type":"structure","required":["AccessToken","DeviceKey"],"members":{"AccessToken":{"shape":"S1q"},"DeviceKey":{},"DeviceRememberedStatus":{}}},"output":{"type":"structure","members":{}}},"UpdateGroup":{"input":{"type":"structure","required":["GroupName","UserPoolId"],"members":{"GroupName":{},"UserPoolId":{},"Description":{},"RoleArn":{},"Precedence":{"type":"integer"}}},"output":{"type":"structure","members":{"Group":{"shape":"S24"}}}},"UpdateIdentityProvider":{"input":{"type":"structure","required":["UserPoolId","ProviderName"],"members":{"UserPoolId":{},"ProviderName":{},"ProviderDetails":{"shape":"S34"},"AttributeMapping":{"shape":"S35"},"IdpIdentifiers":{"shape":"S37"}}},"output":{"type":"structure","required":["IdentityProvider"],"members":{"IdentityProvider":{"shape":"S3a"}}}},"UpdateResourceServer":{"input":{"type":"structure","required":["UserPoolId","Identifier","Name"],"members":{"UserPoolId":{},"Identifier":{},"Name":{},"Scopes":{"shape":"S3e"}}},"output":{"type":"structure","required":["ResourceServer"],"members":{"ResourceServer":{"shape":"S3j"}}}},"UpdateUserAttributes":{"input":{"type":"structure","required":["UserAttributes","AccessToken"],"members":{"UserAttributes":{"shape":"Si"},"AccessToken":{"shape":"S1q"}}},"output":{"type":"structure","members":{"CodeDeliveryDetailsList":{"type":"list","member":{"shape":"S65"}}}},"authtype":"none"},"UpdateUserPool":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"Policies":{"shape":"S3v"},"LambdaConfig":{"shape":"S3y"},"AutoVerifiedAttributes":{"shape":"S3z"},"SmsVerificationMessage":{},"EmailVerificationMessage":{},"EmailVerificationSubject":{},"VerificationMessageTemplate":{"shape":"S48"},"SmsAuthenticationMessage":{},"MfaConfiguration":{},"DeviceConfiguration":{"shape":"S4d"},"EmailConfiguration":{"shape":"S4e"},"SmsConfiguration":{"shape":"S4g"},"UserPoolTags":{"shape":"S4h"},"AdminCreateUserConfig":{"shape":"S4i"}}},"output":{"type":"structure","members":{}}},"UpdateUserPoolClient":{"input":{"type":"structure","required":["UserPoolId","ClientId"],"members":{"UserPoolId":{},"ClientId":{"shape":"S1h"},"ClientName":{},"RefreshTokenValidity":{"type":"integer"},"ReadAttributes":{"shape":"S4t"},"WriteAttributes":{"shape":"S4t"},"ExplicitAuthFlows":{"shape":"S4v"},"SupportedIdentityProviders":{"shape":"S4x"},"CallbackURLs":{"shape":"S4y"},"LogoutURLs":{"shape":"S50"},"DefaultRedirectURI":{},"AllowedOAuthFlows":{"shape":"S51"},"AllowedOAuthScopes":{"shape":"S53"},"AllowedOAuthFlowsUserPoolClient":{"type":"boolean"}}},"output":{"type":"structure","members":{"UserPoolClient":{"shape":"S56"}}}},"VerifyUserAttribute":{"input":{"type":"structure","required":["AccessToken","AttributeName","Code"],"members":{"AccessToken":{"shape":"S1q"},"AttributeName":{},"Code":{}}},"output":{"type":"structure","members":{}},"authtype":"none"}},"shapes":{"S4":{"type":"structure","members":{"Name":{},"AttributeDataType":{},"DeveloperOnlyAttribute":{"type":"boolean"},"Mutable":{"type":"boolean"},"Required":{"type":"boolean"},"NumberAttributeConstraints":{"type":"structure","members":{"MinValue":{},"MaxValue":{}}},"StringAttributeConstraints":{"type":"structure","members":{"MinLength":{},"MaxLength":{}}}}},"Sd":{"type":"string","sensitive":true},"Si":{"type":"list","member":{"type":"structure","required":["Name"],"members":{"Name":{},"Value":{"type":"string","sensitive":true}}}},"Sm":{"type":"string","sensitive":true},"Ss":{"type":"structure","members":{"Username":{"shape":"Sd"},"Attributes":{"shape":"Si"},"UserCreateDate":{"type":"timestamp"},"UserLastModifiedDate":{"type":"timestamp"},"Enabled":{"type":"boolean"},"UserStatus":{},"MFAOptions":{"shape":"Sv"}}},"Sv":{"type":"list","member":{"type":"structure","members":{"DeliveryMedium":{},"AttributeName":{}}}},"Sz":{"type":"list","member":{}},"S12":{"type":"structure","members":{"ProviderName":{},"ProviderAttributeName":{},"ProviderAttributeValue":{}}},"S1d":{"type":"structure","members":{"DeviceKey":{},"DeviceAttributes":{"shape":"Si"},"DeviceCreateDate":{"type":"timestamp"},"DeviceLastModifiedDate":{"type":"timestamp"},"DeviceLastAuthenticatedDate":{"type":"timestamp"}}},"S1h":{"type":"string","sensitive":true},"S1j":{"type":"map","key":{},"value":{}},"S1k":{"type":"map","key":{},"value":{}},"S1o":{"type":"map","key":{},"value":{}},"S1p":{"type":"structure","members":{"AccessToken":{"shape":"S1q"},"ExpiresIn":{"type":"integer"},"TokenType":{},"RefreshToken":{"shape":"S1q"},"IdToken":{"shape":"S1q"},"NewDeviceMetadata":{"type":"structure","members":{"DeviceKey":{},"DeviceGroupKey":{}}}}},"S1q":{"type":"string","sensitive":true},"S1z":{"type":"list","member":{"shape":"S1d"}},"S23":{"type":"list","member":{"shape":"S24"}},"S24":{"type":"structure","members":{"GroupName":{},"UserPoolId":{},"Description":{},"RoleArn":{},"Precedence":{"type":"integer"},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"}}},"S2c":{"type":"map","key":{},"value":{}},"S2u":{"type":"string","sensitive":true},"S34":{"type":"map","key":{},"value":{}},"S35":{"type":"map","key":{},"value":{}},"S37":{"type":"list","member":{}},"S3a":{"type":"structure","members":{"UserPoolId":{},"ProviderName":{},"ProviderType":{},"ProviderDetails":{"shape":"S34"},"AttributeMapping":{"shape":"S35"},"IdpIdentifiers":{"shape":"S37"},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"}}},"S3e":{"type":"list","member":{"type":"structure","required":["ScopeName","ScopeDescription"],"members":{"ScopeName":{},"ScopeDescription":{}}}},"S3j":{"type":"structure","members":{"UserPoolId":{},"Identifier":{},"Name":{},"Scopes":{"shape":"S3e"}}},"S3n":{"type":"structure","members":{"JobName":{},"JobId":{},"UserPoolId":{},"PreSignedUrl":{},"CreationDate":{"type":"timestamp"},"StartDate":{"type":"timestamp"},"CompletionDate":{"type":"timestamp"},"Status":{},"CloudWatchLogsRoleArn":{},"ImportedUsers":{"type":"long"},"SkippedUsers":{"type":"long"},"FailedUsers":{"type":"long"},"CompletionMessage":{}}},"S3v":{"type":"structure","members":{"PasswordPolicy":{"type":"structure","members":{"MinimumLength":{"type":"integer"},"RequireUppercase":{"type":"boolean"},"RequireLowercase":{"type":"boolean"},"RequireNumbers":{"type":"boolean"},"RequireSymbols":{"type":"boolean"}}}}},"S3y":{"type":"structure","members":{"PreSignUp":{},"CustomMessage":{},"PostConfirmation":{},"PreAuthentication":{},"PostAuthentication":{},"DefineAuthChallenge":{},"CreateAuthChallenge":{},"VerifyAuthChallengeResponse":{}}},"S3z":{"type":"list","member":{}},"S41":{"type":"list","member":{}},"S43":{"type":"list","member":{}},"S48":{"type":"structure","members":{"SmsMessage":{},"EmailMessage":{},"EmailSubject":{},"EmailMessageByLink":{},"EmailSubjectByLink":{},"DefaultEmailOption":{}}},"S4d":{"type":"structure","members":{"ChallengeRequiredOnNewDevice":{"type":"boolean"},"DeviceOnlyRememberedOnUserPrompt":{"type":"boolean"}}},"S4e":{"type":"structure","members":{"SourceArn":{},"ReplyToEmailAddress":{}}},"S4g":{"type":"structure","required":["SnsCallerArn"],"members":{"SnsCallerArn":{},"ExternalId":{}}},"S4h":{"type":"map","key":{},"value":{}},"S4i":{"type":"structure","members":{"AllowAdminCreateUserOnly":{"type":"boolean"},"UnusedAccountValidityDays":{"type":"integer"},"InviteMessageTemplate":{"type":"structure","members":{"SMSMessage":{},"EmailMessage":{},"EmailSubject":{}}}}},"S4l":{"type":"list","member":{"shape":"S4"}},"S4n":{"type":"structure","members":{"Id":{},"Name":{},"Policies":{"shape":"S3v"},"LambdaConfig":{"shape":"S3y"},"Status":{},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"},"SchemaAttributes":{"shape":"S4l"},"AutoVerifiedAttributes":{"shape":"S3z"},"AliasAttributes":{"shape":"S41"},"UsernameAttributes":{"shape":"S43"},"SmsVerificationMessage":{},"EmailVerificationMessage":{},"EmailVerificationSubject":{},"VerificationMessageTemplate":{"shape":"S48"},"SmsAuthenticationMessage":{},"MfaConfiguration":{},"DeviceConfiguration":{"shape":"S4d"},"EstimatedNumberOfUsers":{"type":"integer"},"EmailConfiguration":{"shape":"S4e"},"SmsConfiguration":{"shape":"S4g"},"UserPoolTags":{"shape":"S4h"},"SmsConfigurationFailure":{},"EmailConfigurationFailure":{},"AdminCreateUserConfig":{"shape":"S4i"}}},"S4t":{"type":"list","member":{}},"S4v":{"type":"list","member":{}},"S4x":{"type":"list","member":{}},"S4y":{"type":"list","member":{}},"S50":{"type":"list","member":{}},"S51":{"type":"list","member":{}},"S53":{"type":"list","member":{}},"S56":{"type":"structure","members":{"UserPoolId":{},"ClientName":{},"ClientId":{"shape":"S1h"},"ClientSecret":{"type":"string","sensitive":true},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"},"RefreshTokenValidity":{"type":"integer"},"ReadAttributes":{"shape":"S4t"},"WriteAttributes":{"shape":"S4t"},"ExplicitAuthFlows":{"shape":"S4v"},"SupportedIdentityProviders":{"shape":"S4x"},"CallbackURLs":{"shape":"S4y"},"LogoutURLs":{"shape":"S50"},"DefaultRedirectURI":{},"AllowedOAuthFlows":{"shape":"S51"},"AllowedOAuthScopes":{"shape":"S53"},"AllowedOAuthFlowsUserPoolClient":{"type":"boolean"}}},"S65":{"type":"structure","members":{"Destination":{},"DeliveryMedium":{},"AttributeName":{}}},"S6h":{"type":"structure","members":{"UserPoolId":{},"ClientId":{"shape":"S1h"},"ImageUrl":{},"CSS":{},"CSSVersion":{},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"}}},"S7o":{"type":"list","member":{"shape":"Ss"}}}} /***/ }), /***/ "../../../../aws-sdk/apis/cognito-idp-2016-04-18.paginators.json": /***/ (function(module, exports) { module.exports = {"pagination":{}} /***/ }), /***/ "../../../../aws-sdk/apis/metadata.json": /***/ (function(module, exports) { module.exports = {"acm":{"name":"ACM","cors":true},"apigateway":{"name":"APIGateway","cors":true},"applicationautoscaling":{"prefix":"application-autoscaling","name":"ApplicationAutoScaling","cors":true},"appstream":{"name":"AppStream"},"autoscaling":{"name":"AutoScaling","cors":true},"batch":{"name":"Batch"},"budgets":{"name":"Budgets"},"clouddirectory":{"name":"CloudDirectory"},"cloudformation":{"name":"CloudFormation","cors":true},"cloudfront":{"name":"CloudFront","versions":["2013-05-12*","2013-11-11*","2014-05-31*","2014-10-21*","2014-11-06*","2015-04-17*","2015-07-27*","2015-09-17*","2016-01-13*","2016-01-28*","2016-08-01*","2016-08-20*","2016-09-07*","2016-09-29*","2016-11-25*"],"cors":true},"cloudhsm":{"name":"CloudHSM","cors":true},"cloudsearch":{"name":"CloudSearch"},"cloudsearchdomain":{"name":"CloudSearchDomain"},"cloudtrail":{"name":"CloudTrail","cors":true},"cloudwatch":{"prefix":"monitoring","name":"CloudWatch","cors":true},"cloudwatchevents":{"prefix":"events","name":"CloudWatchEvents","versions":["2014-02-03*"],"cors":true},"cloudwatchlogs":{"prefix":"logs","name":"CloudWatchLogs","cors":true},"codebuild":{"name":"CodeBuild"},"codecommit":{"name":"CodeCommit","cors":true},"codedeploy":{"name":"CodeDeploy","cors":true},"codepipeline":{"name":"CodePipeline","cors":true},"cognitoidentity":{"prefix":"cognito-identity","name":"CognitoIdentity","cors":true},"cognitoidentityserviceprovider":{"prefix":"cognito-idp","name":"CognitoIdentityServiceProvider","cors":true},"cognitosync":{"prefix":"cognito-sync","name":"CognitoSync","cors":true},"configservice":{"prefix":"config","name":"ConfigService","cors":true},"cur":{"name":"CUR","cors":true},"datapipeline":{"name":"DataPipeline"},"devicefarm":{"name":"DeviceFarm","cors":true},"directconnect":{"name":"DirectConnect","cors":true},"directoryservice":{"prefix":"ds","name":"DirectoryService"},"discovery":{"name":"Discovery"},"dms":{"name":"DMS"},"dynamodb":{"name":"DynamoDB","cors":true},"dynamodbstreams":{"prefix":"streams.dynamodb","name":"DynamoDBStreams","cors":true},"ec2":{"name":"EC2","versions":["2013-06-15*","2013-10-15*","2014-02-01*","2014-05-01*","2014-06-15*","2014-09-01*","2014-10-01*","2015-03-01*","2015-04-15*","2015-10-01*","2016-04-01*","2016-09-15*"],"cors":true},"ecr":{"name":"ECR","cors":true},"ecs":{"name":"ECS","cors":true},"efs":{"prefix":"elasticfilesystem","name":"EFS","cors":true},"elasticache":{"name":"ElastiCache","versions":["2012-11-15*","2014-03-24*","2014-07-15*","2014-09-30*"],"cors":true},"elasticbeanstalk":{"name":"ElasticBeanstalk","cors":true},"elb":{"prefix":"elasticloadbalancing","name":"ELB","cors":true},"elbv2":{"prefix":"elasticloadbalancingv2","name":"ELBv2","cors":true},"emr":{"prefix":"elasticmapreduce","name":"EMR","cors":true},"es":{"name":"ES"},"elastictranscoder":{"name":"ElasticTranscoder","cors":true},"firehose":{"name":"Firehose","cors":true},"gamelift":{"name":"GameLift","cors":true},"glacier":{"name":"Glacier"},"health":{"name":"Health"},"iam":{"name":"IAM"},"importexport":{"name":"ImportExport"},"inspector":{"name":"Inspector","versions":["2015-08-18*"],"cors":true},"iot":{"name":"Iot","cors":true},"iotdata":{"prefix":"iot-data","name":"IotData","cors":true},"kinesis":{"name":"Kinesis","cors":true},"kinesisanalytics":{"name":"KinesisAnalytics"},"kms":{"name":"KMS","cors":true},"lambda":{"name":"Lambda","cors":true},"lexruntime":{"prefix":"runtime.lex","name":"LexRuntime","cors":true},"lightsail":{"name":"Lightsail"},"machinelearning":{"name":"MachineLearning","cors":true},"marketplacecommerceanalytics":{"name":"MarketplaceCommerceAnalytics","cors":true},"marketplacemetering":{"prefix":"meteringmarketplace","name":"MarketplaceMetering"},"mturk":{"prefix":"mturk-requester","name":"MTurk","cors":true},"mobileanalytics":{"name":"MobileAnalytics","cors":true},"opsworks":{"name":"OpsWorks","cors":true},"opsworkscm":{"name":"OpsWorksCM"},"organizations":{"name":"Organizations"},"pinpoint":{"name":"Pinpoint"},"polly":{"name":"Polly","cors":true},"rds":{"name":"RDS","versions":["2014-09-01*"],"cors":true},"redshift":{"name":"Redshift","cors":true},"rekognition":{"name":"Rekognition","cors":true},"resourcegroupstaggingapi":{"name":"ResourceGroupsTaggingAPI"},"route53":{"name":"Route53","cors":true},"route53domains":{"name":"Route53Domains","cors":true},"s3":{"name":"S3","dualstackAvailable":true,"cors":true},"servicecatalog":{"name":"ServiceCatalog","cors":true},"ses":{"prefix":"email","name":"SES","cors":true},"shield":{"name":"Shield"},"simpledb":{"prefix":"sdb","name":"SimpleDB"},"sms":{"name":"SMS"},"snowball":{"name":"Snowball"},"sns":{"name":"SNS","cors":true},"sqs":{"name":"SQS","cors":true},"ssm":{"name":"SSM","cors":true},"storagegateway":{"name":"StorageGateway","cors":true},"stepfunctions":{"prefix":"states","name":"StepFunctions"},"sts":{"name":"STS","cors":true},"support":{"name":"Support"},"swf":{"name":"SWF"},"xray":{"name":"XRay"},"waf":{"name":"WAF","cors":true},"wafregional":{"prefix":"waf-regional","name":"WAFRegional"},"workdocs":{"name":"WorkDocs","cors":true},"workspaces":{"name":"WorkSpaces"},"codestar":{"name":"CodeStar"},"lexmodelbuildingservice":{"prefix":"lex-models","name":"LexModelBuildingService"},"marketplaceentitlementservice":{"prefix":"entitlement.marketplace","name":"MarketplaceEntitlementService"},"athena":{"name":"Athena"},"greengrass":{"name":"Greengrass"},"dax":{"name":"DAX"},"migrationhub":{"prefix":"AWSMigrationHub","name":"MigrationHub"},"cloudhsmv2":{"name":"CloudHSMV2"},"glue":{"name":"Glue"}} /***/ }), /***/ "../../../../aws-sdk/apis/sts-2011-06-15.min.json": /***/ (function(module, exports) { module.exports = {"version":"2.0","metadata":{"apiVersion":"2011-06-15","endpointPrefix":"sts","globalEndpoint":"sts.amazonaws.com","protocol":"query","serviceAbbreviation":"AWS STS","serviceFullName":"AWS Security Token Service","signatureVersion":"v4","uid":"sts-2011-06-15","xmlNamespace":"https://sts.amazonaws.com/doc/2011-06-15/"},"operations":{"AssumeRole":{"input":{"type":"structure","required":["RoleArn","RoleSessionName"],"members":{"RoleArn":{},"RoleSessionName":{},"Policy":{},"DurationSeconds":{"type":"integer"},"ExternalId":{},"SerialNumber":{},"TokenCode":{}}},"output":{"resultWrapper":"AssumeRoleResult","type":"structure","members":{"Credentials":{"shape":"Sa"},"AssumedRoleUser":{"shape":"Sf"},"PackedPolicySize":{"type":"integer"}}}},"AssumeRoleWithSAML":{"input":{"type":"structure","required":["RoleArn","PrincipalArn","SAMLAssertion"],"members":{"RoleArn":{},"PrincipalArn":{},"SAMLAssertion":{},"Policy":{},"DurationSeconds":{"type":"integer"}}},"output":{"resultWrapper":"AssumeRoleWithSAMLResult","type":"structure","members":{"Credentials":{"shape":"Sa"},"AssumedRoleUser":{"shape":"Sf"},"PackedPolicySize":{"type":"integer"},"Subject":{},"SubjectType":{},"Issuer":{},"Audience":{},"NameQualifier":{}}}},"AssumeRoleWithWebIdentity":{"input":{"type":"structure","required":["RoleArn","RoleSessionName","WebIdentityToken"],"members":{"RoleArn":{},"RoleSessionName":{},"WebIdentityToken":{},"ProviderId":{},"Policy":{},"DurationSeconds":{"type":"integer"}}},"output":{"resultWrapper":"AssumeRoleWithWebIdentityResult","type":"structure","members":{"Credentials":{"shape":"Sa"},"SubjectFromWebIdentityToken":{},"AssumedRoleUser":{"shape":"Sf"},"PackedPolicySize":{"type":"integer"},"Provider":{},"Audience":{}}}},"DecodeAuthorizationMessage":{"input":{"type":"structure","required":["EncodedMessage"],"members":{"EncodedMessage":{}}},"output":{"resultWrapper":"DecodeAuthorizationMessageResult","type":"structure","members":{"DecodedMessage":{}}}},"GetCallerIdentity":{"input":{"type":"structure","members":{}},"output":{"resultWrapper":"GetCallerIdentityResult","type":"structure","members":{"UserId":{},"Account":{},"Arn":{}}}},"GetFederationToken":{"input":{"type":"structure","required":["Name"],"members":{"Name":{},"Policy":{},"DurationSeconds":{"type":"integer"}}},"output":{"resultWrapper":"GetFederationTokenResult","type":"structure","members":{"Credentials":{"shape":"Sa"},"FederatedUser":{"type":"structure","required":["FederatedUserId","Arn"],"members":{"FederatedUserId":{},"Arn":{}}},"PackedPolicySize":{"type":"integer"}}}},"GetSessionToken":{"input":{"type":"structure","members":{"DurationSeconds":{"type":"integer"},"SerialNumber":{},"TokenCode":{}}},"output":{"resultWrapper":"GetSessionTokenResult","type":"structure","members":{"Credentials":{"shape":"Sa"}}}}},"shapes":{"Sa":{"type":"structure","required":["AccessKeyId","SecretAccessKey","SessionToken","Expiration"],"members":{"AccessKeyId":{},"SecretAccessKey":{},"SessionToken":{},"Expiration":{"type":"timestamp"}}},"Sf":{"type":"structure","required":["AssumedRoleId","Arn"],"members":{"AssumedRoleId":{},"Arn":{}}}}} /***/ }), /***/ "../../../../aws-sdk/apis/sts-2011-06-15.paginators.json": /***/ (function(module, exports) { module.exports = {"pagination":{}} /***/ }), /***/ "../../../../aws-sdk/browser.js": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("../../../../aws-sdk/lib/browser_loader.js"); var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); if (typeof window !== 'undefined') window.AWS = AWS; if (true) module.exports = AWS; if (typeof self !== 'undefined') self.AWS = AWS; /***/ }), /***/ "../../../../aws-sdk/clients/cognitoidentity.js": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("../../../../aws-sdk/lib/browser_loader.js"); var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var Service = AWS.Service; var apiLoader = AWS.apiLoader; apiLoader.services['cognitoidentity'] = {}; AWS.CognitoIdentity = Service.defineService('cognitoidentity', ['2014-06-30']); __webpack_require__("../../../../aws-sdk/lib/services/cognitoidentity.js"); Object.defineProperty(apiLoader.services['cognitoidentity'], '2014-06-30', { get: function get() { var model = __webpack_require__("../../../../aws-sdk/apis/cognito-identity-2014-06-30.min.json"); model.paginators = __webpack_require__("../../../../aws-sdk/apis/cognito-identity-2014-06-30.paginators.json").pagination; return model; }, enumerable: true, configurable: true }); module.exports = AWS.CognitoIdentity; /***/ }), /***/ "../../../../aws-sdk/clients/cognitoidentityserviceprovider.js": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("../../../../aws-sdk/lib/browser_loader.js"); var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var Service = AWS.Service; var apiLoader = AWS.apiLoader; apiLoader.services['cognitoidentityserviceprovider'] = {}; AWS.CognitoIdentityServiceProvider = Service.defineService('cognitoidentityserviceprovider', ['2016-04-18']); Object.defineProperty(apiLoader.services['cognitoidentityserviceprovider'], '2016-04-18', { get: function get() { var model = __webpack_require__("../../../../aws-sdk/apis/cognito-idp-2016-04-18.min.json"); model.paginators = __webpack_require__("../../../../aws-sdk/apis/cognito-idp-2016-04-18.paginators.json").pagination; return model; }, enumerable: true, configurable: true }); module.exports = AWS.CognitoIdentityServiceProvider; /***/ }), /***/ "../../../../aws-sdk/clients/sts.js": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("../../../../aws-sdk/lib/browser_loader.js"); var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var Service = AWS.Service; var apiLoader = AWS.apiLoader; apiLoader.services['sts'] = {}; AWS.STS = Service.defineService('sts', ['2011-06-15']); __webpack_require__("../../../../aws-sdk/lib/services/sts.js"); Object.defineProperty(apiLoader.services['sts'], '2011-06-15', { get: function get() { var model = __webpack_require__("../../../../aws-sdk/apis/sts-2011-06-15.min.json"); model.paginators = __webpack_require__("../../../../aws-sdk/apis/sts-2011-06-15.paginators.json").pagination; return model; }, enumerable: true, configurable: true }); module.exports = AWS.STS; /***/ }), /***/ "../../../../aws-sdk/lib/api_loader.js": /***/ (function(module, exports) { function apiLoader(svc, version) { if (!apiLoader.services.hasOwnProperty(svc)) { throw new Error('InvalidService: Failed to load api for ' + svc); } return apiLoader.services[svc][version]; } /** * This member of AWS.apiLoader is private, but changing it will necessitate a * change to ../scripts/services-table-generator.ts */ apiLoader.services = {}; module.exports = apiLoader; /***/ }), /***/ "../../../../aws-sdk/lib/browser_loader.js": /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); // browser specific modules util.crypto.lib = __webpack_require__("../../../../crypto-browserify/index.js"); util.Buffer = __webpack_require__("../../../../buffer/index.js").Buffer; util.url = __webpack_require__("../../../../node-libs-browser/node_modules/url/url.js"); util.querystring = __webpack_require__("../../../../querystring-es3/index.js"); util.environment = 'js'; var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); module.exports = AWS; __webpack_require__("../../../../aws-sdk/lib/credentials.js"); __webpack_require__("../../../../aws-sdk/lib/credentials/credential_provider_chain.js"); __webpack_require__("../../../../aws-sdk/lib/credentials/temporary_credentials.js"); __webpack_require__("../../../../aws-sdk/lib/credentials/web_identity_credentials.js"); __webpack_require__("../../../../aws-sdk/lib/credentials/cognito_identity_credentials.js"); __webpack_require__("../../../../aws-sdk/lib/credentials/saml_credentials.js"); // Load the DOMParser XML parser AWS.XML.Parser = __webpack_require__("../../../../aws-sdk/lib/xml/browser_parser.js"); // Load the XHR HttpClient __webpack_require__("../../../../aws-sdk/lib/http/xhr.js"); if (typeof process === 'undefined') { process = { browser: true }; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__("../../../../process/browser.js"))) /***/ }), /***/ "../../../../aws-sdk/lib/config.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); __webpack_require__("../../../../aws-sdk/lib/credentials.js"); __webpack_require__("../../../../aws-sdk/lib/credentials/credential_provider_chain.js"); var PromisesDependency; /** * The main configuration class used by all service objects to set * the region, credentials, and other options for requests. * * By default, credentials and region settings are left unconfigured. * This should be configured by the application before using any * AWS service APIs. * * In order to set global configuration options, properties should * be assigned to the global {AWS.config} object. * * @see AWS.config * * @!group General Configuration Options * * @!attribute credentials * @return [AWS.Credentials] the AWS credentials to sign requests with. * * @!attribute region * @example Set the global region setting to us-west-2 * AWS.config.update({region: 'us-west-2'}); * @return [AWS.Credentials] The region to send service requests to. * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html * A list of available endpoints for each AWS service * * @!attribute maxRetries * @return [Integer] the maximum amount of retries to perform for a * service request. By default this value is calculated by the specific * service object that the request is being made to. * * @!attribute maxRedirects * @return [Integer] the maximum amount of redirects to follow for a * service request. Defaults to 10. * * @!attribute paramValidation * @return [Boolean|map] whether input parameters should be validated against * the operation description before sending the request. Defaults to true. * Pass a map to enable any of the following specific validation features: * * * **min** [Boolean] — Validates that a value meets the min * constraint. This is enabled by default when paramValidation is set * to `true`. * * **max** [Boolean] — Validates that a value meets the max * constraint. * * **pattern** [Boolean] — Validates that a string value matches a * regular expression. * * **enum** [Boolean] — Validates that a string value matches one * of the allowable enum values. * * @!attribute computeChecksums * @return [Boolean] whether to compute checksums for payload bodies when * the service accepts it (currently supported in S3 only). * * @!attribute convertResponseTypes * @return [Boolean] whether types are converted when parsing response data. * Currently only supported for JSON based services. Turning this off may * improve performance on large response payloads. Defaults to `true`. * * @!attribute correctClockSkew * @return [Boolean] whether to apply a clock skew correction and retry * requests that fail because of an skewed client clock. Defaults to * `false`. * * @!attribute sslEnabled * @return [Boolean] whether SSL is enabled for requests * * @!attribute s3ForcePathStyle * @return [Boolean] whether to force path style URLs for S3 objects * * @!attribute s3BucketEndpoint * @note Setting this configuration option requires an `endpoint` to be * provided explicitly to the service constructor. * @return [Boolean] whether the provided endpoint addresses an individual * bucket (false if it addresses the root API endpoint). * * @!attribute s3DisableBodySigning * @return [Boolean] whether to disable S3 body signing when using signature version `v4`. * Body signing can only be disabled when using https. Defaults to `true`. * * @!attribute useAccelerateEndpoint * @note This configuration option is only compatible with S3 while accessing * dns-compatible buckets. * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service. * Defaults to `false`. * * @!attribute retryDelayOptions * @example Set the base retry delay for all services to 300 ms * AWS.config.update({retryDelayOptions: {base: 300}}); * // Delays with maxRetries = 3: 300, 600, 1200 * @example Set a custom backoff function to provide delay values on retries * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) { * // returns delay in ms * }}}); * @return [map] A set of options to configure the retry delay on retryable errors. * Currently supported options are: * * * **base** [Integer] — The base number of milliseconds to use in the * exponential backoff for operation retries. Defaults to 100 ms for all services except * DynamoDB, where it defaults to 50ms. * * **customBackoff ** [function] — A custom function that accepts a retry count * and returns the amount of time to delay in milliseconds. The `base` option will be * ignored if this option is supplied. * * @!attribute httpOptions * @return [map] A set of options to pass to the low-level HTTP request. * Currently supported options are: * * * **proxy** [String] — the URL to proxy requests through * * **agent** [http.Agent, https.Agent] — the Agent object to perform * HTTP requests with. Used for connection pooling. Defaults to the global * agent (`http.globalAgent`) for non-SSL connections. Note that for * SSL connections, a special Agent object is used in order to enable * peer certificate verification. This feature is only supported in the * Node.js environment. * * **timeout** [Integer] — The number of milliseconds to wait before * giving up on a connection attempt. Defaults to two minutes (120000). * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous * HTTP requests. Used in the browser environment only. Set to false to * send requests synchronously. Defaults to true (async on). * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials" * property of an XMLHttpRequest object. Used in the browser environment * only. Defaults to false. * @!attribute logger * @return [#write,#log] an object that responds to .write() (like a stream) * or .log() (like the console object) in order to log information about * requests * * @!attribute systemClockOffset * @return [Number] an offset value in milliseconds to apply to all signing * times. Use this to compensate for clock skew when your system may be * out of sync with the service time. Note that this configuration option * can only be applied to the global `AWS.config` object and cannot be * overridden in service-specific configuration. Defaults to 0 milliseconds. * * @!attribute signatureVersion * @return [String] the signature version to sign requests with (overriding * the API configuration). Possible values are: 'v2', 'v3', 'v4'. * * @!attribute signatureCache * @return [Boolean] whether the signature to sign requests with (overriding * the API configuration) is cached. Only applies to the signature version 'v4'. * Defaults to `true`. */ AWS.Config = AWS.util.inherit({ /** * @!endgroup */ /** * Creates a new configuration object. This is the object that passes * option data along to service requests, including credentials, security, * region information, and some service specific settings. * * @example Creating a new configuration object with credentials and region * var config = new AWS.Config({ * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2' * }); * @option options accessKeyId [String] your AWS access key ID. * @option options secretAccessKey [String] your AWS secret access key. * @option options sessionToken [AWS.Credentials] the optional AWS * session token to sign requests with. * @option options credentials [AWS.Credentials] the AWS credentials * to sign requests with. You can either specify this object, or * specify the accessKeyId and secretAccessKey options directly. * @option options credentialProvider [AWS.CredentialProviderChain] the * provider chain used to resolve credentials if no static `credentials` * property is set. * @option options region [String] the region to send service requests to. * See {region} for more information. * @option options maxRetries [Integer] the maximum amount of retries to * attempt with a request. See {maxRetries} for more information. * @option options maxRedirects [Integer] the maximum amount of redirects to * follow with a request. See {maxRedirects} for more information. * @option options sslEnabled [Boolean] whether to enable SSL for * requests. * @option options paramValidation [Boolean|map] whether input parameters * should be validated against the operation description before sending * the request. Defaults to true. Pass a map to enable any of the * following specific validation features: * * * **min** [Boolean] — Validates that a value meets the min * constraint. This is enabled by default when paramValidation is set * to `true`. * * **max** [Boolean] — Validates that a value meets the max * constraint. * * **pattern** [Boolean] — Validates that a string value matches a * regular expression. * * **enum** [Boolean] — Validates that a string value matches one * of the allowable enum values. * @option options computeChecksums [Boolean] whether to compute checksums * for payload bodies when the service accepts it (currently supported * in S3 only) * @option options convertResponseTypes [Boolean] whether types are converted * when parsing response data. Currently only supported for JSON based * services. Turning this off may improve performance on large response * payloads. Defaults to `true`. * @option options correctClockSkew [Boolean] whether to apply a clock skew * correction and retry requests that fail because of an skewed client * clock. Defaults to `false`. * @option options s3ForcePathStyle [Boolean] whether to force path * style URLs for S3 objects. * @option options s3BucketEndpoint [Boolean] whether the provided endpoint * addresses an individual bucket (false if it addresses the root API * endpoint). Note that setting this configuration option requires an * `endpoint` to be provided explicitly to the service constructor. * @option options s3DisableBodySigning [Boolean] whether S3 body signing * should be disabled when using signature version `v4`. Body signing * can only be disabled when using https. Defaults to `true`. * * @option options retryDelayOptions [map] A set of options to configure * the retry delay on retryable errors. Currently supported options are: * * * **base** [Integer] — The base number of milliseconds to use in the * exponential backoff for operation retries. Defaults to 100 ms for all * services except DynamoDB, where it defaults to 50ms. * * **customBackoff ** [function] — A custom function that accepts a retry count * and returns the amount of time to delay in milliseconds. The `base` option will be * ignored if this option is supplied. * @option options httpOptions [map] A set of options to pass to the low-level * HTTP request. Currently supported options are: * * * **proxy** [String] — the URL to proxy requests through * * **agent** [http.Agent, https.Agent] — the Agent object to perform * HTTP requests with. Used for connection pooling. Defaults to the global * agent (`http.globalAgent`) for non-SSL connections. Note that for * SSL connections, a special Agent object is used in order to enable * peer certificate verification. This feature is only available in the * Node.js environment. * * **connectTimeout** [Integer] — Sets the socket to timeout after * failing to establish a connection with the server after * `connectTimeout` milliseconds. This timeout has no effect once a socket * connection has been established. * * **timeout** [Integer] — Sets the socket to timeout after timeout * milliseconds of inactivity on the socket. Defaults to two minutes * (120000). * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous * HTTP requests. Used in the browser environment only. Set to false to * send requests synchronously. Defaults to true (async on). * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials" * property of an XMLHttpRequest object. Used in the browser environment * only. Defaults to false. * @option options apiVersion [String, Date] a String in YYYY-MM-DD format * (or a date) that represents the latest possible API version that can be * used in all services (unless overridden by `apiVersions`). Specify * 'latest' to use the latest possible version. * @option options apiVersions [map] a map of service * identifiers (the lowercase service class name) with the API version to * use when instantiating a service. Specify 'latest' for each individual * that can use the latest available version. * @option options logger [#write,#log] an object that responds to .write() * (like a stream) or .log() (like the console object) in order to log * information about requests * @option options systemClockOffset [Number] an offset value in milliseconds * to apply to all signing times. Use this to compensate for clock skew * when your system may be out of sync with the service time. Note that * this configuration option can only be applied to the global `AWS.config` * object and cannot be overridden in service-specific configuration. * Defaults to 0 milliseconds. * @option options signatureVersion [String] the signature version to sign * requests with (overriding the API configuration). Possible values are: * 'v2', 'v3', 'v4'. * @option options signatureCache [Boolean] whether the signature to sign * requests with (overriding the API configuration) is cached. Only applies * to the signature version 'v4'. Defaults to `true`. * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32 * checksum of HTTP response bodies returned by DynamoDB. Default: `true`. */ constructor: function Config(options) { if (options === undefined) options = {}; options = this.extractCredentials(options); AWS.util.each.call(this, this.keys, function (key, value) { this.set(key, options[key], value); }); }, /** * @!group Managing Credentials */ /** * Loads credentials from the configuration object. This is used internally * by the SDK to ensure that refreshable {Credentials} objects are properly * refreshed and loaded when sending a request. If you want to ensure that * your credentials are loaded prior to a request, you can use this method * directly to provide accurate credential data stored in the object. * * @note If you configure the SDK with static or environment credentials, * the credential data should already be present in {credentials} attribute. * This method is primarily necessary to load credentials from asynchronous * sources, or sources that can refresh credentials periodically. * @example Getting your access key * AWS.config.getCredentials(function(err) { * if (err) console.log(err.stack); // credentials not loaded * else console.log("Access Key:", AWS.config.credentials.accessKeyId); * }) * @callback callback function(err) * Called when the {credentials} have been properly set on the configuration * object. * * @param err [Error] if this is set, credentials were not successfully * loaded and this error provides information why. * @see credentials * @see Credentials */ getCredentials: function getCredentials(callback) { var self = this; function finish(err) { callback(err, err ? null : self.credentials); } function credError(msg, err) { return new AWS.util.error(err || new Error(), { code: 'CredentialsError', message: msg, name: 'CredentialsError' }); } function getAsyncCredentials() { self.credentials.get(function(err) { if (err) { var msg = 'Could not load credentials from ' + self.credentials.constructor.name; err = credError(msg, err); } finish(err); }); } function getStaticCredentials() { var err = null; if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) { err = credError('Missing credentials'); } finish(err); } if (self.credentials) { if (typeof self.credentials.get === 'function') { getAsyncCredentials(); } else { // static credentials getStaticCredentials(); } } else if (self.credentialProvider) { self.credentialProvider.resolve(function(err, creds) { if (err) { err = credError('Could not load credentials from any providers', err); } self.credentials = creds; finish(err); }); } else { finish(credError('No credentials to load')); } }, /** * @!group Loading and Setting Configuration Options */ /** * @overload update(options, allowUnknownKeys = false) * Updates the current configuration object with new options. * * @example Update maxRetries property of a configuration object * config.update({maxRetries: 10}); * @param [Object] options a map of option keys and values. * @param [Boolean] allowUnknownKeys whether unknown keys can be set on * the configuration object. Defaults to `false`. * @see constructor */ update: function update(options, allowUnknownKeys) { allowUnknownKeys = allowUnknownKeys || false; options = this.extractCredentials(options); AWS.util.each.call(this, options, function (key, value) { if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) || AWS.Service.hasService(key)) { this.set(key, value); } }); }, /** * Loads configuration data from a JSON file into this config object. * @note Loading configuration will reset all existing configuration * on the object. * @!macro nobrowser * @param path [String] the path relative to your process's current * working directory to load configuration from. * @return [AWS.Config] the same configuration object */ loadFromPath: function loadFromPath(path) { this.clear(); var options = JSON.parse(AWS.util.readFileSync(path)); var fileSystemCreds = new AWS.FileSystemCredentials(path); var chain = new AWS.CredentialProviderChain(); chain.providers.unshift(fileSystemCreds); chain.resolve(function (err, creds) { if (err) throw err; else options.credentials = creds; }); this.constructor(options); return this; }, /** * Clears configuration data on this object * * @api private */ clear: function clear() { /*jshint forin:false */ AWS.util.each.call(this, this.keys, function (key) { delete this[key]; }); // reset credential provider this.set('credentials', undefined); this.set('credentialProvider', undefined); }, /** * Sets a property on the configuration object, allowing for a * default value * @api private */ set: function set(property, value, defaultValue) { if (value === undefined) { if (defaultValue === undefined) { defaultValue = this.keys[property]; } if (typeof defaultValue === 'function') { this[property] = defaultValue.call(this); } else { this[property] = defaultValue; } } else if (property === 'httpOptions' && this[property]) { // deep merge httpOptions this[property] = AWS.util.merge(this[property], value); } else { this[property] = value; } }, /** * All of the keys with their default values. * * @constant * @api private */ keys: { credentials: null, credentialProvider: null, region: null, logger: null, apiVersions: {}, apiVersion: null, endpoint: undefined, httpOptions: { timeout: 120000 }, maxRetries: undefined, maxRedirects: 10, paramValidation: true, sslEnabled: true, s3ForcePathStyle: false, s3BucketEndpoint: false, s3DisableBodySigning: true, computeChecksums: true, convertResponseTypes: true, correctClockSkew: false, customUserAgent: null, dynamoDbCrc32: true, systemClockOffset: 0, signatureVersion: null, signatureCache: true, retryDelayOptions: {}, useAccelerateEndpoint: false }, /** * Extracts accessKeyId, secretAccessKey and sessionToken * from a configuration hash. * * @api private */ extractCredentials: function extractCredentials(options) { if (options.accessKeyId && options.secretAccessKey) { options = AWS.util.copy(options); options.credentials = new AWS.Credentials(options); } return options; }, /** * Sets the promise dependency the SDK will use wherever Promises are returned. * Passing `null` will force the SDK to use native Promises if they are available. * If native Promises are not available, passing `null` will have no effect. * @param [Constructor] dep A reference to a Promise constructor */ setPromisesDependency: function setPromisesDependency(dep) { PromisesDependency = dep; // if null was passed in, we should try to use native promises if (dep === null && typeof Promise === 'function') { PromisesDependency = Promise; } var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain]; if (AWS.S3 && AWS.S3.ManagedUpload) constructors.push(AWS.S3.ManagedUpload); AWS.util.addPromises(constructors, PromisesDependency); }, /** * Gets the promise dependency set by `AWS.config.setPromisesDependency`. */ getPromisesDependency: function getPromisesDependency() { return PromisesDependency; } }); /** * @return [AWS.Config] The global configuration object singleton instance * @readonly * @see AWS.Config */ AWS.config = new AWS.Config(); /***/ }), /***/ "../../../../aws-sdk/lib/core.js": /***/ (function(module, exports, __webpack_require__) { /** * The main AWS namespace */ var AWS = { util: __webpack_require__("../../../../aws-sdk/lib/util.js") }; /** * @api private * @!macro [new] nobrowser * @note This feature is not supported in the browser environment of the SDK. */ var _hidden = {}; _hidden.toString(); // hack to parse macro module.exports = AWS; AWS.util.update(AWS, { /** * @constant */ VERSION: '2.100.0', /** * @api private */ Signers: {}, /** * @api private */ Protocol: { Json: __webpack_require__("../../../../aws-sdk/lib/protocol/json.js"), Query: __webpack_require__("../../../../aws-sdk/lib/protocol/query.js"), Rest: __webpack_require__("../../../../aws-sdk/lib/protocol/rest.js"), RestJson: __webpack_require__("../../../../aws-sdk/lib/protocol/rest_json.js"), RestXml: __webpack_require__("../../../../aws-sdk/lib/protocol/rest_xml.js") }, /** * @api private */ XML: { Builder: __webpack_require__("../../../../aws-sdk/lib/xml/builder.js"), Parser: null // conditionally set based on environment }, /** * @api private */ JSON: { Builder: __webpack_require__("../../../../aws-sdk/lib/json/builder.js"), Parser: __webpack_require__("../../../../aws-sdk/lib/json/parser.js") }, /** * @api private */ Model: { Api: __webpack_require__("../../../../aws-sdk/lib/model/api.js"), Operation: __webpack_require__("../../../../aws-sdk/lib/model/operation.js"), Shape: __webpack_require__("../../../../aws-sdk/lib/model/shape.js"), Paginator: __webpack_require__("../../../../aws-sdk/lib/model/paginator.js"), ResourceWaiter: __webpack_require__("../../../../aws-sdk/lib/model/resource_waiter.js") }, /** * @api private */ apiLoader: __webpack_require__("../../../../aws-sdk/lib/api_loader.js") }); __webpack_require__("../../../../aws-sdk/lib/service.js"); __webpack_require__("../../../../aws-sdk/lib/config.js"); __webpack_require__("../../../../aws-sdk/lib/http.js"); __webpack_require__("../../../../aws-sdk/lib/sequential_executor.js"); __webpack_require__("../../../../aws-sdk/lib/event_listeners.js"); __webpack_require__("../../../../aws-sdk/lib/request.js"); __webpack_require__("../../../../aws-sdk/lib/response.js"); __webpack_require__("../../../../aws-sdk/lib/resource_waiter.js"); __webpack_require__("../../../../aws-sdk/lib/signers/request_signer.js"); __webpack_require__("../../../../aws-sdk/lib/param_validator.js"); /** * @readonly * @return [AWS.SequentialExecutor] a collection of global event listeners that * are attached to every sent request. * @see AWS.Request AWS.Request for a list of events to listen for * @example Logging the time taken to send a request * AWS.events.on('send', function startSend(resp) { * resp.startTime = new Date().getTime(); * }).on('complete', function calculateTime(resp) { * var time = (new Date().getTime() - resp.startTime) / 1000; * console.log('Request took ' + time + ' seconds'); * }); * * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds' */ AWS.events = new AWS.SequentialExecutor(); /***/ }), /***/ "../../../../aws-sdk/lib/credentials.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); /** * Represents your AWS security credentials, specifically the * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}. * Creating a `Credentials` object allows you to pass around your * security information to configuration and service objects. * * Note that this class typically does not need to be constructed manually, * as the {AWS.Config} and {AWS.Service} classes both accept simple * options hashes with the three keys. These structures will be converted * into Credentials objects automatically. * * ## Expiring and Refreshing Credentials * * Occasionally credentials can expire in the middle of a long-running * application. In this case, the SDK will automatically attempt to * refresh the credentials from the storage location if the Credentials * class implements the {refresh} method. * * If you are implementing a credential storage location, you * will want to create a subclass of the `Credentials` class and * override the {refresh} method. This method allows credentials to be * retrieved from the backing store, be it a file system, database, or * some network storage. The method should reset the credential attributes * on the object. * * @!attribute expired * @return [Boolean] whether the credentials have been expired and * require a refresh. Used in conjunction with {expireTime}. * @!attribute expireTime * @return [Date] a time when credentials should be considered expired. Used * in conjunction with {expired}. * @!attribute accessKeyId * @return [String] the AWS access key ID * @!attribute secretAccessKey * @return [String] the AWS secret access key * @!attribute sessionToken * @return [String] an optional AWS session token */ AWS.Credentials = AWS.util.inherit({ /** * A credentials object can be created using positional arguments or an options * hash. * * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null) * Creates a Credentials object with a given set of credential information * as positional arguments. * @param accessKeyId [String] the AWS access key ID * @param secretAccessKey [String] the AWS secret access key * @param sessionToken [String] the optional AWS session token * @example Create a credentials object with AWS credentials * var creds = new AWS.Credentials('akid', 'secret', 'session'); * @overload AWS.Credentials(options) * Creates a Credentials object with a given set of credential information * as an options hash. * @option options accessKeyId [String] the AWS access key ID * @option options secretAccessKey [String] the AWS secret access key * @option options sessionToken [String] the optional AWS session token * @example Create a credentials object with AWS credentials * var creds = new AWS.Credentials({ * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session' * }); */ constructor: function Credentials() { // hide secretAccessKey from being displayed with util.inspect AWS.util.hideProperties(this, ['secretAccessKey']); this.expired = false; this.expireTime = null; if (arguments.length === 1 && typeof arguments[0] === 'object') { var creds = arguments[0].credentials || arguments[0]; this.accessKeyId = creds.accessKeyId; this.secretAccessKey = creds.secretAccessKey; this.sessionToken = creds.sessionToken; } else { this.accessKeyId = arguments[0]; this.secretAccessKey = arguments[1]; this.sessionToken = arguments[2]; } }, /** * @return [Integer] the number of seconds before {expireTime} during which * the credentials will be considered expired. */ expiryWindow: 15, /** * @return [Boolean] whether the credentials object should call {refresh} * @note Subclasses should override this method to provide custom refresh * logic. */ needsRefresh: function needsRefresh() { var currentTime = AWS.util.date.getDate().getTime(); var adjustedTime = new Date(currentTime + this.expiryWindow * 1000); if (this.expireTime && adjustedTime > this.expireTime) { return true; } else { return this.expired || !this.accessKeyId || !this.secretAccessKey; } }, /** * Gets the existing credentials, refreshing them if they are not yet loaded * or have expired. Users should call this method before using {refresh}, * as this will not attempt to reload credentials when they are already * loaded into the object. * * @callback callback function(err) * When this callback is called with no error, it means either credentials * do not need to be refreshed or refreshed credentials information has * been loaded into the object (as the `accessKeyId`, `secretAccessKey`, * and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled */ get: function get(callback) { var self = this; if (this.needsRefresh()) { this.refresh(function(err) { if (!err) self.expired = false; // reset expired flag if (callback) callback(err); }); } else if (callback) { callback(); } }, /** * @!method getPromise() * Returns a 'thenable' promise. * Gets the existing credentials, refreshing them if they are not yet loaded * or have expired. Users should call this method before using {refresh}, * as this will not attempt to reload credentials when they are already * loaded into the object. * * Two callbacks can be provided to the `then` method on the returned promise. * The first callback will be called if the promise is fulfilled, and the second * callback will be called if the promise is rejected. * @callback fulfilledCallback function() * Called if the promise is fulfilled. When this callback is called, it * means either credentials do not need to be refreshed or refreshed * credentials information has been loaded into the object (as the * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). * @callback rejectedCallback function(err) * Called if the promise is rejected. * @param err [Error] if an error occurred, this value will be filled * @return [Promise] A promise that represents the state of the `get` call. * @example Calling the `getPromise` method. * var promise = credProvider.getPromise(); * promise.then(function() { ... }, function(err) { ... }); */ /** * @!method refreshPromise() * Returns a 'thenable' promise. * Refreshes the credentials. Users should call {get} before attempting * to forcibly refresh credentials. * * Two callbacks can be provided to the `then` method on the returned promise. * The first callback will be called if the promise is fulfilled, and the second * callback will be called if the promise is rejected. * @callback fulfilledCallback function() * Called if the promise is fulfilled. When this callback is called, it * means refreshed credentials information has been loaded into the object * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). * @callback rejectedCallback function(err) * Called if the promise is rejected. * @param err [Error] if an error occurred, this value will be filled * @return [Promise] A promise that represents the state of the `refresh` call. * @example Calling the `refreshPromise` method. * var promise = credProvider.refreshPromise(); * promise.then(function() { ... }, function(err) { ... }); */ /** * Refreshes the credentials. Users should call {get} before attempting * to forcibly refresh credentials. * * @callback callback function(err) * When this callback is called with no error, it means refreshed * credentials information has been loaded into the object (as the * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @note Subclasses should override this class to reset the * {accessKeyId}, {secretAccessKey} and optional {sessionToken} * on the credentials object and then call the callback with * any error information. * @see get */ refresh: function refresh(callback) { this.expired = false; callback(); } }); /** * @api private */ AWS.Credentials.addPromisesToClass = function addPromisesToClass(PromiseDependency) { this.prototype.getPromise = AWS.util.promisifyMethod('get', PromiseDependency); this.prototype.refreshPromise = AWS.util.promisifyMethod('refresh', PromiseDependency); }; /** * @api private */ AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() { delete this.prototype.getPromise; delete this.prototype.refreshPromise; }; AWS.util.addPromises(AWS.Credentials); /***/ }), /***/ "../../../../aws-sdk/lib/credentials/cognito_identity_credentials.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var CognitoIdentity = __webpack_require__("../../../../aws-sdk/clients/cognitoidentity.js"); var STS = __webpack_require__("../../../../aws-sdk/clients/sts.js"); /** * Represents credentials retrieved from STS Web Identity Federation using * the Amazon Cognito Identity service. * * By default this provider gets credentials using the * {AWS.CognitoIdentity.getCredentialsForIdentity} service operation, which * requires either an `IdentityId` or an `IdentityPoolId` (Amazon Cognito * Identity Pool ID), which is used to call {AWS.CognitoIdentity.getId} to * obtain an `IdentityId`. If the identity or identity pool is not configured in * the Amazon Cognito Console to use IAM roles with the appropriate permissions, * then additionally a `RoleArn` is required containing the ARN of the IAM trust * policy for the Amazon Cognito role that the user will log into. If a `RoleArn` * is provided, then this provider gets credentials using the * {AWS.STS.assumeRoleWithWebIdentity} service operation, after first getting an * Open ID token from {AWS.CognitoIdentity.getOpenIdToken}. * * In addition, if this credential provider is used to provide authenticated * login, the `Logins` map may be set to the tokens provided by the respective * identity providers. See {constructor} for an example on creating a credentials * object with proper property values. * * ## Refreshing Credentials from Identity Service * * In addition to AWS credentials expiring after a given amount of time, the * login token from the identity provider will also expire. Once this token * expires, it will not be usable to refresh AWS credentials, and another * token will be needed. The SDK does not manage refreshing of the token value, * but this can be done through a "refresh token" supported by most identity * providers. Consult the documentation for the identity provider for refreshing * tokens. Once the refreshed token is acquired, you should make sure to update * this new token in the credentials object's {params} property. The following * code will update the WebIdentityToken, assuming you have retrieved an updated * token from the identity provider: * * ```javascript * AWS.config.credentials.params.Logins['graph.facebook.com'] = updatedToken; * ``` * * Future calls to `credentials.refresh()` will now use the new token. * * @!attribute params * @return [map] the map of params passed to * {AWS.CognitoIdentity.getId}, * {AWS.CognitoIdentity.getOpenIdToken}, and * {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the * `params.WebIdentityToken` property. * @!attribute data * @return [map] the raw data response from the call to * {AWS.CognitoIdentity.getCredentialsForIdentity}, or * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get * access to other properties from the response. * @!attribute identityId * @return [String] the Cognito ID returned by the last call to * {AWS.CognitoIdentity.getOpenIdToken}. This ID represents the actual * final resolved identity ID from Amazon Cognito. */ AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, { /** * @api private */ localStorageKey: { id: 'aws.cognito.identity-id.', providers: 'aws.cognito.identity-providers.' }, /** * Creates a new credentials object. * @example Creating a new credentials object * AWS.config.credentials = new AWS.CognitoIdentityCredentials({ * * // either IdentityPoolId or IdentityId is required * // See the IdentityPoolId param for AWS.CognitoIdentity.getID (linked below) * // See the IdentityId param for AWS.CognitoIdentity.getCredentialsForIdentity * // or AWS.CognitoIdentity.getOpenIdToken (linked below) * IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030', * IdentityId: 'us-east-1:128d0a74-c82f-4553-916d-90053e4a8b0f' * * // optional, only necessary when the identity pool is not configured * // to use IAM roles in the Amazon Cognito Console * // See the RoleArn param for AWS.STS.assumeRoleWithWebIdentity (linked below) * RoleArn: 'arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity', * * // optional tokens, used for authenticated login * // See the Logins param for AWS.CognitoIdentity.getID (linked below) * Logins: { * 'graph.facebook.com': 'FBTOKEN', * 'www.amazon.com': 'AMAZONTOKEN', * 'accounts.google.com': 'GOOGLETOKEN', * 'api.twitter.com': 'TWITTERTOKEN', * 'www.digits.com': 'DIGITSTOKEN' * }, * * // optional name, defaults to web-identity * // See the RoleSessionName param for AWS.STS.assumeRoleWithWebIdentity (linked below) * RoleSessionName: 'web', * * // optional, only necessary when application runs in a browser * // and multiple users are signed in at once, used for caching * LoginId: 'example@gmail.com' * * }, { * // optionally provide configuration to apply to the underlying service clients * // if configuration is not provided, then configuration will be pulled from AWS.config * * // region should match the region your identity pool is located in * region: 'us-east-1', * * // specify timeout options * httpOptions: { * timeout: 100 * } * }); * @see AWS.CognitoIdentity.getId * @see AWS.CognitoIdentity.getCredentialsForIdentity * @see AWS.STS.assumeRoleWithWebIdentity * @see AWS.CognitoIdentity.getOpenIdToken * @see AWS.Config * @note If a region is not provided in the global AWS.config, or * specified in the `clientConfig` to the CognitoIdentityCredentials * constructor, you may encounter a 'Missing credentials in config' error * when calling making a service call. */ constructor: function CognitoIdentityCredentials(params, clientConfig) { AWS.Credentials.call(this); this.expired = true; this.params = params; this.data = null; this._identityId = null; this._clientConfig = AWS.util.copy(clientConfig || {}); this.loadCachedId(); var self = this; Object.defineProperty(this, 'identityId', { get: function() { self.loadCachedId(); return self._identityId || self.params.IdentityId; }, set: function(identityId) { self._identityId = identityId; } }); }, /** * Refreshes credentials using {AWS.CognitoIdentity.getCredentialsForIdentity}, * or {AWS.STS.assumeRoleWithWebIdentity}. * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see AWS.Credentials.get */ refresh: function refresh(callback) { var self = this; self.createClients(); self.data = null; self._identityId = null; self.getId(function(err) { if (!err) { if (!self.params.RoleArn) { self.getCredentialsForIdentity(callback); } else { self.getCredentialsFromSTS(callback); } } else { self.clearIdOnNotAuthorized(err); callback(err); } }); }, /** * Clears the cached Cognito ID associated with the currently configured * identity pool ID. Use this to manually invalidate your cache if * the identity pool ID was deleted. */ clearCachedId: function clearCache() { this._identityId = null; delete this.params.IdentityId; var poolId = this.params.IdentityPoolId; var loginId = this.params.LoginId || ''; delete this.storage[this.localStorageKey.id + poolId + loginId]; delete this.storage[this.localStorageKey.providers + poolId + loginId]; }, /** * @api private */ clearIdOnNotAuthorized: function clearIdOnNotAuthorized(err) { var self = this; if (err.code == 'NotAuthorizedException') { self.clearCachedId(); } }, /** * Retrieves a Cognito ID, loading from cache if it was already retrieved * on this device. * * @callback callback function(err, identityId) * @param err [Error, null] an error object if the call failed or null if * it succeeded. * @param identityId [String, null] if successful, the callback will return * the Cognito ID. * @note If not loaded explicitly, the Cognito ID is loaded and stored in * localStorage in the browser environment of a device. * @api private */ getId: function getId(callback) { var self = this; if (typeof self.params.IdentityId === 'string') { return callback(null, self.params.IdentityId); } self.cognito.getId(function(err, data) { if (!err && data.IdentityId) { self.params.IdentityId = data.IdentityId; callback(null, data.IdentityId); } else { callback(err); } }); }, /** * @api private */ loadCredentials: function loadCredentials(data, credentials) { if (!data || !credentials) return; credentials.expired = false; credentials.accessKeyId = data.Credentials.AccessKeyId; credentials.secretAccessKey = data.Credentials.SecretKey; credentials.sessionToken = data.Credentials.SessionToken; credentials.expireTime = data.Credentials.Expiration; }, /** * @api private */ getCredentialsForIdentity: function getCredentialsForIdentity(callback) { var self = this; self.cognito.getCredentialsForIdentity(function(err, data) { if (!err) { self.cacheId(data); self.data = data; self.loadCredentials(self.data, self); } else { self.clearIdOnNotAuthorized(err); } callback(err); }); }, /** * @api private */ getCredentialsFromSTS: function getCredentialsFromSTS(callback) { var self = this; self.cognito.getOpenIdToken(function(err, data) { if (!err) { self.cacheId(data); self.params.WebIdentityToken = data.Token; self.webIdentityCredentials.refresh(function(webErr) { if (!webErr) { self.data = self.webIdentityCredentials.data; self.sts.credentialsFrom(self.data, self); } callback(webErr); }); } else { self.clearIdOnNotAuthorized(err); callback(err); } }); }, /** * @api private */ loadCachedId: function loadCachedId() { var self = this; // in the browser we source default IdentityId from localStorage if (AWS.util.isBrowser() && !self.params.IdentityId) { var id = self.getStorage('id'); if (id && self.params.Logins) { var actualProviders = Object.keys(self.params.Logins); var cachedProviders = (self.getStorage('providers') || '').split(','); // only load ID if at least one provider used this ID before var intersect = cachedProviders.filter(function(n) { return actualProviders.indexOf(n) !== -1; }); if (intersect.length !== 0) { self.params.IdentityId = id; } } else if (id) { self.params.IdentityId = id; } } }, /** * @api private */ createClients: function() { var clientConfig = this._clientConfig; this.webIdentityCredentials = this.webIdentityCredentials || new AWS.WebIdentityCredentials(this.params, clientConfig); if (!this.cognito) { var cognitoConfig = AWS.util.merge({}, clientConfig); cognitoConfig.params = this.params; this.cognito = new CognitoIdentity(cognitoConfig); } this.sts = this.sts || new STS(clientConfig); }, /** * @api private */ cacheId: function cacheId(data) { this._identityId = data.IdentityId; this.params.IdentityId = this._identityId; // cache this IdentityId in browser localStorage if possible if (AWS.util.isBrowser()) { this.setStorage('id', data.IdentityId); if (this.params.Logins) { this.setStorage('providers', Object.keys(this.params.Logins).join(',')); } } }, /** * @api private */ getStorage: function getStorage(key) { return this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')]; }, /** * @api private */ setStorage: function setStorage(key, val) { try { this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')] = val; } catch (_) {} }, /** * @api private */ storage: (function() { try { var storage = AWS.util.isBrowser() && window.localStorage !== null && typeof window.localStorage === 'object' ? window.localStorage : {}; // Test set/remove which would throw an error in Safari's private browsing storage['aws.test-storage'] = 'foobar'; delete storage['aws.test-storage']; return storage; } catch (_) { return {}; } })() }); /***/ }), /***/ "../../../../aws-sdk/lib/credentials/credential_provider_chain.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); /** * Creates a credential provider chain that searches for AWS credentials * in a list of credential providers specified by the {providers} property. * * By default, the chain will use the {defaultProviders} to resolve credentials. * These providers will look in the environment using the * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes. * * ## Setting Providers * * Each provider in the {providers} list should be a function that returns * a {AWS.Credentials} object, or a hardcoded credentials object. The function * form allows for delayed execution of the credential construction. * * ## Resolving Credentials from a Chain * * Call {resolve} to return the first valid credential object that can be * loaded by the provider chain. * * For example, to resolve a chain with a custom provider that checks a file * on disk after the set of {defaultProviders}: * * ```javascript * var diskProvider = new AWS.FileSystemCredentials('./creds.json'); * var chain = new AWS.CredentialProviderChain(); * chain.providers.push(diskProvider); * chain.resolve(); * ``` * * The above code will return the `diskProvider` object if the * file contains credentials and the `defaultProviders` do not contain * any credential settings. * * @!attribute providers * @return [Array] * a list of credentials objects or functions that return credentials * objects. If the provider is a function, the function will be * executed lazily when the provider needs to be checked for valid * credentials. By default, this object will be set to the * {defaultProviders}. * @see defaultProviders */ AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, { /** * Creates a new CredentialProviderChain with a default set of providers * specified by {defaultProviders}. */ constructor: function CredentialProviderChain(providers) { if (providers) { this.providers = providers; } else { this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0); } }, /** * @!method resolvePromise() * Returns a 'thenable' promise. * Resolves the provider chain by searching for the first set of * credentials in {providers}. * * Two callbacks can be provided to the `then` method on the returned promise. * The first callback will be called if the promise is fulfilled, and the second * callback will be called if the promise is rejected. * @callback fulfilledCallback function(credentials) * Called if the promise is fulfilled and the provider resolves the chain * to a credentials object * @param credentials [AWS.Credentials] the credentials object resolved * by the provider chain. * @callback rejectedCallback function(error) * Called if the promise is rejected. * @param err [Error] the error object returned if no credentials are found. * @return [Promise] A promise that represents the state of the `resolve` method call. * @example Calling the `resolvePromise` method. * var promise = chain.resolvePromise(); * promise.then(function(credentials) { ... }, function(err) { ... }); */ /** * Resolves the provider chain by searching for the first set of * credentials in {providers}. * * @callback callback function(err, credentials) * Called when the provider resolves the chain to a credentials object * or null if no credentials can be found. * * @param err [Error] the error object returned if no credentials are * found. * @param credentials [AWS.Credentials] the credentials object resolved * by the provider chain. * @return [AWS.CredentialProviderChain] the provider, for chaining. */ resolve: function resolve(callback) { if (this.providers.length === 0) { callback(new Error('No providers')); return this; } var index = 0; var providers = this.providers.slice(0); function resolveNext(err, creds) { if ((!err && creds) || index === providers.length) { callback(err, creds); return; } var provider = providers[index++]; if (typeof provider === 'function') { creds = provider.call(); } else { creds = provider; } if (creds.get) { creds.get(function(getErr) { resolveNext(getErr, getErr ? null : creds); }); } else { resolveNext(null, creds); } } resolveNext(); return this; } }); /** * The default set of providers used by a vanilla CredentialProviderChain. * * In the browser: * * ```javascript * AWS.CredentialProviderChain.defaultProviders = [] * ``` * * In Node.js: * * ```javascript * AWS.CredentialProviderChain.defaultProviders = [ * function () { return new AWS.EnvironmentCredentials('AWS'); }, * function () { return new AWS.EnvironmentCredentials('AMAZON'); }, * function () { return new AWS.SharedIniFileCredentials(); }, * function () { * // if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set * return new AWS.ECSCredentials(); * // else * return new AWS.EC2MetadataCredentials(); * } * ] * ``` */ AWS.CredentialProviderChain.defaultProviders = []; /** * @api private */ AWS.CredentialProviderChain.addPromisesToClass = function addPromisesToClass(PromiseDependency) { this.prototype.resolvePromise = AWS.util.promisifyMethod('resolve', PromiseDependency); }; /** * @api private */ AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFromClass() { delete this.prototype.resolvePromise; }; AWS.util.addPromises(AWS.CredentialProviderChain); /***/ }), /***/ "../../../../aws-sdk/lib/credentials/saml_credentials.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var STS = __webpack_require__("../../../../aws-sdk/clients/sts.js"); /** * Represents credentials retrieved from STS SAML support. * * By default this provider gets credentials using the * {AWS.STS.assumeRoleWithSAML} service operation. This operation * requires a `RoleArn` containing the ARN of the IAM trust policy for the * application for which credentials will be given, as well as a `PrincipalArn` * representing the ARN for the SAML identity provider. In addition, the * `SAMLAssertion` must be set to the token provided by the identity * provider. See {constructor} for an example on creating a credentials * object with proper `RoleArn`, `PrincipalArn`, and `SAMLAssertion` values. * * ## Refreshing Credentials from Identity Service * * In addition to AWS credentials expiring after a given amount of time, the * login token from the identity provider will also expire. Once this token * expires, it will not be usable to refresh AWS credentials, and another * token will be needed. The SDK does not manage refreshing of the token value, * but this can be done through a "refresh token" supported by most identity * providers. Consult the documentation for the identity provider for refreshing * tokens. Once the refreshed token is acquired, you should make sure to update * this new token in the credentials object's {params} property. The following * code will update the SAMLAssertion, assuming you have retrieved an updated * token from the identity provider: * * ```javascript * AWS.config.credentials.params.SAMLAssertion = updatedToken; * ``` * * Future calls to `credentials.refresh()` will now use the new token. * * @!attribute params * @return [map] the map of params passed to * {AWS.STS.assumeRoleWithSAML}. To update the token, set the * `params.SAMLAssertion` property. */ AWS.SAMLCredentials = AWS.util.inherit(AWS.Credentials, { /** * Creates a new credentials object. * @param (see AWS.STS.assumeRoleWithSAML) * @example Creating a new credentials object * AWS.config.credentials = new AWS.SAMLCredentials({ * RoleArn: 'arn:aws:iam::1234567890:role/SAMLRole', * PrincipalArn: 'arn:aws:iam::1234567890:role/SAMLPrincipal', * SAMLAssertion: 'base64-token', // base64-encoded token from IdP * }); * @see AWS.STS.assumeRoleWithSAML */ constructor: function SAMLCredentials(params) { AWS.Credentials.call(this); this.expired = true; this.params = params; }, /** * Refreshes credentials using {AWS.STS.assumeRoleWithSAML} * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get */ refresh: function refresh(callback) { var self = this; self.createClients(); if (!callback) callback = function(err) { if (err) throw err; }; self.service.assumeRoleWithSAML(function (err, data) { if (!err) { self.service.credentialsFrom(data, self); } callback(err); }); }, /** * @api private */ createClients: function() { this.service = this.service || new STS({params: this.params}); } }); /***/ }), /***/ "../../../../aws-sdk/lib/credentials/temporary_credentials.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var STS = __webpack_require__("../../../../aws-sdk/clients/sts.js"); /** * Represents temporary credentials retrieved from {AWS.STS}. Without any * extra parameters, credentials will be fetched from the * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the * {AWS.STS.assumeRole} operation will be used to fetch credentials for the * role instead. * * To setup temporary credentials, configure a set of master credentials * using the standard credentials providers (environment, EC2 instance metadata, * or from the filesystem), then set the global credentials to a new * temporary credentials object: * * ```javascript * // Note that environment credentials are loaded by default, * // the following line is shown for clarity: * AWS.config.credentials = new AWS.EnvironmentCredentials('AWS'); * * // Now set temporary credentials seeded from the master credentials * AWS.config.credentials = new AWS.TemporaryCredentials(); * * // subsequent requests will now use temporary credentials from AWS STS. * new AWS.S3().listBucket(function(err, data) { ... }); * ``` * * @!attribute masterCredentials * @return [AWS.Credentials] the master (non-temporary) credentials used to * get and refresh temporary credentials from AWS STS. * @note (see constructor) */ AWS.TemporaryCredentials = AWS.util.inherit(AWS.Credentials, { /** * Creates a new temporary credentials object. * * @note In order to create temporary credentials, you first need to have * "master" credentials configured in {AWS.Config.credentials}. These * master credentials are necessary to retrieve the temporary credentials, * as well as refresh the credentials when they expire. * @param params [map] a map of options that are passed to the * {AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations. * If a `RoleArn` parameter is passed in, credentials will be based on the * IAM role. * @param masterCredentials [AWS.Credentials] the master (non-temporary) credentials * used to get and refresh temporary credentials from AWS STS. * @example Creating a new credentials object for generic temporary credentials * AWS.config.credentials = new AWS.TemporaryCredentials(); * @example Creating a new credentials object for an IAM role * AWS.config.credentials = new AWS.TemporaryCredentials({ * RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials', * }); * @see AWS.STS.assumeRole * @see AWS.STS.getSessionToken */ constructor: function TemporaryCredentials(params, masterCredentials) { AWS.Credentials.call(this); this.loadMasterCredentials(masterCredentials); this.expired = true; this.params = params || {}; if (this.params.RoleArn) { this.params.RoleSessionName = this.params.RoleSessionName || 'temporary-credentials'; } }, /** * Refreshes credentials using {AWS.STS.assumeRole} or * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed * to the credentials {constructor}. * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get */ refresh: function refresh(callback) { var self = this; self.createClients(); if (!callback) callback = function(err) { if (err) throw err; }; self.masterCredentials.get(function() { self.service.config.credentials = self.masterCredentials; var operation = self.params.RoleArn ? self.service.assumeRole : self.service.getSessionToken; operation.call(self.service, function (err, data) { if (!err) { self.service.credentialsFrom(data, self); } callback(err); }); }); }, /** * @api private */ loadMasterCredentials: function loadMasterCredentials(masterCredentials) { this.masterCredentials = masterCredentials || AWS.config.credentials; while (this.masterCredentials.masterCredentials) { this.masterCredentials = this.masterCredentials.masterCredentials; } if (typeof this.masterCredentials.get !== 'function') { this.masterCredentials = new AWS.Credentials(this.masterCredentials); } }, /** * @api private */ createClients: function() { this.service = this.service || new STS({params: this.params}); } }); /***/ }), /***/ "../../../../aws-sdk/lib/credentials/web_identity_credentials.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var STS = __webpack_require__("../../../../aws-sdk/clients/sts.js"); /** * Represents credentials retrieved from STS Web Identity Federation support. * * By default this provider gets credentials using the * {AWS.STS.assumeRoleWithWebIdentity} service operation. This operation * requires a `RoleArn` containing the ARN of the IAM trust policy for the * application for which credentials will be given. In addition, the * `WebIdentityToken` must be set to the token provided by the identity * provider. See {constructor} for an example on creating a credentials * object with proper `RoleArn` and `WebIdentityToken` values. * * ## Refreshing Credentials from Identity Service * * In addition to AWS credentials expiring after a given amount of time, the * login token from the identity provider will also expire. Once this token * expires, it will not be usable to refresh AWS credentials, and another * token will be needed. The SDK does not manage refreshing of the token value, * but this can be done through a "refresh token" supported by most identity * providers. Consult the documentation for the identity provider for refreshing * tokens. Once the refreshed token is acquired, you should make sure to update * this new token in the credentials object's {params} property. The following * code will update the WebIdentityToken, assuming you have retrieved an updated * token from the identity provider: * * ```javascript * AWS.config.credentials.params.WebIdentityToken = updatedToken; * ``` * * Future calls to `credentials.refresh()` will now use the new token. * * @!attribute params * @return [map] the map of params passed to * {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the * `params.WebIdentityToken` property. * @!attribute data * @return [map] the raw data response from the call to * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get * access to other properties from the response. */ AWS.WebIdentityCredentials = AWS.util.inherit(AWS.Credentials, { /** * Creates a new credentials object. * @param (see AWS.STS.assumeRoleWithWebIdentity) * @example Creating a new credentials object * AWS.config.credentials = new AWS.WebIdentityCredentials({ * RoleArn: 'arn:aws:iam::1234567890:role/WebIdentity', * WebIdentityToken: 'ABCDEFGHIJKLMNOP', // token from identity service * RoleSessionName: 'web' // optional name, defaults to web-identity * }, { * // optionally provide configuration to apply to the underlying AWS.STS service client * // if configuration is not provided, then configuration will be pulled from AWS.config * * // specify timeout options * httpOptions: { * timeout: 100 * } * }); * @see AWS.STS.assumeRoleWithWebIdentity * @see AWS.Config */ constructor: function WebIdentityCredentials(params, clientConfig) { AWS.Credentials.call(this); this.expired = true; this.params = params; this.params.RoleSessionName = this.params.RoleSessionName || 'web-identity'; this.data = null; this._clientConfig = AWS.util.copy(clientConfig || {}); }, /** * Refreshes credentials using {AWS.STS.assumeRoleWithWebIdentity} * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get */ refresh: function refresh(callback) { var self = this; self.createClients(); if (!callback) callback = function(err) { if (err) throw err; }; self.service.assumeRoleWithWebIdentity(function (err, data) { self.data = null; if (!err) { self.data = data; self.service.credentialsFrom(data, self); } callback(err); }); }, /** * @api private */ createClients: function() { if (!this.service) { var stsConfig = AWS.util.merge({}, this._clientConfig); stsConfig.params = this.params; this.service = new STS(stsConfig); } } }); /***/ }), /***/ "../../../../aws-sdk/lib/event_listeners.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var SequentialExecutor = __webpack_require__("../../../../aws-sdk/lib/sequential_executor.js"); /** * The namespace used to register global event listeners for request building * and sending. */ AWS.EventListeners = { /** * @!attribute VALIDATE_CREDENTIALS * A request listener that validates whether the request is being * sent with credentials. * Handles the {AWS.Request~validate 'validate' Request event} * @example Sending a request without validating credentials * var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS; * request.removeListener('validate', listener); * @readonly * @return [Function] * @!attribute VALIDATE_REGION * A request listener that validates whether the region is set * for a request. * Handles the {AWS.Request~validate 'validate' Request event} * @example Sending a request without validating region configuration * var listener = AWS.EventListeners.Core.VALIDATE_REGION; * request.removeListener('validate', listener); * @readonly * @return [Function] * @!attribute VALIDATE_PARAMETERS * A request listener that validates input parameters in a request. * Handles the {AWS.Request~validate 'validate' Request event} * @example Sending a request without validating parameters * var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS; * request.removeListener('validate', listener); * @example Disable parameter validation globally * AWS.EventListeners.Core.removeListener('validate', * AWS.EventListeners.Core.VALIDATE_REGION); * @readonly * @return [Function] * @!attribute SEND * A request listener that initiates the HTTP connection for a * request being sent. Handles the {AWS.Request~send 'send' Request event} * @example Replacing the HTTP handler * var listener = AWS.EventListeners.Core.SEND; * request.removeListener('send', listener); * request.on('send', function(response) { * customHandler.send(response); * }); * @return [Function] * @readonly * @!attribute HTTP_DATA * A request listener that reads data from the HTTP connection in order * to build the response data. * Handles the {AWS.Request~httpData 'httpData' Request event}. * Remove this handler if you are overriding the 'httpData' event and * do not want extra data processing and buffering overhead. * @example Disabling default data processing * var listener = AWS.EventListeners.Core.HTTP_DATA; * request.removeListener('httpData', listener); * @return [Function] * @readonly */ Core: {} /* doc hack */ }; /** * @api private */ function getOperationAuthtype(req) { if (!req.service.api.operations) { return ''; } var operation = req.service.api.operations[req.operation]; return operation ? operation.authtype : ''; } AWS.EventListeners = { Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) { addAsync('VALIDATE_CREDENTIALS', 'validate', function VALIDATE_CREDENTIALS(req, done) { if (!req.service.api.signatureVersion) return done(); // none req.service.config.getCredentials(function(err) { if (err) { req.response.error = AWS.util.error(err, {code: 'CredentialsError', message: 'Missing credentials in config'}); } done(); }); }); add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) { if (!req.service.config.region && !req.service.isGlobalEndpoint) { req.response.error = AWS.util.error(new Error(), {code: 'ConfigError', message: 'Missing region in config'}); } }); add('BUILD_IDEMPOTENCY_TOKENS', 'validate', function BUILD_IDEMPOTENCY_TOKENS(req) { if (!req.service.api.operations) { return; } var operation = req.service.api.operations[req.operation]; if (!operation) { return; } var idempotentMembers = operation.idempotentMembers; if (!idempotentMembers.length) { return; } // creates a copy of params so user's param object isn't mutated var params = AWS.util.copy(req.params); for (var i = 0, iLen = idempotentMembers.length; i < iLen; i++) { if (!params[idempotentMembers[i]]) { // add the member params[idempotentMembers[i]] = AWS.util.uuid.v4(); } } req.params = params; }); add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) { if (!req.service.api.operations) { return; } var rules = req.service.api.operations[req.operation].input; var validation = req.service.config.paramValidation; new AWS.ParamValidator(validation).validate(rules, req.params); }); addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) { req.haltHandlersOnError(); if (!req.service.api.operations) { return; } var operation = req.service.api.operations[req.operation]; var authtype = operation ? operation.authtype : ''; if (!req.service.api.signatureVersion && !authtype) return done(); // none if (req.service.getSignerClass(req) === AWS.Signers.V4) { var body = req.httpRequest.body || ''; if (authtype.indexOf('unsigned-body') >= 0) { req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD'; return done(); } AWS.util.computeSha256(body, function(err, sha) { if (err) { done(err); } else { req.httpRequest.headers['X-Amz-Content-Sha256'] = sha; done(); } }); } else { done(); } }); add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) { var authtype = getOperationAuthtype(req); if (req.httpRequest.headers['Content-Length'] === undefined && authtype.indexOf('unsigned-body') === -1) { var length = AWS.util.string.byteLength(req.httpRequest.body); req.httpRequest.headers['Content-Length'] = length; } }); add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) { req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host; }); add('RESTART', 'restart', function RESTART() { var err = this.response.error; if (!err || !err.retryable) return; this.httpRequest = new AWS.HttpRequest( this.service.endpoint, this.service.region ); if (this.response.retryCount < this.service.config.maxRetries) { this.response.retryCount++; } else { this.response.error = null; } }); addAsync('SIGN', 'sign', function SIGN(req, done) { var service = req.service; var operations = req.service.api.operations || {}; var operation = operations[req.operation]; var authtype = operation ? operation.authtype : ''; if (!service.api.signatureVersion && !authtype) return done(); // none service.config.getCredentials(function (err, credentials) { if (err) { req.response.error = err; return done(); } try { var date = AWS.util.date.getDate(); var SignerClass = service.getSignerClass(req); var signer = new SignerClass(req.httpRequest, service.api.signingName || service.api.endpointPrefix, { signatureCache: service.config.signatureCache, operation: operation }); signer.setServiceClientId(service._clientId); // clear old authorization headers delete req.httpRequest.headers['Authorization']; delete req.httpRequest.headers['Date']; delete req.httpRequest.headers['X-Amz-Date']; // add new authorization signer.addAuthorization(credentials, date); req.signedAt = date; } catch (e) { req.response.error = e; } done(); }); }); add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) { if (this.service.successfulResponse(resp, this)) { resp.data = {}; resp.error = null; } else { resp.data = null; resp.error = AWS.util.error(new Error(), {code: 'UnknownError', message: 'An unknown error occurred.'}); } }); addAsync('SEND', 'send', function SEND(resp, done) { resp.httpResponse._abortCallback = done; resp.error = null; resp.data = null; function callback(httpResp) { resp.httpResponse.stream = httpResp; var stream = resp.request.httpRequest.stream; httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) { resp.request.emit( 'httpHeaders', [statusCode, headers, resp, statusMessage] ); if (!resp.httpResponse.streaming) { if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check httpResp.on('readable', function onReadable() { var data = httpResp.read(); if (data !== null) { resp.request.emit('httpData', [data, resp]); } }); } else { // legacy streams API httpResp.on('data', function onData(data) { resp.request.emit('httpData', [data, resp]); }); } } }); httpResp.on('end', function onEnd() { if (!stream || !stream.didCallback) { resp.request.emit('httpDone'); done(); } }); } function progress(httpResp) { httpResp.on('sendProgress', function onSendProgress(value) { resp.request.emit('httpUploadProgress', [value, resp]); }); httpResp.on('receiveProgress', function onReceiveProgress(value) { resp.request.emit('httpDownloadProgress', [value, resp]); }); } function error(err) { if (err.code !== 'RequestAbortedError') { var errCode = err.code === 'TimeoutError' ? err.code : 'NetworkingError'; err = AWS.util.error(err, { code: errCode, region: resp.request.httpRequest.region, hostname: resp.request.httpRequest.endpoint.hostname, retryable: true }); } resp.error = err; resp.request.emit('httpError', [resp.error, resp], function() { done(); }); } function executeSend() { var http = AWS.HttpClient.getInstance(); var httpOptions = resp.request.service.config.httpOptions || {}; try { var stream = http.handleRequest(resp.request.httpRequest, httpOptions, callback, error); progress(stream); } catch (err) { error(err); } } var timeDiff = (AWS.util.date.getDate() - this.signedAt) / 1000; if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign this.emit('sign', [this], function(err) { if (err) done(err); else executeSend(); }); } else { executeSend(); } }); add('HTTP_HEADERS', 'httpHeaders', function HTTP_HEADERS(statusCode, headers, resp, statusMessage) { resp.httpResponse.statusCode = statusCode; resp.httpResponse.statusMessage = statusMessage; resp.httpResponse.headers = headers; resp.httpResponse.body = new AWS.util.Buffer(''); resp.httpResponse.buffers = []; resp.httpResponse.numBytes = 0; var dateHeader = headers.date || headers.Date; if (dateHeader) { var serverTime = Date.parse(dateHeader); if (resp.request.service.config.correctClockSkew && AWS.util.isClockSkewed(serverTime)) { AWS.util.applyClockOffset(serverTime); } } }); add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) { if (chunk) { if (AWS.util.isNode()) { resp.httpResponse.numBytes += chunk.length; var total = resp.httpResponse.headers['content-length']; var progress = { loaded: resp.httpResponse.numBytes, total: total }; resp.request.emit('httpDownloadProgress', [progress, resp]); } resp.httpResponse.buffers.push(new AWS.util.Buffer(chunk)); } }); add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) { // convert buffers array into single buffer if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) { var body = AWS.util.buffer.concat(resp.httpResponse.buffers); resp.httpResponse.body = body; } delete resp.httpResponse.numBytes; delete resp.httpResponse.buffers; }); add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) { if (resp.httpResponse.statusCode) { resp.error.statusCode = resp.httpResponse.statusCode; if (resp.error.retryable === undefined) { resp.error.retryable = this.service.retryableError(resp.error, this); } } }); add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) { if (!resp.error) return; switch (resp.error.code) { case 'RequestExpired': // EC2 only case 'ExpiredTokenException': case 'ExpiredToken': resp.error.retryable = true; resp.request.service.config.credentials.expired = true; } }); add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) { var err = resp.error; if (!err) return; if (typeof err.code === 'string' && typeof err.message === 'string') { if (err.code.match(/Signature/) && err.message.match(/expired/)) { resp.error.retryable = true; } } }); add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) { if (!resp.error) return; if (this.service.clockSkewError(resp.error) && this.service.config.correctClockSkew && AWS.config.isClockSkewed) { resp.error.retryable = true; } }); add('REDIRECT', 'retry', function REDIRECT(resp) { if (resp.error && resp.error.statusCode >= 300 && resp.error.statusCode < 400 && resp.httpResponse.headers['location']) { this.httpRequest.endpoint = new AWS.Endpoint(resp.httpResponse.headers['location']); this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host; resp.error.redirect = true; resp.error.retryable = true; } }); add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) { if (resp.error) { if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { resp.error.retryDelay = 0; } else if (resp.retryCount < resp.maxRetries) { resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0; } } }); addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) { var delay, willRetry = false; if (resp.error) { delay = resp.error.retryDelay || 0; if (resp.error.retryable && resp.retryCount < resp.maxRetries) { resp.retryCount++; willRetry = true; } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { resp.redirectCount++; willRetry = true; } } if (willRetry) { resp.error = null; setTimeout(done, delay); } else { done(); } }); }), CorePost: new SequentialExecutor().addNamedListeners(function(add) { add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId); add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId); add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) { if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') { var message = 'Inaccessible host: `' + err.hostname + '\'. This service may not be available in the `' + err.region + '\' region.'; this.response.error = AWS.util.error(new Error(message), { code: 'UnknownEndpoint', region: err.region, hostname: err.hostname, retryable: true, originalError: err }); } }); }), Logger: new SequentialExecutor().addNamedListeners(function(add) { add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) { var req = resp.request; var logger = req.service.config.logger; if (!logger) return; function buildMessage() { var time = AWS.util.date.getDate().getTime(); var delta = (time - req.startTime.getTime()) / 1000; var ansi = logger.isTTY ? true : false; var status = resp.httpResponse.statusCode; var params = __webpack_require__("../../../../util/util.js").inspect(req.params, true, null); var message = ''; if (ansi) message += '\x1B[33m'; message += '[AWS ' + req.service.serviceIdentifier + ' ' + status; message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]'; if (ansi) message += '\x1B[0;1m'; message += ' ' + AWS.util.string.lowerFirst(req.operation); message += '(' + params + ')'; if (ansi) message += '\x1B[0m'; return message; } var line = buildMessage(); if (typeof logger.log === 'function') { logger.log(line); } else if (typeof logger.write === 'function') { logger.write(line + '\n'); } }); }), Json: new SequentialExecutor().addNamedListeners(function(add) { var svc = __webpack_require__("../../../../aws-sdk/lib/protocol/json.js"); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), Rest: new SequentialExecutor().addNamedListeners(function(add) { var svc = __webpack_require__("../../../../aws-sdk/lib/protocol/rest.js"); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), RestJson: new SequentialExecutor().addNamedListeners(function(add) { var svc = __webpack_require__("../../../../aws-sdk/lib/protocol/rest_json.js"); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), RestXml: new SequentialExecutor().addNamedListeners(function(add) { var svc = __webpack_require__("../../../../aws-sdk/lib/protocol/rest_xml.js"); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), Query: new SequentialExecutor().addNamedListeners(function(add) { var svc = __webpack_require__("../../../../aws-sdk/lib/protocol/query.js"); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }) }; /***/ }), /***/ "../../../../aws-sdk/lib/http.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; /** * The endpoint that a service will talk to, for example, * `'https://ec2.ap-southeast-1.amazonaws.com'`. If * you need to override an endpoint for a service, you can * set the endpoint on a service by passing the endpoint * object with the `endpoint` option key: * * ```javascript * var ep = new AWS.Endpoint('awsproxy.example.com'); * var s3 = new AWS.S3({endpoint: ep}); * s3.service.endpoint.hostname == 'awsproxy.example.com' * ``` * * Note that if you do not specify a protocol, the protocol will * be selected based on your current {AWS.config} configuration. * * @!attribute protocol * @return [String] the protocol (http or https) of the endpoint * URL * @!attribute hostname * @return [String] the host portion of the endpoint, e.g., * example.com * @!attribute host * @return [String] the host portion of the endpoint including * the port, e.g., example.com:80 * @!attribute port * @return [Integer] the port of the endpoint * @!attribute href * @return [String] the full URL of the endpoint */ AWS.Endpoint = inherit({ /** * @overload Endpoint(endpoint) * Constructs a new endpoint given an endpoint URL. If the * URL omits a protocol (http or https), the default protocol * set in the global {AWS.config} will be used. * @param endpoint [String] the URL to construct an endpoint from */ constructor: function Endpoint(endpoint, config) { AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']); if (typeof endpoint === 'undefined' || endpoint === null) { throw new Error('Invalid endpoint: ' + endpoint); } else if (typeof endpoint !== 'string') { return AWS.util.copy(endpoint); } if (!endpoint.match(/^http/)) { var useSSL = config && config.sslEnabled !== undefined ? config.sslEnabled : AWS.config.sslEnabled; endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint; } AWS.util.update(this, AWS.util.urlParse(endpoint)); // Ensure the port property is set as an integer if (this.port) { this.port = parseInt(this.port, 10); } else { this.port = this.protocol === 'https:' ? 443 : 80; } } }); /** * The low level HTTP request object, encapsulating all HTTP header * and body data sent by a service request. * * @!attribute method * @return [String] the HTTP method of the request * @!attribute path * @return [String] the path portion of the URI, e.g., * "/list/?start=5&num=10" * @!attribute headers * @return [map] * a map of header keys and their respective values * @!attribute body * @return [String] the request body payload * @!attribute endpoint * @return [AWS.Endpoint] the endpoint for the request * @!attribute region * @api private * @return [String] the region, for signing purposes only. */ AWS.HttpRequest = inherit({ /** * @api private */ constructor: function HttpRequest(endpoint, region) { endpoint = new AWS.Endpoint(endpoint); this.method = 'POST'; this.path = endpoint.path || '/'; this.headers = {}; this.body = ''; this.endpoint = endpoint; this.region = region; this._userAgent = ''; this.setUserAgent(); }, /** * @api private */ setUserAgent: function setUserAgent() { this._userAgent = this.headers[this.getUserAgentHeaderName()] = AWS.util.userAgent(); }, getUserAgentHeaderName: function getUserAgentHeaderName() { var prefix = AWS.util.isBrowser() ? 'X-Amz-' : ''; return prefix + 'User-Agent'; }, /** * @api private */ appendToUserAgent: function appendToUserAgent(agentPartial) { if (typeof agentPartial === 'string' && agentPartial) { this._userAgent += ' ' + agentPartial; } this.headers[this.getUserAgentHeaderName()] = this._userAgent; }, /** * @api private */ getUserAgent: function getUserAgent() { return this._userAgent; }, /** * @return [String] the part of the {path} excluding the * query string */ pathname: function pathname() { return this.path.split('?', 1)[0]; }, /** * @return [String] the query string portion of the {path} */ search: function search() { var query = this.path.split('?', 2)[1]; if (query) { query = AWS.util.queryStringParse(query); return AWS.util.queryParamsToString(query); } return ''; } }); /** * The low level HTTP response object, encapsulating all HTTP header * and body data returned from the request. * * @!attribute statusCode * @return [Integer] the HTTP status code of the response (e.g., 200, 404) * @!attribute headers * @return [map] * a map of response header keys and their respective values * @!attribute body * @return [String] the response body payload * @!attribute [r] streaming * @return [Boolean] whether this response is being streamed at a low-level. * Defaults to `false` (buffered reads). Do not modify this manually, use * {createUnbufferedStream} to convert the stream to unbuffered mode * instead. */ AWS.HttpResponse = inherit({ /** * @api private */ constructor: function HttpResponse() { this.statusCode = undefined; this.headers = {}; this.body = undefined; this.streaming = false; this.stream = null; }, /** * Disables buffering on the HTTP response and returns the stream for reading. * @return [Stream, XMLHttpRequest, null] the underlying stream object. * Use this object to directly read data off of the stream. * @note This object is only available after the {AWS.Request~httpHeaders} * event has fired. This method must be called prior to * {AWS.Request~httpData}. * @example Taking control of a stream * request.on('httpHeaders', function(statusCode, headers) { * if (statusCode < 300) { * if (headers.etag === 'xyz') { * // pipe the stream, disabling buffering * var stream = this.response.httpResponse.createUnbufferedStream(); * stream.pipe(process.stdout); * } else { // abort this request and set a better error message * this.abort(); * this.response.error = new Error('Invalid ETag'); * } * } * }).send(console.log); */ createUnbufferedStream: function createUnbufferedStream() { this.streaming = true; return this.stream; } }); AWS.HttpClient = inherit({}); /** * @api private */ AWS.HttpClient.getInstance = function getInstance() { if (this.singleton === undefined) { this.singleton = new this(); } return this.singleton; }; /***/ }), /***/ "../../../../aws-sdk/lib/http/xhr.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var EventEmitter = __webpack_require__("../../../../events/events.js").EventEmitter; __webpack_require__("../../../../aws-sdk/lib/http.js"); /** * @api private */ AWS.XHRClient = AWS.util.inherit({ handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) { var self = this; var endpoint = httpRequest.endpoint; var emitter = new EventEmitter(); var href = endpoint.protocol + '//' + endpoint.hostname; if (endpoint.port !== 80 && endpoint.port !== 443) { href += ':' + endpoint.port; } href += httpRequest.path; var xhr = new XMLHttpRequest(), headersEmitted = false; httpRequest.stream = xhr; xhr.addEventListener('readystatechange', function() { try { if (xhr.status === 0) return; // 0 code is invalid } catch (e) { return; } if (this.readyState >= this.HEADERS_RECEIVED && !headersEmitted) { emitter.statusCode = xhr.status; emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders()); emitter.emit( 'headers', emitter.statusCode, emitter.headers, xhr.statusText ); headersEmitted = true; } if (this.readyState === this.DONE) { self.finishRequest(xhr, emitter); } }, false); xhr.upload.addEventListener('progress', function (evt) { emitter.emit('sendProgress', evt); }); xhr.addEventListener('progress', function (evt) { emitter.emit('receiveProgress', evt); }, false); xhr.addEventListener('timeout', function () { errCallback(AWS.util.error(new Error('Timeout'), {code: 'TimeoutError'})); }, false); xhr.addEventListener('error', function () { errCallback(AWS.util.error(new Error('Network Failure'), { code: 'NetworkingError' })); }, false); xhr.addEventListener('abort', function () { errCallback(AWS.util.error(new Error('Request aborted'), { code: 'RequestAbortedError' })); }, false); callback(emitter); xhr.open(httpRequest.method, href, httpOptions.xhrAsync !== false); AWS.util.each(httpRequest.headers, function (key, value) { if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') { xhr.setRequestHeader(key, value); } }); if (httpOptions.timeout && httpOptions.xhrAsync !== false) { xhr.timeout = httpOptions.timeout; } if (httpOptions.xhrWithCredentials) { xhr.withCredentials = true; } try { xhr.responseType = 'arraybuffer'; } catch (e) {} try { if (httpRequest.body) { xhr.send(httpRequest.body); } else { xhr.send(); } } catch (err) { if (httpRequest.body && typeof httpRequest.body.buffer === 'object') { xhr.send(httpRequest.body.buffer); // send ArrayBuffer directly } else { throw err; } } return emitter; }, parseHeaders: function parseHeaders(rawHeaders) { var headers = {}; AWS.util.arrayEach(rawHeaders.split(/\r?\n/), function (line) { var key = line.split(':', 1)[0]; var value = line.substring(key.length + 2); if (key.length > 0) headers[key.toLowerCase()] = value; }); return headers; }, finishRequest: function finishRequest(xhr, emitter) { var buffer; if (xhr.responseType === 'arraybuffer' && xhr.response) { var ab = xhr.response; buffer = new AWS.util.Buffer(ab.byteLength); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } } try { if (!buffer && typeof xhr.responseText === 'string') { buffer = new AWS.util.Buffer(xhr.responseText); } } catch (e) {} if (buffer) emitter.emit('data', buffer); emitter.emit('end'); } }); /** * @api private */ AWS.HttpClient.prototype = AWS.XHRClient.prototype; /** * @api private */ AWS.HttpClient.streamsApiVersion = 1; /***/ }), /***/ "../../../../aws-sdk/lib/json/builder.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); function JsonBuilder() { } JsonBuilder.prototype.build = function(value, shape) { return JSON.stringify(translate(value, shape)); }; function translate(value, shape) { if (!shape || value === undefined || value === null) return undefined; switch (shape.type) { case 'structure': return translateStructure(value, shape); case 'map': return translateMap(value, shape); case 'list': return translateList(value, shape); default: return translateScalar(value, shape); } } function translateStructure(structure, shape) { var struct = {}; util.each(structure, function(name, value) { var memberShape = shape.members[name]; if (memberShape) { if (memberShape.location !== 'body') return; var locationName = memberShape.isLocationName ? memberShape.name : name; var result = translate(value, memberShape); if (result !== undefined) struct[locationName] = result; } }); return struct; } function translateList(list, shape) { var out = []; util.arrayEach(list, function(value) { var result = translate(value, shape.member); if (result !== undefined) out.push(result); }); return out; } function translateMap(map, shape) { var out = {}; util.each(map, function(key, value) { var result = translate(value, shape.value); if (result !== undefined) out[key] = result; }); return out; } function translateScalar(value, shape) { return shape.toWireFormat(value); } module.exports = JsonBuilder; /***/ }), /***/ "../../../../aws-sdk/lib/json/parser.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); function JsonParser() { } JsonParser.prototype.parse = function(value, shape) { return translate(JSON.parse(value), shape); }; function translate(value, shape) { if (!shape || value === undefined) return undefined; switch (shape.type) { case 'structure': return translateStructure(value, shape); case 'map': return translateMap(value, shape); case 'list': return translateList(value, shape); default: return translateScalar(value, shape); } } function translateStructure(structure, shape) { if (structure == null) return undefined; var struct = {}; var shapeMembers = shape.members; util.each(shapeMembers, function(name, memberShape) { var locationName = memberShape.isLocationName ? memberShape.name : name; if (Object.prototype.hasOwnProperty.call(structure, locationName)) { var value = structure[locationName]; var result = translate(value, memberShape); if (result !== undefined) struct[name] = result; } }); return struct; } function translateList(list, shape) { if (list == null) return undefined; var out = []; util.arrayEach(list, function(value) { var result = translate(value, shape.member); if (result === undefined) out.push(null); else out.push(result); }); return out; } function translateMap(map, shape) { if (map == null) return undefined; var out = {}; util.each(map, function(key, value) { var result = translate(value, shape.value); if (result === undefined) out[key] = null; else out[key] = result; }); return out; } function translateScalar(value, shape) { return shape.toType(value); } module.exports = JsonParser; /***/ }), /***/ "../../../../aws-sdk/lib/model/api.js": /***/ (function(module, exports, __webpack_require__) { var Collection = __webpack_require__("../../../../aws-sdk/lib/model/collection.js"); var Operation = __webpack_require__("../../../../aws-sdk/lib/model/operation.js"); var Shape = __webpack_require__("../../../../aws-sdk/lib/model/shape.js"); var Paginator = __webpack_require__("../../../../aws-sdk/lib/model/paginator.js"); var ResourceWaiter = __webpack_require__("../../../../aws-sdk/lib/model/resource_waiter.js"); var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var property = util.property; var memoizedProperty = util.memoizedProperty; function Api(api, options) { api = api || {}; options = options || {}; options.api = this; api.metadata = api.metadata || {}; property(this, 'isApi', true, false); property(this, 'apiVersion', api.metadata.apiVersion); property(this, 'endpointPrefix', api.metadata.endpointPrefix); property(this, 'signingName', api.metadata.signingName); property(this, 'globalEndpoint', api.metadata.globalEndpoint); property(this, 'signatureVersion', api.metadata.signatureVersion); property(this, 'jsonVersion', api.metadata.jsonVersion); property(this, 'targetPrefix', api.metadata.targetPrefix); property(this, 'protocol', api.metadata.protocol); property(this, 'timestampFormat', api.metadata.timestampFormat); property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace); property(this, 'abbreviation', api.metadata.serviceAbbreviation); property(this, 'fullName', api.metadata.serviceFullName); memoizedProperty(this, 'className', function() { var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName; if (!name) return null; name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, ''); if (name === 'ElasticLoadBalancing') name = 'ELB'; return name; }); property(this, 'operations', new Collection(api.operations, options, function(name, operation) { return new Operation(name, operation, options); }, util.string.lowerFirst)); property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) { return Shape.create(shape, options); })); property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) { return new Paginator(name, paginator, options); })); property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) { return new ResourceWaiter(name, waiter, options); }, util.string.lowerFirst)); if (options.documentation) { property(this, 'documentation', api.documentation); property(this, 'documentationUrl', api.documentationUrl); } } module.exports = Api; /***/ }), /***/ "../../../../aws-sdk/lib/model/collection.js": /***/ (function(module, exports, __webpack_require__) { var memoizedProperty = __webpack_require__("../../../../aws-sdk/lib/util.js").memoizedProperty; function memoize(name, value, fn, nameTr) { memoizedProperty(this, nameTr(name), function() { return fn(name, value); }); } function Collection(iterable, options, fn, nameTr) { nameTr = nameTr || String; var self = this; for (var id in iterable) { if (Object.prototype.hasOwnProperty.call(iterable, id)) { memoize.call(self, id, iterable[id], fn, nameTr); } } } module.exports = Collection; /***/ }), /***/ "../../../../aws-sdk/lib/model/operation.js": /***/ (function(module, exports, __webpack_require__) { var Shape = __webpack_require__("../../../../aws-sdk/lib/model/shape.js"); var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var property = util.property; var memoizedProperty = util.memoizedProperty; function Operation(name, operation, options) { var self = this; options = options || {}; property(this, 'name', operation.name || name); property(this, 'api', options.api, false); operation.http = operation.http || {}; property(this, 'httpMethod', operation.http.method || 'POST'); property(this, 'httpPath', operation.http.requestUri || '/'); property(this, 'authtype', operation.authtype || ''); memoizedProperty(this, 'input', function() { if (!operation.input) { return new Shape.create({type: 'structure'}, options); } return Shape.create(operation.input, options); }); memoizedProperty(this, 'output', function() { if (!operation.output) { return new Shape.create({type: 'structure'}, options); } return Shape.create(operation.output, options); }); memoizedProperty(this, 'errors', function() { var list = []; if (!operation.errors) return null; for (var i = 0; i < operation.errors.length; i++) { list.push(Shape.create(operation.errors[i], options)); } return list; }); memoizedProperty(this, 'paginator', function() { return options.api.paginators[name]; }); if (options.documentation) { property(this, 'documentation', operation.documentation); property(this, 'documentationUrl', operation.documentationUrl); } // idempotentMembers only tracks top-level input shapes memoizedProperty(this, 'idempotentMembers', function() { var idempotentMembers = []; var input = self.input; var members = input.members; if (!input.members) { return idempotentMembers; } for (var name in members) { if (!members.hasOwnProperty(name)) { continue; } if (members[name].isIdempotent === true) { idempotentMembers.push(name); } } return idempotentMembers; }); } module.exports = Operation; /***/ }), /***/ "../../../../aws-sdk/lib/model/paginator.js": /***/ (function(module, exports, __webpack_require__) { var property = __webpack_require__("../../../../aws-sdk/lib/util.js").property; function Paginator(name, paginator) { property(this, 'inputToken', paginator.input_token); property(this, 'limitKey', paginator.limit_key); property(this, 'moreResults', paginator.more_results); property(this, 'outputToken', paginator.output_token); property(this, 'resultKey', paginator.result_key); } module.exports = Paginator; /***/ }), /***/ "../../../../aws-sdk/lib/model/resource_waiter.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var property = util.property; function ResourceWaiter(name, waiter, options) { options = options || {}; property(this, 'name', name); property(this, 'api', options.api, false); if (waiter.operation) { property(this, 'operation', util.string.lowerFirst(waiter.operation)); } var self = this; var keys = [ 'type', 'description', 'delay', 'maxAttempts', 'acceptors' ]; keys.forEach(function(key) { var value = waiter[key]; if (value) { property(self, key, value); } }); } module.exports = ResourceWaiter; /***/ }), /***/ "../../../../aws-sdk/lib/model/shape.js": /***/ (function(module, exports, __webpack_require__) { var Collection = __webpack_require__("../../../../aws-sdk/lib/model/collection.js"); var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); function property(obj, name, value) { if (value !== null && value !== undefined) { util.property.apply(this, arguments); } } function memoizedProperty(obj, name) { if (!obj.constructor.prototype[name]) { util.memoizedProperty.apply(this, arguments); } } function Shape(shape, options, memberName) { options = options || {}; property(this, 'shape', shape.shape); property(this, 'api', options.api, false); property(this, 'type', shape.type); property(this, 'enum', shape.enum); property(this, 'min', shape.min); property(this, 'max', shape.max); property(this, 'pattern', shape.pattern); property(this, 'location', shape.location || this.location || 'body'); property(this, 'name', this.name || shape.xmlName || shape.queryName || shape.locationName || memberName); property(this, 'isStreaming', shape.streaming || this.isStreaming || false); property(this, 'isComposite', shape.isComposite || false); property(this, 'isShape', true, false); property(this, 'isQueryName', Boolean(shape.queryName), false); property(this, 'isLocationName', Boolean(shape.locationName), false); property(this, 'isIdempotent', shape.idempotencyToken === true); property(this, 'isJsonValue', shape.jsonvalue === true); if (options.documentation) { property(this, 'documentation', shape.documentation); property(this, 'documentationUrl', shape.documentationUrl); } if (shape.xmlAttribute) { property(this, 'isXmlAttribute', shape.xmlAttribute || false); } // type conversion and parsing property(this, 'defaultValue', null); this.toWireFormat = function(value) { if (value === null || value === undefined) return ''; return value; }; this.toType = function(value) { return value; }; } /** * @api private */ Shape.normalizedTypes = { character: 'string', double: 'float', long: 'integer', short: 'integer', biginteger: 'integer', bigdecimal: 'float', blob: 'binary' }; /** * @api private */ Shape.types = { 'structure': StructureShape, 'list': ListShape, 'map': MapShape, 'boolean': BooleanShape, 'timestamp': TimestampShape, 'float': FloatShape, 'integer': IntegerShape, 'string': StringShape, 'base64': Base64Shape, 'binary': BinaryShape }; Shape.resolve = function resolve(shape, options) { if (shape.shape) { var refShape = options.api.shapes[shape.shape]; if (!refShape) { throw new Error('Cannot find shape reference: ' + shape.shape); } return refShape; } else { return null; } }; Shape.create = function create(shape, options, memberName) { if (shape.isShape) return shape; var refShape = Shape.resolve(shape, options); if (refShape) { var filteredKeys = Object.keys(shape); if (!options.documentation) { filteredKeys = filteredKeys.filter(function(name) { return !name.match(/documentation/); }); } // create an inline shape with extra members var InlineShape = function() { refShape.constructor.call(this, shape, options, memberName); }; InlineShape.prototype = refShape; return new InlineShape(); } else { // set type if not set if (!shape.type) { if (shape.members) shape.type = 'structure'; else if (shape.member) shape.type = 'list'; else if (shape.key) shape.type = 'map'; else shape.type = 'string'; } // normalize types var origType = shape.type; if (Shape.normalizedTypes[shape.type]) { shape.type = Shape.normalizedTypes[shape.type]; } if (Shape.types[shape.type]) { return new Shape.types[shape.type](shape, options, memberName); } else { throw new Error('Unrecognized shape type: ' + origType); } } }; function CompositeShape(shape) { Shape.apply(this, arguments); property(this, 'isComposite', true); if (shape.flattened) { property(this, 'flattened', shape.flattened || false); } } function StructureShape(shape, options) { var requiredMap = null, firstInit = !this.isShape; CompositeShape.apply(this, arguments); if (firstInit) { property(this, 'defaultValue', function() { return {}; }); property(this, 'members', {}); property(this, 'memberNames', []); property(this, 'required', []); property(this, 'isRequired', function() { return false; }); } if (shape.members) { property(this, 'members', new Collection(shape.members, options, function(name, member) { return Shape.create(member, options, name); })); memoizedProperty(this, 'memberNames', function() { return shape.xmlOrder || Object.keys(shape.members); }); } if (shape.required) { property(this, 'required', shape.required); property(this, 'isRequired', function(name) { if (!requiredMap) { requiredMap = {}; for (var i = 0; i < shape.required.length; i++) { requiredMap[shape.required[i]] = true; } } return requiredMap[name]; }, false, true); } property(this, 'resultWrapper', shape.resultWrapper || null); if (shape.payload) { property(this, 'payload', shape.payload); } if (typeof shape.xmlNamespace === 'string') { property(this, 'xmlNamespaceUri', shape.xmlNamespace); } else if (typeof shape.xmlNamespace === 'object') { property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix); property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri); } } function ListShape(shape, options) { var self = this, firstInit = !this.isShape; CompositeShape.apply(this, arguments); if (firstInit) { property(this, 'defaultValue', function() { return []; }); } if (shape.member) { memoizedProperty(this, 'member', function() { return Shape.create(shape.member, options); }); } if (this.flattened) { var oldName = this.name; memoizedProperty(this, 'name', function() { return self.member.name || oldName; }); } } function MapShape(shape, options) { var firstInit = !this.isShape; CompositeShape.apply(this, arguments); if (firstInit) { property(this, 'defaultValue', function() { return {}; }); property(this, 'key', Shape.create({type: 'string'}, options)); property(this, 'value', Shape.create({type: 'string'}, options)); } if (shape.key) { memoizedProperty(this, 'key', function() { return Shape.create(shape.key, options); }); } if (shape.value) { memoizedProperty(this, 'value', function() { return Shape.create(shape.value, options); }); } } function TimestampShape(shape) { var self = this; Shape.apply(this, arguments); if (this.location === 'header') { property(this, 'timestampFormat', 'rfc822'); } else if (shape.timestampFormat) { property(this, 'timestampFormat', shape.timestampFormat); } else if (!this.timestampFormat && this.api) { if (this.api.timestampFormat) { property(this, 'timestampFormat', this.api.timestampFormat); } else { switch (this.api.protocol) { case 'json': case 'rest-json': property(this, 'timestampFormat', 'unixTimestamp'); break; case 'rest-xml': case 'query': case 'ec2': property(this, 'timestampFormat', 'iso8601'); break; } } } this.toType = function(value) { if (value === null || value === undefined) return null; if (typeof value.toUTCString === 'function') return value; return typeof value === 'string' || typeof value === 'number' ? util.date.parseTimestamp(value) : null; }; this.toWireFormat = function(value) { return util.date.format(value, self.timestampFormat); }; } function StringShape() { Shape.apply(this, arguments); var nullLessProtocols = ['rest-xml', 'query', 'ec2']; this.toType = function(value) { value = this.api && nullLessProtocols.indexOf(this.api.protocol) > -1 ? value || '' : value; if (this.isJsonValue) { return JSON.parse(value); } return value && typeof value.toString === 'function' ? value.toString() : value; }; this.toWireFormat = function(value) { return this.isJsonValue ? JSON.stringify(value) : value; }; } function FloatShape() { Shape.apply(this, arguments); this.toType = function(value) { if (value === null || value === undefined) return null; return parseFloat(value); }; this.toWireFormat = this.toType; } function IntegerShape() { Shape.apply(this, arguments); this.toType = function(value) { if (value === null || value === undefined) return null; return parseInt(value, 10); }; this.toWireFormat = this.toType; } function BinaryShape() { Shape.apply(this, arguments); this.toType = util.base64.decode; this.toWireFormat = util.base64.encode; } function Base64Shape() { BinaryShape.apply(this, arguments); } function BooleanShape() { Shape.apply(this, arguments); this.toType = function(value) { if (typeof value === 'boolean') return value; if (value === null || value === undefined) return null; return value === 'true'; }; } /** * @api private */ Shape.shapes = { StructureShape: StructureShape, ListShape: ListShape, MapShape: MapShape, StringShape: StringShape, BooleanShape: BooleanShape, Base64Shape: Base64Shape }; module.exports = Shape; /***/ }), /***/ "../../../../aws-sdk/lib/param_validator.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); /** * @api private */ AWS.ParamValidator = AWS.util.inherit({ /** * Create a new validator object. * * @param validation [Boolean|map] whether input parameters should be * validated against the operation description before sending the * request. Pass a map to enable any of the following specific * validation features: * * * **min** [Boolean] — Validates that a value meets the min * constraint. This is enabled by default when paramValidation is set * to `true`. * * **max** [Boolean] — Validates that a value meets the max * constraint. * * **pattern** [Boolean] — Validates that a string value matches a * regular expression. * * **enum** [Boolean] — Validates that a string value matches one * of the allowable enum values. */ constructor: function ParamValidator(validation) { if (validation === true || validation === undefined) { validation = {'min': true}; } this.validation = validation; }, validate: function validate(shape, params, context) { this.errors = []; this.validateMember(shape, params || {}, context || 'params'); if (this.errors.length > 1) { var msg = this.errors.join('\n* '); msg = 'There were ' + this.errors.length + ' validation errors:\n* ' + msg; throw AWS.util.error(new Error(msg), {code: 'MultipleValidationErrors', errors: this.errors}); } else if (this.errors.length === 1) { throw this.errors[0]; } else { return true; } }, fail: function fail(code, message) { this.errors.push(AWS.util.error(new Error(message), {code: code})); }, validateStructure: function validateStructure(shape, params, context) { this.validateType(params, context, ['object'], 'structure'); var paramName; for (var i = 0; shape.required && i < shape.required.length; i++) { paramName = shape.required[i]; var value = params[paramName]; if (value === undefined || value === null) { this.fail('MissingRequiredParameter', 'Missing required key \'' + paramName + '\' in ' + context); } } // validate hash members for (paramName in params) { if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue; var paramValue = params[paramName], memberShape = shape.members[paramName]; if (memberShape !== undefined) { var memberContext = [context, paramName].join('.'); this.validateMember(memberShape, paramValue, memberContext); } else { this.fail('UnexpectedParameter', 'Unexpected key \'' + paramName + '\' found in ' + context); } } return true; }, validateMember: function validateMember(shape, param, context) { switch (shape.type) { case 'structure': return this.validateStructure(shape, param, context); case 'list': return this.validateList(shape, param, context); case 'map': return this.validateMap(shape, param, context); default: return this.validateScalar(shape, param, context); } }, validateList: function validateList(shape, params, context) { if (this.validateType(params, context, [Array])) { this.validateRange(shape, params.length, context, 'list member count'); // validate array members for (var i = 0; i < params.length; i++) { this.validateMember(shape.member, params[i], context + '[' + i + ']'); } } }, validateMap: function validateMap(shape, params, context) { if (this.validateType(params, context, ['object'], 'map')) { // Build up a count of map members to validate range traits. var mapCount = 0; for (var param in params) { if (!Object.prototype.hasOwnProperty.call(params, param)) continue; // Validate any map key trait constraints this.validateMember(shape.key, param, context + '[key=\'' + param + '\']') this.validateMember(shape.value, params[param], context + '[\'' + param + '\']'); mapCount++; } this.validateRange(shape, mapCount, context, 'map member count'); } }, validateScalar: function validateScalar(shape, value, context) { switch (shape.type) { case null: case undefined: case 'string': return this.validateString(shape, value, context); case 'base64': case 'binary': return this.validatePayload(value, context); case 'integer': case 'float': return this.validateNumber(shape, value, context); case 'boolean': return this.validateType(value, context, ['boolean']); case 'timestamp': return this.validateType(value, context, [Date, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'], 'Date object, ISO-8601 string, or a UNIX timestamp'); default: return this.fail('UnkownType', 'Unhandled type ' + shape.type + ' for ' + context); } }, validateString: function validateString(shape, value, context) { var validTypes = ['string']; if (shape.isJsonValue) { validTypes = validTypes.concat(['number', 'object', 'boolean']); } if (value !== null && this.validateType(value, context, validTypes)) { this.validateEnum(shape, value, context); this.validateRange(shape, value.length, context, 'string length'); this.validatePattern(shape, value, context); } }, validatePattern: function validatePattern(shape, value, context) { if (this.validation['pattern'] && shape['pattern'] !== undefined) { if (!(new RegExp(shape['pattern'])).test(value)) { this.fail('PatternMatchError', 'Provided value "' + value + '" ' + 'does not match regex pattern /' + shape['pattern'] + '/ for ' + context); } } }, validateRange: function validateRange(shape, value, context, descriptor) { if (this.validation['min']) { if (shape['min'] !== undefined && value < shape['min']) { this.fail('MinRangeError', 'Expected ' + descriptor + ' >= ' + shape['min'] + ', but found ' + value + ' for ' + context); } } if (this.validation['max']) { if (shape['max'] !== undefined && value > shape['max']) { this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= ' + shape['max'] + ', but found ' + value + ' for ' + context); } } }, validateEnum: function validateRange(shape, value, context) { if (this.validation['enum'] && shape['enum'] !== undefined) { // Fail if the string value is not present in the enum list if (shape['enum'].indexOf(value) === -1) { this.fail('EnumError', 'Found string value of ' + value + ', but ' + 'expected ' + shape['enum'].join('|') + ' for ' + context); } } }, validateType: function validateType(value, context, acceptedTypes, type) { // We will not log an error for null or undefined, but we will return // false so that callers know that the expected type was not strictly met. if (value === null || value === undefined) return false; var foundInvalidType = false; for (var i = 0; i < acceptedTypes.length; i++) { if (typeof acceptedTypes[i] === 'string') { if (typeof value === acceptedTypes[i]) return true; } else if (acceptedTypes[i] instanceof RegExp) { if ((value || '').toString().match(acceptedTypes[i])) return true; } else { if (value instanceof acceptedTypes[i]) return true; if (AWS.util.isType(value, acceptedTypes[i])) return true; if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice(); acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]); } foundInvalidType = true; } var acceptedType = type; if (!acceptedType) { acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1'); } var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : ''; this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' + vowel + ' ' + acceptedType); return false; }, validateNumber: function validateNumber(shape, value, context) { if (value === null || value === undefined) return; if (typeof value === 'string') { var castedValue = parseFloat(value); if (castedValue.toString() === value) value = castedValue; } if (this.validateType(value, context, ['number'])) { this.validateRange(shape, value, context, 'numeric value'); } }, validatePayload: function validatePayload(value, context) { if (value === null || value === undefined) return; if (typeof value === 'string') return; if (value && typeof value.byteLength === 'number') return; // typed arrays if (AWS.util.isNode()) { // special check for buffer/stream in Node.js var Stream = AWS.util.stream.Stream; if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return; } var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView']; if (value) { for (var i = 0; i < types.length; i++) { if (AWS.util.isType(value, types[i])) return; if (AWS.util.typeName(value.constructor) === types[i]) return; } } this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' + 'string, Buffer, Stream, Blob, or typed array object'); } }); /***/ }), /***/ "../../../../aws-sdk/lib/protocol/json.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var JsonBuilder = __webpack_require__("../../../../aws-sdk/lib/json/builder.js"); var JsonParser = __webpack_require__("../../../../aws-sdk/lib/json/parser.js"); function buildRequest(req) { var httpRequest = req.httpRequest; var api = req.service.api; var target = api.targetPrefix + '.' + api.operations[req.operation].name; var version = api.jsonVersion || '1.0'; var input = api.operations[req.operation].input; var builder = new JsonBuilder(); if (version === 1) version = '1.0'; httpRequest.body = builder.build(req.params || {}, input); httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version; httpRequest.headers['X-Amz-Target'] = target; } function extractError(resp) { var error = {}; var httpResponse = resp.httpResponse; error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError'; if (typeof error.code === 'string') { error.code = error.code.split(':')[0]; } if (httpResponse.body.length > 0) { try { var e = JSON.parse(httpResponse.body.toString()); if (e.__type || e.code) { error.code = (e.__type || e.code).split('#').pop(); } if (error.code === 'RequestEntityTooLarge') { error.message = 'Request body must be less than 1 MB'; } else { error.message = (e.message || e.Message || null); } } catch (e) { error.statusCode = httpResponse.statusCode; error.message = httpResponse.statusMessage; } } else { error.statusCode = httpResponse.statusCode; error.message = httpResponse.statusCode.toString(); } resp.error = util.error(new Error(), error); } function extractData(resp) { var body = resp.httpResponse.body.toString() || '{}'; if (resp.request.service.config.convertResponseTypes === false) { resp.data = JSON.parse(body); } else { var operation = resp.request.service.api.operations[resp.request.operation]; var shape = operation.output || {}; var parser = new JsonParser(); resp.data = parser.parse(body, shape); } } module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; /***/ }), /***/ "../../../../aws-sdk/lib/protocol/query.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var QueryParamSerializer = __webpack_require__("../../../../aws-sdk/lib/query/query_param_serializer.js"); var Shape = __webpack_require__("../../../../aws-sdk/lib/model/shape.js"); function buildRequest(req) { var operation = req.service.api.operations[req.operation]; var httpRequest = req.httpRequest; httpRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; httpRequest.params = { Version: req.service.api.apiVersion, Action: operation.name }; // convert the request parameters into a list of query params, // e.g. Deeply.NestedParam.0.Name=value var builder = new QueryParamSerializer(); builder.serialize(req.params, operation.input, function(name, value) { httpRequest.params[name] = value; }); httpRequest.body = util.queryParamsToString(httpRequest.params); } function extractError(resp) { var data, body = resp.httpResponse.body.toString(); if (body.match('= 0 ? '&' : '?'); var parts = []; util.arrayEach(Object.keys(queryString).sort(), function(key) { if (!Array.isArray(queryString[key])) { queryString[key] = [queryString[key]]; } for (var i = 0; i < queryString[key].length; i++) { parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]); } }); uri += parts.join('&'); } return uri; } function populateURI(req) { var operation = req.service.api.operations[req.operation]; var input = operation.input; var uri = generateURI(req.httpRequest.endpoint.path, operation.httpPath, input, req.params); req.httpRequest.path = uri; } function populateHeaders(req) { var operation = req.service.api.operations[req.operation]; util.each(operation.input.members, function (name, member) { var value = req.params[name]; if (value === null || value === undefined) return; if (member.location === 'headers' && member.type === 'map') { util.each(value, function(key, memberValue) { req.httpRequest.headers[member.name + key] = memberValue; }); } else if (member.location === 'header') { value = member.toWireFormat(value).toString(); if (member.isJsonValue) { value = util.base64.encode(value); } req.httpRequest.headers[member.name] = value; } }); } function buildRequest(req) { populateMethod(req); populateURI(req); populateHeaders(req); } function extractError() { } function extractData(resp) { var req = resp.request; var data = {}; var r = resp.httpResponse; var operation = req.service.api.operations[req.operation]; var output = operation.output; // normalize headers names to lower-cased keys for matching var headers = {}; util.each(r.headers, function (k, v) { headers[k.toLowerCase()] = v; }); util.each(output.members, function(name, member) { var header = (member.name || name).toLowerCase(); if (member.location === 'headers' && member.type === 'map') { data[name] = {}; var location = member.isLocationName ? member.name : ''; var pattern = new RegExp('^' + location + '(.+)', 'i'); util.each(r.headers, function (k, v) { var result = k.match(pattern); if (result !== null) { data[name][result[1]] = v; } }); } else if (member.location === 'header') { if (headers[header] !== undefined) { var value = member.isJsonValue ? util.base64.decode(headers[header]) : headers[header]; data[name] = member.toType(value); } } else if (member.location === 'statusCode') { data[name] = parseInt(r.statusCode, 10); } }); resp.data = data; } module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData, generateURI: generateURI }; /***/ }), /***/ "../../../../aws-sdk/lib/protocol/rest_json.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var Rest = __webpack_require__("../../../../aws-sdk/lib/protocol/rest.js"); var Json = __webpack_require__("../../../../aws-sdk/lib/protocol/json.js"); var JsonBuilder = __webpack_require__("../../../../aws-sdk/lib/json/builder.js"); var JsonParser = __webpack_require__("../../../../aws-sdk/lib/json/parser.js"); function populateBody(req) { var builder = new JsonBuilder(); var input = req.service.api.operations[req.operation].input; if (input.payload) { var params = {}; var payloadShape = input.members[input.payload]; params = req.params[input.payload]; if (params === undefined) return; if (payloadShape.type === 'structure') { req.httpRequest.body = builder.build(params, payloadShape); applyContentTypeHeader(req); } else { // non-JSON payload req.httpRequest.body = params; } } else { req.httpRequest.body = builder.build(req.params, input); applyContentTypeHeader(req); } } function applyContentTypeHeader(req) { if (!req.httpRequest.headers['Content-Type']) { req.httpRequest.headers['Content-Type'] = 'application/json'; } } function buildRequest(req) { Rest.buildRequest(req); // never send body payload on GET/HEAD/DELETE if (['GET', 'HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) { populateBody(req); } } function extractError(resp) { Json.extractError(resp); } function extractData(resp) { Rest.extractData(resp); var req = resp.request; var rules = req.service.api.operations[req.operation].output || {}; if (rules.payload) { var payloadMember = rules.members[rules.payload]; var body = resp.httpResponse.body; if (payloadMember.type === 'structure' || payloadMember.type === 'list') { var parser = new JsonParser(); resp.data[rules.payload] = parser.parse(body, payloadMember); } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) { resp.data[rules.payload] = body; } else { resp.data[rules.payload] = payloadMember.toType(body); } } else { var data = resp.data; Json.extractData(resp); resp.data = util.merge(data, resp.data); } } module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; /***/ }), /***/ "../../../../aws-sdk/lib/protocol/rest_xml.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var Rest = __webpack_require__("../../../../aws-sdk/lib/protocol/rest.js"); function populateBody(req) { var input = req.service.api.operations[req.operation].input; var builder = new AWS.XML.Builder(); var params = req.params; var payload = input.payload; if (payload) { var payloadMember = input.members[payload]; params = params[payload]; if (params === undefined) return; if (payloadMember.type === 'structure') { var rootElement = payloadMember.name; req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true); } else { // non-xml payload req.httpRequest.body = params; } } else { req.httpRequest.body = builder.toXML(params, input, input.name || input.shape || util.string.upperFirst(req.operation) + 'Request'); } } function buildRequest(req) { Rest.buildRequest(req); // never send body payload on GET/HEAD if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) { populateBody(req); } } function extractError(resp) { Rest.extractError(resp); var data; try { data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString()); } catch (e) { data = { Code: resp.httpResponse.statusCode, Message: resp.httpResponse.statusMessage }; } if (data.Errors) data = data.Errors; if (data.Error) data = data.Error; if (data.Code) { resp.error = util.error(new Error(), { code: data.Code, message: data.Message }); } else { resp.error = util.error(new Error(), { code: resp.httpResponse.statusCode, message: null }); } } function extractData(resp) { Rest.extractData(resp); var parser; var req = resp.request; var body = resp.httpResponse.body; var operation = req.service.api.operations[req.operation]; var output = operation.output; var payload = output.payload; if (payload) { var payloadMember = output.members[payload]; if (payloadMember.type === 'structure') { parser = new AWS.XML.Parser(); resp.data[payload] = parser.parse(body.toString(), payloadMember); } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) { resp.data[payload] = body; } else { resp.data[payload] = payloadMember.toType(body); } } else if (body.length > 0) { parser = new AWS.XML.Parser(); var data = parser.parse(body.toString(), output); util.update(resp.data, data); } } module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; /***/ }), /***/ "../../../../aws-sdk/lib/query/query_param_serializer.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); function QueryParamSerializer() { } QueryParamSerializer.prototype.serialize = function(params, shape, fn) { serializeStructure('', params, shape, fn); }; function ucfirst(shape) { if (shape.isQueryName || shape.api.protocol !== 'ec2') { return shape.name; } else { return shape.name[0].toUpperCase() + shape.name.substr(1); } } function serializeStructure(prefix, struct, rules, fn) { util.each(rules.members, function(name, member) { var value = struct[name]; if (value === null || value === undefined) return; var memberName = ucfirst(member); memberName = prefix ? prefix + '.' + memberName : memberName; serializeMember(memberName, value, member, fn); }); } function serializeMap(name, map, rules, fn) { var i = 1; util.each(map, function (key, value) { var prefix = rules.flattened ? '.' : '.entry.'; var position = prefix + (i++) + '.'; var keyName = position + (rules.key.name || 'key'); var valueName = position + (rules.value.name || 'value'); serializeMember(name + keyName, key, rules.key, fn); serializeMember(name + valueName, value, rules.value, fn); }); } function serializeList(name, list, rules, fn) { var memberRules = rules.member || {}; if (list.length === 0) { fn.call(this, name, null); return; } util.arrayEach(list, function (v, n) { var suffix = '.' + (n + 1); if (rules.api.protocol === 'ec2') { // Do nothing for EC2 suffix = suffix + ''; // make linter happy } else if (rules.flattened) { if (memberRules.name) { var parts = name.split('.'); parts.pop(); parts.push(ucfirst(memberRules)); name = parts.join('.'); } } else { suffix = '.' + (memberRules.name ? memberRules.name : 'member') + suffix; } serializeMember(name + suffix, v, memberRules, fn); }); } function serializeMember(name, value, rules, fn) { if (value === null || value === undefined) return; if (rules.type === 'structure') { serializeStructure(name, value, rules, fn); } else if (rules.type === 'list') { serializeList(name, value, rules, fn); } else if (rules.type === 'map') { serializeMap(name, value, rules, fn); } else { fn(name, rules.toWireFormat(value).toString()); } } module.exports = QueryParamSerializer; /***/ }), /***/ "../../../../aws-sdk/lib/region_config.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var regionConfig = __webpack_require__("../../../../aws-sdk/lib/region_config_data.json"); function generateRegionPrefix(region) { if (!region) return null; var parts = region.split('-'); if (parts.length < 3) return null; return parts.slice(0, parts.length - 2).join('-') + '-*'; } function derivedKeys(service) { var region = service.config.region; var regionPrefix = generateRegionPrefix(region); var endpointPrefix = service.api.endpointPrefix; return [ [region, endpointPrefix], [regionPrefix, endpointPrefix], [region, '*'], [regionPrefix, '*'], ['*', endpointPrefix], ['*', '*'] ].map(function(item) { return item[0] && item[1] ? item.join('/') : null; }); } function applyConfig(service, config) { util.each(config, function(key, value) { if (key === 'globalEndpoint') return; if (service.config[key] === undefined || service.config[key] === null) { service.config[key] = value; } }); } function configureEndpoint(service) { var keys = derivedKeys(service); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!key) continue; if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) { var config = regionConfig.rules[key]; if (typeof config === 'string') { config = regionConfig.patterns[config]; } // set dualstack endpoint if (service.config.useDualstack && util.isDualstackAvailable(service)) { config = util.copy(config); config.endpoint = '{service}.dualstack.{region}.amazonaws.com'; } // set global endpoint service.isGlobalEndpoint = !!config.globalEndpoint; // signature version if (!config.signatureVersion) config.signatureVersion = 'v4'; // merge config applyConfig(service, config); return; } } } module.exports = configureEndpoint; /***/ }), /***/ "../../../../aws-sdk/lib/region_config_data.json": /***/ (function(module, exports) { module.exports = {"rules":{"*/*":{"endpoint":"{service}.{region}.amazonaws.com"},"cn-*/*":{"endpoint":"{service}.{region}.amazonaws.com.cn"},"*/budgets":"globalSSL","*/cloudfront":"globalSSL","*/iam":"globalSSL","*/sts":"globalSSL","*/importexport":{"endpoint":"{service}.amazonaws.com","signatureVersion":"v2","globalEndpoint":true},"*/route53":{"endpoint":"https://{service}.amazonaws.com","signatureVersion":"v3https","globalEndpoint":true},"*/waf":"globalSSL","us-gov-*/iam":"globalGovCloud","us-gov-*/sts":{"endpoint":"{service}.{region}.amazonaws.com"},"us-gov-west-1/s3":"s3dash","us-west-1/s3":"s3dash","us-west-2/s3":"s3dash","eu-west-1/s3":"s3dash","ap-southeast-1/s3":"s3dash","ap-southeast-2/s3":"s3dash","ap-northeast-1/s3":"s3dash","sa-east-1/s3":"s3dash","us-east-1/s3":{"endpoint":"{service}.amazonaws.com","signatureVersion":"s3"},"us-east-1/sdb":{"endpoint":"{service}.amazonaws.com","signatureVersion":"v2"},"*/sdb":{"endpoint":"{service}.{region}.amazonaws.com","signatureVersion":"v2"}},"patterns":{"globalSSL":{"endpoint":"https://{service}.amazonaws.com","globalEndpoint":true},"globalGovCloud":{"endpoint":"{service}.us-gov.amazonaws.com"},"s3dash":{"endpoint":"{service}-{region}.amazonaws.com","signatureVersion":"s3"}}} /***/ }), /***/ "../../../../aws-sdk/lib/request.js": /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var AcceptorStateMachine = __webpack_require__("../../../../aws-sdk/lib/state_machine.js"); var inherit = AWS.util.inherit; var domain = AWS.util.domain; var jmespath = __webpack_require__("../../../../jmespath/jmespath.js"); /** * @api private */ var hardErrorStates = {success: 1, error: 1, complete: 1}; function isTerminalState(machine) { return Object.prototype.hasOwnProperty.call(hardErrorStates, machine._asm.currentState); } var fsm = new AcceptorStateMachine(); fsm.setupStates = function() { var transition = function(_, done) { var self = this; self._haltHandlersOnError = false; self.emit(self._asm.currentState, function(err) { if (err) { if (isTerminalState(self)) { if (domain && self.domain instanceof domain.Domain) { err.domainEmitter = self; err.domain = self.domain; err.domainThrown = false; self.domain.emit('error', err); } else { throw err; } } else { self.response.error = err; done(err); } } else { done(self.response.error); } }); }; this.addState('validate', 'build', 'error', transition); this.addState('build', 'afterBuild', 'restart', transition); this.addState('afterBuild', 'sign', 'restart', transition); this.addState('sign', 'send', 'retry', transition); this.addState('retry', 'afterRetry', 'afterRetry', transition); this.addState('afterRetry', 'sign', 'error', transition); this.addState('send', 'validateResponse', 'retry', transition); this.addState('validateResponse', 'extractData', 'extractError', transition); this.addState('extractError', 'extractData', 'retry', transition); this.addState('extractData', 'success', 'retry', transition); this.addState('restart', 'build', 'error', transition); this.addState('success', 'complete', 'complete', transition); this.addState('error', 'complete', 'complete', transition); this.addState('complete', null, null, transition); }; fsm.setupStates(); /** * ## Asynchronous Requests * * All requests made through the SDK are asynchronous and use a * callback interface. Each service method that kicks off a request * returns an `AWS.Request` object that you can use to register * callbacks. * * For example, the following service method returns the request * object as "request", which can be used to register callbacks: * * ```javascript * // request is an AWS.Request object * var request = ec2.describeInstances(); * * // register callbacks on request to retrieve response data * request.on('success', function(response) { * console.log(response.data); * }); * ``` * * When a request is ready to be sent, the {send} method should * be called: * * ```javascript * request.send(); * ``` * * Since registered callbacks may or may not be idempotent, requests should only * be sent once. To perform the same operation multiple times, you will need to * create multiple request objects, each with its own registered callbacks. * * ## Removing Default Listeners for Events * * Request objects are built with default listeners for the various events, * depending on the service type. In some cases, you may want to remove * some built-in listeners to customize behaviour. Doing this requires * access to the built-in listener functions, which are exposed through * the {AWS.EventListeners.Core} namespace. For instance, you may * want to customize the HTTP handler used when sending a request. In this * case, you can remove the built-in listener associated with the 'send' * event, the {AWS.EventListeners.Core.SEND} listener and add your own. * * ## Multiple Callbacks and Chaining * * You can register multiple callbacks on any request object. The * callbacks can be registered for different events, or all for the * same event. In addition, you can chain callback registration, for * example: * * ```javascript * request. * on('success', function(response) { * console.log("Success!"); * }). * on('error', function(response) { * console.log("Error!"); * }). * on('complete', function(response) { * console.log("Always!"); * }). * send(); * ``` * * The above example will print either "Success! Always!", or "Error! Always!", * depending on whether the request succeeded or not. * * @!attribute httpRequest * @readonly * @!group HTTP Properties * @return [AWS.HttpRequest] the raw HTTP request object * containing request headers and body information * sent by the service. * * @!attribute startTime * @readonly * @!group Operation Properties * @return [Date] the time that the request started * * @!group Request Building Events * * @!event validate(request) * Triggered when a request is being validated. Listeners * should throw an error if the request should not be sent. * @param request [Request] the request object being sent * @see AWS.EventListeners.Core.VALIDATE_CREDENTIALS * @see AWS.EventListeners.Core.VALIDATE_REGION * @example Ensuring that a certain parameter is set before sending a request * var req = s3.putObject(params); * req.on('validate', function() { * if (!req.params.Body.match(/^Hello\s/)) { * throw new Error('Body must start with "Hello "'); * } * }); * req.send(function(err, data) { ... }); * * @!event build(request) * Triggered when the request payload is being built. Listeners * should fill the necessary information to send the request * over HTTP. * @param (see AWS.Request~validate) * @example Add a custom HTTP header to a request * var req = s3.putObject(params); * req.on('build', function() { * req.httpRequest.headers['Custom-Header'] = 'value'; * }); * req.send(function(err, data) { ... }); * * @!event sign(request) * Triggered when the request is being signed. Listeners should * add the correct authentication headers and/or adjust the body, * depending on the authentication mechanism being used. * @param (see AWS.Request~validate) * * @!group Request Sending Events * * @!event send(response) * Triggered when the request is ready to be sent. Listeners * should call the underlying transport layer to initiate * the sending of the request. * @param response [Response] the response object * @context [Request] the request object that was sent * @see AWS.EventListeners.Core.SEND * * @!event retry(response) * Triggered when a request failed and might need to be retried or redirected. * If the response is retryable, the listener should set the * `response.error.retryable` property to `true`, and optionally set * `response.error.retryDelay` to the millisecond delay for the next attempt. * In the case of a redirect, `response.error.redirect` should be set to * `true` with `retryDelay` set to an optional delay on the next request. * * If a listener decides that a request should not be retried, * it should set both `retryable` and `redirect` to false. * * Note that a retryable error will be retried at most * {AWS.Config.maxRetries} times (based on the service object's config). * Similarly, a request that is redirected will only redirect at most * {AWS.Config.maxRedirects} times. * * @param (see AWS.Request~send) * @context (see AWS.Request~send) * @example Adding a custom retry for a 404 response * request.on('retry', function(response) { * // this resource is not yet available, wait 10 seconds to get it again * if (response.httpResponse.statusCode === 404 && response.error) { * response.error.retryable = true; // retry this error * response.error.retryDelay = 10000; // wait 10 seconds * } * }); * * @!group Data Parsing Events * * @!event extractError(response) * Triggered on all non-2xx requests so that listeners can extract * error details from the response body. Listeners to this event * should set the `response.error` property. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @!event extractData(response) * Triggered in successful requests to allow listeners to * de-serialize the response body into `response.data`. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @!group Completion Events * * @!event success(response) * Triggered when the request completed successfully. * `response.data` will contain the response data and * `response.error` will be null. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @!event error(error, response) * Triggered when an error occurs at any point during the * request. `response.error` will contain details about the error * that occurred. `response.data` will be null. * @param error [Error] the error object containing details about * the error that occurred. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @!event complete(response) * Triggered whenever a request cycle completes. `response.error` * should be checked, since the request may have failed. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @!group HTTP Events * * @!event httpHeaders(statusCode, headers, response, statusMessage) * Triggered when headers are sent by the remote server * @param statusCode [Integer] the HTTP response code * @param headers [map] the response headers * @param (see AWS.Request~send) * @param statusMessage [String] A status message corresponding to the HTTP * response code * @context (see AWS.Request~send) * * @!event httpData(chunk, response) * Triggered when data is sent by the remote server * @param chunk [Buffer] the buffer data containing the next data chunk * from the server * @param (see AWS.Request~send) * @context (see AWS.Request~send) * @see AWS.EventListeners.Core.HTTP_DATA * * @!event httpUploadProgress(progress, response) * Triggered when the HTTP request has uploaded more data * @param progress [map] An object containing the `loaded` and `total` bytes * of the request. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * @note This event will not be emitted in Node.js 0.8.x. * * @!event httpDownloadProgress(progress, response) * Triggered when the HTTP request has downloaded more data * @param progress [map] An object containing the `loaded` and `total` bytes * of the request. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * @note This event will not be emitted in Node.js 0.8.x. * * @!event httpError(error, response) * Triggered when the HTTP request failed * @param error [Error] the error object that was thrown * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @!event httpDone(response) * Triggered when the server is finished sending data * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @see AWS.Response */ AWS.Request = inherit({ /** * Creates a request for an operation on a given service with * a set of input parameters. * * @param service [AWS.Service] the service to perform the operation on * @param operation [String] the operation to perform on the service * @param params [Object] parameters to send to the operation. * See the operation's documentation for the format of the * parameters. */ constructor: function Request(service, operation, params) { var endpoint = service.endpoint; var region = service.config.region; var customUserAgent = service.config.customUserAgent; // global endpoints sign as us-east-1 if (service.isGlobalEndpoint) region = 'us-east-1'; this.domain = domain && domain.active; this.service = service; this.operation = operation; this.params = params || {}; this.httpRequest = new AWS.HttpRequest(endpoint, region); this.httpRequest.appendToUserAgent(customUserAgent); this.startTime = AWS.util.date.getDate(); this.response = new AWS.Response(this); this._asm = new AcceptorStateMachine(fsm.states, 'validate'); this._haltHandlersOnError = false; AWS.SequentialExecutor.call(this); this.emit = this.emitEvent; }, /** * @!group Sending a Request */ /** * @overload send(callback = null) * Sends the request object. * * @callback callback function(err, data) * If a callback is supplied, it is called when a response is returned * from the service. * @context [AWS.Request] the request object being sent. * @param err [Error] the error object returned from the request. * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. * @example Sending a request with a callback * request = s3.putObject({Bucket: 'bucket', Key: 'key'}); * request.send(function(err, data) { console.log(err, data); }); * @example Sending a request with no callback (using event handlers) * request = s3.putObject({Bucket: 'bucket', Key: 'key'}); * request.on('complete', function(response) { ... }); // register a callback * request.send(); */ send: function send(callback) { if (callback) { // append to user agent this.httpRequest.appendToUserAgent('callback'); this.on('complete', function (resp) { callback.call(resp, resp.error, resp.data); }); } this.runTo(); return this.response; }, /** * @!method promise() * Sends the request and returns a 'thenable' promise. * * Two callbacks can be provided to the `then` method on the returned promise. * The first callback will be called if the promise is fulfilled, and the second * callback will be called if the promise is rejected. * @callback fulfilledCallback function(data) * Called if the promise is fulfilled. * @param data [Object] the de-serialized data returned from the request. * @callback rejectedCallback function(error) * Called if the promise is rejected. * @param error [Error] the error object returned from the request. * @return [Promise] A promise that represents the state of the request. * @example Sending a request using promises. * var request = s3.putObject({Bucket: 'bucket', Key: 'key'}); * var result = request.promise(); * result.then(function(data) { ... }, function(error) { ... }); */ /** * @api private */ build: function build(callback) { return this.runTo('send', callback); }, /** * @api private */ runTo: function runTo(state, done) { this._asm.runTo(state, done, this); return this; }, /** * Aborts a request, emitting the error and complete events. * * @!macro nobrowser * @example Aborting a request after sending * var params = { * Bucket: 'bucket', Key: 'key', * Body: new Buffer(1024 * 1024 * 5) // 5MB payload * }; * var request = s3.putObject(params); * request.send(function (err, data) { * if (err) console.log("Error:", err.code, err.message); * else console.log(data); * }); * * // abort request in 1 second * setTimeout(request.abort.bind(request), 1000); * * // prints "Error: RequestAbortedError Request aborted by user" * @return [AWS.Request] the same request object, for chaining. * @since v1.4.0 */ abort: function abort() { this.removeAllListeners('validateResponse'); this.removeAllListeners('extractError'); this.on('validateResponse', function addAbortedError(resp) { resp.error = AWS.util.error(new Error('Request aborted by user'), { code: 'RequestAbortedError', retryable: false }); }); if (this.httpRequest.stream && !this.httpRequest.stream.didCallback) { // abort HTTP stream this.httpRequest.stream.abort(); if (this.httpRequest._abortCallback) { this.httpRequest._abortCallback(); } else { this.removeAllListeners('send'); // haven't sent yet, so let's not } } return this; }, /** * Iterates over each page of results given a pageable request, calling * the provided callback with each page of data. After all pages have been * retrieved, the callback is called with `null` data. * * @note This operation can generate multiple requests to a service. * @example Iterating over multiple pages of objects in an S3 bucket * var pages = 1; * s3.listObjects().eachPage(function(err, data) { * if (err) return; * console.log("Page", pages++); * console.log(data); * }); * @example Iterating over multiple pages with an asynchronous callback * s3.listObjects(params).eachPage(function(err, data, done) { * doSomethingAsyncAndOrExpensive(function() { * // The next page of results isn't fetched until done is called * done(); * }); * }); * @callback callback function(err, data, [doneCallback]) * Called with each page of resulting data from the request. If the * optional `doneCallback` is provided in the function, it must be called * when the callback is complete. * * @param err [Error] an error object, if an error occurred. * @param data [Object] a single page of response data. If there is no * more data, this object will be `null`. * @param doneCallback [Function] an optional done callback. If this * argument is defined in the function declaration, it should be called * when the next page is ready to be retrieved. This is useful for * controlling serial pagination across asynchronous operations. * @return [Boolean] if the callback returns `false`, pagination will * stop. * * @see AWS.Request.eachItem * @see AWS.Response.nextPage * @since v1.4.0 */ eachPage: function eachPage(callback) { // Make all callbacks async-ish callback = AWS.util.fn.makeAsync(callback, 3); function wrappedCallback(response) { callback.call(response, response.error, response.data, function (result) { if (result === false) return; if (response.hasNextPage()) { response.nextPage().on('complete', wrappedCallback).send(); } else { callback.call(response, null, null, AWS.util.fn.noop); } }); } this.on('complete', wrappedCallback).send(); }, /** * Enumerates over individual items of a request, paging the responses if * necessary. * * @api experimental * @since v1.4.0 */ eachItem: function eachItem(callback) { var self = this; function wrappedCallback(err, data) { if (err) return callback(err, null); if (data === null) return callback(null, null); var config = self.service.paginationConfig(self.operation); var resultKey = config.resultKey; if (Array.isArray(resultKey)) resultKey = resultKey[0]; var items = jmespath.search(data, resultKey); var continueIteration = true; AWS.util.arrayEach(items, function(item) { continueIteration = callback(null, item); if (continueIteration === false) { return AWS.util.abort; } }); return continueIteration; } this.eachPage(wrappedCallback); }, /** * @return [Boolean] whether the operation can return multiple pages of * response data. * @see AWS.Response.eachPage * @since v1.4.0 */ isPageable: function isPageable() { return this.service.paginationConfig(this.operation) ? true : false; }, /** * Sends the request and converts the request object into a readable stream * that can be read from or piped into a writable stream. * * @note The data read from a readable stream contains only * the raw HTTP body contents. * @example Manually reading from a stream * request.createReadStream().on('data', function(data) { * console.log("Got data:", data.toString()); * }); * @example Piping a request body into a file * var out = fs.createWriteStream('/path/to/outfile.jpg'); * s3.service.getObject(params).createReadStream().pipe(out); * @return [Stream] the readable stream object that can be piped * or read from (by registering 'data' event listeners). * @!macro nobrowser */ createReadStream: function createReadStream() { var streams = AWS.util.stream; var req = this; var stream = null; if (AWS.HttpClient.streamsApiVersion === 2) { stream = new streams.PassThrough(); process.nextTick(function() { req.send(); }); } else { stream = new streams.Stream(); stream.readable = true; stream.sent = false; stream.on('newListener', function(event) { if (!stream.sent && event === 'data') { stream.sent = true; process.nextTick(function() { req.send(); }); } }); } this.on('error', function(err) { stream.emit('error', err); }); this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) { if (statusCode < 300) { req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA); req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR); req.on('httpError', function streamHttpError(error) { resp.error = error; resp.error.retryable = false; }); var shouldCheckContentLength = false; var expectedLen; if (req.httpRequest.method !== 'HEAD') { expectedLen = parseInt(headers['content-length'], 10); } if (expectedLen !== undefined && !isNaN(expectedLen) && expectedLen >= 0) { shouldCheckContentLength = true; var receivedLen = 0; } var checkContentLengthAndEmit = function checkContentLengthAndEmit() { if (shouldCheckContentLength && receivedLen !== expectedLen) { stream.emit('error', AWS.util.error( new Error('Stream content length mismatch. Received ' + receivedLen + ' of ' + expectedLen + ' bytes.'), { code: 'StreamContentLengthMismatch' } )); } else if (AWS.HttpClient.streamsApiVersion === 2) { stream.end(); } else { stream.emit('end'); } }; var httpStream = resp.httpResponse.createUnbufferedStream(); if (AWS.HttpClient.streamsApiVersion === 2) { if (shouldCheckContentLength) { var lengthAccumulator = new streams.PassThrough(); lengthAccumulator._write = function(chunk) { if (chunk && chunk.length) { receivedLen += chunk.length; } return streams.PassThrough.prototype._write.apply(this, arguments); }; lengthAccumulator.on('end', checkContentLengthAndEmit); stream.on('error', function(err) { shouldCheckContentLength = false; httpStream.unpipe(lengthAccumulator); lengthAccumulator.emit('end'); lengthAccumulator.end(); }); httpStream.pipe(lengthAccumulator).pipe(stream, { end: false }); } else { httpStream.pipe(stream); } } else { if (shouldCheckContentLength) { httpStream.on('data', function(arg) { if (arg && arg.length) { receivedLen += arg.length; } }); } httpStream.on('data', function(arg) { stream.emit('data', arg); }); httpStream.on('end', checkContentLengthAndEmit); } httpStream.on('error', function(err) { shouldCheckContentLength = false; stream.emit('error', err); }); } }); return stream; }, /** * @param [Array,Response] args This should be the response object, * or an array of args to send to the event. * @api private */ emitEvent: function emit(eventName, args, done) { if (typeof args === 'function') { done = args; args = null; } if (!done) done = function() { }; if (!args) args = this.eventParameters(eventName, this.response); var origEmit = AWS.SequentialExecutor.prototype.emit; origEmit.call(this, eventName, args, function (err) { if (err) this.response.error = err; done.call(this, err); }); }, /** * @api private */ eventParameters: function eventParameters(eventName) { switch (eventName) { case 'restart': case 'validate': case 'sign': case 'build': case 'afterValidate': case 'afterBuild': return [this]; case 'error': return [this.response.error, this.response]; default: return [this.response]; } }, /** * @api private */ presign: function presign(expires, callback) { if (!callback && typeof expires === 'function') { callback = expires; expires = null; } return new AWS.Signers.Presign().sign(this.toGet(), expires, callback); }, /** * @api private */ isPresigned: function isPresigned() { return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires'); }, /** * @api private */ toUnauthenticated: function toUnauthenticated() { this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS); this.removeListener('sign', AWS.EventListeners.Core.SIGN); return this; }, /** * @api private */ toGet: function toGet() { if (this.service.api.protocol === 'query' || this.service.api.protocol === 'ec2') { this.removeListener('build', this.buildAsGet); this.addListener('build', this.buildAsGet); } return this; }, /** * @api private */ buildAsGet: function buildAsGet(request) { request.httpRequest.method = 'GET'; request.httpRequest.path = request.service.endpoint.path + '?' + request.httpRequest.body; request.httpRequest.body = ''; // don't need these headers on a GET request delete request.httpRequest.headers['Content-Length']; delete request.httpRequest.headers['Content-Type']; }, /** * @api private */ haltHandlersOnError: function haltHandlersOnError() { this._haltHandlersOnError = true; } }); /** * @api private */ AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) { this.prototype.promise = function promise() { var self = this; // append to user agent this.httpRequest.appendToUserAgent('promise'); return new PromiseDependency(function(resolve, reject) { self.on('complete', function(resp) { if (resp.error) { reject(resp.error); } else { // define $response property so that it is not enumberable // this prevents circular reference errors when stringifying the JSON object resolve(Object.defineProperty( resp.data || {}, '$response', {value: resp} )); } }); self.runTo(); }); }; }; /** * @api private */ AWS.Request.deletePromisesFromClass = function deletePromisesFromClass() { delete this.prototype.promise; }; AWS.util.addPromises(AWS.Request); AWS.util.mixin(AWS.Request, AWS.SequentialExecutor); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__("../../../../process/browser.js"))) /***/ }), /***/ "../../../../aws-sdk/lib/resource_waiter.js": /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; var jmespath = __webpack_require__("../../../../jmespath/jmespath.js"); /** * @api private */ function CHECK_ACCEPTORS(resp) { var waiter = resp.request._waiter; var acceptors = waiter.config.acceptors; var acceptorMatched = false; var state = 'retry'; acceptors.forEach(function(acceptor) { if (!acceptorMatched) { var matcher = waiter.matchers[acceptor.matcher]; if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) { acceptorMatched = true; state = acceptor.state; } } }); if (!acceptorMatched && resp.error) state = 'failure'; if (state === 'success') { waiter.setSuccess(resp); } else { waiter.setError(resp, state === 'retry'); } } /** * @api private */ AWS.ResourceWaiter = inherit({ /** * Waits for a given state on a service object * @param service [Service] the service object to wait on * @param state [String] the state (defined in waiter configuration) to wait * for. * @example Create a waiter for running EC2 instances * var ec2 = new AWS.EC2; * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning'); */ constructor: function constructor(service, state) { this.service = service; this.state = state; this.loadWaiterConfig(this.state); }, service: null, state: null, config: null, matchers: { path: function(resp, expected, argument) { try { var result = jmespath.search(resp.data, argument); } catch (err) { return false; } return jmespath.strictDeepEqual(result,expected); }, pathAll: function(resp, expected, argument) { try { var results = jmespath.search(resp.data, argument); } catch (err) { return false; } if (!Array.isArray(results)) results = [results]; var numResults = results.length; if (!numResults) return false; for (var ind = 0 ; ind < numResults; ind++) { if (!jmespath.strictDeepEqual(results[ind], expected)) { return false; } } return true; }, pathAny: function(resp, expected, argument) { try { var results = jmespath.search(resp.data, argument); } catch (err) { return false; } if (!Array.isArray(results)) results = [results]; var numResults = results.length; for (var ind = 0 ; ind < numResults; ind++) { if (jmespath.strictDeepEqual(results[ind], expected)) { return true; } } return false; }, status: function(resp, expected) { var statusCode = resp.httpResponse.statusCode; return (typeof statusCode === 'number') && (statusCode === expected); }, error: function(resp, expected) { if (typeof expected === 'string' && resp.error) { return expected === resp.error.code; } // if expected is not string, can be boolean indicating presence of error return expected === !!resp.error; } }, listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) { add('RETRY_CHECK', 'retry', function(resp) { var waiter = resp.request._waiter; if (resp.error && resp.error.code === 'ResourceNotReady') { resp.error.retryDelay = (waiter.config.delay || 0) * 1000; } }); add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS); add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS); }), /** * @return [AWS.Request] */ wait: function wait(params, callback) { if (typeof params === 'function') { callback = params; params = undefined; } if (params && params.$waiter) { params = AWS.util.copy(params); if (typeof params.$waiter.delay === 'number') { this.config.delay = params.$waiter.delay; } if (typeof params.$waiter.maxAttempts === 'number') { this.config.maxAttempts = params.$waiter.maxAttempts; } delete params.$waiter; } var request = this.service.makeRequest(this.config.operation, params); request._waiter = this; request.response.maxRetries = this.config.maxAttempts; request.addListeners(this.listeners); if (callback) request.send(callback); return request; }, setSuccess: function setSuccess(resp) { resp.error = null; resp.data = resp.data || {}; resp.request.removeAllListeners('extractData'); }, setError: function setError(resp, retryable) { resp.data = null; resp.error = AWS.util.error(resp.error || new Error(), { code: 'ResourceNotReady', message: 'Resource is not in the state ' + this.state, retryable: retryable }); }, /** * Loads waiter configuration from API configuration * * @api private */ loadWaiterConfig: function loadWaiterConfig(state) { if (!this.service.api.waiters[state]) { throw new AWS.util.error(new Error(), { code: 'StateNotFoundError', message: 'State ' + state + ' not found.' }); } this.config = AWS.util.copy(this.service.api.waiters[state]); } }); /***/ }), /***/ "../../../../aws-sdk/lib/response.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; var jmespath = __webpack_require__("../../../../jmespath/jmespath.js"); /** * This class encapsulates the response information * from a service request operation sent through {AWS.Request}. * The response object has two main properties for getting information * back from a request: * * ## The `data` property * * The `response.data` property contains the serialized object data * retrieved from the service request. For instance, for an * Amazon DynamoDB `listTables` method call, the response data might * look like: * * ``` * > resp.data * { TableNames: * [ 'table1', 'table2', ... ] } * ``` * * The `data` property can be null if an error occurs (see below). * * ## The `error` property * * In the event of a service error (or transfer error), the * `response.error` property will be filled with the given * error data in the form: * * ``` * { code: 'SHORT_UNIQUE_ERROR_CODE', * message: 'Some human readable error message' } * ``` * * In the case of an error, the `data` property will be `null`. * Note that if you handle events that can be in a failure state, * you should always check whether `response.error` is set * before attempting to access the `response.data` property. * * @!attribute data * @readonly * @!group Data Properties * @note Inside of a {AWS.Request~httpData} event, this * property contains a single raw packet instead of the * full de-serialized service response. * @return [Object] the de-serialized response data * from the service. * * @!attribute error * An structure containing information about a service * or networking error. * @readonly * @!group Data Properties * @note This attribute is only filled if a service or * networking error occurs. * @return [Error] * * code [String] a unique short code representing the * error that was emitted. * * message [String] a longer human readable error message * * retryable [Boolean] whether the error message is * retryable. * * statusCode [Numeric] in the case of a request that reached the service, * this value contains the response status code. * * time [Date] the date time object when the error occurred. * * hostname [String] set when a networking error occurs to easily * identify the endpoint of the request. * * region [String] set when a networking error occurs to easily * identify the region of the request. * * @!attribute requestId * @readonly * @!group Data Properties * @return [String] the unique request ID associated with the response. * Log this value when debugging requests for AWS support. * * @!attribute retryCount * @readonly * @!group Operation Properties * @return [Integer] the number of retries that were * attempted before the request was completed. * * @!attribute redirectCount * @readonly * @!group Operation Properties * @return [Integer] the number of redirects that were * followed before the request was completed. * * @!attribute httpResponse * @readonly * @!group HTTP Properties * @return [AWS.HttpResponse] the raw HTTP response object * containing the response headers and body information * from the server. * * @see AWS.Request */ AWS.Response = inherit({ /** * @api private */ constructor: function Response(request) { this.request = request; this.data = null; this.error = null; this.retryCount = 0; this.redirectCount = 0; this.httpResponse = new AWS.HttpResponse(); if (request) { this.maxRetries = request.service.numRetries(); this.maxRedirects = request.service.config.maxRedirects; } }, /** * Creates a new request for the next page of response data, calling the * callback with the page data if a callback is provided. * * @callback callback function(err, data) * Called when a page of data is returned from the next request. * * @param err [Error] an error object, if an error occurred in the request * @param data [Object] the next page of data, or null, if there are no * more pages left. * @return [AWS.Request] the request object for the next page of data * @return [null] if no callback is provided and there are no pages left * to retrieve. * @since v1.4.0 */ nextPage: function nextPage(callback) { var config; var service = this.request.service; var operation = this.request.operation; try { config = service.paginationConfig(operation, true); } catch (e) { this.error = e; } if (!this.hasNextPage()) { if (callback) callback(this.error, null); else if (this.error) throw this.error; return null; } var params = AWS.util.copy(this.request.params); if (!this.nextPageTokens) { return callback ? callback(null, null) : null; } else { var inputTokens = config.inputToken; if (typeof inputTokens === 'string') inputTokens = [inputTokens]; for (var i = 0; i < inputTokens.length; i++) { params[inputTokens[i]] = this.nextPageTokens[i]; } return service.makeRequest(this.request.operation, params, callback); } }, /** * @return [Boolean] whether more pages of data can be returned by further * requests * @since v1.4.0 */ hasNextPage: function hasNextPage() { this.cacheNextPageTokens(); if (this.nextPageTokens) return true; if (this.nextPageTokens === undefined) return undefined; else return false; }, /** * @api private */ cacheNextPageTokens: function cacheNextPageTokens() { if (Object.prototype.hasOwnProperty.call(this, 'nextPageTokens')) return this.nextPageTokens; this.nextPageTokens = undefined; var config = this.request.service.paginationConfig(this.request.operation); if (!config) return this.nextPageTokens; this.nextPageTokens = null; if (config.moreResults) { if (!jmespath.search(this.data, config.moreResults)) { return this.nextPageTokens; } } var exprs = config.outputToken; if (typeof exprs === 'string') exprs = [exprs]; AWS.util.arrayEach.call(this, exprs, function (expr) { var output = jmespath.search(this.data, expr); if (output) { this.nextPageTokens = this.nextPageTokens || []; this.nextPageTokens.push(output); } }); return this.nextPageTokens; } }); /***/ }), /***/ "../../../../aws-sdk/lib/sequential_executor.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); /** * @api private * @!method on(eventName, callback) * Registers an event listener callback for the event given by `eventName`. * Parameters passed to the callback function depend on the individual event * being triggered. See the event documentation for those parameters. * * @param eventName [String] the event name to register the listener for * @param callback [Function] the listener callback function * @return [AWS.SequentialExecutor] the same object for chaining */ AWS.SequentialExecutor = AWS.util.inherit({ constructor: function SequentialExecutor() { this._events = {}; }, /** * @api private */ listeners: function listeners(eventName) { return this._events[eventName] ? this._events[eventName].slice(0) : []; }, on: function on(eventName, listener) { if (this._events[eventName]) { this._events[eventName].push(listener); } else { this._events[eventName] = [listener]; } return this; }, /** * @api private */ onAsync: function onAsync(eventName, listener) { listener._isAsync = true; return this.on(eventName, listener); }, removeListener: function removeListener(eventName, listener) { var listeners = this._events[eventName]; if (listeners) { var length = listeners.length; var position = -1; for (var i = 0; i < length; ++i) { if (listeners[i] === listener) { position = i; } } if (position > -1) { listeners.splice(position, 1); } } return this; }, removeAllListeners: function removeAllListeners(eventName) { if (eventName) { delete this._events[eventName]; } else { this._events = {}; } return this; }, /** * @api private */ emit: function emit(eventName, eventArgs, doneCallback) { if (!doneCallback) doneCallback = function() { }; var listeners = this.listeners(eventName); var count = listeners.length; this.callListeners(listeners, eventArgs, doneCallback); return count > 0; }, /** * @api private */ callListeners: function callListeners(listeners, args, doneCallback, prevError) { var self = this; var error = prevError || null; function callNextListener(err) { if (err) { error = AWS.util.error(error || new Error(), err); if (self._haltHandlersOnError) { return doneCallback.call(self, error); } } self.callListeners(listeners, args, doneCallback, error); } while (listeners.length > 0) { var listener = listeners.shift(); if (listener._isAsync) { // asynchronous listener listener.apply(self, args.concat([callNextListener])); return; // stop here, callNextListener will continue } else { // synchronous listener try { listener.apply(self, args); } catch (err) { error = AWS.util.error(error || new Error(), err); } if (error && self._haltHandlersOnError) { doneCallback.call(self, error); return; } } } doneCallback.call(self, error); }, /** * Adds or copies a set of listeners from another list of * listeners or SequentialExecutor object. * * @param listeners [map>, AWS.SequentialExecutor] * a list of events and callbacks, or an event emitter object * containing listeners to add to this emitter object. * @return [AWS.SequentialExecutor] the emitter object, for chaining. * @example Adding listeners from a map of listeners * emitter.addListeners({ * event1: [function() { ... }, function() { ... }], * event2: [function() { ... }] * }); * emitter.emit('event1'); // emitter has event1 * emitter.emit('event2'); // emitter has event2 * @example Adding listeners from another emitter object * var emitter1 = new AWS.SequentialExecutor(); * emitter1.on('event1', function() { ... }); * emitter1.on('event2', function() { ... }); * var emitter2 = new AWS.SequentialExecutor(); * emitter2.addListeners(emitter1); * emitter2.emit('event1'); // emitter2 has event1 * emitter2.emit('event2'); // emitter2 has event2 */ addListeners: function addListeners(listeners) { var self = this; // extract listeners if parameter is an SequentialExecutor object if (listeners._events) listeners = listeners._events; AWS.util.each(listeners, function(event, callbacks) { if (typeof callbacks === 'function') callbacks = [callbacks]; AWS.util.arrayEach(callbacks, function(callback) { self.on(event, callback); }); }); return self; }, /** * Registers an event with {on} and saves the callback handle function * as a property on the emitter object using a given `name`. * * @param name [String] the property name to set on this object containing * the callback function handle so that the listener can be removed in * the future. * @param (see on) * @return (see on) * @example Adding a named listener DATA_CALLBACK * var listener = function() { doSomething(); }; * emitter.addNamedListener('DATA_CALLBACK', 'data', listener); * * // the following prints: true * console.log(emitter.DATA_CALLBACK == listener); */ addNamedListener: function addNamedListener(name, eventName, callback) { this[name] = callback; this.addListener(eventName, callback); return this; }, /** * @api private */ addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback) { callback._isAsync = true; return this.addNamedListener(name, eventName, callback); }, /** * Helper method to add a set of named listeners using * {addNamedListener}. The callback contains a parameter * with a handle to the `addNamedListener` method. * * @callback callback function(add) * The callback function is called immediately in order to provide * the `add` function to the block. This simplifies the addition of * a large group of named listeners. * @param add [Function] the {addNamedListener} function to call * when registering listeners. * @example Adding a set of named listeners * emitter.addNamedListeners(function(add) { * add('DATA_CALLBACK', 'data', function() { ... }); * add('OTHER', 'otherEvent', function() { ... }); * add('LAST', 'lastEvent', function() { ... }); * }); * * // these properties are now set: * emitter.DATA_CALLBACK; * emitter.OTHER; * emitter.LAST; */ addNamedListeners: function addNamedListeners(callback) { var self = this; callback( function() { self.addNamedListener.apply(self, arguments); }, function() { self.addNamedAsyncListener.apply(self, arguments); } ); return this; } }); /** * {on} is the prefered method. * @api private */ AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on; module.exports = AWS.SequentialExecutor; /***/ }), /***/ "../../../../aws-sdk/lib/service.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var Api = __webpack_require__("../../../../aws-sdk/lib/model/api.js"); var regionConfig = __webpack_require__("../../../../aws-sdk/lib/region_config.js"); var inherit = AWS.util.inherit; var clientCount = 0; /** * The service class representing an AWS service. * * @abstract * * @!attribute apiVersions * @return [Array] the list of API versions supported by this service. * @readonly */ AWS.Service = inherit({ /** * Create a new service object with a configuration object * * @param config [map] a map of configuration options */ constructor: function Service(config) { if (!this.loadServiceClass) { throw AWS.util.error(new Error(), 'Service must be constructed with `new\' operator'); } var ServiceClass = this.loadServiceClass(config || {}); if (ServiceClass) { var originalConfig = AWS.util.copy(config); var svc = new ServiceClass(config); Object.defineProperty(svc, '_originalConfig', { get: function() { return originalConfig; }, enumerable: false, configurable: true }); svc._clientId = ++clientCount; return svc; } this.initialize(config); }, /** * @api private */ initialize: function initialize(config) { var svcConfig = AWS.config[this.serviceIdentifier]; this.config = new AWS.Config(AWS.config); if (svcConfig) this.config.update(svcConfig, true); if (config) this.config.update(config, true); this.validateService(); if (!this.config.endpoint) regionConfig(this); this.config.endpoint = this.endpointFromTemplate(this.config.endpoint); this.setEndpoint(this.config.endpoint); }, /** * @api private */ validateService: function validateService() { }, /** * @api private */ loadServiceClass: function loadServiceClass(serviceConfig) { var config = serviceConfig; if (!AWS.util.isEmpty(this.api)) { return null; } else if (config.apiConfig) { return AWS.Service.defineServiceApi(this.constructor, config.apiConfig); } else if (!this.constructor.services) { return null; } else { config = new AWS.Config(AWS.config); config.update(serviceConfig, true); var version = config.apiVersions[this.constructor.serviceIdentifier]; version = version || config.apiVersion; return this.getLatestServiceClass(version); } }, /** * @api private */ getLatestServiceClass: function getLatestServiceClass(version) { version = this.getLatestServiceVersion(version); if (this.constructor.services[version] === null) { AWS.Service.defineServiceApi(this.constructor, version); } return this.constructor.services[version]; }, /** * @api private */ getLatestServiceVersion: function getLatestServiceVersion(version) { if (!this.constructor.services || this.constructor.services.length === 0) { throw new Error('No services defined on ' + this.constructor.serviceIdentifier); } if (!version) { version = 'latest'; } else if (AWS.util.isType(version, Date)) { version = AWS.util.date.iso8601(version).split('T')[0]; } if (Object.hasOwnProperty(this.constructor.services, version)) { return version; } var keys = Object.keys(this.constructor.services).sort(); var selectedVersion = null; for (var i = keys.length - 1; i >= 0; i--) { // versions that end in "*" are not available on disk and can be // skipped, so do not choose these as selectedVersions if (keys[i][keys[i].length - 1] !== '*') { selectedVersion = keys[i]; } if (keys[i].substr(0, 10) <= version) { return selectedVersion; } } throw new Error('Could not find ' + this.constructor.serviceIdentifier + ' API to satisfy version constraint `' + version + '\''); }, /** * @api private */ api: {}, /** * @api private */ defaultRetryCount: 3, /** * @api private */ customizeRequests: function customizeRequests(callback) { if (!callback) { this.customRequestHandler = null; } else if (typeof callback === 'function') { this.customRequestHandler = callback; } else { throw new Error('Invalid callback type \'' + typeof callback + '\' provided in customizeRequests'); } }, /** * Calls an operation on a service with the given input parameters. * * @param operation [String] the name of the operation to call on the service. * @param params [map] a map of input options for the operation * @callback callback function(err, data) * If a callback is supplied, it is called when a response is returned * from the service. * @param err [Error] the error object returned from the request. * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. */ makeRequest: function makeRequest(operation, params, callback) { if (typeof params === 'function') { callback = params; params = null; } params = params || {}; if (this.config.params) { // copy only toplevel bound params var rules = this.api.operations[operation]; if (rules) { params = AWS.util.copy(params); AWS.util.each(this.config.params, function(key, value) { if (rules.input.members[key]) { if (params[key] === undefined || params[key] === null) { params[key] = value; } } }); } } var request = new AWS.Request(this, operation, params); this.addAllRequestListeners(request); if (callback) request.send(callback); return request; }, /** * Calls an operation on a service with the given input parameters, without * any authentication data. This method is useful for "public" API operations. * * @param operation [String] the name of the operation to call on the service. * @param params [map] a map of input options for the operation * @callback callback function(err, data) * If a callback is supplied, it is called when a response is returned * from the service. * @param err [Error] the error object returned from the request. * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. */ makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) { if (typeof params === 'function') { callback = params; params = {}; } var request = this.makeRequest(operation, params).toUnauthenticated(); return callback ? request.send(callback) : request; }, /** * Waits for a given state * * @param state [String] the state on the service to wait for * @param params [map] a map of parameters to pass with each request * @option params $waiter [map] a map of configuration options for the waiter * @option params $waiter.delay [Number] The number of seconds to wait between * requests * @option params $waiter.maxAttempts [Number] The maximum number of requests * to send while waiting * @callback callback function(err, data) * If a callback is supplied, it is called when a response is returned * from the service. * @param err [Error] the error object returned from the request. * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. */ waitFor: function waitFor(state, params, callback) { var waiter = new AWS.ResourceWaiter(this, state); return waiter.wait(params, callback); }, /** * @api private */ addAllRequestListeners: function addAllRequestListeners(request) { var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(), AWS.EventListeners.CorePost]; for (var i = 0; i < list.length; i++) { if (list[i]) request.addListeners(list[i]); } // disable parameter validation if (!this.config.paramValidation) { request.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS); } if (this.config.logger) { // add logging events request.addListeners(AWS.EventListeners.Logger); } this.setupRequestListeners(request); // call prototype's customRequestHandler if (typeof this.constructor.prototype.customRequestHandler === 'function') { this.constructor.prototype.customRequestHandler(request); } // call instance's customRequestHandler if (Object.prototype.hasOwnProperty.call(this, 'customRequestHandler') && typeof this.customRequestHandler === 'function') { this.customRequestHandler(request); } }, /** * Override this method to setup any custom request listeners for each * new request to the service. * * @abstract */ setupRequestListeners: function setupRequestListeners() { }, /** * Gets the signer class for a given request * @api private */ getSignerClass: function getSignerClass(request) { var version; // get operation authtype if present var operation = null; var authtype = ''; if (request) { var operations = request.service.api.operations || {}; operation = operations[request.operation] || null; authtype = operation ? operation.authtype : ''; } if (this.config.signatureVersion) { version = this.config.signatureVersion; } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') { version = 'v4'; } else { version = this.api.signatureVersion; } return AWS.Signers.RequestSigner.getVersion(version); }, /** * @api private */ serviceInterface: function serviceInterface() { switch (this.api.protocol) { case 'ec2': return AWS.EventListeners.Query; case 'query': return AWS.EventListeners.Query; case 'json': return AWS.EventListeners.Json; case 'rest-json': return AWS.EventListeners.RestJson; case 'rest-xml': return AWS.EventListeners.RestXml; } if (this.api.protocol) { throw new Error('Invalid service `protocol\' ' + this.api.protocol + ' in API config'); } }, /** * @api private */ successfulResponse: function successfulResponse(resp) { return resp.httpResponse.statusCode < 300; }, /** * How many times a failed request should be retried before giving up. * the defaultRetryCount can be overriden by service classes. * * @api private */ numRetries: function numRetries() { if (this.config.maxRetries !== undefined) { return this.config.maxRetries; } else { return this.defaultRetryCount; } }, /** * @api private */ retryDelays: function retryDelays(retryCount) { return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions); }, /** * @api private */ retryableError: function retryableError(error) { if (this.timeoutError(error)) return true; if (this.networkingError(error)) return true; if (this.expiredCredentialsError(error)) return true; if (this.throttledError(error)) return true; if (error.statusCode >= 500) return true; return false; }, /** * @api private */ networkingError: function networkingError(error) { return error.code === 'NetworkingError'; }, /** * @api private */ timeoutError: function timeoutError(error) { return error.code === 'TimeoutError'; }, /** * @api private */ expiredCredentialsError: function expiredCredentialsError(error) { // TODO : this only handles *one* of the expired credential codes return (error.code === 'ExpiredTokenException'); }, /** * @api private */ clockSkewError: function clockSkewError(error) { switch (error.code) { case 'RequestTimeTooSkewed': case 'RequestExpired': case 'InvalidSignatureException': case 'SignatureDoesNotMatch': case 'AuthFailure': case 'RequestInTheFuture': return true; default: return false; } }, /** * @api private */ throttledError: function throttledError(error) { // this logic varies between services switch (error.code) { case 'ProvisionedThroughputExceededException': case 'Throttling': case 'ThrottlingException': case 'RequestLimitExceeded': case 'RequestThrottled': return true; default: return false; } }, /** * @api private */ endpointFromTemplate: function endpointFromTemplate(endpoint) { if (typeof endpoint !== 'string') return endpoint; var e = endpoint; e = e.replace(/\{service\}/g, this.api.endpointPrefix); e = e.replace(/\{region\}/g, this.config.region); e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http'); return e; }, /** * @api private */ setEndpoint: function setEndpoint(endpoint) { this.endpoint = new AWS.Endpoint(endpoint, this.config); }, /** * @api private */ paginationConfig: function paginationConfig(operation, throwException) { var paginator = this.api.operations[operation].paginator; if (!paginator) { if (throwException) { var e = new Error(); throw AWS.util.error(e, 'No pagination configuration for ' + operation); } return null; } return paginator; } }); AWS.util.update(AWS.Service, { /** * Adds one method for each operation described in the api configuration * * @api private */ defineMethods: function defineMethods(svc) { AWS.util.each(svc.prototype.api.operations, function iterator(method) { if (svc.prototype[method]) return; var operation = svc.prototype.api.operations[method]; if (operation.authtype === 'none') { svc.prototype[method] = function (params, callback) { return this.makeUnauthenticatedRequest(method, params, callback); }; } else { svc.prototype[method] = function (params, callback) { return this.makeRequest(method, params, callback); }; } }); }, /** * Defines a new Service class using a service identifier and list of versions * including an optional set of features (functions) to apply to the class * prototype. * * @param serviceIdentifier [String] the identifier for the service * @param versions [Array] a list of versions that work with this * service * @param features [Object] an object to attach to the prototype * @return [Class] the service class defined by this function. */ defineService: function defineService(serviceIdentifier, versions, features) { AWS.Service._serviceMap[serviceIdentifier] = true; if (!Array.isArray(versions)) { features = versions; versions = []; } var svc = inherit(AWS.Service, features || {}); if (typeof serviceIdentifier === 'string') { AWS.Service.addVersions(svc, versions); var identifier = svc.serviceIdentifier || serviceIdentifier; svc.serviceIdentifier = identifier; } else { // defineService called with an API svc.prototype.api = serviceIdentifier; AWS.Service.defineMethods(svc); } return svc; }, /** * @api private */ addVersions: function addVersions(svc, versions) { if (!Array.isArray(versions)) versions = [versions]; svc.services = svc.services || {}; for (var i = 0; i < versions.length; i++) { if (svc.services[versions[i]] === undefined) { svc.services[versions[i]] = null; } } svc.apiVersions = Object.keys(svc.services).sort(); }, /** * @api private */ defineServiceApi: function defineServiceApi(superclass, version, apiConfig) { var svc = inherit(superclass, { serviceIdentifier: superclass.serviceIdentifier }); function setApi(api) { if (api.isApi) { svc.prototype.api = api; } else { svc.prototype.api = new Api(api); } } if (typeof version === 'string') { if (apiConfig) { setApi(apiConfig); } else { try { setApi(AWS.apiLoader(superclass.serviceIdentifier, version)); } catch (err) { throw AWS.util.error(err, { message: 'Could not find API configuration ' + superclass.serviceIdentifier + '-' + version }); } } if (!Object.prototype.hasOwnProperty.call(superclass.services, version)) { superclass.apiVersions = superclass.apiVersions.concat(version).sort(); } superclass.services[version] = svc; } else { setApi(version); } AWS.Service.defineMethods(svc); return svc; }, /** * @api private */ hasService: function(identifier) { return Object.prototype.hasOwnProperty.call(AWS.Service._serviceMap, identifier); }, /** * @api private */ _serviceMap: {} }); module.exports = AWS.Service; /***/ }), /***/ "../../../../aws-sdk/lib/services/cognitoidentity.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); AWS.util.update(AWS.CognitoIdentity.prototype, { getOpenIdToken: function getOpenIdToken(params, callback) { return this.makeUnauthenticatedRequest('getOpenIdToken', params, callback); }, getId: function getId(params, callback) { return this.makeUnauthenticatedRequest('getId', params, callback); }, getCredentialsForIdentity: function getCredentialsForIdentity(params, callback) { return this.makeUnauthenticatedRequest('getCredentialsForIdentity', params, callback); } }); /***/ }), /***/ "../../../../aws-sdk/lib/services/sts.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); AWS.util.update(AWS.STS.prototype, { /** * @overload credentialsFrom(data, credentials = null) * Creates a credentials object from STS response data containing * credentials information. Useful for quickly setting AWS credentials. * * @note This is a low-level utility function. If you want to load temporary * credentials into your process for subsequent requests to AWS resources, * you should use {AWS.TemporaryCredentials} instead. * @param data [map] data retrieved from a call to {getFederatedToken}, * {getSessionToken}, {assumeRole}, or {assumeRoleWithWebIdentity}. * @param credentials [AWS.Credentials] an optional credentials object to * fill instead of creating a new object. Useful when modifying an * existing credentials object from a refresh call. * @return [AWS.TemporaryCredentials] the set of temporary credentials * loaded from a raw STS operation response. * @example Using credentialsFrom to load global AWS credentials * var sts = new AWS.STS(); * sts.getSessionToken(function (err, data) { * if (err) console.log("Error getting credentials"); * else { * AWS.config.credentials = sts.credentialsFrom(data); * } * }); * @see AWS.TemporaryCredentials */ credentialsFrom: function credentialsFrom(data, credentials) { if (!data) return null; if (!credentials) credentials = new AWS.TemporaryCredentials(); credentials.expired = false; credentials.accessKeyId = data.Credentials.AccessKeyId; credentials.secretAccessKey = data.Credentials.SecretAccessKey; credentials.sessionToken = data.Credentials.SessionToken; credentials.expireTime = data.Credentials.Expiration; return credentials; }, assumeRoleWithWebIdentity: function assumeRoleWithWebIdentity(params, callback) { return this.makeUnauthenticatedRequest('assumeRoleWithWebIdentity', params, callback); }, assumeRoleWithSAML: function assumeRoleWithSAML(params, callback) { return this.makeUnauthenticatedRequest('assumeRoleWithSAML', params, callback); } }); /***/ }), /***/ "../../../../aws-sdk/lib/signers/presign.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; /** * @api private */ var expiresHeader = 'presigned-expires'; /** * @api private */ function signedUrlBuilder(request) { var expires = request.httpRequest.headers[expiresHeader]; var signerClass = request.service.getSignerClass(request); delete request.httpRequest.headers['User-Agent']; delete request.httpRequest.headers['X-Amz-User-Agent']; if (signerClass === AWS.Signers.V4) { if (expires > 604800) { // one week expiry is invalid var message = 'Presigning does not support expiry time greater ' + 'than a week with SigV4 signing.'; throw AWS.util.error(new Error(), { code: 'InvalidExpiryTime', message: message, retryable: false }); } request.httpRequest.headers[expiresHeader] = expires; } else if (signerClass === AWS.Signers.S3) { request.httpRequest.headers[expiresHeader] = parseInt( AWS.util.date.unixTimestamp() + expires, 10).toString(); } else { throw AWS.util.error(new Error(), { message: 'Presigning only supports S3 or SigV4 signing.', code: 'UnsupportedSigner', retryable: false }); } } /** * @api private */ function signedUrlSigner(request) { var endpoint = request.httpRequest.endpoint; var parsedUrl = AWS.util.urlParse(request.httpRequest.path); var queryParams = {}; if (parsedUrl.search) { queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1)); } AWS.util.each(request.httpRequest.headers, function (key, value) { if (key === expiresHeader) key = 'Expires'; if (key.indexOf('x-amz-meta-') === 0) { // Delete existing, potentially not normalized key delete queryParams[key]; key = key.toLowerCase(); } queryParams[key] = value; }); delete request.httpRequest.headers[expiresHeader]; var auth = queryParams['Authorization'].split(' '); if (auth[0] === 'AWS') { auth = auth[1].split(':'); queryParams['AWSAccessKeyId'] = auth[0]; queryParams['Signature'] = auth[1]; } else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing auth.shift(); var rest = auth.join(' '); var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1]; queryParams['X-Amz-Signature'] = signature; delete queryParams['Expires']; } delete queryParams['Authorization']; delete queryParams['Host']; // build URL endpoint.pathname = parsedUrl.pathname; endpoint.search = AWS.util.queryParamsToString(queryParams); } /** * @api private */ AWS.Signers.Presign = inherit({ /** * @api private */ sign: function sign(request, expireTime, callback) { request.httpRequest.headers[expiresHeader] = expireTime || 3600; request.on('build', signedUrlBuilder); request.on('sign', signedUrlSigner); request.removeListener('afterBuild', AWS.EventListeners.Core.SET_CONTENT_LENGTH); request.removeListener('afterBuild', AWS.EventListeners.Core.COMPUTE_SHA256); request.emit('beforePresign', [request]); if (callback) { request.build(function() { if (this.response.error) callback(this.response.error); else { callback(null, AWS.util.urlFormat(request.httpRequest.endpoint)); } }); } else { request.build(); if (request.response.error) throw request.response.error; return AWS.util.urlFormat(request.httpRequest.endpoint); } } }); module.exports = AWS.Signers.Presign; /***/ }), /***/ "../../../../aws-sdk/lib/signers/request_signer.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; /** * @api private */ AWS.Signers.RequestSigner = inherit({ constructor: function RequestSigner(request) { this.request = request; }, setServiceClientId: function setServiceClientId(id) { this.serviceClientId = id; }, getServiceClientId: function getServiceClientId() { return this.serviceClientId; } }); AWS.Signers.RequestSigner.getVersion = function getVersion(version) { switch (version) { case 'v2': return AWS.Signers.V2; case 'v3': return AWS.Signers.V3; case 'v4': return AWS.Signers.V4; case 's3': return AWS.Signers.S3; case 'v3https': return AWS.Signers.V3Https; } throw new Error('Unknown signing version ' + version); }; __webpack_require__("../../../../aws-sdk/lib/signers/v2.js"); __webpack_require__("../../../../aws-sdk/lib/signers/v3.js"); __webpack_require__("../../../../aws-sdk/lib/signers/v3https.js"); __webpack_require__("../../../../aws-sdk/lib/signers/v4.js"); __webpack_require__("../../../../aws-sdk/lib/signers/s3.js"); __webpack_require__("../../../../aws-sdk/lib/signers/presign.js"); /***/ }), /***/ "../../../../aws-sdk/lib/signers/s3.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; /** * @api private */ AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, { /** * When building the stringToSign, these sub resource params should be * part of the canonical resource string with their NON-decoded values */ subResources: { 'acl': 1, 'accelerate': 1, 'analytics': 1, 'cors': 1, 'lifecycle': 1, 'delete': 1, 'inventory': 1, 'location': 1, 'logging': 1, 'metrics': 1, 'notification': 1, 'partNumber': 1, 'policy': 1, 'requestPayment': 1, 'replication': 1, 'restore': 1, 'tagging': 1, 'torrent': 1, 'uploadId': 1, 'uploads': 1, 'versionId': 1, 'versioning': 1, 'versions': 1, 'website': 1 }, // when building the stringToSign, these querystring params should be // part of the canonical resource string with their NON-encoded values responseHeaders: { 'response-content-type': 1, 'response-content-language': 1, 'response-expires': 1, 'response-cache-control': 1, 'response-content-disposition': 1, 'response-content-encoding': 1 }, addAuthorization: function addAuthorization(credentials, date) { if (!this.request.headers['presigned-expires']) { this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date); } if (credentials.sessionToken) { // presigned URLs require this header to be lowercased this.request.headers['x-amz-security-token'] = credentials.sessionToken; } var signature = this.sign(credentials.secretAccessKey, this.stringToSign()); var auth = 'AWS ' + credentials.accessKeyId + ':' + signature; this.request.headers['Authorization'] = auth; }, stringToSign: function stringToSign() { var r = this.request; var parts = []; parts.push(r.method); parts.push(r.headers['Content-MD5'] || ''); parts.push(r.headers['Content-Type'] || ''); // This is the "Date" header, but we use X-Amz-Date. // The S3 signing mechanism requires us to pass an empty // string for this Date header regardless. parts.push(r.headers['presigned-expires'] || ''); var headers = this.canonicalizedAmzHeaders(); if (headers) parts.push(headers); parts.push(this.canonicalizedResource()); return parts.join('\n'); }, canonicalizedAmzHeaders: function canonicalizedAmzHeaders() { var amzHeaders = []; AWS.util.each(this.request.headers, function (name) { if (name.match(/^x-amz-/i)) amzHeaders.push(name); }); amzHeaders.sort(function (a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; }); var parts = []; AWS.util.arrayEach.call(this, amzHeaders, function (name) { parts.push(name.toLowerCase() + ':' + String(this.request.headers[name])); }); return parts.join('\n'); }, canonicalizedResource: function canonicalizedResource() { var r = this.request; var parts = r.path.split('?'); var path = parts[0]; var querystring = parts[1]; var resource = ''; if (r.virtualHostedBucket) resource += '/' + r.virtualHostedBucket; resource += path; if (querystring) { // collect a list of sub resources and query params that need to be signed var resources = []; AWS.util.arrayEach.call(this, querystring.split('&'), function (param) { var name = param.split('=')[0]; var value = param.split('=')[1]; if (this.subResources[name] || this.responseHeaders[name]) { var subresource = { name: name }; if (value !== undefined) { if (this.subResources[name]) { subresource.value = value; } else { subresource.value = decodeURIComponent(value); } } resources.push(subresource); } }); resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; }); if (resources.length) { querystring = []; AWS.util.arrayEach(resources, function (res) { if (res.value === undefined) { querystring.push(res.name); } else { querystring.push(res.name + '=' + res.value); } }); resource += '?' + querystring.join('&'); } } return resource; }, sign: function sign(secret, string) { return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1'); } }); module.exports = AWS.Signers.S3; /***/ }), /***/ "../../../../aws-sdk/lib/signers/v2.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; /** * @api private */ AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, { addAuthorization: function addAuthorization(credentials, date) { if (!date) date = AWS.util.date.getDate(); var r = this.request; r.params.Timestamp = AWS.util.date.iso8601(date); r.params.SignatureVersion = '2'; r.params.SignatureMethod = 'HmacSHA256'; r.params.AWSAccessKeyId = credentials.accessKeyId; if (credentials.sessionToken) { r.params.SecurityToken = credentials.sessionToken; } delete r.params.Signature; // delete old Signature for re-signing r.params.Signature = this.signature(credentials); r.body = AWS.util.queryParamsToString(r.params); r.headers['Content-Length'] = r.body.length; }, signature: function signature(credentials) { return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64'); }, stringToSign: function stringToSign() { var parts = []; parts.push(this.request.method); parts.push(this.request.endpoint.host.toLowerCase()); parts.push(this.request.pathname()); parts.push(AWS.util.queryParamsToString(this.request.params)); return parts.join('\n'); } }); module.exports = AWS.Signers.V2; /***/ }), /***/ "../../../../aws-sdk/lib/signers/v3.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; /** * @api private */ AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, { addAuthorization: function addAuthorization(credentials, date) { var datetime = AWS.util.date.rfc822(date); this.request.headers['X-Amz-Date'] = datetime; if (credentials.sessionToken) { this.request.headers['x-amz-security-token'] = credentials.sessionToken; } this.request.headers['X-Amzn-Authorization'] = this.authorization(credentials, datetime); }, authorization: function authorization(credentials) { return 'AWS3 ' + 'AWSAccessKeyId=' + credentials.accessKeyId + ',' + 'Algorithm=HmacSHA256,' + 'SignedHeaders=' + this.signedHeaders() + ',' + 'Signature=' + this.signature(credentials); }, signedHeaders: function signedHeaders() { var headers = []; AWS.util.arrayEach(this.headersToSign(), function iterator(h) { headers.push(h.toLowerCase()); }); return headers.sort().join(';'); }, canonicalHeaders: function canonicalHeaders() { var headers = this.request.headers; var parts = []; AWS.util.arrayEach(this.headersToSign(), function iterator(h) { parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim()); }); return parts.sort().join('\n') + '\n'; }, headersToSign: function headersToSign() { var headers = []; AWS.util.each(this.request.headers, function iterator(k) { if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) { headers.push(k); } }); return headers; }, signature: function signature(credentials) { return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64'); }, stringToSign: function stringToSign() { var parts = []; parts.push(this.request.method); parts.push('/'); parts.push(''); parts.push(this.canonicalHeaders()); parts.push(this.request.body); return AWS.util.crypto.sha256(parts.join('\n')); } }); module.exports = AWS.Signers.V3; /***/ }), /***/ "../../../../aws-sdk/lib/signers/v3https.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var inherit = AWS.util.inherit; __webpack_require__("../../../../aws-sdk/lib/signers/v3.js"); /** * @api private */ AWS.Signers.V3Https = inherit(AWS.Signers.V3, { authorization: function authorization(credentials) { return 'AWS3-HTTPS ' + 'AWSAccessKeyId=' + credentials.accessKeyId + ',' + 'Algorithm=HmacSHA256,' + 'Signature=' + this.signature(credentials); }, stringToSign: function stringToSign() { return this.request.headers['X-Amz-Date']; } }); module.exports = AWS.Signers.V3Https; /***/ }), /***/ "../../../../aws-sdk/lib/signers/v4.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); var v4Credentials = __webpack_require__("../../../../aws-sdk/lib/signers/v4_credentials.js"); var inherit = AWS.util.inherit; /** * @api private */ var expiresHeader = 'presigned-expires'; /** * @api private */ AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, { constructor: function V4(request, serviceName, options) { AWS.Signers.RequestSigner.call(this, request); this.serviceName = serviceName; options = options || {}; this.signatureCache = typeof options.signatureCache === 'boolean' ? options.signatureCache : true; this.operation = options.operation; }, algorithm: 'AWS4-HMAC-SHA256', addAuthorization: function addAuthorization(credentials, date) { var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, ''); if (this.isPresigned()) { this.updateForPresigned(credentials, datetime); } else { this.addHeaders(credentials, datetime); } this.request.headers['Authorization'] = this.authorization(credentials, datetime); }, addHeaders: function addHeaders(credentials, datetime) { this.request.headers['X-Amz-Date'] = datetime; if (credentials.sessionToken) { this.request.headers['x-amz-security-token'] = credentials.sessionToken; } }, updateForPresigned: function updateForPresigned(credentials, datetime) { var credString = this.credentialString(datetime); var qs = { 'X-Amz-Date': datetime, 'X-Amz-Algorithm': this.algorithm, 'X-Amz-Credential': credentials.accessKeyId + '/' + credString, 'X-Amz-Expires': this.request.headers[expiresHeader], 'X-Amz-SignedHeaders': this.signedHeaders() }; if (credentials.sessionToken) { qs['X-Amz-Security-Token'] = credentials.sessionToken; } if (this.request.headers['Content-Type']) { qs['Content-Type'] = this.request.headers['Content-Type']; } if (this.request.headers['Content-MD5']) { qs['Content-MD5'] = this.request.headers['Content-MD5']; } if (this.request.headers['Cache-Control']) { qs['Cache-Control'] = this.request.headers['Cache-Control']; } // need to pull in any other X-Amz-* headers AWS.util.each.call(this, this.request.headers, function(key, value) { if (key === expiresHeader) return; if (this.isSignableHeader(key)) { var lowerKey = key.toLowerCase(); // Metadata should be normalized if (lowerKey.indexOf('x-amz-meta-') === 0) { qs[lowerKey] = value; } else if (lowerKey.indexOf('x-amz-') === 0) { qs[key] = value; } } }); var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?'; this.request.path += sep + AWS.util.queryParamsToString(qs); }, authorization: function authorization(credentials, datetime) { var parts = []; var credString = this.credentialString(datetime); parts.push(this.algorithm + ' Credential=' + credentials.accessKeyId + '/' + credString); parts.push('SignedHeaders=' + this.signedHeaders()); parts.push('Signature=' + this.signature(credentials, datetime)); return parts.join(', '); }, signature: function signature(credentials, datetime) { var signingKey = v4Credentials.getSigningKey( credentials, datetime.substr(0, 8), this.request.region, this.serviceName, this.signatureCache ); return AWS.util.crypto.hmac(signingKey, this.stringToSign(datetime), 'hex'); }, stringToSign: function stringToSign(datetime) { var parts = []; parts.push('AWS4-HMAC-SHA256'); parts.push(datetime); parts.push(this.credentialString(datetime)); parts.push(this.hexEncodedHash(this.canonicalString())); return parts.join('\n'); }, canonicalString: function canonicalString() { var parts = [], pathname = this.request.pathname(); if (this.serviceName !== 's3') pathname = AWS.util.uriEscapePath(pathname); parts.push(this.request.method); parts.push(pathname); parts.push(this.request.search()); parts.push(this.canonicalHeaders() + '\n'); parts.push(this.signedHeaders()); parts.push(this.hexEncodedBodyHash()); return parts.join('\n'); }, canonicalHeaders: function canonicalHeaders() { var headers = []; AWS.util.each.call(this, this.request.headers, function (key, item) { headers.push([key, item]); }); headers.sort(function (a, b) { return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1; }); var parts = []; AWS.util.arrayEach.call(this, headers, function (item) { var key = item[0].toLowerCase(); if (this.isSignableHeader(key)) { var value = item[1]; if (typeof value === 'undefined' || value === null || typeof value.toString !== 'function') { throw AWS.util.error(new Error('Header ' + key + ' contains invalid value'), { code: 'InvalidHeader' }); } parts.push(key + ':' + this.canonicalHeaderValues(value.toString())); } }); return parts.join('\n'); }, canonicalHeaderValues: function canonicalHeaderValues(values) { return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, ''); }, signedHeaders: function signedHeaders() { var keys = []; AWS.util.each.call(this, this.request.headers, function (key) { key = key.toLowerCase(); if (this.isSignableHeader(key)) keys.push(key); }); return keys.sort().join(';'); }, credentialString: function credentialString(datetime) { return v4Credentials.createScope( datetime.substr(0, 8), this.request.region, this.serviceName ); }, hexEncodedHash: function hash(string) { return AWS.util.crypto.sha256(string, 'hex'); }, hexEncodedBodyHash: function hexEncodedBodyHash() { var request = this.request; if (this.isPresigned() && this.serviceName === 's3' && !request.body) { return 'UNSIGNED-PAYLOAD'; } else if (request.headers['X-Amz-Content-Sha256']) { return request.headers['X-Amz-Content-Sha256']; } else { return this.hexEncodedHash(this.request.body || ''); } }, unsignableHeaders: [ 'authorization', 'content-type', 'content-length', 'user-agent', expiresHeader, 'expect', 'x-amzn-trace-id' ], isSignableHeader: function isSignableHeader(key) { if (key.toLowerCase().indexOf('x-amz-') === 0) return true; return this.unsignableHeaders.indexOf(key) < 0; }, isPresigned: function isPresigned() { return this.request.headers[expiresHeader] ? true : false; } }); module.exports = AWS.Signers.V4; /***/ }), /***/ "../../../../aws-sdk/lib/signers/v4_credentials.js": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); /** * @api private */ var cachedSecret = {}; /** * @api private */ var cacheQueue = []; /** * @api private */ var maxCacheEntries = 50; /** * @api private */ var v4Identifier = 'aws4_request'; module.exports = { /** * @api private * * @param date [String] * @param region [String] * @param serviceName [String] * @return [String] */ createScope: function createScope(date, region, serviceName) { return [ date.substr(0, 8), region, serviceName, v4Identifier ].join('/'); }, /** * @api private * * @param credentials [Credentials] * @param date [String] * @param region [String] * @param service [String] * @param shouldCache [Boolean] * @return [String] */ getSigningKey: function getSigningKey( credentials, date, region, service, shouldCache ) { var credsIdentifier = AWS.util.crypto .hmac(credentials.secretAccessKey, credentials.accessKeyId, 'base64'); var cacheKey = [credsIdentifier, date, region, service].join('_'); shouldCache = shouldCache !== false; if (shouldCache && (cacheKey in cachedSecret)) { return cachedSecret[cacheKey]; } var kDate = AWS.util.crypto.hmac( 'AWS4' + credentials.secretAccessKey, date, 'buffer' ); var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer'); var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer'); var signingKey = AWS.util.crypto.hmac(kService, v4Identifier, 'buffer'); if (shouldCache) { cachedSecret[cacheKey] = signingKey; cacheQueue.push(cacheKey); if (cacheQueue.length > maxCacheEntries) { // remove the oldest entry (not the least recently used) delete cachedSecret[cacheQueue.shift()]; } } return signingKey; }, /** * @api private * * Empties the derived signing key cache. Made available for testing purposes * only. */ emptyCache: function emptyCache() { cachedSecret = {}; cacheQueue = []; } }; /***/ }), /***/ "../../../../aws-sdk/lib/state_machine.js": /***/ (function(module, exports) { function AcceptorStateMachine(states, state) { this.currentState = state || null; this.states = states || {}; } AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) { if (typeof finalState === 'function') { inputError = bindObject; bindObject = done; done = finalState; finalState = null; } var self = this; var state = self.states[self.currentState]; state.fn.call(bindObject || self, inputError, function(err) { if (err) { if (state.fail) self.currentState = state.fail; else return done ? done.call(bindObject, err) : null; } else { if (state.accept) self.currentState = state.accept; else return done ? done.call(bindObject) : null; } if (self.currentState === finalState) { return done ? done.call(bindObject, err) : null; } self.runTo(finalState, done, bindObject, err); }); }; AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) { if (typeof acceptState === 'function') { fn = acceptState; acceptState = null; failState = null; } else if (typeof failState === 'function') { fn = failState; failState = null; } if (!this.currentState) this.currentState = name; this.states[name] = { accept: acceptState, fail: failState, fn: fn }; return this; }; module.exports = AcceptorStateMachine; /***/ }), /***/ "../../../../aws-sdk/lib/util.js": /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/* eslint guard-for-in:0 */ var AWS; /** * A set of utility methods for use with the AWS SDK. * * @!attribute abort * Return this value from an iterator function {each} or {arrayEach} * to break out of the iteration. * @example Breaking out of an iterator function * AWS.util.each({a: 1, b: 2, c: 3}, function(key, value) { * if (key == 'b') return AWS.util.abort; * }); * @see each * @see arrayEach * @api private */ var util = { environment: 'nodejs', engine: function engine() { if (util.isBrowser() && typeof navigator !== 'undefined') { return navigator.userAgent; } else { var engine = process.platform + '/' + process.version; if (process.env.AWS_EXECUTION_ENV) { engine += ' exec-env/' + process.env.AWS_EXECUTION_ENV; } return engine; } }, userAgent: function userAgent() { var name = util.environment; var agent = 'aws-sdk-' + name + '/' + __webpack_require__("../../../../aws-sdk/lib/core.js").VERSION; if (name === 'nodejs') agent += ' ' + util.engine(); return agent; }, isBrowser: function isBrowser() { return process && process.browser; }, isNode: function isNode() { return !util.isBrowser(); }, uriEscape: function uriEscape(string) { var output = encodeURIComponent(string); output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape); // AWS percent-encodes some extra non-standard characters in a URI output = output.replace(/[*]/g, function(ch) { return '%' + ch.charCodeAt(0).toString(16).toUpperCase(); }); return output; }, uriEscapePath: function uriEscapePath(string) { var parts = []; util.arrayEach(string.split('/'), function (part) { parts.push(util.uriEscape(part)); }); return parts.join('/'); }, urlParse: function urlParse(url) { return util.url.parse(url); }, urlFormat: function urlFormat(url) { return util.url.format(url); }, queryStringParse: function queryStringParse(qs) { return util.querystring.parse(qs); }, queryParamsToString: function queryParamsToString(params) { var items = []; var escape = util.uriEscape; var sortedKeys = Object.keys(params).sort(); util.arrayEach(sortedKeys, function(name) { var value = params[name]; var ename = escape(name); var result = ename + '='; if (Array.isArray(value)) { var vals = []; util.arrayEach(value, function(item) { vals.push(escape(item)); }); result = ename + '=' + vals.sort().join('&' + ename + '='); } else if (value !== undefined && value !== null) { result = ename + '=' + escape(value); } items.push(result); }); return items.join('&'); }, readFileSync: function readFileSync(path) { if (util.isBrowser()) return null; return __webpack_require__(0).readFileSync(path, 'utf-8'); }, base64: { encode: function encode64(string) { if (typeof string === 'number') { throw util.error(new Error('Cannot base64 encode number ' + string)); } if (string === null || typeof string === 'undefined') { return string; } var buf = (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(string) : new util.Buffer(string); return buf.toString('base64'); }, decode: function decode64(string) { if (typeof string === 'number') { throw util.error(new Error('Cannot base64 decode number ' + string)); } if (string === null || typeof string === 'undefined') { return string; } return (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(string, 'base64') : new util.Buffer(string, 'base64'); } }, buffer: { toStream: function toStream(buffer) { if (!util.Buffer.isBuffer(buffer)) buffer = new util.Buffer(buffer); var readable = new (util.stream.Readable)(); var pos = 0; readable._read = function(size) { if (pos >= buffer.length) return readable.push(null); var end = pos + size; if (end > buffer.length) end = buffer.length; readable.push(buffer.slice(pos, end)); pos = end; }; return readable; }, /** * Concatenates a list of Buffer objects. */ concat: function(buffers) { var length = 0, offset = 0, buffer = null, i; for (i = 0; i < buffers.length; i++) { length += buffers[i].length; } buffer = new util.Buffer(length); for (i = 0; i < buffers.length; i++) { buffers[i].copy(buffer, offset); offset += buffers[i].length; } return buffer; } }, string: { byteLength: function byteLength(string) { if (string === null || string === undefined) return 0; if (typeof string === 'string') string = new util.Buffer(string); if (typeof string.byteLength === 'number') { return string.byteLength; } else if (typeof string.length === 'number') { return string.length; } else if (typeof string.size === 'number') { return string.size; } else if (typeof string.path === 'string') { return __webpack_require__(0).lstatSync(string.path).size; } else { throw util.error(new Error('Cannot determine length of ' + string), { object: string }); } }, upperFirst: function upperFirst(string) { return string[0].toUpperCase() + string.substr(1); }, lowerFirst: function lowerFirst(string) { return string[0].toLowerCase() + string.substr(1); } }, ini: { parse: function string(ini) { var currentSection, map = {}; util.arrayEach(ini.split(/\r?\n/), function(line) { line = line.split(/(^|\s)[;#]/)[0]; // remove comments var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/); if (section) { currentSection = section[1]; } else if (currentSection) { var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/); if (item) { map[currentSection] = map[currentSection] || {}; map[currentSection][item[1]] = item[2]; } } }); return map; } }, fn: { noop: function() {}, /** * Turn a synchronous function into as "async" function by making it call * a callback. The underlying function is called with all but the last argument, * which is treated as the callback. The callback is passed passed a first argument * of null on success to mimick standard node callbacks. */ makeAsync: function makeAsync(fn, expectedArgs) { if (expectedArgs && expectedArgs <= fn.length) { return fn; } return function() { var args = Array.prototype.slice.call(arguments, 0); var callback = args.pop(); var result = fn.apply(null, args); callback(result); }; } }, /** * Date and time utility functions. */ date: { /** * @return [Date] the current JavaScript date object. Since all * AWS services rely on this date object, you can override * this function to provide a special time value to AWS service * requests. */ getDate: function getDate() { if (!AWS) AWS = __webpack_require__("../../../../aws-sdk/lib/core.js"); if (AWS.config.systemClockOffset) { // use offset when non-zero return new Date(new Date().getTime() + AWS.config.systemClockOffset); } else { return new Date(); } }, /** * @return [String] the date in ISO-8601 format */ iso8601: function iso8601(date) { if (date === undefined) { date = util.date.getDate(); } return date.toISOString().replace(/\.\d{3}Z$/, 'Z'); }, /** * @return [String] the date in RFC 822 format */ rfc822: function rfc822(date) { if (date === undefined) { date = util.date.getDate(); } return date.toUTCString(); }, /** * @return [Integer] the UNIX timestamp value for the current time */ unixTimestamp: function unixTimestamp(date) { if (date === undefined) { date = util.date.getDate(); } return date.getTime() / 1000; }, /** * @param [String,number,Date] date * @return [Date] */ from: function format(date) { if (typeof date === 'number') { return new Date(date * 1000); // unix timestamp } else { return new Date(date); } }, /** * Given a Date or date-like value, this function formats the * date into a string of the requested value. * @param [String,number,Date] date * @param [String] formatter Valid formats are: # * 'iso8601' # * 'rfc822' # * 'unixTimestamp' * @return [String] */ format: function format(date, formatter) { if (!formatter) formatter = 'iso8601'; return util.date[formatter](util.date.from(date)); }, parseTimestamp: function parseTimestamp(value) { if (typeof value === 'number') { // unix timestamp (number) return new Date(value * 1000); } else if (value.match(/^\d+$/)) { // unix timestamp return new Date(value * 1000); } else if (value.match(/^\d{4}/)) { // iso8601 return new Date(value); } else if (value.match(/^\w{3},/)) { // rfc822 return new Date(value); } else { throw util.error( new Error('unhandled timestamp format: ' + value), {code: 'TimestampParserError'}); } } }, crypto: { crc32Table: [ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D], crc32: function crc32(data) { var tbl = util.crypto.crc32Table; var crc = 0 ^ -1; if (typeof data === 'string') { data = new util.Buffer(data); } for (var i = 0; i < data.length; i++) { var code = data.readUInt8(i); crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF]; } return (crc ^ -1) >>> 0; }, hmac: function hmac(key, string, digest, fn) { if (!digest) digest = 'binary'; if (digest === 'buffer') { digest = undefined; } if (!fn) fn = 'sha256'; if (typeof string === 'string') string = new util.Buffer(string); return util.crypto.lib.createHmac(fn, key).update(string).digest(digest); }, md5: function md5(data, digest, callback) { return util.crypto.hash('md5', data, digest, callback); }, sha256: function sha256(data, digest, callback) { return util.crypto.hash('sha256', data, digest, callback); }, hash: function(algorithm, data, digest, callback) { var hash = util.crypto.createHash(algorithm); if (!digest) { digest = 'binary'; } if (digest === 'buffer') { digest = undefined; } if (typeof data === 'string') data = new util.Buffer(data); var sliceFn = util.arraySliceFn(data); var isBuffer = util.Buffer.isBuffer(data); //Identifying objects with an ArrayBuffer as buffers if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true; if (callback && typeof data === 'object' && typeof data.on === 'function' && !isBuffer) { data.on('data', function(chunk) { hash.update(chunk); }); data.on('error', function(err) { callback(err); }); data.on('end', function() { callback(null, hash.digest(digest)); }); } else if (callback && sliceFn && !isBuffer && typeof FileReader !== 'undefined') { // this might be a File/Blob var index = 0, size = 1024 * 512; var reader = new FileReader(); reader.onerror = function() { callback(new Error('Failed to read data.')); }; reader.onload = function() { var buf = new util.Buffer(new Uint8Array(reader.result)); hash.update(buf); index += buf.length; reader._continueReading(); }; reader._continueReading = function() { if (index >= data.size) { callback(null, hash.digest(digest)); return; } var back = index + size; if (back > data.size) back = data.size; reader.readAsArrayBuffer(sliceFn.call(data, index, back)); }; reader._continueReading(); } else { if (util.isBrowser() && typeof data === 'object' && !isBuffer) { data = new util.Buffer(new Uint8Array(data)); } var out = hash.update(data).digest(digest); if (callback) callback(null, out); return out; } }, toHex: function toHex(data) { var out = []; for (var i = 0; i < data.length; i++) { out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2)); } return out.join(''); }, createHash: function createHash(algorithm) { return util.crypto.lib.createHash(algorithm); } }, /** @!ignore */ /* Abort constant */ abort: {}, each: function each(object, iterFunction) { for (var key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { var ret = iterFunction.call(this, key, object[key]); if (ret === util.abort) break; } } }, arrayEach: function arrayEach(array, iterFunction) { for (var idx in array) { if (Object.prototype.hasOwnProperty.call(array, idx)) { var ret = iterFunction.call(this, array[idx], parseInt(idx, 10)); if (ret === util.abort) break; } } }, update: function update(obj1, obj2) { util.each(obj2, function iterator(key, item) { obj1[key] = item; }); return obj1; }, merge: function merge(obj1, obj2) { return util.update(util.copy(obj1), obj2); }, copy: function copy(object) { if (object === null || object === undefined) return object; var dupe = {}; // jshint forin:false for (var key in object) { dupe[key] = object[key]; } return dupe; }, isEmpty: function isEmpty(obj) { for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { return false; } } return true; }, arraySliceFn: function arraySliceFn(obj) { var fn = obj.slice || obj.webkitSlice || obj.mozSlice; return typeof fn === 'function' ? fn : null; }, isType: function isType(obj, type) { // handle cross-"frame" objects if (typeof type === 'function') type = util.typeName(type); return Object.prototype.toString.call(obj) === '[object ' + type + ']'; }, typeName: function typeName(type) { if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name; var str = type.toString(); var match = str.match(/^\s*function (.+)\(/); return match ? match[1] : str; }, error: function error(err, options) { var originalError = null; if (typeof err.message === 'string' && err.message !== '') { if (typeof options === 'string' || (options && options.message)) { originalError = util.copy(err); originalError.message = err.message; } } err.message = err.message || null; if (typeof options === 'string') { err.message = options; } else if (typeof options === 'object' && options !== null) { util.update(err, options); if (options.message) err.message = options.message; if (options.code || options.name) err.code = options.code || options.name; if (options.stack) err.stack = options.stack; } if (typeof Object.defineProperty === 'function') { Object.defineProperty(err, 'name', {writable: true, enumerable: false}); Object.defineProperty(err, 'message', {enumerable: true}); } err.name = options && options.name || err.name || err.code || 'Error'; err.time = new Date(); if (originalError) err.originalError = originalError; return err; }, /** * @api private */ inherit: function inherit(klass, features) { var newObject = null; if (features === undefined) { features = klass; klass = Object; newObject = {}; } else { var ctor = function ConstructorWrapper() {}; ctor.prototype = klass.prototype; newObject = new ctor(); } // constructor not supplied, create pass-through ctor if (features.constructor === Object) { features.constructor = function() { if (klass !== Object) { return klass.apply(this, arguments); } }; } features.constructor.prototype = newObject; util.update(features.constructor.prototype, features); features.constructor.__super__ = klass; return features.constructor; }, /** * @api private */ mixin: function mixin() { var klass = arguments[0]; for (var i = 1; i < arguments.length; i++) { // jshint forin:false for (var prop in arguments[i].prototype) { var fn = arguments[i].prototype[prop]; if (prop !== 'constructor') { klass.prototype[prop] = fn; } } } return klass; }, /** * @api private */ hideProperties: function hideProperties(obj, props) { if (typeof Object.defineProperty !== 'function') return; util.arrayEach(props, function (key) { Object.defineProperty(obj, key, { enumerable: false, writable: true, configurable: true }); }); }, /** * @api private */ property: function property(obj, name, value, enumerable, isValue) { var opts = { configurable: true, enumerable: enumerable !== undefined ? enumerable : true }; if (typeof value === 'function' && !isValue) { opts.get = value; } else { opts.value = value; opts.writable = true; } Object.defineProperty(obj, name, opts); }, /** * @api private */ memoizedProperty: function memoizedProperty(obj, name, get, enumerable) { var cachedValue = null; // build enumerable attribute for each value with lazy accessor. util.property(obj, name, function() { if (cachedValue === null) { cachedValue = get(); } return cachedValue; }, enumerable); }, /** * TODO Remove in major version revision * This backfill populates response data without the * top-level payload name. * * @api private */ hoistPayloadMember: function hoistPayloadMember(resp) { var req = resp.request; var operation = req.operation; var output = req.service.api.operations[operation].output; if (output.payload) { var payloadMember = output.members[output.payload]; var responsePayload = resp.data[output.payload]; if (payloadMember.type === 'structure') { util.each(responsePayload, function(key, value) { util.property(resp.data, key, value, false); }); } } }, /** * Compute SHA-256 checksums of streams * * @api private */ computeSha256: function computeSha256(body, done) { if (util.isNode()) { var Stream = util.stream.Stream; var fs = __webpack_require__(0); if (body instanceof Stream) { if (typeof body.path === 'string') { // assume file object var settings = {}; if (typeof body.start === 'number') { settings.start = body.start; } if (typeof body.end === 'number') { settings.end = body.end; } body = fs.createReadStream(body.path, settings); } else { // TODO support other stream types return done(new Error('Non-file stream objects are ' + 'not supported with SigV4')); } } } util.crypto.sha256(body, 'hex', function(err, sha) { if (err) done(err); else done(null, sha); }); }, /** * @api private */ isClockSkewed: function isClockSkewed(serverTime) { if (serverTime) { util.property(AWS.config, 'isClockSkewed', Math.abs(new Date().getTime() - serverTime) >= 300000, false); return AWS.config.isClockSkewed; } }, applyClockOffset: function applyClockOffset(serverTime) { if (serverTime) AWS.config.systemClockOffset = serverTime - new Date().getTime(); }, /** * @api private */ extractRequestId: function extractRequestId(resp) { var requestId = resp.httpResponse.headers['x-amz-request-id'] || resp.httpResponse.headers['x-amzn-requestid']; if (!requestId && resp.data && resp.data.ResponseMetadata) { requestId = resp.data.ResponseMetadata.RequestId; } if (requestId) { resp.requestId = requestId; } if (resp.error) { resp.error.requestId = requestId; } }, /** * @api private */ addPromises: function addPromises(constructors, PromiseDependency) { if (PromiseDependency === undefined && AWS && AWS.config) { PromiseDependency = AWS.config.getPromisesDependency(); } if (PromiseDependency === undefined && typeof Promise !== 'undefined') { PromiseDependency = Promise; } if (typeof PromiseDependency !== 'function') var deletePromises = true; if (!Array.isArray(constructors)) constructors = [constructors]; for (var ind = 0; ind < constructors.length; ind++) { var constructor = constructors[ind]; if (deletePromises) { if (constructor.deletePromisesFromClass) { constructor.deletePromisesFromClass(); } } else if (constructor.addPromisesToClass) { constructor.addPromisesToClass(PromiseDependency); } } }, /** * @api private */ promisifyMethod: function promisifyMethod(methodName, PromiseDependency) { return function promise() { var self = this; return new PromiseDependency(function(resolve, reject) { self[methodName](function(err, data) { if (err) { reject(err); } else { resolve(data); } }); }); }; }, /** * @api private */ isDualstackAvailable: function isDualstackAvailable(service) { if (!service) return false; var metadata = __webpack_require__("../../../../aws-sdk/apis/metadata.json"); if (typeof service !== 'string') service = service.serviceIdentifier; if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false; return !!metadata[service].dualstackAvailable; }, /** * @api private */ calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) { if (!retryDelayOptions) retryDelayOptions = {}; var customBackoff = retryDelayOptions.customBackoff || null; if (typeof customBackoff === 'function') { return customBackoff(retryCount); } var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100; var delay = Math.random() * (Math.pow(2, retryCount) * base); return delay; }, /** * @api private */ handleRequestWithRetries: function handleRequestWithRetries(httpRequest, options, cb) { if (!options) options = {}; var http = AWS.HttpClient.getInstance(); var httpOptions = options.httpOptions || {}; var retryCount = 0; var errCallback = function(err) { var maxRetries = options.maxRetries || 0; if (err && err.code === 'TimeoutError') err.retryable = true; if (err && err.retryable && retryCount < maxRetries) { retryCount++; var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions); setTimeout(sendRequest, delay + (err.retryAfter || 0)); } else { cb(err); } }; var sendRequest = function() { var data = ''; http.handleRequest(httpRequest, httpOptions, function(httpResponse) { httpResponse.on('data', function(chunk) { data += chunk.toString(); }); httpResponse.on('end', function() { var statusCode = httpResponse.statusCode; if (statusCode < 300) { cb(null, data); } else { var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0; var err = util.error(new Error(), { retryable: statusCode >= 500 || statusCode === 429 } ); if (retryAfter && err.retryable) err.retryAfter = retryAfter; errCallback(err); } }); }, errCallback); }; AWS.util.defer(sendRequest); }, /** * @api private */ uuid: { v4: function uuidV4() { return __webpack_require__("../../../../uuid/index.js").v4(); } }, /** * @api private */ convertPayloadToString: function convertPayloadToString(resp) { var req = resp.request; var operation = req.operation; var rules = req.service.api.operations[operation].output || {}; if (rules.payload && resp.data[rules.payload]) { resp.data[rules.payload] = resp.data[rules.payload].toString(); } }, /** * @api private */ defer: function defer(callback) { if (typeof process === 'object' && typeof process.nextTick === 'function') { process.nextTick(callback); } else if (typeof setImmediate === 'function') { setImmediate(callback); } else { setTimeout(callback, 0); } }, /** * @api private */ defaultProfile: 'default', /** * @api private */ configOptInEnv: 'AWS_SDK_LOAD_CONFIG', /** * @api private */ sharedCredentialsFileEnv: 'AWS_SHARED_CREDENTIALS_FILE', /** * @api private */ sharedConfigFileEnv: 'AWS_CONFIG_FILE' }; module.exports = util; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__("../../../../process/browser.js"))) /***/ }), /***/ "../../../../aws-sdk/lib/xml/browser_parser.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var Shape = __webpack_require__("../../../../aws-sdk/lib/model/shape.js"); function DomXmlParser() { } DomXmlParser.prototype.parse = function(xml, shape) { if (xml.replace(/^\s+/, '') === '') return {}; var result, error; try { if (window.DOMParser) { try { var parser = new DOMParser(); result = parser.parseFromString(xml, 'text/xml'); } catch (syntaxError) { throw util.error(new Error('Parse error in document'), { originalError: syntaxError, code: 'XMLParserError', retryable: true }); } if (result.documentElement === null) { throw util.error(new Error('Cannot parse empty document.'), { code: 'XMLParserError', retryable: true }); } var isError = result.getElementsByTagName('parsererror')[0]; if (isError && (isError.parentNode === result || isError.parentNode.nodeName === 'body' || isError.parentNode.parentNode === result || isError.parentNode.parentNode.nodeName === 'body')) { var errorElement = isError.getElementsByTagName('div')[0] || isError; throw util.error(new Error(errorElement.textContent || 'Parser error in document'), { code: 'XMLParserError', retryable: true }); } } else if (window.ActiveXObject) { result = new window.ActiveXObject('Microsoft.XMLDOM'); result.async = false; if (!result.loadXML(xml)) { throw util.error(new Error('Parse error in document'), { code: 'XMLParserError', retryable: true }); } } else { throw new Error('Cannot load XML parser'); } } catch (e) { error = e; } if (result && result.documentElement && !error) { var data = parseXml(result.documentElement, shape); var metadata = result.getElementsByTagName('ResponseMetadata')[0]; if (metadata) { data.ResponseMetadata = parseXml(metadata, {}); } return data; } else if (error) { throw util.error(error || new Error(), {code: 'XMLParserError', retryable: true}); } else { // empty xml document return {}; } }; function parseXml(xml, shape) { if (!shape) shape = {}; switch (shape.type) { case 'structure': return parseStructure(xml, shape); case 'map': return parseMap(xml, shape); case 'list': return parseList(xml, shape); case undefined: case null: return parseUnknown(xml); default: return parseScalar(xml, shape); } } function parseStructure(xml, shape) { var data = {}; if (xml === null) return data; util.each(shape.members, function(memberName, memberShape) { if (memberShape.isXmlAttribute) { if (Object.prototype.hasOwnProperty.call(xml.attributes, memberShape.name)) { var value = xml.attributes[memberShape.name].value; data[memberName] = parseXml({textContent: value}, memberShape); } } else { var xmlChild = memberShape.flattened ? xml : xml.getElementsByTagName(memberShape.name)[0]; if (xmlChild) { data[memberName] = parseXml(xmlChild, memberShape); } else if (!memberShape.flattened && memberShape.type === 'list') { data[memberName] = memberShape.defaultValue; } } }); return data; } function parseMap(xml, shape) { var data = {}; var xmlKey = shape.key.name || 'key'; var xmlValue = shape.value.name || 'value'; var tagName = shape.flattened ? shape.name : 'entry'; var child = xml.firstElementChild; while (child) { if (child.nodeName === tagName) { var key = child.getElementsByTagName(xmlKey)[0].textContent; var value = child.getElementsByTagName(xmlValue)[0]; data[key] = parseXml(value, shape.value); } child = child.nextElementSibling; } return data; } function parseList(xml, shape) { var data = []; var tagName = shape.flattened ? shape.name : (shape.member.name || 'member'); var child = xml.firstElementChild; while (child) { if (child.nodeName === tagName) { data.push(parseXml(child, shape.member)); } child = child.nextElementSibling; } return data; } function parseScalar(xml, shape) { if (xml.getAttribute) { var encoding = xml.getAttribute('encoding'); if (encoding === 'base64') { shape = new Shape.create({type: encoding}); } } var text = xml.textContent; if (text === '') text = null; if (typeof shape.toType === 'function') { return shape.toType(text); } else { return text; } } function parseUnknown(xml) { if (xml === undefined || xml === null) return ''; // empty object if (!xml.firstElementChild) { if (xml.parentNode.parentNode === null) return {}; if (xml.childNodes.length === 0) return ''; else return xml.textContent; } // object, parse as structure var shape = {type: 'structure', members: {}}; var child = xml.firstElementChild; while (child) { var tag = child.nodeName; if (Object.prototype.hasOwnProperty.call(shape.members, tag)) { // multiple tags of the same name makes it a list shape.members[tag].type = 'list'; } else { shape.members[tag] = {name: tag}; } child = child.nextElementSibling; } return parseStructure(xml, shape); } module.exports = DomXmlParser; /***/ }), /***/ "../../../../aws-sdk/lib/xml/builder.js": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("../../../../aws-sdk/lib/util.js"); var builder = __webpack_require__("../../../../xmlbuilder/lib/index.js"); function XmlBuilder() { } XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) { var xml = builder.create(rootElement); applyNamespaces(xml, shape); serialize(xml, params, shape); return xml.children.length > 0 || noEmpty ? xml.root().toString() : ''; }; function serialize(xml, value, shape) { switch (shape.type) { case 'structure': return serializeStructure(xml, value, shape); case 'map': return serializeMap(xml, value, shape); case 'list': return serializeList(xml, value, shape); default: return serializeScalar(xml, value, shape); } } function serializeStructure(xml, params, shape) { util.arrayEach(shape.memberNames, function(memberName) { var memberShape = shape.members[memberName]; if (memberShape.location !== 'body') return; var value = params[memberName]; var name = memberShape.name; if (value !== undefined && value !== null) { if (memberShape.isXmlAttribute) { xml.att(name, value); } else if (memberShape.flattened) { serialize(xml, value, memberShape); } else { var element = xml.ele(name); applyNamespaces(element, memberShape); serialize(element, value, memberShape); } } }); } function serializeMap(xml, map, shape) { var xmlKey = shape.key.name || 'key'; var xmlValue = shape.value.name || 'value'; util.each(map, function(key, value) { var entry = xml.ele(shape.flattened ? shape.name : 'entry'); serialize(entry.ele(xmlKey), key, shape.key); serialize(entry.ele(xmlValue), value, shape.value); }); } function serializeList(xml, list, shape) { if (shape.flattened) { util.arrayEach(list, function(value) { var name = shape.member.name || shape.name; var element = xml.ele(name); serialize(element, value, shape.member); }); } else { util.arrayEach(list, function(value) { var name = shape.member.name || 'member'; var element = xml.ele(name); serialize(element, value, shape.member); }); } } function serializeScalar(xml, value, shape) { xml.txt(shape.toWireFormat(value)); } function applyNamespaces(xml, shape) { var uri, prefix = 'xmlns'; if (shape.xmlNamespaceUri) { uri = shape.xmlNamespaceUri; if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix; } else if (xml.isRoot && shape.api.xmlNamespaceUri) { uri = shape.api.xmlNamespaceUri; } if (uri) xml.att(prefix, uri); } module.exports = XmlBuilder; /***/ }), /***/ "../../../../base64-js/index.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return (b64.length * 3 / 4) - placeHoldersCount(b64) } function toByteArray (b64) { var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr((len * 3 / 4) - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0; i < l; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } /***/ }), /***/ "../../../../buffer/index.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ var base64 = __webpack_require__("../../../../base64-js/index.js") var ieee754 = __webpack_require__("../../../../ieee754/index.js") var isArray = __webpack_require__("../../../../isarray/index.js") exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__("../../../../webpack/buildin/global.js"))) /***/ }), /***/ "../../../../chart.js/src/chart.js": /***/ (function(module, exports, __webpack_require__) { /** * @namespace Chart */ var Chart = __webpack_require__("../../../../chart.js/src/core/core.js")(); __webpack_require__("../../../../chart.js/src/core/core.helpers.js")(Chart); __webpack_require__("../../../../chart.js/src/platforms/platform.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.canvasHelpers.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.element.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.plugin.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.animation.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.controller.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.datasetController.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.layoutService.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.scaleService.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.ticks.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.scale.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.interaction.js")(Chart); __webpack_require__("../../../../chart.js/src/core/core.tooltip.js")(Chart); __webpack_require__("../../../../chart.js/src/elements/element.arc.js")(Chart); __webpack_require__("../../../../chart.js/src/elements/element.line.js")(Chart); __webpack_require__("../../../../chart.js/src/elements/element.point.js")(Chart); __webpack_require__("../../../../chart.js/src/elements/element.rectangle.js")(Chart); __webpack_require__("../../../../chart.js/src/scales/scale.linearbase.js")(Chart); __webpack_require__("../../../../chart.js/src/scales/scale.category.js")(Chart); __webpack_require__("../../../../chart.js/src/scales/scale.linear.js")(Chart); __webpack_require__("../../../../chart.js/src/scales/scale.logarithmic.js")(Chart); __webpack_require__("../../../../chart.js/src/scales/scale.radialLinear.js")(Chart); __webpack_require__("../../../../chart.js/src/scales/scale.time.js")(Chart); // Controllers must be loaded after elements // See Chart.core.datasetController.dataElementType __webpack_require__("../../../../chart.js/src/controllers/controller.bar.js")(Chart); __webpack_require__("../../../../chart.js/src/controllers/controller.bubble.js")(Chart); __webpack_require__("../../../../chart.js/src/controllers/controller.doughnut.js")(Chart); __webpack_require__("../../../../chart.js/src/controllers/controller.line.js")(Chart); __webpack_require__("../../../../chart.js/src/controllers/controller.polarArea.js")(Chart); __webpack_require__("../../../../chart.js/src/controllers/controller.radar.js")(Chart); __webpack_require__("../../../../chart.js/src/charts/Chart.Bar.js")(Chart); __webpack_require__("../../../../chart.js/src/charts/Chart.Bubble.js")(Chart); __webpack_require__("../../../../chart.js/src/charts/Chart.Doughnut.js")(Chart); __webpack_require__("../../../../chart.js/src/charts/Chart.Line.js")(Chart); __webpack_require__("../../../../chart.js/src/charts/Chart.PolarArea.js")(Chart); __webpack_require__("../../../../chart.js/src/charts/Chart.Radar.js")(Chart); __webpack_require__("../../../../chart.js/src/charts/Chart.Scatter.js")(Chart); // Loading built-it plugins var plugins = []; plugins.push( __webpack_require__("../../../../chart.js/src/plugins/plugin.filler.js")(Chart), __webpack_require__("../../../../chart.js/src/plugins/plugin.legend.js")(Chart), __webpack_require__("../../../../chart.js/src/plugins/plugin.title.js")(Chart) ); Chart.plugins.register(plugins); module.exports = Chart; if (typeof window !== 'undefined') { window.Chart = Chart; } /***/ }), /***/ "../../../../chart.js/src/charts/Chart.Bar.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { Chart.Bar = function(context, config) { config.type = 'bar'; return new Chart(context, config); }; }; /***/ }), /***/ "../../../../chart.js/src/charts/Chart.Bubble.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { Chart.Bubble = function(context, config) { config.type = 'bubble'; return new Chart(context, config); }; }; /***/ }), /***/ "../../../../chart.js/src/charts/Chart.Doughnut.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { Chart.Doughnut = function(context, config) { config.type = 'doughnut'; return new Chart(context, config); }; }; /***/ }), /***/ "../../../../chart.js/src/charts/Chart.Line.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { Chart.Line = function(context, config) { config.type = 'line'; return new Chart(context, config); }; }; /***/ }), /***/ "../../../../chart.js/src/charts/Chart.PolarArea.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { Chart.PolarArea = function(context, config) { config.type = 'polarArea'; return new Chart(context, config); }; }; /***/ }), /***/ "../../../../chart.js/src/charts/Chart.Radar.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { Chart.Radar = function(context, config) { config.type = 'radar'; return new Chart(context, config); }; }; /***/ }), /***/ "../../../../chart.js/src/charts/Chart.Scatter.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { var defaultConfig = { hover: { mode: 'single' }, scales: { xAxes: [{ type: 'linear', // scatter should not use a category axis position: 'bottom', id: 'x-axis-1' // need an ID so datasets can reference the scale }], yAxes: [{ type: 'linear', position: 'left', id: 'y-axis-1' }] }, tooltips: { callbacks: { title: function() { // Title doesn't make sense for scatter since we format the data as a point return ''; }, label: function(tooltipItem) { return '(' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')'; } } } }; // Register the default config for this type Chart.defaults.scatter = defaultConfig; // Scatter charts use line controllers Chart.controllers.scatter = Chart.controllers.line; Chart.Scatter = function(context, config) { config.type = 'scatter'; return new Chart(context, config); }; }; /***/ }), /***/ "../../../../chart.js/src/controllers/controller.bar.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { var helpers = Chart.helpers; Chart.defaults.bar = { hover: { mode: 'label' }, scales: { xAxes: [{ type: 'category', // Specific to Bar Controller categoryPercentage: 0.8, barPercentage: 0.9, // grid line settings gridLines: { offsetGridLines: true } }], yAxes: [{ type: 'linear' }] } }; Chart.controllers.bar = Chart.DatasetController.extend({ dataElementType: Chart.elements.Rectangle, initialize: function() { var me = this; var meta; Chart.DatasetController.prototype.initialize.apply(me, arguments); meta = me.getMeta(); meta.stack = me.getDataset().stack; meta.bar = true; }, update: function(reset) { var me = this; var elements = me.getMeta().data; var i, ilen; me._ruler = me.getRuler(); for (i = 0, ilen = elements.length; i < ilen; ++i) { me.updateElement(elements[i], i, reset); } }, updateElement: function(rectangle, index, reset) { var me = this; var chart = me.chart; var meta = me.getMeta(); var dataset = me.getDataset(); var custom = rectangle.custom || {}; var rectangleOptions = chart.options.elements.rectangle; rectangle._xScale = me.getScaleForId(meta.xAxisID); rectangle._yScale = me.getScaleForId(meta.yAxisID); rectangle._datasetIndex = me.index; rectangle._index = index; rectangle._model = { datasetLabel: dataset.label, label: chart.data.labels[index], borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleOptions.borderSkipped, backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleOptions.backgroundColor), borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleOptions.borderColor), borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, rectangleOptions.borderWidth) }; me.updateElementGeometry(rectangle, index, reset); rectangle.pivot(); }, /** * @private */ updateElementGeometry: function(rectangle, index, reset) { var me = this; var model = rectangle._model; var vscale = me.getValueScale(); var base = vscale.getBasePixel(); var horizontal = vscale.isHorizontal(); var ruler = me._ruler || me.getRuler(); var vpixels = me.calculateBarValuePixels(me.index, index); var ipixels = me.calculateBarIndexPixels(me.index, index, ruler); model.horizontal = horizontal; model.base = reset? base : vpixels.base; model.x = horizontal? reset? base : vpixels.head : ipixels.center; model.y = horizontal? ipixels.center : reset? base : vpixels.head; model.height = horizontal? ipixels.size : undefined; model.width = horizontal? undefined : ipixels.size; }, /** * @private */ getValueScaleId: function() { return this.getMeta().yAxisID; }, /** * @private */ getIndexScaleId: function() { return this.getMeta().xAxisID; }, /** * @private */ getValueScale: function() { return this.getScaleForId(this.getValueScaleId()); }, /** * @private */ getIndexScale: function() { return this.getScaleForId(this.getIndexScaleId()); }, /** * Returns the effective number of stacks based on groups and bar visibility. * @private */ getStackCount: function(last) { var me = this; var chart = me.chart; var scale = me.getIndexScale(); var stacked = scale.options.stacked; var ilen = last === undefined? chart.data.datasets.length : last + 1; var stacks = []; var i, meta; for (i = 0; i < ilen; ++i) { meta = chart.getDatasetMeta(i); if (meta.bar && chart.isDatasetVisible(i) && (stacked === false || (stacked === true && stacks.indexOf(meta.stack) === -1) || (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) { stacks.push(meta.stack); } } return stacks.length; }, /** * Returns the stack index for the given dataset based on groups and bar visibility. * @private */ getStackIndex: function(datasetIndex) { return this.getStackCount(datasetIndex) - 1; }, /** * @private */ getRuler: function() { var me = this; var scale = me.getIndexScale(); var options = scale.options; var stackCount = me.getStackCount(); var fullSize = scale.isHorizontal()? scale.width : scale.height; var tickSize = fullSize / scale.ticks.length; var categorySize = tickSize * options.categoryPercentage; var fullBarSize = categorySize / stackCount; var barSize = fullBarSize * options.barPercentage; barSize = Math.min( helpers.getValueOrDefault(options.barThickness, barSize), helpers.getValueOrDefault(options.maxBarThickness, Infinity)); return { stackCount: stackCount, tickSize: tickSize, categorySize: categorySize, categorySpacing: tickSize - categorySize, fullBarSize: fullBarSize, barSize: barSize, barSpacing: fullBarSize - barSize, scale: scale }; }, /** * Note: pixel values are not clamped to the scale area. * @private */ calculateBarValuePixels: function(datasetIndex, index) { var me = this; var chart = me.chart; var meta = me.getMeta(); var scale = me.getValueScale(); var datasets = chart.data.datasets; var value = Number(datasets[datasetIndex].data[index]); var stacked = scale.options.stacked; var stack = meta.stack; var start = 0; var i, imeta, ivalue, base, head, size; if (stacked || (stacked === undefined && stack !== undefined)) { for (i = 0; i < datasetIndex; ++i) { imeta = chart.getDatasetMeta(i); if (imeta.bar && imeta.stack === stack && imeta.controller.getValueScaleId() === scale.id && chart.isDatasetVisible(i)) { ivalue = Number(datasets[i].data[index]); if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) { start += ivalue; } } } } base = scale.getPixelForValue(start); head = scale.getPixelForValue(start + value); size = (head - base) / 2; return { size: size, base: base, head: head, center: head + size / 2 }; }, /** * @private */ calculateBarIndexPixels: function(datasetIndex, index, ruler) { var me = this; var scale = ruler.scale; var isCombo = me.chart.isCombo; var stackIndex = me.getStackIndex(datasetIndex); var base = scale.getPixelForValue(null, index, datasetIndex, isCombo); var size = ruler.barSize; base -= isCombo? ruler.tickSize / 2 : 0; base += ruler.fullBarSize * stackIndex; base += ruler.categorySpacing / 2; base += ruler.barSpacing / 2; return { size: size, base: base, head: base + size, center: base + size / 2 }; }, draw: function() { var me = this; var chart = me.chart; var elements = me.getMeta().data; var dataset = me.getDataset(); var ilen = elements.length; var i = 0; var d; helpers.canvas.clipArea(chart.ctx, chart.chartArea); for (; i 0) { if (tooltipItems[0].yLabel) { title = tooltipItems[0].yLabel; } else if (data.labels.length > 0 && tooltipItems[0].index < data.labels.length) { title = data.labels[tooltipItems[0].index]; } } return title; }, label: function(tooltipItem, data) { var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || ''; return datasetLabel + ': ' + tooltipItem.xLabel; } } } }; Chart.controllers.horizontalBar = Chart.controllers.bar.extend({ /** * @private */ getValueScaleId: function() { return this.getMeta().xAxisID; }, /** * @private */ getIndexScaleId: function() { return this.getMeta().yAxisID; } }); }; /***/ }), /***/ "../../../../chart.js/src/controllers/controller.bubble.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { var helpers = Chart.helpers; Chart.defaults.bubble = { hover: { mode: 'single' }, scales: { xAxes: [{ type: 'linear', // bubble should probably use a linear scale by default position: 'bottom', id: 'x-axis-0' // need an ID so datasets can reference the scale }], yAxes: [{ type: 'linear', position: 'left', id: 'y-axis-0' }] }, tooltips: { callbacks: { title: function() { // Title doesn't make sense for scatter since we format the data as a point return ''; }, label: function(tooltipItem, data) { var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || ''; var dataPoint = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; return datasetLabel + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ', ' + dataPoint.r + ')'; } } } }; Chart.controllers.bubble = Chart.DatasetController.extend({ dataElementType: Chart.elements.Point, update: function(reset) { var me = this; var meta = me.getMeta(); var points = meta.data; // Update Points helpers.each(points, function(point, index) { me.updateElement(point, index, reset); }); }, updateElement: function(point, index, reset) { var me = this; var meta = me.getMeta(); var xScale = me.getScaleForId(meta.xAxisID); var yScale = me.getScaleForId(meta.yAxisID); var custom = point.custom || {}; var dataset = me.getDataset(); var data = dataset.data[index]; var pointElementOptions = me.chart.options.elements.point; var dsIndex = me.index; helpers.extend(point, { // Utility _xScale: xScale, _yScale: yScale, _datasetIndex: dsIndex, _index: index, // Desired view properties _model: { x: reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex, me.chart.isCombo), y: reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex), // Appearance radius: reset ? 0 : custom.radius ? custom.radius : me.getRadius(data), // Tooltip hitRadius: custom.hitRadius ? custom.hitRadius : helpers.getValueAtIndexOrDefault(dataset.hitRadius, index, pointElementOptions.hitRadius) } }); // Trick to reset the styles of the point Chart.DatasetController.prototype.removeHoverStyle.call(me, point, pointElementOptions); var model = point._model; model.skip = custom.skip ? custom.skip : (isNaN(model.x) || isNaN(model.y)); point.pivot(); }, getRadius: function(value) { return value.r || this.chart.options.elements.point.radius; }, setHoverStyle: function(point) { var me = this; Chart.DatasetController.prototype.setHoverStyle.call(me, point); // Radius var dataset = me.chart.data.datasets[point._datasetIndex]; var index = point._index; var custom = point.custom || {}; var model = point._model; model.radius = custom.hoverRadius ? custom.hoverRadius : (helpers.getValueAtIndexOrDefault(dataset.hoverRadius, index, me.chart.options.elements.point.hoverRadius)) + me.getRadius(dataset.data[index]); }, removeHoverStyle: function(point) { var me = this; Chart.DatasetController.prototype.removeHoverStyle.call(me, point, me.chart.options.elements.point); var dataVal = me.chart.data.datasets[point._datasetIndex].data[point._index]; var custom = point.custom || {}; var model = point._model; model.radius = custom.radius ? custom.radius : me.getRadius(dataVal); } }); }; /***/ }), /***/ "../../../../chart.js/src/controllers/controller.doughnut.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { var helpers = Chart.helpers, defaults = Chart.defaults; defaults.doughnut = { animation: { // Boolean - Whether we animate the rotation of the Doughnut animateRotate: true, // Boolean - Whether we animate scaling the Doughnut from the centre animateScale: false }, aspectRatio: 1, hover: { mode: 'single' }, legendCallback: function(chart) { var text = []; text.push('
    '); var data = chart.data; var datasets = data.datasets; var labels = data.labels; if (datasets.length) { for (var i = 0; i < datasets[0].data.length; ++i) { text.push('
  • '); if (labels[i]) { text.push(labels[i]); } text.push('
  • '); } } text.push('
'); return text.join(''); }, legend: { labels: { generateLabels: function(chart) { var data = chart.data; if (data.labels.length && data.datasets.length) { return data.labels.map(function(label, i) { var meta = chart.getDatasetMeta(0); var ds = data.datasets[0]; var arc = meta.data[i]; var custom = arc && arc.custom || {}; var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault; var arcOpts = chart.options.elements.arc; var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor); var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor); var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth); return { text: label, fillStyle: fill, strokeStyle: stroke, lineWidth: bw, hidden: isNaN(ds.data[i]) || meta.data[i].hidden, // Extra data used for toggling the correct item index: i }; }); } return []; } }, onClick: function(e, legendItem) { var index = legendItem.index; var chart = this.chart; var i, ilen, meta; for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { meta = chart.getDatasetMeta(i); // toggle visibility of index if exists if (meta.data[index]) { meta.data[index].hidden = !meta.data[index].hidden; } } chart.update(); } }, // The percentage of the chart that we cut out of the middle. cutoutPercentage: 50, // The rotation of the chart, where the first data arc begins. rotation: Math.PI * -0.5, // The total circumference of the chart. circumference: Math.PI * 2.0, // Need to override these to give a nice default tooltips: { callbacks: { title: function() { return ''; }, label: function(tooltipItem, data) { var dataLabel = data.labels[tooltipItem.index]; var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; if (helpers.isArray(dataLabel)) { // show value on first line of multiline label // need to clone because we are changing the value dataLabel = dataLabel.slice(); dataLabel[0] += value; } else { dataLabel += value; } return dataLabel; } } } }; defaults.pie = helpers.clone(defaults.doughnut); helpers.extend(defaults.pie, { cutoutPercentage: 0 }); Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({ dataElementType: Chart.elements.Arc, linkScales: helpers.noop, // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly getRingIndex: function(datasetIndex) { var ringIndex = 0; for (var j = 0; j < datasetIndex; ++j) { if (this.chart.isDatasetVisible(j)) { ++ringIndex; } } return ringIndex; }, update: function(reset) { var me = this; var chart = me.chart, chartArea = chart.chartArea, opts = chart.options, arcOpts = opts.elements.arc, availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth, availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth, minSize = Math.min(availableWidth, availableHeight), offset = { x: 0, y: 0 }, meta = me.getMeta(), cutoutPercentage = opts.cutoutPercentage, circumference = opts.circumference; // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc if (circumference < Math.PI * 2.0) { var startAngle = opts.rotation % (Math.PI * 2.0); startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0); var endAngle = startAngle + circumference; var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)}; var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)}; var contains0 = (startAngle <= 0 && 0 <= endAngle) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle); var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle); var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle); var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle); var cutout = cutoutPercentage / 100.0; var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))}; var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))}; var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5}; minSize = Math.min(availableWidth / size.width, availableHeight / size.height); offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5}; } chart.borderWidth = me.getMaxBorderWidth(meta.data); chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0); chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0); chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); chart.offsetX = offset.x * chart.outerRadius; chart.offsetY = offset.y * chart.outerRadius; meta.total = me.calculateTotal(); me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index)); me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0); helpers.each(meta.data, function(arc, index) { me.updateElement(arc, index, reset); }); }, updateElement: function(arc, index, reset) { var me = this; var chart = me.chart, chartArea = chart.chartArea, opts = chart.options, animationOpts = opts.animation, centerX = (chartArea.left + chartArea.right) / 2, centerY = (chartArea.top + chartArea.bottom) / 2, startAngle = opts.rotation, // non reset case handled later endAngle = opts.rotation, // non reset case handled later dataset = me.getDataset(), circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)), innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius, outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius, valueAtIndexOrDefault = helpers.getValueAtIndexOrDefault; helpers.extend(arc, { // Utility _datasetIndex: me.index, _index: index, // Desired view properties _model: { x: centerX + chart.offsetX, y: centerY + chart.offsetY, startAngle: startAngle, endAngle: endAngle, circumference: circumference, outerRadius: outerRadius, innerRadius: innerRadius, label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index]) } }); var model = arc._model; // Resets the visual styles this.removeHoverStyle(arc); // Set correct angles if not resetting if (!reset || !animationOpts.animateRotate) { if (index === 0) { model.startAngle = opts.rotation; } else { model.startAngle = me.getMeta().data[index - 1]._model.endAngle; } model.endAngle = model.startAngle + model.circumference; } arc.pivot(); }, removeHoverStyle: function(arc) { Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc); }, calculateTotal: function() { var dataset = this.getDataset(); var meta = this.getMeta(); var total = 0; var value; helpers.each(meta.data, function(element, index) { value = dataset.data[index]; if (!isNaN(value) && !element.hidden) { total += Math.abs(value); } }); /* if (total === 0) { total = NaN; }*/ return total; }, calculateCircumference: function(value) { var total = this.getMeta().total; if (total > 0 && !isNaN(value)) { return (Math.PI * 2.0) * (value / total); } return 0; }, // gets the max border or hover width to properly scale pie charts getMaxBorderWidth: function(elements) { var max = 0, index = this.index, length = elements.length, borderWidth, hoverWidth; for (var i = 0; i < length; i++) { borderWidth = elements[i]._model ? elements[i]._model.borderWidth : 0; hoverWidth = elements[i]._chart ? elements[i]._chart.config.data.datasets[index].hoverBorderWidth : 0; max = borderWidth > max ? borderWidth : max; max = hoverWidth > max ? hoverWidth : max; } return max; } }); }; /***/ }), /***/ "../../../../chart.js/src/controllers/controller.line.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { var helpers = Chart.helpers; Chart.defaults.line = { showLines: true, spanGaps: false, hover: { mode: 'label' }, scales: { xAxes: [{ type: 'category', id: 'x-axis-0' }], yAxes: [{ type: 'linear', id: 'y-axis-0' }] } }; function lineEnabled(dataset, options) { return helpers.getValueOrDefault(dataset.showLine, options.showLines); } Chart.controllers.line = Chart.DatasetController.extend({ datasetElementType: Chart.elements.Line, dataElementType: Chart.elements.Point, update: function(reset) { var me = this; var meta = me.getMeta(); var line = meta.dataset; var points = meta.data || []; var options = me.chart.options; var lineElementOptions = options.elements.line; var scale = me.getScaleForId(meta.yAxisID); var i, ilen, custom; var dataset = me.getDataset(); var showLine = lineEnabled(dataset, options); // Update Line if (showLine) { custom = line.custom || {}; // Compatibility: If the properties are defined with only the old name, use those values if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { dataset.lineTension = dataset.tension; } // Utility line._scale = scale; line._datasetIndex = me.index; // Data line._children = points; // Model line._model = { // Appearance // The default behavior of lines is to break at null values, according // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158 // This option gives lines the ability to span gaps spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps, tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, lineElementOptions.tension), backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor), borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth), borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor), borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle), borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash), borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset), borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle), fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill), steppedLine: custom.steppedLine ? custom.steppedLine : helpers.getValueOrDefault(dataset.steppedLine, lineElementOptions.stepped), cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.getValueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode), }; line.pivot(); } // Update Points for (i=0, ilen=points.length; i'); var data = chart.data; var datasets = data.datasets; var labels = data.labels; if (datasets.length) { for (var i = 0; i < datasets[0].data.length; ++i) { text.push('
  • '); if (labels[i]) { text.push(labels[i]); } text.push('
  • '); } } text.push(''); return text.join(''); }, legend: { labels: { generateLabels: function(chart) { var data = chart.data; if (data.labels.length && data.datasets.length) { return data.labels.map(function(label, i) { var meta = chart.getDatasetMeta(0); var ds = data.datasets[0]; var arc = meta.data[i]; var custom = arc.custom || {}; var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault; var arcOpts = chart.options.elements.arc; var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor); var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor); var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth); return { text: label, fillStyle: fill, strokeStyle: stroke, lineWidth: bw, hidden: isNaN(ds.data[i]) || meta.data[i].hidden, // Extra data used for toggling the correct item index: i }; }); } return []; } }, onClick: function(e, legendItem) { var index = legendItem.index; var chart = this.chart; var i, ilen, meta; for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { meta = chart.getDatasetMeta(i); meta.data[index].hidden = !meta.data[index].hidden; } chart.update(); } }, // Need to override these to give a nice default tooltips: { callbacks: { title: function() { return ''; }, label: function(tooltipItem, data) { return data.labels[tooltipItem.index] + ': ' + tooltipItem.yLabel; } } } }; Chart.controllers.polarArea = Chart.DatasetController.extend({ dataElementType: Chart.elements.Arc, linkScales: helpers.noop, update: function(reset) { var me = this; var chart = me.chart; var chartArea = chart.chartArea; var meta = me.getMeta(); var opts = chart.options; var arcOpts = opts.elements.arc; var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0); chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); me.innerRadius = me.outerRadius - chart.radiusLength; meta.count = me.countVisibleElements(); helpers.each(meta.data, function(arc, index) { me.updateElement(arc, index, reset); }); }, updateElement: function(arc, index, reset) { var me = this; var chart = me.chart; var dataset = me.getDataset(); var opts = chart.options; var animationOpts = opts.animation; var scale = chart.scale; var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault; var labels = chart.data.labels; var circumference = me.calculateCircumference(dataset.data[index]); var centerX = scale.xCenter; var centerY = scale.yCenter; // If there is NaN data before us, we need to calculate the starting angle correctly. // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data var visibleCount = 0; var meta = me.getMeta(); for (var i = 0; i < index; ++i) { if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) { ++visibleCount; } } // var negHalfPI = -0.5 * Math.PI; var datasetStartAngle = opts.startAngle; var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); var startAngle = datasetStartAngle + (circumference * visibleCount); var endAngle = startAngle + (arc.hidden ? 0 : circumference); var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); helpers.extend(arc, { // Utility _datasetIndex: me.index, _index: index, _scale: scale, // Desired view properties _model: { x: centerX, y: centerY, innerRadius: 0, outerRadius: reset ? resetRadius : distance, startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle, endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle, label: getValueAtIndexOrDefault(labels, index, labels[index]) } }); // Apply border and fill style me.removeHoverStyle(arc); arc.pivot(); }, removeHoverStyle: function(arc) { Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc); }, countVisibleElements: function() { var dataset = this.getDataset(); var meta = this.getMeta(); var count = 0; helpers.each(meta.data, function(element, index) { if (!isNaN(dataset.data[index]) && !element.hidden) { count++; } }); return count; }, calculateCircumference: function(value) { var count = this.getMeta().count; if (count > 0 && !isNaN(value)) { return (2 * Math.PI) / count; } return 0; } }); }; /***/ }), /***/ "../../../../chart.js/src/controllers/controller.radar.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { var helpers = Chart.helpers; Chart.defaults.radar = { aspectRatio: 1, scale: { type: 'radialLinear' }, elements: { line: { tension: 0 // no bezier in radar } } }; Chart.controllers.radar = Chart.DatasetController.extend({ datasetElementType: Chart.elements.Line, dataElementType: Chart.elements.Point, linkScales: helpers.noop, update: function(reset) { var me = this; var meta = me.getMeta(); var line = meta.dataset; var points = meta.data; var custom = line.custom || {}; var dataset = me.getDataset(); var lineElementOptions = me.chart.options.elements.line; var scale = me.chart.scale; // Compatibility: If the properties are defined with only the old name, use those values if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { dataset.lineTension = dataset.tension; } helpers.extend(meta.dataset, { // Utility _datasetIndex: me.index, _scale: scale, // Data _children: points, _loop: true, // Model _model: { // Appearance tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, lineElementOptions.tension), backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor), borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth), borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor), fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill), borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle), borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash), borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset), borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle), } }); meta.dataset.pivot(); // Update Points helpers.each(points, function(point, index) { me.updateElement(point, index, reset); }, me); // Update bezier control points me.updateBezierControlPoints(); }, updateElement: function(point, index, reset) { var me = this; var custom = point.custom || {}; var dataset = me.getDataset(); var scale = me.chart.scale; var pointElementOptions = me.chart.options.elements.point; var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); // Compatibility: If the properties are defined with only the old name, use those values if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) { dataset.pointRadius = dataset.radius; } if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) { dataset.pointHitRadius = dataset.hitRadius; } helpers.extend(point, { // Utility _datasetIndex: me.index, _index: index, _scale: scale, // Desired view properties _model: { x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales y: reset ? scale.yCenter : pointPosition.y, // Appearance tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension), radius: custom.radius ? custom.radius : helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius), backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor), borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor), borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth), pointStyle: custom.pointStyle ? custom.pointStyle : helpers.getValueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle), // Tooltip hitRadius: custom.hitRadius ? custom.hitRadius : helpers.getValueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius) } }); point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y)); }, updateBezierControlPoints: function() { var chartArea = this.chart.chartArea; var meta = this.getMeta(); helpers.each(meta.data, function(point, index) { var model = point._model; var controlPoints = helpers.splineCurve( helpers.previousItem(meta.data, index, true)._model, model, helpers.nextItem(meta.data, index, true)._model, model.tension ); // Prevent the bezier going outside of the bounds of the graph model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left); model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top); model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left); model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top); // Now pivot the point for animation point.pivot(); }); }, setHoverStyle: function(point) { // Point var dataset = this.chart.data.datasets[point._datasetIndex]; var custom = point.custom || {}; var index = point._index; var model = point._model; model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.getValueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius); model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor)); model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor)); model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth); }, removeHoverStyle: function(point) { var dataset = this.chart.data.datasets[point._datasetIndex]; var custom = point.custom || {}; var index = point._index; var model = point._model; var pointElementOptions = this.chart.options.elements.point; model.radius = custom.radius ? custom.radius : helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius); model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor); model.borderColor = custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor); model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth); } }); }; /***/ }), /***/ "../../../../chart.js/src/core/core.animation.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; /* global window: false */ module.exports = function(Chart) { var helpers = Chart.helpers; Chart.defaults.global.animation = { duration: 1000, easing: 'easeOutQuart', onProgress: helpers.noop, onComplete: helpers.noop }; Chart.Animation = Chart.Element.extend({ chart: null, // the animation associated chart instance currentStep: 0, // the current animation step numSteps: 60, // default number of steps easing: '', // the easing to use for this animation render: null, // render function used by the animation service onAnimationProgress: null, // user specified callback to fire on each step of the animation onAnimationComplete: null, // user specified callback to fire when the animation finishes }); Chart.animationService = { frameDuration: 17, animations: [], dropFrames: 0, request: null, /** * @param {Chart} chart - The chart to animate. * @param {Chart.Animation} animation - The animation that we will animate. * @param {Number} duration - The animation duration in ms. * @param {Boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions */ addAnimation: function(chart, animation, duration, lazy) { var animations = this.animations; var i, ilen; animation.chart = chart; if (!lazy) { chart.animating = true; } for (i=0, ilen=animations.length; i < ilen; ++i) { if (animations[i].chart === chart) { animations[i] = animation; return; } } animations.push(animation); // If there are no animations queued, manually kickstart a digest, for lack of a better word if (animations.length === 1) { this.requestAnimationFrame(); } }, cancelAnimation: function(chart) { var index = helpers.findIndex(this.animations, function(animation) { return animation.chart === chart; }); if (index !== -1) { this.animations.splice(index, 1); chart.animating = false; } }, requestAnimationFrame: function() { var me = this; if (me.request === null) { // Skip animation frame requests until the active one is executed. // This can happen when processing mouse events, e.g. 'mousemove' // and 'mouseout' events will trigger multiple renders. me.request = helpers.requestAnimFrame.call(window, function() { me.request = null; me.startDigest(); }); } }, /** * @private */ startDigest: function() { var me = this; var startTime = Date.now(); var framesToDrop = 0; if (me.dropFrames > 1) { framesToDrop = Math.floor(me.dropFrames); me.dropFrames = me.dropFrames % 1; } me.advance(1 + framesToDrop); var endTime = Date.now(); me.dropFrames += (endTime - startTime) / me.frameDuration; // Do we have more stuff to animate? if (me.animations.length > 0) { me.requestAnimationFrame(); } }, /** * @private */ advance: function(count) { var animations = this.animations; var animation, chart; var i = 0; while (i < animations.length) { animation = animations[i]; chart = animation.chart; animation.currentStep = (animation.currentStep || 0) + count; animation.currentStep = Math.min(animation.currentStep, animation.numSteps); helpers.callback(animation.render, [chart, animation], chart); helpers.callback(animation.onAnimationProgress, [animation], chart); if (animation.currentStep >= animation.numSteps) { helpers.callback(animation.onAnimationComplete, [animation], chart); chart.animating = false; animations.splice(i, 1); } else { ++i; } } } }; /** * Provided for backward compatibility, use Chart.Animation instead * @prop Chart.Animation#animationObject * @deprecated since version 2.6.0 * @todo remove at version 3 */ Object.defineProperty(Chart.Animation.prototype, 'animationObject', { get: function() { return this; } }); /** * Provided for backward compatibility, use Chart.Animation#chart instead * @prop Chart.Animation#chartInstance * @deprecated since version 2.6.0 * @todo remove at version 3 */ Object.defineProperty(Chart.Animation.prototype, 'chartInstance', { get: function() { return this.chart; }, set: function(value) { this.chart = value; } }); }; /***/ }), /***/ "../../../../chart.js/src/core/core.canvasHelpers.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { // Global Chart canvas helpers object for drawing items to canvas var helpers = Chart.canvasHelpers = {}; helpers.drawPoint = function(ctx, pointStyle, radius, x, y) { var type, edgeLength, xOffset, yOffset, height, size; if (typeof pointStyle === 'object') { type = pointStyle.toString(); if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { ctx.drawImage(pointStyle, x - pointStyle.width / 2, y - pointStyle.height / 2, pointStyle.width, pointStyle.height); return; } } if (isNaN(radius) || radius <= 0) { return; } switch (pointStyle) { // Default includes circle default: ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); break; case 'triangle': ctx.beginPath(); edgeLength = 3 * radius / Math.sqrt(3); height = edgeLength * Math.sqrt(3) / 2; ctx.moveTo(x - edgeLength / 2, y + height / 3); ctx.lineTo(x + edgeLength / 2, y + height / 3); ctx.lineTo(x, y - 2 * height / 3); ctx.closePath(); ctx.fill(); break; case 'rect': size = 1 / Math.SQRT2 * radius; ctx.beginPath(); ctx.fillRect(x - size, y - size, 2 * size, 2 * size); ctx.strokeRect(x - size, y - size, 2 * size, 2 * size); break; case 'rectRounded': var offset = radius / Math.SQRT2; var leftX = x - offset; var topY = y - offset; var sideSize = Math.SQRT2 * radius; Chart.helpers.drawRoundedRectangle(ctx, leftX, topY, sideSize, sideSize, radius / 2); ctx.fill(); break; case 'rectRot': size = 1 / Math.SQRT2 * radius; ctx.beginPath(); ctx.moveTo(x - size, y); ctx.lineTo(x, y + size); ctx.lineTo(x + size, y); ctx.lineTo(x, y - size); ctx.closePath(); ctx.fill(); break; case 'cross': ctx.beginPath(); ctx.moveTo(x, y + radius); ctx.lineTo(x, y - radius); ctx.moveTo(x - radius, y); ctx.lineTo(x + radius, y); ctx.closePath(); break; case 'crossRot': ctx.beginPath(); xOffset = Math.cos(Math.PI / 4) * radius; yOffset = Math.sin(Math.PI / 4) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.moveTo(x - xOffset, y + yOffset); ctx.lineTo(x + xOffset, y - yOffset); ctx.closePath(); break; case 'star': ctx.beginPath(); ctx.moveTo(x, y + radius); ctx.lineTo(x, y - radius); ctx.moveTo(x - radius, y); ctx.lineTo(x + radius, y); xOffset = Math.cos(Math.PI / 4) * radius; yOffset = Math.sin(Math.PI / 4) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.moveTo(x - xOffset, y + yOffset); ctx.lineTo(x + xOffset, y - yOffset); ctx.closePath(); break; case 'line': ctx.beginPath(); ctx.moveTo(x - radius, y); ctx.lineTo(x + radius, y); ctx.closePath(); break; case 'dash': ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + radius, y); ctx.closePath(); break; } ctx.stroke(); }; helpers.clipArea = function(ctx, clipArea) { ctx.save(); ctx.beginPath(); ctx.rect(clipArea.left, clipArea.top, clipArea.right - clipArea.left, clipArea.bottom - clipArea.top); ctx.clip(); }; helpers.unclipArea = function(ctx) { ctx.restore(); }; helpers.lineTo = function(ctx, previous, target, flip) { if (target.steppedLine) { if (target.steppedLine === 'after') { ctx.lineTo(previous.x, target.y); } else { ctx.lineTo(target.x, previous.y); } ctx.lineTo(target.x, target.y); return; } if (!target.tension) { ctx.lineTo(target.x, target.y); return; } ctx.bezierCurveTo( flip? previous.controlPointPreviousX : previous.controlPointNextX, flip? previous.controlPointPreviousY : previous.controlPointNextY, flip? target.controlPointNextX : target.controlPointPreviousX, flip? target.controlPointNextY : target.controlPointPreviousY, target.x, target.y); }; Chart.helpers.canvas = helpers; }; /***/ }), /***/ "../../../../chart.js/src/core/core.controller.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function(Chart) { var helpers = Chart.helpers; var plugins = Chart.plugins; var platform = Chart.platform; // Create a dictionary of chart types, to allow for extension of existing types Chart.types = {}; // Store a reference to each instance - allowing us to globally resize chart instances on window resize. // Destroy method on the chart will remove the instance of the chart from this reference. Chart.instances = {}; // Controllers available for dataset visualization eg. bar, line, slice, etc. Chart.controllers = {}; /** * Initializes the given config with global and chart default values. */ function initConfig(config) { config = config || {}; // Do NOT use configMerge() for the data object because this method merges arrays // and so would change references to labels and datasets, preventing data updates. var data = config.data = config.data || {}; data.datasets = data.datasets || []; data.labels = data.labels || []; config.options = helpers.configMerge( Chart.defaults.global, Chart.defaults[config.type], config.options || {}); return config; } /** * Updates the config of the chart * @param chart {Chart} chart to update the options for */ function updateConfig(chart) { var newOptions = chart.options; // Update Scale(s) with options if (newOptions.scale) { chart.scale.options = newOptions.scale; } else if (newOptions.scales) { newOptions.scales.xAxes.concat(newOptions.scales.yAxes).forEach(function(scaleOptions) { chart.scales[scaleOptions.id].options = scaleOptions; }); } // Tooltip chart.tooltip._options = newOptions.tooltips; } function positionIsHorizontal(position) { return position === 'top' || position === 'bottom'; } helpers.extend(Chart.prototype, /** @lends Chart */ { /** * @private */ construct: function(item, config) { var me = this; config = initConfig(config); var context = platform.acquireContext(item, config); var canvas = context && context.canvas; var height = canvas && canvas.height; var width = canvas && canvas.width; me.id = helpers.uid(); me.ctx = context; me.canvas = canvas; me.config = config; me.width = width; me.height = height; me.aspectRatio = height? width / height : null; me.options = config.options; me._bufferedRender = false; /** * Provided for backward compatibility, Chart and Chart.Controller have been merged, * the "instance" still need to be defined since it might be called from plugins. * @prop Chart#chart * @deprecated since version 2.6.0 * @todo remove at version 3 * @private */ me.chart = me; me.controller = me; // chart.chart.controller #inception // Add the chart instance to the global namespace Chart.instances[me.id] = me; // Define alias to the config data: `chart.data === chart.config.data` Object.defineProperty(me, 'data', { get: function() { return me.config.data; }, set: function(value) { me.config.data = value; } }); if (!context || !canvas) { // The given item is not a compatible context2d element, let's return before finalizing // the chart initialization but after setting basic chart / controller properties that // can help to figure out that the chart is not valid (e.g chart.canvas !== null); // https://github.com/chartjs/Chart.js/issues/2807 console.error("Failed to create chart: can't acquire context from the given item"); return; } me.initialize(); me.update(); }, /** * @private */ initialize: function() { var me = this; // Before init plugin notification plugins.notify(me, 'beforeInit'); helpers.retinaScale(me); me.bindEvents(); if (me.options.responsive) { // Initial resize before chart draws (must be silent to preserve initial animations). me.resize(true); } // Make sure scales have IDs and are built before we build any controllers. me.ensureScalesHaveIDs(); me.buildScales(); me.initToolTip(); // After init plugin notification plugins.notify(me, 'afterInit'); return me; }, clear: function() { helpers.clear(this); return this; }, stop: function() { // Stops any current animation loop occurring Chart.animationService.cancelAnimation(this); return this; }, resize: function(silent) { var me = this; var options = me.options; var canvas = me.canvas; var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null; // the canvas render width and height will be casted to integers so make sure that // the canvas display style uses the same integer values to avoid blurring effect. var newWidth = Math.floor(helpers.getMaximumWidth(canvas)); var newHeight = Math.floor(aspectRatio? newWidth / aspectRatio : helpers.getMaximumHeight(canvas)); if (me.width === newWidth && me.height === newHeight) { return; } canvas.width = me.width = newWidth; canvas.height = me.height = newHeight; canvas.style.width = newWidth + 'px'; canvas.style.height = newHeight + 'px'; helpers.retinaScale(me); if (!silent) { // Notify any plugins about the resize var newSize = {width: newWidth, height: newHeight}; plugins.notify(me, 'resize', [newSize]); // Notify of resize if (me.options.onResize) { me.options.onResize(me, newSize); } me.stop(); me.update(me.options.responsiveAnimationDuration); } }, ensureScalesHaveIDs: function() { var options = this.options; var scalesOptions = options.scales || {}; var scaleOptions = options.scale; helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) { xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index); }); helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) { yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index); }); if (scaleOptions) { scaleOptions.id = scaleOptions.id || 'scale'; } }, /** * Builds a map of scale ID to scale object for future lookup. */ buildScales: function() { var me = this; var options = me.options; var scales = me.scales = {}; var items = []; if (options.scales) { items = items.concat( (options.scales.xAxes || []).map(function(xAxisOptions) { return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'}; }), (options.scales.yAxes || []).map(function(yAxisOptions) { return {options: yAxisOptions, dtype: 'linear', dposition: 'left'}; }) ); } if (options.scale) { items.push({ options: options.scale, dtype: 'radialLinear', isDefault: true, dposition: 'chartArea' }); } helpers.each(items, function(item) { var scaleOptions = item.options; var scaleType = helpers.getValueOrDefault(scaleOptions.type, item.dtype); var scaleClass = Chart.scaleService.getScaleConstructor(scaleType); if (!scaleClass) { return; } if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) { scaleOptions.position = item.dposition; } var scale = new scaleClass({ id: scaleOptions.id, options: scaleOptions, ctx: me.ctx, chart: me }); scales[scale.id] = scale; // TODO(SB): I think we should be able to remove this custom case (options.scale) // and consider it as a regular scale part of the "scales"" map only! This would // make the logic easier and remove some useless? custom code. if (item.isDefault) { me.scale = scale; } }); Chart.scaleService.addScalesToLayout(this); }, buildOrUpdateControllers: function() { var me = this; var types = []; var newControllers = []; helpers.each(me.data.datasets, function(dataset, datasetIndex) { var meta = me.getDatasetMeta(datasetIndex); if (!meta.type) { meta.type = dataset.type || me.config.type; } types.push(meta.type); if (meta.controller) { meta.controller.updateIndex(datasetIndex); } else { var ControllerClass = Chart.controllers[meta.type]; if (ControllerClass === undefined) { throw new Error('"' + meta.type + '" is not a chart type.'); } meta.controller = new ControllerClass(me, datasetIndex); newControllers.push(meta.controller); } }, me); if (types.length > 1) { for (var i = 1; i < types.length; i++) { if (types[i] !== types[i - 1]) { me.isCombo = true; break; } } } return newControllers; }, /** * Reset the elements of all datasets * @private */ resetElements: function() { var me = this; helpers.each(me.data.datasets, function(dataset, datasetIndex) { me.getDatasetMeta(datasetIndex).controller.reset(); }, me); }, /** * Resets the chart back to it's state before the initial animation */ reset: function() { this.resetElements(); this.tooltip.initialize(); }, update: function(animationDuration, lazy) { var me = this; updateConfig(me); if (plugins.notify(me, 'beforeUpdate') === false) { return; } // In case the entire data object changed me.tooltip._data = me.data; // Make sure dataset controllers are updated and new controllers are reset var newControllers = me.buildOrUpdateControllers(); // Make sure all dataset controllers have correct meta data counts helpers.each(me.data.datasets, function(dataset, datasetIndex) { me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements(); }, me); me.updateLayout(); // Can only reset the new controllers after the scales have been updated helpers.each(newControllers, function(controller) { controller.reset(); }); me.updateDatasets(); // Do this before render so that any plugins that need final scale updates can use it plugins.notify(me, 'afterUpdate'); if (me._bufferedRender) { me._bufferedRequest = { lazy: lazy, duration: animationDuration }; } else { me.render(animationDuration, lazy); } }, /** * Updates the chart layout unless a plugin returns `false` to the `beforeLayout` * hook, in which case, plugins will not be called on `afterLayout`. * @private */ updateLayout: function() { var me = this; if (plugins.notify(me, 'beforeLayout') === false) { return; } Chart.layoutService.update(this, this.width, this.height); /** * Provided for backward compatibility, use `afterLayout` instead. * @method IPlugin#afterScaleUpdate * @deprecated since version 2.5.0 * @todo remove at version 3 * @private */ plugins.notify(me, 'afterScaleUpdate'); plugins.notify(me, 'afterLayout'); }, /** * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate` * hook, in which case, plugins will not be called on `afterDatasetsUpdate`. * @private */ updateDatasets: function() { var me = this; if (plugins.notify(me, 'beforeDatasetsUpdate') === false) { return; } for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { me.updateDataset(i); } plugins.notify(me, 'afterDatasetsUpdate'); }, /** * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate` * hook, in which case, plugins will not be called on `afterDatasetUpdate`. * @private */ updateDataset: function(index) { var me = this; var meta = me.getDatasetMeta(index); var args = { meta: meta, index: index }; if (plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) { return; } meta.controller.update(); plugins.notify(me, 'afterDatasetUpdate', [args]); }, render: function(duration, lazy) { var me = this; if (plugins.notify(me, 'beforeRender') === false) { return; } var animationOptions = me.options.animation; var onComplete = function(animation) { plugins.notify(me, 'afterRender'); helpers.callback(animationOptions && animationOptions.onComplete, [animation], me); }; if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) { var animation = new Chart.Animation({ numSteps: (duration || animationOptions.duration) / 16.66, // 60 fps easing: animationOptions.easing, render: function(chart, animationObject) { var easingFunction = helpers.easingEffects[animationObject.easing]; var currentStep = animationObject.currentStep; var stepDecimal = currentStep / animationObject.numSteps; chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep); }, onAnimationProgress: animationOptions.onProgress, onAnimationComplete: onComplete }); Chart.animationService.addAnimation(me, animation, duration, lazy); } else { me.draw(); // See https://github.com/chartjs/Chart.js/issues/3781 onComplete(new Chart.Animation({numSteps: 0, chart: me})); } return me; }, draw: function(easingValue) { var me = this; me.clear(); if (easingValue === undefined || easingValue === null) { easingValue = 1; } me.transition(easingValue); if (plugins.notify(me, 'beforeDraw', [easingValue]) === false) { return; } // Draw all the scales helpers.each(me.boxes, function(box) { box.draw(me.chartArea); }, me); if (me.scale) { me.scale.draw(); } me.drawDatasets(easingValue); // Finally draw the tooltip me.tooltip.draw(); plugins.notify(me, 'afterDraw', [easingValue]); }, /** * @private */ transition: function(easingValue) { var me = this; for (var i=0, ilen=(me.data.datasets || []).length; i= 0; --i) { if (me.isDatasetVisible(i)) { me.drawDataset(i, easingValue); } } plugins.notify(me, 'afterDatasetsDraw', [easingValue]); }, /** * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw` * hook, in which case, plugins will not be called on `afterDatasetDraw`. * @private */ drawDataset: function(index, easingValue) { var me = this; var meta = me.getDatasetMeta(index); var args = { meta: meta, index: index, easingValue: easingValue }; if (plugins.notify(me, 'beforeDatasetDraw', [args]) === false) { return; } meta.controller.draw(easingValue); plugins.notify(me, 'afterDatasetDraw', [args]); }, // Get the single element that was clicked on // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw getElementAtEvent: function(e) { return Chart.Interaction.modes.single(this, e); }, getElementsAtEvent: function(e) { return Chart.Interaction.modes.label(this, e, {intersect: true}); }, getElementsAtXAxis: function(e) { return Chart.Interaction.modes['x-axis'](this, e, {intersect: true}); }, getElementsAtEventForMode: function(e, mode, options) { var method = Chart.Interaction.modes[mode]; if (typeof method === 'function') { return method(this, e, options); } return []; }, getDatasetAtEvent: function(e) { return Chart.Interaction.modes.dataset(this, e, {intersect: true}); }, getDatasetMeta: function(datasetIndex) { var me = this; var dataset = me.data.datasets[datasetIndex]; if (!dataset._meta) { dataset._meta = {}; } var meta = dataset._meta[me.id]; if (!meta) { meta = dataset._meta[me.id] = { type: null, data: [], dataset: null, controller: null, hidden: null, // See isDatasetVisible() comment xAxisID: null, yAxisID: null }; } return meta; }, getVisibleDatasetCount: function() { var count = 0; for (var i = 0, ilen = this.data.datasets.length; i