(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["chunk-vendors"],{ /***/ "0012": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("a7b2").Observable; /***/ }), /***/ "00ef": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/types/Auth.js /* * Copyright 2017-2017 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 CognitoHostedUIIdentityProvider; (function (CognitoHostedUIIdentityProvider) { CognitoHostedUIIdentityProvider["Cognito"] = "COGNITO"; CognitoHostedUIIdentityProvider["Google"] = "Google"; CognitoHostedUIIdentityProvider["Facebook"] = "Facebook"; CognitoHostedUIIdentityProvider["Amazon"] = "LoginWithAmazon"; })(CognitoHostedUIIdentityProvider || (CognitoHostedUIIdentityProvider = {})); function isFederatedSignInOptions(obj) { var keys = ['provider', 'customState']; return obj && !!keys.find(function (k) { return obj.hasOwnProperty(k); }); } function isFederatedSignInOptionsCustom(obj) { var keys = [ 'customProvider', 'customState', ]; return obj && !!keys.find(function (k) { return obj.hasOwnProperty(k); }); } function isCognitoHostedOpts(oauth) { return oauth.redirectSignIn !== undefined; } var AuthErrorTypes; (function (AuthErrorTypes) { AuthErrorTypes["NoConfig"] = "noConfig"; AuthErrorTypes["MissingAuthConfig"] = "missingAuthConfig"; AuthErrorTypes["EmptyUsername"] = "emptyUsername"; AuthErrorTypes["InvalidUsername"] = "invalidUsername"; AuthErrorTypes["EmptyPassword"] = "emptyPassword"; AuthErrorTypes["EmptyCode"] = "emptyCode"; AuthErrorTypes["SignUpError"] = "signUpError"; AuthErrorTypes["NoMFA"] = "noMFA"; AuthErrorTypes["InvalidMFA"] = "invalidMFA"; AuthErrorTypes["EmptyChallengeResponse"] = "emptyChallengeResponse"; AuthErrorTypes["NoUserSession"] = "noUserSession"; AuthErrorTypes["Default"] = "default"; })(AuthErrorTypes || (AuthErrorTypes = {})); function isUsernamePasswordOpts(obj) { return !!obj.username; } //# sourceMappingURL=Auth.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/types/index.js /* * Copyright 2017-2017 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. */ //# sourceMappingURL=index.js.map // EXTERNAL MODULE: ./node_modules/aws-sdk/browser.js var browser = __webpack_require__("31ce"); // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Facet.js /* * Copyright 2017-2017 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. */ // import * as S3 from 'aws-sdk/clients/s3'; // import * as Pinpoint from 'aws-sdk/clients/pinpoint'; // import * as Kinesis from 'aws-sdk/clients/kinesis'; // import * as MobileAnalytics from 'aws-sdk/clients/mobileanalytics'; // export {AWS, S3, Pinpoint, MobileAnalytics, Kinesis }; //# sourceMappingURL=Facet.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js /* * Copyright 2017-2019 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 __spreadArrays = (undefined && undefined.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; var LOG_LEVELS = { VERBOSE: 1, DEBUG: 2, INFO: 3, WARN: 4, ERROR: 5, }; /** * Write logs * @class Logger */ var ConsoleLogger = /** @class */ (function () { /** * @constructor * @param {string} name - Name of the logger */ function ConsoleLogger(name, level) { if (level === void 0) { level = 'WARN'; } this.name = name; this.level = level; } ConsoleLogger.prototype._padding = function (n) { return n < 10 ? '0' + n : '' + n; }; ConsoleLogger.prototype._ts = function () { var dt = new Date(); return ([this._padding(dt.getMinutes()), this._padding(dt.getSeconds())].join(':') + '.' + dt.getMilliseconds()); }; /** * Write log * @method * @memeberof Logger * @param {string} type - log type, default INFO * @param {string|object} msg - Logging message or object */ ConsoleLogger.prototype._log = function (type) { var msg = []; for (var _i = 1; _i < arguments.length; _i++) { msg[_i - 1] = arguments[_i]; } var logger_level_name = this.level; if (ConsoleLogger.LOG_LEVEL) { logger_level_name = ConsoleLogger.LOG_LEVEL; } if (typeof window !== 'undefined' && window.LOG_LEVEL) { logger_level_name = window.LOG_LEVEL; } var logger_level = LOG_LEVELS[logger_level_name]; var type_level = LOG_LEVELS[type]; if (!(type_level >= logger_level)) { // Do nothing if type is not greater than or equal to logger level (handle undefined) return; } var log = console.log.bind(console); if (type === 'ERROR' && console.error) { log = console.error.bind(console); } if (type === 'WARN' && console.warn) { log = console.warn.bind(console); } var prefix = "[" + type + "] " + this._ts() + " " + this.name; if (msg.length === 1 && typeof msg[0] === 'string') { log(prefix + " - " + msg[0]); } else if (msg.length === 1) { log(prefix, msg[0]); } else if (typeof msg[0] === 'string') { var obj = msg.slice(1); if (obj.length === 1) { obj = obj[0]; } log(prefix + " - " + msg[0], obj); } else { log(prefix, msg); } }; /** * Write General log. Default to INFO * @method * @memeberof Logger * @param {string|object} msg - Logging message or object */ ConsoleLogger.prototype.log = function () { var msg = []; for (var _i = 0; _i < arguments.length; _i++) { msg[_i] = arguments[_i]; } this._log.apply(this, __spreadArrays(['INFO'], msg)); }; /** * Write INFO log * @method * @memeberof Logger * @param {string|object} msg - Logging message or object */ ConsoleLogger.prototype.info = function () { var msg = []; for (var _i = 0; _i < arguments.length; _i++) { msg[_i] = arguments[_i]; } this._log.apply(this, __spreadArrays(['INFO'], msg)); }; /** * Write WARN log * @method * @memeberof Logger * @param {string|object} msg - Logging message or object */ ConsoleLogger.prototype.warn = function () { var msg = []; for (var _i = 0; _i < arguments.length; _i++) { msg[_i] = arguments[_i]; } this._log.apply(this, __spreadArrays(['WARN'], msg)); }; /** * Write ERROR log * @method * @memeberof Logger * @param {string|object} msg - Logging message or object */ ConsoleLogger.prototype.error = function () { var msg = []; for (var _i = 0; _i < arguments.length; _i++) { msg[_i] = arguments[_i]; } this._log.apply(this, __spreadArrays(['ERROR'], msg)); }; /** * Write DEBUG log * @method * @memeberof Logger * @param {string|object} msg - Logging message or object */ ConsoleLogger.prototype.debug = function () { var msg = []; for (var _i = 0; _i < arguments.length; _i++) { msg[_i] = arguments[_i]; } this._log.apply(this, __spreadArrays(['DEBUG'], msg)); }; /** * Write VERBOSE log * @method * @memeberof Logger * @param {string|object} msg - Logging message or object */ ConsoleLogger.prototype.verbose = function () { var msg = []; for (var _i = 0; _i < arguments.length; _i++) { msg[_i] = arguments[_i]; } this._log.apply(this, __spreadArrays(['VERBOSE'], msg)); }; ConsoleLogger.LOG_LEVEL = null; return ConsoleLogger; }()); //# sourceMappingURL=ConsoleLogger.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Logger/index.js /* * Copyright 2017-2017 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. */ //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Amplify.js var logger = new ConsoleLogger('Amplify'); var Amplify_Amplify = /** @class */ (function () { function Amplify() { } Amplify.register = function (comp) { logger.debug('component registered in amplify', comp); this._components.push(comp); if (typeof comp.getModuleName === 'function') { Amplify[comp.getModuleName()] = comp; } else { logger.debug('no getModuleName method for component', comp); } }; Amplify.configure = function (config) { var _this = this; if (!config) return this._config; this._config = Object.assign(this._config, config); logger.debug('amplify config', this._config); this._components.map(function (comp) { comp.configure(_this._config); }); return this._config; }; Amplify.addPluggable = function (pluggable) { if (pluggable && pluggable['getCategory'] && typeof pluggable['getCategory'] === 'function') { this._components.map(function (comp) { if (comp['addPluggable'] && typeof comp['addPluggable'] === 'function') { comp.addPluggable(pluggable); } }); } }; Amplify._components = []; Amplify._config = {}; // for backward compatibility to avoid breaking change // if someone is using like Amplify.Auth Amplify.Auth = null; Amplify.Analytics = null; Amplify.API = null; Amplify.Storage = null; Amplify.I18n = null; Amplify.Cache = null; Amplify.PubSub = null; Amplify.Interactions = null; Amplify.Pushnotification = null; Amplify.UI = null; Amplify.XR = null; Amplify.Predictions = null; Amplify.Logger = ConsoleLogger; Amplify.ServiceWorker = null; return Amplify; }()); /* harmony default export */ var lib_esm_Amplify = (Amplify_Amplify); //# sourceMappingURL=Amplify.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/ClientDevice/browser.js /* * Copyright 2017-2017 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 browser_logger = new ConsoleLogger('ClientDevice_Browser'); function clientInfo() { if (typeof window === 'undefined') { return {}; } return browserClientInfo(); } function browserClientInfo() { if (typeof window === 'undefined') { browser_logger.warn('No window object available to get browser client info'); return {}; } var nav = window.navigator; if (!nav) { browser_logger.warn('No navigator object available to get browser client info'); return {}; } var platform = nav.platform, product = nav.product, vendor = nav.vendor, userAgent = nav.userAgent, language = nav.language; var type = browserType(userAgent); var timezone = browserTimezone(); return { platform: platform, make: product || vendor, model: type.type, version: type.version, appVersion: [type.type, type.version].join('/'), language: language, timezone: timezone, }; } function dimension() { if (typeof window === 'undefined') { browser_logger.warn('No window object available to get browser client info'); return { width: 320, height: 320 }; } return { width: window.innerWidth, height: window.innerHeight, }; } function browserTimezone() { var tzMatch = /\(([A-Za-z\s].*)\)/.exec(new Date().toString()); return tzMatch ? tzMatch[1] || '' : ''; } function browserType(userAgent) { var operaMatch = /.+(Opera[\s[A-Z]*|OPR[\sA-Z]*)\/([0-9\.]+).*/i.exec(userAgent); if (operaMatch) { return { type: operaMatch[1], version: operaMatch[2] }; } var ieMatch = /.+(Trident|Edge)\/([0-9\.]+).*/i.exec(userAgent); if (ieMatch) { return { type: ieMatch[1], version: ieMatch[2] }; } var cfMatch = /.+(Chrome|Firefox|FxiOS)\/([0-9\.]+).*/i.exec(userAgent); if (cfMatch) { return { type: cfMatch[1], version: cfMatch[2] }; } var sMatch = /.+(Safari)\/([0-9\.]+).*/i.exec(userAgent); if (sMatch) { return { type: sMatch[1], version: sMatch[2] }; } var awkMatch = /.+(AppleWebKit)\/([0-9\.]+).*/i.exec(userAgent); if (awkMatch) { return { type: awkMatch[1], version: awkMatch[2] }; } var anyMatch = /.*([A-Z]+)\/([0-9\.]+).*/i.exec(userAgent); if (anyMatch) { return { type: anyMatch[1], version: anyMatch[2] }; } return { type: '', version: '' }; } //# sourceMappingURL=browser.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/ClientDevice/index.js /* * Copyright 2017-2017 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 ClientDevice_ClientDevice = /** @class */ (function () { function ClientDevice() { } ClientDevice.clientInfo = function () { return clientInfo(); }; ClientDevice.dimension = function () { return dimension(); }; return ClientDevice; }()); /* harmony default export */ var lib_esm_ClientDevice = (ClientDevice_ClientDevice); //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Errors.js /* * Copyright 2017-2017 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. */ function missingConfig(name) { return new Error('Missing config value of ' + name); } function invalidParameter(name) { return new Error('Invalid parameter value of ' + name); } //# sourceMappingURL=Errors.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Hub.js /* * Copyright 2017-2017 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 __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var Hub_spreadArrays = (undefined && undefined.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; var Hub_logger = new ConsoleLogger('Hub'); var AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function' ? Symbol.for('amplify_default') : '@@amplify_default'); function isLegacyCallback(callback) { return callback.onHubCapsule !== undefined; } var HubClass = /** @class */ (function () { function HubClass(name) { this.listeners = []; this.patterns = []; this.protectedChannels = [ 'core', 'auth', 'api', 'analytics', 'interactions', 'pubsub', 'storage', 'xr', ]; this.name = name; } // Note - Need to pass channel as a reference for removal to work and not anonymous function HubClass.prototype.remove = function (channel, listener) { if (channel instanceof RegExp) { var pattern_1 = this.patterns.find(function (_a) { var pattern = _a.pattern; return pattern.source === channel.source; }); if (!pattern_1) { Hub_logger.warn("No listeners for " + channel); return; } this.patterns = Hub_spreadArrays(this.patterns.filter(function (x) { return x !== pattern_1; })); } else { var holder = this.listeners[channel]; if (!holder) { Hub_logger.warn("No listeners for " + channel); return; } this.listeners[channel] = Hub_spreadArrays(holder.filter(function (_a) { var callback = _a.callback; return callback !== listener; })); } }; HubClass.prototype.dispatch = function (channel, payload, source, ampSymbol) { if (source === void 0) { source = ''; } if (this.protectedChannels.indexOf(channel) > -1) { var hasAccess = ampSymbol === AMPLIFY_SYMBOL; if (!hasAccess) { Hub_logger.warn("WARNING: " + channel + " is protected and dispatching on it can have unintended consequences"); } } var capsule = { channel: channel, payload: __assign({}, payload), source: source, patternInfo: [], }; try { this._toListeners(capsule); } catch (e) { Hub_logger.error(e); } }; HubClass.prototype.listen = function (channel, callback, listenerName) { if (listenerName === void 0) { listenerName = 'noname'; } var cb; // Check for legacy onHubCapsule callback for backwards compatability if (isLegacyCallback(callback)) { Hub_logger.warn("WARNING onHubCapsule is Deprecated. Please pass in a callback."); cb = callback.onHubCapsule.bind(callback); } else if (typeof callback !== 'function') { throw new Error('No callback supplied to Hub'); } else { cb = callback; } if (channel instanceof RegExp) { this.patterns.push({ pattern: channel, callback: cb, }); } else { var holder = this.listeners[channel]; if (!holder) { holder = []; this.listeners[channel] = holder; } holder.push({ name: listenerName, callback: cb, }); } }; HubClass.prototype._toListeners = function (capsule) { var channel = capsule.channel, payload = capsule.payload; var holder = this.listeners[channel]; if (holder) { holder.forEach(function (listener) { Hub_logger.debug("Dispatching to " + channel + " with ", payload); try { listener.callback(capsule); } catch (e) { Hub_logger.error(e); } }); } if (this.patterns.length > 0) { if (!payload.message) { Hub_logger.warn("Cannot perform pattern matching without a message key"); return; } var payloadStr_1 = payload.message; this.patterns.forEach(function (pattern) { var match = payloadStr_1.match(pattern.pattern); if (match) { var groups = match.slice(1); var dispatchingCapsule = __assign(__assign({}, capsule), { patternInfo: groups }); try { pattern.callback(dispatchingCapsule); } catch (e) { Hub_logger.error(e); } } }); } }; return HubClass; }()); /*We export a __default__ instance of HubClass to use it as a psuedo Singleton for the main messaging bus, however you can still create your own instance of HubClass() for a separate "private bus" of events.*/ var Hub = new HubClass('__default__'); /* harmony default export */ var lib_esm_Hub = (Hub); //# sourceMappingURL=Hub.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/I18n/I18n.js /* * Copyright 2017-2017 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 I18n_logger = new ConsoleLogger('I18n'); /** * Language transition class */ var I18n_I18n = /** @class */ (function () { /** * @constructor * Initialize with configurations * @param {Object} options */ function I18n(options) { /** * @private */ this._options = null; /** * @private */ this._lang = null; /** * @private */ this._dict = {}; this._options = Object.assign({}, options); this._lang = this._options.language; if (!this._lang && typeof window !== 'undefined' && window && window.navigator) { this._lang = window.navigator.language; } I18n_logger.debug(this._lang); } /** * @method * Explicitly setting language * @param {String} lang */ I18n.prototype.setLanguage = function (lang) { this._lang = lang; }; /** * @method * Get value * @param {String} key * @param {String} defVal - Default value */ I18n.prototype.get = function (key, defVal) { if (defVal === void 0) { defVal = undefined; } if (!this._lang) { return typeof defVal !== 'undefined' ? defVal : key; } var lang = this._lang; var val = this.getByLanguage(key, lang); if (val) { return val; } if (lang.indexOf('-') > 0) { val = this.getByLanguage(key, lang.split('-')[0]); } if (val) { return val; } return typeof defVal !== 'undefined' ? defVal : key; }; /** * @method * Get value according to specified language * @param {String} key * @param {String} language - Specified langurage to be used * @param {String} defVal - Default value */ I18n.prototype.getByLanguage = function (key, language, defVal) { if (defVal === void 0) { defVal = null; } if (!language) { return defVal; } var lang_dict = this._dict[language]; if (!lang_dict) { return defVal; } return lang_dict[key]; }; /** * @method * Add vocabularies for one language * @param {String} langurage - Language of the dictionary * @param {Object} vocabularies - Object that has key-value as dictionary entry */ I18n.prototype.putVocabulariesForLanguage = function (language, vocabularies) { var lang_dict = this._dict[language]; if (!lang_dict) { lang_dict = this._dict[language] = {}; } Object.assign(lang_dict, vocabularies); }; /** * @method * Add vocabularies for one language * @param {Object} vocabularies - Object that has language as key, * vocabularies of each language as value */ I18n.prototype.putVocabularies = function (vocabularies) { var _this = this; Object.keys(vocabularies).map(function (key) { _this.putVocabulariesForLanguage(key, vocabularies[key]); }); }; return I18n; }()); //# sourceMappingURL=I18n.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/I18n/index.js /* * Copyright 2017-2017 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 lib_esm_I18n_logger = new ConsoleLogger('I18n'); var _config = null; var _i18n = null; /** * Export I18n APIs */ var lib_esm_I18n_I18n = /** @class */ (function () { function I18n() { } /** * @static * @method * Configure I18n part * @param {Object} config - Configuration of the I18n */ I18n.configure = function (config) { lib_esm_I18n_logger.debug('configure I18n'); if (!config) { return _config; } _config = Object.assign({}, _config, config.I18n || config); I18n.createInstance(); return _config; }; I18n.getModuleName = function () { return 'I18n'; }; /** * @static * @method * Create an instance of I18n for the library */ I18n.createInstance = function () { lib_esm_I18n_logger.debug('create I18n instance'); if (_i18n) { return; } _i18n = new I18n_I18n(_config); }; /** * @static @method * Explicitly setting language * @param {String} lang */ I18n.setLanguage = function (lang) { I18n.checkConfig(); return _i18n.setLanguage(lang); }; /** * @static @method * Get value * @param {String} key * @param {String} defVal - Default value */ I18n.get = function (key, defVal) { if (!I18n.checkConfig()) { return typeof defVal === 'undefined' ? key : defVal; } return _i18n.get(key, defVal); }; /** * @static * @method * Add vocabularies for one language * @param {String} langurage - Language of the dictionary * @param {Object} vocabularies - Object that has key-value as dictionary entry */ I18n.putVocabulariesForLanguage = function (language, vocabularies) { I18n.checkConfig(); return _i18n.putVocabulariesForLanguage(language, vocabularies); }; /** * @static * @method * Add vocabularies for one language * @param {Object} vocabularies - Object that has language as key, * vocabularies of each language as value */ I18n.putVocabularies = function (vocabularies) { I18n.checkConfig(); return _i18n.putVocabularies(vocabularies); }; I18n.checkConfig = function () { if (!_i18n) { _i18n = new I18n_I18n(_config); } return true; }; return I18n; }()); lib_esm_Amplify.register(lib_esm_I18n_I18n); /* harmony default export */ var lib_esm_I18n = (lib_esm_I18n_I18n); //# sourceMappingURL=index.js.map // EXTERNAL MODULE: ./node_modules/@aws-amplify/core/lib-esm/JS.js var JS = __webpack_require__("1f3a"); // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Signer.js /* * Copyright 2017-2017 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 Signer_assign = (undefined && undefined.__assign) || function () { Signer_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Signer_assign.apply(this, arguments); }; var __rest = (undefined && undefined.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var Signer_logger = new ConsoleLogger('Signer'), Signer_url = __webpack_require__("0b16"), Signer_crypto = browser['util'].crypto; var DEFAULT_ALGORITHM = 'AWS4-HMAC-SHA256'; var IOT_SERVICE_NAME = 'iotdevicegateway'; var encrypt = function (key, src, encoding) { return Signer_crypto.lib .createHmac('sha256', key) .update(src, 'utf8') .digest(encoding); }; var Signer_hash = function (src) { var arg = src || ''; return Signer_crypto .createHash('sha256') .update(arg, 'utf8') .digest('hex'); }; /** * @private * RFC 3986 compliant version of encodeURIComponent */ var escape_RFC3986 = function (component) { return component.replace(/[!'()*]/g, function (c) { return ('%' + c .charCodeAt(0) .toString(16) .toUpperCase()); }); }; /** * @private * Create canonical query string * */ var canonical_query = function (query) { if (!query || query.length === 0) { return ''; } return query .split('&') .map(function (e) { var key_val = e.split('='); if (key_val.length === 1) { return e; } else { var reencoded_val = escape_RFC3986(key_val[1]); return key_val[0] + '=' + reencoded_val; } }) .sort(function (a, b) { var key_a = a.split('=')[0]; var key_b = b.split('=')[0]; if (key_a === key_b) { return a < b ? -1 : 1; } else { return key_a < key_b ? -1 : 1; } }) .join('&'); }; /** * @private * Create canonical headers *
CanonicalHeaders =
    CanonicalHeadersEntry0 + CanonicalHeadersEntry1 + ... + CanonicalHeadersEntryN
CanonicalHeadersEntry =
    Lowercase(HeaderName) + ':' + Trimall(HeaderValue) + '\n'
*/ var canonical_headers = function (headers) { if (!headers || Object.keys(headers).length === 0) { return ''; } return (Object.keys(headers) .map(function (key) { return { key: key.toLowerCase(), value: headers[key] ? headers[key].trim().replace(/\s+/g, ' ') : '', }; }) .sort(function (a, b) { return a.key < b.key ? -1 : 1; }) .map(function (item) { return item.key + ':' + item.value; }) .join('\n') + '\n'); }; /** * List of header keys included in the canonical headers. * @access private */ var signed_headers = function (headers) { return Object.keys(headers) .map(function (key) { return key.toLowerCase(); }) .sort() .join(';'); }; /** * @private * Create canonical request * Refer to * {@link http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html|Create a Canonical Request} *
CanonicalRequest =
    HTTPRequestMethod + '\n' +
    CanonicalURI + '\n' +
    CanonicalQueryString + '\n' +
    CanonicalHeaders + '\n' +
    SignedHeaders + '\n' +
    HexEncode(Hash(RequestPayload))
*/ var canonical_request = function (request) { var url_info = Signer_url.parse(request.url); return [ request.method || '/', encodeURIComponent(url_info.pathname).replace(/%2F/gi, '/'), canonical_query(url_info.query), canonical_headers(request.headers), signed_headers(request.headers), Signer_hash(request.data), ].join('\n'); }; var parse_service_info = function (request) { var url_info = Signer_url.parse(request.url), host = url_info.host; var matched = host.match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/); var parsed = (matched || []).slice(1, 3); if (parsed[1] === 'es') { // Elastic Search parsed = parsed.reverse(); } return { service: request.service || parsed[0], region: request.region || parsed[1], }; }; var credential_scope = function (d_str, region, service) { return [d_str, region, service, 'aws4_request'].join('/'); }; /** * @private * Create a string to sign * Refer to * {@link http://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html|Create String to Sign} *
StringToSign =
    Algorithm + \n +
    RequestDateTime + \n +
    CredentialScope + \n +
    HashedCanonicalRequest
*/ var string_to_sign = function (algorithm, canonical_request, dt_str, scope) { return [algorithm, dt_str, scope, Signer_hash(canonical_request)].join('\n'); }; /** * @private * Create signing key * Refer to * {@link http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html|Calculate Signature} *
kSecret = your secret access key
kDate = HMAC("AWS4" + kSecret, Date)
kRegion = HMAC(kDate, Region)
kService = HMAC(kRegion, Service)
kSigning = HMAC(kService, "aws4_request")
*/ var get_signing_key = function (secret_key, d_str, service_info) { Signer_logger.debug(service_info); var k = 'AWS4' + secret_key, k_date = encrypt(k, d_str), k_region = encrypt(k_date, service_info.region), k_service = encrypt(k_region, service_info.service), k_signing = encrypt(k_service, 'aws4_request'); return k_signing; }; var get_signature = function (signing_key, str_to_sign) { return encrypt(signing_key, str_to_sign, 'hex'); }; /** * @private * Create authorization header * Refer to * {@link http://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html|Add the Signing Information} */ var get_authorization_header = function (algorithm, access_key, scope, signed_headers, signature) { return [ algorithm + ' ' + 'Credential=' + access_key + '/' + scope, 'SignedHeaders=' + signed_headers, 'Signature=' + signature, ].join(', '); }; /** * AWS request signer. * Refer to {@link http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html|Signature Version 4} * * @class Signer */ var Signer = /** @class */ (function () { function Signer() { } /** * Sign a HTTP request, add 'Authorization' header to request param * @method sign * @memberof Signer * @static * * @param {object} request - HTTP request object
    request: {
        method: GET | POST | PUT ...
        url: ...,
        headers: {
            header1: ...
        },
        data: data
    }
    
* @param {object} access_info - AWS access credential info
    access_info: {
        access_key: ...,
        secret_key: ...,
        session_token: ...
    }
    
* @param {object} [service_info] - AWS service type and region, optional, * if not provided then parse out from url
    service_info: {
        service: ...,
        region: ...
    }
    
* * @returns {object} Signed HTTP request */ Signer.sign = function (request, access_info, service_info) { if (service_info === void 0) { service_info = null; } request.headers = request.headers || {}; // datetime string and date string var dt = new Date(), dt_str = dt.toISOString().replace(/[:\-]|\.\d{3}/g, ''), d_str = dt_str.substr(0, 8); var url_info = Signer_url.parse(request.url); request.headers['host'] = url_info.host; request.headers['x-amz-date'] = dt_str; if (access_info.session_token) { request.headers['X-Amz-Security-Token'] = access_info.session_token; } // Task 1: Create a Canonical Request var request_str = canonical_request(request); Signer_logger.debug(request_str); // Task 2: Create a String to Sign var serviceInfo = service_info || parse_service_info(request), scope = credential_scope(d_str, serviceInfo.region, serviceInfo.service), str_to_sign = string_to_sign(DEFAULT_ALGORITHM, request_str, dt_str, scope); // Task 3: Calculate the Signature var signing_key = get_signing_key(access_info.secret_key, d_str, serviceInfo), signature = get_signature(signing_key, str_to_sign); // Task 4: Adding the Signing information to the Request var authorization_header = get_authorization_header(DEFAULT_ALGORITHM, access_info.access_key, scope, signed_headers(request.headers), signature); request.headers['Authorization'] = authorization_header; return request; }; Signer.signUrl = function (urlOrRequest, accessInfo, serviceInfo, expiration) { var urlToSign = typeof urlOrRequest === 'object' ? urlOrRequest.url : urlOrRequest; var method = typeof urlOrRequest === 'object' ? urlOrRequest.method : 'GET'; var body = typeof urlOrRequest === 'object' ? urlOrRequest.body : undefined; var now = new Date().toISOString().replace(/[:\-]|\.\d{3}/g, ''); var today = now.substr(0, 8); // Intentionally discarding search var _a = Signer_url.parse(urlToSign, true, true), search = _a.search, parsedUrl = __rest(_a, ["search"]); var host = parsedUrl.host; var signedHeaders = { host: host }; var _b = serviceInfo || parse_service_info({ url: Signer_url.format(parsedUrl) }), region = _b.region, service = _b.service; var credentialScope = credential_scope(today, region, service); // IoT service does not allow the session token in the canonical request // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html var sessionTokenRequired = accessInfo.session_token && service !== IOT_SERVICE_NAME; var queryParams = Signer_assign(Signer_assign(Signer_assign({ 'X-Amz-Algorithm': DEFAULT_ALGORITHM, 'X-Amz-Credential': [accessInfo.access_key, credentialScope].join('/'), 'X-Amz-Date': now.substr(0, 16) }, (sessionTokenRequired ? { 'X-Amz-Security-Token': "" + accessInfo.session_token } : {})), (expiration ? { 'X-Amz-Expires': "" + expiration } : {})), { 'X-Amz-SignedHeaders': Object.keys(signedHeaders).join(',') }); var canonicalRequest = canonical_request({ method: method, url: Signer_url.format(Signer_assign(Signer_assign({}, parsedUrl), { query: Signer_assign(Signer_assign({}, parsedUrl.query), queryParams) })), headers: signedHeaders, data: body, }); var stringToSign = string_to_sign(DEFAULT_ALGORITHM, canonicalRequest, now, credentialScope); var signing_key = get_signing_key(accessInfo.secret_key, today, { region: region, service: service, }); var signature = get_signature(signing_key, stringToSign); var additionalQueryParams = Signer_assign({ 'X-Amz-Signature': signature }, (accessInfo.session_token && { 'X-Amz-Security-Token': accessInfo.session_token, })); var result = Signer_url.format({ protocol: parsedUrl.protocol, slashes: true, hostname: parsedUrl.hostname, port: parsedUrl.port, pathname: parsedUrl.pathname, query: Signer_assign(Signer_assign(Signer_assign({}, parsedUrl.query), queryParams), additionalQueryParams), }); return result; }; return Signer; }()); /* harmony default export */ var lib_esm_Signer = (Signer); //# sourceMappingURL=Signer.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Parser.js var Parser_logger = new ConsoleLogger('Parser'); var Parser = /** @class */ (function () { function Parser() { } Parser.parseMobilehubConfig = function (config) { var amplifyConfig = {}; // Analytics if (config['aws_mobile_analytics_app_id']) { var Analytics = { AWSPinpoint: { appId: config['aws_mobile_analytics_app_id'], region: config['aws_mobile_analytics_app_region'], }, }; amplifyConfig.Analytics = Analytics; } // Auth if (config['aws_cognito_identity_pool_id'] || config['aws_user_pools_id']) { var Auth = { userPoolId: config['aws_user_pools_id'], userPoolWebClientId: config['aws_user_pools_web_client_id'], region: config['aws_cognito_region'], identityPoolId: config['aws_cognito_identity_pool_id'], mandatorySignIn: config['aws_mandatory_sign_in'] === 'enable' ? true : false, }; amplifyConfig.Auth = Auth; } // Storage var storageConfig; if (config['aws_user_files_s3_bucket']) { storageConfig = { AWSS3: { bucket: config['aws_user_files_s3_bucket'], region: config['aws_user_files_s3_bucket_region'], dangerouslyConnectToHttpEndpointForTesting: config['aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing'], }, }; } else { storageConfig = config ? config.Storage || config : {}; } amplifyConfig.Analytics = Object.assign({}, amplifyConfig.Analytics, config.Analytics); amplifyConfig.Auth = Object.assign({}, amplifyConfig.Auth, config.Auth); amplifyConfig.Storage = Object.assign({}, storageConfig); Parser_logger.debug('parse config', config, 'to amplifyconfig', amplifyConfig); return amplifyConfig; }; return Parser; }()); /* harmony default export */ var lib_esm_Parser = (Parser); //# sourceMappingURL=Parser.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/OAuthHelper/GoogleOAuth.js var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; /* * Copyright 2017-2017 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 GoogleOAuth_logger = new ConsoleLogger('CognitoCredentials'); var waitForInit = new Promise(function (res, rej) { if (!JS["a" /* default */].browserOrNode().isBrowser) { GoogleOAuth_logger.debug('not in the browser, directly resolved'); return res(); } var ga = window['gapi'] && window['gapi'].auth2 ? window['gapi'].auth2 : null; if (ga) { GoogleOAuth_logger.debug('google api already loaded'); return res(); } else { setTimeout(function () { return res(); }, 2000); } }); var GoogleOAuth_GoogleOAuth = /** @class */ (function () { function GoogleOAuth() { this.initialized = false; this.refreshGoogleToken = this.refreshGoogleToken.bind(this); this._refreshGoogleTokenImpl = this._refreshGoogleTokenImpl.bind(this); } GoogleOAuth.prototype.refreshGoogleToken = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!!this.initialized) return [3 /*break*/, 2]; GoogleOAuth_logger.debug('need to wait for the Google SDK loaded'); return [4 /*yield*/, waitForInit]; case 1: _a.sent(); this.initialized = true; GoogleOAuth_logger.debug('finish waiting'); _a.label = 2; case 2: return [2 /*return*/, this._refreshGoogleTokenImpl()]; } }); }); }; GoogleOAuth.prototype._refreshGoogleTokenImpl = function () { var ga = null; if (JS["a" /* default */].browserOrNode().isBrowser) ga = window['gapi'] && window['gapi'].auth2 ? window['gapi'].auth2 : null; if (!ga) { GoogleOAuth_logger.debug('no gapi auth2 available'); return Promise.reject('no gapi auth2 available'); } return new Promise(function (res, rej) { ga.getAuthInstance() .then(function (googleAuth) { if (!googleAuth) { console.log('google Auth undefiend'); rej('google Auth undefiend'); } var googleUser = googleAuth.currentUser.get(); // refresh the token if (googleUser.isSignedIn()) { GoogleOAuth_logger.debug('refreshing the google access token'); googleUser.reloadAuthResponse().then(function (authResponse) { var id_token = authResponse.id_token, expires_at = authResponse.expires_at; var profile = googleUser.getBasicProfile(); var user = { email: profile.getEmail(), name: profile.getName(), }; res({ token: id_token, expires_at: expires_at }); }); } else { rej('User is not signed in with Google'); } }) .catch(function (err) { GoogleOAuth_logger.debug('Failed to refresh google token', err); rej('Failed to refresh google token'); }); }); }; return GoogleOAuth; }()); /* harmony default export */ var OAuthHelper_GoogleOAuth = (GoogleOAuth_GoogleOAuth); //# sourceMappingURL=GoogleOAuth.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/OAuthHelper/FacebookOAuth.js var FacebookOAuth_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var FacebookOAuth_generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; /* * Copyright 2017-2017 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 FacebookOAuth_logger = new ConsoleLogger('CognitoCredentials'); var FacebookOAuth_waitForInit = new Promise(function (res, rej) { if (!JS["a" /* default */].browserOrNode().isBrowser) { FacebookOAuth_logger.debug('not in the browser, directly resolved'); return res(); } var fb = window['FB']; if (fb) { FacebookOAuth_logger.debug('FB SDK already loaded'); return res(); } else { setTimeout(function () { return res(); }, 2000); } }); var FacebookOAuth_FacebookOAuth = /** @class */ (function () { function FacebookOAuth() { this.initialized = false; this.refreshFacebookToken = this.refreshFacebookToken.bind(this); this._refreshFacebookTokenImpl = this._refreshFacebookTokenImpl.bind(this); } FacebookOAuth.prototype.refreshFacebookToken = function () { return FacebookOAuth_awaiter(this, void 0, void 0, function () { return FacebookOAuth_generator(this, function (_a) { switch (_a.label) { case 0: if (!!this.initialized) return [3 /*break*/, 2]; FacebookOAuth_logger.debug('need to wait for the Facebook SDK loaded'); return [4 /*yield*/, FacebookOAuth_waitForInit]; case 1: _a.sent(); this.initialized = true; FacebookOAuth_logger.debug('finish waiting'); _a.label = 2; case 2: return [2 /*return*/, this._refreshFacebookTokenImpl()]; } }); }); }; FacebookOAuth.prototype._refreshFacebookTokenImpl = function () { var fb = null; if (JS["a" /* default */].browserOrNode().isBrowser) fb = window['FB']; if (!fb) { FacebookOAuth_logger.debug('no fb sdk available'); return Promise.reject('no fb sdk available'); } return new Promise(function (res, rej) { fb.getLoginStatus(function (fbResponse) { if (!fbResponse || !fbResponse.authResponse) { FacebookOAuth_logger.debug('no response from facebook when refreshing the jwt token'); rej('no response from facebook when refreshing the jwt token'); } var response = fbResponse.authResponse; var accessToken = response.accessToken, expiresIn = response.expiresIn; var date = new Date(); var expires_at = expiresIn * 1000 + date.getTime(); if (!accessToken) { FacebookOAuth_logger.debug('the jwtToken is undefined'); rej('the jwtToken is undefined'); } res({ token: accessToken, expires_at: expires_at }); }, { scope: 'public_profile,email' }); }); }; return FacebookOAuth; }()); /* harmony default export */ var OAuthHelper_FacebookOAuth = (FacebookOAuth_FacebookOAuth); //# sourceMappingURL=FacebookOAuth.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/OAuthHelper/index.js /* * Copyright 2017-2017 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 lib_esm_OAuthHelper_GoogleOAuth = new OAuthHelper_GoogleOAuth(); var lib_esm_OAuthHelper_FacebookOAuth = new OAuthHelper_FacebookOAuth(); //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/StorageHelper/index.js /* * Copyright 2017-2017 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 dataMemory = {}; /** @class */ var MemoryStorage = /** @class */ (function () { function 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 (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 (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 (key) { return delete dataMemory[key]; }; /** * This is used to clear the storage * @returns {string} nothing */ MemoryStorage.clear = function () { dataMemory = {}; return dataMemory; }; return MemoryStorage; }()); var StorageHelper = /** @class */ (function () { /** * This is used to get a storage object * @returns {object} the storage */ function StorageHelper() { try { this.storageWindow = window.localStorage; this.storageWindow.setItem('aws.amplify.test-ls', 1); this.storageWindow.removeItem('aws.amplify.test-ls'); } catch (exception) { this.storageWindow = MemoryStorage; } } /** * This is used to return the storage * @returns {object} the storage */ StorageHelper.prototype.getStorage = function () { return this.storageWindow; }; return StorageHelper; }()); /* harmony default export */ var lib_esm_StorageHelper = (StorageHelper); //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/RNComponents/index.js /* * Copyright 2017-2017 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 Linking = {}; var AppState = { addEventListener: function (action, handler) { return; }, }; // if not in react native, just use local storage var AsyncStorage = JS["a" /* default */].browserOrNode().isBrowser ? new lib_esm_StorageHelper().getStorage() : undefined; //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Credentials.js var Credentials_assign = (undefined && undefined.__assign) || function () { Credentials_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Credentials_assign.apply(this, arguments); }; var Credentials_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Credentials_generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var Credentials_logger = new ConsoleLogger('Credentials'); var Credentials_Credentials = /** @class */ (function () { function Credentials(config) { this._gettingCredPromise = null; this._refreshHandlers = {}; this.configure(config); this._refreshHandlers['google'] = lib_esm_OAuthHelper_GoogleOAuth.refreshGoogleToken; this._refreshHandlers['facebook'] = lib_esm_OAuthHelper_FacebookOAuth.refreshFacebookToken; } Credentials.prototype.getCredSource = function () { return this._credentials_source; }; Credentials.prototype.configure = function (config) { if (!config) return this._config || {}; this._config = Object.assign({}, this._config, config); var refreshHandlers = this._config.refreshHandlers; // If the developer has provided an object of refresh handlers, // then we can merge the provided handlers with the current handlers. if (refreshHandlers) { this._refreshHandlers = Credentials_assign(Credentials_assign({}, this._refreshHandlers), refreshHandlers); } this._storage = this._config.storage; if (!this._storage) { this._storage = new lib_esm_StorageHelper().getStorage(); } this._storageSync = Promise.resolve(); if (typeof this._storage['sync'] === 'function') { this._storageSync = this._storage['sync'](); } return this._config; }; Credentials.prototype.get = function () { Credentials_logger.debug('getting credentials'); return this._pickupCredentials(); }; Credentials.prototype._pickupCredentials = function () { Credentials_logger.debug('picking up credentials'); if (!this._gettingCredPromise || !this._gettingCredPromise.isPending()) { Credentials_logger.debug('getting new cred promise'); if (browser.config && browser.config.credentials && browser.config.credentials instanceof browser.Credentials) { this._gettingCredPromise = JS["a" /* default */].makeQuerablePromise(this._setCredentialsFromAWS()); } else { this._gettingCredPromise = JS["a" /* default */].makeQuerablePromise(this._keepAlive()); } } else { Credentials_logger.debug('getting old cred promise'); } return this._gettingCredPromise; }; Credentials.prototype._keepAlive = function () { Credentials_logger.debug('checking if credentials exists and not expired'); var cred = this._credentials; if (cred && !this._isExpired(cred)) { Credentials_logger.debug('credentials not changed and not expired, directly return'); return Promise.resolve(cred); } Credentials_logger.debug('need to get a new credential or refresh the existing one'); if (lib_esm_Amplify.Auth && typeof lib_esm_Amplify.Auth.currentUserCredentials === 'function') { return lib_esm_Amplify.Auth.currentUserCredentials(); } else { return Promise.reject('No Auth module registered in Amplify'); } }; Credentials.prototype.refreshFederatedToken = function (federatedInfo) { var _this = this; Credentials_logger.debug('Getting federated credentials'); var provider = federatedInfo.provider, user = federatedInfo.user; var token = federatedInfo.token, expires_at = federatedInfo.expires_at, identity_id = federatedInfo.identity_id; var that = this; Credentials_logger.debug('checking if federated jwt token expired'); if (expires_at > new Date().getTime()) { // if not expired Credentials_logger.debug('token not expired'); return this._setCredentialsFromFederation({ provider: provider, token: token, user: user, identity_id: identity_id, expires_at: expires_at, }); } else { // if refresh handler exists if (that._refreshHandlers[provider] && typeof that._refreshHandlers[provider] === 'function') { Credentials_logger.debug('getting refreshed jwt token from federation provider'); return that._refreshHandlers[provider]() .then(function (data) { Credentials_logger.debug('refresh federated token sucessfully', data); token = data.token; identity_id = data.identity_id; expires_at = data.expires_at; return that._setCredentialsFromFederation({ provider: provider, token: token, user: user, identity_id: identity_id, expires_at: expires_at, }); }) .catch(function (e) { Credentials_logger.debug('refresh federated token failed', e); _this.clear(); return Promise.reject('refreshing federation token failed: ' + e); }); } else { Credentials_logger.debug('no refresh handler for provider:', provider); this.clear(); return Promise.reject('no refresh handler for provider'); } } }; Credentials.prototype._isExpired = function (credentials) { if (!credentials) { Credentials_logger.debug('no credentials for expiration check'); return true; } Credentials_logger.debug('is this credentials expired?', credentials); var ts = new Date().getTime(); var delta = 10 * 60 * 1000; // 10 minutes var expired = credentials.expired, expireTime = credentials.expireTime; if (!expired && expireTime > ts + delta) { return false; } return true; }; Credentials.prototype._setCredentialsForGuest = function () { return Credentials_awaiter(this, void 0, void 0, function () { var attempted, _a, identityPoolId, region, mandatorySignIn, identityId, e_1, credentials, that; var _this = this; return Credentials_generator(this, function (_b) { switch (_b.label) { case 0: attempted = false; Credentials_logger.debug('setting credentials for guest'); _a = this._config, identityPoolId = _a.identityPoolId, region = _a.region, mandatorySignIn = _a.mandatorySignIn; if (mandatorySignIn) { return [2 /*return*/, Promise.reject('cannot get guest credentials when mandatory signin enabled')]; } if (!identityPoolId) { Credentials_logger.debug('No Cognito Federated Identity pool provided'); return [2 /*return*/, Promise.reject('No Cognito Federated Identity pool provided')]; } identityId = undefined; _b.label = 1; case 1: _b.trys.push([1, 3, , 4]); return [4 /*yield*/, this._storageSync]; case 2: _b.sent(); identityId = this._storage.getItem('CognitoIdentityId-' + identityPoolId); return [3 /*break*/, 4]; case 3: e_1 = _b.sent(); Credentials_logger.debug('Failed to get the cached identityId', e_1); return [3 /*break*/, 4]; case 4: credentials = new browser.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId, IdentityId: identityId ? identityId : undefined, }, { region: region, }); that = this; return [2 /*return*/, this._loadCredentials(credentials, 'guest', false, null) .then(function (res) { return res; }) .catch(function (e) { return Credentials_awaiter(_this, void 0, void 0, function () { var newCredentials; return Credentials_generator(this, function (_a) { // If identity id is deleted in the console, we make one attempt to recreate it // and remove existing id from cache. if (e.code === 'ResourceNotFoundException' && e.message === "Identity '" + identityId + "' not found." && !attempted) { attempted = true; Credentials_logger.debug('Failed to load guest credentials'); this._storage.removeItem('CognitoIdentityId-' + identityPoolId); credentials.clearCachedId(); newCredentials = new browser.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId, IdentityId: undefined, }, { region: region, }); return [2 /*return*/, this._loadCredentials(newCredentials, 'guest', false, null)]; } else { return [2 /*return*/, e]; } return [2 /*return*/]; }); }); })]; } }); }); }; Credentials.prototype._setCredentialsFromAWS = function () { var credentials = browser.config.credentials; Credentials_logger.debug('setting credentials from aws'); var that = this; if (credentials instanceof browser.Credentials) { return Promise.resolve(credentials); } else { Credentials_logger.debug('AWS.config.credentials is not an instance of AWS Credentials'); return Promise.reject('AWS.config.credentials is not an instance of AWS Credentials'); } }; Credentials.prototype._setCredentialsFromFederation = function (params) { var provider = params.provider, token = params.token, identity_id = params.identity_id, user = params.user, expires_at = params.expires_at; var domains = { google: 'accounts.google.com', facebook: 'graph.facebook.com', amazon: 'www.amazon.com', developer: 'cognito-identity.amazonaws.com', }; // Use custom provider url instead of the predefined ones var domain = domains[provider] || provider; if (!domain) { return Promise.reject('You must specify a federated provider'); } var logins = {}; logins[domain] = token; var _a = this._config, identityPoolId = _a.identityPoolId, region = _a.region; if (!identityPoolId) { Credentials_logger.debug('No Cognito Federated Identity pool provided'); return Promise.reject('No Cognito Federated Identity pool provided'); } var credentials = new browser.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId, IdentityId: identity_id, Logins: logins, }, { region: region, }); return this._loadCredentials(credentials, 'federated', true, params); }; Credentials.prototype._setCredentialsFromSession = function (session) { Credentials_logger.debug('set credentials from session'); var idToken = session.getIdToken().getJwtToken(); var _a = this._config, region = _a.region, userPoolId = _a.userPoolId, identityPoolId = _a.identityPoolId; if (!identityPoolId) { Credentials_logger.debug('No Cognito Federated Identity pool provided'); return Promise.reject('No Cognito Federated Identity pool provided'); } var key = 'cognito-idp.' + region + '.amazonaws.com/' + userPoolId; var logins = {}; logins[key] = idToken; var credentials = new browser.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId, Logins: logins, }, { region: region, }); return this._loadCredentials(credentials, 'userPool', true, null); }; Credentials.prototype._loadCredentials = function (credentials, source, authenticated, info) { var _this = this; var that = this; var identityPoolId = this._config.identityPoolId; return new Promise(function (res, rej) { credentials.get(function (err) { return Credentials_awaiter(_this, void 0, void 0, function () { var user, provider, token, expires_at, identity_id, e_2; return Credentials_generator(this, function (_a) { switch (_a.label) { case 0: if (err) { Credentials_logger.debug('Failed to load credentials', credentials); rej(err); return [2 /*return*/]; } Credentials_logger.debug('Load credentials successfully', credentials); that._credentials = credentials; that._credentials.authenticated = authenticated; that._credentials_source = source; if (!(source === 'federated')) return [3 /*break*/, 3]; user = Object.assign({ id: this._credentials.identityId }, info.user); provider = info.provider, token = info.token, expires_at = info.expires_at, identity_id = info.identity_id; try { this._storage.setItem('aws-amplify-federatedInfo', JSON.stringify({ provider: provider, token: token, user: user, expires_at: expires_at, identity_id: identity_id, })); } catch (e) { Credentials_logger.debug('Failed to put federated info into auth storage', e); } if (!(lib_esm_Amplify.Cache && typeof lib_esm_Amplify.Cache.setItem === 'function')) return [3 /*break*/, 2]; return [4 /*yield*/, lib_esm_Amplify.Cache.setItem('federatedInfo', { provider: provider, token: token, user: user, expires_at: expires_at, identity_id: identity_id, }, { priority: 1 })]; case 1: _a.sent(); return [3 /*break*/, 3]; case 2: Credentials_logger.debug('No Cache module registered in Amplify'); _a.label = 3; case 3: if (!(source === 'guest')) return [3 /*break*/, 7]; _a.label = 4; case 4: _a.trys.push([4, 6, , 7]); return [4 /*yield*/, this._storageSync]; case 5: _a.sent(); this._storage.setItem('CognitoIdentityId-' + identityPoolId, credentials.identityId); return [3 /*break*/, 7]; case 6: e_2 = _a.sent(); Credentials_logger.debug('Failed to cache identityId', e_2); return [3 /*break*/, 7]; case 7: res(that._credentials); return [2 /*return*/]; } }); }); }); }); }; Credentials.prototype.set = function (params, source) { if (source === 'session') { return this._setCredentialsFromSession(params); } else if (source === 'federation') { return this._setCredentialsFromFederation(params); } else if (source === 'guest') { return this._setCredentialsForGuest(); } else { Credentials_logger.debug('no source specified for setting credentials'); return Promise.reject('invalid source'); } }; Credentials.prototype.clear = function () { return Credentials_awaiter(this, void 0, void 0, function () { var _a, identityPoolId, region, credentials; return Credentials_generator(this, function (_b) { switch (_b.label) { case 0: _a = this._config, identityPoolId = _a.identityPoolId, region = _a.region; if (identityPoolId) { credentials = new browser.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId, }, { region: region, }); credentials.clearCachedId(); } this._credentials = null; this._credentials_source = null; this._storage.removeItem('aws-amplify-federatedInfo'); if (!(lib_esm_Amplify.Cache && typeof lib_esm_Amplify.Cache.setItem === 'function')) return [3 /*break*/, 2]; return [4 /*yield*/, lib_esm_Amplify.Cache.removeItem('federatedInfo')]; case 1: _b.sent(); return [3 /*break*/, 3]; case 2: Credentials_logger.debug('No Cache module registered in Amplify'); _b.label = 3; case 3: return [2 /*return*/]; } }); }); }; /** * Compact version of credentials * @param {Object} credentials * @return {Object} - Credentials */ Credentials.prototype.shear = function (credentials) { return { accessKeyId: credentials.accessKeyId, sessionToken: credentials.sessionToken, secretAccessKey: credentials.secretAccessKey, identityId: credentials.identityId, authenticated: credentials.authenticated, }; }; return Credentials; }()); var instance = new Credentials_Credentials(null); /* harmony default export */ var lib_esm_Credentials = (instance); //# sourceMappingURL=Credentials.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/ServiceWorker/ServiceWorker.js /** * Copyright 2018 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. */ /** * Provides a means to registering a service worker in the browser * and communicating with it via postMessage events. * https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/ * * postMessage events are currently not supported in all browsers. See: * https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API * * At the minmum this class will register the service worker and listen * and attempt to dispatch messages on state change and record analytics * events based on the service worker lifecycle. */ var ServiceWorker_ServiceWorkerClass = /** @class */ (function () { function ServiceWorkerClass() { // The AWS Amplify logger this._logger = new ConsoleLogger('ServiceWorker'); } Object.defineProperty(ServiceWorkerClass.prototype, "serviceWorker", { /** * Get the currently active service worker */ get: function () { return this._serviceWorker; }, enumerable: true, configurable: true }); /** * Register the service-worker.js file in the browser * Make sure the service-worker.js is part of the build * for example with Angular, modify the angular-cli.json file * and add to "assets" array "service-worker.js" * @param {string} - (optional) Service worker file. Defaults to "/service-worker.js" * @param {string} - (optional) The service worker scope. Defaults to "/" * - API Doc: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register * @returns {Promise} * - resolve(ServiceWorkerRegistration) * - reject(Error) **/ ServiceWorkerClass.prototype.register = function (filePath, scope) { var _this = this; if (filePath === void 0) { filePath = '/service-worker.js'; } if (scope === void 0) { scope = '/'; } this._logger.debug("registering " + filePath); this._logger.debug("registering service worker with scope " + scope); return new Promise(function (resolve, reject) { if (navigator && 'serviceWorker' in navigator) { navigator.serviceWorker .register(filePath, { scope: scope, }) .then(function (registration) { if (registration.installing) { _this._serviceWorker = registration.installing; } else if (registration.waiting) { _this._serviceWorker = registration.waiting; } else if (registration.active) { _this._serviceWorker = registration.active; } _this._registration = registration; _this._setupListeners(); _this._logger.debug("Service Worker Registration Success: " + registration); return resolve(registration); }) .catch(function (error) { _this._logger.debug("Service Worker Registration Failed " + error); return reject(error); }); } else { return reject(new Error('Service Worker not available')); } }); }; /** * Enable web push notifications. If not subscribed, a new subscription will * be created and registered. * Test Push Server: https://web-push-codelab.glitch.me/ * Push Server Libraries: https://github.com/web-push-libs/ * API Doc: https://developers.google.com/web/fundamentals/codelabs/push-notifications/ * @param publicKey * @returns {Promise} * - resolve(PushSubscription) * - reject(Error) */ ServiceWorkerClass.prototype.enablePush = function (publicKey) { var _this = this; if (!this._registration) throw new Error('Service Worker not registered'); this._publicKey = publicKey; return new Promise(function (resolve, reject) { if (JS["a" /* default */].browserOrNode().isBrowser) { _this._registration.pushManager.getSubscription().then(function (subscription) { if (subscription) { _this._subscription = subscription; _this._logger.debug("User is subscribed to push: " + JSON.stringify(subscription)); resolve(subscription); } else { _this._logger.debug("User is NOT subscribed to push"); return _this._registration.pushManager .subscribe({ userVisibleOnly: true, applicationServerKey: _this._urlB64ToUint8Array(publicKey), }) .then(function (subscription) { _this._subscription = subscription; _this._logger.debug("User subscribed: " + JSON.stringify(subscription)); resolve(subscription); }) .catch(function (error) { _this._logger.error(error); }); } }); } else { return reject(new Error('Service Worker not available')); } }); }; /** * Convert a base64 encoded string to a Uint8 array for the push server key * @param base64String */ ServiceWorkerClass.prototype._urlB64ToUint8Array = function (base64String) { var padding = '='.repeat((4 - (base64String.length % 4)) % 4); var base64 = (base64String + padding) .replace(/\-/g, '+') .replace(/_/g, '/'); var rawData = window.atob(base64); var outputArray = new Uint8Array(rawData.length); for (var i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; }; /** * Send a message to the service worker. The service worker needs * to implement `self.addEventListener('message') to handle the * message. This ***currently*** does not work in Safari or IE. * @param {object | string} - An arbitrary JSON object or string message to send to the service worker * - see: https://developer.mozilla.org/en-US/docs/Web/API/Transferable * @returns {Promise} **/ ServiceWorkerClass.prototype.send = function (message) { if (this._serviceWorker) { this._serviceWorker.postMessage(typeof message === 'object' ? JSON.stringify(message) : message); } }; /** * Listen for service worker state change and message events * https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/state **/ ServiceWorkerClass.prototype._setupListeners = function () { var _this = this; this._serviceWorker.addEventListener('statechange', function (event) { var currentState = _this._serviceWorker.state; _this._logger.debug("ServiceWorker statechange: " + currentState); if (lib_esm_Amplify.Analytics && typeof lib_esm_Amplify.Analytics.record === 'function') { lib_esm_Amplify.Analytics.record({ name: 'ServiceWorker', attributes: { state: currentState, }, }); } }); this._serviceWorker.addEventListener('message', function (event) { _this._logger.debug("ServiceWorker message event: " + event); }); }; return ServiceWorkerClass; }()); /* harmony default export */ var ServiceWorker = (ServiceWorker_ServiceWorkerClass); //# sourceMappingURL=ServiceWorker.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/ServiceWorker/index.js /** * Copyright 2018 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. */ //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Platform/index.js /* * Copyright 2017-2017 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 packageInfo = __webpack_require__("e341"); var Platform = { userAgent: "aws-amplify/" + packageInfo.version + " js", product: '', navigator: null, isReactNative: false, }; if (typeof navigator !== 'undefined' && navigator.product) { Platform.product = navigator.product || ''; Platform.navigator = navigator || null; switch (navigator.product) { case 'ReactNative': Platform.userAgent = "aws-amplify/" + packageInfo.version + " react-native"; Platform.isReactNative = true; break; default: Platform.userAgent = "aws-amplify/" + packageInfo.version + " js"; Platform.isReactNative = false; break; } } /* harmony default export */ var lib_esm_Platform = (Platform); //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/constants.js /* * Copyright 2018-2019 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. */ /** * This Symbol is used to reference an internal-only PubSub provider that * is used for AppSync/GraphQL subscriptions in the API category. */ var hasSymbol = typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'; var INTERNAL_AWS_APPSYNC_PUBSUB_PROVIDER = hasSymbol ? Symbol.for('INTERNAL_AWS_APPSYNC_PUBSUB_PROVIDER') : '@@INTERNAL_AWS_APPSYNC_PUBSUB_PROVIDER'; var INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER = hasSymbol ? Symbol.for('INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER') : '@@INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER'; var USER_AGENT_HEADER = 'x-amz-user-agent'; //# sourceMappingURL=constants.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Util/Retry.js var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Retry_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Retry_generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var Retry_logger = new ConsoleLogger('Util'); var NonRetryableError = /** @class */ (function (_super) { __extends(NonRetryableError, _super); function NonRetryableError(message) { var _this = _super.call(this, message) || this; _this.nonRetryable = true; return _this; } return NonRetryableError; }(Error)); var isNonRetryableError = function (obj) { var key = 'nonRetryable'; return obj && obj[key]; }; /** * @private * Internal use of Amplify only */ function retry(functionToRetry, args, delayFn, attempt) { if (attempt === void 0) { attempt = 1; } return Retry_awaiter(this, void 0, void 0, function () { var err_1, retryIn_1; return Retry_generator(this, function (_a) { switch (_a.label) { case 0: if (typeof functionToRetry !== 'function') { throw Error('functionToRetry must be a function'); } Retry_logger.debug(functionToRetry.name + " attempt #" + attempt + " with this vars: " + JSON.stringify(args)); _a.label = 1; case 1: _a.trys.push([1, 3, , 8]); return [4 /*yield*/, functionToRetry.apply(void 0, args)]; case 2: return [2 /*return*/, _a.sent()]; case 3: err_1 = _a.sent(); Retry_logger.debug("error on " + functionToRetry.name + ": " + err_1 + " "); if (isNonRetryableError(err_1)) { Retry_logger.debug(functionToRetry.name + " non retryable error " + err_1); throw err_1; } retryIn_1 = delayFn(attempt, args, err_1); Retry_logger.debug(functionToRetry.name + " retrying in " + retryIn_1 + " ms"); if (!(retryIn_1 !== false)) return [3 /*break*/, 6]; return [4 /*yield*/, new Promise(function (res) { return setTimeout(res, retryIn_1); })]; case 4: _a.sent(); return [4 /*yield*/, retry(functionToRetry, args, delayFn, attempt + 1)]; case 5: return [2 /*return*/, _a.sent()]; case 6: throw err_1; case 7: return [3 /*break*/, 8]; case 8: return [2 /*return*/]; } }); }); } var MAX_DELAY_MS = 5 * 60 * 1000; function jitteredBackoff(maxDelayMs) { var BASE_TIME_MS = 100; var JITTER_FACTOR = 100; return function (attempt) { var delay = Math.pow(2, attempt) * BASE_TIME_MS + JITTER_FACTOR * Math.random(); return delay > maxDelayMs ? false : delay; }; } /** * @private * Internal use of Amplify only */ var jitteredExponentialRetry = function (functionToRetry, args, maxDelayMs) { if (maxDelayMs === void 0) { maxDelayMs = MAX_DELAY_MS; } return retry(functionToRetry, args, jitteredBackoff(maxDelayMs)); }; //# sourceMappingURL=Retry.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Util/Mutex.js /*! * The MIT License (MIT) * * Copyright (c) 2016 Christian Speckner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var Mutex = /** @class */ (function () { function Mutex() { this._queue = []; this._pending = false; } Mutex.prototype.isLocked = function () { return this._pending; }; Mutex.prototype.acquire = function () { var _this = this; var ticket = new Promise(function (resolve) { return _this._queue.push(resolve); }); if (!this._pending) { this._dispatchNext(); } return ticket; }; Mutex.prototype.runExclusive = function (callback) { return this.acquire().then(function (release) { var result; try { result = callback(); } catch (e) { release(); throw e; } return Promise.resolve(result).then(function (x) { return (release(), x); }, function (e) { release(); throw e; }); }); }; Mutex.prototype._dispatchNext = function () { if (this._queue.length > 0) { this._pending = true; this._queue.shift()(this._dispatchNext.bind(this)); } else { this._pending = false; } }; return Mutex; }()); /* harmony default export */ var Util_Mutex = (Mutex); //# sourceMappingURL=Mutex.js.map // EXTERNAL MODULE: ./node_modules/zen-observable/index.js var zen_observable = __webpack_require__("0012"); // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Util/Reachability.js var Reachability_ReachabilityNavigator = /** @class */ (function () { function ReachabilityNavigator() { } ReachabilityNavigator.prototype.networkMonitor = function () { return new zen_observable(function (observer) { observer.next({ online: window.navigator.onLine }); var notifyOnline = function () { return observer.next({ online: true }); }; var notifyOffline = function () { return observer.next({ online: false }); }; window.addEventListener('online', notifyOnline); window.addEventListener('offline', notifyOffline); return function () { window.removeEventListener('online', notifyOnline); window.removeEventListener('offline', notifyOffline); }; }); }; return ReachabilityNavigator; }()); /* harmony default export */ var Reachability = (Reachability_ReachabilityNavigator); //# sourceMappingURL=Reachability.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/Util/index.js //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/core/lib-esm/index.js /* * Copyright 2017-2017 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 Constants = { userAgent: lib_esm_Platform.userAgent, }; /* harmony default export */ var lib_esm = (lib_esm_Amplify); var lib_esm_logger = new ConsoleLogger('Core'); if (browser['util']) { browser['util'].userAgent = function () { return Constants.userAgent; }; } else if (browser.config) { browser.config.update({ customUserAgent: Constants.userAgent }); } else { lib_esm_logger.warn('No AWS.config'); } //# sourceMappingURL=index.js.map // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/AuthenticationDetails.js /*! * 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 = /*#__PURE__*/ 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. * @param {(AttributeArg[])?} data.AuthParamaters Authentication paramaters for custom auth. */ function AuthenticationDetails(data) { var _ref = data || {}, ValidationData = _ref.ValidationData, Username = _ref.Username, Password = _ref.Password, AuthParameters = _ref.AuthParameters, ClientMetadata = _ref.ClientMetadata; this.validationData = ValidationData || {}; this.authParameters = AuthParameters || {}; this.clientMetadata = ClientMetadata || {}; this.username = Username; this.password = Password; } /** * @returns {string} the record's username */ var _proto = AuthenticationDetails.prototype; _proto.getUsername = function getUsername() { return this.username; } /** * @returns {string} the record's password */ ; _proto.getPassword = function getPassword() { return this.password; } /** * @returns {Array} the record's validationData */ ; _proto.getValidationData = function getValidationData() { return this.validationData; } /** * @returns {Array} the record's authParameters */ ; _proto.getAuthParameters = function getAuthParameters() { return this.authParameters; } /** * @returns {ClientMetadata} the clientMetadata for a Lambda trigger */ ; _proto.getClientMetadata = function getClientMetadata() { return this.clientMetadata; }; return AuthenticationDetails; }(); // EXTERNAL MODULE: ./node_modules/buffer/index.js var buffer = __webpack_require__("b639"); // EXTERNAL MODULE: ./node_modules/crypto-js/core.js var core = __webpack_require__("21bf"); var core_default = /*#__PURE__*/__webpack_require__.n(core); // EXTERNAL MODULE: ./node_modules/crypto-js/lib-typedarrays.js var lib_typedarrays = __webpack_require__("17e1"); // EXTERNAL MODULE: ./node_modules/crypto-js/sha256.js var sha256 = __webpack_require__("94f8"); var sha256_default = /*#__PURE__*/__webpack_require__.n(sha256); // EXTERNAL MODULE: ./node_modules/crypto-js/hmac-sha256.js var hmac_sha256 = __webpack_require__("ed53"); var hmac_sha256_default = /*#__PURE__*/__webpack_require__.n(hmac_sha256); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/BigInteger.js // 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 */ var BigInteger = (BigInteger_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_BigInteger(a, b) { if (a != null) this.fromString(a, b); } // return new, unset BigInteger function nbi() { return new BigInteger_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_BigInteger.prototype.am = am2; dbits = 30; } else if (inBrowser && j_lm && navigator.appName != 'Netscape') { BigInteger_BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger_BigInteger.prototype.am = am3; dbits = 28; } BigInteger_BigInteger.prototype.DB = dbits; BigInteger_BigInteger.prototype.DM = (1 << dbits) - 1; BigInteger_BigInteger.prototype.DV = 1 << dbits; var BI_FP = 52; BigInteger_BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger_BigInteger.prototype.F1 = BI_FP - dbits; BigInteger_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_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(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'); 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_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_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_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_BigInteger.ZERO.subTo(q, q); } r.t = ys; r.clamp(); if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder if (ts < 0) BigInteger_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_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_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, callback) { 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; } } } var result = z.revert(r); callback(null, result); return result; } // protected BigInteger_BigInteger.prototype.copyTo = bnpCopyTo; BigInteger_BigInteger.prototype.fromInt = bnpFromInt; BigInteger_BigInteger.prototype.fromString = bnpFromString; BigInteger_BigInteger.prototype.clamp = bnpClamp; BigInteger_BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger_BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger_BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger_BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger_BigInteger.prototype.subTo = bnpSubTo; BigInteger_BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger_BigInteger.prototype.squareTo = bnpSquareTo; BigInteger_BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger_BigInteger.prototype.invDigit = bnpInvDigit; BigInteger_BigInteger.prototype.addTo = bnpAddTo; // public BigInteger_BigInteger.prototype.toString = bnToString; BigInteger_BigInteger.prototype.negate = bnNegate; BigInteger_BigInteger.prototype.abs = bnAbs; BigInteger_BigInteger.prototype.compareTo = bnCompareTo; BigInteger_BigInteger.prototype.bitLength = bnBitLength; BigInteger_BigInteger.prototype.mod = bnMod; BigInteger_BigInteger.prototype.equals = bnEquals; BigInteger_BigInteger.prototype.add = bnAdd; BigInteger_BigInteger.prototype.subtract = bnSubtract; BigInteger_BigInteger.prototype.multiply = bnMultiply; BigInteger_BigInteger.prototype.divide = bnDivide; BigInteger_BigInteger.prototype.modPow = bnModPow; // "constants" BigInteger_BigInteger.ZERO = nbv(0); BigInteger_BigInteger.ONE = nbv(1); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/AuthenticationHelper.js /*! * 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. */ // necessary for crypto js var AuthenticationHelper_randomBytes = function randomBytes(nBytes) { return buffer["Buffer"].from(core_default.a.lib.WordArray.random(nBytes).toString(), 'hex'); }; var initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF'; var newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.'; /** @class */ var AuthenticationHelper_AuthenticationHelper = /*#__PURE__*/ function () { /** * Constructs a new AuthenticationHelper object * @param {string} PoolName Cognito user pool name. */ function AuthenticationHelper(PoolName) { this.N = new BigInteger(initN, 16); this.g = new BigInteger('2', 16); this.k = new BigInteger(this.hexHash("00" + this.N.toString(16) + "0" + this.g.toString(16)), 16); this.smallAValue = this.generateRandomSmallA(); this.getLargeAValue(function () {}); this.infoBits = buffer["Buffer"].from('Caldera Derived Key', 'utf8'); this.poolName = PoolName; } /** * @returns {BigInteger} small A, a random number */ var _proto = AuthenticationHelper.prototype; _proto.getSmallAValue = function getSmallAValue() { return this.smallAValue; } /** * @param {nodeCallback} callback Called with (err, largeAValue) * @returns {void} */ ; _proto.getLargeAValue = function getLargeAValue(callback) { var _this = this; if (this.largeAValue) { callback(null, this.largeAValue); } else { this.calculateA(this.smallAValue, function (err, largeAValue) { if (err) { callback(err, null); } _this.largeAValue = largeAValue; callback(null, _this.largeAValue); }); } } /** * helper function to generate a random big integer * @returns {BigInteger} a random value. * @private */ ; _proto.generateRandomSmallA = function generateRandomSmallA() { var hexRandom = AuthenticationHelper_randomBytes(128).toString('hex'); var randomBigInt = new BigInteger(hexRandom, 16); var smallABigInt = randomBigInt.mod(this.N); return smallABigInt; } /** * helper function to generate a random string * @returns {string} a random value. * @private */ ; _proto.generateRandomString = function generateRandomString() { return AuthenticationHelper_randomBytes(40).toString('base64'); } /** * @returns {string} Generated random value included in password hash. */ ; _proto.getRandomPassword = function getRandomPassword() { return this.randomPassword; } /** * @returns {string} Generated random value included in devices hash. */ ; _proto.getSaltDevices = function getSaltDevices() { return this.SaltToHashDevices; } /** * @returns {string} Value used to verify devices. */ ; _proto.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. * @param {nodeCallback} callback Called with (err, null) * @returns {void} */ ; _proto.generateHashDevice = function generateHashDevice(deviceGroupKey, username, callback) { var _this2 = this; this.randomPassword = this.generateRandomString(); var combinedString = "" + deviceGroupKey + username + ":" + this.randomPassword; var hashedString = this.hash(combinedString); var hexRandom = AuthenticationHelper_randomBytes(16).toString('hex'); this.SaltToHashDevices = this.padHex(new BigInteger(hexRandom, 16)); this.g.modPow(new BigInteger(this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, function (err, verifierDevicesNotPadded) { if (err) { callback(err, null); } _this2.verifierDevices = _this2.padHex(verifierDevicesNotPadded); callback(null, null); }); } /** * Calculate the client's public value A = g^a%N * with the generated random number a * @param {BigInteger} a Randomly generated small A. * @param {nodeCallback} callback Called with (err, largeAValue) * @returns {void} * @private */ ; _proto.calculateA = function calculateA(a, callback) { var _this3 = this; this.g.modPow(a, this.N, function (err, A) { if (err) { callback(err, null); } if (A.mod(_this3.N).equals(BigInteger.ZERO)) { callback(new Error('Illegal paramater. A mod N cannot be 0.'), null); } callback(null, 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 */ ; _proto.calculateU = function calculateU(A, B) { this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B)); var finalU = new BigInteger(this.UHexHash, 16); return finalU; } /** * Calculate a hash from a bitArray * @param {Buffer} buf Value to hash. * @returns {String} Hex-encoded hash. * @private */ ; _proto.hash = function hash(buf) { var str = buf instanceof buffer["Buffer"] ? core_default.a.lib.WordArray.create(buf) : buf; var hashHex = sha256_default()(str).toString(); 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 */ ; _proto.hexHash = function hexHash(hexStr) { return this.hash(buffer["Buffer"].from(hexStr, 'hex')); } /** * Standard hkdf algorithm * @param {Buffer} ikm Input key material. * @param {Buffer} salt Salt value. * @returns {Buffer} Strong key material. * @private */ ; _proto.computehkdf = function computehkdf(ikm, salt) { var infoBitsWordArray = core_default.a.lib.WordArray.create(buffer["Buffer"].concat([this.infoBits, buffer["Buffer"].from(String.fromCharCode(1), 'utf8')])); var ikmWordArray = ikm instanceof buffer["Buffer"] ? core_default.a.lib.WordArray.create(ikm) : ikm; var saltWordArray = salt instanceof buffer["Buffer"] ? core_default.a.lib.WordArray.create(salt) : salt; var prk = hmac_sha256_default()(ikmWordArray, saltWordArray); var hmac = hmac_sha256_default()(infoBitsWordArray, prk); return buffer["Buffer"].from(hmac.toString(), 'hex').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. * @param {nodeCallback} callback Called with (err, hkdfValue) * @returns {void} */ ; _proto.getPasswordAuthenticationKey = function getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) { var _this4 = this; if (serverBValue.mod(this.N).equals(BigInteger.ZERO)) { throw new Error('B cannot be zero.'); } this.UValue = this.calculateU(this.largeAValue, serverBValue); if (this.UValue.equals(BigInteger.ZERO)) { throw new Error('U cannot be zero.'); } var usernamePassword = "" + this.poolName + username + ":" + password; var usernamePasswordHash = this.hash(usernamePassword); var xValue = new BigInteger(this.hexHash(this.padHex(salt) + usernamePasswordHash), 16); this.calculateS(xValue, serverBValue, function (err, sValue) { if (err) { callback(err, null); } var hkdf = _this4.computehkdf(buffer["Buffer"].from(_this4.padHex(sValue), 'hex'), buffer["Buffer"].from(_this4.padHex(_this4.UValue.toString(16)), 'hex')); callback(null, hkdf); }); } /** * Calculates the S value used in getPasswordAuthenticationKey * @param {BigInteger} xValue Salted password hash value. * @param {BigInteger} serverBValue Server B value. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ ; _proto.calculateS = function calculateS(xValue, serverBValue, callback) { var _this5 = this; this.g.modPow(xValue, this.N, function (err, gModPowXN) { if (err) { callback(err, null); } var intValue2 = serverBValue.subtract(_this5.k.multiply(gModPowXN)); intValue2.modPow(_this5.smallAValue.add(_this5.UValue.multiply(xValue)), _this5.N, function (err2, result) { if (err2) { callback(err2, null); } callback(null, result.mod(_this5.N)); }); }); } /** * Return constant newPasswordRequiredChallengeUserAttributePrefix * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value */ ; _proto.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. */ ; _proto.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; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CognitoJwtToken.js /*! * 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 CognitoJwtToken_CognitoJwtToken = /*#__PURE__*/ function () { /** * Constructs a new CognitoJwtToken object * @param {string=} token The JWT token. */ function CognitoJwtToken(token) { // Assign object this.jwtToken = token || ''; this.payload = this.decodePayload(); } /** * @returns {string} the record's token. */ var _proto = CognitoJwtToken.prototype; _proto.getJwtToken = function getJwtToken() { return this.jwtToken; } /** * @returns {int} the token's expiration (exp member). */ ; _proto.getExpiration = function getExpiration() { return this.payload.exp; } /** * @returns {int} the token's "issued at" (iat member). */ ; _proto.getIssuedAt = function getIssuedAt() { return this.payload.iat; } /** * @returns {object} the token's payload. */ ; _proto.decodePayload = function decodePayload() { var payload = this.jwtToken.split('.')[1]; try { return JSON.parse(buffer["Buffer"].from(payload, 'base64').toString('utf8')); } catch (err) { return {}; } }; return CognitoJwtToken; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CognitoAccessToken.js function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /* * 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 = /*#__PURE__*/ function (_CognitoJwtToken) { _inheritsLoose(CognitoAccessToken, _CognitoJwtToken); /** * Constructs a new CognitoAccessToken object * @param {string=} AccessToken The JWT access token. */ function CognitoAccessToken(_temp) { var _ref = _temp === void 0 ? {} : _temp, AccessToken = _ref.AccessToken; return _CognitoJwtToken.call(this, AccessToken || '') || this; } return CognitoAccessToken; }(CognitoJwtToken_CognitoJwtToken); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CognitoIdToken.js function CognitoIdToken_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /*! * 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 = /*#__PURE__*/ function (_CognitoJwtToken) { CognitoIdToken_inheritsLoose(CognitoIdToken, _CognitoJwtToken); /** * Constructs a new CognitoIdToken object * @param {string=} IdToken The JWT Id token */ function CognitoIdToken(_temp) { var _ref = _temp === void 0 ? {} : _temp, IdToken = _ref.IdToken; return _CognitoJwtToken.call(this, IdToken || '') || this; } return CognitoIdToken; }(CognitoJwtToken_CognitoJwtToken); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CognitoRefreshToken.js /*! * 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 = /*#__PURE__*/ function () { /** * Constructs a new CognitoRefreshToken object * @param {string=} RefreshToken The JWT refresh token. */ function CognitoRefreshToken(_temp) { var _ref = _temp === void 0 ? {} : _temp, RefreshToken = _ref.RefreshToken; // Assign object this.token = RefreshToken || ''; } /** * @returns {string} the record's token. */ var _proto = CognitoRefreshToken.prototype; _proto.getToken = function getToken() { return this.token; }; return CognitoRefreshToken; }(); // EXTERNAL MODULE: ./node_modules/crypto-js/enc-base64.js var enc_base64 = __webpack_require__("1132"); var enc_base64_default = /*#__PURE__*/__webpack_require__.n(enc_base64); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CognitoUserSession.js /*! * 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 = /*#__PURE__*/ function () { /** * Constructs a new CognitoUserSession object * @param {CognitoIdToken} IdToken The session's Id token. * @param {CognitoRefreshToken=} RefreshToken The session's refresh token. * @param {CognitoAccessToken} AccessToken The session's access token. * @param {int} ClockDrift The saved computer's clock drift or undefined to force calculation. */ function CognitoUserSession(_temp) { var _ref = _temp === void 0 ? {} : _temp, IdToken = _ref.IdToken, RefreshToken = _ref.RefreshToken, AccessToken = _ref.AccessToken, ClockDrift = _ref.ClockDrift; 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; this.clockDrift = ClockDrift === undefined ? this.calculateClockDrift() : ClockDrift; } /** * @returns {CognitoIdToken} the session's Id token */ var _proto = CognitoUserSession.prototype; _proto.getIdToken = function getIdToken() { return this.idToken; } /** * @returns {CognitoRefreshToken} the session's refresh token */ ; _proto.getRefreshToken = function getRefreshToken() { return this.refreshToken; } /** * @returns {CognitoAccessToken} the session's access token */ ; _proto.getAccessToken = function getAccessToken() { return this.accessToken; } /** * @returns {int} the session's clock drift */ ; _proto.getClockDrift = function getClockDrift() { return this.clockDrift; } /** * @returns {int} the computer's clock drift */ ; _proto.calculateClockDrift = function calculateClockDrift() { var now = Math.floor(new Date() / 1000); var iat = Math.min(this.accessToken.getIssuedAt(), this.idToken.getIssuedAt()); return now - iat; } /** * Checks to see if the session is still valid based on session expiry information found * in tokens and the current time (adjusted with clock drift) * @returns {boolean} if the session is still valid */ ; _proto.isValid = function isValid() { var now = Math.floor(new Date() / 1000); var adjusted = now - this.clockDrift; return adjusted < this.accessToken.getExpiration() && adjusted < this.idToken.getExpiration(); }; return CognitoUserSession; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/DateHelper.js /*! * 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 = /*#__PURE__*/ function () { function DateHelper() {} var _proto = DateHelper.prototype; /** * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format. */ _proto.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; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CognitoUserAttribute.js /*! * 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 = /*#__PURE__*/ function () { /** * Constructs a new CognitoUserAttribute object * @param {string=} Name The record's name * @param {string=} Value The record's value */ function CognitoUserAttribute(_temp) { var _ref = _temp === void 0 ? {} : _temp, Name = _ref.Name, Value = _ref.Value; this.Name = Name || ''; this.Value = Value || ''; } /** * @returns {string} the record's value. */ var _proto = CognitoUserAttribute.prototype; _proto.getValue = function getValue() { return this.Value; } /** * Sets the record's value. * @param {string} value The new value. * @returns {CognitoUserAttribute} The record for method chaining. */ ; _proto.setValue = function setValue(value) { this.Value = value; return this; } /** * @returns {string} the record's name. */ ; _proto.getName = function getName() { return this.Name; } /** * Sets the record's name * @param {string} name The new name. * @returns {CognitoUserAttribute} The record for method chaining. */ ; _proto.setName = function setName(name) { this.Name = name; return this; } /** * @returns {string} a string representation of the record. */ ; _proto.toString = function toString() { return JSON.stringify(this); } /** * @returns {object} a flat object representing the record. */ ; _proto.toJSON = function toJSON() { return { Name: this.Name, Value: this.Value }; }; return CognitoUserAttribute; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/StorageHelper.js /*! * 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 StorageHelper_dataMemory = {}; /** @class */ var StorageHelper_MemoryStorage = /*#__PURE__*/ function () { function 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) { StorageHelper_dataMemory[key] = value; return StorageHelper_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(StorageHelper_dataMemory, key) ? StorageHelper_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 StorageHelper_dataMemory[key]; } /** * This is used to clear the storage * @returns {string} nothing */ ; MemoryStorage.clear = function clear() { StorageHelper_dataMemory = {}; return StorageHelper_dataMemory; }; return MemoryStorage; }(); /** @class */ var StorageHelper_StorageHelper = /*#__PURE__*/ function () { /** * This is used to get a storage object * @returns {object} the storage */ function 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 = StorageHelper_MemoryStorage; } } /** * This is used to return the storage * @returns {object} the storage */ var _proto = StorageHelper.prototype; _proto.getStorage = function getStorage() { return this.storageWindow; }; return StorageHelper; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CognitoUser.js /*! * 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. */ // necessary for crypto js /** * @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_CognitoUser = /*#__PURE__*/ 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) { 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 StorageHelper_StorageHelper().getStorage(); this.keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId(); this.userDataKey = this.keyPrefix + "." + this.username + ".userData"; } /** * Sets the session for this user * @param {CognitoUserSession} signInUserSession the session * @returns {void} */ var _proto = CognitoUser.prototype; _proto.setSignInUserSession = function setSignInUserSession(signInUserSession) { this.clearCachedUserData(); this.signInUserSession = signInUserSession; this.cacheTokens(); } /** * @returns {CognitoUserSession} the current session for this user */ ; _proto.getSignInUserSession = function getSignInUserSession() { return this.signInUserSession; } /** * @returns {string} the user's username */ ; _proto.getUsername = function getUsername() { return this.username; } /** * @returns {String} the authentication flow type */ ; _proto.getAuthenticationFlowType = function getAuthenticationFlowType() { return this.authenticationFlowType; } /** * sets authentication flow type * @param {string} authenticationFlowType New value. * @returns {void} */ ; _proto.setAuthenticationFlowType = function setAuthenticationFlowType(authenticationFlowType) { this.authenticationFlowType = authenticationFlowType; } /** * This is used for authenticating the user through the custom authentication flow. * @param {AuthenticationDetails} authDetails Contains the authentication data * @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} */ ; _proto.initiateAuth = function initiateAuth(authDetails, callback) { var _this = this; var authParameters = authDetails.getAuthParameters(); authParameters.USERNAME = this.username; var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata(); var jsonReq = { AuthFlow: 'CUSTOM_AUTH', ClientId: this.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: clientMetaData }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('InitiateAuth', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeName = data.ChallengeName; var challengeParameters = data.ChallengeParameters; if (challengeName === 'CUSTOM_CHALLENGE') { _this.Session = data.Session; return callback.customChallenge(challengeParameters); } _this.signInUserSession = _this.getCognitoUserSession(data.AuthenticationResult); _this.cacheTokens(); return callback.onSuccess(_this.signInUserSession); }); } /** * This is used for authenticating the user. * 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} */ ; _proto.authenticateUser = function authenticateUser(authDetails, callback) { if (this.authenticationFlowType === 'USER_PASSWORD_AUTH') { return this.authenticateUserPlainUsernamePassword(authDetails, callback); } else if (this.authenticationFlowType === 'USER_SRP_AUTH' || this.authenticationFlowType === 'CUSTOM_AUTH') { return this.authenticateUserDefaultAuth(authDetails, callback); } return callback.onFailure(new Error('Authentication flow type is invalid.')); } /** * PRIVATE ONLY: This is an internal only method and should not * be directly called by the consumers. * 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} */ ; _proto.authenticateUserDefaultAuth = function authenticateUserDefaultAuth(authDetails, callback) { var _this2 = this; var authenticationHelper = new AuthenticationHelper_AuthenticationHelper(this.pool.getUserPoolId().split('_')[1]); var dateHelper = new DateHelper(); var serverBValue; var salt; var authParameters = {}; if (this.deviceKey != null) { authParameters.DEVICE_KEY = this.deviceKey; } authParameters.USERNAME = this.username; authenticationHelper.getLargeAValue(function (errOnAValue, aValue) { // getLargeAValue callback start if (errOnAValue) { callback.onFailure(errOnAValue); } authParameters.SRP_A = aValue.toString(16); if (_this2.authenticationFlowType === 'CUSTOM_AUTH') { authParameters.CHALLENGE_NAME = 'SRP_A'; } var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata(); var jsonReq = { AuthFlow: _this2.authenticationFlowType, ClientId: _this2.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: clientMetaData }; if (_this2.getUserContextData(_this2.username)) { jsonReq.UserContextData = _this2.getUserContextData(_this2.username); } _this2.client.request('InitiateAuth', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeParameters = data.ChallengeParameters; _this2.username = challengeParameters.USER_ID_FOR_SRP; serverBValue = new BigInteger(challengeParameters.SRP_B, 16); salt = new BigInteger(challengeParameters.SALT, 16); _this2.getCachedDeviceKeyAndPassword(); authenticationHelper.getPasswordAuthenticationKey(_this2.username, authDetails.getPassword(), serverBValue, salt, function (errOnHkdf, hkdf) { // getPasswordAuthenticationKey callback start if (errOnHkdf) { callback.onFailure(errOnHkdf); } var dateNow = dateHelper.getNowString(); var message = core_default.a.lib.WordArray.create(buffer["Buffer"].concat([buffer["Buffer"].from(_this2.pool.getUserPoolId().split('_')[1], 'utf8'), buffer["Buffer"].from(_this2.username, 'utf8'), buffer["Buffer"].from(challengeParameters.SECRET_BLOCK, 'base64'), buffer["Buffer"].from(dateNow, 'utf8')])); var key = core_default.a.lib.WordArray.create(hkdf); var signatureString = enc_base64_default.a.stringify(hmac_sha256_default()(message, key)); var challengeResponses = {}; challengeResponses.USERNAME = _this2.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; if (_this2.deviceKey != null) { challengeResponses.DEVICE_KEY = _this2.deviceKey; } var respondToAuthChallenge = function respondToAuthChallenge(challenge, challengeCallback) { return _this2.client.request('RespondToAuthChallenge', challenge, function (errChallenge, dataChallenge) { if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) { challengeResponses.DEVICE_KEY = null; _this2.deviceKey = null; _this2.randomPassword = null; _this2.deviceGroupKey = null; _this2.clearCachedDeviceKeyAndPassword(); return respondToAuthChallenge(challenge, challengeCallback); } return challengeCallback(errChallenge, dataChallenge); }); }; var jsonReqResp = { ChallengeName: 'PASSWORD_VERIFIER', ClientId: _this2.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session, ClientMetadata: clientMetaData }; if (_this2.getUserContextData()) { jsonReqResp.UserContextData = _this2.getUserContextData(); } respondToAuthChallenge(jsonReqResp, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } return _this2.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback); }); return undefined; // getPasswordAuthenticationKey callback end }); return undefined; }); // getLargeAValue callback end }); } /** * PRIVATE ONLY: This is an internal only method and should not * be directly called by the consumers. * @param {AuthenticationDetails} authDetails Contains the authentication data. * @param {object} callback Result callback map. * @param {onFailure} callback.onFailure Called on any error. * @param {mfaRequired} callback.mfaRequired MFA code * required to continue. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @returns {void} */ ; _proto.authenticateUserPlainUsernamePassword = function authenticateUserPlainUsernamePassword(authDetails, callback) { var _this3 = this; var authParameters = {}; authParameters.USERNAME = this.username; authParameters.PASSWORD = authDetails.getPassword(); if (!authParameters.PASSWORD) { callback.onFailure(new Error('PASSWORD parameter is required')); return; } var authenticationHelper = new AuthenticationHelper_AuthenticationHelper(this.pool.getUserPoolId().split('_')[1]); this.getCachedDeviceKeyAndPassword(); if (this.deviceKey != null) { authParameters.DEVICE_KEY = this.deviceKey; } var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata(); var jsonReq = { AuthFlow: 'USER_PASSWORD_AUTH', ClientId: this.pool.getClientId(), AuthParameters: authParameters, ClientMetadata: clientMetaData }; if (this.getUserContextData(this.username)) { jsonReq.UserContextData = this.getUserContextData(this.username); } // USER_PASSWORD_AUTH happens in a single round-trip: client sends userName and password, // Cognito UserPools verifies password and returns tokens. this.client.request('InitiateAuth', jsonReq, function (err, authResult) { if (err) { return callback.onFailure(err); } return _this3.authenticateUserInternal(authResult, authenticationHelper, callback); }); } /** * 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} */ ; _proto.authenticateUserInternal = function authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) { var _this4 = this; var challengeName = dataAuthenticate.ChallengeName; var challengeParameters = dataAuthenticate.ChallengeParameters; if (challengeName === 'SMS_MFA') { this.Session = dataAuthenticate.Session; return callback.mfaRequired(challengeName, challengeParameters); } if (challengeName === 'SELECT_MFA_TYPE') { this.Session = dataAuthenticate.Session; return callback.selectMFAType(challengeName, challengeParameters); } if (challengeName === 'MFA_SETUP') { this.Session = dataAuthenticate.Session; return callback.mfaSetup(challengeName, challengeParameters); } if (challengeName === 'SOFTWARE_TOKEN_MFA') { this.Session = dataAuthenticate.Session; return callback.totpRequired(challengeName, challengeParameters); } if (challengeName === 'CUSTOM_CHALLENGE') { this.Session = dataAuthenticate.Session; return callback.customChallenge(challengeParameters); } if (challengeName === 'NEW_PASSWORD_REQUIRED') { this.Session = dataAuthenticate.Session; var userAttributes = null; var rawRequiredAttributes = null; var requiredAttributes = []; var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix(); if (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); } if (challengeName === 'DEVICE_SRP_AUTH') { this.getDeviceResponse(callback); return undefined; } this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult); this.challengeName = challengeName; 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, function (errGenHash) { if (errGenHash) { return callback.onFailure(errGenHash); } var deviceSecretVerifierConfig = { Salt: buffer["Buffer"].from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'), PasswordVerifier: buffer["Buffer"].from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64') }; _this4.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; _this4.deviceGroupKey = newDeviceMetadata.DeviceGroupKey; _this4.randomPassword = authenticationHelper.getRandomPassword(); _this4.client.request('ConfirmDevice', { DeviceKey: newDeviceMetadata.DeviceKey, AccessToken: _this4.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent }, function (errConfirm, dataConfirm) { if (errConfirm) { return callback.onFailure(errConfirm); } _this4.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; _this4.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess(_this4.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(_this4.signInUserSession); }); return undefined; }); 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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.completeNewPasswordChallenge = function completeNewPasswordChallenge(newPassword, requiredAttributeData, callback, clientMetadata) { var _this5 = this; if (!newPassword) { return callback.onFailure(new Error('New password is required.')); } var authenticationHelper = new AuthenticationHelper_AuthenticationHelper(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; var jsonReq = { ChallengeName: 'NEW_PASSWORD_REQUIRED', ClientId: this.pool.getClientId(), ChallengeResponses: finalUserAttributes, Session: this.Session, ClientMetadata: clientMetadata }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('RespondToAuthChallenge', jsonReq, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } return _this5.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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} * @private */ ; _proto.getDeviceResponse = function getDeviceResponse(callback, clientMetadata) { var _this6 = this; var authenticationHelper = new AuthenticationHelper_AuthenticationHelper(this.deviceGroupKey); var dateHelper = new DateHelper(); var authParameters = {}; authParameters.USERNAME = this.username; authParameters.DEVICE_KEY = this.deviceKey; authenticationHelper.getLargeAValue(function (errAValue, aValue) { // getLargeAValue callback start if (errAValue) { callback.onFailure(errAValue); } authParameters.SRP_A = aValue.toString(16); var jsonReq = { ChallengeName: 'DEVICE_SRP_AUTH', ClientId: _this6.pool.getClientId(), ChallengeResponses: authParameters, ClientMetadata: clientMetadata }; if (_this6.getUserContextData()) { jsonReq.UserContextData = _this6.getUserContextData(); } _this6.client.request('RespondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } var challengeParameters = data.ChallengeParameters; var serverBValue = new BigInteger(challengeParameters.SRP_B, 16); var salt = new BigInteger(challengeParameters.SALT, 16); authenticationHelper.getPasswordAuthenticationKey(_this6.deviceKey, _this6.randomPassword, serverBValue, salt, function (errHkdf, hkdf) { // getPasswordAuthenticationKey callback start if (errHkdf) { return callback.onFailure(errHkdf); } var dateNow = dateHelper.getNowString(); var message = core_default.a.lib.WordArray.create(buffer["Buffer"].concat([buffer["Buffer"].from(_this6.deviceGroupKey, 'utf8'), buffer["Buffer"].from(_this6.deviceKey, 'utf8'), buffer["Buffer"].from(challengeParameters.SECRET_BLOCK, 'base64'), buffer["Buffer"].from(dateNow, 'utf8')])); var key = core_default.a.lib.WordArray.create(hkdf); var signatureString = enc_base64_default.a.stringify(hmac_sha256_default()(message, key)); var challengeResponses = {}; challengeResponses.USERNAME = _this6.username; challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK; challengeResponses.TIMESTAMP = dateNow; challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString; challengeResponses.DEVICE_KEY = _this6.deviceKey; var jsonReqResp = { ChallengeName: 'DEVICE_PASSWORD_VERIFIER', ClientId: _this6.pool.getClientId(), ChallengeResponses: challengeResponses, Session: data.Session }; if (_this6.getUserContextData()) { jsonReqResp.UserContextData = _this6.getUserContextData(); } _this6.client.request('RespondToAuthChallenge', jsonReqResp, function (errAuthenticate, dataAuthenticate) { if (errAuthenticate) { return callback.onFailure(errAuthenticate); } _this6.signInUserSession = _this6.getCognitoUserSession(dataAuthenticate.AuthenticationResult); _this6.cacheTokens(); return callback.onSuccess(_this6.signInUserSession); }); return undefined; // getPasswordAuthenticationKey callback end }); return undefined; }); // getLargeAValue callback end }); } /** * 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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.confirmRegistration = function confirmRegistration(confirmationCode, forceAliasCreation, callback, clientMetadata) { var jsonReq = { ClientId: this.pool.getClientId(), ConfirmationCode: confirmationCode, Username: this.username, ForceAliasCreation: forceAliasCreation, ClientMetadata: clientMetadata }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('ConfirmSignUp', jsonReq, 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 challenge 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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.sendCustomChallengeAnswer = function sendCustomChallengeAnswer(answerChallenge, callback, clientMetadata) { var _this7 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; var authenticationHelper = new AuthenticationHelper_AuthenticationHelper(this.pool.getUserPoolId().split('_')[1]); this.getCachedDeviceKeyAndPassword(); if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } var jsonReq = { ChallengeName: 'CUSTOM_CHALLENGE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session, ClientMetadata: clientMetadata }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } return _this7.authenticateUserInternal(data, authenticationHelper, callback); }); } /** * 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 {string} mfaType The mfa we are replying to. * @param {onFailure} callback.onFailure Called on any error. * @param {authSuccess} callback.onSuccess Called on success with the new session. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.sendMFACode = function sendMFACode(confirmationCode, callback, mfaType, clientMetadata) { var _this8 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.SMS_MFA_CODE = confirmationCode; var mfaTypeSelection = mfaType || 'SMS_MFA'; if (mfaTypeSelection === 'SOFTWARE_TOKEN_MFA') { challengeResponses.SOFTWARE_TOKEN_MFA_CODE = confirmationCode; } if (this.deviceKey != null) { challengeResponses.DEVICE_KEY = this.deviceKey; } var jsonReq = { ChallengeName: mfaTypeSelection, ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session, ClientMetadata: clientMetadata }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('RespondToAuthChallenge', jsonReq, function (err, dataAuthenticate) { if (err) { return callback.onFailure(err); } var challengeName = dataAuthenticate.ChallengeName; if (challengeName === 'DEVICE_SRP_AUTH') { _this8.getDeviceResponse(callback); return undefined; } _this8.signInUserSession = _this8.getCognitoUserSession(dataAuthenticate.AuthenticationResult); _this8.cacheTokens(); if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) { return callback.onSuccess(_this8.signInUserSession); } var authenticationHelper = new AuthenticationHelper_AuthenticationHelper(_this8.pool.getUserPoolId().split('_')[1]); authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) { if (errGenHash) { return callback.onFailure(errGenHash); } var deviceSecretVerifierConfig = { Salt: buffer["Buffer"].from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'), PasswordVerifier: buffer["Buffer"].from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64') }; _this8.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier; _this8.deviceGroupKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey; _this8.randomPassword = authenticationHelper.getRandomPassword(); _this8.client.request('ConfirmDevice', { DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, AccessToken: _this8.signInUserSession.getAccessToken().getJwtToken(), DeviceSecretVerifierConfig: deviceSecretVerifierConfig, DeviceName: navigator.userAgent }, function (errConfirm, dataConfirm) { if (errConfirm) { return callback.onFailure(errConfirm); } _this8.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey; _this8.cacheDeviceKeyAndPassword(); if (dataConfirm.UserConfirmationNecessary === true) { return callback.onSuccess(_this8.signInUserSession, dataConfirm.UserConfirmationNecessary); } return callback.onSuccess(_this8.signInUserSession); }); return undefined; }); 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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.changePassword = function changePassword(oldUserPassword, newUserPassword, callback, clientMetadata) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.request('ChangePassword', { PreviousPassword: oldUserPassword, ProposedPassword: newUserPassword, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), ClientMetadata: clientMetadata }, 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 itself * @deprecated * @param {nodeCallback} callback Called on success or error. * @returns {void} */ ; _proto.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.request('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 enable MFA for itself * @param {IMfaSettings} smsMfaSettings the sms mfa settings * @param {IMFASettings} softwareTokenMfaSettings the software token mfa settings * @param {nodeCallback} callback Called on success or error. * @returns {void} */ ; _proto.setUserMfaPreference = function setUserMfaPreference(smsMfaSettings, softwareTokenMfaSettings, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.request('SetUserMFAPreference', { SMSMfaSettings: smsMfaSettings, SoftwareTokenMfaSettings: softwareTokenMfaSettings, 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 itself * @deprecated * @param {nodeCallback} callback Called on success or error. * @returns {void} */ ; _proto.disableMFA = function disableMFA(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } var mfaOptions = []; this.client.request('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 itself * @param {nodeCallback} callback Called on success or error. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.deleteUser = function deleteUser(callback, clientMetadata) { var _this9 = this; if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.request('DeleteUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), ClientMetadata: clientMetadata }, function (err) { if (err) { return callback(err, null); } _this9.clearCachedUser(); 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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.updateAttributes = function updateAttributes(attributes, callback, clientMetadata) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback(new Error('User is not authenticated'), null); } this.client.request('UpdateUserAttributes', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserAttributes: attributes, ClientMetadata: clientMetadata }, 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} */ ; _proto.getUserAttributes = function getUserAttributes(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.request('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 CognitoUserAttribute(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} */ ; _proto.getMFAOptions = function getMFAOptions(callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.request('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 users to get the userData * @param {nodeCallback} callback Called on success or error. * @returns {void} */ ; _proto.getUserData = function getUserData(callback, params) { var _this10 = this; if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.clearCachedUserData(); return callback(new Error('User is not authenticated'), null); } var bypassCache = params ? params.bypassCache : false; var userData = this.storage.getItem(this.userDataKey); // get the cached user data if (!userData || bypassCache) { this.client.request('GetUser', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, latestUserData) { if (err) { return callback(err, null); } _this10.cacheUserData(latestUserData); var refresh = _this10.signInUserSession.getRefreshToken(); if (refresh && refresh.getToken()) { _this10.refreshSession(refresh, function (refreshError, data) { if (refreshError) { return callback(refreshError, null); } return callback(null, latestUserData); }); } else { return callback(null, latestUserData); } }); } else { try { return callback(null, JSON.parse(userData)); } catch (err) { this.clearCachedUserData(); return callback(err, null); } } 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} */ ; _proto.deleteAttributes = function deleteAttributes(attributeList, callback) { if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { return callback(new Error('User is not authenticated'), null); } this.client.request('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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.resendConfirmationCode = function resendConfirmationCode(callback, clientMetadata) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username, ClientMetadata: clientMetadata }; this.client.request('ResendConfirmationCode', jsonReq, 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} */ ; _proto.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"; var clockDriftKey = keyPrefix + ".clockDrift"; if (this.storage.getItem(idTokenKey)) { var idToken = new CognitoIdToken({ IdToken: this.storage.getItem(idTokenKey) }); var accessToken = new CognitoAccessToken({ AccessToken: this.storage.getItem(accessTokenKey) }); var refreshToken = new CognitoRefreshToken({ RefreshToken: this.storage.getItem(refreshTokenKey) }); var clockDrift = parseInt(this.storage.getItem(clockDriftKey), 0) || 0; var sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken, ClockDrift: clockDrift }; var cachedSession = new CognitoUserSession(sessionData); if (cachedSession.isValid()) { this.signInUserSession = cachedSession; return callback(null, this.signInUserSession); } if (!refreshToken.getToken()) { 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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.refreshSession = function refreshSession(refreshToken, callback, clientMetadata) { var _this11 = 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; } var jsonReq = { ClientId: this.pool.getClientId(), AuthFlow: 'REFRESH_TOKEN_AUTH', AuthParameters: authParameters, ClientMetadata: clientMetadata }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('InitiateAuth', jsonReq, function (err, authResult) { if (err) { if (err.code === 'NotAuthorizedException') { _this11.clearCachedUser(); } return callback(err, null); } if (authResult) { var authenticationResult = authResult.AuthenticationResult; if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) { authenticationResult.RefreshToken = refreshToken.getToken(); } _this11.signInUserSession = _this11.getCognitoUserSession(authenticationResult); _this11.cacheTokens(); return callback(null, _this11.signInUserSession); } return undefined; }); } /** * This is used to save the session tokens to local storage * @returns {void} */ ; _proto.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 clockDriftKey = keyPrefix + "." + this.username + ".clockDrift"; 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(clockDriftKey, "" + this.signInUserSession.getClockDrift()); this.storage.setItem(lastUserKey, this.username); } /** * This is to cache user data */ ; _proto.cacheUserData = function cacheUserData(userData) { this.storage.setItem(this.userDataKey, JSON.stringify(userData)); } /** * This is to remove cached user data */ ; _proto.clearCachedUserData = function clearCachedUserData() { this.storage.removeItem(this.userDataKey); }; _proto.clearCachedUser = function clearCachedUser() { this.clearCachedTokens(); this.clearCachedUserData(); } /** * This is used to cache the device key and device group and device password * @returns {void} */ ; _proto.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} */ ; _proto.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} */ ; _proto.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} */ ; _proto.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"; var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift"; this.storage.removeItem(idTokenKey); this.storage.removeItem(accessTokenKey); this.storage.removeItem(refreshTokenKey); this.storage.removeItem(lastUserKey); this.storage.removeItem(clockDriftKey); } /** * 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 */ ; _proto.getCognitoUserSession = function getCognitoUserSession(authResult) { var idToken = new CognitoIdToken(authResult); var accessToken = new CognitoAccessToken(authResult); var refreshToken = new CognitoRefreshToken(authResult); var sessionData = { IdToken: idToken, AccessToken: accessToken, RefreshToken: refreshToken }; return new CognitoUserSession(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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.forgotPassword = function forgotPassword(callback, clientMetadata) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username, ClientMetadata: clientMetadata }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('ForgotPassword', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } if (typeof callback.inputVerificationCode === 'function') { return callback.inputVerificationCode(data); } return callback.onSuccess(data); }); } /** * 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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.confirmPassword = function confirmPassword(confirmationCode, newPassword, callback, clientMetadata) { var jsonReq = { ClientId: this.pool.getClientId(), Username: this.username, ConfirmationCode: confirmationCode, Password: newPassword, ClientMetadata: clientMetadata }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('ConfirmForgotPassword', jsonReq, 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. * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger * @returns {void} */ ; _proto.getAttributeVerificationCode = function getAttributeVerificationCode(attributeName, callback, clientMetadata) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.request('GetUserAttributeVerificationCode', { AttributeName: attributeName, AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), ClientMetadata: clientMetadata }, 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} */ ; _proto.verifyAttribute = function verifyAttribute(attributeName, confirmationCode, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.request('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} */ ; _proto.getDevice = function getDevice(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.request('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} */ ; _proto.forgetSpecificDevice = function forgetSpecificDevice(deviceKey, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.request('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} */ ; _proto.forgetDevice = function forgetDevice(callback) { var _this12 = this; this.forgetSpecificDevice(this.deviceKey, { onFailure: callback.onFailure, onSuccess: function onSuccess(result) { _this12.deviceKey = null; _this12.deviceGroupKey = null; _this12.randomPassword = null; _this12.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} */ ; _proto.setDeviceStatusRemembered = function setDeviceStatusRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.request('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} */ ; _proto.setDeviceStatusNotRemembered = function setDeviceStatusNotRemembered(callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.request('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} */ ; _proto.listDevices = function listDevices(limit, paginationToken, callback) { if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.request('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} */ ; _proto.globalSignOut = function globalSignOut(callback) { var _this13 = this; if (this.signInUserSession == null || !this.signInUserSession.isValid()) { return callback.onFailure(new Error('User is not authenticated')); } this.client.request('GlobalSignOut', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err) { if (err) { return callback.onFailure(err); } _this13.clearCachedUser(); return callback.onSuccess('SUCCESS'); }); return undefined; } /** * This is used for the user to signOut of the application and clear the cached tokens. * @returns {void} */ ; _proto.signOut = function signOut() { this.signInUserSession = null; this.clearCachedUser(); } /** * This is used by a user trying to select a given MFA * @param {string} answerChallenge the mfa the user wants * @param {nodeCallback} callback Called on success or error. * @returns {void} */ ; _proto.sendMFASelectionAnswer = function sendMFASelectionAnswer(answerChallenge, callback) { var _this14 = this; var challengeResponses = {}; challengeResponses.USERNAME = this.username; challengeResponses.ANSWER = answerChallenge; var jsonReq = { ChallengeName: 'SELECT_MFA_TYPE', ChallengeResponses: challengeResponses, ClientId: this.pool.getClientId(), Session: this.Session }; if (this.getUserContextData()) { jsonReq.UserContextData = this.getUserContextData(); } this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) { if (err) { return callback.onFailure(err); } _this14.Session = data.Session; if (answerChallenge === 'SMS_MFA') { return callback.mfaRequired(data.challengeName, data.challengeParameters); } if (answerChallenge === 'SOFTWARE_TOKEN_MFA') { return callback.totpRequired(data.challengeName, data.challengeParameters); } return undefined; }); } /** * This returns the user context data for advanced security feature. * @returns {void} */ ; _proto.getUserContextData = function getUserContextData() { var pool = this.pool; return pool.getUserContextData(this.username); } /** * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA * @param {nodeCallback} callback Called on success or error. * @returns {void} */ ; _proto.associateSoftwareToken = function associateSoftwareToken(callback) { var _this15 = this; if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.client.request('AssociateSoftwareToken', { Session: this.Session }, function (err, data) { if (err) { return callback.onFailure(err); } _this15.Session = data.Session; return callback.associateSecretCode(data.SecretCode); }); } else { this.client.request('AssociateSoftwareToken', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken() }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.associateSecretCode(data.SecretCode); }); } } /** * This is used by an authenticated or a user trying to authenticate to verify a TOTP MFA * @param {string} totpCode The MFA code entered by the user. * @param {string} friendlyDeviceName The device name we are assigning to the device. * @param {nodeCallback} callback Called on success or error. * @returns {void} */ ; _proto.verifySoftwareToken = function verifySoftwareToken(totpCode, friendlyDeviceName, callback) { var _this16 = this; if (!(this.signInUserSession != null && this.signInUserSession.isValid())) { this.client.request('VerifySoftwareToken', { Session: this.Session, UserCode: totpCode, FriendlyDeviceName: friendlyDeviceName }, function (err, data) { if (err) { return callback.onFailure(err); } _this16.Session = data.Session; var challengeResponses = {}; challengeResponses.USERNAME = _this16.username; var jsonReq = { ChallengeName: 'MFA_SETUP', ClientId: _this16.pool.getClientId(), ChallengeResponses: challengeResponses, Session: _this16.Session }; if (_this16.getUserContextData()) { jsonReq.UserContextData = _this16.getUserContextData(); } _this16.client.request('RespondToAuthChallenge', jsonReq, function (errRespond, dataRespond) { if (errRespond) { return callback.onFailure(errRespond); } _this16.signInUserSession = _this16.getCognitoUserSession(dataRespond.AuthenticationResult); _this16.cacheTokens(); return callback.onSuccess(_this16.signInUserSession); }); return undefined; }); } else { this.client.request('VerifySoftwareToken', { AccessToken: this.signInUserSession.getAccessToken().getJwtToken(), UserCode: totpCode, FriendlyDeviceName: friendlyDeviceName }, function (err, data) { if (err) { return callback.onFailure(err); } return callback.onSuccess(data); }); } }; return CognitoUser; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/UserAgent.js // class for defining the amzn user-agent /* harmony default export */ var UserAgent = (UserAgent_UserAgent); // constructor function UserAgent_UserAgent() {} // public UserAgent_UserAgent.prototype.userAgent = 'aws-amplify/0.1.x js'; // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/Client.js /** @class */ var Client_Client = /*#__PURE__*/ function () { /** * Constructs a new AWS Cognito Identity Provider client object * @param {string} region AWS region * @param {string} endpoint endpoint */ function Client(region, endpoint) { this.endpoint = endpoint || "https://cognito-idp." + region + ".amazonaws.com/"; this.userAgent = UserAgent.prototype.userAgent || 'aws-amplify/0.1.x js'; } /** * Makes an unauthenticated request on AWS Cognito Identity Provider API * using fetch * @param {string} operation API operation * @param {object} params Input parameters * @param {function} callback Callback called when a response is returned * @returns {void} */ var _proto = Client.prototype; _proto.request = function request(operation, params, callback) { var headers = { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': "AWSCognitoIdentityProviderService." + operation, 'X-Amz-User-Agent': this.userAgent }; var options = { headers: headers, method: 'POST', mode: 'cors', cache: 'no-cache', body: JSON.stringify(params) }; var response; var responseJsonData; fetch(this.endpoint, options).then(function (resp) { response = resp; return resp; }, function (err) { // If error happens here, the request failed // if it is TypeError throw network error if (err instanceof TypeError) { throw new Error('Network error'); } throw err; }).then(function (resp) { return resp.json()["catch"](function () { return {}; }); }).then(function (data) { // return parsed body stream if (response.ok) return callback(null, data); responseJsonData = data; // Taken from aws-sdk-js/lib/protocol/json.js // eslint-disable-next-line no-underscore-dangle var code = (data.__type || data.code).split('#').pop(); var error = { code: code, name: code, message: data.message || data.Message || null }; return callback(error); })["catch"](function (err) { // first check if we have a service error if (response && response.headers && response.headers.get('x-amzn-errortype')) { try { var code = response.headers.get('x-amzn-errortype').split(':')[0]; var error = { code: code, name: code, statusCode: response.status, message: response.status ? response.status.toString() : null }; return callback(error); } catch (ex) { return callback(err); } // otherwise check if error is Network error } else if (err instanceof Error && err.message === 'Network error') { var _error = { code: 'NetworkError', name: err.name, message: err.message }; return callback(_error); } else { return callback(err); } }); }; return Client; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CognitoUserPool.js /*! * 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_CognitoUserPool = /*#__PURE__*/ 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. * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional: * boolean flag indicating if the data collection is enabled * to support cognito advanced security features. By default, this * flag is set to true. */ function CognitoUserPool(data) { var _ref = data || {}, UserPoolId = _ref.UserPoolId, ClientId = _ref.ClientId, endpoint = _ref.endpoint, AdvancedSecurityDataCollectionFlag = _ref.AdvancedSecurityDataCollectionFlag; 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 Client_Client(region, endpoint); /** * By default, AdvancedSecurityDataCollectionFlag is set to true, * if no input value is provided. */ this.advancedSecurityDataCollectionFlag = AdvancedSecurityDataCollectionFlag !== false; this.storage = data.Storage || new StorageHelper_StorageHelper().getStorage(); } /** * @returns {string} the user pool id */ var _proto = CognitoUserPool.prototype; _proto.getUserPoolId = function getUserPoolId() { return this.userPoolId; } /** * @returns {string} the client id */ ; _proto.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 {(AttributeArg[])=} clientMetadata Client metadata. * @param {nodeCallback} callback Called on error or with the new user. * @returns {void} */ ; _proto.signUp = function signUp(username, password, userAttributes, validationData, callback, clientMetadata) { var _this = this; var jsonReq = { ClientId: this.clientId, Username: username, Password: password, UserAttributes: userAttributes, ValidationData: validationData, ClientMetadata: clientMetadata }; if (this.getUserContextData(username)) { jsonReq.UserContextData = this.getUserContextData(username); } this.client.request('SignUp', jsonReq, function (err, data) { if (err) { return callback(err, null); } var cognitoUser = { Username: username, Pool: _this, Storage: _this.storage }; var returnData = { user: new CognitoUser_CognitoUser(cognitoUser), userConfirmed: data.UserConfirmed, userSub: data.UserSub, codeDeliveryDetails: data.CodeDeliveryDetails }; return callback(null, returnData); }); } /** * method for getting the current user of the application from the local storage * * @returns {CognitoUser} the user retrieved from storage */ ; _proto.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 CognitoUser_CognitoUser(cognitoUser); } return null; } /** * This method returns the encoded data string used for cognito advanced security feature. * This would be generated only when developer has included the JS used for collecting the * data on their client. Please refer to documentation to know more about using AdvancedSecurity * features * @param {string} username the username for the context data * @returns {string} the user context data **/ ; _proto.getUserContextData = function getUserContextData(username) { if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') { return undefined; } /* eslint-disable */ var amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData; /* eslint-enable */ if (this.advancedSecurityDataCollectionFlag) { var advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData(username, this.userPoolId, this.clientId); if (advancedSecurityData) { var userContextData = { EncodedData: advancedSecurityData }; return userContextData; } } return {}; }; return CognitoUserPool; }(); // EXTERNAL MODULE: ./node_modules/js-cookie/src/js.cookie.js var js_cookie = __webpack_require__("a78e"); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/CookieStorage.js /** @class */ var CookieStorage_CookieStorage = /*#__PURE__*/ function () { /** * Constructs a new CookieStorage object * @param {object} data Creation options. * @param {string} data.domain Cookies domain (mandatory). * @param {string} data.path Cookies path (default: '/') * @param {integer} data.expires Cookie expiration (in days, default: 365) * @param {boolean} data.secure Cookie secure flag (default: true) */ function CookieStorage(data) { if (data.domain) { this.domain = data.domain; } else { throw new Error('The domain of cookieStorage can not be undefined.'); } if (data.path) { this.path = data.path; } else { this.path = '/'; } if (Object.prototype.hasOwnProperty.call(data, 'expires')) { this.expires = data.expires; } else { this.expires = 365; } if (Object.prototype.hasOwnProperty.call(data, 'secure')) { this.secure = data.secure; } else { this.secure = true; } } /** * 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 */ var _proto = CookieStorage.prototype; _proto.setItem = function setItem(key, value) { js_cookie["set"](key, value, { path: this.path, expires: this.expires, domain: this.domain, secure: this.secure }); return js_cookie["get"](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 */ ; _proto.getItem = function getItem(key) { return js_cookie["get"](key); } /** * This is used to remove an item from storage * @param {string} key - the key being set * @returns {string} value - value that was deleted */ ; _proto.removeItem = function removeItem(key) { return js_cookie["remove"](key, { path: this.path, domain: this.domain, secure: this.secure }); } /** * This is used to clear the storage * @returns {string} nothing */ ; _proto.clear = function clear() { var cookies = js_cookie["get"](); var index; for (index = 0; index < cookies.length; ++index) { js_cookie["remove"](cookies[index]); } return {}; }; return CookieStorage; }(); // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/index.js /*! * 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. */ // EXTERNAL MODULE: ./node_modules/url/url.js var url_url = __webpack_require__("0b16"); // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/OAuth/urlOpener.js /* * Copyright 2017-2017 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 SELF = '_self'; var launchUri = function (url) { var windowProxy = window.open(url, SELF); if (windowProxy) { return Promise.resolve(windowProxy); } else { return Promise.reject(); } }; //# sourceMappingURL=urlOpener.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/OAuth/oauthStorage.js /* * Copyright 2017-2017 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 setState = function (state) { window.sessionStorage.setItem('oauth_state', state); }; var getState = function () { var oauth_state = window.sessionStorage.getItem('oauth_state'); window.sessionStorage.removeItem('oauth_state'); return oauth_state; }; var setPKCE = function (private_key) { window.sessionStorage.setItem('ouath_pkce_key', private_key); }; var getPKCE = function () { var ouath_pkce_key = window.sessionStorage.getItem('ouath_pkce_key'); window.sessionStorage.removeItem('ouath_pkce_key'); return ouath_pkce_key; }; var clearAll = function () { window.sessionStorage.removeItem('ouath_pkce_key'); window.sessionStorage.removeItem('oauth_state'); }; //# sourceMappingURL=oauthStorage.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/OAuth/OAuth.js /* * Copyright 2017-2017 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 OAuth_assign = (undefined && undefined.__assign) || function () { OAuth_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return OAuth_assign.apply(this, arguments); }; var OAuth_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var OAuth_generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; // Used for OAuth parsing of Cognito Hosted UI var SHA256 = __webpack_require__("94f8"); var Base64 = __webpack_require__("1132"); var OAuth_AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function' ? Symbol.for('amplify_default') : '@@amplify_default'); var dispatchAuthEvent = function (event, data, message) { lib_esm_Hub.dispatch('auth', { event: event, data: data, message: message }, 'Auth', OAuth_AMPLIFY_SYMBOL); }; var OAuth_logger = new ConsoleLogger('OAuth'); var OAuth_OAuth = /** @class */ (function () { function OAuth(_a) { var config = _a.config, cognitoClientId = _a.cognitoClientId, _b = _a.scopes, scopes = _b === void 0 ? [] : _b; this._urlOpener = config.urlOpener || launchUri; this._config = config; this._cognitoClientId = cognitoClientId; this._scopes = scopes; } OAuth.prototype.oauthSignIn = function (responseType, domain, redirectSignIn, clientId, provider, customState) { if (responseType === void 0) { responseType = 'code'; } if (provider === void 0) { provider = CognitoHostedUIIdentityProvider.Cognito; } var generatedState = this._generateState(32); var state = customState ? generatedState + "-" + customState : generatedState; setState(encodeURIComponent(state)); var pkce_key = this._generateRandom(128); setPKCE(pkce_key); var code_challenge = this._generateChallenge(pkce_key); var code_challenge_method = 'S256'; var queryString = Object.entries(OAuth_assign(OAuth_assign({ redirect_uri: redirectSignIn, response_type: responseType, client_id: clientId, identity_provider: provider, scopes: this._scopes, state: state }, (responseType === 'code' ? { code_challenge: code_challenge } : {})), (responseType === 'code' ? { code_challenge_method: code_challenge_method } : {}))) .map(function (_a) { var k = _a[0], v = _a[1]; return encodeURIComponent(k) + "=" + encodeURIComponent(v); }) .join('&'); var URL = "https://" + domain + "/oauth2/authorize?" + queryString; OAuth_logger.debug("Redirecting to " + URL); this._urlOpener(URL, redirectSignIn); }; OAuth.prototype._handleCodeFlow = function (currentUrl) { return OAuth_awaiter(this, void 0, void 0, function () { var code, oAuthTokenEndpoint, client_id, redirect_uri, code_verifier, oAuthTokenBody, body, _a, access_token, refresh_token, id_token, error; return OAuth_generator(this, function (_b) { switch (_b.label) { case 0: code = (Object(url_url["parse"])(currentUrl).query || '') .split('&') .map(function (pairings) { return pairings.split('='); }) .reduce(function (accum, _a) { var _b; var k = _a[0], v = _a[1]; return (OAuth_assign(OAuth_assign({}, accum), (_b = {}, _b[k] = v, _b))); }, { code: undefined }).code; if (!code) { return [2 /*return*/]; } oAuthTokenEndpoint = 'https://' + this._config.domain + '/oauth2/token'; dispatchAuthEvent('codeFlow', {}, "Retrieving tokens from " + oAuthTokenEndpoint); client_id = isCognitoHostedOpts(this._config) ? this._cognitoClientId : this._config.clientID; redirect_uri = isCognitoHostedOpts(this._config) ? this._config.redirectSignIn : this._config.redirectUri; code_verifier = getPKCE(); oAuthTokenBody = OAuth_assign({ grant_type: 'authorization_code', code: code, client_id: client_id, redirect_uri: redirect_uri }, (code_verifier ? { code_verifier: code_verifier } : {})); OAuth_logger.debug("Calling token endpoint: " + oAuthTokenEndpoint + " with", oAuthTokenBody); body = Object.entries(oAuthTokenBody) .map(function (_a) { var k = _a[0], v = _a[1]; return encodeURIComponent(k) + "=" + encodeURIComponent(v); }) .join('&'); return [4 /*yield*/, fetch(oAuthTokenEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: body, })]; case 1: return [4 /*yield*/, (_b.sent()).json()]; case 2: _a = _b.sent(), access_token = _a.access_token, refresh_token = _a.refresh_token, id_token = _a.id_token, error = _a.error; if (error) { throw new Error(error); } return [2 /*return*/, { accessToken: access_token, refreshToken: refresh_token, idToken: id_token, }]; } }); }); }; OAuth.prototype._handleImplicitFlow = function (currentUrl) { return OAuth_awaiter(this, void 0, void 0, function () { var _a, id_token, access_token; return OAuth_generator(this, function (_b) { _a = Object(url_url["parse"])(currentUrl) .hash.substr(1) // Remove # from returned code .split('&') .map(function (pairings) { return pairings.split('='); }) .reduce(function (accum, _a) { var _b; var k = _a[0], v = _a[1]; return (OAuth_assign(OAuth_assign({}, accum), (_b = {}, _b[k] = v, _b))); }, { id_token: undefined, access_token: undefined, }), id_token = _a.id_token, access_token = _a.access_token; dispatchAuthEvent('implicitFlow', {}, "Got tokens from " + currentUrl); OAuth_logger.debug("Retrieving implicit tokens from " + currentUrl + " with"); return [2 /*return*/, { accessToken: access_token, idToken: id_token, refreshToken: null, }]; }); }); }; OAuth.prototype.handleAuthResponse = function (currentUrl) { return OAuth_awaiter(this, void 0, void 0, function () { var urlParams, error, error_description, state, _a, _b, e_1; return OAuth_generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 5, , 6]); urlParams = currentUrl ? OAuth_assign(OAuth_assign({}, (Object(url_url["parse"])(currentUrl).hash || '#') .substr(1) .split('&') .map(function (entry) { return entry.split('='); }) .reduce(function (acc, _a) { var k = _a[0], v = _a[1]; return ((acc[k] = v), acc); }, {})), (Object(url_url["parse"])(currentUrl).query || '') .split('&') .map(function (entry) { return entry.split('='); }) .reduce(function (acc, _a) { var k = _a[0], v = _a[1]; return ((acc[k] = v), acc); }, {})) : {}; error = urlParams.error, error_description = urlParams.error_description; if (error) { throw new Error(error_description); } state = this._validateState(urlParams); OAuth_logger.debug("Starting " + this._config.responseType + " flow with " + currentUrl); if (!(this._config.responseType === 'code')) return [3 /*break*/, 2]; _a = [{}]; return [4 /*yield*/, this._handleCodeFlow(currentUrl)]; case 1: return [2 /*return*/, OAuth_assign.apply(void 0, [OAuth_assign.apply(void 0, _a.concat([(_c.sent())])), { state: state }])]; case 2: _b = [{}]; return [4 /*yield*/, this._handleImplicitFlow(currentUrl)]; case 3: return [2 /*return*/, OAuth_assign.apply(void 0, [OAuth_assign.apply(void 0, _b.concat([(_c.sent())])), { state: state }])]; case 4: return [3 /*break*/, 6]; case 5: e_1 = _c.sent(); OAuth_logger.error("Error handling auth response.", e_1); return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); }; OAuth.prototype._validateState = function (urlParams) { if (!urlParams) { return; } var savedState = getState(); var returnedState = urlParams.state; // This is because savedState only exists if the flow was initiated by Amplify if (savedState && savedState !== returnedState) { throw new Error('Invalid state in OAuth flow'); } return returnedState; }; OAuth.prototype.signOut = function () { return OAuth_awaiter(this, void 0, void 0, function () { var oAuthLogoutEndpoint, client_id, signout_uri; return OAuth_generator(this, function (_a) { oAuthLogoutEndpoint = 'https://' + this._config.domain + '/logout?'; client_id = isCognitoHostedOpts(this._config) ? this._cognitoClientId : this._config.oauth.clientID; signout_uri = isCognitoHostedOpts(this._config) ? this._config.redirectSignOut : this._config.returnTo; oAuthLogoutEndpoint += Object.entries({ client_id: client_id, logout_uri: encodeURIComponent(signout_uri), }) .map(function (_a) { var k = _a[0], v = _a[1]; return k + "=" + v; }) .join('&'); dispatchAuthEvent('oAuthSignOut', { oAuth: 'signOut' }, "Signing out from " + oAuthLogoutEndpoint); OAuth_logger.debug("Signing out from " + oAuthLogoutEndpoint); return [2 /*return*/, this._urlOpener(oAuthLogoutEndpoint)]; }); }); }; OAuth.prototype._generateState = function (length) { var result = ''; var i = length; var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; for (; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))]; return result; }; OAuth.prototype._generateChallenge = function (code) { return this._base64URL(SHA256(code)); }; OAuth.prototype._base64URL = function (string) { return string .toString(Base64) .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); }; OAuth.prototype._generateRandom = function (size) { var CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; var buffer = new Uint8Array(size); if (typeof window !== 'undefined' && !!window.crypto) { window.crypto.getRandomValues(buffer); } else { for (var i = 0; i < size; i += 1) { buffer[i] = (Math.random() * CHARSET.length) | 0; } } return this._bufferToString(buffer); }; OAuth.prototype._bufferToString = function (buffer) { var CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var state = []; for (var i = 0; i < buffer.byteLength; i += 1) { var index = buffer[i] % CHARSET.length; state.push(CHARSET[index]); } return state.join(''); }; return OAuth; }()); /* harmony default export */ var lib_esm_OAuth_OAuth = (OAuth_OAuth); //# sourceMappingURL=OAuth.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/urlListener.js /* * Copyright 2017-2019 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. */ /* harmony default export */ var urlListener = (function (callback) { if (JS["a" /* default */].browserOrNode().isBrowser && window.location) { var url = window.location.href; callback({ url: url }); } else if (JS["a" /* default */].browserOrNode().isNode) { // continue building on ssr (function () { }); // noop } else { throw new Error('Not supported'); } }); //# sourceMappingURL=urlListener.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/Errors.js /* * Copyright 2019-2020 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 Errors_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Errors_logger = new ConsoleLogger('AuthError'); var DEFAULT_MSG = 'Authentication Error'; var AuthError = /** @class */ (function (_super) { Errors_extends(AuthError, _super); function AuthError(type) { var _this = this; var _a = authErrorMessages[type], message = _a.message, log = _a.log; _this = _super.call(this, message) || this; // Hack for making the custom error class work when transpiled to es5 // TODO: Delete the following 2 lines after we change the build target to >= es2015 _this.constructor = AuthError; Object.setPrototypeOf(_this, AuthError.prototype); _this.name = 'AuthError'; _this.log = log || message; Errors_logger.error(_this.log); return _this; } return AuthError; }(Error)); var NoUserPoolError = /** @class */ (function (_super) { Errors_extends(NoUserPoolError, _super); function NoUserPoolError(type) { var _this = _super.call(this, type) || this; // Hack for making the custom error class work when transpiled to es5 // TODO: Delete the following 2 lines after we change the build target to >= es2015 _this.constructor = NoUserPoolError; Object.setPrototypeOf(_this, NoUserPoolError.prototype); _this.name = 'NoUserPoolError'; return _this; } return NoUserPoolError; }(AuthError)); var authErrorMessages = { noConfig: { message: DEFAULT_MSG, log: "\n Error: Amplify has not been configured correctly.\n This error is typically caused by one of the following scenarios:\n\n 1. Make sure you're passing the awsconfig object to Amplify.configure() in your app's entry point\n See https://aws-amplify.github.io/docs/js/authentication#configure-your-app for more information\n \n 2. There might be multiple conflicting versions of aws-amplify or amplify packages in your node_modules.\n Try deleting your node_modules folder and reinstalling the dependencies with `yarn install`\n ", }, missingAuthConfig: { message: DEFAULT_MSG, log: "\n Error: Amplify has not been configured correctly. \n The configuration object is missing required auth properties. \n Did you run `amplify push` after adding auth via `amplify add auth`?\n See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information\n ", }, emptyUsername: { message: 'Username cannot be empty', }, // TODO: should include a list of valid sign-in types invalidUsername: { message: 'The username should either be a string or one of the sign in types', }, emptyPassword: { message: 'Password cannot be empty', }, emptyCode: { message: 'Confirmation code cannot be empty', }, signUpError: { message: 'Error creating account', log: 'The first parameter should either be non-null string or object', }, noMFA: { message: 'No valid MFA method provided', }, invalidMFA: { message: 'Invalid MFA type', }, emptyChallengeResponse: { message: 'Challenge response cannot be empty', }, noUserSession: { message: 'Failed to get the session because the user is empty', }, default: { message: DEFAULT_MSG, }, }; //# sourceMappingURL=Errors.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/Auth.js /* * Copyright 2017-2019 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 Auth_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Auth_generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var Auth_logger = new ConsoleLogger('AuthClass'); var USER_ADMIN_SCOPE = 'aws.cognito.signin.user.admin'; var Auth_AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function' ? Symbol.for('amplify_default') : '@@amplify_default'); var Auth_dispatchAuthEvent = function (event, data, message) { lib_esm_Hub.dispatch('auth', { event: event, data: data, message: message }, 'Auth', Auth_AMPLIFY_SYMBOL); }; var Auth_CognitoHostedUIIdentityProvider; (function (CognitoHostedUIIdentityProvider) { CognitoHostedUIIdentityProvider["Cognito"] = "COGNITO"; CognitoHostedUIIdentityProvider["Google"] = "Google"; CognitoHostedUIIdentityProvider["Facebook"] = "Facebook"; CognitoHostedUIIdentityProvider["Amazon"] = "LoginWithAmazon"; })(Auth_CognitoHostedUIIdentityProvider || (Auth_CognitoHostedUIIdentityProvider = {})); /** * Provide authentication steps */ var Auth_AuthClass = /** @class */ (function () { /** * Initialize Auth with AWS configurations * @param {Object} config - Configuration of the Auth */ function AuthClass(config) { var _this = this; this.userPool = null; this.user = null; this.configure(config); this.currentUserCredentials = this.currentUserCredentials.bind(this); if (browser.config) { browser.config.update({ customUserAgent: Constants.userAgent }); } else { Auth_logger.warn('No AWS.config'); } lib_esm_Hub.listen('auth', function (_a) { var payload = _a.payload; var event = payload.event; switch (event) { case 'signIn': _this._storage.setItem('amplify-signin-with-hostedUI', 'false'); break; case 'signOut': _this._storage.removeItem('amplify-signin-with-hostedUI'); break; case 'cognitoHostedUI': _this._storage.setItem('amplify-signin-with-hostedUI', 'true'); break; } }); } AuthClass.prototype.getModuleName = function () { return 'Auth'; }; AuthClass.prototype.configure = function (config) { var _this = this; if (!config) return this._config || {}; Auth_logger.debug('configure Auth'); var conf = Object.assign({}, this._config, lib_esm_Parser.parseMobilehubConfig(config).Auth, config); this._config = conf; var _a = this._config, userPoolId = _a.userPoolId, userPoolWebClientId = _a.userPoolWebClientId, cookieStorage = _a.cookieStorage, oauth = _a.oauth, region = _a.region, identityPoolId = _a.identityPoolId, mandatorySignIn = _a.mandatorySignIn, refreshHandlers = _a.refreshHandlers, identityPoolRegion = _a.identityPoolRegion, clientMetadata = _a.clientMetadata; if (!this._config.storage) { // backward compatbility if (cookieStorage) this._storage = new CookieStorage_CookieStorage(cookieStorage); else { this._storage = new lib_esm_StorageHelper().getStorage(); } } else { if (!this._isValidAuthStorage(this._config.storage)) { Auth_logger.error('The storage in the Auth config is not valid!'); throw new Error('Empty storage object'); } this._storage = this._config.storage; } this._storageSync = Promise.resolve(); if (typeof this._storage['sync'] === 'function') { this._storageSync = this._storage['sync'](); } if (userPoolId) { var userPoolData = { UserPoolId: userPoolId, ClientId: userPoolWebClientId, }; userPoolData.Storage = this._storage; this.userPool = new CognitoUserPool_CognitoUserPool(userPoolData); } lib_esm_Credentials.configure({ mandatorySignIn: mandatorySignIn, region: identityPoolRegion || region, userPoolId: userPoolId, identityPoolId: identityPoolId, refreshHandlers: refreshHandlers, storage: this._storage, }); // initiailize cognitoauth client if hosted ui options provided // to keep backward compatibility: var cognitoHostedUIConfig = oauth ? isCognitoHostedOpts(this._config.oauth) ? oauth : oauth.awsCognito : undefined; if (cognitoHostedUIConfig) { var cognitoAuthParams = Object.assign({ cognitoClientId: userPoolWebClientId, UserPoolId: userPoolId, domain: cognitoHostedUIConfig['domain'], scopes: cognitoHostedUIConfig['scope'], redirectSignIn: cognitoHostedUIConfig['redirectSignIn'], redirectSignOut: cognitoHostedUIConfig['redirectSignOut'], responseType: cognitoHostedUIConfig['responseType'], Storage: this._storage, urlOpener: cognitoHostedUIConfig['urlOpener'], clientMetadata: clientMetadata, }, cognitoHostedUIConfig['options']); this._oAuthHandler = new lib_esm_OAuth_OAuth({ scopes: cognitoAuthParams.scopes, config: cognitoAuthParams, cognitoClientId: cognitoAuthParams.cognitoClientId, }); // **NOTE** - Remove this in a future major release as it is a breaking change urlListener(function (_a) { var url = _a.url; _this._handleAuthResponse(url); }); } Auth_dispatchAuthEvent('configured', null, "The Auth category has been configured successfully"); return this._config; }; /** * Sign up with username, password and other attrbutes like phone, email * @param {String | object} params - The user attirbutes used for signin * @param {String[]} restOfAttrs - for the backward compatability * @return - A promise resolves callback data if success */ AuthClass.prototype.signUp = function (params) { var _this = this; var restOfAttrs = []; for (var _i = 1; _i < arguments.length; _i++) { restOfAttrs[_i - 1] = arguments[_i]; } if (!this.userPool) { return this.rejectNoUserPool(); } var username = null; var password = null; var attributes = []; var validationData = null; var clientMetadata; if (params && typeof params === 'string') { username = params; password = restOfAttrs ? restOfAttrs[0] : null; var email = restOfAttrs ? restOfAttrs[1] : null; var phone_number = restOfAttrs ? restOfAttrs[2] : null; if (email) attributes.push({ Name: 'email', Value: email }); if (phone_number) attributes.push({ Name: 'phone_number', Value: phone_number }); } else if (params && typeof params === 'object') { username = params['username']; password = params['password']; if (params && params.clientMetadata) { clientMetadata = params.clientMetadata; } else if (this._config.clientMetadata) { clientMetadata = this._config.clientMetadata; } var attrs_1 = params['attributes']; if (attrs_1) { Object.keys(attrs_1).map(function (key) { var ele = { Name: key, Value: attrs_1[key] }; attributes.push(ele); }); } validationData = params['validationData'] || null; } else { return this.rejectAuthError(AuthErrorTypes.SignUpError); } if (!username) { return this.rejectAuthError(AuthErrorTypes.EmptyUsername); } if (!password) { return this.rejectAuthError(AuthErrorTypes.EmptyPassword); } Auth_logger.debug('signUp attrs:', attributes); Auth_logger.debug('signUp validation data:', validationData); return new Promise(function (resolve, reject) { _this.userPool.signUp(username, password, attributes, validationData, function (err, data) { if (err) { Auth_dispatchAuthEvent('signUp_failure', err, username + " failed to signup"); reject(err); } else { Auth_dispatchAuthEvent('signUp', data, username + " has signed up successfully"); resolve(data); } }, clientMetadata); }); }; /** * Send the verfication code to confirm sign up * @param {String} username - The username to be confirmed * @param {String} code - The verification code * @param {ConfirmSignUpOptions} options - other options for confirm signup * @return - A promise resolves callback data if success */ AuthClass.prototype.confirmSignUp = function (username, code, options) { if (!this.userPool) { return this.rejectNoUserPool(); } if (!username) { return this.rejectAuthError(AuthErrorTypes.EmptyUsername); } if (!code) { return this.rejectAuthError(AuthErrorTypes.EmptyCode); } var user = this.createCognitoUser(username); var forceAliasCreation = options && typeof options.forceAliasCreation === 'boolean' ? options.forceAliasCreation : true; var clientMetadata; if (options && options.clientMetadata) { clientMetadata = options.clientMetadata; } else if (this._config.clientMetadata) { clientMetadata = this._config.clientMetadata; } return new Promise(function (resolve, reject) { user.confirmRegistration(code, forceAliasCreation, function (err, data) { if (err) { reject(err); } else { resolve(data); } }, clientMetadata); }); }; /** * Resend the verification code * @param {String} username - The username to be confirmed * @param {ClientMetadata} clientMetadata - Metadata to be passed to Cognito Lambda triggers * @return - A promise resolves data if success */ AuthClass.prototype.resendSignUp = function (username, clientMetadata) { if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } if (!this.userPool) { return this.rejectNoUserPool(); } if (!username) { return this.rejectAuthError(AuthErrorTypes.EmptyUsername); } var user = this.createCognitoUser(username); return new Promise(function (resolve, reject) { user.resendConfirmationCode(function (err, data) { if (err) { reject(err); } else { resolve(data); } }, clientMetadata); }); }; /** * Sign in * @param {String | SignInOpts} usernameOrSignInOpts - The username to be signed in or the sign in options * @param {String} password - The password of the username * @return - A promise resolves the CognitoUser */ AuthClass.prototype.signIn = function (usernameOrSignInOpts, pw, clientMetadata) { if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } if (!this.userPool) { return this.rejectNoUserPool(); } var username = null; var password = null; var validationData = {}; // for backward compatibility if (typeof usernameOrSignInOpts === 'string') { username = usernameOrSignInOpts; password = pw; } else if (isUsernamePasswordOpts(usernameOrSignInOpts)) { if (typeof pw !== 'undefined') { Auth_logger.warn('The password should be defined under the first parameter object!'); } username = usernameOrSignInOpts.username; password = usernameOrSignInOpts.password; validationData = usernameOrSignInOpts.validationData; } else { return this.rejectAuthError(AuthErrorTypes.InvalidUsername); } if (!username) { return this.rejectAuthError(AuthErrorTypes.EmptyUsername); } var authDetails = new AuthenticationDetails({ Username: username, Password: password, ValidationData: validationData, ClientMetadata: clientMetadata, }); if (password) { return this.signInWithPassword(authDetails); } else { return this.signInWithoutPassword(authDetails); } }; /** * Return an object with the authentication callbacks * @param {CognitoUser} user - the cognito user object * @param {} resolve - function called when resolving the current step * @param {} reject - function called when rejecting the current step * @return - an object with the callback methods for user authentication */ AuthClass.prototype.authCallbacks = function (user, resolve, reject) { var _this = this; var that = this; return { onSuccess: function (session) { return Auth_awaiter(_this, void 0, void 0, function () { var cred, e_1, currentUser, e_2; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: Auth_logger.debug(session); delete user['challengeName']; delete user['challengeParam']; _a.label = 1; case 1: _a.trys.push([1, 4, 5, 9]); return [4 /*yield*/, lib_esm_Credentials.clear()]; case 2: _a.sent(); return [4 /*yield*/, lib_esm_Credentials.set(session, 'session')]; case 3: cred = _a.sent(); Auth_logger.debug('succeed to get cognito credentials', cred); return [3 /*break*/, 9]; case 4: e_1 = _a.sent(); Auth_logger.debug('cannot get cognito credentials', e_1); return [3 /*break*/, 9]; case 5: _a.trys.push([5, 7, , 8]); return [4 /*yield*/, this.currentUserPoolUser()]; case 6: currentUser = _a.sent(); that.user = currentUser; Auth_dispatchAuthEvent('signIn', currentUser, "A user " + user.getUsername() + " has been signed in"); resolve(currentUser); return [3 /*break*/, 8]; case 7: e_2 = _a.sent(); Auth_logger.error('Failed to get the signed in user', e_2); reject(e_2); return [3 /*break*/, 8]; case 8: return [7 /*endfinally*/]; case 9: return [2 /*return*/]; } }); }); }, onFailure: function (err) { Auth_logger.debug('signIn failure', err); Auth_dispatchAuthEvent('signIn_failure', err, user.getUsername() + " failed to signin"); reject(err); }, customChallenge: function (challengeParam) { Auth_logger.debug('signIn custom challenge answer required'); user['challengeName'] = 'CUSTOM_CHALLENGE'; user['challengeParam'] = challengeParam; resolve(user); }, mfaRequired: function (challengeName, challengeParam) { Auth_logger.debug('signIn MFA required'); user['challengeName'] = challengeName; user['challengeParam'] = challengeParam; resolve(user); }, mfaSetup: function (challengeName, challengeParam) { Auth_logger.debug('signIn mfa setup', challengeName); user['challengeName'] = challengeName; user['challengeParam'] = challengeParam; resolve(user); }, newPasswordRequired: function (userAttributes, requiredAttributes) { Auth_logger.debug('signIn new password'); user['challengeName'] = 'NEW_PASSWORD_REQUIRED'; user['challengeParam'] = { userAttributes: userAttributes, requiredAttributes: requiredAttributes, }; resolve(user); }, totpRequired: function (challengeName, challengeParam) { Auth_logger.debug('signIn totpRequired'); user['challengeName'] = challengeName; user['challengeParam'] = challengeParam; resolve(user); }, selectMFAType: function (challengeName, challengeParam) { Auth_logger.debug('signIn selectMFAType', challengeName); user['challengeName'] = challengeName; user['challengeParam'] = challengeParam; resolve(user); }, }; }; /** * Sign in with a password * @private * @param {AuthenticationDetails} authDetails - the user sign in data * @return - A promise resolves the CognitoUser object if success or mfa required */ AuthClass.prototype.signInWithPassword = function (authDetails) { var _this = this; var user = this.createCognitoUser(authDetails.getUsername()); return new Promise(function (resolve, reject) { user.authenticateUser(authDetails, _this.authCallbacks(user, resolve, reject)); }); }; /** * Sign in without a password * @private * @param {AuthenticationDetails} authDetails - the user sign in data * @return - A promise resolves the CognitoUser object if success or mfa required */ AuthClass.prototype.signInWithoutPassword = function (authDetails) { var _this = this; var user = this.createCognitoUser(authDetails.getUsername()); user.setAuthenticationFlowType('CUSTOM_AUTH'); return new Promise(function (resolve, reject) { user.initiateAuth(authDetails, _this.authCallbacks(user, resolve, reject)); }); }; /** * get user current preferred mfa option * this method doesn't work with totp, we need to deprecate it. * @deprecated * @param {CognitoUser} user - the current user * @return - A promise resolves the current preferred mfa option if success */ AuthClass.prototype.getMFAOptions = function (user) { return new Promise(function (res, rej) { user.getMFAOptions(function (err, mfaOptions) { if (err) { Auth_logger.debug('get MFA Options failed', err); rej(err); return; } Auth_logger.debug('get MFA options success', mfaOptions); res(mfaOptions); return; }); }); }; /** * get preferred mfa method * @param {CognitoUser} user - the current cognito user * @param {GetPreferredMFAOpts} params - options for getting the current user preferred MFA */ AuthClass.prototype.getPreferredMFA = function (user, params) { var that = this; return new Promise(function (res, rej) { var bypassCache = params ? params.bypassCache : false; user.getUserData(function (err, data) { if (err) { Auth_logger.debug('getting preferred mfa failed', err); rej(err); return; } var mfaType = that._getMfaTypeFromUserData(data); if (!mfaType) { rej('invalid MFA Type'); return; } else { res(mfaType); return; } }, { bypassCache: bypassCache }); }); }; AuthClass.prototype._getMfaTypeFromUserData = function (data) { var ret = null; var preferredMFA = data.PreferredMfaSetting; // if the user has used Auth.setPreferredMFA() to setup the mfa type // then the "PreferredMfaSetting" would exist in the response if (preferredMFA) { ret = preferredMFA; } else { // if mfaList exists but empty, then its noMFA var mfaList = data.UserMFASettingList; if (!mfaList) { // if SMS was enabled by using Auth.enableSMS(), // the response would contain MFAOptions // as for now Cognito only supports for SMS, so we will say it is 'SMS_MFA' // if it does not exist, then it should be NOMFA var MFAOptions = data.MFAOptions; if (MFAOptions) { ret = 'SMS_MFA'; } else { ret = 'NOMFA'; } } else if (mfaList.length === 0) { ret = 'NOMFA'; } else { Auth_logger.debug('invalid case for getPreferredMFA', data); } } return ret; }; AuthClass.prototype._getUserData = function (user, params) { return new Promise(function (res, rej) { user.getUserData(function (err, data) { if (err) { Auth_logger.debug('getting user data failed', err); rej(err); return; } else { res(data); return; } }, params); }); }; /** * set preferred MFA method * @param {CognitoUser} user - the current Cognito user * @param {string} mfaMethod - preferred mfa method * @return - A promise resolve if success */ AuthClass.prototype.setPreferredMFA = function (user, mfaMethod) { return Auth_awaiter(this, void 0, void 0, function () { var userData, smsMfaSettings, totpMfaSettings, _a, mfaList, currentMFAType, that; return Auth_generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this._getUserData(user, { bypassCache: true })]; case 1: userData = _b.sent(); smsMfaSettings = null; totpMfaSettings = null; _a = mfaMethod; switch (_a) { case 'TOTP' || false: return [3 /*break*/, 2]; case 'SMS' || false: return [3 /*break*/, 3]; case 'NOMFA': return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: totpMfaSettings = { PreferredMfa: true, Enabled: true, }; return [3 /*break*/, 7]; case 3: smsMfaSettings = { PreferredMfa: true, Enabled: true, }; return [3 /*break*/, 7]; case 4: mfaList = userData['UserMFASettingList']; return [4 /*yield*/, this._getMfaTypeFromUserData(userData)]; case 5: currentMFAType = _b.sent(); if (currentMFAType === 'NOMFA') { return [2 /*return*/, Promise.resolve('No change for mfa type')]; } else if (currentMFAType === 'SMS_MFA') { smsMfaSettings = { PreferredMfa: false, Enabled: false, }; } else if (currentMFAType === 'SOFTWARE_TOKEN_MFA') { totpMfaSettings = { PreferredMfa: false, Enabled: false, }; } else { return [2 /*return*/, this.rejectAuthError(AuthErrorTypes.InvalidMFA)]; } // if there is a UserMFASettingList in the response // we need to disable every mfa type in that list if (mfaList && mfaList.length !== 0) { // to disable SMS or TOTP if exists in that list mfaList.forEach(function (mfaType) { if (mfaType === 'SMS_MFA') { smsMfaSettings = { PreferredMfa: false, Enabled: false, }; } else if (mfaType === 'SOFTWARE_TOKEN_MFA') { totpMfaSettings = { PreferredMfa: false, Enabled: false, }; } }); } return [3 /*break*/, 7]; case 6: Auth_logger.debug('no validmfa method provided'); return [2 /*return*/, this.rejectAuthError(AuthErrorTypes.NoMFA)]; case 7: that = this; return [2 /*return*/, new Promise(function (res, rej) { user.setUserMfaPreference(smsMfaSettings, totpMfaSettings, function (err, result) { if (err) { Auth_logger.debug('Set user mfa preference error', err); return rej(err); } Auth_logger.debug('Set user mfa success', result); Auth_logger.debug('Caching the latest user data into local'); // cache the latest result into user data user.getUserData(function (err, data) { if (err) { Auth_logger.debug('getting user data failed', err); return rej(err); } else { return res(result); } }, { bypassCache: true }); }); })]; } }); }); }; /** * diable SMS * @deprecated * @param {CognitoUser} user - the current user * @return - A promise resolves is success */ AuthClass.prototype.disableSMS = function (user) { return new Promise(function (res, rej) { user.disableMFA(function (err, data) { if (err) { Auth_logger.debug('disable mfa failed', err); rej(err); return; } Auth_logger.debug('disable mfa succeed', data); res(data); return; }); }); }; /** * enable SMS * @deprecated * @param {CognitoUser} user - the current user * @return - A promise resolves is success */ AuthClass.prototype.enableSMS = function (user) { return new Promise(function (res, rej) { user.enableMFA(function (err, data) { if (err) { Auth_logger.debug('enable mfa failed', err); rej(err); return; } Auth_logger.debug('enable mfa succeed', data); res(data); return; }); }); }; /** * Setup TOTP * @param {CognitoUser} user - the current user * @return - A promise resolves with the secret code if success */ AuthClass.prototype.setupTOTP = function (user) { return new Promise(function (res, rej) { user.associateSoftwareToken({ onFailure: function (err) { Auth_logger.debug('associateSoftwareToken failed', err); rej(err); return; }, associateSecretCode: function (secretCode) { Auth_logger.debug('associateSoftwareToken sucess', secretCode); res(secretCode); return; }, }); }); }; /** * verify TOTP setup * @param {CognitoUser} user - the current user * @param {string} challengeAnswer - challenge answer * @return - A promise resolves is success */ AuthClass.prototype.verifyTotpToken = function (user, challengeAnswer) { Auth_logger.debug('verfication totp token', user, challengeAnswer); return new Promise(function (res, rej) { user.verifySoftwareToken(challengeAnswer, 'My TOTP device', { onFailure: function (err) { Auth_logger.debug('verifyTotpToken failed', err); rej(err); return; }, onSuccess: function (data) { Auth_logger.debug('verifyTotpToken success', data); res(data); return; }, }); }); }; /** * Send MFA code to confirm sign in * @param {Object} user - The CognitoUser object * @param {String} code - The confirmation code */ AuthClass.prototype.confirmSignIn = function (user, code, mfaType, clientMetadata) { var _this = this; if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } if (!code) { return this.rejectAuthError(AuthErrorTypes.EmptyCode); } var that = this; return new Promise(function (resolve, reject) { user.sendMFACode(code, { onSuccess: function (session) { return Auth_awaiter(_this, void 0, void 0, function () { var cred, e_3; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: Auth_logger.debug(session); _a.label = 1; case 1: _a.trys.push([1, 4, 5, 6]); return [4 /*yield*/, lib_esm_Credentials.clear()]; case 2: _a.sent(); return [4 /*yield*/, lib_esm_Credentials.set(session, 'session')]; case 3: cred = _a.sent(); Auth_logger.debug('succeed to get cognito credentials', cred); return [3 /*break*/, 6]; case 4: e_3 = _a.sent(); Auth_logger.debug('cannot get cognito credentials', e_3); return [3 /*break*/, 6]; case 5: that.user = user; Auth_dispatchAuthEvent('signIn', user, user + " has signed in"); resolve(user); return [7 /*endfinally*/]; case 6: return [2 /*return*/]; } }); }); }, onFailure: function (err) { Auth_logger.debug('confirm signIn failure', err); reject(err); }, }, mfaType, clientMetadata); }); }; AuthClass.prototype.completeNewPassword = function (user, password, requiredAttributes, clientMetadata) { var _this = this; if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } if (!password) { return this.rejectAuthError(AuthErrorTypes.EmptyPassword); } var that = this; return new Promise(function (resolve, reject) { user.completeNewPasswordChallenge(password, requiredAttributes, { onSuccess: function (session) { return Auth_awaiter(_this, void 0, void 0, function () { var cred, e_4; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: Auth_logger.debug(session); _a.label = 1; case 1: _a.trys.push([1, 4, 5, 6]); return [4 /*yield*/, lib_esm_Credentials.clear()]; case 2: _a.sent(); return [4 /*yield*/, lib_esm_Credentials.set(session, 'session')]; case 3: cred = _a.sent(); Auth_logger.debug('succeed to get cognito credentials', cred); return [3 /*break*/, 6]; case 4: e_4 = _a.sent(); Auth_logger.debug('cannot get cognito credentials', e_4); return [3 /*break*/, 6]; case 5: that.user = user; Auth_dispatchAuthEvent('signIn', user, user + " has signed in"); resolve(user); return [7 /*endfinally*/]; case 6: return [2 /*return*/]; } }); }); }, onFailure: function (err) { Auth_logger.debug('completeNewPassword failure', err); Auth_dispatchAuthEvent('completeNewPassword_failure', err, _this.user + " failed to complete the new password flow"); reject(err); }, mfaRequired: function (challengeName, challengeParam) { Auth_logger.debug('signIn MFA required'); user['challengeName'] = challengeName; user['challengeParam'] = challengeParam; resolve(user); }, mfaSetup: function (challengeName, challengeParam) { Auth_logger.debug('signIn mfa setup', challengeName); user['challengeName'] = challengeName; user['challengeParam'] = challengeParam; resolve(user); }, }, clientMetadata); }); }; /** * Send the answer to a custom challenge * @param {CognitoUser} user - The CognitoUser object * @param {String} challengeResponses - The confirmation code */ AuthClass.prototype.sendCustomChallengeAnswer = function (user, challengeResponses, clientMetadata) { var _this = this; if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } if (!this.userPool) { return this.rejectNoUserPool(); } if (!challengeResponses) { return this.rejectAuthError(AuthErrorTypes.EmptyChallengeResponse); } var that = this; return new Promise(function (resolve, reject) { user.sendCustomChallengeAnswer(challengeResponses, _this.authCallbacks(user, resolve, reject), clientMetadata); }); }; /** * Update an authenticated users' attributes * @param {CognitoUser} - The currently logged in user object * @return {Promise} **/ AuthClass.prototype.updateUserAttributes = function (user, attributes, clientMetadata) { if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } var attributeList = []; var that = this; return new Promise(function (resolve, reject) { that.userSession(user).then(function (session) { for (var key in attributes) { if (key !== 'sub' && key.indexOf('_verified') < 0) { var attr = { Name: key, Value: attributes[key], }; attributeList.push(attr); } } user.updateAttributes(attributeList, function (err, result) { if (err) { return reject(err); } else { return resolve(result); } }, clientMetadata); }); }); }; /** * Return user attributes * @param {Object} user - The CognitoUser object * @return - A promise resolves to user attributes if success */ AuthClass.prototype.userAttributes = function (user) { var _this = this; return new Promise(function (resolve, reject) { _this.userSession(user).then(function (session) { user.getUserAttributes(function (err, attributes) { if (err) { reject(err); } else { resolve(attributes); } }); }); }); }; AuthClass.prototype.verifiedContact = function (user) { var that = this; return this.userAttributes(user).then(function (attributes) { var attrs = that.attributesToObject(attributes); var unverified = {}; var verified = {}; if (attrs['email']) { if (attrs['email_verified']) { verified['email'] = attrs['email']; } else { unverified['email'] = attrs['email']; } } if (attrs['phone_number']) { if (attrs['phone_number_verified']) { verified['phone_number'] = attrs['phone_number']; } else { unverified['phone_number'] = attrs['phone_number']; } } return { verified: verified, unverified: unverified, }; }); }; /** * Get current authenticated user * @return - A promise resolves to current authenticated CognitoUser if success */ AuthClass.prototype.currentUserPoolUser = function (params) { var _this = this; if (!this.userPool) { return this.rejectNoUserPool(); } var that = this; return new Promise(function (res, rej) { _this._storageSync .then(function () { var user = that.userPool.getCurrentUser(); if (!user) { Auth_logger.debug('Failed to get user from user pool'); rej('No current user'); return; } // refresh the session if the session expired. user.getSession(function (err, session) { if (err) { Auth_logger.debug('Failed to get the user session', err); rej(err); return; } // get user data from Cognito var bypassCache = params ? params.bypassCache : false; // validate the token's scope fisrt before calling this function var _a = session.getAccessToken().decodePayload().scope, scope = _a === void 0 ? '' : _a; if (scope.split(' ').includes(USER_ADMIN_SCOPE)) { user.getUserData(function (err, data) { if (err) { Auth_logger.debug('getting user data failed', err); // Make sure the user is still valid if (err.message === 'User is disabled.' || err.message === 'User does not exist.' || err.message === 'Access Token has been revoked' // Session revoked by another app ) { rej(err); } else { // the error may also be thrown when lack of permissions to get user info etc // in that case we just bypass the error res(user); } return; } var preferredMFA = data.PreferredMfaSetting || 'NOMFA'; var attributeList = []; for (var i = 0; i < data.UserAttributes.length; i++) { var attribute = { Name: data.UserAttributes[i].Name, Value: data.UserAttributes[i].Value, }; var userAttribute = new CognitoUserAttribute(attribute); attributeList.push(userAttribute); } var attributes = that.attributesToObject(attributeList); Object.assign(user, { attributes: attributes, preferredMFA: preferredMFA }); return res(user); }, { bypassCache: bypassCache }); } else { Auth_logger.debug("Unable to get the user data because the " + USER_ADMIN_SCOPE + " " + "is not in the scopes of the access token"); return res(user); } }); }) .catch(function (e) { Auth_logger.debug('Failed to sync cache info into memory', e); return rej(e); }); }); }; /** * Get current authenticated user * @param {CurrentUserOpts} - options for getting the current user * @return - A promise resolves to current authenticated CognitoUser if success */ AuthClass.prototype.currentAuthenticatedUser = function (params) { return Auth_awaiter(this, void 0, void 0, function () { var federatedUser, e_5, user, e_6; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: Auth_logger.debug('getting current authenticated user'); federatedUser = null; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this._storageSync]; case 2: _a.sent(); return [3 /*break*/, 4]; case 3: e_5 = _a.sent(); Auth_logger.debug('Failed to sync cache info into memory', e_5); throw e_5; case 4: try { federatedUser = JSON.parse(this._storage.getItem('aws-amplify-federatedInfo')).user; } catch (e) { Auth_logger.debug('cannot load federated user from auth storage'); } if (!federatedUser) return [3 /*break*/, 5]; this.user = federatedUser; Auth_logger.debug('get current authenticated federated user', this.user); return [2 /*return*/, this.user]; case 5: Auth_logger.debug('get current authenticated userpool user'); user = null; _a.label = 6; case 6: _a.trys.push([6, 8, , 9]); return [4 /*yield*/, this.currentUserPoolUser(params)]; case 7: user = _a.sent(); return [3 /*break*/, 9]; case 8: e_6 = _a.sent(); if (e_6 === 'No userPool') { Auth_logger.error('Cannot get the current user because the user pool is missing. ' + 'Please make sure the Auth module is configured with a valid Cognito User Pool ID'); } Auth_logger.debug('The user is not authenticated by the error', e_6); throw 'not authenticated'; case 9: this.user = user; return [2 /*return*/, this.user]; } }); }); }; /** * Get current user's session * @return - A promise resolves to session object if success */ AuthClass.prototype.currentSession = function () { var that = this; Auth_logger.debug('Getting current session'); // Purposely not calling the reject method here because we don't need a console error if (!this.userPool) { return Promise.reject(); } return new Promise(function (res, rej) { that .currentUserPoolUser() .then(function (user) { that .userSession(user) .then(function (session) { res(session); return; }) .catch(function (e) { Auth_logger.debug('Failed to get the current session', e); rej(e); return; }); }) .catch(function (e) { Auth_logger.debug('Failed to get the current user', e); rej(e); return; }); }); }; /** * Get the corresponding user session * @param {Object} user - The CognitoUser object * @return - A promise resolves to the session */ AuthClass.prototype.userSession = function (user) { if (!user) { Auth_logger.debug('the user is null'); return this.rejectAuthError(AuthErrorTypes.NoUserSession); } return new Promise(function (resolve, reject) { Auth_logger.debug('Getting the session from this user:', user); user.getSession(function (err, session) { if (err) { Auth_logger.debug('Failed to get the session from user', user); reject(err); return; } else { Auth_logger.debug('Succeed to get the user session', session); resolve(session); return; } }); }); }; /** * Get authenticated credentials of current user. * @return - A promise resolves to be current user's credentials */ AuthClass.prototype.currentUserCredentials = function () { return Auth_awaiter(this, void 0, void 0, function () { var that, e_7, federatedInfo; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: that = this; Auth_logger.debug('Getting current user credentials'); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this._storageSync]; case 2: _a.sent(); return [3 /*break*/, 4]; case 3: e_7 = _a.sent(); Auth_logger.debug('Failed to sync cache info into memory', e_7); throw e_7; case 4: federatedInfo = null; try { federatedInfo = JSON.parse(this._storage.getItem('aws-amplify-federatedInfo')); } catch (e) { Auth_logger.debug('failed to get or parse item aws-amplify-federatedInfo', e); } if (federatedInfo) { // refresh the jwt token here if necessary return [2 /*return*/, lib_esm_Credentials.refreshFederatedToken(federatedInfo)]; } else { return [2 /*return*/, this.currentSession() .then(function (session) { Auth_logger.debug('getting session success', session); return lib_esm_Credentials.set(session, 'session'); }) .catch(function (error) { Auth_logger.debug('getting session failed', error); return lib_esm_Credentials.set(null, 'guest'); })]; } return [2 /*return*/]; } }); }); }; AuthClass.prototype.currentCredentials = function () { Auth_logger.debug('getting current credntials'); return lib_esm_Credentials.get(); }; /** * Initiate an attribute confirmation request * @param {Object} user - The CognitoUser * @param {Object} attr - The attributes to be verified * @return - A promise resolves to callback data if success */ AuthClass.prototype.verifyUserAttribute = function (user, attr, clientMetadata) { if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } return new Promise(function (resolve, reject) { user.getAttributeVerificationCode(attr, { onSuccess: function () { return resolve(); }, onFailure: function (err) { return reject(err); }, clientMetadata: clientMetadata, }); }); }; /** * Confirm an attribute using a confirmation code * @param {Object} user - The CognitoUser * @param {Object} attr - The attribute to be verified * @param {String} code - The confirmation code * @return - A promise resolves to callback data if success */ AuthClass.prototype.verifyUserAttributeSubmit = function (user, attr, code) { if (!code) { return this.rejectAuthError(AuthErrorTypes.EmptyCode); } return new Promise(function (resolve, reject) { user.verifyAttribute(attr, code, { onSuccess: function (data) { resolve(data); return; }, onFailure: function (err) { reject(err); return; }, }); }); }; AuthClass.prototype.verifyCurrentUserAttribute = function (attr) { var that = this; return that .currentUserPoolUser() .then(function (user) { return that.verifyUserAttribute(user, attr); }); }; /** * Confirm current user's attribute using a confirmation code * @param {Object} attr - The attribute to be verified * @param {String} code - The confirmation code * @return - A promise resolves to callback data if success */ AuthClass.prototype.verifyCurrentUserAttributeSubmit = function (attr, code) { var that = this; return that .currentUserPoolUser() .then(function (user) { return that.verifyUserAttributeSubmit(user, attr, code); }); }; AuthClass.prototype.cognitoIdentitySignOut = function (opts, user) { return Auth_awaiter(this, void 0, void 0, function () { var e_8, isSignedInHostedUI; var _this = this; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this._storageSync]; case 1: _a.sent(); return [3 /*break*/, 3]; case 2: e_8 = _a.sent(); Auth_logger.debug('Failed to sync cache info into memory', e_8); throw e_8; case 3: isSignedInHostedUI = this._oAuthHandler && this._storage.getItem('amplify-signin-with-hostedUI') === 'true'; return [2 /*return*/, new Promise(function (res, rej) { if (opts && opts.global) { Auth_logger.debug('user global sign out', user); // in order to use global signout // we must validate the user as an authenticated user by using getSession user.getSession(function (err, result) { if (err) { Auth_logger.debug('failed to get the user session', err); return rej(err); } user.globalSignOut({ onSuccess: function (data) { Auth_logger.debug('global sign out success'); if (isSignedInHostedUI) { return res(_this._oAuthHandler.signOut()); } else { return res(); } }, onFailure: function (err) { Auth_logger.debug('global sign out failed', err); return rej(err); }, }); }); } else { Auth_logger.debug('user sign out', user); user.signOut(); if (isSignedInHostedUI) { return res(_this._oAuthHandler.signOut()); } else { return res(); } } })]; } }); }); }; /** * Sign out method * @ * @return - A promise resolved if success */ AuthClass.prototype.signOut = function (opts) { return Auth_awaiter(this, void 0, void 0, function () { var e_9, user; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.cleanCachedItems()]; case 1: _a.sent(); return [3 /*break*/, 3]; case 2: e_9 = _a.sent(); Auth_logger.debug('failed to clear cached items'); return [3 /*break*/, 3]; case 3: if (!this.userPool) return [3 /*break*/, 7]; user = this.userPool.getCurrentUser(); if (!user) return [3 /*break*/, 5]; return [4 /*yield*/, this.cognitoIdentitySignOut(opts, user)]; case 4: _a.sent(); return [3 /*break*/, 6]; case 5: Auth_logger.debug('no current Cognito user'); _a.label = 6; case 6: return [3 /*break*/, 8]; case 7: Auth_logger.debug('no Congito User pool'); _a.label = 8; case 8: /** * Note for future refactor - no reliable way to get username with * Cognito User Pools vs Identity when federating with Social Providers * This is why we need a well structured session object that can be inspected * and information passed back in the message below for Hub dispatch */ Auth_dispatchAuthEvent('signOut', this.user, "A user has been signed out"); this.user = null; return [2 /*return*/]; } }); }); }; AuthClass.prototype.cleanCachedItems = function () { return Auth_awaiter(this, void 0, void 0, function () { return Auth_generator(this, function (_a) { switch (_a.label) { case 0: // clear cognito cached item return [4 /*yield*/, lib_esm_Credentials.clear()]; case 1: // clear cognito cached item _a.sent(); return [2 /*return*/]; } }); }); }; /** * Change a password for an authenticated user * @param {Object} user - The CognitoUser object * @param {String} oldPassword - the current password * @param {String} newPassword - the requested new password * @return - A promise resolves if success */ AuthClass.prototype.changePassword = function (user, oldPassword, newPassword, clientMetadata) { var _this = this; if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } return new Promise(function (resolve, reject) { _this.userSession(user).then(function (session) { user.changePassword(oldPassword, newPassword, function (err, data) { if (err) { Auth_logger.debug('change password failure', err); return reject(err); } else { return resolve(data); } }, clientMetadata); }); }); }; /** * Initiate a forgot password request * @param {String} username - the username to change password * @return - A promise resolves if success */ AuthClass.prototype.forgotPassword = function (username, clientMetadata) { if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } if (!this.userPool) { return this.rejectNoUserPool(); } if (!username) { return this.rejectAuthError(AuthErrorTypes.EmptyUsername); } var user = this.createCognitoUser(username); return new Promise(function (resolve, reject) { user.forgotPassword({ onSuccess: function () { resolve(); return; }, onFailure: function (err) { Auth_logger.debug('forgot password failure', err); Auth_dispatchAuthEvent('forgotPassword_failure', err, username + " forgotPassword failed"); reject(err); return; }, inputVerificationCode: function (data) { Auth_dispatchAuthEvent('forgotPassword', user, username + " has initiated forgot password flow"); resolve(data); return; }, }, clientMetadata); }); }; /** * Confirm a new password using a confirmation Code * @param {String} username - The username * @param {String} code - The confirmation code * @param {String} password - The new password * @return - A promise that resolves if success */ AuthClass.prototype.forgotPasswordSubmit = function (username, code, password, clientMetadata) { if (clientMetadata === void 0) { clientMetadata = this._config.clientMetadata; } if (!this.userPool) { return this.rejectNoUserPool(); } if (!username) { return this.rejectAuthError(AuthErrorTypes.EmptyUsername); } if (!code) { return this.rejectAuthError(AuthErrorTypes.EmptyCode); } if (!password) { return this.rejectAuthError(AuthErrorTypes.EmptyPassword); } var user = this.createCognitoUser(username); return new Promise(function (resolve, reject) { user.confirmPassword(code, password, { onSuccess: function () { Auth_dispatchAuthEvent('forgotPasswordSubmit', user, username + " forgotPasswordSubmit successful"); resolve(); return; }, onFailure: function (err) { Auth_dispatchAuthEvent('forgotPasswordSubmit_failure', err, username + " forgotPasswordSubmit failed"); reject(err); return; }, }, clientMetadata); }); }; /** * Get user information * @async * @return {Object }- current User's information */ AuthClass.prototype.currentUserInfo = function () { return Auth_awaiter(this, void 0, void 0, function () { var source, user, attributes, userAttrs, credentials, e_10, info, err_1, user; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: source = lib_esm_Credentials.getCredSource(); if (!(!source || source === 'aws' || source === 'userPool')) return [3 /*break*/, 9]; return [4 /*yield*/, this.currentUserPoolUser().catch(function (err) { return Auth_logger.debug(err); })]; case 1: user = _a.sent(); if (!user) { return [2 /*return*/, null]; } _a.label = 2; case 2: _a.trys.push([2, 8, , 9]); return [4 /*yield*/, this.userAttributes(user)]; case 3: attributes = _a.sent(); userAttrs = this.attributesToObject(attributes); credentials = null; _a.label = 4; case 4: _a.trys.push([4, 6, , 7]); return [4 /*yield*/, this.currentCredentials()]; case 5: credentials = _a.sent(); return [3 /*break*/, 7]; case 6: e_10 = _a.sent(); Auth_logger.debug('Failed to retrieve credentials while getting current user info', e_10); return [3 /*break*/, 7]; case 7: info = { id: credentials ? credentials.identityId : undefined, username: user.getUsername(), attributes: userAttrs, }; return [2 /*return*/, info]; case 8: err_1 = _a.sent(); Auth_logger.debug('currentUserInfo error', err_1); return [2 /*return*/, {}]; case 9: if (source === 'federated') { user = this.user; return [2 /*return*/, user ? user : {}]; } return [2 /*return*/]; } }); }); }; AuthClass.prototype.federatedSignIn = function (providerOrOptions, response, user) { return Auth_awaiter(this, void 0, void 0, function () { var options, provider, customState, client_id, redirect_uri, provider, loggedInUser, token, identity_id, expires_at, credentials, currentUser; return Auth_generator(this, function (_a) { switch (_a.label) { case 0: if (!this._config.identityPoolId && !this._config.userPoolId) { throw new Error("Federation requires either a User Pool or Identity Pool in config"); } // Ensure backwards compatability if (typeof providerOrOptions === 'undefined') { if (this._config.identityPoolId && !this._config.userPoolId) { throw new Error("Federation with Identity Pools requires tokens passed as arguments"); } } if (!(isFederatedSignInOptions(providerOrOptions) || isFederatedSignInOptionsCustom(providerOrOptions) || typeof providerOrOptions === 'undefined')) return [3 /*break*/, 1]; options = providerOrOptions || { provider: Auth_CognitoHostedUIIdentityProvider.Cognito, }; provider = isFederatedSignInOptions(options) ? options.provider : options.customProvider; customState = isFederatedSignInOptions(options) ? options.customState : options.customState; if (this._config.userPoolId) { client_id = isCognitoHostedOpts(this._config.oauth) ? this._config.userPoolWebClientId : this._config.oauth.clientID; redirect_uri = isCognitoHostedOpts(this._config.oauth) ? this._config.oauth.redirectSignIn : this._config.oauth.redirectUri; this._oAuthHandler.oauthSignIn(this._config.oauth.responseType, this._config.oauth.domain, redirect_uri, client_id, provider, customState); } return [3 /*break*/, 4]; case 1: provider = providerOrOptions; // To check if the user is already logged in try { loggedInUser = JSON.stringify(JSON.parse(this._storage.getItem('aws-amplify-federatedInfo')).user); if (loggedInUser) { Auth_logger.warn("There is already a signed in user: " + loggedInUser + " in your app.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tYou should not call Auth.federatedSignIn method again as it may cause unexpected behavior."); } } catch (e) { } token = response.token, identity_id = response.identity_id, expires_at = response.expires_at; return [4 /*yield*/, lib_esm_Credentials.set({ provider: provider, token: token, identity_id: identity_id, user: user, expires_at: expires_at }, 'federation')]; case 2: credentials = _a.sent(); return [4 /*yield*/, this.currentAuthenticatedUser()]; case 3: currentUser = _a.sent(); Auth_dispatchAuthEvent('signIn', currentUser, "A user " + currentUser.username + " has been signed in"); Auth_logger.debug('federated sign in credentials', credentials); return [2 /*return*/, credentials]; case 4: return [2 /*return*/]; } }); }); }; /** * Used to complete the OAuth flow with or without the Cognito Hosted UI * @param {String} URL - optional parameter for customers to pass in the response URL */ AuthClass.prototype._handleAuthResponse = function (URL) { return Auth_awaiter(this, void 0, void 0, function () { var currentUrl, hasCodeOrError, hasTokenOrError, _a, accessToken, idToken, refreshToken, state, session, credentials, isCustomStateIncluded, currentUser, customState, err_2; return Auth_generator(this, function (_b) { switch (_b.label) { case 0: if (!this._config.userPoolId) { throw new Error("OAuth responses require a User Pool defined in config"); } Auth_dispatchAuthEvent('parsingCallbackUrl', { url: URL }, "The callback url is being parsed"); currentUrl = URL || (JS["a" /* default */].browserOrNode().isBrowser ? window.location.href : ''); hasCodeOrError = !!(Object(url_url["parse"])(currentUrl).query || '') .split('&') .map(function (entry) { return entry.split('='); }) .find(function (_a) { var k = _a[0]; return k === 'code' || k === 'error'; }); hasTokenOrError = !!(Object(url_url["parse"])(currentUrl).hash || '#') .substr(1) .split('&') .map(function (entry) { return entry.split('='); }) .find(function (_a) { var k = _a[0]; return k === 'access_token' || k === 'error'; }); if (!(hasCodeOrError || hasTokenOrError)) return [3 /*break*/, 6]; _b.label = 1; case 1: _b.trys.push([1, 5, , 6]); return [4 /*yield*/, this._oAuthHandler.handleAuthResponse(currentUrl)]; case 2: _a = _b.sent(), accessToken = _a.accessToken, idToken = _a.idToken, refreshToken = _a.refreshToken, state = _a.state; session = new CognitoUserSession({ IdToken: new CognitoIdToken({ IdToken: idToken }), RefreshToken: new CognitoRefreshToken({ RefreshToken: refreshToken }), AccessToken: new CognitoAccessToken({ AccessToken: accessToken }), }); credentials = void 0; if (!this._config.identityPoolId) return [3 /*break*/, 4]; return [4 /*yield*/, lib_esm_Credentials.set(session, 'session')]; case 3: credentials = _b.sent(); Auth_logger.debug('AWS credentials', credentials); _b.label = 4; case 4: isCustomStateIncluded = /-/.test(state); currentUser = this.createCognitoUser(session.getIdToken().decodePayload()['cognito:username']); Auth_dispatchAuthEvent('signIn', currentUser, "A user " + currentUser.getUsername() + " has been signed in"); Auth_dispatchAuthEvent('cognitoHostedUI', currentUser, "A user " + currentUser.getUsername() + " has been signed in via Cognito Hosted UI"); if (isCustomStateIncluded) { customState = state .split('-') .splice(1) .join('-'); Auth_dispatchAuthEvent('customOAuthState', customState, "State for user " + currentUser.getUsername()); } // This calls cacheTokens() in Cognito SDK currentUser.setSignInUserSession(session); //#endregion if (window && typeof window.history !== 'undefined') { window.history.replaceState({}, null, this._config.oauth.redirectSignIn); } return [2 /*return*/, credentials]; case 5: err_2 = _b.sent(); Auth_logger.debug('Error in cognito hosted auth response', err_2); Auth_dispatchAuthEvent('signIn_failure', err_2, "The OAuth response flow failed"); Auth_dispatchAuthEvent('cognitoHostedUI_failure', err_2, "A failure occurred when returning to the Cognito Hosted UI"); Auth_dispatchAuthEvent('customState_failure', err_2, "A failure occurred when returning state"); throw err_2; case 6: return [2 /*return*/]; } }); }); }; /** * Compact version of credentials * @param {Object} credentials * @return {Object} - Credentials */ AuthClass.prototype.essentialCredentials = function (credentials) { return { accessKeyId: credentials.accessKeyId, sessionToken: credentials.sessionToken, secretAccessKey: credentials.secretAccessKey, identityId: credentials.identityId, authenticated: credentials.authenticated, }; }; AuthClass.prototype.attributesToObject = function (attributes) { var obj = {}; if (attributes) { attributes.map(function (attribute) { if (attribute.Value === 'true') { obj[attribute.Name] = true; } else if (attribute.Value === 'false') { obj[attribute.Name] = false; } else { obj[attribute.Name] = attribute.Value; } }); } return obj; }; AuthClass.prototype.createCognitoUser = function (username) { var userData = { Username: username, Pool: this.userPool, }; userData.Storage = this._storage; var authenticationFlowType = this._config.authenticationFlowType; var user = new CognitoUser_CognitoUser(userData); if (authenticationFlowType) { user.setAuthenticationFlowType(authenticationFlowType); } return user; }; AuthClass.prototype._isValidAuthStorage = function (obj) { // We need to check if the obj has the functions of Storage return (!!obj && typeof obj.getItem === 'function' && typeof obj.setItem === 'function' && typeof obj.removeItem === 'function' && typeof obj.clear === 'function'); }; AuthClass.prototype.noUserPoolErrorHandler = function (config) { if (config) { if (!config.userPoolId || !config.identityPoolId) { return AuthErrorTypes.MissingAuthConfig; } } return AuthErrorTypes.NoConfig; }; AuthClass.prototype.rejectAuthError = function (type) { return Promise.reject(new AuthError(type)); }; AuthClass.prototype.rejectNoUserPool = function () { var type = this.noUserPoolErrorHandler(this._config); return Promise.reject(new NoUserPoolError(type)); }; return AuthClass; }()); /* harmony default export */ var Auth = (Auth_AuthClass); //# sourceMappingURL=Auth.js.map // CONCATENATED MODULE: ./node_modules/@aws-amplify/auth/lib-esm/index.js /* unused concated harmony import AuthClass */ /* unused concated harmony import CognitoUser */ /* unused concated harmony import CookieStorage */ /* unused concated harmony import CognitoHostedUIIdentityProvider */ /* * Copyright 2017-2017 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 auth_lib_esm_logger = new ConsoleLogger('Auth'); var _instance = null; if (!_instance) { auth_lib_esm_logger.debug('Create Auth Instance'); _instance = new Auth(null); } var lib_esm_Auth = _instance; lib_esm.register(lib_esm_Auth); /* harmony default export */ var auth_lib_esm = __webpack_exports__["a"] = (lib_esm_Auth); //# sourceMappingURL=index.js.map /***/ }), /***/ "0273": /***/ (function(module, exports, __webpack_require__) { var DESCRIPTORS = __webpack_require__("c1b2"); var definePropertyModule = __webpack_require__("4180"); var createPropertyDescriptor = __webpack_require__("2c6c"); module.exports = DESCRIPTORS ? function (object, key, value) { return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /***/ "0466": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("05a3"); var JsonBuilder = __webpack_require__("2560"); var JsonParser = __webpack_require__("85e9"); var populateHostPrefix = __webpack_require__("9521").populateHostPrefix; 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; populateHostPrefix(req); } 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); } } /** * @api private */ module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; /***/ }), /***/ "057f": /***/ (function(module, exports, __webpack_require__) { var toIndexedObject = __webpack_require__("fc6a"); var nativeGetOwnPropertyNames = __webpack_require__("241c").f; var toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function (it) { try { return nativeGetOwnPropertyNames(it); } catch (error) { return windowNames.slice(); } }; // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : nativeGetOwnPropertyNames(toIndexedObject(it)); }; /***/ }), /***/ "05a3": /***/ (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 (Object({"NODE_ENV":"production","VUE_APP_API_URL":"https://api.home.millican.me","VUE_APP_AUTH_REDIR_URL":"https://home.millican.me/implicit/callback","VUE_APP_OKTA_CLIENTID":"0oaojmjqdzCch3YTU0h7","VUE_APP_OKTA_URL":"https://dev-510139.oktapreview.com/","BASE_URL":"/"}).AWS_EXECUTION_ENV) { engine += ' exec-env/' + Object({"NODE_ENV":"production","VUE_APP_API_URL":"https://api.home.millican.me","VUE_APP_AUTH_REDIR_URL":"https://home.millican.me/implicit/callback","VUE_APP_OKTA_CLIENTID":"0oaojmjqdzCch3YTU0h7","VUE_APP_OKTA_URL":"https://dev-510139.oktapreview.com/","BASE_URL":"/"}).AWS_EXECUTION_ENV; } return engine; } }, userAgent: function userAgent() { var name = util.environment; var agent = 'aws-sdk-' + name + '/' + __webpack_require__("42c5").VERSION; if (name === 'nodejs') agent += ' ' + util.engine(); return agent; }, 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 = util.buffer.toBuffer(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 util.buffer.toBuffer(string, 'base64'); } }, buffer: { /** * Buffer constructor for Node buffer and buffer pollyfill */ toBuffer: function(data, encoding) { return (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(data, encoding) : new util.Buffer(data, encoding); }, alloc: function(size, fill, encoding) { if (typeof size !== 'number') { throw new Error('size passed to alloc must be a number.'); } if (typeof util.Buffer.alloc === 'function') { return util.Buffer.alloc(size, fill, encoding); } else { var buf = new util.Buffer(size); if (fill !== undefined && typeof buf.fill === 'function') { buf.fill(fill, undefined, undefined, encoding); } return buf; } }, toStream: function toStream(buffer) { if (!util.Buffer.isBuffer(buffer)) buffer = util.buffer.toBuffer(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 = util.buffer.alloc(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 = util.buffer.toBuffer(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() {}, callback: function (err) { if (err) throw err; }, /** * 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__("42c5"); 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 = util.buffer.toBuffer(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 = util.buffer.toBuffer(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 = util.buffer.toBuffer(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 operationName = req.operation; var operation = req.service.api.operations[operationName]; var output = operation.output; if (output.payload && !operation.hasEventOutput) { 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 (typeof Stream === 'function' && 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) { var deletePromises = false; if (PromiseDependency === undefined && AWS && AWS.config) { PromiseDependency = AWS.config.getPromisesDependency(); } if (PromiseDependency === undefined && typeof Promise !== 'undefined') { PromiseDependency = Promise; } if (typeof PromiseDependency !== 'function') 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__("1505"); 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__("9d74").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 */ getRequestPayloadShape: function getRequestPayloadShape(req) { var operations = req.service.api.operations; if (!operations) return undefined; var operation = (operations || {})[req.operation]; if (!operation || !operation.input || !operation.input.payload) return undefined; return operation.input.members[operation.input.payload]; }, getProfilesFromSharedConfig: function getProfilesFromSharedConfig(iniLoader, filename) { var profiles = {}; var profilesFromConfig = {}; if (Object({"NODE_ENV":"production","VUE_APP_API_URL":"https://api.home.millican.me","VUE_APP_AUTH_REDIR_URL":"https://home.millican.me/implicit/callback","VUE_APP_OKTA_CLIENTID":"0oaojmjqdzCch3YTU0h7","VUE_APP_OKTA_URL":"https://dev-510139.oktapreview.com/","BASE_URL":"/"})[util.configOptInEnv]) { var profilesFromConfig = iniLoader.loadFrom({ isConfig: true, filename: Object({"NODE_ENV":"production","VUE_APP_API_URL":"https://api.home.millican.me","VUE_APP_AUTH_REDIR_URL":"https://home.millican.me/implicit/callback","VUE_APP_OKTA_CLIENTID":"0oaojmjqdzCch3YTU0h7","VUE_APP_OKTA_URL":"https://dev-510139.oktapreview.com/","BASE_URL":"/"})[util.sharedConfigFileEnv] }); } var profilesFromCreds = iniLoader.loadFrom({ filename: filename || (Object({"NODE_ENV":"production","VUE_APP_API_URL":"https://api.home.millican.me","VUE_APP_AUTH_REDIR_URL":"https://home.millican.me/implicit/callback","VUE_APP_OKTA_CLIENTID":"0oaojmjqdzCch3YTU0h7","VUE_APP_OKTA_URL":"https://dev-510139.oktapreview.com/","BASE_URL":"/"})[util.configOptInEnv] && Object({"NODE_ENV":"production","VUE_APP_API_URL":"https://api.home.millican.me","VUE_APP_AUTH_REDIR_URL":"https://home.millican.me/implicit/callback","VUE_APP_OKTA_CLIENTID":"0oaojmjqdzCch3YTU0h7","VUE_APP_OKTA_URL":"https://dev-510139.oktapreview.com/","BASE_URL":"/"})[util.sharedCredentialsFileEnv]) }); for (var i = 0, profileNames = Object.keys(profilesFromConfig); i < profileNames.length; i++) { profiles[profileNames[i]] = profilesFromConfig[profileNames[i]]; } for (var i = 0, profileNames = Object.keys(profilesFromCreds); i < profileNames.length; i++) { profiles[profileNames[i]] = profilesFromCreds[profileNames[i]]; } return profiles; }, /** * @api private */ defaultProfile: 'default', /** * @api private */ configOptInEnv: 'AWS_SDK_LOAD_CONFIG', /** * @api private */ sharedCredentialsFileEnv: 'AWS_SHARED_CREDENTIALS_FILE', /** * @api private */ sharedConfigFileEnv: 'AWS_CONFIG_FILE', /** * @api private */ imdsDisabledEnv: 'AWS_EC2_METADATA_DISABLED' }; /** * @api private */ module.exports = util; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("4362"))) /***/ }), /***/ "06cf": /***/ (function(module, exports, __webpack_require__) { var DESCRIPTORS = __webpack_require__("83ab"); var propertyIsEnumerableModule = __webpack_require__("d1e7"); var createPropertyDescriptor = __webpack_require__("5c6c"); var toIndexedObject = __webpack_require__("fc6a"); var toPrimitive = __webpack_require__("c04e"); var has = __webpack_require__("5135"); var IE8_DOM_DEFINE = __webpack_require__("0cfb"); var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return nativeGetOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]); }; /***/ }), /***/ "06fa": /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (error) { return true; } }; /***/ }), /***/ "0713": /***/ (function(module) { module.exports = JSON.parse("{\"version\":\"2.0\",\"metadata\":{\"apiVersion\":\"2011-06-15\",\"endpointPrefix\":\"sts\",\"globalEndpoint\":\"sts.amazonaws.com\",\"protocol\":\"query\",\"serviceAbbreviation\":\"AWS STS\",\"serviceFullName\":\"AWS Security Token Service\",\"serviceId\":\"STS\",\"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\":{},\"PolicyArns\":{\"shape\":\"S4\"},\"Policy\":{},\"DurationSeconds\":{\"type\":\"integer\"},\"ExternalId\":{},\"SerialNumber\":{},\"TokenCode\":{}}},\"output\":{\"resultWrapper\":\"AssumeRoleResult\",\"type\":\"structure\",\"members\":{\"Credentials\":{\"shape\":\"Sc\"},\"AssumedRoleUser\":{\"shape\":\"Sh\"},\"PackedPolicySize\":{\"type\":\"integer\"}}}},\"AssumeRoleWithSAML\":{\"input\":{\"type\":\"structure\",\"required\":[\"RoleArn\",\"PrincipalArn\",\"SAMLAssertion\"],\"members\":{\"RoleArn\":{},\"PrincipalArn\":{},\"SAMLAssertion\":{},\"PolicyArns\":{\"shape\":\"S4\"},\"Policy\":{},\"DurationSeconds\":{\"type\":\"integer\"}}},\"output\":{\"resultWrapper\":\"AssumeRoleWithSAMLResult\",\"type\":\"structure\",\"members\":{\"Credentials\":{\"shape\":\"Sc\"},\"AssumedRoleUser\":{\"shape\":\"Sh\"},\"PackedPolicySize\":{\"type\":\"integer\"},\"Subject\":{},\"SubjectType\":{},\"Issuer\":{},\"Audience\":{},\"NameQualifier\":{}}}},\"AssumeRoleWithWebIdentity\":{\"input\":{\"type\":\"structure\",\"required\":[\"RoleArn\",\"RoleSessionName\",\"WebIdentityToken\"],\"members\":{\"RoleArn\":{},\"RoleSessionName\":{},\"WebIdentityToken\":{},\"ProviderId\":{},\"PolicyArns\":{\"shape\":\"S4\"},\"Policy\":{},\"DurationSeconds\":{\"type\":\"integer\"}}},\"output\":{\"resultWrapper\":\"AssumeRoleWithWebIdentityResult\",\"type\":\"structure\",\"members\":{\"Credentials\":{\"shape\":\"Sc\"},\"SubjectFromWebIdentityToken\":{},\"AssumedRoleUser\":{\"shape\":\"Sh\"},\"PackedPolicySize\":{\"type\":\"integer\"},\"Provider\":{},\"Audience\":{}}}},\"DecodeAuthorizationMessage\":{\"input\":{\"type\":\"structure\",\"required\":[\"EncodedMessage\"],\"members\":{\"EncodedMessage\":{}}},\"output\":{\"resultWrapper\":\"DecodeAuthorizationMessageResult\",\"type\":\"structure\",\"members\":{\"DecodedMessage\":{}}}},\"GetAccessKeyInfo\":{\"input\":{\"type\":\"structure\",\"required\":[\"AccessKeyId\"],\"members\":{\"AccessKeyId\":{}}},\"output\":{\"resultWrapper\":\"GetAccessKeyInfoResult\",\"type\":\"structure\",\"members\":{\"Account\":{}}}},\"GetCallerIdentity\":{\"input\":{\"type\":\"structure\",\"members\":{}},\"output\":{\"resultWrapper\":\"GetCallerIdentityResult\",\"type\":\"structure\",\"members\":{\"UserId\":{},\"Account\":{},\"Arn\":{}}}},\"GetFederationToken\":{\"input\":{\"type\":\"structure\",\"required\":[\"Name\"],\"members\":{\"Name\":{},\"Policy\":{},\"PolicyArns\":{\"shape\":\"S4\"},\"DurationSeconds\":{\"type\":\"integer\"}}},\"output\":{\"resultWrapper\":\"GetFederationTokenResult\",\"type\":\"structure\",\"members\":{\"Credentials\":{\"shape\":\"Sc\"},\"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\":\"Sc\"}}}}},\"shapes\":{\"S4\":{\"type\":\"list\",\"member\":{\"type\":\"structure\",\"members\":{\"arn\":{}}}},\"Sc\":{\"type\":\"structure\",\"required\":[\"AccessKeyId\",\"SecretAccessKey\",\"SessionToken\",\"Expiration\"],\"members\":{\"AccessKeyId\":{},\"SecretAccessKey\":{},\"SessionToken\":{},\"Expiration\":{\"type\":\"timestamp\"}}},\"Sh\":{\"type\":\"structure\",\"required\":[\"AssumedRoleId\",\"Arn\"],\"members\":{\"AssumedRoleId\":{},\"Arn\":{}}}}}"); /***/ }), /***/ "0744": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("42c5"); 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 's3v4': return AWS.Signers.V4; 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__("0fc2"); __webpack_require__("376f"); __webpack_require__("54d1"); __webpack_require__("2886"); __webpack_require__("4b2b"); __webpack_require__("178e"); /***/ }), /***/ "0857": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("05a3"); var Shape = __webpack_require__("9f21"); 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 = getElementByTagName(result.documentElement, 'ResponseMetadata'); 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 getElementByTagName(xml, tag) { var elements = xml.getElementsByTagName(tag); for (var i = 0, iLen = elements.length; i < iLen; i++) { if (elements[i].parentNode === xml) { return elements[i]; } } } 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 : getElementByTagName(xml, memberShape.name); 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 = getElementByTagName(child, xmlKey).textContent; var value = getElementByTagName(child, xmlValue); 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); } /** * @api private */ module.exports = DomXmlParser; /***/ }), /***/ "08da": /***/ (function(module, exports, __webpack_require__) { (function(exports) { "use strict"; function isArray(obj) { if (obj !== null) { return Object.prototype.toString.call(obj) === "[object Array]"; } else { return false; } } function isObject(obj) { if (obj !== null) { return Object.prototype.toString.call(obj) === "[object Object]"; } else { return false; } } function strictDeepEqual(first, second) { // Check the scalar case first. if (first === second) { return true; } // Check if they are the same type. var firstType = Object.prototype.toString.call(first); if (firstType !== Object.prototype.toString.call(second)) { return false; } // We know that first and second have the same type so we can just check the // first type from now on. if (isArray(first) === true) { // Short circuit if they're not the same length; if (first.length !== second.length) { return false; } for (var i = 0; i < first.length; i++) { if (strictDeepEqual(first[i], second[i]) === false) { return false; } } return true; } if (isObject(first) === true) { // An object is equal if it has the same key/value pairs. var keysSeen = {}; for (var key in first) { if (hasOwnProperty.call(first, key)) { if (strictDeepEqual(first[key], second[key]) === false) { return false; } keysSeen[key] = true; } } // Now check that there aren't any keys in second that weren't // in first. for (var key2 in second) { if (hasOwnProperty.call(second, key2)) { if (keysSeen[key2] !== true) { return false; } } } return true; } return false; } function isFalse(obj) { // From the spec: // A false value corresponds to the following values: // Empty list // Empty object // Empty string // False boolean // null value // First check the scalar values. if (obj === "" || obj === false || obj === null) { return true; } else if (isArray(obj) && obj.length === 0) { // Check for an empty array. return true; } else if (isObject(obj)) { // Check for an empty object. for (var key in obj) { // If there are any keys, then // the object is not empty so the object // is not false. if (obj.hasOwnProperty(key)) { return false; } } return true; } else { return false; } } function objValues(obj) { var keys = Object.keys(obj); var values = []; for (var i = 0; i < keys.length; i++) { values.push(obj[keys[i]]); } return values; } function merge(a, b) { var merged = {}; for (var key in a) { merged[key] = a[key]; } for (var key2 in b) { merged[key2] = b[key2]; } return merged; } var trimLeft; if (typeof String.prototype.trimLeft === "function") { trimLeft = function(str) { return str.trimLeft(); }; } else { trimLeft = function(str) { return str.match(/^\s*(.*)/)[1]; }; } // Type constants used to define functions. var TYPE_NUMBER = 0; var TYPE_ANY = 1; var TYPE_STRING = 2; var TYPE_ARRAY = 3; var TYPE_OBJECT = 4; var TYPE_BOOLEAN = 5; var TYPE_EXPREF = 6; var TYPE_NULL = 7; var TYPE_ARRAY_NUMBER = 8; var TYPE_ARRAY_STRING = 9; var TOK_EOF = "EOF"; var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; var TOK_RBRACKET = "Rbracket"; var TOK_RPAREN = "Rparen"; var TOK_COMMA = "Comma"; var TOK_COLON = "Colon"; var TOK_RBRACE = "Rbrace"; var TOK_NUMBER = "Number"; var TOK_CURRENT = "Current"; var TOK_EXPREF = "Expref"; var TOK_PIPE = "Pipe"; var TOK_OR = "Or"; var TOK_AND = "And"; var TOK_EQ = "EQ"; var TOK_GT = "GT"; var TOK_LT = "LT"; var TOK_GTE = "GTE"; var TOK_LTE = "LTE"; var TOK_NE = "NE"; var TOK_FLATTEN = "Flatten"; var TOK_STAR = "Star"; var TOK_FILTER = "Filter"; var TOK_DOT = "Dot"; var TOK_NOT = "Not"; var TOK_LBRACE = "Lbrace"; var TOK_LBRACKET = "Lbracket"; var TOK_LPAREN= "Lparen"; var TOK_LITERAL= "Literal"; // The "&", "[", "<", ">" tokens // are not in basicToken because // there are two token variants // ("&&", "[?", "<=", ">="). This is specially handled // below. var basicTokens = { ".": TOK_DOT, "*": TOK_STAR, ",": TOK_COMMA, ":": TOK_COLON, "{": TOK_LBRACE, "}": TOK_RBRACE, "]": TOK_RBRACKET, "(": TOK_LPAREN, ")": TOK_RPAREN, "@": TOK_CURRENT }; var operatorStartToken = { "<": true, ">": true, "=": true, "!": true }; var skipChars = { " ": true, "\t": true, "\n": true }; function isAlpha(ch) { return (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || ch === "_"; } function isNum(ch) { return (ch >= "0" && ch <= "9") || ch === "-"; } function isAlphaNum(ch) { return (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || (ch >= "0" && ch <= "9") || ch === "_"; } function Lexer() { } Lexer.prototype = { tokenize: function(stream) { var tokens = []; this._current = 0; var start; var identifier; var token; while (this._current < stream.length) { if (isAlpha(stream[this._current])) { start = this._current; identifier = this._consumeUnquotedIdentifier(stream); tokens.push({type: TOK_UNQUOTEDIDENTIFIER, value: identifier, start: start}); } else if (basicTokens[stream[this._current]] !== undefined) { tokens.push({type: basicTokens[stream[this._current]], value: stream[this._current], start: this._current}); this._current++; } else if (isNum(stream[this._current])) { token = this._consumeNumber(stream); tokens.push(token); } else if (stream[this._current] === "[") { // No need to increment this._current. This happens // in _consumeLBracket token = this._consumeLBracket(stream); tokens.push(token); } else if (stream[this._current] === "\"") { start = this._current; identifier = this._consumeQuotedIdentifier(stream); tokens.push({type: TOK_QUOTEDIDENTIFIER, value: identifier, start: start}); } else if (stream[this._current] === "'") { start = this._current; identifier = this._consumeRawStringLiteral(stream); tokens.push({type: TOK_LITERAL, value: identifier, start: start}); } else if (stream[this._current] === "`") { start = this._current; var literal = this._consumeLiteral(stream); tokens.push({type: TOK_LITERAL, value: literal, start: start}); } else if (operatorStartToken[stream[this._current]] !== undefined) { tokens.push(this._consumeOperator(stream)); } else if (skipChars[stream[this._current]] !== undefined) { // Ignore whitespace. this._current++; } else if (stream[this._current] === "&") { start = this._current; this._current++; if (stream[this._current] === "&") { this._current++; tokens.push({type: TOK_AND, value: "&&", start: start}); } else { tokens.push({type: TOK_EXPREF, value: "&", start: start}); } } else if (stream[this._current] === "|") { start = this._current; this._current++; if (stream[this._current] === "|") { this._current++; tokens.push({type: TOK_OR, value: "||", start: start}); } else { tokens.push({type: TOK_PIPE, value: "|", start: start}); } } else { var error = new Error("Unknown character:" + stream[this._current]); error.name = "LexerError"; throw error; } } return tokens; }, _consumeUnquotedIdentifier: function(stream) { var start = this._current; this._current++; while (this._current < stream.length && isAlphaNum(stream[this._current])) { this._current++; } return stream.slice(start, this._current); }, _consumeQuotedIdentifier: function(stream) { var start = this._current; this._current++; var maxLength = stream.length; while (stream[this._current] !== "\"" && this._current < maxLength) { // You can escape a double quote and you can escape an escape. var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "\"")) { current += 2; } else { current++; } this._current = current; } this._current++; return JSON.parse(stream.slice(start, this._current)); }, _consumeRawStringLiteral: function(stream) { var start = this._current; this._current++; var maxLength = stream.length; while (stream[this._current] !== "'" && this._current < maxLength) { // You can escape a single quote and you can escape an escape. var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "'")) { current += 2; } else { current++; } this._current = current; } this._current++; var literal = stream.slice(start + 1, this._current - 1); return literal.replace("\\'", "'"); }, _consumeNumber: function(stream) { var start = this._current; this._current++; var maxLength = stream.length; while (isNum(stream[this._current]) && this._current < maxLength) { this._current++; } var value = parseInt(stream.slice(start, this._current)); return {type: TOK_NUMBER, value: value, start: start}; }, _consumeLBracket: function(stream) { var start = this._current; this._current++; if (stream[this._current] === "?") { this._current++; return {type: TOK_FILTER, value: "[?", start: start}; } else if (stream[this._current] === "]") { this._current++; return {type: TOK_FLATTEN, value: "[]", start: start}; } else { return {type: TOK_LBRACKET, value: "[", start: start}; } }, _consumeOperator: function(stream) { var start = this._current; var startingChar = stream[start]; this._current++; if (startingChar === "!") { if (stream[this._current] === "=") { this._current++; return {type: TOK_NE, value: "!=", start: start}; } else { return {type: TOK_NOT, value: "!", start: start}; } } else if (startingChar === "<") { if (stream[this._current] === "=") { this._current++; return {type: TOK_LTE, value: "<=", start: start}; } else { return {type: TOK_LT, value: "<", start: start}; } } else if (startingChar === ">") { if (stream[this._current] === "=") { this._current++; return {type: TOK_GTE, value: ">=", start: start}; } else { return {type: TOK_GT, value: ">", start: start}; } } else if (startingChar === "=") { if (stream[this._current] === "=") { this._current++; return {type: TOK_EQ, value: "==", start: start}; } } }, _consumeLiteral: function(stream) { this._current++; var start = this._current; var maxLength = stream.length; var literal; while(stream[this._current] !== "`" && this._current < maxLength) { // You can escape a literal char or you can escape the escape. var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "`")) { current += 2; } else { current++; } this._current = current; } var literalString = trimLeft(stream.slice(start, this._current)); literalString = literalString.replace("\\`", "`"); if (this._looksLikeJSON(literalString)) { literal = JSON.parse(literalString); } else { // Try to JSON parse it as "" literal = JSON.parse("\"" + literalString + "\""); } // +1 gets us to the ending "`", +1 to move on to the next char. this._current++; return literal; }, _looksLikeJSON: function(literalString) { var startingChars = "[{\""; var jsonLiterals = ["true", "false", "null"]; var numberLooking = "-0123456789"; if (literalString === "") { return false; } else if (startingChars.indexOf(literalString[0]) >= 0) { return true; } else if (jsonLiterals.indexOf(literalString) >= 0) { return true; } else if (numberLooking.indexOf(literalString[0]) >= 0) { try { JSON.parse(literalString); return true; } catch (ex) { return false; } } else { return false; } } }; var bindingPower = {}; bindingPower[TOK_EOF] = 0; bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; bindingPower[TOK_QUOTEDIDENTIFIER] = 0; bindingPower[TOK_RBRACKET] = 0; bindingPower[TOK_RPAREN] = 0; bindingPower[TOK_COMMA] = 0; bindingPower[TOK_RBRACE] = 0; bindingPower[TOK_NUMBER] = 0; bindingPower[TOK_CURRENT] = 0; bindingPower[TOK_EXPREF] = 0; bindingPower[TOK_PIPE] = 1; bindingPower[TOK_OR] = 2; bindingPower[TOK_AND] = 3; bindingPower[TOK_EQ] = 5; bindingPower[TOK_GT] = 5; bindingPower[TOK_LT] = 5; bindingPower[TOK_GTE] = 5; bindingPower[TOK_LTE] = 5; bindingPower[TOK_NE] = 5; bindingPower[TOK_FLATTEN] = 9; bindingPower[TOK_STAR] = 20; bindingPower[TOK_FILTER] = 21; bindingPower[TOK_DOT] = 40; bindingPower[TOK_NOT] = 45; bindingPower[TOK_LBRACE] = 50; bindingPower[TOK_LBRACKET] = 55; bindingPower[TOK_LPAREN] = 60; function Parser() { } Parser.prototype = { parse: function(expression) { this._loadTokens(expression); this.index = 0; var ast = this.expression(0); if (this._lookahead(0) !== TOK_EOF) { var t = this._lookaheadToken(0); var error = new Error( "Unexpected token type: " + t.type + ", value: " + t.value); error.name = "ParserError"; throw error; } return ast; }, _loadTokens: function(expression) { var lexer = new Lexer(); var tokens = lexer.tokenize(expression); tokens.push({type: TOK_EOF, value: "", start: expression.length}); this.tokens = tokens; }, expression: function(rbp) { var leftToken = this._lookaheadToken(0); this._advance(); var left = this.nud(leftToken); var currentToken = this._lookahead(0); while (rbp < bindingPower[currentToken]) { this._advance(); left = this.led(currentToken, left); currentToken = this._lookahead(0); } return left; }, _lookahead: function(number) { return this.tokens[this.index + number].type; }, _lookaheadToken: function(number) { return this.tokens[this.index + number]; }, _advance: function() { this.index++; }, nud: function(token) { var left; var right; var expression; switch (token.type) { case TOK_LITERAL: return {type: "Literal", value: token.value}; case TOK_UNQUOTEDIDENTIFIER: return {type: "Field", name: token.value}; case TOK_QUOTEDIDENTIFIER: var node = {type: "Field", name: token.value}; if (this._lookahead(0) === TOK_LPAREN) { throw new Error("Quoted identifier not allowed for function names."); } else { return node; } break; case TOK_NOT: right = this.expression(bindingPower.Not); return {type: "NotExpression", children: [right]}; case TOK_STAR: left = {type: "Identity"}; right = null; if (this._lookahead(0) === TOK_RBRACKET) { // This can happen in a multiselect, // [a, b, *] right = {type: "Identity"}; } else { right = this._parseProjectionRHS(bindingPower.Star); } return {type: "ValueProjection", children: [left, right]}; case TOK_FILTER: return this.led(token.type, {type: "Identity"}); case TOK_LBRACE: return this._parseMultiselectHash(); case TOK_FLATTEN: left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; right = this._parseProjectionRHS(bindingPower.Flatten); return {type: "Projection", children: [left, right]}; case TOK_LBRACKET: if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { right = this._parseIndexExpression(); return this._projectIfSlice({type: "Identity"}, right); } else if (this._lookahead(0) === TOK_STAR && this._lookahead(1) === TOK_RBRACKET) { this._advance(); this._advance(); right = this._parseProjectionRHS(bindingPower.Star); return {type: "Projection", children: [{type: "Identity"}, right]}; } else { return this._parseMultiselectList(); } break; case TOK_CURRENT: return {type: TOK_CURRENT}; case TOK_EXPREF: expression = this.expression(bindingPower.Expref); return {type: "ExpressionReference", children: [expression]}; case TOK_LPAREN: var args = []; while (this._lookahead(0) !== TOK_RPAREN) { if (this._lookahead(0) === TOK_CURRENT) { expression = {type: TOK_CURRENT}; this._advance(); } else { expression = this.expression(0); } args.push(expression); } this._match(TOK_RPAREN); return args[0]; default: this._errorToken(token); } }, led: function(tokenName, left) { var right; switch(tokenName) { case TOK_DOT: var rbp = bindingPower.Dot; if (this._lookahead(0) !== TOK_STAR) { right = this._parseDotRHS(rbp); return {type: "Subexpression", children: [left, right]}; } else { // Creating a projection. this._advance(); right = this._parseProjectionRHS(rbp); return {type: "ValueProjection", children: [left, right]}; } break; case TOK_PIPE: right = this.expression(bindingPower.Pipe); return {type: TOK_PIPE, children: [left, right]}; case TOK_OR: right = this.expression(bindingPower.Or); return {type: "OrExpression", children: [left, right]}; case TOK_AND: right = this.expression(bindingPower.And); return {type: "AndExpression", children: [left, right]}; case TOK_LPAREN: var name = left.name; var args = []; var expression, node; while (this._lookahead(0) !== TOK_RPAREN) { if (this._lookahead(0) === TOK_CURRENT) { expression = {type: TOK_CURRENT}; this._advance(); } else { expression = this.expression(0); } if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); } args.push(expression); } this._match(TOK_RPAREN); node = {type: "Function", name: name, children: args}; return node; case TOK_FILTER: var condition = this.expression(0); this._match(TOK_RBRACKET); if (this._lookahead(0) === TOK_FLATTEN) { right = {type: "Identity"}; } else { right = this._parseProjectionRHS(bindingPower.Filter); } return {type: "FilterProjection", children: [left, right, condition]}; case TOK_FLATTEN: var leftNode = {type: TOK_FLATTEN, children: [left]}; var rightNode = this._parseProjectionRHS(bindingPower.Flatten); return {type: "Projection", children: [leftNode, rightNode]}; case TOK_EQ: case TOK_NE: case TOK_GT: case TOK_GTE: case TOK_LT: case TOK_LTE: return this._parseComparator(left, tokenName); case TOK_LBRACKET: var token = this._lookaheadToken(0); if (token.type === TOK_NUMBER || token.type === TOK_COLON) { right = this._parseIndexExpression(); return this._projectIfSlice(left, right); } else { this._match(TOK_STAR); this._match(TOK_RBRACKET); right = this._parseProjectionRHS(bindingPower.Star); return {type: "Projection", children: [left, right]}; } break; default: this._errorToken(this._lookaheadToken(0)); } }, _match: function(tokenType) { if (this._lookahead(0) === tokenType) { this._advance(); } else { var t = this._lookaheadToken(0); var error = new Error("Expected " + tokenType + ", got: " + t.type); error.name = "ParserError"; throw error; } }, _errorToken: function(token) { var error = new Error("Invalid token (" + token.type + "): \"" + token.value + "\""); error.name = "ParserError"; throw error; }, _parseIndexExpression: function() { if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { return this._parseSliceExpression(); } else { var node = { type: "Index", value: this._lookaheadToken(0).value}; this._advance(); this._match(TOK_RBRACKET); return node; } }, _projectIfSlice: function(left, right) { var indexExpr = {type: "IndexExpression", children: [left, right]}; if (right.type === "Slice") { return { type: "Projection", children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] }; } else { return indexExpr; } }, _parseSliceExpression: function() { // [start:end:step] where each part is optional, as well as the last // colon. var parts = [null, null, null]; var index = 0; var currentToken = this._lookahead(0); while (currentToken !== TOK_RBRACKET && index < 3) { if (currentToken === TOK_COLON) { index++; this._advance(); } else if (currentToken === TOK_NUMBER) { parts[index] = this._lookaheadToken(0).value; this._advance(); } else { var t = this._lookahead(0); var error = new Error("Syntax error, unexpected token: " + t.value + "(" + t.type + ")"); error.name = "Parsererror"; throw error; } currentToken = this._lookahead(0); } this._match(TOK_RBRACKET); return { type: "Slice", children: parts }; }, _parseComparator: function(left, comparator) { var right = this.expression(bindingPower[comparator]); return {type: "Comparator", name: comparator, children: [left, right]}; }, _parseDotRHS: function(rbp) { var lookahead = this._lookahead(0); var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; if (exprTokens.indexOf(lookahead) >= 0) { return this.expression(rbp); } else if (lookahead === TOK_LBRACKET) { this._match(TOK_LBRACKET); return this._parseMultiselectList(); } else if (lookahead === TOK_LBRACE) { this._match(TOK_LBRACE); return this._parseMultiselectHash(); } }, _parseProjectionRHS: function(rbp) { var right; if (bindingPower[this._lookahead(0)] < 10) { right = {type: "Identity"}; } else if (this._lookahead(0) === TOK_LBRACKET) { right = this.expression(rbp); } else if (this._lookahead(0) === TOK_FILTER) { right = this.expression(rbp); } else if (this._lookahead(0) === TOK_DOT) { this._match(TOK_DOT); right = this._parseDotRHS(rbp); } else { var t = this._lookaheadToken(0); var error = new Error("Sytanx error, unexpected token: " + t.value + "(" + t.type + ")"); error.name = "ParserError"; throw error; } return right; }, _parseMultiselectList: function() { var expressions = []; while (this._lookahead(0) !== TOK_RBRACKET) { var expression = this.expression(0); expressions.push(expression); if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); if (this._lookahead(0) === TOK_RBRACKET) { throw new Error("Unexpected token Rbracket"); } } } this._match(TOK_RBRACKET); return {type: "MultiSelectList", children: expressions}; }, _parseMultiselectHash: function() { var pairs = []; var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; var keyToken, keyName, value, node; for (;;) { keyToken = this._lookaheadToken(0); if (identifierTypes.indexOf(keyToken.type) < 0) { throw new Error("Expecting an identifier token, got: " + keyToken.type); } keyName = keyToken.value; this._advance(); this._match(TOK_COLON); value = this.expression(0); node = {type: "KeyValuePair", name: keyName, value: value}; pairs.push(node); if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); } else if (this._lookahead(0) === TOK_RBRACE) { this._match(TOK_RBRACE); break; } } return {type: "MultiSelectHash", children: pairs}; } }; function TreeInterpreter(runtime) { this.runtime = runtime; } TreeInterpreter.prototype = { search: function(node, value) { return this.visit(node, value); }, visit: function(node, value) { var matched, current, result, first, second, field, left, right, collected, i; switch (node.type) { case "Field": if (value === null ) { return null; } else if (isObject(value)) { field = value[node.name]; if (field === undefined) { return null; } else { return field; } } else { return null; } break; case "Subexpression": result = this.visit(node.children[0], value); for (i = 1; i < node.children.length; i++) { result = this.visit(node.children[1], result); if (result === null) { return null; } } return result; case "IndexExpression": left = this.visit(node.children[0], value); right = this.visit(node.children[1], left); return right; case "Index": if (!isArray(value)) { return null; } var index = node.value; if (index < 0) { index = value.length + index; } result = value[index]; if (result === undefined) { result = null; } return result; case "Slice": if (!isArray(value)) { return null; } var sliceParams = node.children.slice(0); var computed = this.computeSliceParams(value.length, sliceParams); var start = computed[0]; var stop = computed[1]; var step = computed[2]; result = []; if (step > 0) { for (i = start; i < stop; i += step) { result.push(value[i]); } } else { for (i = start; i > stop; i += step) { result.push(value[i]); } } return result; case "Projection": // Evaluate left child. var base = this.visit(node.children[0], value); if (!isArray(base)) { return null; } collected = []; for (i = 0; i < base.length; i++) { current = this.visit(node.children[1], base[i]); if (current !== null) { collected.push(current); } } return collected; case "ValueProjection": // Evaluate left child. base = this.visit(node.children[0], value); if (!isObject(base)) { return null; } collected = []; var values = objValues(base); for (i = 0; i < values.length; i++) { current = this.visit(node.children[1], values[i]); if (current !== null) { collected.push(current); } } return collected; case "FilterProjection": base = this.visit(node.children[0], value); if (!isArray(base)) { return null; } var filtered = []; var finalResults = []; for (i = 0; i < base.length; i++) { matched = this.visit(node.children[2], base[i]); if (!isFalse(matched)) { filtered.push(base[i]); } } for (var j = 0; j < filtered.length; j++) { current = this.visit(node.children[1], filtered[j]); if (current !== null) { finalResults.push(current); } } return finalResults; case "Comparator": first = this.visit(node.children[0], value); second = this.visit(node.children[1], value); switch(node.name) { case TOK_EQ: result = strictDeepEqual(first, second); break; case TOK_NE: result = !strictDeepEqual(first, second); break; case TOK_GT: result = first > second; break; case TOK_GTE: result = first >= second; break; case TOK_LT: result = first < second; break; case TOK_LTE: result = first <= second; break; default: throw new Error("Unknown comparator: " + node.name); } return result; case TOK_FLATTEN: var original = this.visit(node.children[0], value); if (!isArray(original)) { return null; } var merged = []; for (i = 0; i < original.length; i++) { current = original[i]; if (isArray(current)) { merged.push.apply(merged, current); } else { merged.push(current); } } return merged; case "Identity": return value; case "MultiSelectList": if (value === null) { return null; } collected = []; for (i = 0; i < node.children.length; i++) { collected.push(this.visit(node.children[i], value)); } return collected; case "MultiSelectHash": if (value === null) { return null; } collected = {}; var child; for (i = 0; i < node.children.length; i++) { child = node.children[i]; collected[child.name] = this.visit(child.value, value); } return collected; case "OrExpression": matched = this.visit(node.children[0], value); if (isFalse(matched)) { matched = this.visit(node.children[1], value); } return matched; case "AndExpression": first = this.visit(node.children[0], value); if (isFalse(first) === true) { return first; } return this.visit(node.children[1], value); case "NotExpression": first = this.visit(node.children[0], value); return isFalse(first); case "Literal": return node.value; case TOK_PIPE: left = this.visit(node.children[0], value); return this.visit(node.children[1], left); case TOK_CURRENT: return value; case "Function": var resolvedArgs = []; for (i = 0; i < node.children.length; i++) { resolvedArgs.push(this.visit(node.children[i], value)); } return this.runtime.callFunction(node.name, resolvedArgs); case "ExpressionReference": var refNode = node.children[0]; // Tag the node with a specific attribute so the type // checker verify the type. refNode.jmespathType = TOK_EXPREF; return refNode; default: throw new Error("Unknown node type: " + node.type); } }, computeSliceParams: function(arrayLength, sliceParams) { var start = sliceParams[0]; var stop = sliceParams[1]; var step = sliceParams[2]; var computed = [null, null, null]; if (step === null) { step = 1; } else if (step === 0) { var error = new Error("Invalid slice, step cannot be 0"); error.name = "RuntimeError"; throw error; } var stepValueNegative = step < 0 ? true : false; if (start === null) { start = stepValueNegative ? arrayLength - 1 : 0; } else { start = this.capSliceRange(arrayLength, start, step); } if (stop === null) { stop = stepValueNegative ? -1 : arrayLength; } else { stop = this.capSliceRange(arrayLength, stop, step); } computed[0] = start; computed[1] = stop; computed[2] = step; return computed; }, capSliceRange: function(arrayLength, actualValue, step) { if (actualValue < 0) { actualValue += arrayLength; if (actualValue < 0) { actualValue = step < 0 ? -1 : 0; } } else if (actualValue >= arrayLength) { actualValue = step < 0 ? arrayLength - 1 : arrayLength; } return actualValue; } }; function Runtime(interpreter) { this._interpreter = interpreter; this.functionTable = { // name: [function, ] // The can be: // // { // args: [[type1, type2], [type1, type2]], // variadic: true|false // } // // Each arg in the arg list is a list of valid types // (if the function is overloaded and supports multiple // types. If the type is "any" then no type checking // occurs on the argument. Variadic is optional // and if not provided is assumed to be false. abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, contains: { _func: this._functionContains, _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, {types: [TYPE_ANY]}]}, "ends_with": { _func: this._functionEndsWith, _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, length: { _func: this._functionLength, _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, map: { _func: this._functionMap, _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, max: { _func: this._functionMax, _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, "merge": { _func: this._functionMerge, _signature: [{types: [TYPE_OBJECT], variadic: true}] }, "max_by": { _func: this._functionMaxBy, _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] }, sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, "starts_with": { _func: this._functionStartsWith, _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, min: { _func: this._functionMin, _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, "min_by": { _func: this._functionMinBy, _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] }, type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, "sort_by": { _func: this._functionSortBy, _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] }, join: { _func: this._functionJoin, _signature: [ {types: [TYPE_STRING]}, {types: [TYPE_ARRAY_STRING]} ] }, reverse: { _func: this._functionReverse, _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, "not_null": { _func: this._functionNotNull, _signature: [{types: [TYPE_ANY], variadic: true}] } }; } Runtime.prototype = { callFunction: function(name, resolvedArgs) { var functionEntry = this.functionTable[name]; if (functionEntry === undefined) { throw new Error("Unknown function: " + name + "()"); } this._validateArgs(name, resolvedArgs, functionEntry._signature); return functionEntry._func.call(this, resolvedArgs); }, _validateArgs: function(name, args, signature) { // Validating the args requires validating // the correct arity and the correct type of each arg. // If the last argument is declared as variadic, then we need // a minimum number of args to be required. Otherwise it has to // be an exact amount. var pluralized; if (signature[signature.length - 1].variadic) { if (args.length < signature.length) { pluralized = signature.length === 1 ? " argument" : " arguments"; throw new Error("ArgumentError: " + name + "() " + "takes at least" + signature.length + pluralized + " but received " + args.length); } } else if (args.length !== signature.length) { pluralized = signature.length === 1 ? " argument" : " arguments"; throw new Error("ArgumentError: " + name + "() " + "takes " + signature.length + pluralized + " but received " + args.length); } var currentSpec; var actualType; var typeMatched; for (var i = 0; i < signature.length; i++) { typeMatched = false; currentSpec = signature[i].types; actualType = this._getTypeName(args[i]); for (var j = 0; j < currentSpec.length; j++) { if (this._typeMatches(actualType, currentSpec[j], args[i])) { typeMatched = true; break; } } if (!typeMatched) { throw new Error("TypeError: " + name + "() " + "expected argument " + (i + 1) + " to be type " + currentSpec + " but received type " + actualType + " instead."); } } }, _typeMatches: function(actual, expected, argValue) { if (expected === TYPE_ANY) { return true; } if (expected === TYPE_ARRAY_STRING || expected === TYPE_ARRAY_NUMBER || expected === TYPE_ARRAY) { // The expected type can either just be array, // or it can require a specific subtype (array of numbers). // // The simplest case is if "array" with no subtype is specified. if (expected === TYPE_ARRAY) { return actual === TYPE_ARRAY; } else if (actual === TYPE_ARRAY) { // Otherwise we need to check subtypes. // I think this has potential to be improved. var subtype; if (expected === TYPE_ARRAY_NUMBER) { subtype = TYPE_NUMBER; } else if (expected === TYPE_ARRAY_STRING) { subtype = TYPE_STRING; } for (var i = 0; i < argValue.length; i++) { if (!this._typeMatches( this._getTypeName(argValue[i]), subtype, argValue[i])) { return false; } } return true; } } else { return actual === expected; } }, _getTypeName: function(obj) { switch (Object.prototype.toString.call(obj)) { case "[object String]": return TYPE_STRING; case "[object Number]": return TYPE_NUMBER; case "[object Array]": return TYPE_ARRAY; case "[object Boolean]": return TYPE_BOOLEAN; case "[object Null]": return TYPE_NULL; case "[object Object]": // Check if it's an expref. If it has, it's been // tagged with a jmespathType attr of 'Expref'; if (obj.jmespathType === TOK_EXPREF) { return TYPE_EXPREF; } else { return TYPE_OBJECT; } } }, _functionStartsWith: function(resolvedArgs) { return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; }, _functionEndsWith: function(resolvedArgs) { var searchStr = resolvedArgs[0]; var suffix = resolvedArgs[1]; return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; }, _functionReverse: function(resolvedArgs) { var typeName = this._getTypeName(resolvedArgs[0]); if (typeName === TYPE_STRING) { var originalStr = resolvedArgs[0]; var reversedStr = ""; for (var i = originalStr.length - 1; i >= 0; i--) { reversedStr += originalStr[i]; } return reversedStr; } else { var reversedArray = resolvedArgs[0].slice(0); reversedArray.reverse(); return reversedArray; } }, _functionAbs: function(resolvedArgs) { return Math.abs(resolvedArgs[0]); }, _functionCeil: function(resolvedArgs) { return Math.ceil(resolvedArgs[0]); }, _functionAvg: function(resolvedArgs) { var sum = 0; var inputArray = resolvedArgs[0]; for (var i = 0; i < inputArray.length; i++) { sum += inputArray[i]; } return sum / inputArray.length; }, _functionContains: function(resolvedArgs) { return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; }, _functionFloor: function(resolvedArgs) { return Math.floor(resolvedArgs[0]); }, _functionLength: function(resolvedArgs) { if (!isObject(resolvedArgs[0])) { return resolvedArgs[0].length; } else { // As far as I can tell, there's no way to get the length // of an object without O(n) iteration through the object. return Object.keys(resolvedArgs[0]).length; } }, _functionMap: function(resolvedArgs) { var mapped = []; var interpreter = this._interpreter; var exprefNode = resolvedArgs[0]; var elements = resolvedArgs[1]; for (var i = 0; i < elements.length; i++) { mapped.push(interpreter.visit(exprefNode, elements[i])); } return mapped; }, _functionMerge: function(resolvedArgs) { var merged = {}; for (var i = 0; i < resolvedArgs.length; i++) { var current = resolvedArgs[i]; for (var key in current) { merged[key] = current[key]; } } return merged; }, _functionMax: function(resolvedArgs) { if (resolvedArgs[0].length > 0) { var typeName = this._getTypeName(resolvedArgs[0][0]); if (typeName === TYPE_NUMBER) { return Math.max.apply(Math, resolvedArgs[0]); } else { var elements = resolvedArgs[0]; var maxElement = elements[0]; for (var i = 1; i < elements.length; i++) { if (maxElement.localeCompare(elements[i]) < 0) { maxElement = elements[i]; } } return maxElement; } } else { return null; } }, _functionMin: function(resolvedArgs) { if (resolvedArgs[0].length > 0) { var typeName = this._getTypeName(resolvedArgs[0][0]); if (typeName === TYPE_NUMBER) { return Math.min.apply(Math, resolvedArgs[0]); } else { var elements = resolvedArgs[0]; var minElement = elements[0]; for (var i = 1; i < elements.length; i++) { if (elements[i].localeCompare(minElement) < 0) { minElement = elements[i]; } } return minElement; } } else { return null; } }, _functionSum: function(resolvedArgs) { var sum = 0; var listToSum = resolvedArgs[0]; for (var i = 0; i < listToSum.length; i++) { sum += listToSum[i]; } return sum; }, _functionType: function(resolvedArgs) { switch (this._getTypeName(resolvedArgs[0])) { case TYPE_NUMBER: return "number"; case TYPE_STRING: return "string"; case TYPE_ARRAY: return "array"; case TYPE_OBJECT: return "object"; case TYPE_BOOLEAN: return "boolean"; case TYPE_EXPREF: return "expref"; case TYPE_NULL: return "null"; } }, _functionKeys: function(resolvedArgs) { return Object.keys(resolvedArgs[0]); }, _functionValues: function(resolvedArgs) { var obj = resolvedArgs[0]; var keys = Object.keys(obj); var values = []; for (var i = 0; i < keys.length; i++) { values.push(obj[keys[i]]); } return values; }, _functionJoin: function(resolvedArgs) { var joinChar = resolvedArgs[0]; var listJoin = resolvedArgs[1]; return listJoin.join(joinChar); }, _functionToArray: function(resolvedArgs) { if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { return resolvedArgs[0]; } else { return [resolvedArgs[0]]; } }, _functionToString: function(resolvedArgs) { if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { return resolvedArgs[0]; } else { return JSON.stringify(resolvedArgs[0]); } }, _functionToNumber: function(resolvedArgs) { var typeName = this._getTypeName(resolvedArgs[0]); var convertedValue; if (typeName === TYPE_NUMBER) { return resolvedArgs[0]; } else if (typeName === TYPE_STRING) { convertedValue = +resolvedArgs[0]; if (!isNaN(convertedValue)) { return convertedValue; } } return null; }, _functionNotNull: function(resolvedArgs) { for (var i = 0; i < resolvedArgs.length; i++) { if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { return resolvedArgs[i]; } } return null; }, _functionSort: function(resolvedArgs) { var sortedArray = resolvedArgs[0].slice(0); sortedArray.sort(); return sortedArray; }, _functionSortBy: function(resolvedArgs) { var sortedArray = resolvedArgs[0].slice(0); if (sortedArray.length === 0) { return sortedArray; } var interpreter = this._interpreter; var exprefNode = resolvedArgs[1]; var requiredType = this._getTypeName( interpreter.visit(exprefNode, sortedArray[0])); if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { throw new Error("TypeError"); } var that = this; // In order to get a stable sort out of an unstable // sort algorithm, we decorate/sort/undecorate (DSU) // by creating a new list of [index, element] pairs. // In the cmp function, if the evaluated elements are // equal, then the index will be used as the tiebreaker. // After the decorated list has been sorted, it will be // undecorated to extract the original elements. var decorated = []; for (var i = 0; i < sortedArray.length; i++) { decorated.push([i, sortedArray[i]]); } decorated.sort(function(a, b) { var exprA = interpreter.visit(exprefNode, a[1]); var exprB = interpreter.visit(exprefNode, b[1]); if (that._getTypeName(exprA) !== requiredType) { throw new Error( "TypeError: expected " + requiredType + ", received " + that._getTypeName(exprA)); } else if (that._getTypeName(exprB) !== requiredType) { throw new Error( "TypeError: expected " + requiredType + ", received " + that._getTypeName(exprB)); } if (exprA > exprB) { return 1; } else if (exprA < exprB) { return -1; } else { // If they're equal compare the items by their // order to maintain relative order of equal keys // (i.e. to get a stable sort). return a[0] - b[0]; } }); // Undecorate: extract out the original list elements. for (var j = 0; j < decorated.length; j++) { sortedArray[j] = decorated[j][1]; } return sortedArray; }, _functionMaxBy: function(resolvedArgs) { var exprefNode = resolvedArgs[1]; var resolvedArray = resolvedArgs[0]; var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); var maxNumber = -Infinity; var maxRecord; var current; for (var i = 0; i < resolvedArray.length; i++) { current = keyFunction(resolvedArray[i]); if (current > maxNumber) { maxNumber = current; maxRecord = resolvedArray[i]; } } return maxRecord; }, _functionMinBy: function(resolvedArgs) { var exprefNode = resolvedArgs[1]; var resolvedArray = resolvedArgs[0]; var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); var minNumber = Infinity; var minRecord; var current; for (var i = 0; i < resolvedArray.length; i++) { current = keyFunction(resolvedArray[i]); if (current < minNumber) { minNumber = current; minRecord = resolvedArray[i]; } } return minRecord; }, createKeyFunction: function(exprefNode, allowedTypes) { var that = this; var interpreter = this._interpreter; var keyFunc = function(x) { var current = interpreter.visit(exprefNode, x); if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { var msg = "TypeError: expected one of " + allowedTypes + ", received " + that._getTypeName(current); throw new Error(msg); } return current; }; return keyFunc; } }; function compile(stream) { var parser = new Parser(); var ast = parser.parse(stream); return ast; } function tokenize(stream) { var lexer = new Lexer(); return lexer.tokenize(stream); } function search(data, expression) { var parser = new Parser(); // This needs to be improved. Both the interpreter and runtime depend on // each other. The runtime needs the interpreter to support exprefs. // There's likely a clean way to avoid the cyclic dependency. var runtime = new Runtime(); var interpreter = new TreeInterpreter(runtime); runtime._interpreter = interpreter; var node = parser.parse(expression); return interpreter.search(node, data); } exports.tokenize = tokenize; exports.compile = compile; exports.search = search; exports.strictDeepEqual = strictDeepEqual; })( false ? undefined : exports); /***/ }), /***/ "09b4": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("05a3"); 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); } }); } /** * @api private */ module.exports = ResourceWaiter; /***/ }), /***/ "0a06": /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__("c532"); var buildURL = __webpack_require__("30b5"); var InterceptorManager = __webpack_require__("f6b4"); var dispatchRequest = __webpack_require__("5270"); var mergeConfig = __webpack_require__("4a7b"); /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig(this.defaults, config); config.method = config.method ? config.method.toLowerCase() : 'get'; // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(utils.merge(config || {}, { method: method, url: url })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(utils.merge(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; /***/ }), /***/ "0b16": /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var punycode = __webpack_require__("1985"); var util = __webpack_require__("35e8"); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = __webpack_require__("b383"); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.path = rest; this.href = rest; this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; if (parseQueryString) { this.query = querystring.parse(this.search.substr(1)); } else { this.query = this.search.substr(1); } } else if (parseQueryString) { this.search = ''; this.query = {}; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; /***/ }), /***/ "0cfb": /***/ (function(module, exports, __webpack_require__) { var DESCRIPTORS = __webpack_require__("83ab"); var fails = __webpack_require__("d039"); var createElement = __webpack_require__("cc12"); // Thank's IE8 for his funny defineProperty module.exports = !DESCRIPTORS && !fails(function () { return Object.defineProperty(createElement('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "0d03": /***/ (function(module, exports, __webpack_require__) { var redefine = __webpack_require__("6eeb"); var DatePrototype = Date.prototype; var INVALID_DATE = 'Invalid Date'; var TO_STRING = 'toString'; var nativeDateToString = DatePrototype[TO_STRING]; var getTime = DatePrototype.getTime; // `Date.prototype.toString` method // https://tc39.github.io/ecma262/#sec-date.prototype.tostring if (new Date(NaN) + '' != INVALID_DATE) { redefine(DatePrototype, TO_STRING, function toString() { var value = getTime.call(this); // eslint-disable-next-line no-self-compare return value === value ? nativeDateToString.call(this) : INVALID_DATE; }); } /***/ }), /***/ "0df6": /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ "0fc2": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("42c5"); 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'); } }); /** * @api private */ module.exports = AWS.Signers.V2; /***/ }), /***/ "1132": /***/ (function(module, exports, __webpack_require__) { ;(function (root, factory) { if (true) { // CommonJS module.exports = exports = factory(__webpack_require__("21bf")); } else {} }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; var reverseMap = this._reverseMap; if (!reverseMap) { reverseMap = this._reverseMap = []; for (var j = 0; j < map.length; j++) { reverseMap[map.charCodeAt(j)] = j; } } // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex !== -1) { base64StrLength = paddingIndex; } } // Convert return parseLoop(base64Str, base64StrLength, reverseMap); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); } }()); return CryptoJS.enc.Base64; })); /***/ }), /***/ "12e2": /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LRU_1 = __webpack_require__("8445"); var CACHE_SIZE = 1000; /** * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache] */ var EndpointCache = /** @class */ (function () { function EndpointCache(maxSize) { if (maxSize === void 0) { maxSize = CACHE_SIZE; } this.maxSize = maxSize; this.cache = new LRU_1.LRUCache(maxSize); } ; Object.defineProperty(EndpointCache.prototype, "size", { get: function () { return this.cache.length; }, enumerable: true, configurable: true }); EndpointCache.prototype.put = function (key, value) { var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; var endpointRecord = this.populateValue(value); this.cache.put(keyString, endpointRecord); }; EndpointCache.prototype.get = function (key) { var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; var now = Date.now(); var records = this.cache.get(keyString); if (records) { for (var i = 0; i < records.length; i++) { var record = records[i]; if (record.Expire < now) { this.cache.remove(keyString); return undefined; } } } return records; }; EndpointCache.getKeyString = function (key) { var identifiers = []; var identifierNames = Object.keys(key).sort(); for (var i = 0; i < identifierNames.length; i++) { var identifierName = identifierNames[i]; if (key[identifierName] === undefined) continue; identifiers.push(key[identifierName]); } return identifiers.join(' '); }; EndpointCache.prototype.populateValue = function (endpoints) { var now = Date.now(); return endpoints.map(function (endpoint) { return ({ Address: endpoint.Address || '', Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000 }); }); }; EndpointCache.prototype.empty = function () { this.cache.empty(); }; EndpointCache.prototype.remove = function (key) { var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; this.cache.remove(keyString); }; return EndpointCache; }()); exports.EndpointCache = EndpointCache; /***/ }), /***/ "146b": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("42c5"); /** * @api private */ var cachedSecret = {}; /** * @api private */ var cacheQueue = []; /** * @api private */ var maxCacheEntries = 50; /** * @api private */ var v4Identifier = 'aws4_request'; /** * @api private */ 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 = []; } }; /***/ }), /***/ "1505": /***/ (function(module) { module.exports = JSON.parse("{\"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\",\"versions\":[\"2016-05-10*\"]},\"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*\",\"2017-03-25*\",\"2017-10-30*\",\"2018-06-18*\",\"2018-11-05*\"],\"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\",\"cors\":true},\"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\",\"cors\":true},\"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},\"s3control\":{\"name\":\"S3Control\",\"dualstackAvailable\":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\",\"cors\":true},\"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\"},\"mobile\":{\"name\":\"Mobile\"},\"pricing\":{\"name\":\"Pricing\",\"cors\":true},\"costexplorer\":{\"prefix\":\"ce\",\"name\":\"CostExplorer\",\"cors\":true},\"mediaconvert\":{\"name\":\"MediaConvert\"},\"medialive\":{\"name\":\"MediaLive\"},\"mediapackage\":{\"name\":\"MediaPackage\"},\"mediastore\":{\"name\":\"MediaStore\"},\"mediastoredata\":{\"prefix\":\"mediastore-data\",\"name\":\"MediaStoreData\",\"cors\":true},\"appsync\":{\"name\":\"AppSync\"},\"guardduty\":{\"name\":\"GuardDuty\"},\"mq\":{\"name\":\"MQ\"},\"comprehend\":{\"name\":\"Comprehend\",\"cors\":true},\"iotjobsdataplane\":{\"prefix\":\"iot-jobs-data\",\"name\":\"IoTJobsDataPlane\"},\"kinesisvideoarchivedmedia\":{\"prefix\":\"kinesis-video-archived-media\",\"name\":\"KinesisVideoArchivedMedia\",\"cors\":true},\"kinesisvideomedia\":{\"prefix\":\"kinesis-video-media\",\"name\":\"KinesisVideoMedia\",\"cors\":true},\"kinesisvideo\":{\"name\":\"KinesisVideo\",\"cors\":true},\"sagemakerruntime\":{\"prefix\":\"runtime.sagemaker\",\"name\":\"SageMakerRuntime\"},\"sagemaker\":{\"name\":\"SageMaker\"},\"translate\":{\"name\":\"Translate\",\"cors\":true},\"resourcegroups\":{\"prefix\":\"resource-groups\",\"name\":\"ResourceGroups\",\"cors\":true},\"alexaforbusiness\":{\"name\":\"AlexaForBusiness\"},\"cloud9\":{\"name\":\"Cloud9\"},\"serverlessapplicationrepository\":{\"prefix\":\"serverlessrepo\",\"name\":\"ServerlessApplicationRepository\"},\"servicediscovery\":{\"name\":\"ServiceDiscovery\"},\"workmail\":{\"name\":\"WorkMail\"},\"autoscalingplans\":{\"prefix\":\"autoscaling-plans\",\"name\":\"AutoScalingPlans\"},\"transcribeservice\":{\"prefix\":\"transcribe\",\"name\":\"TranscribeService\"},\"connect\":{\"name\":\"Connect\"},\"acmpca\":{\"prefix\":\"acm-pca\",\"name\":\"ACMPCA\"},\"fms\":{\"name\":\"FMS\"},\"secretsmanager\":{\"name\":\"SecretsManager\",\"cors\":true},\"iotanalytics\":{\"name\":\"IoTAnalytics\"},\"iot1clickdevicesservice\":{\"prefix\":\"iot1click-devices\",\"name\":\"IoT1ClickDevicesService\"},\"iot1clickprojects\":{\"prefix\":\"iot1click-projects\",\"name\":\"IoT1ClickProjects\"},\"pi\":{\"name\":\"PI\"},\"neptune\":{\"name\":\"Neptune\"},\"mediatailor\":{\"name\":\"MediaTailor\"},\"eks\":{\"name\":\"EKS\"},\"macie\":{\"name\":\"Macie\"},\"dlm\":{\"name\":\"DLM\"},\"signer\":{\"name\":\"Signer\"},\"chime\":{\"name\":\"Chime\"},\"pinpointemail\":{\"prefix\":\"pinpoint-email\",\"name\":\"PinpointEmail\"},\"ram\":{\"name\":\"RAM\"},\"route53resolver\":{\"name\":\"Route53Resolver\"},\"pinpointsmsvoice\":{\"prefix\":\"sms-voice\",\"name\":\"PinpointSMSVoice\"},\"quicksight\":{\"name\":\"QuickSight\"},\"rdsdataservice\":{\"prefix\":\"rds-data\",\"name\":\"RDSDataService\"},\"amplify\":{\"name\":\"Amplify\"},\"datasync\":{\"name\":\"DataSync\"},\"robomaker\":{\"name\":\"RoboMaker\"},\"transfer\":{\"name\":\"Transfer\"},\"globalaccelerator\":{\"name\":\"GlobalAccelerator\"},\"comprehendmedical\":{\"name\":\"ComprehendMedical\",\"cors\":true},\"kinesisanalyticsv2\":{\"name\":\"KinesisAnalyticsV2\"},\"mediaconnect\":{\"name\":\"MediaConnect\"},\"fsx\":{\"name\":\"FSx\"},\"securityhub\":{\"name\":\"SecurityHub\"},\"appmesh\":{\"name\":\"AppMesh\",\"versions\":[\"2018-10-01*\"]},\"licensemanager\":{\"prefix\":\"license-manager\",\"name\":\"LicenseManager\"},\"kafka\":{\"name\":\"Kafka\"},\"apigatewaymanagementapi\":{\"name\":\"ApiGatewayManagementApi\"},\"apigatewayv2\":{\"name\":\"ApiGatewayV2\"},\"docdb\":{\"name\":\"DocDB\"},\"backup\":{\"name\":\"Backup\"},\"worklink\":{\"name\":\"WorkLink\"},\"textract\":{\"name\":\"Textract\"},\"managedblockchain\":{\"name\":\"ManagedBlockchain\"},\"mediapackagevod\":{\"prefix\":\"mediapackage-vod\",\"name\":\"MediaPackageVod\"},\"groundstation\":{\"name\":\"GroundStation\"},\"iotthingsgraph\":{\"name\":\"IoTThingsGraph\"},\"iotevents\":{\"name\":\"IoTEvents\"},\"ioteventsdata\":{\"prefix\":\"iotevents-data\",\"name\":\"IoTEventsData\"},\"personalize\":{\"name\":\"Personalize\",\"cors\":true},\"personalizeevents\":{\"prefix\":\"personalize-events\",\"name\":\"PersonalizeEvents\",\"cors\":true},\"personalizeruntime\":{\"prefix\":\"personalize-runtime\",\"name\":\"PersonalizeRuntime\",\"cors\":true},\"applicationinsights\":{\"prefix\":\"application-insights\",\"name\":\"ApplicationInsights\"},\"servicequotas\":{\"prefix\":\"service-quotas\",\"name\":\"ServiceQuotas\"},\"ec2instanceconnect\":{\"prefix\":\"ec2-instance-connect\",\"name\":\"EC2InstanceConnect\"},\"eventbridge\":{\"name\":\"EventBridge\"},\"lakeformation\":{\"name\":\"LakeFormation\"},\"forecastservice\":{\"prefix\":\"forecast\",\"name\":\"ForecastService\"},\"forecastqueryservice\":{\"prefix\":\"forecastquery\",\"name\":\"ForecastQueryService\"}}"); /***/ }), /***/ "159b": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("da84"); var DOMIterables = __webpack_require__("fdbc"); var forEach = __webpack_require__("17c2"); var createNonEnumerableProperty = __webpack_require__("9112"); for (var COLLECTION_NAME in DOMIterables) { var Collection = global[COLLECTION_NAME]; var CollectionPrototype = Collection && Collection.prototype; // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try { createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach); } catch (error) { CollectionPrototype.forEach = forEach; } } /***/ }), /***/ "178e": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("42c5"); 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) { var now = request.service ? request.service.getSkewCorrectedDate() : AWS.util.date.getDate(); request.httpRequest.headers[expiresHeader] = parseInt( AWS.util.date.unixTimestamp(now) + 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)); } var auth = request.httpRequest.headers['Authorization'].split(' '); if (auth[0] === 'AWS') { auth = auth[1].split(':'); queryParams['AWSAccessKeyId'] = auth[0]; queryParams['Signature'] = auth[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]; delete queryParams['Authorization']; delete queryParams['Host']; } 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']; } // 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); } } }); /** * @api private */ module.exports = AWS.Signers.Presign; /***/ }), /***/ "17c2": /***/ (function(module, exports, __webpack_require__) { "use strict"; var $forEach = __webpack_require__("b727").forEach; var sloppyArrayMethod = __webpack_require__("b301"); // `Array.prototype.forEach` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.foreach module.exports = sloppyArrayMethod('forEach') ? function forEach(callbackfn /* , thisArg */) { return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } : [].forEach; /***/ }), /***/ "17e1": /***/ (function(module, exports, __webpack_require__) { ;(function (root, factory) { if (true) { // CommonJS module.exports = exports = factory(__webpack_require__("21bf")); } else {} }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); /***/ }), /***/ "1875": /***/ (function(module, exports) { // `RequireObjectCoercible` abstract operation // https://tc39.github.io/ecma262/#sec-requireobjectcoercible module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /***/ "194a": /***/ (function(module, exports, __webpack_require__) { var aFunction = __webpack_require__("cc94"); // optional / simple context binding module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 0: return function () { return fn.call(that); }; case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /***/ "1985": /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = true && exports && !exports.nodeType && exports; var freeModule = true && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( true ) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return punycode; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }(this)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("62e4")(module), __webpack_require__("c8ba"))) /***/ }), /***/ "19aa": /***/ (function(module, exports) { module.exports = function (it, Constructor, name) { if (!(it instanceof Constructor)) { throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation'); } return it; }; /***/ }), /***/ "1be4": /***/ (function(module, exports, __webpack_require__) { var getBuiltIn = __webpack_require__("d066"); module.exports = getBuiltIn('document', 'documentElement'); /***/ }), /***/ "1c0b": /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') { throw TypeError(String(it) + ' is not a function'); } return it; }; /***/ }), /***/ "1c7e": /***/ (function(module, exports, __webpack_require__) { var wellKnownSymbol = __webpack_require__("b622"); var ITERATOR = wellKnownSymbol('iterator'); var SAFE_CLOSING = false; try { var called = 0; var iteratorWithReturn = { next: function () { return { done: !!called++ }; }, 'return': function () { SAFE_CLOSING = true; } }; iteratorWithReturn[ITERATOR] = function () { return this; }; // eslint-disable-next-line no-throw-literal Array.from(iteratorWithReturn, function () { throw 2; }); } catch (error) { /* empty */ } module.exports = function (exec, SKIP_CLOSING) { if (!SKIP_CLOSING && !SAFE_CLOSING) return false; var ITERATION_SUPPORT = false; try { var object = {}; object[ITERATOR] = function () { return { next: function () { return { done: ITERATION_SUPPORT = true }; } }; }; exec(object); } catch (error) { /* empty */ } return ITERATION_SUPPORT; }; /***/ }), /***/ "1d2b": /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ "1d80": /***/ (function(module, exports) { // `RequireObjectCoercible` abstract operation // https://tc39.github.io/ecma262/#sec-requireobjectcoercible module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /***/ "1dde": /***/ (function(module, exports, __webpack_require__) { var fails = __webpack_require__("d039"); var wellKnownSymbol = __webpack_require__("b622"); var V8_VERSION = __webpack_require__("60ae"); var SPECIES = wellKnownSymbol('species'); module.exports = function (METHOD_NAME) { // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/677 return V8_VERSION >= 51 || !fails(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; /***/ }), /***/ "1f3a": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) {/* * Copyright 2017-2017 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 MIME_MAP = [ { type: 'text/plain', ext: 'txt' }, { type: 'text/html', ext: 'html' }, { type: 'text/javascript', ext: 'js' }, { type: 'text/css', ext: 'css' }, { type: 'text/csv', ext: 'csv' }, { type: 'text/yaml', ext: 'yml' }, { type: 'text/yaml', ext: 'yaml' }, { type: 'text/calendar', ext: 'ics' }, { type: 'text/calendar', ext: 'ical' }, { type: 'image/png', ext: 'png' }, { type: 'image/gif', ext: 'gif' }, { type: 'image/jpeg', ext: 'jpg' }, { type: 'image/jpeg', ext: 'jpeg' }, { type: 'image/bmp', ext: 'bmp' }, { type: 'image/x-icon', ext: 'ico' }, { type: 'image/tiff', ext: 'tif' }, { type: 'image/tiff', ext: 'tiff' }, { type: 'image/svg+xml', ext: 'svg' }, { type: 'application/json', ext: 'json' }, { type: 'application/xml', ext: 'xml' }, { type: 'application/x-sh', ext: 'sh' }, { type: 'application/zip', ext: 'zip' }, { type: 'application/x-rar-compressed', ext: 'rar' }, { type: 'application/x-tar', ext: 'tar' }, { type: 'application/x-bzip', ext: 'bz' }, { type: 'application/x-bzip2', ext: 'bz2' }, { type: 'application/pdf', ext: 'pdf' }, { type: 'application/java-archive', ext: 'jar' }, { type: 'application/msword', ext: 'doc' }, { type: 'application/vnd.ms-excel', ext: 'xls' }, { type: 'application/vnd.ms-excel', ext: 'xlsx' }, { type: 'message/rfc822', ext: 'eml' }, ]; var JS = /** @class */ (function () { function JS() { } JS.isEmpty = function (obj) { return Object.keys(obj).length === 0; }; JS.sortByField = function (list, field, dir) { if (!list || !list.sort) { return false; } var dirX = dir && dir === 'desc' ? -1 : 1; list.sort(function (a, b) { var a_val = a[field]; var b_val = b[field]; if (typeof b_val === 'undefined') { return typeof a_val === 'undefined' ? 0 : 1 * dirX; } if (typeof a_val === 'undefined') { return -1 * dirX; } if (a_val < b_val) { return -1 * dirX; } if (a_val > b_val) { return 1 * dirX; } return 0; }); return true; }; JS.objectLessAttributes = function (obj, less) { var ret = Object.assign({}, obj); if (less) { if (typeof less === 'string') { delete ret[less]; } else { less.forEach(function (attr) { delete ret[attr]; }); } } return ret; }; JS.filenameToContentType = function (filename, defVal) { if (defVal === void 0) { defVal = 'application/octet-stream'; } var name = filename.toLowerCase(); var filtered = MIME_MAP.filter(function (mime) { return name.endsWith('.' + mime.ext); }); return filtered.length > 0 ? filtered[0].type : defVal; }; JS.isTextFile = function (contentType) { var type = contentType.toLowerCase(); if (type.startsWith('text/')) { return true; } return ('application/json' === type || 'application/xml' === type || 'application/sh' === type); }; /** * generate random string */ JS.generateRandomString = function () { var result = ''; var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; for (var i = 32; i > 0; i -= 1) { result += chars[Math.floor(Math.random() * chars.length)]; } return result; }; JS.makeQuerablePromise = function (promise) { if (promise.isResolved) return promise; var isPending = true; var isRejected = false; var isFullfilled = false; var result = promise.then(function (data) { isFullfilled = true; isPending = false; return data; }, function (e) { isRejected = true; isPending = false; throw e; }); result.isFullfilled = function () { return isFullfilled; }; result.isPending = function () { return isPending; }; result.isRejected = function () { return isRejected; }; return result; }; JS.browserOrNode = function () { var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined'; var isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null; return { isBrowser: isBrowser, isNode: isNode, }; }; /** * transfer the first letter of the keys to lowercase * @param {Object} obj - the object need to be transferred * @param {Array} whiteListForItself - whitelist itself from being transferred * @param {Array} whiteListForChildren - whitelist its children keys from being transferred */ JS.transferKeyToLowerCase = function (obj, whiteListForItself, whiteListForChildren) { if (whiteListForItself === void 0) { whiteListForItself = []; } if (whiteListForChildren === void 0) { whiteListForChildren = []; } if (!JS.isStrictObject(obj)) return obj; var ret = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { var transferedKey = whiteListForItself.includes(key) ? key : key[0].toLowerCase() + key.slice(1); ret[transferedKey] = whiteListForChildren.includes(key) ? obj[key] : JS.transferKeyToLowerCase(obj[key], whiteListForItself, whiteListForChildren); } } return ret; }; /** * transfer the first letter of the keys to lowercase * @param {Object} obj - the object need to be transferred * @param {Array} whiteListForItself - whitelist itself from being transferred * @param {Array} whiteListForChildren - whitelist its children keys from being transferred */ JS.transferKeyToUpperCase = function (obj, whiteListForItself, whiteListForChildren) { if (whiteListForItself === void 0) { whiteListForItself = []; } if (whiteListForChildren === void 0) { whiteListForChildren = []; } if (!JS.isStrictObject(obj)) return obj; var ret = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { var transferedKey = whiteListForItself.includes(key) ? key : key[0].toUpperCase() + key.slice(1); ret[transferedKey] = whiteListForChildren.includes(key) ? obj[key] : JS.transferKeyToUpperCase(obj[key], whiteListForItself, whiteListForChildren); } } return ret; }; /** * Return true if the object is a strict object * which means it's not Array, Function, Number, String, Boolean or Null * @param obj the Object */ JS.isStrictObject = function (obj) { return (obj instanceof Object && !(obj instanceof Array) && !(obj instanceof Function) && !(obj instanceof Number) && !(obj instanceof String) && !(obj instanceof Boolean)); }; return JS; }()); /* harmony default export */ __webpack_exports__["a"] = (JS); //# sourceMappingURL=JS.js.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("4362"))) /***/ }), /***/ "1fb5": /***/ (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 } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } 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) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) 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 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] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } /***/ }), /***/ "21bf": /***/ (function(module, exports, __webpack_require__) { ;(function (root, factory) { if (true) { // CommonJS module.exports = exports = factory(); } else {} }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /* * Local polyfil of Object.create */ var create = Object.create || (function () { function F() {}; return function (obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()) /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); /***/ }), /***/ "2266": /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__("825a"); var isArrayIteratorMethod = __webpack_require__("e95a"); var toLength = __webpack_require__("50c4"); var bind = __webpack_require__("f8c2"); var getIteratorMethod = __webpack_require__("35a1"); var callWithSafeIterationClosing = __webpack_require__("9bdd"); var Result = function (stopped, result) { this.stopped = stopped; this.result = result; }; var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) { var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1); var iterator, iterFn, index, length, result, next, step; if (IS_ITERATOR) { iterator = iterable; } else { iterFn = getIteratorMethod(iterable); if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); // optimisation for array iterators if (isArrayIteratorMethod(iterFn)) { for (index = 0, length = toLength(iterable.length); length > index; index++) { result = AS_ENTRIES ? boundFunction(anObject(step = iterable[index])[0], step[1]) : boundFunction(iterable[index]); if (result && result instanceof Result) return result; } return new Result(false); } iterator = iterFn.call(iterable); } next = iterator.next; while (!(step = next.call(iterator)).done) { result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES); if (typeof result == 'object' && result && result instanceof Result) return result; } return new Result(false); }; iterate.stop = function (result) { return new Result(true, result); }; /***/ }), /***/ "23cb": /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__("a691"); var max = Math.max; var min = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(length, length). module.exports = function (index, length) { var integer = toInteger(index); return integer < 0 ? max(integer + length, 0) : min(integer, length); }; /***/ }), /***/ "23e7": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("da84"); var getOwnPropertyDescriptor = __webpack_require__("06cf").f; var createNonEnumerableProperty = __webpack_require__("9112"); var redefine = __webpack_require__("6eeb"); var setGlobal = __webpack_require__("ce4e"); var copyConstructorProperties = __webpack_require__("e893"); var isForced = __webpack_require__("94ca"); /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ module.exports = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global; } else if (STATIC) { target = global[TARGET] || setGlobal(TARGET, {}); } else { target = (global[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } }; /***/ }), /***/ "241c": /***/ (function(module, exports, __webpack_require__) { var internalObjectKeys = __webpack_require__("ca84"); var enumBugKeys = __webpack_require__("7839"); var hiddenKeys = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return internalObjectKeys(O, hiddenKeys); }; /***/ }), /***/ "2444": /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) { var utils = __webpack_require__("c532"); var normalizeHeaderName = __webpack_require__("c8af"); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; // Only Node.JS has a process variable that is of [[Class]] process if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = __webpack_require__("b50d"); } else if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __webpack_require__("b50d"); } return adapter; } var defaults = { adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__("4362"))) /***/ }), /***/ "2560": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("05a3"); 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); } /** * @api private */ module.exports = JsonBuilder; /***/ }), /***/ "2626": /***/ (function(module, exports, __webpack_require__) { "use strict"; var getBuiltIn = __webpack_require__("d066"); var definePropertyModule = __webpack_require__("9bf2"); var wellKnownSymbol = __webpack_require__("b622"); var DESCRIPTORS = __webpack_require__("83ab"); var SPECIES = wellKnownSymbol('species'); module.exports = function (CONSTRUCTOR_NAME) { var Constructor = getBuiltIn(CONSTRUCTOR_NAME); var defineProperty = definePropertyModule.f; if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) { defineProperty(Constructor, SPECIES, { configurable: true, get: function () { return this; } }); } }; /***/ }), /***/ "2735": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("42c5"); 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); } }); /***/ }), /***/ "2856": /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__("05a3"); var populateHostPrefix = __webpack_require__("9521").populateHostPrefix; function populateMethod(req) { req.httpRequest.method = req.service.api.operations[req.operation].httpMethod; } function generateURI(endpointPath, operationPath, input, params) { var uri = [endpointPath, operationPath].join('/'); uri = uri.replace(/\/+/g, '/'); var queryString = {}, queryStringSet = false; util.each(input.members, function (name, member) { var paramValue = params[name]; if (paramValue === null || paramValue === undefined) return; if (member.location === 'uri') { var regex = new RegExp('\\{' + member.name + '(\\+)?\\}'); uri = uri.replace(regex, function(_, plus) { var fn = plus ? util.uriEscapePath : util.uriEscape; return fn(String(paramValue)); }); } else if (member.location === 'querystring') { queryStringSet = true; if (member.type === 'list') { queryString[member.name] = paramValue.map(function(val) { return util.uriEscape(member.member.toWireFormat(val).toString()); }); } else if (member.type === 'map') { util.each(paramValue, function(key, value) { if (Array.isArray(value)) { queryString[key] = value.map(function(val) { return util.uriEscape(String(val)); }); } else { queryString[key] = util.uriEscape(String(value)); } }); } else { queryString[member.name] = util.uriEscape(member.toWireFormat(paramValue).toString()); } } }); if (queryStringSet) { uri += (uri.indexOf('?') >= 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); populateHostPrefix(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; } /** * @api private */ module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData, generateURI: generateURI }; /***/ }), /***/ "2877": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return normalizeComponent; }); /* globals __VUE_SSR_CONTEXT__ */ // IMPORTANT: Do NOT use ES2015 features in this file (except for modules). // This module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle. function normalizeComponent ( scriptExports, render, staticRenderFns, functionalTemplate, injectStyles, scopeId, moduleIdentifier, /* server only */ shadowMode /* vue-cli only */ ) { // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (render) { options.render = render options.staticRenderFns = staticRenderFns options._compiled = true } // functional template if (functionalTemplate) { options.functional = true } // scopedId if (scopeId) { options._scopeId = 'data-v-' + scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = shadowMode ? function () { injectStyles.call(this, this.$root.$options.shadowRoot) } : injectStyles } if (hook) { if (options.functional) { // for template-only hot-reload because in that case the render fn doesn't // go through the normalizer options._injectStyles = hook // register for functioal component in vue file var originalRender = options.render options.render = function renderWithStyleInjection (h, context) { hook.call(context) return originalRender(h, context) } } else { // inject component registration as beforeCreate hook var existing = options.beforeCreate options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } } return { exports: scriptExports, options: options } } /***/ }), /***/ "2886": /***/ (function(module, exports, __webpack_require__) { var AWS = __webpack_require__("42c5"); var v4Credentials = __webpack_require__("146b"); 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; this.signatureVersion = options.signatureVersion; }, 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' && this.signatureVersion !== 's3v4') 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; } }); /** * @api private */ module.exports = AWS.Signers.V4; /***/ }), /***/ "28a0": /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /***/ "2b0e": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global) {/*! * Vue.js v2.6.10 * (c) 2014-2019 Evan You * Released under the MIT License. */ /* */ var emptyObject = Object.freeze({}); // These helpers produce better VM code in JS engines due to their // explicitness and function inlining. function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive. */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || // $flow-disable-line typeof value === 'symbol' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value, e.g., [object Object]. */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } function isPromise (val) { return ( isDef(val) && typeof val.then === 'function' && typeof val.catch === 'function' ) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, null, 2) : String(val) } /** * Convert an input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if an attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array. */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether an object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind polyfill for environments that do not support it, * e.g., PhantomJS 1.x. Technically, we don't need this anymore * since native bind is now performant enough in most browsers. * But removing it would mean breaking code that was able to run in * PhantomJS 1.x, so this must be kept for backward compatibility. */ /* istanbul ignore next */ function polyfillBind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } boundFn._length = fn.length; return boundFn } function nativeBind (fn, ctx) { return fn.bind(ctx) } var bind = Function.prototype.bind ? nativeBind : polyfillBind; /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /* eslint-disable no-unused-vars */ /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /* eslint-enable no-unused-vars */ /** * Return the same value. */ var identity = function (_) { return _; }; /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime() } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } /** * Return the first index at which a loosely equal value can be * found in the array (if value is a plain object, the array must * contain an object of the same shape), or -1 if it is not present. */ function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured', 'serverPrefetch' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ // $flow-disable-line optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: "production" !== 'production', /** * Whether to enable devtools */ devtools: "production" !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ // $flow-disable-line keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Perform updates asynchronously. Intended to be used by Vue Test Utils * This will significantly reduce performance if set to false. */ async: true, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ /** * unicode letters used for parsing html tags, component names and property paths. * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname * skipping \u10000-\uEFFFF due to it freezing up PhantomJS */ var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/; /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]")); function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; var isPhantomJS = UA && /phantomjs/.test(UA); var isFF = UA && UA.match(/firefox\/(\d+)/); // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && !inWeex && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'] && global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = /*@__PURE__*/(function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); if (false) { var repeat, classify, classifyRE, hasConsole; } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); if (false) {} for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // The current target watcher being evaluated. // This is globally unique because only one watcher // can be evaluated at a time. Dep.target = null; var targetStack = []; function pushTarget (target) { targetStack.push(target); Dep.target = target; } function popTarget () { targetStack.pop(); Dep.target = targetStack[targetStack.length - 1]; } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.fnContext = undefined; this.fnOptions = undefined; this.fnScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, // #7975 // clone children array to avoid mutating original in case of cloning // a child. vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.fnContext = vnode.fnContext; cloned.fnOptions = vnode.fnOptions; cloned.fnScopeId = vnode.fnScopeId; cloned.asyncMeta = vnode.asyncMeta; cloned.isCloned = true; return cloned } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto); var methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * In some cases we may want to disable observation inside a component's * update computation. */ var shouldObserve = true; function toggleObserving (value) { shouldObserve = value; } /** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { if (hasProto) { protoAugment(value, arrayMethods); } else { copyAugment(value, arrayMethods, arrayKeys); } this.observeArray(value); } else { this.walk(value); } }; /** * Walk through all properties and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment a target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment a target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; if ((!getter || setter) && arguments.length === 2) { val = obj[key]; } var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (false) {} // #7981: for accessor properties without setter if (getter && !setter) { return } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (false ) {} if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (key in target && !(key in Object.prototype)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { false && false; return val } if (!ob) { target[key] = val; return val } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (false ) {} if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { false && false; return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ if (false) {} /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = hasSymbol ? Reflect.ownKeys(from) : Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; // in case the object is already observed... if (key === '__ob__') { continue } toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if ( toVal !== fromVal && isPlainObject(toVal) && isPlainObject(fromVal) ) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this, this) : childVal, typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal ) } } else { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm, vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm, vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { false && false; return parentVal } return mergeDataOrFn(parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal; return res ? dedupeHooks(res) : res } function dedupeHooks (hooks) { var res = []; for (var i = 0; i < hooks.length; i++) { if (res.indexOf(hooks[i]) === -1) { res.push(hooks[i]); } } return res } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { false && false; return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } if (false) {} if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && "production" !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { validateComponentName(key); } } function validateComponentName (name) { if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'should conform to valid custom element name in html5 specification.' ); } if (isBuiltInTag(name) || config.isReservedTag(name)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + name ); } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else if (false) {} } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else if (false) {} options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; if (!inject) { return } var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else if (false) {} } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def$$1 = dirs[key]; if (typeof def$$1 === 'function') { dirs[key] = { bind: def$$1, update: def$$1 }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { if (false) {} if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); // Apply extends and mixins on the child options, // but only if it is a raw options object that isn't // the result of another mergeOptions call. // Only merged options has the _base property. if (!child._base) { if (child.extends) { parent = mergeOptions(parent, child.extends, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (false) {} return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // boolean casting var booleanIndex = getTypeIndex(Boolean, prop.type); if (booleanIndex > -1) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (value === '' || value === hyphenate(key)) { // only cast empty string / same name to boolean if // boolean has higher priority var stringIndex = getTypeIndex(String, prop.type); if (stringIndex < 0 || booleanIndex < stringIndex) { value = true; } } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldObserve = shouldObserve; toggleObserving(true); observe(value); toggleObserving(prevShouldObserve); } if ( false ) {} return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (false) {} // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( getInvalidTypeMessage(name, value, expectedTypes), vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isSameType (a, b) { return getType(a) === getType(b) } function getTypeIndex (type, expectedTypes) { if (!Array.isArray(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1 } for (var i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i } } return -1 } function getInvalidTypeMessage (name, value, expectedTypes) { var message = "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')); var expectedType = expectedTypes[0]; var receivedType = toRawType(value); var expectedValue = styleValue(value, expectedType); var receivedValue = styleValue(value, receivedType); // check if we need to specify expected value if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) { message += " with value " + expectedValue; } message += ", got " + receivedType + " "; // check if we need to specify received value if (isExplicable(receivedType)) { message += "with value " + receivedValue + "."; } return message } function styleValue (value, type) { if (type === 'String') { return ("\"" + value + "\"") } else if (type === 'Number') { return ("" + (Number(value))) } else { return ("" + value) } } function isExplicable (value) { var explicitTypes = ['string', 'number', 'boolean']; return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; }) } function isBoolean () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; }) } /* */ function handleError (err, vm, info) { // Deactivate deps tracking while processing error handler to avoid possible infinite rendering. // See: https://github.com/vuejs/vuex/issues/1505 pushTarget(); try { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } finally { popTarget(); } } function invokeWithErrorHandling ( handler, context, args, vm, info ) { var res; try { res = args ? handler.apply(context, args) : handler.call(context); if (res && !res._isVue && isPromise(res) && !res._handled) { res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); // issue #9511 // avoid catch triggering multiple times when nested calls res._handled = true; } } catch (e) { handleError(e, vm, info); } return res } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { // if the user intentionally throws the original error in the handler, // do not log it twice if (e !== err) { logError(e, null, 'config.errorHandler'); } } } logError(err, vm, info); } function logError (err, vm, info) { if (false) {} /* istanbul ignore else */ if ((inBrowser || inWeex) && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ var isUsingMicroTask = false; var callbacks = []; var pending = false; function flushCallbacks () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // Here we have async deferring wrappers using microtasks. // In 2.5 we used (macro) tasks (in combination with microtasks). // However, it has subtle problems when state is changed right before repaint // (e.g. #6813, out-in transitions). // Also, using (macro) tasks in event handler would cause some weird behaviors // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109). // So we now use microtasks everywhere, again. // A major drawback of this tradeoff is that there are some scenarios // where microtasks have too high a priority and fire in between supposedly // sequential events (e.g. #4521, #6690, which have workarounds) // or even between bubbling of the same event (#6566). var timerFunc; // The nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); timerFunc = function () { p.then(flushCallbacks); // In problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; isUsingMicroTask = true; } else if (!isIE && typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // Use MutationObserver where native Promise is not available, // e.g. PhantomJS, iOS7, Android 4.4 // (#6466 MutationObserver is unreliable in IE11) var counter = 1; var observer = new MutationObserver(flushCallbacks); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; isUsingMicroTask = true; } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { // Fallback to setImmediate. // Techinically it leverages the (macro) task queue, // but it is still a better choice than setTimeout. timerFunc = function () { setImmediate(flushCallbacks); }; } else { // Fallback to setTimeout. timerFunc = function () { setTimeout(flushCallbacks, 0); }; } function nextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } /* */ /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; if (false) { var getHandler, hasHandler, isBuiltInModifier, hasProxy, warnReservedPrefix, warnNonPresent, allowedGlobals; } /* */ var seenObjects = new _Set(); /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ function traverse (val) { _traverse(val, seenObjects); seenObjects.clear(); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } var mark; var measure; if (false) { var perf; } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns, vm) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler"); } } else { // return handler return value for single handlers return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler") } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, createOnceHandler, vm ) { var name, def$$1, cur, old, event; for (name in on) { def$$1 = cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { false && false; } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur, vm); } if (isTrue(event.once)) { cur = on[name] = createOnceHandler(event.name, cur, event.capture); } add(event.name, cur, event.capture, event.passive, event.params); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { if (def instanceof VNode) { def = def.data.hook || (def.data.hook = {}); } var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); if (false) { var keyInLowerCase; } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g.