UNPKG

252 kBJavaScriptView Raw
1/*!
2 * Copyright 2016 Amazon.com,
3 * Inc. or its affiliates. All Rights Reserved.
4 *
5 * Licensed under the Amazon Software License (the "License").
6 * You may not use this file except in compliance with the
7 * License. A copy of the License is located at
8 *
9 * http://aws.amazon.com/asl/
10 *
11 * or in the "license" file accompanying this file. This file is
12 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
13 * CONDITIONS OF ANY KIND, express or implied. See the License
14 * for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18
19(function webpackUniversalModuleDefinition(root, factory) {
20 if(typeof exports === 'object' && typeof module === 'object')
21 module.exports = factory();
22 else if(typeof define === 'function' && define.amd)
23 define([], factory);
24 else if(typeof exports === 'object')
25 exports["AmazonCognitoIdentity"] = factory();
26 else
27 root["AmazonCognitoIdentity"] = factory();
28})(typeof self !== 'undefined' ? self : this, function() {
29return /******/ (function(modules) { // webpackBootstrap
30/******/ // The module cache
31/******/ var installedModules = {};
32/******/
33/******/ // The require function
34/******/ function __webpack_require__(moduleId) {
35/******/
36/******/ // Check if module is in cache
37/******/ if(installedModules[moduleId]) {
38/******/ return installedModules[moduleId].exports;
39/******/ }
40/******/ // Create a new module (and put it into the cache)
41/******/ var module = installedModules[moduleId] = {
42/******/ i: moduleId,
43/******/ l: false,
44/******/ exports: {}
45/******/ };
46/******/
47/******/ // Execute the module function
48/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
49/******/
50/******/ // Flag the module as loaded
51/******/ module.l = true;
52/******/
53/******/ // Return the exports of the module
54/******/ return module.exports;
55/******/ }
56/******/
57/******/
58/******/ // expose the modules object (__webpack_modules__)
59/******/ __webpack_require__.m = modules;
60/******/
61/******/ // expose the module cache
62/******/ __webpack_require__.c = installedModules;
63/******/
64/******/ // define getter function for harmony exports
65/******/ __webpack_require__.d = function(exports, name, getter) {
66/******/ if(!__webpack_require__.o(exports, name)) {
67/******/ Object.defineProperty(exports, name, {
68/******/ configurable: false,
69/******/ enumerable: true,
70/******/ get: getter
71/******/ });
72/******/ }
73/******/ };
74/******/
75/******/ // getDefaultExport function for compatibility with non-harmony modules
76/******/ __webpack_require__.n = function(module) {
77/******/ var getter = module && module.__esModule ?
78/******/ function getDefault() { return module['default']; } :
79/******/ function getModuleExports() { return module; };
80/******/ __webpack_require__.d(getter, 'a', getter);
81/******/ return getter;
82/******/ };
83/******/
84/******/ // Object.prototype.hasOwnProperty.call
85/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
86/******/
87/******/ // __webpack_public_path__
88/******/ __webpack_require__.p = "";
89/******/
90/******/ // Load entry module and return exports
91/******/ return __webpack_require__(__webpack_require__.s = 18);
92/******/ })
93/************************************************************************/
94/******/ ([
95/* 0 */
96/***/ (function(module, exports, __webpack_require__) {
97
98;(function (root, factory) {
99 if (true) {
100 // CommonJS
101 module.exports = exports = factory();
102 }
103 else if (typeof define === "function" && define.amd) {
104 // AMD
105 define([], factory);
106 }
107 else {
108 // Global (browser)
109 root.CryptoJS = factory();
110 }
111}(this, function () {
112
113 /**
114 * CryptoJS core components.
115 */
116 var CryptoJS = CryptoJS || (function (Math, undefined) {
117 /*
118 * Local polyfil of Object.create
119 */
120 var create = Object.create || (function () {
121 function F() {};
122
123 return function (obj) {
124 var subtype;
125
126 F.prototype = obj;
127
128 subtype = new F();
129
130 F.prototype = null;
131
132 return subtype;
133 };
134 }())
135
136 /**
137 * CryptoJS namespace.
138 */
139 var C = {};
140
141 /**
142 * Library namespace.
143 */
144 var C_lib = C.lib = {};
145
146 /**
147 * Base object for prototypal inheritance.
148 */
149 var Base = C_lib.Base = (function () {
150
151
152 return {
153 /**
154 * Creates a new object that inherits from this object.
155 *
156 * @param {Object} overrides Properties to copy into the new object.
157 *
158 * @return {Object} The new object.
159 *
160 * @static
161 *
162 * @example
163 *
164 * var MyType = CryptoJS.lib.Base.extend({
165 * field: 'value',
166 *
167 * method: function () {
168 * }
169 * });
170 */
171 extend: function (overrides) {
172 // Spawn
173 var subtype = create(this);
174
175 // Augment
176 if (overrides) {
177 subtype.mixIn(overrides);
178 }
179
180 // Create default initializer
181 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
182 subtype.init = function () {
183 subtype.$super.init.apply(this, arguments);
184 };
185 }
186
187 // Initializer's prototype is the subtype object
188 subtype.init.prototype = subtype;
189
190 // Reference supertype
191 subtype.$super = this;
192
193 return subtype;
194 },
195
196 /**
197 * Extends this object and runs the init method.
198 * Arguments to create() will be passed to init().
199 *
200 * @return {Object} The new object.
201 *
202 * @static
203 *
204 * @example
205 *
206 * var instance = MyType.create();
207 */
208 create: function () {
209 var instance = this.extend();
210 instance.init.apply(instance, arguments);
211
212 return instance;
213 },
214
215 /**
216 * Initializes a newly created object.
217 * Override this method to add some logic when your objects are created.
218 *
219 * @example
220 *
221 * var MyType = CryptoJS.lib.Base.extend({
222 * init: function () {
223 * // ...
224 * }
225 * });
226 */
227 init: function () {
228 },
229
230 /**
231 * Copies properties into this object.
232 *
233 * @param {Object} properties The properties to mix in.
234 *
235 * @example
236 *
237 * MyType.mixIn({
238 * field: 'value'
239 * });
240 */
241 mixIn: function (properties) {
242 for (var propertyName in properties) {
243 if (properties.hasOwnProperty(propertyName)) {
244 this[propertyName] = properties[propertyName];
245 }
246 }
247
248 // IE won't copy toString using the loop above
249 if (properties.hasOwnProperty('toString')) {
250 this.toString = properties.toString;
251 }
252 },
253
254 /**
255 * Creates a copy of this object.
256 *
257 * @return {Object} The clone.
258 *
259 * @example
260 *
261 * var clone = instance.clone();
262 */
263 clone: function () {
264 return this.init.prototype.extend(this);
265 }
266 };
267 }());
268
269 /**
270 * An array of 32-bit words.
271 *
272 * @property {Array} words The array of 32-bit words.
273 * @property {number} sigBytes The number of significant bytes in this word array.
274 */
275 var WordArray = C_lib.WordArray = Base.extend({
276 /**
277 * Initializes a newly created word array.
278 *
279 * @param {Array} words (Optional) An array of 32-bit words.
280 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
281 *
282 * @example
283 *
284 * var wordArray = CryptoJS.lib.WordArray.create();
285 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
286 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
287 */
288 init: function (words, sigBytes) {
289 words = this.words = words || [];
290
291 if (sigBytes != undefined) {
292 this.sigBytes = sigBytes;
293 } else {
294 this.sigBytes = words.length * 4;
295 }
296 },
297
298 /**
299 * Converts this word array to a string.
300 *
301 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
302 *
303 * @return {string} The stringified word array.
304 *
305 * @example
306 *
307 * var string = wordArray + '';
308 * var string = wordArray.toString();
309 * var string = wordArray.toString(CryptoJS.enc.Utf8);
310 */
311 toString: function (encoder) {
312 return (encoder || Hex).stringify(this);
313 },
314
315 /**
316 * Concatenates a word array to this word array.
317 *
318 * @param {WordArray} wordArray The word array to append.
319 *
320 * @return {WordArray} This word array.
321 *
322 * @example
323 *
324 * wordArray1.concat(wordArray2);
325 */
326 concat: function (wordArray) {
327 // Shortcuts
328 var thisWords = this.words;
329 var thatWords = wordArray.words;
330 var thisSigBytes = this.sigBytes;
331 var thatSigBytes = wordArray.sigBytes;
332
333 // Clamp excess bits
334 this.clamp();
335
336 // Concat
337 if (thisSigBytes % 4) {
338 // Copy one byte at a time
339 for (var i = 0; i < thatSigBytes; i++) {
340 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
341 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
342 }
343 } else {
344 // Copy one word at a time
345 for (var i = 0; i < thatSigBytes; i += 4) {
346 thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
347 }
348 }
349 this.sigBytes += thatSigBytes;
350
351 // Chainable
352 return this;
353 },
354
355 /**
356 * Removes insignificant bits.
357 *
358 * @example
359 *
360 * wordArray.clamp();
361 */
362 clamp: function () {
363 // Shortcuts
364 var words = this.words;
365 var sigBytes = this.sigBytes;
366
367 // Clamp
368 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
369 words.length = Math.ceil(sigBytes / 4);
370 },
371
372 /**
373 * Creates a copy of this word array.
374 *
375 * @return {WordArray} The clone.
376 *
377 * @example
378 *
379 * var clone = wordArray.clone();
380 */
381 clone: function () {
382 var clone = Base.clone.call(this);
383 clone.words = this.words.slice(0);
384
385 return clone;
386 },
387
388 /**
389 * Creates a word array filled with random bytes.
390 *
391 * @param {number} nBytes The number of random bytes to generate.
392 *
393 * @return {WordArray} The random word array.
394 *
395 * @static
396 *
397 * @example
398 *
399 * var wordArray = CryptoJS.lib.WordArray.random(16);
400 */
401 random: function (nBytes) {
402 var words = [];
403
404 var r = (function (m_w) {
405 var m_w = m_w;
406 var m_z = 0x3ade68b1;
407 var mask = 0xffffffff;
408
409 return function () {
410 m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
411 m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
412 var result = ((m_z << 0x10) + m_w) & mask;
413 result /= 0x100000000;
414 result += 0.5;
415 return result * (Math.random() > .5 ? 1 : -1);
416 }
417 });
418
419 for (var i = 0, rcache; i < nBytes; i += 4) {
420 var _r = r((rcache || Math.random()) * 0x100000000);
421
422 rcache = _r() * 0x3ade67b7;
423 words.push((_r() * 0x100000000) | 0);
424 }
425
426 return new WordArray.init(words, nBytes);
427 }
428 });
429
430 /**
431 * Encoder namespace.
432 */
433 var C_enc = C.enc = {};
434
435 /**
436 * Hex encoding strategy.
437 */
438 var Hex = C_enc.Hex = {
439 /**
440 * Converts a word array to a hex string.
441 *
442 * @param {WordArray} wordArray The word array.
443 *
444 * @return {string} The hex string.
445 *
446 * @static
447 *
448 * @example
449 *
450 * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
451 */
452 stringify: function (wordArray) {
453 // Shortcuts
454 var words = wordArray.words;
455 var sigBytes = wordArray.sigBytes;
456
457 // Convert
458 var hexChars = [];
459 for (var i = 0; i < sigBytes; i++) {
460 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
461 hexChars.push((bite >>> 4).toString(16));
462 hexChars.push((bite & 0x0f).toString(16));
463 }
464
465 return hexChars.join('');
466 },
467
468 /**
469 * Converts a hex string to a word array.
470 *
471 * @param {string} hexStr The hex string.
472 *
473 * @return {WordArray} The word array.
474 *
475 * @static
476 *
477 * @example
478 *
479 * var wordArray = CryptoJS.enc.Hex.parse(hexString);
480 */
481 parse: function (hexStr) {
482 // Shortcut
483 var hexStrLength = hexStr.length;
484
485 // Convert
486 var words = [];
487 for (var i = 0; i < hexStrLength; i += 2) {
488 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
489 }
490
491 return new WordArray.init(words, hexStrLength / 2);
492 }
493 };
494
495 /**
496 * Latin1 encoding strategy.
497 */
498 var Latin1 = C_enc.Latin1 = {
499 /**
500 * Converts a word array to a Latin1 string.
501 *
502 * @param {WordArray} wordArray The word array.
503 *
504 * @return {string} The Latin1 string.
505 *
506 * @static
507 *
508 * @example
509 *
510 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
511 */
512 stringify: function (wordArray) {
513 // Shortcuts
514 var words = wordArray.words;
515 var sigBytes = wordArray.sigBytes;
516
517 // Convert
518 var latin1Chars = [];
519 for (var i = 0; i < sigBytes; i++) {
520 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
521 latin1Chars.push(String.fromCharCode(bite));
522 }
523
524 return latin1Chars.join('');
525 },
526
527 /**
528 * Converts a Latin1 string to a word array.
529 *
530 * @param {string} latin1Str The Latin1 string.
531 *
532 * @return {WordArray} The word array.
533 *
534 * @static
535 *
536 * @example
537 *
538 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
539 */
540 parse: function (latin1Str) {
541 // Shortcut
542 var latin1StrLength = latin1Str.length;
543
544 // Convert
545 var words = [];
546 for (var i = 0; i < latin1StrLength; i++) {
547 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
548 }
549
550 return new WordArray.init(words, latin1StrLength);
551 }
552 };
553
554 /**
555 * UTF-8 encoding strategy.
556 */
557 var Utf8 = C_enc.Utf8 = {
558 /**
559 * Converts a word array to a UTF-8 string.
560 *
561 * @param {WordArray} wordArray The word array.
562 *
563 * @return {string} The UTF-8 string.
564 *
565 * @static
566 *
567 * @example
568 *
569 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
570 */
571 stringify: function (wordArray) {
572 try {
573 return decodeURIComponent(escape(Latin1.stringify(wordArray)));
574 } catch (e) {
575 throw new Error('Malformed UTF-8 data');
576 }
577 },
578
579 /**
580 * Converts a UTF-8 string to a word array.
581 *
582 * @param {string} utf8Str The UTF-8 string.
583 *
584 * @return {WordArray} The word array.
585 *
586 * @static
587 *
588 * @example
589 *
590 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
591 */
592 parse: function (utf8Str) {
593 return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
594 }
595 };
596
597 /**
598 * Abstract buffered block algorithm template.
599 *
600 * The property blockSize must be implemented in a concrete subtype.
601 *
602 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
603 */
604 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
605 /**
606 * Resets this block algorithm's data buffer to its initial state.
607 *
608 * @example
609 *
610 * bufferedBlockAlgorithm.reset();
611 */
612 reset: function () {
613 // Initial values
614 this._data = new WordArray.init();
615 this._nDataBytes = 0;
616 },
617
618 /**
619 * Adds new data to this block algorithm's buffer.
620 *
621 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
622 *
623 * @example
624 *
625 * bufferedBlockAlgorithm._append('data');
626 * bufferedBlockAlgorithm._append(wordArray);
627 */
628 _append: function (data) {
629 // Convert string to WordArray, else assume WordArray already
630 if (typeof data == 'string') {
631 data = Utf8.parse(data);
632 }
633
634 // Append
635 this._data.concat(data);
636 this._nDataBytes += data.sigBytes;
637 },
638
639 /**
640 * Processes available data blocks.
641 *
642 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
643 *
644 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
645 *
646 * @return {WordArray} The processed data.
647 *
648 * @example
649 *
650 * var processedData = bufferedBlockAlgorithm._process();
651 * var processedData = bufferedBlockAlgorithm._process(!!'flush');
652 */
653 _process: function (doFlush) {
654 // Shortcuts
655 var data = this._data;
656 var dataWords = data.words;
657 var dataSigBytes = data.sigBytes;
658 var blockSize = this.blockSize;
659 var blockSizeBytes = blockSize * 4;
660
661 // Count blocks ready
662 var nBlocksReady = dataSigBytes / blockSizeBytes;
663 if (doFlush) {
664 // Round up to include partial blocks
665 nBlocksReady = Math.ceil(nBlocksReady);
666 } else {
667 // Round down to include only full blocks,
668 // less the number of blocks that must remain in the buffer
669 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
670 }
671
672 // Count words ready
673 var nWordsReady = nBlocksReady * blockSize;
674
675 // Count bytes ready
676 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
677
678 // Process blocks
679 if (nWordsReady) {
680 for (var offset = 0; offset < nWordsReady; offset += blockSize) {
681 // Perform concrete-algorithm logic
682 this._doProcessBlock(dataWords, offset);
683 }
684
685 // Remove processed words
686 var processedWords = dataWords.splice(0, nWordsReady);
687 data.sigBytes -= nBytesReady;
688 }
689
690 // Return processed words
691 return new WordArray.init(processedWords, nBytesReady);
692 },
693
694 /**
695 * Creates a copy of this object.
696 *
697 * @return {Object} The clone.
698 *
699 * @example
700 *
701 * var clone = bufferedBlockAlgorithm.clone();
702 */
703 clone: function () {
704 var clone = Base.clone.call(this);
705 clone._data = this._data.clone();
706
707 return clone;
708 },
709
710 _minBufferSize: 0
711 });
712
713 /**
714 * Abstract hasher template.
715 *
716 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
717 */
718 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
719 /**
720 * Configuration options.
721 */
722 cfg: Base.extend(),
723
724 /**
725 * Initializes a newly created hasher.
726 *
727 * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
728 *
729 * @example
730 *
731 * var hasher = CryptoJS.algo.SHA256.create();
732 */
733 init: function (cfg) {
734 // Apply config defaults
735 this.cfg = this.cfg.extend(cfg);
736
737 // Set initial values
738 this.reset();
739 },
740
741 /**
742 * Resets this hasher to its initial state.
743 *
744 * @example
745 *
746 * hasher.reset();
747 */
748 reset: function () {
749 // Reset data buffer
750 BufferedBlockAlgorithm.reset.call(this);
751
752 // Perform concrete-hasher logic
753 this._doReset();
754 },
755
756 /**
757 * Updates this hasher with a message.
758 *
759 * @param {WordArray|string} messageUpdate The message to append.
760 *
761 * @return {Hasher} This hasher.
762 *
763 * @example
764 *
765 * hasher.update('message');
766 * hasher.update(wordArray);
767 */
768 update: function (messageUpdate) {
769 // Append
770 this._append(messageUpdate);
771
772 // Update the hash
773 this._process();
774
775 // Chainable
776 return this;
777 },
778
779 /**
780 * Finalizes the hash computation.
781 * Note that the finalize operation is effectively a destructive, read-once operation.
782 *
783 * @param {WordArray|string} messageUpdate (Optional) A final message update.
784 *
785 * @return {WordArray} The hash.
786 *
787 * @example
788 *
789 * var hash = hasher.finalize();
790 * var hash = hasher.finalize('message');
791 * var hash = hasher.finalize(wordArray);
792 */
793 finalize: function (messageUpdate) {
794 // Final message update
795 if (messageUpdate) {
796 this._append(messageUpdate);
797 }
798
799 // Perform concrete-hasher logic
800 var hash = this._doFinalize();
801
802 return hash;
803 },
804
805 blockSize: 512/32,
806
807 /**
808 * Creates a shortcut function to a hasher's object interface.
809 *
810 * @param {Hasher} hasher The hasher to create a helper for.
811 *
812 * @return {Function} The shortcut function.
813 *
814 * @static
815 *
816 * @example
817 *
818 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
819 */
820 _createHelper: function (hasher) {
821 return function (message, cfg) {
822 return new hasher.init(cfg).finalize(message);
823 };
824 },
825
826 /**
827 * Creates a shortcut function to the HMAC's object interface.
828 *
829 * @param {Hasher} hasher The hasher to use in this HMAC helper.
830 *
831 * @return {Function} The shortcut function.
832 *
833 * @static
834 *
835 * @example
836 *
837 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
838 */
839 _createHmacHelper: function (hasher) {
840 return function (message, key) {
841 return new C_algo.HMAC.init(hasher, key).finalize(message);
842 };
843 }
844 });
845
846 /**
847 * Algorithm namespace.
848 */
849 var C_algo = C.algo = {};
850
851 return C;
852 }(Math));
853
854
855 return CryptoJS;
856
857}));
858
859/***/ }),
860/* 1 */
861/***/ (function(module, exports, __webpack_require__) {
862
863"use strict";
864/* WEBPACK VAR INJECTION */(function(global) {/*!
865 * The buffer module from node.js, for the browser.
866 *
867 * @author Feross Aboukhadijeh <http://feross.org>
868 * @license MIT
869 */
870/* eslint-disable no-proto */
871
872
873
874var base64 = __webpack_require__(21)
875var ieee754 = __webpack_require__(22)
876var isArray = __webpack_require__(23)
877
878exports.Buffer = Buffer
879exports.SlowBuffer = SlowBuffer
880exports.INSPECT_MAX_BYTES = 50
881
882/**
883 * If `Buffer.TYPED_ARRAY_SUPPORT`:
884 * === true Use Uint8Array implementation (fastest)
885 * === false Use Object implementation (most compatible, even IE6)
886 *
887 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
888 * Opera 11.6+, iOS 4.2+.
889 *
890 * Due to various browser bugs, sometimes the Object implementation will be used even
891 * when the browser supports typed arrays.
892 *
893 * Note:
894 *
895 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
896 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
897 *
898 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
899 *
900 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
901 * incorrect length in some situations.
902
903 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
904 * get the Object implementation, which is slower but behaves correctly.
905 */
906Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
907 ? global.TYPED_ARRAY_SUPPORT
908 : typedArraySupport()
909
910/*
911 * Export kMaxLength after typed array support is determined.
912 */
913exports.kMaxLength = kMaxLength()
914
915function typedArraySupport () {
916 try {
917 var arr = new Uint8Array(1)
918 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
919 return arr.foo() === 42 && // typed array instances can be augmented
920 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
921 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
922 } catch (e) {
923 return false
924 }
925}
926
927function kMaxLength () {
928 return Buffer.TYPED_ARRAY_SUPPORT
929 ? 0x7fffffff
930 : 0x3fffffff
931}
932
933function createBuffer (that, length) {
934 if (kMaxLength() < length) {
935 throw new RangeError('Invalid typed array length')
936 }
937 if (Buffer.TYPED_ARRAY_SUPPORT) {
938 // Return an augmented `Uint8Array` instance, for best performance
939 that = new Uint8Array(length)
940 that.__proto__ = Buffer.prototype
941 } else {
942 // Fallback: Return an object instance of the Buffer class
943 if (that === null) {
944 that = new Buffer(length)
945 }
946 that.length = length
947 }
948
949 return that
950}
951
952/**
953 * The Buffer constructor returns instances of `Uint8Array` that have their
954 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
955 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
956 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
957 * returns a single octet.
958 *
959 * The `Uint8Array` prototype remains unmodified.
960 */
961
962function Buffer (arg, encodingOrOffset, length) {
963 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
964 return new Buffer(arg, encodingOrOffset, length)
965 }
966
967 // Common case.
968 if (typeof arg === 'number') {
969 if (typeof encodingOrOffset === 'string') {
970 throw new Error(
971 'If encoding is specified then the first argument must be a string'
972 )
973 }
974 return allocUnsafe(this, arg)
975 }
976 return from(this, arg, encodingOrOffset, length)
977}
978
979Buffer.poolSize = 8192 // not used by this implementation
980
981// TODO: Legacy, not needed anymore. Remove in next major version.
982Buffer._augment = function (arr) {
983 arr.__proto__ = Buffer.prototype
984 return arr
985}
986
987function from (that, value, encodingOrOffset, length) {
988 if (typeof value === 'number') {
989 throw new TypeError('"value" argument must not be a number')
990 }
991
992 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
993 return fromArrayBuffer(that, value, encodingOrOffset, length)
994 }
995
996 if (typeof value === 'string') {
997 return fromString(that, value, encodingOrOffset)
998 }
999
1000 return fromObject(that, value)
1001}
1002
1003/**
1004 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1005 * if value is a number.
1006 * Buffer.from(str[, encoding])
1007 * Buffer.from(array)
1008 * Buffer.from(buffer)
1009 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1010 **/
1011Buffer.from = function (value, encodingOrOffset, length) {
1012 return from(null, value, encodingOrOffset, length)
1013}
1014
1015if (Buffer.TYPED_ARRAY_SUPPORT) {
1016 Buffer.prototype.__proto__ = Uint8Array.prototype
1017 Buffer.__proto__ = Uint8Array
1018 if (typeof Symbol !== 'undefined' && Symbol.species &&
1019 Buffer[Symbol.species] === Buffer) {
1020 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
1021 Object.defineProperty(Buffer, Symbol.species, {
1022 value: null,
1023 configurable: true
1024 })
1025 }
1026}
1027
1028function assertSize (size) {
1029 if (typeof size !== 'number') {
1030 throw new TypeError('"size" argument must be a number')
1031 } else if (size < 0) {
1032 throw new RangeError('"size" argument must not be negative')
1033 }
1034}
1035
1036function alloc (that, size, fill, encoding) {
1037 assertSize(size)
1038 if (size <= 0) {
1039 return createBuffer(that, size)
1040 }
1041 if (fill !== undefined) {
1042 // Only pay attention to encoding if it's a string. This
1043 // prevents accidentally sending in a number that would
1044 // be interpretted as a start offset.
1045 return typeof encoding === 'string'
1046 ? createBuffer(that, size).fill(fill, encoding)
1047 : createBuffer(that, size).fill(fill)
1048 }
1049 return createBuffer(that, size)
1050}
1051
1052/**
1053 * Creates a new filled Buffer instance.
1054 * alloc(size[, fill[, encoding]])
1055 **/
1056Buffer.alloc = function (size, fill, encoding) {
1057 return alloc(null, size, fill, encoding)
1058}
1059
1060function allocUnsafe (that, size) {
1061 assertSize(size)
1062 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
1063 if (!Buffer.TYPED_ARRAY_SUPPORT) {
1064 for (var i = 0; i < size; ++i) {
1065 that[i] = 0
1066 }
1067 }
1068 return that
1069}
1070
1071/**
1072 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
1073 * */
1074Buffer.allocUnsafe = function (size) {
1075 return allocUnsafe(null, size)
1076}
1077/**
1078 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
1079 */
1080Buffer.allocUnsafeSlow = function (size) {
1081 return allocUnsafe(null, size)
1082}
1083
1084function fromString (that, string, encoding) {
1085 if (typeof encoding !== 'string' || encoding === '') {
1086 encoding = 'utf8'
1087 }
1088
1089 if (!Buffer.isEncoding(encoding)) {
1090 throw new TypeError('"encoding" must be a valid string encoding')
1091 }
1092
1093 var length = byteLength(string, encoding) | 0
1094 that = createBuffer(that, length)
1095
1096 var actual = that.write(string, encoding)
1097
1098 if (actual !== length) {
1099 // Writing a hex string, for example, that contains invalid characters will
1100 // cause everything after the first invalid character to be ignored. (e.g.
1101 // 'abxxcd' will be treated as 'ab')
1102 that = that.slice(0, actual)
1103 }
1104
1105 return that
1106}
1107
1108function fromArrayLike (that, array) {
1109 var length = array.length < 0 ? 0 : checked(array.length) | 0
1110 that = createBuffer(that, length)
1111 for (var i = 0; i < length; i += 1) {
1112 that[i] = array[i] & 255
1113 }
1114 return that
1115}
1116
1117function fromArrayBuffer (that, array, byteOffset, length) {
1118 array.byteLength // this throws if `array` is not a valid ArrayBuffer
1119
1120 if (byteOffset < 0 || array.byteLength < byteOffset) {
1121 throw new RangeError('\'offset\' is out of bounds')
1122 }
1123
1124 if (array.byteLength < byteOffset + (length || 0)) {
1125 throw new RangeError('\'length\' is out of bounds')
1126 }
1127
1128 if (byteOffset === undefined && length === undefined) {
1129 array = new Uint8Array(array)
1130 } else if (length === undefined) {
1131 array = new Uint8Array(array, byteOffset)
1132 } else {
1133 array = new Uint8Array(array, byteOffset, length)
1134 }
1135
1136 if (Buffer.TYPED_ARRAY_SUPPORT) {
1137 // Return an augmented `Uint8Array` instance, for best performance
1138 that = array
1139 that.__proto__ = Buffer.prototype
1140 } else {
1141 // Fallback: Return an object instance of the Buffer class
1142 that = fromArrayLike(that, array)
1143 }
1144 return that
1145}
1146
1147function fromObject (that, obj) {
1148 if (Buffer.isBuffer(obj)) {
1149 var len = checked(obj.length) | 0
1150 that = createBuffer(that, len)
1151
1152 if (that.length === 0) {
1153 return that
1154 }
1155
1156 obj.copy(that, 0, 0, len)
1157 return that
1158 }
1159
1160 if (obj) {
1161 if ((typeof ArrayBuffer !== 'undefined' &&
1162 obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
1163 if (typeof obj.length !== 'number' || isnan(obj.length)) {
1164 return createBuffer(that, 0)
1165 }
1166 return fromArrayLike(that, obj)
1167 }
1168
1169 if (obj.type === 'Buffer' && isArray(obj.data)) {
1170 return fromArrayLike(that, obj.data)
1171 }
1172 }
1173
1174 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
1175}
1176
1177function checked (length) {
1178 // Note: cannot use `length < kMaxLength()` here because that fails when
1179 // length is NaN (which is otherwise coerced to zero.)
1180 if (length >= kMaxLength()) {
1181 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1182 'size: 0x' + kMaxLength().toString(16) + ' bytes')
1183 }
1184 return length | 0
1185}
1186
1187function SlowBuffer (length) {
1188 if (+length != length) { // eslint-disable-line eqeqeq
1189 length = 0
1190 }
1191 return Buffer.alloc(+length)
1192}
1193
1194Buffer.isBuffer = function isBuffer (b) {
1195 return !!(b != null && b._isBuffer)
1196}
1197
1198Buffer.compare = function compare (a, b) {
1199 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1200 throw new TypeError('Arguments must be Buffers')
1201 }
1202
1203 if (a === b) return 0
1204
1205 var x = a.length
1206 var y = b.length
1207
1208 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1209 if (a[i] !== b[i]) {
1210 x = a[i]
1211 y = b[i]
1212 break
1213 }
1214 }
1215
1216 if (x < y) return -1
1217 if (y < x) return 1
1218 return 0
1219}
1220
1221Buffer.isEncoding = function isEncoding (encoding) {
1222 switch (String(encoding).toLowerCase()) {
1223 case 'hex':
1224 case 'utf8':
1225 case 'utf-8':
1226 case 'ascii':
1227 case 'latin1':
1228 case 'binary':
1229 case 'base64':
1230 case 'ucs2':
1231 case 'ucs-2':
1232 case 'utf16le':
1233 case 'utf-16le':
1234 return true
1235 default:
1236 return false
1237 }
1238}
1239
1240Buffer.concat = function concat (list, length) {
1241 if (!isArray(list)) {
1242 throw new TypeError('"list" argument must be an Array of Buffers')
1243 }
1244
1245 if (list.length === 0) {
1246 return Buffer.alloc(0)
1247 }
1248
1249 var i
1250 if (length === undefined) {
1251 length = 0
1252 for (i = 0; i < list.length; ++i) {
1253 length += list[i].length
1254 }
1255 }
1256
1257 var buffer = Buffer.allocUnsafe(length)
1258 var pos = 0
1259 for (i = 0; i < list.length; ++i) {
1260 var buf = list[i]
1261 if (!Buffer.isBuffer(buf)) {
1262 throw new TypeError('"list" argument must be an Array of Buffers')
1263 }
1264 buf.copy(buffer, pos)
1265 pos += buf.length
1266 }
1267 return buffer
1268}
1269
1270function byteLength (string, encoding) {
1271 if (Buffer.isBuffer(string)) {
1272 return string.length
1273 }
1274 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
1275 (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
1276 return string.byteLength
1277 }
1278 if (typeof string !== 'string') {
1279 string = '' + string
1280 }
1281
1282 var len = string.length
1283 if (len === 0) return 0
1284
1285 // Use a for loop to avoid recursion
1286 var loweredCase = false
1287 for (;;) {
1288 switch (encoding) {
1289 case 'ascii':
1290 case 'latin1':
1291 case 'binary':
1292 return len
1293 case 'utf8':
1294 case 'utf-8':
1295 case undefined:
1296 return utf8ToBytes(string).length
1297 case 'ucs2':
1298 case 'ucs-2':
1299 case 'utf16le':
1300 case 'utf-16le':
1301 return len * 2
1302 case 'hex':
1303 return len >>> 1
1304 case 'base64':
1305 return base64ToBytes(string).length
1306 default:
1307 if (loweredCase) return utf8ToBytes(string).length // assume utf8
1308 encoding = ('' + encoding).toLowerCase()
1309 loweredCase = true
1310 }
1311 }
1312}
1313Buffer.byteLength = byteLength
1314
1315function slowToString (encoding, start, end) {
1316 var loweredCase = false
1317
1318 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1319 // property of a typed array.
1320
1321 // This behaves neither like String nor Uint8Array in that we set start/end
1322 // to their upper/lower bounds if the value passed is out of range.
1323 // undefined is handled specially as per ECMA-262 6th Edition,
1324 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1325 if (start === undefined || start < 0) {
1326 start = 0
1327 }
1328 // Return early if start > this.length. Done here to prevent potential uint32
1329 // coercion fail below.
1330 if (start > this.length) {
1331 return ''
1332 }
1333
1334 if (end === undefined || end > this.length) {
1335 end = this.length
1336 }
1337
1338 if (end <= 0) {
1339 return ''
1340 }
1341
1342 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1343 end >>>= 0
1344 start >>>= 0
1345
1346 if (end <= start) {
1347 return ''
1348 }
1349
1350 if (!encoding) encoding = 'utf8'
1351
1352 while (true) {
1353 switch (encoding) {
1354 case 'hex':
1355 return hexSlice(this, start, end)
1356
1357 case 'utf8':
1358 case 'utf-8':
1359 return utf8Slice(this, start, end)
1360
1361 case 'ascii':
1362 return asciiSlice(this, start, end)
1363
1364 case 'latin1':
1365 case 'binary':
1366 return latin1Slice(this, start, end)
1367
1368 case 'base64':
1369 return base64Slice(this, start, end)
1370
1371 case 'ucs2':
1372 case 'ucs-2':
1373 case 'utf16le':
1374 case 'utf-16le':
1375 return utf16leSlice(this, start, end)
1376
1377 default:
1378 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1379 encoding = (encoding + '').toLowerCase()
1380 loweredCase = true
1381 }
1382 }
1383}
1384
1385// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
1386// Buffer instances.
1387Buffer.prototype._isBuffer = true
1388
1389function swap (b, n, m) {
1390 var i = b[n]
1391 b[n] = b[m]
1392 b[m] = i
1393}
1394
1395Buffer.prototype.swap16 = function swap16 () {
1396 var len = this.length
1397 if (len % 2 !== 0) {
1398 throw new RangeError('Buffer size must be a multiple of 16-bits')
1399 }
1400 for (var i = 0; i < len; i += 2) {
1401 swap(this, i, i + 1)
1402 }
1403 return this
1404}
1405
1406Buffer.prototype.swap32 = function swap32 () {
1407 var len = this.length
1408 if (len % 4 !== 0) {
1409 throw new RangeError('Buffer size must be a multiple of 32-bits')
1410 }
1411 for (var i = 0; i < len; i += 4) {
1412 swap(this, i, i + 3)
1413 swap(this, i + 1, i + 2)
1414 }
1415 return this
1416}
1417
1418Buffer.prototype.swap64 = function swap64 () {
1419 var len = this.length
1420 if (len % 8 !== 0) {
1421 throw new RangeError('Buffer size must be a multiple of 64-bits')
1422 }
1423 for (var i = 0; i < len; i += 8) {
1424 swap(this, i, i + 7)
1425 swap(this, i + 1, i + 6)
1426 swap(this, i + 2, i + 5)
1427 swap(this, i + 3, i + 4)
1428 }
1429 return this
1430}
1431
1432Buffer.prototype.toString = function toString () {
1433 var length = this.length | 0
1434 if (length === 0) return ''
1435 if (arguments.length === 0) return utf8Slice(this, 0, length)
1436 return slowToString.apply(this, arguments)
1437}
1438
1439Buffer.prototype.equals = function equals (b) {
1440 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1441 if (this === b) return true
1442 return Buffer.compare(this, b) === 0
1443}
1444
1445Buffer.prototype.inspect = function inspect () {
1446 var str = ''
1447 var max = exports.INSPECT_MAX_BYTES
1448 if (this.length > 0) {
1449 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1450 if (this.length > max) str += ' ... '
1451 }
1452 return '<Buffer ' + str + '>'
1453}
1454
1455Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1456 if (!Buffer.isBuffer(target)) {
1457 throw new TypeError('Argument must be a Buffer')
1458 }
1459
1460 if (start === undefined) {
1461 start = 0
1462 }
1463 if (end === undefined) {
1464 end = target ? target.length : 0
1465 }
1466 if (thisStart === undefined) {
1467 thisStart = 0
1468 }
1469 if (thisEnd === undefined) {
1470 thisEnd = this.length
1471 }
1472
1473 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1474 throw new RangeError('out of range index')
1475 }
1476
1477 if (thisStart >= thisEnd && start >= end) {
1478 return 0
1479 }
1480 if (thisStart >= thisEnd) {
1481 return -1
1482 }
1483 if (start >= end) {
1484 return 1
1485 }
1486
1487 start >>>= 0
1488 end >>>= 0
1489 thisStart >>>= 0
1490 thisEnd >>>= 0
1491
1492 if (this === target) return 0
1493
1494 var x = thisEnd - thisStart
1495 var y = end - start
1496 var len = Math.min(x, y)
1497
1498 var thisCopy = this.slice(thisStart, thisEnd)
1499 var targetCopy = target.slice(start, end)
1500
1501 for (var i = 0; i < len; ++i) {
1502 if (thisCopy[i] !== targetCopy[i]) {
1503 x = thisCopy[i]
1504 y = targetCopy[i]
1505 break
1506 }
1507 }
1508
1509 if (x < y) return -1
1510 if (y < x) return 1
1511 return 0
1512}
1513
1514// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1515// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1516//
1517// Arguments:
1518// - buffer - a Buffer to search
1519// - val - a string, Buffer, or number
1520// - byteOffset - an index into `buffer`; will be clamped to an int32
1521// - encoding - an optional encoding, relevant is val is a string
1522// - dir - true for indexOf, false for lastIndexOf
1523function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1524 // Empty buffer means no match
1525 if (buffer.length === 0) return -1
1526
1527 // Normalize byteOffset
1528 if (typeof byteOffset === 'string') {
1529 encoding = byteOffset
1530 byteOffset = 0
1531 } else if (byteOffset > 0x7fffffff) {
1532 byteOffset = 0x7fffffff
1533 } else if (byteOffset < -0x80000000) {
1534 byteOffset = -0x80000000
1535 }
1536 byteOffset = +byteOffset // Coerce to Number.
1537 if (isNaN(byteOffset)) {
1538 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1539 byteOffset = dir ? 0 : (buffer.length - 1)
1540 }
1541
1542 // Normalize byteOffset: negative offsets start from the end of the buffer
1543 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1544 if (byteOffset >= buffer.length) {
1545 if (dir) return -1
1546 else byteOffset = buffer.length - 1
1547 } else if (byteOffset < 0) {
1548 if (dir) byteOffset = 0
1549 else return -1
1550 }
1551
1552 // Normalize val
1553 if (typeof val === 'string') {
1554 val = Buffer.from(val, encoding)
1555 }
1556
1557 // Finally, search either indexOf (if dir is true) or lastIndexOf
1558 if (Buffer.isBuffer(val)) {
1559 // Special case: looking for empty string/buffer always fails
1560 if (val.length === 0) {
1561 return -1
1562 }
1563 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1564 } else if (typeof val === 'number') {
1565 val = val & 0xFF // Search for a byte value [0-255]
1566 if (Buffer.TYPED_ARRAY_SUPPORT &&
1567 typeof Uint8Array.prototype.indexOf === 'function') {
1568 if (dir) {
1569 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1570 } else {
1571 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1572 }
1573 }
1574 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1575 }
1576
1577 throw new TypeError('val must be string, number or Buffer')
1578}
1579
1580function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1581 var indexSize = 1
1582 var arrLength = arr.length
1583 var valLength = val.length
1584
1585 if (encoding !== undefined) {
1586 encoding = String(encoding).toLowerCase()
1587 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1588 encoding === 'utf16le' || encoding === 'utf-16le') {
1589 if (arr.length < 2 || val.length < 2) {
1590 return -1
1591 }
1592 indexSize = 2
1593 arrLength /= 2
1594 valLength /= 2
1595 byteOffset /= 2
1596 }
1597 }
1598
1599 function read (buf, i) {
1600 if (indexSize === 1) {
1601 return buf[i]
1602 } else {
1603 return buf.readUInt16BE(i * indexSize)
1604 }
1605 }
1606
1607 var i
1608 if (dir) {
1609 var foundIndex = -1
1610 for (i = byteOffset; i < arrLength; i++) {
1611 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1612 if (foundIndex === -1) foundIndex = i
1613 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1614 } else {
1615 if (foundIndex !== -1) i -= i - foundIndex
1616 foundIndex = -1
1617 }
1618 }
1619 } else {
1620 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1621 for (i = byteOffset; i >= 0; i--) {
1622 var found = true
1623 for (var j = 0; j < valLength; j++) {
1624 if (read(arr, i + j) !== read(val, j)) {
1625 found = false
1626 break
1627 }
1628 }
1629 if (found) return i
1630 }
1631 }
1632
1633 return -1
1634}
1635
1636Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1637 return this.indexOf(val, byteOffset, encoding) !== -1
1638}
1639
1640Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1641 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1642}
1643
1644Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1645 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1646}
1647
1648function hexWrite (buf, string, offset, length) {
1649 offset = Number(offset) || 0
1650 var remaining = buf.length - offset
1651 if (!length) {
1652 length = remaining
1653 } else {
1654 length = Number(length)
1655 if (length > remaining) {
1656 length = remaining
1657 }
1658 }
1659
1660 // must be an even number of digits
1661 var strLen = string.length
1662 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1663
1664 if (length > strLen / 2) {
1665 length = strLen / 2
1666 }
1667 for (var i = 0; i < length; ++i) {
1668 var parsed = parseInt(string.substr(i * 2, 2), 16)
1669 if (isNaN(parsed)) return i
1670 buf[offset + i] = parsed
1671 }
1672 return i
1673}
1674
1675function utf8Write (buf, string, offset, length) {
1676 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1677}
1678
1679function asciiWrite (buf, string, offset, length) {
1680 return blitBuffer(asciiToBytes(string), buf, offset, length)
1681}
1682
1683function latin1Write (buf, string, offset, length) {
1684 return asciiWrite(buf, string, offset, length)
1685}
1686
1687function base64Write (buf, string, offset, length) {
1688 return blitBuffer(base64ToBytes(string), buf, offset, length)
1689}
1690
1691function ucs2Write (buf, string, offset, length) {
1692 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1693}
1694
1695Buffer.prototype.write = function write (string, offset, length, encoding) {
1696 // Buffer#write(string)
1697 if (offset === undefined) {
1698 encoding = 'utf8'
1699 length = this.length
1700 offset = 0
1701 // Buffer#write(string, encoding)
1702 } else if (length === undefined && typeof offset === 'string') {
1703 encoding = offset
1704 length = this.length
1705 offset = 0
1706 // Buffer#write(string, offset[, length][, encoding])
1707 } else if (isFinite(offset)) {
1708 offset = offset | 0
1709 if (isFinite(length)) {
1710 length = length | 0
1711 if (encoding === undefined) encoding = 'utf8'
1712 } else {
1713 encoding = length
1714 length = undefined
1715 }
1716 // legacy write(string, encoding, offset, length) - remove in v0.13
1717 } else {
1718 throw new Error(
1719 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1720 )
1721 }
1722
1723 var remaining = this.length - offset
1724 if (length === undefined || length > remaining) length = remaining
1725
1726 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1727 throw new RangeError('Attempt to write outside buffer bounds')
1728 }
1729
1730 if (!encoding) encoding = 'utf8'
1731
1732 var loweredCase = false
1733 for (;;) {
1734 switch (encoding) {
1735 case 'hex':
1736 return hexWrite(this, string, offset, length)
1737
1738 case 'utf8':
1739 case 'utf-8':
1740 return utf8Write(this, string, offset, length)
1741
1742 case 'ascii':
1743 return asciiWrite(this, string, offset, length)
1744
1745 case 'latin1':
1746 case 'binary':
1747 return latin1Write(this, string, offset, length)
1748
1749 case 'base64':
1750 // Warning: maxLength not taken into account in base64Write
1751 return base64Write(this, string, offset, length)
1752
1753 case 'ucs2':
1754 case 'ucs-2':
1755 case 'utf16le':
1756 case 'utf-16le':
1757 return ucs2Write(this, string, offset, length)
1758
1759 default:
1760 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1761 encoding = ('' + encoding).toLowerCase()
1762 loweredCase = true
1763 }
1764 }
1765}
1766
1767Buffer.prototype.toJSON = function toJSON () {
1768 return {
1769 type: 'Buffer',
1770 data: Array.prototype.slice.call(this._arr || this, 0)
1771 }
1772}
1773
1774function base64Slice (buf, start, end) {
1775 if (start === 0 && end === buf.length) {
1776 return base64.fromByteArray(buf)
1777 } else {
1778 return base64.fromByteArray(buf.slice(start, end))
1779 }
1780}
1781
1782function utf8Slice (buf, start, end) {
1783 end = Math.min(buf.length, end)
1784 var res = []
1785
1786 var i = start
1787 while (i < end) {
1788 var firstByte = buf[i]
1789 var codePoint = null
1790 var bytesPerSequence = (firstByte > 0xEF) ? 4
1791 : (firstByte > 0xDF) ? 3
1792 : (firstByte > 0xBF) ? 2
1793 : 1
1794
1795 if (i + bytesPerSequence <= end) {
1796 var secondByte, thirdByte, fourthByte, tempCodePoint
1797
1798 switch (bytesPerSequence) {
1799 case 1:
1800 if (firstByte < 0x80) {
1801 codePoint = firstByte
1802 }
1803 break
1804 case 2:
1805 secondByte = buf[i + 1]
1806 if ((secondByte & 0xC0) === 0x80) {
1807 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1808 if (tempCodePoint > 0x7F) {
1809 codePoint = tempCodePoint
1810 }
1811 }
1812 break
1813 case 3:
1814 secondByte = buf[i + 1]
1815 thirdByte = buf[i + 2]
1816 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1817 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1818 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1819 codePoint = tempCodePoint
1820 }
1821 }
1822 break
1823 case 4:
1824 secondByte = buf[i + 1]
1825 thirdByte = buf[i + 2]
1826 fourthByte = buf[i + 3]
1827 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1828 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1829 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1830 codePoint = tempCodePoint
1831 }
1832 }
1833 }
1834 }
1835
1836 if (codePoint === null) {
1837 // we did not generate a valid codePoint so insert a
1838 // replacement char (U+FFFD) and advance only 1 byte
1839 codePoint = 0xFFFD
1840 bytesPerSequence = 1
1841 } else if (codePoint > 0xFFFF) {
1842 // encode to utf16 (surrogate pair dance)
1843 codePoint -= 0x10000
1844 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1845 codePoint = 0xDC00 | codePoint & 0x3FF
1846 }
1847
1848 res.push(codePoint)
1849 i += bytesPerSequence
1850 }
1851
1852 return decodeCodePointsArray(res)
1853}
1854
1855// Based on http://stackoverflow.com/a/22747272/680742, the browser with
1856// the lowest limit is Chrome, with 0x10000 args.
1857// We go 1 magnitude less, for safety
1858var MAX_ARGUMENTS_LENGTH = 0x1000
1859
1860function decodeCodePointsArray (codePoints) {
1861 var len = codePoints.length
1862 if (len <= MAX_ARGUMENTS_LENGTH) {
1863 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1864 }
1865
1866 // Decode in chunks to avoid "call stack size exceeded".
1867 var res = ''
1868 var i = 0
1869 while (i < len) {
1870 res += String.fromCharCode.apply(
1871 String,
1872 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1873 )
1874 }
1875 return res
1876}
1877
1878function asciiSlice (buf, start, end) {
1879 var ret = ''
1880 end = Math.min(buf.length, end)
1881
1882 for (var i = start; i < end; ++i) {
1883 ret += String.fromCharCode(buf[i] & 0x7F)
1884 }
1885 return ret
1886}
1887
1888function latin1Slice (buf, start, end) {
1889 var ret = ''
1890 end = Math.min(buf.length, end)
1891
1892 for (var i = start; i < end; ++i) {
1893 ret += String.fromCharCode(buf[i])
1894 }
1895 return ret
1896}
1897
1898function hexSlice (buf, start, end) {
1899 var len = buf.length
1900
1901 if (!start || start < 0) start = 0
1902 if (!end || end < 0 || end > len) end = len
1903
1904 var out = ''
1905 for (var i = start; i < end; ++i) {
1906 out += toHex(buf[i])
1907 }
1908 return out
1909}
1910
1911function utf16leSlice (buf, start, end) {
1912 var bytes = buf.slice(start, end)
1913 var res = ''
1914 for (var i = 0; i < bytes.length; i += 2) {
1915 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
1916 }
1917 return res
1918}
1919
1920Buffer.prototype.slice = function slice (start, end) {
1921 var len = this.length
1922 start = ~~start
1923 end = end === undefined ? len : ~~end
1924
1925 if (start < 0) {
1926 start += len
1927 if (start < 0) start = 0
1928 } else if (start > len) {
1929 start = len
1930 }
1931
1932 if (end < 0) {
1933 end += len
1934 if (end < 0) end = 0
1935 } else if (end > len) {
1936 end = len
1937 }
1938
1939 if (end < start) end = start
1940
1941 var newBuf
1942 if (Buffer.TYPED_ARRAY_SUPPORT) {
1943 newBuf = this.subarray(start, end)
1944 newBuf.__proto__ = Buffer.prototype
1945 } else {
1946 var sliceLen = end - start
1947 newBuf = new Buffer(sliceLen, undefined)
1948 for (var i = 0; i < sliceLen; ++i) {
1949 newBuf[i] = this[i + start]
1950 }
1951 }
1952
1953 return newBuf
1954}
1955
1956/*
1957 * Need to make sure that buffer isn't trying to write out of bounds.
1958 */
1959function checkOffset (offset, ext, length) {
1960 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1961 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1962}
1963
1964Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1965 offset = offset | 0
1966 byteLength = byteLength | 0
1967 if (!noAssert) checkOffset(offset, byteLength, this.length)
1968
1969 var val = this[offset]
1970 var mul = 1
1971 var i = 0
1972 while (++i < byteLength && (mul *= 0x100)) {
1973 val += this[offset + i] * mul
1974 }
1975
1976 return val
1977}
1978
1979Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1980 offset = offset | 0
1981 byteLength = byteLength | 0
1982 if (!noAssert) {
1983 checkOffset(offset, byteLength, this.length)
1984 }
1985
1986 var val = this[offset + --byteLength]
1987 var mul = 1
1988 while (byteLength > 0 && (mul *= 0x100)) {
1989 val += this[offset + --byteLength] * mul
1990 }
1991
1992 return val
1993}
1994
1995Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1996 if (!noAssert) checkOffset(offset, 1, this.length)
1997 return this[offset]
1998}
1999
2000Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2001 if (!noAssert) checkOffset(offset, 2, this.length)
2002 return this[offset] | (this[offset + 1] << 8)
2003}
2004
2005Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2006 if (!noAssert) checkOffset(offset, 2, this.length)
2007 return (this[offset] << 8) | this[offset + 1]
2008}
2009
2010Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2011 if (!noAssert) checkOffset(offset, 4, this.length)
2012
2013 return ((this[offset]) |
2014 (this[offset + 1] << 8) |
2015 (this[offset + 2] << 16)) +
2016 (this[offset + 3] * 0x1000000)
2017}
2018
2019Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2020 if (!noAssert) checkOffset(offset, 4, this.length)
2021
2022 return (this[offset] * 0x1000000) +
2023 ((this[offset + 1] << 16) |
2024 (this[offset + 2] << 8) |
2025 this[offset + 3])
2026}
2027
2028Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2029 offset = offset | 0
2030 byteLength = byteLength | 0
2031 if (!noAssert) checkOffset(offset, byteLength, this.length)
2032
2033 var val = this[offset]
2034 var mul = 1
2035 var i = 0
2036 while (++i < byteLength && (mul *= 0x100)) {
2037 val += this[offset + i] * mul
2038 }
2039 mul *= 0x80
2040
2041 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2042
2043 return val
2044}
2045
2046Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2047 offset = offset | 0
2048 byteLength = byteLength | 0
2049 if (!noAssert) checkOffset(offset, byteLength, this.length)
2050
2051 var i = byteLength
2052 var mul = 1
2053 var val = this[offset + --i]
2054 while (i > 0 && (mul *= 0x100)) {
2055 val += this[offset + --i] * mul
2056 }
2057 mul *= 0x80
2058
2059 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2060
2061 return val
2062}
2063
2064Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2065 if (!noAssert) checkOffset(offset, 1, this.length)
2066 if (!(this[offset] & 0x80)) return (this[offset])
2067 return ((0xff - this[offset] + 1) * -1)
2068}
2069
2070Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2071 if (!noAssert) checkOffset(offset, 2, this.length)
2072 var val = this[offset] | (this[offset + 1] << 8)
2073 return (val & 0x8000) ? val | 0xFFFF0000 : val
2074}
2075
2076Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2077 if (!noAssert) checkOffset(offset, 2, this.length)
2078 var val = this[offset + 1] | (this[offset] << 8)
2079 return (val & 0x8000) ? val | 0xFFFF0000 : val
2080}
2081
2082Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2083 if (!noAssert) checkOffset(offset, 4, this.length)
2084
2085 return (this[offset]) |
2086 (this[offset + 1] << 8) |
2087 (this[offset + 2] << 16) |
2088 (this[offset + 3] << 24)
2089}
2090
2091Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2092 if (!noAssert) checkOffset(offset, 4, this.length)
2093
2094 return (this[offset] << 24) |
2095 (this[offset + 1] << 16) |
2096 (this[offset + 2] << 8) |
2097 (this[offset + 3])
2098}
2099
2100Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2101 if (!noAssert) checkOffset(offset, 4, this.length)
2102 return ieee754.read(this, offset, true, 23, 4)
2103}
2104
2105Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2106 if (!noAssert) checkOffset(offset, 4, this.length)
2107 return ieee754.read(this, offset, false, 23, 4)
2108}
2109
2110Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2111 if (!noAssert) checkOffset(offset, 8, this.length)
2112 return ieee754.read(this, offset, true, 52, 8)
2113}
2114
2115Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2116 if (!noAssert) checkOffset(offset, 8, this.length)
2117 return ieee754.read(this, offset, false, 52, 8)
2118}
2119
2120function checkInt (buf, value, offset, ext, max, min) {
2121 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
2122 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
2123 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2124}
2125
2126Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2127 value = +value
2128 offset = offset | 0
2129 byteLength = byteLength | 0
2130 if (!noAssert) {
2131 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2132 checkInt(this, value, offset, byteLength, maxBytes, 0)
2133 }
2134
2135 var mul = 1
2136 var i = 0
2137 this[offset] = value & 0xFF
2138 while (++i < byteLength && (mul *= 0x100)) {
2139 this[offset + i] = (value / mul) & 0xFF
2140 }
2141
2142 return offset + byteLength
2143}
2144
2145Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2146 value = +value
2147 offset = offset | 0
2148 byteLength = byteLength | 0
2149 if (!noAssert) {
2150 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2151 checkInt(this, value, offset, byteLength, maxBytes, 0)
2152 }
2153
2154 var i = byteLength - 1
2155 var mul = 1
2156 this[offset + i] = value & 0xFF
2157 while (--i >= 0 && (mul *= 0x100)) {
2158 this[offset + i] = (value / mul) & 0xFF
2159 }
2160
2161 return offset + byteLength
2162}
2163
2164Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2165 value = +value
2166 offset = offset | 0
2167 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2168 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
2169 this[offset] = (value & 0xff)
2170 return offset + 1
2171}
2172
2173function objectWriteUInt16 (buf, value, offset, littleEndian) {
2174 if (value < 0) value = 0xffff + value + 1
2175 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
2176 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
2177 (littleEndian ? i : 1 - i) * 8
2178 }
2179}
2180
2181Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2182 value = +value
2183 offset = offset | 0
2184 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2185 if (Buffer.TYPED_ARRAY_SUPPORT) {
2186 this[offset] = (value & 0xff)
2187 this[offset + 1] = (value >>> 8)
2188 } else {
2189 objectWriteUInt16(this, value, offset, true)
2190 }
2191 return offset + 2
2192}
2193
2194Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2195 value = +value
2196 offset = offset | 0
2197 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2198 if (Buffer.TYPED_ARRAY_SUPPORT) {
2199 this[offset] = (value >>> 8)
2200 this[offset + 1] = (value & 0xff)
2201 } else {
2202 objectWriteUInt16(this, value, offset, false)
2203 }
2204 return offset + 2
2205}
2206
2207function objectWriteUInt32 (buf, value, offset, littleEndian) {
2208 if (value < 0) value = 0xffffffff + value + 1
2209 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
2210 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
2211 }
2212}
2213
2214Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2215 value = +value
2216 offset = offset | 0
2217 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2218 if (Buffer.TYPED_ARRAY_SUPPORT) {
2219 this[offset + 3] = (value >>> 24)
2220 this[offset + 2] = (value >>> 16)
2221 this[offset + 1] = (value >>> 8)
2222 this[offset] = (value & 0xff)
2223 } else {
2224 objectWriteUInt32(this, value, offset, true)
2225 }
2226 return offset + 4
2227}
2228
2229Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2230 value = +value
2231 offset = offset | 0
2232 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2233 if (Buffer.TYPED_ARRAY_SUPPORT) {
2234 this[offset] = (value >>> 24)
2235 this[offset + 1] = (value >>> 16)
2236 this[offset + 2] = (value >>> 8)
2237 this[offset + 3] = (value & 0xff)
2238 } else {
2239 objectWriteUInt32(this, value, offset, false)
2240 }
2241 return offset + 4
2242}
2243
2244Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2245 value = +value
2246 offset = offset | 0
2247 if (!noAssert) {
2248 var limit = Math.pow(2, 8 * byteLength - 1)
2249
2250 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2251 }
2252
2253 var i = 0
2254 var mul = 1
2255 var sub = 0
2256 this[offset] = value & 0xFF
2257 while (++i < byteLength && (mul *= 0x100)) {
2258 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2259 sub = 1
2260 }
2261 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2262 }
2263
2264 return offset + byteLength
2265}
2266
2267Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2268 value = +value
2269 offset = offset | 0
2270 if (!noAssert) {
2271 var limit = Math.pow(2, 8 * byteLength - 1)
2272
2273 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2274 }
2275
2276 var i = byteLength - 1
2277 var mul = 1
2278 var sub = 0
2279 this[offset + i] = value & 0xFF
2280 while (--i >= 0 && (mul *= 0x100)) {
2281 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2282 sub = 1
2283 }
2284 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2285 }
2286
2287 return offset + byteLength
2288}
2289
2290Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2291 value = +value
2292 offset = offset | 0
2293 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2294 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
2295 if (value < 0) value = 0xff + value + 1
2296 this[offset] = (value & 0xff)
2297 return offset + 1
2298}
2299
2300Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2301 value = +value
2302 offset = offset | 0
2303 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2304 if (Buffer.TYPED_ARRAY_SUPPORT) {
2305 this[offset] = (value & 0xff)
2306 this[offset + 1] = (value >>> 8)
2307 } else {
2308 objectWriteUInt16(this, value, offset, true)
2309 }
2310 return offset + 2
2311}
2312
2313Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2314 value = +value
2315 offset = offset | 0
2316 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2317 if (Buffer.TYPED_ARRAY_SUPPORT) {
2318 this[offset] = (value >>> 8)
2319 this[offset + 1] = (value & 0xff)
2320 } else {
2321 objectWriteUInt16(this, value, offset, false)
2322 }
2323 return offset + 2
2324}
2325
2326Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2327 value = +value
2328 offset = offset | 0
2329 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2330 if (Buffer.TYPED_ARRAY_SUPPORT) {
2331 this[offset] = (value & 0xff)
2332 this[offset + 1] = (value >>> 8)
2333 this[offset + 2] = (value >>> 16)
2334 this[offset + 3] = (value >>> 24)
2335 } else {
2336 objectWriteUInt32(this, value, offset, true)
2337 }
2338 return offset + 4
2339}
2340
2341Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2342 value = +value
2343 offset = offset | 0
2344 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2345 if (value < 0) value = 0xffffffff + value + 1
2346 if (Buffer.TYPED_ARRAY_SUPPORT) {
2347 this[offset] = (value >>> 24)
2348 this[offset + 1] = (value >>> 16)
2349 this[offset + 2] = (value >>> 8)
2350 this[offset + 3] = (value & 0xff)
2351 } else {
2352 objectWriteUInt32(this, value, offset, false)
2353 }
2354 return offset + 4
2355}
2356
2357function checkIEEE754 (buf, value, offset, ext, max, min) {
2358 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2359 if (offset < 0) throw new RangeError('Index out of range')
2360}
2361
2362function writeFloat (buf, value, offset, littleEndian, noAssert) {
2363 if (!noAssert) {
2364 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2365 }
2366 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2367 return offset + 4
2368}
2369
2370Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2371 return writeFloat(this, value, offset, true, noAssert)
2372}
2373
2374Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2375 return writeFloat(this, value, offset, false, noAssert)
2376}
2377
2378function writeDouble (buf, value, offset, littleEndian, noAssert) {
2379 if (!noAssert) {
2380 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2381 }
2382 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2383 return offset + 8
2384}
2385
2386Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2387 return writeDouble(this, value, offset, true, noAssert)
2388}
2389
2390Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2391 return writeDouble(this, value, offset, false, noAssert)
2392}
2393
2394// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2395Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2396 if (!start) start = 0
2397 if (!end && end !== 0) end = this.length
2398 if (targetStart >= target.length) targetStart = target.length
2399 if (!targetStart) targetStart = 0
2400 if (end > 0 && end < start) end = start
2401
2402 // Copy 0 bytes; we're done
2403 if (end === start) return 0
2404 if (target.length === 0 || this.length === 0) return 0
2405
2406 // Fatal error conditions
2407 if (targetStart < 0) {
2408 throw new RangeError('targetStart out of bounds')
2409 }
2410 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2411 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2412
2413 // Are we oob?
2414 if (end > this.length) end = this.length
2415 if (target.length - targetStart < end - start) {
2416 end = target.length - targetStart + start
2417 }
2418
2419 var len = end - start
2420 var i
2421
2422 if (this === target && start < targetStart && targetStart < end) {
2423 // descending copy from end
2424 for (i = len - 1; i >= 0; --i) {
2425 target[i + targetStart] = this[i + start]
2426 }
2427 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
2428 // ascending copy from start
2429 for (i = 0; i < len; ++i) {
2430 target[i + targetStart] = this[i + start]
2431 }
2432 } else {
2433 Uint8Array.prototype.set.call(
2434 target,
2435 this.subarray(start, start + len),
2436 targetStart
2437 )
2438 }
2439
2440 return len
2441}
2442
2443// Usage:
2444// buffer.fill(number[, offset[, end]])
2445// buffer.fill(buffer[, offset[, end]])
2446// buffer.fill(string[, offset[, end]][, encoding])
2447Buffer.prototype.fill = function fill (val, start, end, encoding) {
2448 // Handle string cases:
2449 if (typeof val === 'string') {
2450 if (typeof start === 'string') {
2451 encoding = start
2452 start = 0
2453 end = this.length
2454 } else if (typeof end === 'string') {
2455 encoding = end
2456 end = this.length
2457 }
2458 if (val.length === 1) {
2459 var code = val.charCodeAt(0)
2460 if (code < 256) {
2461 val = code
2462 }
2463 }
2464 if (encoding !== undefined && typeof encoding !== 'string') {
2465 throw new TypeError('encoding must be a string')
2466 }
2467 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2468 throw new TypeError('Unknown encoding: ' + encoding)
2469 }
2470 } else if (typeof val === 'number') {
2471 val = val & 255
2472 }
2473
2474 // Invalid ranges are not set to a default, so can range check early.
2475 if (start < 0 || this.length < start || this.length < end) {
2476 throw new RangeError('Out of range index')
2477 }
2478
2479 if (end <= start) {
2480 return this
2481 }
2482
2483 start = start >>> 0
2484 end = end === undefined ? this.length : end >>> 0
2485
2486 if (!val) val = 0
2487
2488 var i
2489 if (typeof val === 'number') {
2490 for (i = start; i < end; ++i) {
2491 this[i] = val
2492 }
2493 } else {
2494 var bytes = Buffer.isBuffer(val)
2495 ? val
2496 : utf8ToBytes(new Buffer(val, encoding).toString())
2497 var len = bytes.length
2498 for (i = 0; i < end - start; ++i) {
2499 this[i + start] = bytes[i % len]
2500 }
2501 }
2502
2503 return this
2504}
2505
2506// HELPER FUNCTIONS
2507// ================
2508
2509var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
2510
2511function base64clean (str) {
2512 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2513 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
2514 // Node converts strings with length < 2 to ''
2515 if (str.length < 2) return ''
2516 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2517 while (str.length % 4 !== 0) {
2518 str = str + '='
2519 }
2520 return str
2521}
2522
2523function stringtrim (str) {
2524 if (str.trim) return str.trim()
2525 return str.replace(/^\s+|\s+$/g, '')
2526}
2527
2528function toHex (n) {
2529 if (n < 16) return '0' + n.toString(16)
2530 return n.toString(16)
2531}
2532
2533function utf8ToBytes (string, units) {
2534 units = units || Infinity
2535 var codePoint
2536 var length = string.length
2537 var leadSurrogate = null
2538 var bytes = []
2539
2540 for (var i = 0; i < length; ++i) {
2541 codePoint = string.charCodeAt(i)
2542
2543 // is surrogate component
2544 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2545 // last char was a lead
2546 if (!leadSurrogate) {
2547 // no lead yet
2548 if (codePoint > 0xDBFF) {
2549 // unexpected trail
2550 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2551 continue
2552 } else if (i + 1 === length) {
2553 // unpaired lead
2554 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2555 continue
2556 }
2557
2558 // valid lead
2559 leadSurrogate = codePoint
2560
2561 continue
2562 }
2563
2564 // 2 leads in a row
2565 if (codePoint < 0xDC00) {
2566 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2567 leadSurrogate = codePoint
2568 continue
2569 }
2570
2571 // valid surrogate pair
2572 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2573 } else if (leadSurrogate) {
2574 // valid bmp char, but last char was a lead
2575 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2576 }
2577
2578 leadSurrogate = null
2579
2580 // encode utf8
2581 if (codePoint < 0x80) {
2582 if ((units -= 1) < 0) break
2583 bytes.push(codePoint)
2584 } else if (codePoint < 0x800) {
2585 if ((units -= 2) < 0) break
2586 bytes.push(
2587 codePoint >> 0x6 | 0xC0,
2588 codePoint & 0x3F | 0x80
2589 )
2590 } else if (codePoint < 0x10000) {
2591 if ((units -= 3) < 0) break
2592 bytes.push(
2593 codePoint >> 0xC | 0xE0,
2594 codePoint >> 0x6 & 0x3F | 0x80,
2595 codePoint & 0x3F | 0x80
2596 )
2597 } else if (codePoint < 0x110000) {
2598 if ((units -= 4) < 0) break
2599 bytes.push(
2600 codePoint >> 0x12 | 0xF0,
2601 codePoint >> 0xC & 0x3F | 0x80,
2602 codePoint >> 0x6 & 0x3F | 0x80,
2603 codePoint & 0x3F | 0x80
2604 )
2605 } else {
2606 throw new Error('Invalid code point')
2607 }
2608 }
2609
2610 return bytes
2611}
2612
2613function asciiToBytes (str) {
2614 var byteArray = []
2615 for (var i = 0; i < str.length; ++i) {
2616 // Node's code seems to be doing this and not & 0x7F..
2617 byteArray.push(str.charCodeAt(i) & 0xFF)
2618 }
2619 return byteArray
2620}
2621
2622function utf16leToBytes (str, units) {
2623 var c, hi, lo
2624 var byteArray = []
2625 for (var i = 0; i < str.length; ++i) {
2626 if ((units -= 2) < 0) break
2627
2628 c = str.charCodeAt(i)
2629 hi = c >> 8
2630 lo = c % 256
2631 byteArray.push(lo)
2632 byteArray.push(hi)
2633 }
2634
2635 return byteArray
2636}
2637
2638function base64ToBytes (str) {
2639 return base64.toByteArray(base64clean(str))
2640}
2641
2642function blitBuffer (src, dst, offset, length) {
2643 for (var i = 0; i < length; ++i) {
2644 if ((i + offset >= dst.length) || (i >= src.length)) break
2645 dst[i + offset] = src[i]
2646 }
2647 return i
2648}
2649
2650function isnan (val) {
2651 return val !== val // eslint-disable-line no-self-compare
2652}
2653
2654/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20)))
2655
2656/***/ }),
2657/* 2 */
2658/***/ (function(module, __webpack_exports__, __webpack_require__) {
2659
2660"use strict";
2661/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AuthenticationHelper; });
2662/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_buffer__ = __webpack_require__(1);
2663/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_buffer___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_buffer__);
2664/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_crypto_js_core__ = __webpack_require__(0);
2665/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_crypto_js_core__);
2666/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_crypto_js_lib_typedarrays__ = __webpack_require__(3);
2667/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_crypto_js_lib_typedarrays___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_crypto_js_lib_typedarrays__);
2668/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_crypto_js_sha256__ = __webpack_require__(4);
2669/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_crypto_js_sha256___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_crypto_js_sha256__);
2670/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256__ = __webpack_require__(5);
2671/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256__);
2672/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__BigInteger__ = __webpack_require__(6);
2673/*!
2674 * Copyright 2016 Amazon.com,
2675 * Inc. or its affiliates. All Rights Reserved.
2676 *
2677 * Licensed under the Amazon Software License (the "License").
2678 * You may not use this file except in compliance with the
2679 * License. A copy of the License is located at
2680 *
2681 * http://aws.amazon.com/asl/
2682 *
2683 * or in the "license" file accompanying this file. This file is
2684 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
2685 * CONDITIONS OF ANY KIND, express or implied. See the License
2686 * for the specific language governing permissions and
2687 * limitations under the License.
2688 */
2689
2690
2691 // necessary for crypto js
2692
2693
2694
2695
2696var randomBytes = function randomBytes(nBytes) {
2697 return __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(__WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.random(nBytes).toString(), 'hex');
2698};
2699
2700
2701var initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF';
2702var newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.';
2703/** @class */
2704
2705var AuthenticationHelper = /*#__PURE__*/function () {
2706 /**
2707 * Constructs a new AuthenticationHelper object
2708 * @param {string} PoolName Cognito user pool name.
2709 */
2710 function AuthenticationHelper(PoolName) {
2711 this.N = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](initN, 16);
2712 this.g = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */]('2', 16);
2713 this.k = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](this.hexHash("00" + this.N.toString(16) + "0" + this.g.toString(16)), 16);
2714 this.smallAValue = this.generateRandomSmallA();
2715 this.getLargeAValue(function () {});
2716 this.infoBits = __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from('Caldera Derived Key', 'utf8');
2717 this.poolName = PoolName;
2718 }
2719 /**
2720 * @returns {BigInteger} small A, a random number
2721 */
2722
2723
2724 var _proto = AuthenticationHelper.prototype;
2725
2726 _proto.getSmallAValue = function getSmallAValue() {
2727 return this.smallAValue;
2728 }
2729 /**
2730 * @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
2731 * @returns {void}
2732 */
2733 ;
2734
2735 _proto.getLargeAValue = function getLargeAValue(callback) {
2736 var _this = this;
2737
2738 if (this.largeAValue) {
2739 callback(null, this.largeAValue);
2740 } else {
2741 this.calculateA(this.smallAValue, function (err, largeAValue) {
2742 if (err) {
2743 callback(err, null);
2744 }
2745
2746 _this.largeAValue = largeAValue;
2747 callback(null, _this.largeAValue);
2748 });
2749 }
2750 }
2751 /**
2752 * helper function to generate a random big integer
2753 * @returns {BigInteger} a random value.
2754 * @private
2755 */
2756 ;
2757
2758 _proto.generateRandomSmallA = function generateRandomSmallA() {
2759 var hexRandom = randomBytes(128).toString('hex');
2760 var randomBigInt = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](hexRandom, 16);
2761 var smallABigInt = randomBigInt.mod(this.N);
2762 return smallABigInt;
2763 }
2764 /**
2765 * helper function to generate a random string
2766 * @returns {string} a random value.
2767 * @private
2768 */
2769 ;
2770
2771 _proto.generateRandomString = function generateRandomString() {
2772 return randomBytes(40).toString('base64');
2773 }
2774 /**
2775 * @returns {string} Generated random value included in password hash.
2776 */
2777 ;
2778
2779 _proto.getRandomPassword = function getRandomPassword() {
2780 return this.randomPassword;
2781 }
2782 /**
2783 * @returns {string} Generated random value included in devices hash.
2784 */
2785 ;
2786
2787 _proto.getSaltDevices = function getSaltDevices() {
2788 return this.SaltToHashDevices;
2789 }
2790 /**
2791 * @returns {string} Value used to verify devices.
2792 */
2793 ;
2794
2795 _proto.getVerifierDevices = function getVerifierDevices() {
2796 return this.verifierDevices;
2797 }
2798 /**
2799 * Generate salts and compute verifier.
2800 * @param {string} deviceGroupKey Devices to generate verifier for.
2801 * @param {string} username User to generate verifier for.
2802 * @param {nodeCallback<null>} callback Called with (err, null)
2803 * @returns {void}
2804 */
2805 ;
2806
2807 _proto.generateHashDevice = function generateHashDevice(deviceGroupKey, username, callback) {
2808 var _this2 = this;
2809
2810 this.randomPassword = this.generateRandomString();
2811 var combinedString = "" + deviceGroupKey + username + ":" + this.randomPassword;
2812 var hashedString = this.hash(combinedString);
2813 var hexRandom = randomBytes(16).toString('hex');
2814 this.SaltToHashDevices = this.padHex(new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](hexRandom, 16));
2815 this.g.modPow(new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, function (err, verifierDevicesNotPadded) {
2816 if (err) {
2817 callback(err, null);
2818 }
2819
2820 _this2.verifierDevices = _this2.padHex(verifierDevicesNotPadded);
2821 callback(null, null);
2822 });
2823 }
2824 /**
2825 * Calculate the client's public value A = g^a%N
2826 * with the generated random number a
2827 * @param {BigInteger} a Randomly generated small A.
2828 * @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
2829 * @returns {void}
2830 * @private
2831 */
2832 ;
2833
2834 _proto.calculateA = function calculateA(a, callback) {
2835 var _this3 = this;
2836
2837 this.g.modPow(a, this.N, function (err, A) {
2838 if (err) {
2839 callback(err, null);
2840 }
2841
2842 if (A.mod(_this3.N).equals(__WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */].ZERO)) {
2843 callback(new Error('Illegal paramater. A mod N cannot be 0.'), null);
2844 }
2845
2846 callback(null, A);
2847 });
2848 }
2849 /**
2850 * Calculate the client's value U which is the hash of A and B
2851 * @param {BigInteger} A Large A value.
2852 * @param {BigInteger} B Server B value.
2853 * @returns {BigInteger} Computed U value.
2854 * @private
2855 */
2856 ;
2857
2858 _proto.calculateU = function calculateU(A, B) {
2859 this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B));
2860 var finalU = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](this.UHexHash, 16);
2861 return finalU;
2862 }
2863 /**
2864 * Calculate a hash from a bitArray
2865 * @param {Buffer} buf Value to hash.
2866 * @returns {String} Hex-encoded hash.
2867 * @private
2868 */
2869 ;
2870
2871 _proto.hash = function hash(buf) {
2872 var str = buf instanceof __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"] ? __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.create(buf) : buf;
2873 var hashHex = __WEBPACK_IMPORTED_MODULE_3_crypto_js_sha256___default()(str).toString();
2874 return new Array(64 - hashHex.length).join('0') + hashHex;
2875 }
2876 /**
2877 * Calculate a hash from a hex string
2878 * @param {String} hexStr Value to hash.
2879 * @returns {String} Hex-encoded hash.
2880 * @private
2881 */
2882 ;
2883
2884 _proto.hexHash = function hexHash(hexStr) {
2885 return this.hash(__WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(hexStr, 'hex'));
2886 }
2887 /**
2888 * Standard hkdf algorithm
2889 * @param {Buffer} ikm Input key material.
2890 * @param {Buffer} salt Salt value.
2891 * @returns {Buffer} Strong key material.
2892 * @private
2893 */
2894 ;
2895
2896 _proto.computehkdf = function computehkdf(ikm, salt) {
2897 var infoBitsWordArray = __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.create(__WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].concat([this.infoBits, __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(String.fromCharCode(1), 'utf8')]));
2898 var ikmWordArray = ikm instanceof __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"] ? __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.create(ikm) : ikm;
2899 var saltWordArray = salt instanceof __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"] ? __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.create(salt) : salt;
2900 var prk = __WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256___default()(ikmWordArray, saltWordArray);
2901 var hmac = __WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256___default()(infoBitsWordArray, prk);
2902 return __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(hmac.toString(), 'hex').slice(0, 16);
2903 }
2904 /**
2905 * Calculates the final hkdf based on computed S value, and computed U value and the key
2906 * @param {String} username Username.
2907 * @param {String} password Password.
2908 * @param {BigInteger} serverBValue Server B value.
2909 * @param {BigInteger} salt Generated salt.
2910 * @param {nodeCallback<Buffer>} callback Called with (err, hkdfValue)
2911 * @returns {void}
2912 */
2913 ;
2914
2915 _proto.getPasswordAuthenticationKey = function getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) {
2916 var _this4 = this;
2917
2918 if (serverBValue.mod(this.N).equals(__WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */].ZERO)) {
2919 throw new Error('B cannot be zero.');
2920 }
2921
2922 this.UValue = this.calculateU(this.largeAValue, serverBValue);
2923
2924 if (this.UValue.equals(__WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */].ZERO)) {
2925 throw new Error('U cannot be zero.');
2926 }
2927
2928 var usernamePassword = "" + this.poolName + username + ":" + password;
2929 var usernamePasswordHash = this.hash(usernamePassword);
2930 var xValue = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](this.hexHash(this.padHex(salt) + usernamePasswordHash), 16);
2931 this.calculateS(xValue, serverBValue, function (err, sValue) {
2932 if (err) {
2933 callback(err, null);
2934 }
2935
2936 var hkdf = _this4.computehkdf(__WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(_this4.padHex(sValue), 'hex'), __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(_this4.padHex(_this4.UValue.toString(16)), 'hex'));
2937
2938 callback(null, hkdf);
2939 });
2940 }
2941 /**
2942 * Calculates the S value used in getPasswordAuthenticationKey
2943 * @param {BigInteger} xValue Salted password hash value.
2944 * @param {BigInteger} serverBValue Server B value.
2945 * @param {nodeCallback<string>} callback Called on success or error.
2946 * @returns {void}
2947 */
2948 ;
2949
2950 _proto.calculateS = function calculateS(xValue, serverBValue, callback) {
2951 var _this5 = this;
2952
2953 this.g.modPow(xValue, this.N, function (err, gModPowXN) {
2954 if (err) {
2955 callback(err, null);
2956 }
2957
2958 var intValue2 = serverBValue.subtract(_this5.k.multiply(gModPowXN));
2959 intValue2.modPow(_this5.smallAValue.add(_this5.UValue.multiply(xValue)), _this5.N, function (err2, result) {
2960 if (err2) {
2961 callback(err2, null);
2962 }
2963
2964 callback(null, result.mod(_this5.N));
2965 });
2966 });
2967 }
2968 /**
2969 * Return constant newPasswordRequiredChallengeUserAttributePrefix
2970 * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value
2971 */
2972 ;
2973
2974 _proto.getNewPasswordRequiredChallengeUserAttributePrefix = function getNewPasswordRequiredChallengeUserAttributePrefix() {
2975 return newPasswordRequiredChallengeUserAttributePrefix;
2976 }
2977 /**
2978 * Converts a BigInteger (or hex string) to hex format padded with zeroes for hashing
2979 * @param {BigInteger|String} bigInt Number or string to pad.
2980 * @returns {String} Padded hex string.
2981 */
2982 ;
2983
2984 _proto.padHex = function padHex(bigInt) {
2985 var hashStr = bigInt.toString(16);
2986
2987 if (hashStr.length % 2 === 1) {
2988 hashStr = "0" + hashStr;
2989 } else if ('89ABCDEFabcdef'.indexOf(hashStr[0]) !== -1) {
2990 hashStr = "00" + hashStr;
2991 }
2992
2993 return hashStr;
2994 };
2995
2996 return AuthenticationHelper;
2997}();
2998
2999
3000
3001/***/ }),
3002/* 3 */
3003/***/ (function(module, exports, __webpack_require__) {
3004
3005;(function (root, factory) {
3006 if (true) {
3007 // CommonJS
3008 module.exports = exports = factory(__webpack_require__(0));
3009 }
3010 else if (typeof define === "function" && define.amd) {
3011 // AMD
3012 define(["./core"], factory);
3013 }
3014 else {
3015 // Global (browser)
3016 factory(root.CryptoJS);
3017 }
3018}(this, function (CryptoJS) {
3019
3020 (function () {
3021 // Check if typed arrays are supported
3022 if (typeof ArrayBuffer != 'function') {
3023 return;
3024 }
3025
3026 // Shortcuts
3027 var C = CryptoJS;
3028 var C_lib = C.lib;
3029 var WordArray = C_lib.WordArray;
3030
3031 // Reference original init
3032 var superInit = WordArray.init;
3033
3034 // Augment WordArray.init to handle typed arrays
3035 var subInit = WordArray.init = function (typedArray) {
3036 // Convert buffers to uint8
3037 if (typedArray instanceof ArrayBuffer) {
3038 typedArray = new Uint8Array(typedArray);
3039 }
3040
3041 // Convert other array views to uint8
3042 if (
3043 typedArray instanceof Int8Array ||
3044 (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
3045 typedArray instanceof Int16Array ||
3046 typedArray instanceof Uint16Array ||
3047 typedArray instanceof Int32Array ||
3048 typedArray instanceof Uint32Array ||
3049 typedArray instanceof Float32Array ||
3050 typedArray instanceof Float64Array
3051 ) {
3052 typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
3053 }
3054
3055 // Handle Uint8Array
3056 if (typedArray instanceof Uint8Array) {
3057 // Shortcut
3058 var typedArrayByteLength = typedArray.byteLength;
3059
3060 // Extract bytes
3061 var words = [];
3062 for (var i = 0; i < typedArrayByteLength; i++) {
3063 words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
3064 }
3065
3066 // Initialize this word array
3067 superInit.call(this, words, typedArrayByteLength);
3068 } else {
3069 // Else call normal init
3070 superInit.apply(this, arguments);
3071 }
3072 };
3073
3074 subInit.prototype = WordArray;
3075 }());
3076
3077
3078 return CryptoJS.lib.WordArray;
3079
3080}));
3081
3082/***/ }),
3083/* 4 */
3084/***/ (function(module, exports, __webpack_require__) {
3085
3086;(function (root, factory) {
3087 if (true) {
3088 // CommonJS
3089 module.exports = exports = factory(__webpack_require__(0));
3090 }
3091 else if (typeof define === "function" && define.amd) {
3092 // AMD
3093 define(["./core"], factory);
3094 }
3095 else {
3096 // Global (browser)
3097 factory(root.CryptoJS);
3098 }
3099}(this, function (CryptoJS) {
3100
3101 (function (Math) {
3102 // Shortcuts
3103 var C = CryptoJS;
3104 var C_lib = C.lib;
3105 var WordArray = C_lib.WordArray;
3106 var Hasher = C_lib.Hasher;
3107 var C_algo = C.algo;
3108
3109 // Initialization and round constants tables
3110 var H = [];
3111 var K = [];
3112
3113 // Compute constants
3114 (function () {
3115 function isPrime(n) {
3116 var sqrtN = Math.sqrt(n);
3117 for (var factor = 2; factor <= sqrtN; factor++) {
3118 if (!(n % factor)) {
3119 return false;
3120 }
3121 }
3122
3123 return true;
3124 }
3125
3126 function getFractionalBits(n) {
3127 return ((n - (n | 0)) * 0x100000000) | 0;
3128 }
3129
3130 var n = 2;
3131 var nPrime = 0;
3132 while (nPrime < 64) {
3133 if (isPrime(n)) {
3134 if (nPrime < 8) {
3135 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
3136 }
3137 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
3138
3139 nPrime++;
3140 }
3141
3142 n++;
3143 }
3144 }());
3145
3146 // Reusable object
3147 var W = [];
3148
3149 /**
3150 * SHA-256 hash algorithm.
3151 */
3152 var SHA256 = C_algo.SHA256 = Hasher.extend({
3153 _doReset: function () {
3154 this._hash = new WordArray.init(H.slice(0));
3155 },
3156
3157 _doProcessBlock: function (M, offset) {
3158 // Shortcut
3159 var H = this._hash.words;
3160
3161 // Working variables
3162 var a = H[0];
3163 var b = H[1];
3164 var c = H[2];
3165 var d = H[3];
3166 var e = H[4];
3167 var f = H[5];
3168 var g = H[6];
3169 var h = H[7];
3170
3171 // Computation
3172 for (var i = 0; i < 64; i++) {
3173 if (i < 16) {
3174 W[i] = M[offset + i] | 0;
3175 } else {
3176 var gamma0x = W[i - 15];
3177 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
3178 ((gamma0x << 14) | (gamma0x >>> 18)) ^
3179 (gamma0x >>> 3);
3180
3181 var gamma1x = W[i - 2];
3182 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
3183 ((gamma1x << 13) | (gamma1x >>> 19)) ^
3184 (gamma1x >>> 10);
3185
3186 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
3187 }
3188
3189 var ch = (e & f) ^ (~e & g);
3190 var maj = (a & b) ^ (a & c) ^ (b & c);
3191
3192 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
3193 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
3194
3195 var t1 = h + sigma1 + ch + K[i] + W[i];
3196 var t2 = sigma0 + maj;
3197
3198 h = g;
3199 g = f;
3200 f = e;
3201 e = (d + t1) | 0;
3202 d = c;
3203 c = b;
3204 b = a;
3205 a = (t1 + t2) | 0;
3206 }
3207
3208 // Intermediate hash value
3209 H[0] = (H[0] + a) | 0;
3210 H[1] = (H[1] + b) | 0;
3211 H[2] = (H[2] + c) | 0;
3212 H[3] = (H[3] + d) | 0;
3213 H[4] = (H[4] + e) | 0;
3214 H[5] = (H[5] + f) | 0;
3215 H[6] = (H[6] + g) | 0;
3216 H[7] = (H[7] + h) | 0;
3217 },
3218
3219 _doFinalize: function () {
3220 // Shortcuts
3221 var data = this._data;
3222 var dataWords = data.words;
3223
3224 var nBitsTotal = this._nDataBytes * 8;
3225 var nBitsLeft = data.sigBytes * 8;
3226
3227 // Add padding
3228 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
3229 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
3230 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
3231 data.sigBytes = dataWords.length * 4;
3232
3233 // Hash final blocks
3234 this._process();
3235
3236 // Return final computed hash
3237 return this._hash;
3238 },
3239
3240 clone: function () {
3241 var clone = Hasher.clone.call(this);
3242 clone._hash = this._hash.clone();
3243
3244 return clone;
3245 }
3246 });
3247
3248 /**
3249 * Shortcut function to the hasher's object interface.
3250 *
3251 * @param {WordArray|string} message The message to hash.
3252 *
3253 * @return {WordArray} The hash.
3254 *
3255 * @static
3256 *
3257 * @example
3258 *
3259 * var hash = CryptoJS.SHA256('message');
3260 * var hash = CryptoJS.SHA256(wordArray);
3261 */
3262 C.SHA256 = Hasher._createHelper(SHA256);
3263
3264 /**
3265 * Shortcut function to the HMAC's object interface.
3266 *
3267 * @param {WordArray|string} message The message to hash.
3268 * @param {WordArray|string} key The secret key.
3269 *
3270 * @return {WordArray} The HMAC.
3271 *
3272 * @static
3273 *
3274 * @example
3275 *
3276 * var hmac = CryptoJS.HmacSHA256(message, key);
3277 */
3278 C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
3279 }(Math));
3280
3281
3282 return CryptoJS.SHA256;
3283
3284}));
3285
3286/***/ }),
3287/* 5 */
3288/***/ (function(module, exports, __webpack_require__) {
3289
3290;(function (root, factory, undef) {
3291 if (true) {
3292 // CommonJS
3293 module.exports = exports = factory(__webpack_require__(0), __webpack_require__(4), __webpack_require__(24));
3294 }
3295 else if (typeof define === "function" && define.amd) {
3296 // AMD
3297 define(["./core", "./sha256", "./hmac"], factory);
3298 }
3299 else {
3300 // Global (browser)
3301 factory(root.CryptoJS);
3302 }
3303}(this, function (CryptoJS) {
3304
3305 return CryptoJS.HmacSHA256;
3306
3307}));
3308
3309/***/ }),
3310/* 6 */
3311/***/ (function(module, __webpack_exports__, __webpack_require__) {
3312
3313"use strict";
3314// A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/
3315//
3316// All public methods have been removed except the following:
3317// new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported)
3318// toString (only radix 2, 4, 8, 16 and 32 supported)
3319// negate
3320// abs
3321// compareTo
3322// bitLength
3323// mod
3324// equals
3325// add
3326// subtract
3327// multiply
3328// divide
3329// modPow
3330/* harmony default export */ __webpack_exports__["a"] = (BigInteger);
3331/*
3332 * Copyright (c) 2003-2005 Tom Wu
3333 * All Rights Reserved.
3334 *
3335 * Permission is hereby granted, free of charge, to any person obtaining
3336 * a copy of this software and associated documentation files (the
3337 * "Software"), to deal in the Software without restriction, including
3338 * without limitation the rights to use, copy, modify, merge, publish,
3339 * distribute, sublicense, and/or sell copies of the Software, and to
3340 * permit persons to whom the Software is furnished to do so, subject to
3341 * the following conditions:
3342 *
3343 * The above copyright notice and this permission notice shall be
3344 * included in all copies or substantial portions of the Software.
3345 *
3346 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
3347 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
3348 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
3349 *
3350 * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
3351 * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
3352 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
3353 * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
3354 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
3355 *
3356 * In addition, the following condition applies:
3357 *
3358 * All redistributions must retain an intact copy of this copyright notice
3359 * and disclaimer.
3360 */
3361// (public) Constructor
3362
3363function BigInteger(a, b) {
3364 if (a != null) this.fromString(a, b);
3365} // return new, unset BigInteger
3366
3367
3368function nbi() {
3369 return new BigInteger(null);
3370} // Bits per digit
3371
3372
3373var dbits; // JavaScript engine analysis
3374
3375var canary = 0xdeadbeefcafe;
3376var j_lm = (canary & 0xffffff) == 0xefcafe; // am: Compute w_j += (x*this_i), propagate carries,
3377// c is initial carry, returns final carry.
3378// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
3379// We need to select the fastest one that works in this environment.
3380// am1: use a single mult and divide to get the high bits,
3381// max digit bits should be 26 because
3382// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
3383
3384function am1(i, x, w, j, c, n) {
3385 while (--n >= 0) {
3386 var v = x * this[i++] + w[j] + c;
3387 c = Math.floor(v / 0x4000000);
3388 w[j++] = v & 0x3ffffff;
3389 }
3390
3391 return c;
3392} // am2 avoids a big mult-and-extract completely.
3393// Max digit bits should be <= 30 because we do bitwise ops
3394// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
3395
3396
3397function am2(i, x, w, j, c, n) {
3398 var xl = x & 0x7fff,
3399 xh = x >> 15;
3400
3401 while (--n >= 0) {
3402 var l = this[i] & 0x7fff;
3403 var h = this[i++] >> 15;
3404 var m = xh * l + h * xl;
3405 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
3406 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
3407 w[j++] = l & 0x3fffffff;
3408 }
3409
3410 return c;
3411} // Alternately, set max digit bits to 28 since some
3412// browsers slow down when dealing with 32-bit numbers.
3413
3414
3415function am3(i, x, w, j, c, n) {
3416 var xl = x & 0x3fff,
3417 xh = x >> 14;
3418
3419 while (--n >= 0) {
3420 var l = this[i] & 0x3fff;
3421 var h = this[i++] >> 14;
3422 var m = xh * l + h * xl;
3423 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
3424 c = (l >> 28) + (m >> 14) + xh * h;
3425 w[j++] = l & 0xfffffff;
3426 }
3427
3428 return c;
3429}
3430
3431var inBrowser = typeof navigator !== 'undefined';
3432
3433if (inBrowser && j_lm && navigator.appName == 'Microsoft Internet Explorer') {
3434 BigInteger.prototype.am = am2;
3435 dbits = 30;
3436} else if (inBrowser && j_lm && navigator.appName != 'Netscape') {
3437 BigInteger.prototype.am = am1;
3438 dbits = 26;
3439} else {
3440 // Mozilla/Netscape seems to prefer am3
3441 BigInteger.prototype.am = am3;
3442 dbits = 28;
3443}
3444
3445BigInteger.prototype.DB = dbits;
3446BigInteger.prototype.DM = (1 << dbits) - 1;
3447BigInteger.prototype.DV = 1 << dbits;
3448var BI_FP = 52;
3449BigInteger.prototype.FV = Math.pow(2, BI_FP);
3450BigInteger.prototype.F1 = BI_FP - dbits;
3451BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions
3452
3453var BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz';
3454var BI_RC = new Array();
3455var rr, vv;
3456rr = '0'.charCodeAt(0);
3457
3458for (vv = 0; vv <= 9; ++vv) {
3459 BI_RC[rr++] = vv;
3460}
3461
3462rr = 'a'.charCodeAt(0);
3463
3464for (vv = 10; vv < 36; ++vv) {
3465 BI_RC[rr++] = vv;
3466}
3467
3468rr = 'A'.charCodeAt(0);
3469
3470for (vv = 10; vv < 36; ++vv) {
3471 BI_RC[rr++] = vv;
3472}
3473
3474function int2char(n) {
3475 return BI_RM.charAt(n);
3476}
3477
3478function intAt(s, i) {
3479 var c = BI_RC[s.charCodeAt(i)];
3480 return c == null ? -1 : c;
3481} // (protected) copy this to r
3482
3483
3484function bnpCopyTo(r) {
3485 for (var i = this.t - 1; i >= 0; --i) {
3486 r[i] = this[i];
3487 }
3488
3489 r.t = this.t;
3490 r.s = this.s;
3491} // (protected) set from integer value x, -DV <= x < DV
3492
3493
3494function bnpFromInt(x) {
3495 this.t = 1;
3496 this.s = x < 0 ? -1 : 0;
3497 if (x > 0) this[0] = x;else if (x < -1) this[0] = x + this.DV;else this.t = 0;
3498} // return bigint initialized to value
3499
3500
3501function nbv(i) {
3502 var r = nbi();
3503 r.fromInt(i);
3504 return r;
3505} // (protected) set from string and radix
3506
3507
3508function bnpFromString(s, b) {
3509 var k;
3510 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');
3511 this.t = 0;
3512 this.s = 0;
3513 var i = s.length,
3514 mi = false,
3515 sh = 0;
3516
3517 while (--i >= 0) {
3518 var x = intAt(s, i);
3519
3520 if (x < 0) {
3521 if (s.charAt(i) == '-') mi = true;
3522 continue;
3523 }
3524
3525 mi = false;
3526 if (sh == 0) this[this.t++] = x;else if (sh + k > this.DB) {
3527 this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh;
3528 this[this.t++] = x >> this.DB - sh;
3529 } else this[this.t - 1] |= x << sh;
3530 sh += k;
3531 if (sh >= this.DB) sh -= this.DB;
3532 }
3533
3534 this.clamp();
3535 if (mi) BigInteger.ZERO.subTo(this, this);
3536} // (protected) clamp off excess high words
3537
3538
3539function bnpClamp() {
3540 var c = this.s & this.DM;
3541
3542 while (this.t > 0 && this[this.t - 1] == c) {
3543 --this.t;
3544 }
3545} // (public) return string representation in given radix
3546
3547
3548function bnToString(b) {
3549 if (this.s < 0) return '-' + this.negate().toString(b);
3550 var k;
3551 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');
3552 var km = (1 << k) - 1,
3553 d,
3554 m = false,
3555 r = '',
3556 i = this.t;
3557 var p = this.DB - i * this.DB % k;
3558
3559 if (i-- > 0) {
3560 if (p < this.DB && (d = this[i] >> p) > 0) {
3561 m = true;
3562 r = int2char(d);
3563 }
3564
3565 while (i >= 0) {
3566 if (p < k) {
3567 d = (this[i] & (1 << p) - 1) << k - p;
3568 d |= this[--i] >> (p += this.DB - k);
3569 } else {
3570 d = this[i] >> (p -= k) & km;
3571
3572 if (p <= 0) {
3573 p += this.DB;
3574 --i;
3575 }
3576 }
3577
3578 if (d > 0) m = true;
3579 if (m) r += int2char(d);
3580 }
3581 }
3582
3583 return m ? r : '0';
3584} // (public) -this
3585
3586
3587function bnNegate() {
3588 var r = nbi();
3589 BigInteger.ZERO.subTo(this, r);
3590 return r;
3591} // (public) |this|
3592
3593
3594function bnAbs() {
3595 return this.s < 0 ? this.negate() : this;
3596} // (public) return + if this > a, - if this < a, 0 if equal
3597
3598
3599function bnCompareTo(a) {
3600 var r = this.s - a.s;
3601 if (r != 0) return r;
3602 var i = this.t;
3603 r = i - a.t;
3604 if (r != 0) return this.s < 0 ? -r : r;
3605
3606 while (--i >= 0) {
3607 if ((r = this[i] - a[i]) != 0) return r;
3608 }
3609
3610 return 0;
3611} // returns bit length of the integer x
3612
3613
3614function nbits(x) {
3615 var r = 1,
3616 t;
3617
3618 if ((t = x >>> 16) != 0) {
3619 x = t;
3620 r += 16;
3621 }
3622
3623 if ((t = x >> 8) != 0) {
3624 x = t;
3625 r += 8;
3626 }
3627
3628 if ((t = x >> 4) != 0) {
3629 x = t;
3630 r += 4;
3631 }
3632
3633 if ((t = x >> 2) != 0) {
3634 x = t;
3635 r += 2;
3636 }
3637
3638 if ((t = x >> 1) != 0) {
3639 x = t;
3640 r += 1;
3641 }
3642
3643 return r;
3644} // (public) return the number of bits in "this"
3645
3646
3647function bnBitLength() {
3648 if (this.t <= 0) return 0;
3649 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM);
3650} // (protected) r = this << n*DB
3651
3652
3653function bnpDLShiftTo(n, r) {
3654 var i;
3655
3656 for (i = this.t - 1; i >= 0; --i) {
3657 r[i + n] = this[i];
3658 }
3659
3660 for (i = n - 1; i >= 0; --i) {
3661 r[i] = 0;
3662 }
3663
3664 r.t = this.t + n;
3665 r.s = this.s;
3666} // (protected) r = this >> n*DB
3667
3668
3669function bnpDRShiftTo(n, r) {
3670 for (var i = n; i < this.t; ++i) {
3671 r[i - n] = this[i];
3672 }
3673
3674 r.t = Math.max(this.t - n, 0);
3675 r.s = this.s;
3676} // (protected) r = this << n
3677
3678
3679function bnpLShiftTo(n, r) {
3680 var bs = n % this.DB;
3681 var cbs = this.DB - bs;
3682 var bm = (1 << cbs) - 1;
3683 var ds = Math.floor(n / this.DB),
3684 c = this.s << bs & this.DM,
3685 i;
3686
3687 for (i = this.t - 1; i >= 0; --i) {
3688 r[i + ds + 1] = this[i] >> cbs | c;
3689 c = (this[i] & bm) << bs;
3690 }
3691
3692 for (i = ds - 1; i >= 0; --i) {
3693 r[i] = 0;
3694 }
3695
3696 r[ds] = c;
3697 r.t = this.t + ds + 1;
3698 r.s = this.s;
3699 r.clamp();
3700} // (protected) r = this >> n
3701
3702
3703function bnpRShiftTo(n, r) {
3704 r.s = this.s;
3705 var ds = Math.floor(n / this.DB);
3706
3707 if (ds >= this.t) {
3708 r.t = 0;
3709 return;
3710 }
3711
3712 var bs = n % this.DB;
3713 var cbs = this.DB - bs;
3714 var bm = (1 << bs) - 1;
3715 r[0] = this[ds] >> bs;
3716
3717 for (var i = ds + 1; i < this.t; ++i) {
3718 r[i - ds - 1] |= (this[i] & bm) << cbs;
3719 r[i - ds] = this[i] >> bs;
3720 }
3721
3722 if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs;
3723 r.t = this.t - ds;
3724 r.clamp();
3725} // (protected) r = this - a
3726
3727
3728function bnpSubTo(a, r) {
3729 var i = 0,
3730 c = 0,
3731 m = Math.min(a.t, this.t);
3732
3733 while (i < m) {
3734 c += this[i] - a[i];
3735 r[i++] = c & this.DM;
3736 c >>= this.DB;
3737 }
3738
3739 if (a.t < this.t) {
3740 c -= a.s;
3741
3742 while (i < this.t) {
3743 c += this[i];
3744 r[i++] = c & this.DM;
3745 c >>= this.DB;
3746 }
3747
3748 c += this.s;
3749 } else {
3750 c += this.s;
3751
3752 while (i < a.t) {
3753 c -= a[i];
3754 r[i++] = c & this.DM;
3755 c >>= this.DB;
3756 }
3757
3758 c -= a.s;
3759 }
3760
3761 r.s = c < 0 ? -1 : 0;
3762 if (c < -1) r[i++] = this.DV + c;else if (c > 0) r[i++] = c;
3763 r.t = i;
3764 r.clamp();
3765} // (protected) r = this * a, r != this,a (HAC 14.12)
3766// "this" should be the larger one if appropriate.
3767
3768
3769function bnpMultiplyTo(a, r) {
3770 var x = this.abs(),
3771 y = a.abs();
3772 var i = x.t;
3773 r.t = i + y.t;
3774
3775 while (--i >= 0) {
3776 r[i] = 0;
3777 }
3778
3779 for (i = 0; i < y.t; ++i) {
3780 r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
3781 }
3782
3783 r.s = 0;
3784 r.clamp();
3785 if (this.s != a.s) BigInteger.ZERO.subTo(r, r);
3786} // (protected) r = this^2, r != this (HAC 14.16)
3787
3788
3789function bnpSquareTo(r) {
3790 var x = this.abs();
3791 var i = r.t = 2 * x.t;
3792
3793 while (--i >= 0) {
3794 r[i] = 0;
3795 }
3796
3797 for (i = 0; i < x.t - 1; ++i) {
3798 var c = x.am(i, x[i], r, 2 * i, 0, 1);
3799
3800 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
3801 r[i + x.t] -= x.DV;
3802 r[i + x.t + 1] = 1;
3803 }
3804 }
3805
3806 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
3807 r.s = 0;
3808 r.clamp();
3809} // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
3810// r != q, this != m. q or r may be null.
3811
3812
3813function bnpDivRemTo(m, q, r) {
3814 var pm = m.abs();
3815 if (pm.t <= 0) return;
3816 var pt = this.abs();
3817
3818 if (pt.t < pm.t) {
3819 if (q != null) q.fromInt(0);
3820 if (r != null) this.copyTo(r);
3821 return;
3822 }
3823
3824 if (r == null) r = nbi();
3825 var y = nbi(),
3826 ts = this.s,
3827 ms = m.s;
3828 var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
3829
3830 if (nsh > 0) {
3831 pm.lShiftTo(nsh, y);
3832 pt.lShiftTo(nsh, r);
3833 } else {
3834 pm.copyTo(y);
3835 pt.copyTo(r);
3836 }
3837
3838 var ys = y.t;
3839 var y0 = y[ys - 1];
3840 if (y0 == 0) return;
3841 var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0);
3842 var d1 = this.FV / yt,
3843 d2 = (1 << this.F1) / yt,
3844 e = 1 << this.F2;
3845 var i = r.t,
3846 j = i - ys,
3847 t = q == null ? nbi() : q;
3848 y.dlShiftTo(j, t);
3849
3850 if (r.compareTo(t) >= 0) {
3851 r[r.t++] = 1;
3852 r.subTo(t, r);
3853 }
3854
3855 BigInteger.ONE.dlShiftTo(ys, t);
3856 t.subTo(y, y); // "negative" y so we can replace sub with am later
3857
3858 while (y.t < ys) {
3859 y[y.t++] = 0;
3860 }
3861
3862 while (--j >= 0) {
3863 // Estimate quotient digit
3864 var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
3865
3866 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {
3867 // Try it out
3868 y.dlShiftTo(j, t);
3869 r.subTo(t, r);
3870
3871 while (r[i] < --qd) {
3872 r.subTo(t, r);
3873 }
3874 }
3875 }
3876
3877 if (q != null) {
3878 r.drShiftTo(ys, q);
3879 if (ts != ms) BigInteger.ZERO.subTo(q, q);
3880 }
3881
3882 r.t = ys;
3883 r.clamp();
3884 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
3885
3886 if (ts < 0) BigInteger.ZERO.subTo(r, r);
3887} // (public) this mod a
3888
3889
3890function bnMod(a) {
3891 var r = nbi();
3892 this.abs().divRemTo(a, null, r);
3893 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r);
3894 return r;
3895} // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
3896// justification:
3897// xy == 1 (mod m)
3898// xy = 1+km
3899// xy(2-xy) = (1+km)(1-km)
3900// x[y(2-xy)] = 1-k^2m^2
3901// x[y(2-xy)] == 1 (mod m^2)
3902// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
3903// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
3904// JS multiply "overflows" differently from C/C++, so care is needed here.
3905
3906
3907function bnpInvDigit() {
3908 if (this.t < 1) return 0;
3909 var x = this[0];
3910 if ((x & 1) == 0) return 0;
3911 var y = x & 3; // y == 1/x mod 2^2
3912
3913 y = y * (2 - (x & 0xf) * y) & 0xf; // y == 1/x mod 2^4
3914
3915 y = y * (2 - (x & 0xff) * y) & 0xff; // y == 1/x mod 2^8
3916
3917 y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; // y == 1/x mod 2^16
3918 // last step - calculate inverse mod DV directly;
3919 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
3920
3921 y = y * (2 - x * y % this.DV) % this.DV; // y == 1/x mod 2^dbits
3922 // we really want the negative inverse, and -DV < y < DV
3923
3924 return y > 0 ? this.DV - y : -y;
3925}
3926
3927function bnEquals(a) {
3928 return this.compareTo(a) == 0;
3929} // (protected) r = this + a
3930
3931
3932function bnpAddTo(a, r) {
3933 var i = 0,
3934 c = 0,
3935 m = Math.min(a.t, this.t);
3936
3937 while (i < m) {
3938 c += this[i] + a[i];
3939 r[i++] = c & this.DM;
3940 c >>= this.DB;
3941 }
3942
3943 if (a.t < this.t) {
3944 c += a.s;
3945
3946 while (i < this.t) {
3947 c += this[i];
3948 r[i++] = c & this.DM;
3949 c >>= this.DB;
3950 }
3951
3952 c += this.s;
3953 } else {
3954 c += this.s;
3955
3956 while (i < a.t) {
3957 c += a[i];
3958 r[i++] = c & this.DM;
3959 c >>= this.DB;
3960 }
3961
3962 c += a.s;
3963 }
3964
3965 r.s = c < 0 ? -1 : 0;
3966 if (c > 0) r[i++] = c;else if (c < -1) r[i++] = this.DV + c;
3967 r.t = i;
3968 r.clamp();
3969} // (public) this + a
3970
3971
3972function bnAdd(a) {
3973 var r = nbi();
3974 this.addTo(a, r);
3975 return r;
3976} // (public) this - a
3977
3978
3979function bnSubtract(a) {
3980 var r = nbi();
3981 this.subTo(a, r);
3982 return r;
3983} // (public) this * a
3984
3985
3986function bnMultiply(a) {
3987 var r = nbi();
3988 this.multiplyTo(a, r);
3989 return r;
3990} // (public) this / a
3991
3992
3993function bnDivide(a) {
3994 var r = nbi();
3995 this.divRemTo(a, r, null);
3996 return r;
3997} // Montgomery reduction
3998
3999
4000function Montgomery(m) {
4001 this.m = m;
4002 this.mp = m.invDigit();
4003 this.mpl = this.mp & 0x7fff;
4004 this.mph = this.mp >> 15;
4005 this.um = (1 << m.DB - 15) - 1;
4006 this.mt2 = 2 * m.t;
4007} // xR mod m
4008
4009
4010function montConvert(x) {
4011 var r = nbi();
4012 x.abs().dlShiftTo(this.m.t, r);
4013 r.divRemTo(this.m, null, r);
4014 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r);
4015 return r;
4016} // x/R mod m
4017
4018
4019function montRevert(x) {
4020 var r = nbi();
4021 x.copyTo(r);
4022 this.reduce(r);
4023 return r;
4024} // x = x/R mod m (HAC 14.32)
4025
4026
4027function montReduce(x) {
4028 while (x.t <= this.mt2) {
4029 // pad x so am has enough room later
4030 x[x.t++] = 0;
4031 }
4032
4033 for (var i = 0; i < this.m.t; ++i) {
4034 // faster way of calculating u0 = x[i]*mp mod DV
4035 var j = x[i] & 0x7fff;
4036 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
4037
4038 j = i + this.m.t;
4039 x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry
4040
4041 while (x[j] >= x.DV) {
4042 x[j] -= x.DV;
4043 x[++j]++;
4044 }
4045 }
4046
4047 x.clamp();
4048 x.drShiftTo(this.m.t, x);
4049 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x);
4050} // r = "x^2/R mod m"; x != r
4051
4052
4053function montSqrTo(x, r) {
4054 x.squareTo(r);
4055 this.reduce(r);
4056} // r = "xy/R mod m"; x,y != r
4057
4058
4059function montMulTo(x, y, r) {
4060 x.multiplyTo(y, r);
4061 this.reduce(r);
4062}
4063
4064Montgomery.prototype.convert = montConvert;
4065Montgomery.prototype.revert = montRevert;
4066Montgomery.prototype.reduce = montReduce;
4067Montgomery.prototype.mulTo = montMulTo;
4068Montgomery.prototype.sqrTo = montSqrTo; // (public) this^e % m (HAC 14.85)
4069
4070function bnModPow(e, m, callback) {
4071 var i = e.bitLength(),
4072 k,
4073 r = nbv(1),
4074 z = new Montgomery(m);
4075 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
4076
4077 var g = new Array(),
4078 n = 3,
4079 k1 = k - 1,
4080 km = (1 << k) - 1;
4081 g[1] = z.convert(this);
4082
4083 if (k > 1) {
4084 var g2 = nbi();
4085 z.sqrTo(g[1], g2);
4086
4087 while (n <= km) {
4088 g[n] = nbi();
4089 z.mulTo(g2, g[n - 2], g[n]);
4090 n += 2;
4091 }
4092 }
4093
4094 var j = e.t - 1,
4095 w,
4096 is1 = true,
4097 r2 = nbi(),
4098 t;
4099 i = nbits(e[j]) - 1;
4100
4101 while (j >= 0) {
4102 if (i >= k1) w = e[j] >> i - k1 & km;else {
4103 w = (e[j] & (1 << i + 1) - 1) << k1 - i;
4104 if (j > 0) w |= e[j - 1] >> this.DB + i - k1;
4105 }
4106 n = k;
4107
4108 while ((w & 1) == 0) {
4109 w >>= 1;
4110 --n;
4111 }
4112
4113 if ((i -= n) < 0) {
4114 i += this.DB;
4115 --j;
4116 }
4117
4118 if (is1) {
4119 // ret == 1, don't bother squaring or multiplying it
4120 g[w].copyTo(r);
4121 is1 = false;
4122 } else {
4123 while (n > 1) {
4124 z.sqrTo(r, r2);
4125 z.sqrTo(r2, r);
4126 n -= 2;
4127 }
4128
4129 if (n > 0) z.sqrTo(r, r2);else {
4130 t = r;
4131 r = r2;
4132 r2 = t;
4133 }
4134 z.mulTo(r2, g[w], r);
4135 }
4136
4137 while (j >= 0 && (e[j] & 1 << i) == 0) {
4138 z.sqrTo(r, r2);
4139 t = r;
4140 r = r2;
4141 r2 = t;
4142
4143 if (--i < 0) {
4144 i = this.DB - 1;
4145 --j;
4146 }
4147 }
4148 }
4149
4150 var result = z.revert(r);
4151 callback(null, result);
4152 return result;
4153} // protected
4154
4155
4156BigInteger.prototype.copyTo = bnpCopyTo;
4157BigInteger.prototype.fromInt = bnpFromInt;
4158BigInteger.prototype.fromString = bnpFromString;
4159BigInteger.prototype.clamp = bnpClamp;
4160BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
4161BigInteger.prototype.drShiftTo = bnpDRShiftTo;
4162BigInteger.prototype.lShiftTo = bnpLShiftTo;
4163BigInteger.prototype.rShiftTo = bnpRShiftTo;
4164BigInteger.prototype.subTo = bnpSubTo;
4165BigInteger.prototype.multiplyTo = bnpMultiplyTo;
4166BigInteger.prototype.squareTo = bnpSquareTo;
4167BigInteger.prototype.divRemTo = bnpDivRemTo;
4168BigInteger.prototype.invDigit = bnpInvDigit;
4169BigInteger.prototype.addTo = bnpAddTo; // public
4170
4171BigInteger.prototype.toString = bnToString;
4172BigInteger.prototype.negate = bnNegate;
4173BigInteger.prototype.abs = bnAbs;
4174BigInteger.prototype.compareTo = bnCompareTo;
4175BigInteger.prototype.bitLength = bnBitLength;
4176BigInteger.prototype.mod = bnMod;
4177BigInteger.prototype.equals = bnEquals;
4178BigInteger.prototype.add = bnAdd;
4179BigInteger.prototype.subtract = bnSubtract;
4180BigInteger.prototype.multiply = bnMultiply;
4181BigInteger.prototype.divide = bnDivide;
4182BigInteger.prototype.modPow = bnModPow; // "constants"
4183
4184BigInteger.ZERO = nbv(0);
4185BigInteger.ONE = nbv(1);
4186
4187/***/ }),
4188/* 7 */
4189/***/ (function(module, __webpack_exports__, __webpack_require__) {
4190
4191"use strict";
4192/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CognitoAccessToken; });
4193/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__CognitoJwtToken__ = __webpack_require__(8);
4194function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
4195
4196/*
4197 * Copyright 2016 Amazon.com,
4198 * Inc. or its affiliates. All Rights Reserved.
4199 *
4200 * Licensed under the Amazon Software License (the "License").
4201 * You may not use this file except in compliance with the
4202 * License. A copy of the License is located at
4203 *
4204 * http://aws.amazon.com/asl/
4205 *
4206 * or in the "license" file accompanying this file. This file is
4207 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
4208 * CONDITIONS OF ANY KIND, express or implied. See the License
4209 * for the specific language governing permissions and
4210 * limitations under the License.
4211 */
4212
4213/** @class */
4214
4215var CognitoAccessToken = /*#__PURE__*/function (_CognitoJwtToken) {
4216 _inheritsLoose(CognitoAccessToken, _CognitoJwtToken);
4217
4218 /**
4219 * Constructs a new CognitoAccessToken object
4220 * @param {string=} AccessToken The JWT access token.
4221 */
4222 function CognitoAccessToken(_temp) {
4223 var _ref = _temp === void 0 ? {} : _temp,
4224 AccessToken = _ref.AccessToken;
4225
4226 return _CognitoJwtToken.call(this, AccessToken || '') || this;
4227 }
4228
4229 return CognitoAccessToken;
4230}(__WEBPACK_IMPORTED_MODULE_0__CognitoJwtToken__["a" /* default */]);
4231
4232
4233
4234/***/ }),
4235/* 8 */
4236/***/ (function(module, __webpack_exports__, __webpack_require__) {
4237
4238"use strict";
4239/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CognitoJwtToken; });
4240/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_buffer__ = __webpack_require__(1);
4241/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_buffer___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_buffer__);
4242/*!
4243 * Copyright 2016 Amazon.com,
4244 * Inc. or its affiliates. All Rights Reserved.
4245 *
4246 * Licensed under the Amazon Software License (the "License").
4247 * You may not use this file except in compliance with the
4248 * License. A copy of the License is located at
4249 *
4250 * http://aws.amazon.com/asl/
4251 *
4252 * or in the "license" file accompanying this file. This file is
4253 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
4254 * CONDITIONS OF ANY KIND, express or implied. See the License
4255 * for the specific language governing permissions and
4256 * limitations under the License.
4257 */
4258
4259/** @class */
4260
4261var CognitoJwtToken = /*#__PURE__*/function () {
4262 /**
4263 * Constructs a new CognitoJwtToken object
4264 * @param {string=} token The JWT token.
4265 */
4266 function CognitoJwtToken(token) {
4267 // Assign object
4268 this.jwtToken = token || '';
4269 this.payload = this.decodePayload();
4270 }
4271 /**
4272 * @returns {string} the record's token.
4273 */
4274
4275
4276 var _proto = CognitoJwtToken.prototype;
4277
4278 _proto.getJwtToken = function getJwtToken() {
4279 return this.jwtToken;
4280 }
4281 /**
4282 * @returns {int} the token's expiration (exp member).
4283 */
4284 ;
4285
4286 _proto.getExpiration = function getExpiration() {
4287 return this.payload.exp;
4288 }
4289 /**
4290 * @returns {int} the token's "issued at" (iat member).
4291 */
4292 ;
4293
4294 _proto.getIssuedAt = function getIssuedAt() {
4295 return this.payload.iat;
4296 }
4297 /**
4298 * @returns {object} the token's payload.
4299 */
4300 ;
4301
4302 _proto.decodePayload = function decodePayload() {
4303 var payload = this.jwtToken.split('.')[1];
4304
4305 try {
4306 return JSON.parse(__WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(payload, 'base64').toString('utf8'));
4307 } catch (err) {
4308 return {};
4309 }
4310 };
4311
4312 return CognitoJwtToken;
4313}();
4314
4315
4316
4317/***/ }),
4318/* 9 */
4319/***/ (function(module, __webpack_exports__, __webpack_require__) {
4320
4321"use strict";
4322/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CognitoIdToken; });
4323/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__CognitoJwtToken__ = __webpack_require__(8);
4324function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
4325
4326/*!
4327 * Copyright 2016 Amazon.com,
4328 * Inc. or its affiliates. All Rights Reserved.
4329 *
4330 * Licensed under the Amazon Software License (the "License").
4331 * You may not use this file except in compliance with the
4332 * License. A copy of the License is located at
4333 *
4334 * http://aws.amazon.com/asl/
4335 *
4336 * or in the "license" file accompanying this file. This file is
4337 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
4338 * CONDITIONS OF ANY KIND, express or implied. See the License
4339 * for the specific language governing permissions and
4340 * limitations under the License.
4341 */
4342
4343/** @class */
4344
4345var CognitoIdToken = /*#__PURE__*/function (_CognitoJwtToken) {
4346 _inheritsLoose(CognitoIdToken, _CognitoJwtToken);
4347
4348 /**
4349 * Constructs a new CognitoIdToken object
4350 * @param {string=} IdToken The JWT Id token
4351 */
4352 function CognitoIdToken(_temp) {
4353 var _ref = _temp === void 0 ? {} : _temp,
4354 IdToken = _ref.IdToken;
4355
4356 return _CognitoJwtToken.call(this, IdToken || '') || this;
4357 }
4358
4359 return CognitoIdToken;
4360}(__WEBPACK_IMPORTED_MODULE_0__CognitoJwtToken__["a" /* default */]);
4361
4362
4363
4364/***/ }),
4365/* 10 */
4366/***/ (function(module, __webpack_exports__, __webpack_require__) {
4367
4368"use strict";
4369/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CognitoRefreshToken; });
4370/*!
4371 * Copyright 2016 Amazon.com,
4372 * Inc. or its affiliates. All Rights Reserved.
4373 *
4374 * Licensed under the Amazon Software License (the "License").
4375 * You may not use this file except in compliance with the
4376 * License. A copy of the License is located at
4377 *
4378 * http://aws.amazon.com/asl/
4379 *
4380 * or in the "license" file accompanying this file. This file is
4381 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
4382 * CONDITIONS OF ANY KIND, express or implied. See the License
4383 * for the specific language governing permissions and
4384 * limitations under the License.
4385 */
4386
4387/** @class */
4388var CognitoRefreshToken = /*#__PURE__*/function () {
4389 /**
4390 * Constructs a new CognitoRefreshToken object
4391 * @param {string=} RefreshToken The JWT refresh token.
4392 */
4393 function CognitoRefreshToken(_temp) {
4394 var _ref = _temp === void 0 ? {} : _temp,
4395 RefreshToken = _ref.RefreshToken;
4396
4397 // Assign object
4398 this.token = RefreshToken || '';
4399 }
4400 /**
4401 * @returns {string} the record's token.
4402 */
4403
4404
4405 var _proto = CognitoRefreshToken.prototype;
4406
4407 _proto.getToken = function getToken() {
4408 return this.token;
4409 };
4410
4411 return CognitoRefreshToken;
4412}();
4413
4414
4415
4416/***/ }),
4417/* 11 */
4418/***/ (function(module, __webpack_exports__, __webpack_require__) {
4419
4420"use strict";
4421/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CognitoUser; });
4422/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_buffer__ = __webpack_require__(1);
4423/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_buffer___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_buffer__);
4424/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_crypto_js_core__ = __webpack_require__(0);
4425/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_crypto_js_core__);
4426/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_crypto_js_lib_typedarrays__ = __webpack_require__(3);
4427/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_crypto_js_lib_typedarrays___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_crypto_js_lib_typedarrays__);
4428/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_crypto_js_enc_base64__ = __webpack_require__(25);
4429/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_crypto_js_enc_base64___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_crypto_js_enc_base64__);
4430/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256__ = __webpack_require__(5);
4431/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256__);
4432/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__BigInteger__ = __webpack_require__(6);
4433/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__AuthenticationHelper__ = __webpack_require__(2);
4434/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__CognitoAccessToken__ = __webpack_require__(7);
4435/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__CognitoIdToken__ = __webpack_require__(9);
4436/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__CognitoRefreshToken__ = __webpack_require__(10);
4437/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__CognitoUserSession__ = __webpack_require__(12);
4438/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__DateHelper__ = __webpack_require__(13);
4439/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__CognitoUserAttribute__ = __webpack_require__(14);
4440/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__StorageHelper__ = __webpack_require__(15);
4441/*!
4442 * Copyright 2016 Amazon.com,
4443 * Inc. or its affiliates. All Rights Reserved.
4444 *
4445 * Licensed under the Amazon Software License (the "License").
4446 * You may not use this file except in compliance with the
4447 * License. A copy of the License is located at
4448 *
4449 * http://aws.amazon.com/asl/
4450 *
4451 * or in the "license" file accompanying this file. This file is
4452 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
4453 * CONDITIONS OF ANY KIND, express or implied. See the License
4454 * for the specific language governing permissions and
4455 * limitations under the License.
4456 */
4457
4458
4459 // necessary for crypto js
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472/**
4473 * @callback nodeCallback
4474 * @template T result
4475 * @param {*} err The operation failure reason, or null.
4476 * @param {T} result The operation result.
4477 */
4478
4479/**
4480 * @callback onFailure
4481 * @param {*} err Failure reason.
4482 */
4483
4484/**
4485 * @callback onSuccess
4486 * @template T result
4487 * @param {T} result The operation result.
4488 */
4489
4490/**
4491 * @callback mfaRequired
4492 * @param {*} details MFA challenge details.
4493 */
4494
4495/**
4496 * @callback customChallenge
4497 * @param {*} details Custom challenge details.
4498 */
4499
4500/**
4501 * @callback inputVerificationCode
4502 * @param {*} data Server response.
4503 */
4504
4505/**
4506 * @callback authSuccess
4507 * @param {CognitoUserSession} session The new session.
4508 * @param {bool=} userConfirmationNecessary User must be confirmed.
4509 */
4510
4511var isBrowser = typeof navigator !== 'undefined';
4512var userAgent = isBrowser ? navigator.userAgent : 'nodejs';
4513/** @class */
4514
4515var CognitoUser = /*#__PURE__*/function () {
4516 /**
4517 * Constructs a new CognitoUser object
4518 * @param {object} data Creation options
4519 * @param {string} data.Username The user's username.
4520 * @param {CognitoUserPool} data.Pool Pool containing the user.
4521 * @param {object} data.Storage Optional storage object.
4522 */
4523 function CognitoUser(data) {
4524 if (data == null || data.Username == null || data.Pool == null) {
4525 throw new Error('Username and pool information are required.');
4526 }
4527
4528 this.username = data.Username || '';
4529 this.pool = data.Pool;
4530 this.Session = null;
4531 this.client = data.Pool.client;
4532 this.signInUserSession = null;
4533 this.authenticationFlowType = 'USER_SRP_AUTH';
4534 this.storage = data.Storage || new __WEBPACK_IMPORTED_MODULE_13__StorageHelper__["a" /* default */]().getStorage();
4535 this.keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
4536 this.userDataKey = this.keyPrefix + "." + this.username + ".userData";
4537 }
4538 /**
4539 * Sets the session for this user
4540 * @param {CognitoUserSession} signInUserSession the session
4541 * @returns {void}
4542 */
4543
4544
4545 var _proto = CognitoUser.prototype;
4546
4547 _proto.setSignInUserSession = function setSignInUserSession(signInUserSession) {
4548 this.clearCachedUserData();
4549 this.signInUserSession = signInUserSession;
4550 this.cacheTokens();
4551 }
4552 /**
4553 * @returns {CognitoUserSession} the current session for this user
4554 */
4555 ;
4556
4557 _proto.getSignInUserSession = function getSignInUserSession() {
4558 return this.signInUserSession;
4559 }
4560 /**
4561 * @returns {string} the user's username
4562 */
4563 ;
4564
4565 _proto.getUsername = function getUsername() {
4566 return this.username;
4567 }
4568 /**
4569 * @returns {String} the authentication flow type
4570 */
4571 ;
4572
4573 _proto.getAuthenticationFlowType = function getAuthenticationFlowType() {
4574 return this.authenticationFlowType;
4575 }
4576 /**
4577 * sets authentication flow type
4578 * @param {string} authenticationFlowType New value.
4579 * @returns {void}
4580 */
4581 ;
4582
4583 _proto.setAuthenticationFlowType = function setAuthenticationFlowType(authenticationFlowType) {
4584 this.authenticationFlowType = authenticationFlowType;
4585 }
4586 /**
4587 * This is used for authenticating the user through the custom authentication flow.
4588 * @param {AuthenticationDetails} authDetails Contains the authentication data
4589 * @param {object} callback Result callback map.
4590 * @param {onFailure} callback.onFailure Called on any error.
4591 * @param {customChallenge} callback.customChallenge Custom challenge
4592 * response required to continue.
4593 * @param {authSuccess} callback.onSuccess Called on success with the new session.
4594 * @returns {void}
4595 */
4596 ;
4597
4598 _proto.initiateAuth = function initiateAuth(authDetails, callback) {
4599 var _this = this;
4600
4601 var authParameters = authDetails.getAuthParameters();
4602 authParameters.USERNAME = this.username;
4603 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
4604 var jsonReq = {
4605 AuthFlow: 'CUSTOM_AUTH',
4606 ClientId: this.pool.getClientId(),
4607 AuthParameters: authParameters,
4608 ClientMetadata: clientMetaData
4609 };
4610
4611 if (this.getUserContextData()) {
4612 jsonReq.UserContextData = this.getUserContextData();
4613 }
4614
4615 this.client.request('InitiateAuth', jsonReq, function (err, data) {
4616 if (err) {
4617 return callback.onFailure(err);
4618 }
4619
4620 var challengeName = data.ChallengeName;
4621 var challengeParameters = data.ChallengeParameters;
4622
4623 if (challengeName === 'CUSTOM_CHALLENGE') {
4624 _this.Session = data.Session;
4625 return callback.customChallenge(challengeParameters);
4626 }
4627
4628 _this.signInUserSession = _this.getCognitoUserSession(data.AuthenticationResult);
4629
4630 _this.cacheTokens();
4631
4632 return callback.onSuccess(_this.signInUserSession);
4633 });
4634 }
4635 /**
4636 * This is used for authenticating the user.
4637 * stuff
4638 * @param {AuthenticationDetails} authDetails Contains the authentication data
4639 * @param {object} callback Result callback map.
4640 * @param {onFailure} callback.onFailure Called on any error.
4641 * @param {newPasswordRequired} callback.newPasswordRequired new
4642 * password and any required attributes are required to continue
4643 * @param {mfaRequired} callback.mfaRequired MFA code
4644 * required to continue.
4645 * @param {customChallenge} callback.customChallenge Custom challenge
4646 * response required to continue.
4647 * @param {authSuccess} callback.onSuccess Called on success with the new session.
4648 * @returns {void}
4649 */
4650 ;
4651
4652 _proto.authenticateUser = function authenticateUser(authDetails, callback) {
4653 if (this.authenticationFlowType === 'USER_PASSWORD_AUTH') {
4654 return this.authenticateUserPlainUsernamePassword(authDetails, callback);
4655 } else if (this.authenticationFlowType === 'USER_SRP_AUTH' || this.authenticationFlowType === 'CUSTOM_AUTH') {
4656 return this.authenticateUserDefaultAuth(authDetails, callback);
4657 }
4658
4659 return callback.onFailure(new Error('Authentication flow type is invalid.'));
4660 }
4661 /**
4662 * PRIVATE ONLY: This is an internal only method and should not
4663 * be directly called by the consumers.
4664 * It calls the AuthenticationHelper for SRP related
4665 * stuff
4666 * @param {AuthenticationDetails} authDetails Contains the authentication data
4667 * @param {object} callback Result callback map.
4668 * @param {onFailure} callback.onFailure Called on any error.
4669 * @param {newPasswordRequired} callback.newPasswordRequired new
4670 * password and any required attributes are required to continue
4671 * @param {mfaRequired} callback.mfaRequired MFA code
4672 * required to continue.
4673 * @param {customChallenge} callback.customChallenge Custom challenge
4674 * response required to continue.
4675 * @param {authSuccess} callback.onSuccess Called on success with the new session.
4676 * @returns {void}
4677 */
4678 ;
4679
4680 _proto.authenticateUserDefaultAuth = function authenticateUserDefaultAuth(authDetails, callback) {
4681 var _this2 = this;
4682
4683 var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_6__AuthenticationHelper__["a" /* default */](this.pool.getUserPoolId().split('_')[1]);
4684 var dateHelper = new __WEBPACK_IMPORTED_MODULE_11__DateHelper__["a" /* default */]();
4685 var serverBValue;
4686 var salt;
4687 var authParameters = {};
4688
4689 if (this.deviceKey != null) {
4690 authParameters.DEVICE_KEY = this.deviceKey;
4691 }
4692
4693 authParameters.USERNAME = this.username;
4694 authenticationHelper.getLargeAValue(function (errOnAValue, aValue) {
4695 // getLargeAValue callback start
4696 if (errOnAValue) {
4697 callback.onFailure(errOnAValue);
4698 }
4699
4700 authParameters.SRP_A = aValue.toString(16);
4701
4702 if (_this2.authenticationFlowType === 'CUSTOM_AUTH') {
4703 authParameters.CHALLENGE_NAME = 'SRP_A';
4704 }
4705
4706 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
4707 var jsonReq = {
4708 AuthFlow: _this2.authenticationFlowType,
4709 ClientId: _this2.pool.getClientId(),
4710 AuthParameters: authParameters,
4711 ClientMetadata: clientMetaData
4712 };
4713
4714 if (_this2.getUserContextData(_this2.username)) {
4715 jsonReq.UserContextData = _this2.getUserContextData(_this2.username);
4716 }
4717
4718 _this2.client.request('InitiateAuth', jsonReq, function (err, data) {
4719 if (err) {
4720 return callback.onFailure(err);
4721 }
4722
4723 var challengeParameters = data.ChallengeParameters;
4724 _this2.username = challengeParameters.USER_ID_FOR_SRP;
4725 serverBValue = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](challengeParameters.SRP_B, 16);
4726 salt = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](challengeParameters.SALT, 16);
4727
4728 _this2.getCachedDeviceKeyAndPassword();
4729
4730 authenticationHelper.getPasswordAuthenticationKey(_this2.username, authDetails.getPassword(), serverBValue, salt, function (errOnHkdf, hkdf) {
4731 // getPasswordAuthenticationKey callback start
4732 if (errOnHkdf) {
4733 callback.onFailure(errOnHkdf);
4734 }
4735
4736 var dateNow = dateHelper.getNowString();
4737 var message = __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.create(__WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].concat([__WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(_this2.pool.getUserPoolId().split('_')[1], 'utf8'), __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(_this2.username, 'utf8'), __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(challengeParameters.SECRET_BLOCK, 'base64'), __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(dateNow, 'utf8')]));
4738 var key = __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.create(hkdf);
4739 var signatureString = __WEBPACK_IMPORTED_MODULE_3_crypto_js_enc_base64___default.a.stringify(__WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256___default()(message, key));
4740 var challengeResponses = {};
4741 challengeResponses.USERNAME = _this2.username;
4742 challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK;
4743 challengeResponses.TIMESTAMP = dateNow;
4744 challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString;
4745
4746 if (_this2.deviceKey != null) {
4747 challengeResponses.DEVICE_KEY = _this2.deviceKey;
4748 }
4749
4750 var respondToAuthChallenge = function respondToAuthChallenge(challenge, challengeCallback) {
4751 return _this2.client.request('RespondToAuthChallenge', challenge, function (errChallenge, dataChallenge) {
4752 if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) {
4753 challengeResponses.DEVICE_KEY = null;
4754 _this2.deviceKey = null;
4755 _this2.randomPassword = null;
4756 _this2.deviceGroupKey = null;
4757
4758 _this2.clearCachedDeviceKeyAndPassword();
4759
4760 return respondToAuthChallenge(challenge, challengeCallback);
4761 }
4762
4763 return challengeCallback(errChallenge, dataChallenge);
4764 });
4765 };
4766
4767 var jsonReqResp = {
4768 ChallengeName: 'PASSWORD_VERIFIER',
4769 ClientId: _this2.pool.getClientId(),
4770 ChallengeResponses: challengeResponses,
4771 Session: data.Session,
4772 ClientMetadata: clientMetaData
4773 };
4774
4775 if (_this2.getUserContextData()) {
4776 jsonReqResp.UserContextData = _this2.getUserContextData();
4777 }
4778
4779 respondToAuthChallenge(jsonReqResp, function (errAuthenticate, dataAuthenticate) {
4780 if (errAuthenticate) {
4781 return callback.onFailure(errAuthenticate);
4782 }
4783
4784 return _this2.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback);
4785 });
4786 return undefined; // getPasswordAuthenticationKey callback end
4787 });
4788 return undefined;
4789 }); // getLargeAValue callback end
4790
4791 });
4792 }
4793 /**
4794 * PRIVATE ONLY: This is an internal only method and should not
4795 * be directly called by the consumers.
4796 * @param {AuthenticationDetails} authDetails Contains the authentication data.
4797 * @param {object} callback Result callback map.
4798 * @param {onFailure} callback.onFailure Called on any error.
4799 * @param {mfaRequired} callback.mfaRequired MFA code
4800 * required to continue.
4801 * @param {authSuccess} callback.onSuccess Called on success with the new session.
4802 * @returns {void}
4803 */
4804 ;
4805
4806 _proto.authenticateUserPlainUsernamePassword = function authenticateUserPlainUsernamePassword(authDetails, callback) {
4807 var _this3 = this;
4808
4809 var authParameters = {};
4810 authParameters.USERNAME = this.username;
4811 authParameters.PASSWORD = authDetails.getPassword();
4812
4813 if (!authParameters.PASSWORD) {
4814 callback.onFailure(new Error('PASSWORD parameter is required'));
4815 return;
4816 }
4817
4818 var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_6__AuthenticationHelper__["a" /* default */](this.pool.getUserPoolId().split('_')[1]);
4819 this.getCachedDeviceKeyAndPassword();
4820
4821 if (this.deviceKey != null) {
4822 authParameters.DEVICE_KEY = this.deviceKey;
4823 }
4824
4825 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
4826 var jsonReq = {
4827 AuthFlow: 'USER_PASSWORD_AUTH',
4828 ClientId: this.pool.getClientId(),
4829 AuthParameters: authParameters,
4830 ClientMetadata: clientMetaData
4831 };
4832
4833 if (this.getUserContextData(this.username)) {
4834 jsonReq.UserContextData = this.getUserContextData(this.username);
4835 } // USER_PASSWORD_AUTH happens in a single round-trip: client sends userName and password,
4836 // Cognito UserPools verifies password and returns tokens.
4837
4838
4839 this.client.request('InitiateAuth', jsonReq, function (err, authResult) {
4840 if (err) {
4841 return callback.onFailure(err);
4842 }
4843
4844 return _this3.authenticateUserInternal(authResult, authenticationHelper, callback);
4845 });
4846 }
4847 /**
4848 * PRIVATE ONLY: This is an internal only method and should not
4849 * be directly called by the consumers.
4850 * @param {object} dataAuthenticate authentication data
4851 * @param {object} authenticationHelper helper created
4852 * @param {callback} callback passed on from caller
4853 * @returns {void}
4854 */
4855 ;
4856
4857 _proto.authenticateUserInternal = function authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) {
4858 var _this4 = this;
4859
4860 var challengeName = dataAuthenticate.ChallengeName;
4861 var challengeParameters = dataAuthenticate.ChallengeParameters;
4862
4863 if (challengeName === 'SMS_MFA') {
4864 this.Session = dataAuthenticate.Session;
4865 return callback.mfaRequired(challengeName, challengeParameters);
4866 }
4867
4868 if (challengeName === 'SELECT_MFA_TYPE') {
4869 this.Session = dataAuthenticate.Session;
4870 return callback.selectMFAType(challengeName, challengeParameters);
4871 }
4872
4873 if (challengeName === 'MFA_SETUP') {
4874 this.Session = dataAuthenticate.Session;
4875 return callback.mfaSetup(challengeName, challengeParameters);
4876 }
4877
4878 if (challengeName === 'SOFTWARE_TOKEN_MFA') {
4879 this.Session = dataAuthenticate.Session;
4880 return callback.totpRequired(challengeName, challengeParameters);
4881 }
4882
4883 if (challengeName === 'CUSTOM_CHALLENGE') {
4884 this.Session = dataAuthenticate.Session;
4885 return callback.customChallenge(challengeParameters);
4886 }
4887
4888 if (challengeName === 'NEW_PASSWORD_REQUIRED') {
4889 this.Session = dataAuthenticate.Session;
4890 var userAttributes = null;
4891 var rawRequiredAttributes = null;
4892 var requiredAttributes = [];
4893 var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix();
4894
4895 if (challengeParameters) {
4896 userAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.userAttributes);
4897 rawRequiredAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.requiredAttributes);
4898 }
4899
4900 if (rawRequiredAttributes) {
4901 for (var i = 0; i < rawRequiredAttributes.length; i++) {
4902 requiredAttributes[i] = rawRequiredAttributes[i].substr(userAttributesPrefix.length);
4903 }
4904 }
4905
4906 return callback.newPasswordRequired(userAttributes, requiredAttributes);
4907 }
4908
4909 if (challengeName === 'DEVICE_SRP_AUTH') {
4910 this.getDeviceResponse(callback);
4911 return undefined;
4912 }
4913
4914 this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
4915 this.challengeName = challengeName;
4916 this.cacheTokens();
4917 var newDeviceMetadata = dataAuthenticate.AuthenticationResult.NewDeviceMetadata;
4918
4919 if (newDeviceMetadata == null) {
4920 return callback.onSuccess(this.signInUserSession);
4921 }
4922
4923 authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) {
4924 if (errGenHash) {
4925 return callback.onFailure(errGenHash);
4926 }
4927
4928 var deviceSecretVerifierConfig = {
4929 Salt: __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'),
4930 PasswordVerifier: __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64')
4931 };
4932 _this4.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier;
4933 _this4.deviceGroupKey = newDeviceMetadata.DeviceGroupKey;
4934 _this4.randomPassword = authenticationHelper.getRandomPassword();
4935
4936 _this4.client.request('ConfirmDevice', {
4937 DeviceKey: newDeviceMetadata.DeviceKey,
4938 AccessToken: _this4.signInUserSession.getAccessToken().getJwtToken(),
4939 DeviceSecretVerifierConfig: deviceSecretVerifierConfig,
4940 DeviceName: userAgent
4941 }, function (errConfirm, dataConfirm) {
4942 if (errConfirm) {
4943 return callback.onFailure(errConfirm);
4944 }
4945
4946 _this4.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey;
4947
4948 _this4.cacheDeviceKeyAndPassword();
4949
4950 if (dataConfirm.UserConfirmationNecessary === true) {
4951 return callback.onSuccess(_this4.signInUserSession, dataConfirm.UserConfirmationNecessary);
4952 }
4953
4954 return callback.onSuccess(_this4.signInUserSession);
4955 });
4956
4957 return undefined;
4958 });
4959 return undefined;
4960 }
4961 /**
4962 * This method is user to complete the NEW_PASSWORD_REQUIRED challenge.
4963 * Pass the new password with any new user attributes to be updated.
4964 * User attribute keys must be of format userAttributes.<attribute_name>.
4965 * @param {string} newPassword new password for this user
4966 * @param {object} requiredAttributeData map with values for all required attributes
4967 * @param {object} callback Result callback map.
4968 * @param {onFailure} callback.onFailure Called on any error.
4969 * @param {mfaRequired} callback.mfaRequired MFA code required to continue.
4970 * @param {customChallenge} callback.customChallenge Custom challenge
4971 * response required to continue.
4972 * @param {authSuccess} callback.onSuccess Called on success with the new session.
4973 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
4974 * @returns {void}
4975 */
4976 ;
4977
4978 _proto.completeNewPasswordChallenge = function completeNewPasswordChallenge(newPassword, requiredAttributeData, callback, clientMetadata) {
4979 var _this5 = this;
4980
4981 if (!newPassword) {
4982 return callback.onFailure(new Error('New password is required.'));
4983 }
4984
4985 var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_6__AuthenticationHelper__["a" /* default */](this.pool.getUserPoolId().split('_')[1]);
4986 var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix();
4987 var finalUserAttributes = {};
4988
4989 if (requiredAttributeData) {
4990 Object.keys(requiredAttributeData).forEach(function (key) {
4991 finalUserAttributes[userAttributesPrefix + key] = requiredAttributeData[key];
4992 });
4993 }
4994
4995 finalUserAttributes.NEW_PASSWORD = newPassword;
4996 finalUserAttributes.USERNAME = this.username;
4997 var jsonReq = {
4998 ChallengeName: 'NEW_PASSWORD_REQUIRED',
4999 ClientId: this.pool.getClientId(),
5000 ChallengeResponses: finalUserAttributes,
5001 Session: this.Session,
5002 ClientMetadata: clientMetadata
5003 };
5004
5005 if (this.getUserContextData()) {
5006 jsonReq.UserContextData = this.getUserContextData();
5007 }
5008
5009 this.client.request('RespondToAuthChallenge', jsonReq, function (errAuthenticate, dataAuthenticate) {
5010 if (errAuthenticate) {
5011 return callback.onFailure(errAuthenticate);
5012 }
5013
5014 return _this5.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback);
5015 });
5016 return undefined;
5017 }
5018 /**
5019 * This is used to get a session using device authentication. It is called at the end of user
5020 * authentication
5021 *
5022 * @param {object} callback Result callback map.
5023 * @param {onFailure} callback.onFailure Called on any error.
5024 * @param {authSuccess} callback.onSuccess Called on success with the new session.
5025 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5026 * @returns {void}
5027 * @private
5028 */
5029 ;
5030
5031 _proto.getDeviceResponse = function getDeviceResponse(callback, clientMetadata) {
5032 var _this6 = this;
5033
5034 var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_6__AuthenticationHelper__["a" /* default */](this.deviceGroupKey);
5035 var dateHelper = new __WEBPACK_IMPORTED_MODULE_11__DateHelper__["a" /* default */]();
5036 var authParameters = {};
5037 authParameters.USERNAME = this.username;
5038 authParameters.DEVICE_KEY = this.deviceKey;
5039 authenticationHelper.getLargeAValue(function (errAValue, aValue) {
5040 // getLargeAValue callback start
5041 if (errAValue) {
5042 callback.onFailure(errAValue);
5043 }
5044
5045 authParameters.SRP_A = aValue.toString(16);
5046 var jsonReq = {
5047 ChallengeName: 'DEVICE_SRP_AUTH',
5048 ClientId: _this6.pool.getClientId(),
5049 ChallengeResponses: authParameters,
5050 ClientMetadata: clientMetadata
5051 };
5052
5053 if (_this6.getUserContextData()) {
5054 jsonReq.UserContextData = _this6.getUserContextData();
5055 }
5056
5057 _this6.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
5058 if (err) {
5059 return callback.onFailure(err);
5060 }
5061
5062 var challengeParameters = data.ChallengeParameters;
5063 var serverBValue = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](challengeParameters.SRP_B, 16);
5064 var salt = new __WEBPACK_IMPORTED_MODULE_5__BigInteger__["a" /* default */](challengeParameters.SALT, 16);
5065 authenticationHelper.getPasswordAuthenticationKey(_this6.deviceKey, _this6.randomPassword, serverBValue, salt, function (errHkdf, hkdf) {
5066 // getPasswordAuthenticationKey callback start
5067 if (errHkdf) {
5068 return callback.onFailure(errHkdf);
5069 }
5070
5071 var dateNow = dateHelper.getNowString();
5072 var message = __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.create(__WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].concat([__WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(_this6.deviceGroupKey, 'utf8'), __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(_this6.deviceKey, 'utf8'), __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(challengeParameters.SECRET_BLOCK, 'base64'), __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(dateNow, 'utf8')]));
5073 var key = __WEBPACK_IMPORTED_MODULE_1_crypto_js_core___default.a.lib.WordArray.create(hkdf);
5074 var signatureString = __WEBPACK_IMPORTED_MODULE_3_crypto_js_enc_base64___default.a.stringify(__WEBPACK_IMPORTED_MODULE_4_crypto_js_hmac_sha256___default()(message, key));
5075 var challengeResponses = {};
5076 challengeResponses.USERNAME = _this6.username;
5077 challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK;
5078 challengeResponses.TIMESTAMP = dateNow;
5079 challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString;
5080 challengeResponses.DEVICE_KEY = _this6.deviceKey;
5081 var jsonReqResp = {
5082 ChallengeName: 'DEVICE_PASSWORD_VERIFIER',
5083 ClientId: _this6.pool.getClientId(),
5084 ChallengeResponses: challengeResponses,
5085 Session: data.Session
5086 };
5087
5088 if (_this6.getUserContextData()) {
5089 jsonReqResp.UserContextData = _this6.getUserContextData();
5090 }
5091
5092 _this6.client.request('RespondToAuthChallenge', jsonReqResp, function (errAuthenticate, dataAuthenticate) {
5093 if (errAuthenticate) {
5094 return callback.onFailure(errAuthenticate);
5095 }
5096
5097 _this6.signInUserSession = _this6.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
5098
5099 _this6.cacheTokens();
5100
5101 return callback.onSuccess(_this6.signInUserSession);
5102 });
5103
5104 return undefined; // getPasswordAuthenticationKey callback end
5105 });
5106 return undefined;
5107 }); // getLargeAValue callback end
5108
5109 });
5110 }
5111 /**
5112 * This is used for a certain user to confirm the registration by using a confirmation code
5113 * @param {string} confirmationCode Code entered by user.
5114 * @param {bool} forceAliasCreation Allow migrating from an existing email / phone number.
5115 * @param {nodeCallback<string>} callback Called on success or error.
5116 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5117 * @returns {void}
5118 */
5119 ;
5120
5121 _proto.confirmRegistration = function confirmRegistration(confirmationCode, forceAliasCreation, callback, clientMetadata) {
5122 var jsonReq = {
5123 ClientId: this.pool.getClientId(),
5124 ConfirmationCode: confirmationCode,
5125 Username: this.username,
5126 ForceAliasCreation: forceAliasCreation,
5127 ClientMetadata: clientMetadata
5128 };
5129
5130 if (this.getUserContextData()) {
5131 jsonReq.UserContextData = this.getUserContextData();
5132 }
5133
5134 this.client.request('ConfirmSignUp', jsonReq, function (err) {
5135 if (err) {
5136 return callback(err, null);
5137 }
5138
5139 return callback(null, 'SUCCESS');
5140 });
5141 }
5142 /**
5143 * This is used by the user once he has the responses to a custom challenge
5144 * @param {string} answerChallenge The custom challenge answer.
5145 * @param {object} callback Result callback map.
5146 * @param {onFailure} callback.onFailure Called on any error.
5147 * @param {customChallenge} callback.customChallenge
5148 * Custom challenge response required to continue.
5149 * @param {authSuccess} callback.onSuccess Called on success with the new session.
5150 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5151 * @returns {void}
5152 */
5153 ;
5154
5155 _proto.sendCustomChallengeAnswer = function sendCustomChallengeAnswer(answerChallenge, callback, clientMetadata) {
5156 var _this7 = this;
5157
5158 var challengeResponses = {};
5159 challengeResponses.USERNAME = this.username;
5160 challengeResponses.ANSWER = answerChallenge;
5161 var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_6__AuthenticationHelper__["a" /* default */](this.pool.getUserPoolId().split('_')[1]);
5162 this.getCachedDeviceKeyAndPassword();
5163
5164 if (this.deviceKey != null) {
5165 challengeResponses.DEVICE_KEY = this.deviceKey;
5166 }
5167
5168 var jsonReq = {
5169 ChallengeName: 'CUSTOM_CHALLENGE',
5170 ChallengeResponses: challengeResponses,
5171 ClientId: this.pool.getClientId(),
5172 Session: this.Session,
5173 ClientMetadata: clientMetadata
5174 };
5175
5176 if (this.getUserContextData()) {
5177 jsonReq.UserContextData = this.getUserContextData();
5178 }
5179
5180 this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
5181 if (err) {
5182 return callback.onFailure(err);
5183 }
5184
5185 return _this7.authenticateUserInternal(data, authenticationHelper, callback);
5186 });
5187 }
5188 /**
5189 * This is used by the user once he has an MFA code
5190 * @param {string} confirmationCode The MFA code entered by the user.
5191 * @param {object} callback Result callback map.
5192 * @param {string} mfaType The mfa we are replying to.
5193 * @param {onFailure} callback.onFailure Called on any error.
5194 * @param {authSuccess} callback.onSuccess Called on success with the new session.
5195 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5196 * @returns {void}
5197 */
5198 ;
5199
5200 _proto.sendMFACode = function sendMFACode(confirmationCode, callback, mfaType, clientMetadata) {
5201 var _this8 = this;
5202
5203 var challengeResponses = {};
5204 challengeResponses.USERNAME = this.username;
5205 challengeResponses.SMS_MFA_CODE = confirmationCode;
5206 var mfaTypeSelection = mfaType || 'SMS_MFA';
5207
5208 if (mfaTypeSelection === 'SOFTWARE_TOKEN_MFA') {
5209 challengeResponses.SOFTWARE_TOKEN_MFA_CODE = confirmationCode;
5210 }
5211
5212 if (this.deviceKey != null) {
5213 challengeResponses.DEVICE_KEY = this.deviceKey;
5214 }
5215
5216 var jsonReq = {
5217 ChallengeName: mfaTypeSelection,
5218 ChallengeResponses: challengeResponses,
5219 ClientId: this.pool.getClientId(),
5220 Session: this.Session,
5221 ClientMetadata: clientMetadata
5222 };
5223
5224 if (this.getUserContextData()) {
5225 jsonReq.UserContextData = this.getUserContextData();
5226 }
5227
5228 this.client.request('RespondToAuthChallenge', jsonReq, function (err, dataAuthenticate) {
5229 if (err) {
5230 return callback.onFailure(err);
5231 }
5232
5233 var challengeName = dataAuthenticate.ChallengeName;
5234
5235 if (challengeName === 'DEVICE_SRP_AUTH') {
5236 _this8.getDeviceResponse(callback);
5237
5238 return undefined;
5239 }
5240
5241 _this8.signInUserSession = _this8.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
5242
5243 _this8.cacheTokens();
5244
5245 if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) {
5246 return callback.onSuccess(_this8.signInUserSession);
5247 }
5248
5249 var authenticationHelper = new __WEBPACK_IMPORTED_MODULE_6__AuthenticationHelper__["a" /* default */](_this8.pool.getUserPoolId().split('_')[1]);
5250 authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) {
5251 if (errGenHash) {
5252 return callback.onFailure(errGenHash);
5253 }
5254
5255 var deviceSecretVerifierConfig = {
5256 Salt: __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'),
5257 PasswordVerifier: __WEBPACK_IMPORTED_MODULE_0_buffer__["Buffer"].from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64')
5258 };
5259 _this8.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier;
5260 _this8.deviceGroupKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey;
5261 _this8.randomPassword = authenticationHelper.getRandomPassword();
5262
5263 _this8.client.request('ConfirmDevice', {
5264 DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey,
5265 AccessToken: _this8.signInUserSession.getAccessToken().getJwtToken(),
5266 DeviceSecretVerifierConfig: deviceSecretVerifierConfig,
5267 DeviceName: userAgent
5268 }, function (errConfirm, dataConfirm) {
5269 if (errConfirm) {
5270 return callback.onFailure(errConfirm);
5271 }
5272
5273 _this8.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey;
5274
5275 _this8.cacheDeviceKeyAndPassword();
5276
5277 if (dataConfirm.UserConfirmationNecessary === true) {
5278 return callback.onSuccess(_this8.signInUserSession, dataConfirm.UserConfirmationNecessary);
5279 }
5280
5281 return callback.onSuccess(_this8.signInUserSession);
5282 });
5283
5284 return undefined;
5285 });
5286 return undefined;
5287 });
5288 }
5289 /**
5290 * This is used by an authenticated user to change the current password
5291 * @param {string} oldUserPassword The current password.
5292 * @param {string} newUserPassword The requested new password.
5293 * @param {nodeCallback<string>} callback Called on success or error.
5294 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5295 * @returns {void}
5296 */
5297 ;
5298
5299 _proto.changePassword = function changePassword(oldUserPassword, newUserPassword, callback, clientMetadata) {
5300 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
5301 return callback(new Error('User is not authenticated'), null);
5302 }
5303
5304 this.client.request('ChangePassword', {
5305 PreviousPassword: oldUserPassword,
5306 ProposedPassword: newUserPassword,
5307 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
5308 ClientMetadata: clientMetadata
5309 }, function (err) {
5310 if (err) {
5311 return callback(err, null);
5312 }
5313
5314 return callback(null, 'SUCCESS');
5315 });
5316 return undefined;
5317 }
5318 /**
5319 * This is used by an authenticated user to enable MFA for itself
5320 * @deprecated
5321 * @param {nodeCallback<string>} callback Called on success or error.
5322 * @returns {void}
5323 */
5324 ;
5325
5326 _proto.enableMFA = function enableMFA(callback) {
5327 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
5328 return callback(new Error('User is not authenticated'), null);
5329 }
5330
5331 var mfaOptions = [];
5332 var mfaEnabled = {
5333 DeliveryMedium: 'SMS',
5334 AttributeName: 'phone_number'
5335 };
5336 mfaOptions.push(mfaEnabled);
5337 this.client.request('SetUserSettings', {
5338 MFAOptions: mfaOptions,
5339 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
5340 }, function (err) {
5341 if (err) {
5342 return callback(err, null);
5343 }
5344
5345 return callback(null, 'SUCCESS');
5346 });
5347 return undefined;
5348 }
5349 /**
5350 * This is used by an authenticated user to enable MFA for itself
5351 * @param {IMfaSettings} smsMfaSettings the sms mfa settings
5352 * @param {IMFASettings} softwareTokenMfaSettings the software token mfa settings
5353 * @param {nodeCallback<string>} callback Called on success or error.
5354 * @returns {void}
5355 */
5356 ;
5357
5358 _proto.setUserMfaPreference = function setUserMfaPreference(smsMfaSettings, softwareTokenMfaSettings, callback) {
5359 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
5360 return callback(new Error('User is not authenticated'), null);
5361 }
5362
5363 this.client.request('SetUserMFAPreference', {
5364 SMSMfaSettings: smsMfaSettings,
5365 SoftwareTokenMfaSettings: softwareTokenMfaSettings,
5366 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
5367 }, function (err) {
5368 if (err) {
5369 return callback(err, null);
5370 }
5371
5372 return callback(null, 'SUCCESS');
5373 });
5374 return undefined;
5375 }
5376 /**
5377 * This is used by an authenticated user to disable MFA for itself
5378 * @deprecated
5379 * @param {nodeCallback<string>} callback Called on success or error.
5380 * @returns {void}
5381 */
5382 ;
5383
5384 _proto.disableMFA = function disableMFA(callback) {
5385 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
5386 return callback(new Error('User is not authenticated'), null);
5387 }
5388
5389 var mfaOptions = [];
5390 this.client.request('SetUserSettings', {
5391 MFAOptions: mfaOptions,
5392 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
5393 }, function (err) {
5394 if (err) {
5395 return callback(err, null);
5396 }
5397
5398 return callback(null, 'SUCCESS');
5399 });
5400 return undefined;
5401 }
5402 /**
5403 * This is used by an authenticated user to delete itself
5404 * @param {nodeCallback<string>} callback Called on success or error.
5405 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5406 * @returns {void}
5407 */
5408 ;
5409
5410 _proto.deleteUser = function deleteUser(callback, clientMetadata) {
5411 var _this9 = this;
5412
5413 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
5414 return callback(new Error('User is not authenticated'), null);
5415 }
5416
5417 this.client.request('DeleteUser', {
5418 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
5419 ClientMetadata: clientMetadata
5420 }, function (err) {
5421 if (err) {
5422 return callback(err, null);
5423 }
5424
5425 _this9.clearCachedUser();
5426
5427 return callback(null, 'SUCCESS');
5428 });
5429 return undefined;
5430 }
5431 /**
5432 * @typedef {CognitoUserAttribute | { Name:string, Value:string }} AttributeArg
5433 */
5434
5435 /**
5436 * This is used by an authenticated user to change a list of attributes
5437 * @param {AttributeArg[]} attributes A list of the new user attributes.
5438 * @param {nodeCallback<string>} callback Called on success or error.
5439 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5440 * @returns {void}
5441 */
5442 ;
5443
5444 _proto.updateAttributes = function updateAttributes(attributes, callback, clientMetadata) {
5445 var _this10 = this;
5446
5447 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
5448 return callback(new Error('User is not authenticated'), null);
5449 }
5450
5451 this.client.request('UpdateUserAttributes', {
5452 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
5453 UserAttributes: attributes,
5454 ClientMetadata: clientMetadata
5455 }, function (err) {
5456 if (err) {
5457 return callback(err, null);
5458 } // update cached user
5459
5460
5461 return _this10.getUserData(function () {
5462 return callback(null, 'SUCCESS');
5463 }, {
5464 bypassCache: true
5465 });
5466 });
5467 return undefined;
5468 }
5469 /**
5470 * This is used by an authenticated user to get a list of attributes
5471 * @param {nodeCallback<CognitoUserAttribute[]>} callback Called on success or error.
5472 * @returns {void}
5473 */
5474 ;
5475
5476 _proto.getUserAttributes = function getUserAttributes(callback) {
5477 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
5478 return callback(new Error('User is not authenticated'), null);
5479 }
5480
5481 this.client.request('GetUser', {
5482 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
5483 }, function (err, userData) {
5484 if (err) {
5485 return callback(err, null);
5486 }
5487
5488 var attributeList = [];
5489
5490 for (var i = 0; i < userData.UserAttributes.length; i++) {
5491 var attribute = {
5492 Name: userData.UserAttributes[i].Name,
5493 Value: userData.UserAttributes[i].Value
5494 };
5495 var userAttribute = new __WEBPACK_IMPORTED_MODULE_12__CognitoUserAttribute__["a" /* default */](attribute);
5496 attributeList.push(userAttribute);
5497 }
5498
5499 return callback(null, attributeList);
5500 });
5501 return undefined;
5502 }
5503 /**
5504 * This is used by an authenticated user to get the MFAOptions
5505 * @param {nodeCallback<MFAOptions>} callback Called on success or error.
5506 * @returns {void}
5507 */
5508 ;
5509
5510 _proto.getMFAOptions = function getMFAOptions(callback) {
5511 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
5512 return callback(new Error('User is not authenticated'), null);
5513 }
5514
5515 this.client.request('GetUser', {
5516 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
5517 }, function (err, userData) {
5518 if (err) {
5519 return callback(err, null);
5520 }
5521
5522 return callback(null, userData.MFAOptions);
5523 });
5524 return undefined;
5525 }
5526 /**
5527 * PRIVATE ONLY: This is an internal only method and should not
5528 * be directly called by the consumers.
5529 */
5530 ;
5531
5532 _proto.createGetUserRequest = function createGetUserRequest() {
5533 return this.client.promisifyRequest('GetUser', {
5534 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
5535 });
5536 }
5537 /**
5538 * PRIVATE ONLY: This is an internal only method and should not
5539 * be directly called by the consumers.
5540 */
5541 ;
5542
5543 _proto.refreshSessionIfPossible = function refreshSessionIfPossible() {
5544 var _this11 = this;
5545
5546 // best effort, if not possible
5547 return new Promise(function (resolve) {
5548 var refresh = _this11.signInUserSession.getRefreshToken();
5549
5550 if (refresh && refresh.getToken()) {
5551 _this11.refreshSession(refresh, resolve);
5552 } else {
5553 resolve();
5554 }
5555 });
5556 }
5557 /**
5558 * This is used by an authenticated users to get the userData
5559 * @param {nodeCallback<UserData>} callback Called on success or error.
5560 * @param {GetUserDataOptions} params
5561 * @returns {void}
5562 */
5563 ;
5564
5565 _proto.getUserData = function getUserData(callback, params) {
5566 var _this12 = this;
5567
5568 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
5569 this.clearCachedUserData();
5570 return callback(new Error('User is not authenticated'), null);
5571 }
5572
5573 var userData = this.getUserDataFromCache();
5574
5575 if (!userData) {
5576 this.fetchUserData().then(function (data) {
5577 callback(null, data);
5578 })["catch"](callback);
5579 return;
5580 }
5581
5582 if (this.isFetchUserDataAndTokenRequired(params)) {
5583 this.fetchUserData().then(function (data) {
5584 return _this12.refreshSessionIfPossible().then(function () {
5585 return data;
5586 });
5587 }).then(function (data) {
5588 return callback(null, data);
5589 })["catch"](callback);
5590 return;
5591 }
5592
5593 try {
5594 callback(null, JSON.parse(userData));
5595 return;
5596 } catch (err) {
5597 this.clearCachedUserData();
5598 callback(err, null);
5599 return;
5600 }
5601 }
5602 /**
5603 *
5604 * PRIVATE ONLY: This is an internal only method and should not
5605 * be directly called by the consumers.
5606 */
5607 ;
5608
5609 _proto.getUserDataFromCache = function getUserDataFromCache() {
5610 var userData = this.storage.getItem(this.userDataKey);
5611 return userData;
5612 }
5613 /**
5614 *
5615 * PRIVATE ONLY: This is an internal only method and should not
5616 * be directly called by the consumers.
5617 */
5618 ;
5619
5620 _proto.isFetchUserDataAndTokenRequired = function isFetchUserDataAndTokenRequired(params) {
5621 var _ref = params || {},
5622 _ref$bypassCache = _ref.bypassCache,
5623 bypassCache = _ref$bypassCache === void 0 ? false : _ref$bypassCache;
5624
5625 return bypassCache;
5626 }
5627 /**
5628 *
5629 * PRIVATE ONLY: This is an internal only method and should not
5630 * be directly called by the consumers.
5631 */
5632 ;
5633
5634 _proto.fetchUserData = function fetchUserData() {
5635 var _this13 = this;
5636
5637 return this.createGetUserRequest().then(function (data) {
5638 _this13.cacheUserData(data);
5639
5640 return data;
5641 });
5642 }
5643 /**
5644 * This is used by an authenticated user to delete a list of attributes
5645 * @param {string[]} attributeList Names of the attributes to delete.
5646 * @param {nodeCallback<string>} callback Called on success or error.
5647 * @returns {void}
5648 */
5649 ;
5650
5651 _proto.deleteAttributes = function deleteAttributes(attributeList, callback) {
5652 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
5653 return callback(new Error('User is not authenticated'), null);
5654 }
5655
5656 this.client.request('DeleteUserAttributes', {
5657 UserAttributeNames: attributeList,
5658 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
5659 }, function (err) {
5660 if (err) {
5661 return callback(err, null);
5662 }
5663
5664 return callback(null, 'SUCCESS');
5665 });
5666 return undefined;
5667 }
5668 /**
5669 * This is used by a user to resend a confirmation code
5670 * @param {nodeCallback<string>} callback Called on success or error.
5671 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5672 * @returns {void}
5673 */
5674 ;
5675
5676 _proto.resendConfirmationCode = function resendConfirmationCode(callback, clientMetadata) {
5677 var jsonReq = {
5678 ClientId: this.pool.getClientId(),
5679 Username: this.username,
5680 ClientMetadata: clientMetadata
5681 };
5682 this.client.request('ResendConfirmationCode', jsonReq, function (err, result) {
5683 if (err) {
5684 return callback(err, null);
5685 }
5686
5687 return callback(null, result);
5688 });
5689 }
5690 /**
5691 * This is used to get a session, either from the session object
5692 * or from the local storage, or by using a refresh token
5693 *
5694 * @param {nodeCallback<CognitoUserSession>} callback Called on success or error.
5695 * @returns {void}
5696 */
5697 ;
5698
5699 _proto.getSession = function getSession(callback) {
5700 if (this.username == null) {
5701 return callback(new Error('Username is null. Cannot retrieve a new session'), null);
5702 }
5703
5704 if (this.signInUserSession != null && this.signInUserSession.isValid()) {
5705 return callback(null, this.signInUserSession);
5706 }
5707
5708 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
5709 var idTokenKey = keyPrefix + ".idToken";
5710 var accessTokenKey = keyPrefix + ".accessToken";
5711 var refreshTokenKey = keyPrefix + ".refreshToken";
5712 var clockDriftKey = keyPrefix + ".clockDrift";
5713
5714 if (this.storage.getItem(idTokenKey)) {
5715 var idToken = new __WEBPACK_IMPORTED_MODULE_8__CognitoIdToken__["a" /* default */]({
5716 IdToken: this.storage.getItem(idTokenKey)
5717 });
5718 var accessToken = new __WEBPACK_IMPORTED_MODULE_7__CognitoAccessToken__["a" /* default */]({
5719 AccessToken: this.storage.getItem(accessTokenKey)
5720 });
5721 var refreshToken = new __WEBPACK_IMPORTED_MODULE_9__CognitoRefreshToken__["a" /* default */]({
5722 RefreshToken: this.storage.getItem(refreshTokenKey)
5723 });
5724 var clockDrift = parseInt(this.storage.getItem(clockDriftKey), 0) || 0;
5725 var sessionData = {
5726 IdToken: idToken,
5727 AccessToken: accessToken,
5728 RefreshToken: refreshToken,
5729 ClockDrift: clockDrift
5730 };
5731 var cachedSession = new __WEBPACK_IMPORTED_MODULE_10__CognitoUserSession__["a" /* default */](sessionData);
5732
5733 if (cachedSession.isValid()) {
5734 this.signInUserSession = cachedSession;
5735 return callback(null, this.signInUserSession);
5736 }
5737
5738 if (!refreshToken.getToken()) {
5739 return callback(new Error('Cannot retrieve a new session. Please authenticate.'), null);
5740 }
5741
5742 this.refreshSession(refreshToken, callback);
5743 } else {
5744 callback(new Error('Local storage is missing an ID Token, Please authenticate'), null);
5745 }
5746
5747 return undefined;
5748 }
5749 /**
5750 * This uses the refreshToken to retrieve a new session
5751 * @param {CognitoRefreshToken} refreshToken A previous session's refresh token.
5752 * @param {nodeCallback<CognitoUserSession>} callback Called on success or error.
5753 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5754 * @returns {void}
5755 */
5756 ;
5757
5758 _proto.refreshSession = function refreshSession(refreshToken, callback, clientMetadata) {
5759 var _this14 = this;
5760
5761 var authParameters = {};
5762 authParameters.REFRESH_TOKEN = refreshToken.getToken();
5763 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
5764 var lastUserKey = keyPrefix + ".LastAuthUser";
5765
5766 if (this.storage.getItem(lastUserKey)) {
5767 this.username = this.storage.getItem(lastUserKey);
5768 var deviceKeyKey = keyPrefix + "." + this.username + ".deviceKey";
5769 this.deviceKey = this.storage.getItem(deviceKeyKey);
5770 authParameters.DEVICE_KEY = this.deviceKey;
5771 }
5772
5773 var jsonReq = {
5774 ClientId: this.pool.getClientId(),
5775 AuthFlow: 'REFRESH_TOKEN_AUTH',
5776 AuthParameters: authParameters,
5777 ClientMetadata: clientMetadata
5778 };
5779
5780 if (this.getUserContextData()) {
5781 jsonReq.UserContextData = this.getUserContextData();
5782 }
5783
5784 this.client.request('InitiateAuth', jsonReq, function (err, authResult) {
5785 if (err) {
5786 if (err.code === 'NotAuthorizedException') {
5787 _this14.clearCachedUser();
5788 }
5789
5790 return callback(err, null);
5791 }
5792
5793 if (authResult) {
5794 var authenticationResult = authResult.AuthenticationResult;
5795
5796 if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) {
5797 authenticationResult.RefreshToken = refreshToken.getToken();
5798 }
5799
5800 _this14.signInUserSession = _this14.getCognitoUserSession(authenticationResult);
5801
5802 _this14.cacheTokens();
5803
5804 return callback(null, _this14.signInUserSession);
5805 }
5806
5807 return undefined;
5808 });
5809 }
5810 /**
5811 * This is used to save the session tokens to local storage
5812 * @returns {void}
5813 */
5814 ;
5815
5816 _proto.cacheTokens = function cacheTokens() {
5817 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
5818 var idTokenKey = keyPrefix + "." + this.username + ".idToken";
5819 var accessTokenKey = keyPrefix + "." + this.username + ".accessToken";
5820 var refreshTokenKey = keyPrefix + "." + this.username + ".refreshToken";
5821 var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift";
5822 var lastUserKey = keyPrefix + ".LastAuthUser";
5823 this.storage.setItem(idTokenKey, this.signInUserSession.getIdToken().getJwtToken());
5824 this.storage.setItem(accessTokenKey, this.signInUserSession.getAccessToken().getJwtToken());
5825 this.storage.setItem(refreshTokenKey, this.signInUserSession.getRefreshToken().getToken());
5826 this.storage.setItem(clockDriftKey, "" + this.signInUserSession.getClockDrift());
5827 this.storage.setItem(lastUserKey, this.username);
5828 }
5829 /**
5830 * This is to cache user data
5831 */
5832 ;
5833
5834 _proto.cacheUserData = function cacheUserData(userData) {
5835 this.storage.setItem(this.userDataKey, JSON.stringify(userData));
5836 }
5837 /**
5838 * This is to remove cached user data
5839 */
5840 ;
5841
5842 _proto.clearCachedUserData = function clearCachedUserData() {
5843 this.storage.removeItem(this.userDataKey);
5844 };
5845
5846 _proto.clearCachedUser = function clearCachedUser() {
5847 this.clearCachedTokens();
5848 this.clearCachedUserData();
5849 }
5850 /**
5851 * This is used to cache the device key and device group and device password
5852 * @returns {void}
5853 */
5854 ;
5855
5856 _proto.cacheDeviceKeyAndPassword = function cacheDeviceKeyAndPassword() {
5857 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
5858 var deviceKeyKey = keyPrefix + ".deviceKey";
5859 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
5860 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
5861 this.storage.setItem(deviceKeyKey, this.deviceKey);
5862 this.storage.setItem(randomPasswordKey, this.randomPassword);
5863 this.storage.setItem(deviceGroupKeyKey, this.deviceGroupKey);
5864 }
5865 /**
5866 * This is used to get current device key and device group and device password
5867 * @returns {void}
5868 */
5869 ;
5870
5871 _proto.getCachedDeviceKeyAndPassword = function getCachedDeviceKeyAndPassword() {
5872 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
5873 var deviceKeyKey = keyPrefix + ".deviceKey";
5874 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
5875 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
5876
5877 if (this.storage.getItem(deviceKeyKey)) {
5878 this.deviceKey = this.storage.getItem(deviceKeyKey);
5879 this.randomPassword = this.storage.getItem(randomPasswordKey);
5880 this.deviceGroupKey = this.storage.getItem(deviceGroupKeyKey);
5881 }
5882 }
5883 /**
5884 * This is used to clear the device key info from local storage
5885 * @returns {void}
5886 */
5887 ;
5888
5889 _proto.clearCachedDeviceKeyAndPassword = function clearCachedDeviceKeyAndPassword() {
5890 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
5891 var deviceKeyKey = keyPrefix + ".deviceKey";
5892 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
5893 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
5894 this.storage.removeItem(deviceKeyKey);
5895 this.storage.removeItem(randomPasswordKey);
5896 this.storage.removeItem(deviceGroupKeyKey);
5897 }
5898 /**
5899 * This is used to clear the session tokens from local storage
5900 * @returns {void}
5901 */
5902 ;
5903
5904 _proto.clearCachedTokens = function clearCachedTokens() {
5905 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
5906 var idTokenKey = keyPrefix + "." + this.username + ".idToken";
5907 var accessTokenKey = keyPrefix + "." + this.username + ".accessToken";
5908 var refreshTokenKey = keyPrefix + "." + this.username + ".refreshToken";
5909 var lastUserKey = keyPrefix + ".LastAuthUser";
5910 var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift";
5911 this.storage.removeItem(idTokenKey);
5912 this.storage.removeItem(accessTokenKey);
5913 this.storage.removeItem(refreshTokenKey);
5914 this.storage.removeItem(lastUserKey);
5915 this.storage.removeItem(clockDriftKey);
5916 }
5917 /**
5918 * This is used to build a user session from tokens retrieved in the authentication result
5919 * @param {object} authResult Successful auth response from server.
5920 * @returns {CognitoUserSession} The new user session.
5921 * @private
5922 */
5923 ;
5924
5925 _proto.getCognitoUserSession = function getCognitoUserSession(authResult) {
5926 var idToken = new __WEBPACK_IMPORTED_MODULE_8__CognitoIdToken__["a" /* default */](authResult);
5927 var accessToken = new __WEBPACK_IMPORTED_MODULE_7__CognitoAccessToken__["a" /* default */](authResult);
5928 var refreshToken = new __WEBPACK_IMPORTED_MODULE_9__CognitoRefreshToken__["a" /* default */](authResult);
5929 var sessionData = {
5930 IdToken: idToken,
5931 AccessToken: accessToken,
5932 RefreshToken: refreshToken
5933 };
5934 return new __WEBPACK_IMPORTED_MODULE_10__CognitoUserSession__["a" /* default */](sessionData);
5935 }
5936 /**
5937 * This is used to initiate a forgot password request
5938 * @param {object} callback Result callback map.
5939 * @param {onFailure} callback.onFailure Called on any error.
5940 * @param {inputVerificationCode?} callback.inputVerificationCode
5941 * Optional callback raised instead of onSuccess with response data.
5942 * @param {onSuccess} callback.onSuccess Called on success.
5943 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5944 * @returns {void}
5945 */
5946 ;
5947
5948 _proto.forgotPassword = function forgotPassword(callback, clientMetadata) {
5949 var jsonReq = {
5950 ClientId: this.pool.getClientId(),
5951 Username: this.username,
5952 ClientMetadata: clientMetadata
5953 };
5954
5955 if (this.getUserContextData()) {
5956 jsonReq.UserContextData = this.getUserContextData();
5957 }
5958
5959 this.client.request('ForgotPassword', jsonReq, function (err, data) {
5960 if (err) {
5961 return callback.onFailure(err);
5962 }
5963
5964 if (typeof callback.inputVerificationCode === 'function') {
5965 return callback.inputVerificationCode(data);
5966 }
5967
5968 return callback.onSuccess(data);
5969 });
5970 }
5971 /**
5972 * This is used to confirm a new password using a confirmationCode
5973 * @param {string} confirmationCode Code entered by user.
5974 * @param {string} newPassword Confirm new password.
5975 * @param {object} callback Result callback map.
5976 * @param {onFailure} callback.onFailure Called on any error.
5977 * @param {onSuccess<void>} callback.onSuccess Called on success.
5978 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
5979 * @returns {void}
5980 */
5981 ;
5982
5983 _proto.confirmPassword = function confirmPassword(confirmationCode, newPassword, callback, clientMetadata) {
5984 var jsonReq = {
5985 ClientId: this.pool.getClientId(),
5986 Username: this.username,
5987 ConfirmationCode: confirmationCode,
5988 Password: newPassword,
5989 ClientMetadata: clientMetadata
5990 };
5991
5992 if (this.getUserContextData()) {
5993 jsonReq.UserContextData = this.getUserContextData();
5994 }
5995
5996 this.client.request('ConfirmForgotPassword', jsonReq, function (err) {
5997 if (err) {
5998 return callback.onFailure(err);
5999 }
6000
6001 return callback.onSuccess();
6002 });
6003 }
6004 /**
6005 * This is used to initiate an attribute confirmation request
6006 * @param {string} attributeName User attribute that needs confirmation.
6007 * @param {object} callback Result callback map.
6008 * @param {onFailure} callback.onFailure Called on any error.
6009 * @param {inputVerificationCode} callback.inputVerificationCode Called on success.
6010 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
6011 * @returns {void}
6012 */
6013 ;
6014
6015 _proto.getAttributeVerificationCode = function getAttributeVerificationCode(attributeName, callback, clientMetadata) {
6016 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6017 return callback.onFailure(new Error('User is not authenticated'));
6018 }
6019
6020 this.client.request('GetUserAttributeVerificationCode', {
6021 AttributeName: attributeName,
6022 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6023 ClientMetadata: clientMetadata
6024 }, function (err, data) {
6025 if (err) {
6026 return callback.onFailure(err);
6027 }
6028
6029 if (typeof callback.inputVerificationCode === 'function') {
6030 return callback.inputVerificationCode(data);
6031 }
6032
6033 return callback.onSuccess();
6034 });
6035 return undefined;
6036 }
6037 /**
6038 * This is used to confirm an attribute using a confirmation code
6039 * @param {string} attributeName Attribute being confirmed.
6040 * @param {string} confirmationCode Code entered by user.
6041 * @param {object} callback Result callback map.
6042 * @param {onFailure} callback.onFailure Called on any error.
6043 * @param {onSuccess<string>} callback.onSuccess Called on success.
6044 * @returns {void}
6045 */
6046 ;
6047
6048 _proto.verifyAttribute = function verifyAttribute(attributeName, confirmationCode, callback) {
6049 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6050 return callback.onFailure(new Error('User is not authenticated'));
6051 }
6052
6053 this.client.request('VerifyUserAttribute', {
6054 AttributeName: attributeName,
6055 Code: confirmationCode,
6056 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6057 }, function (err) {
6058 if (err) {
6059 return callback.onFailure(err);
6060 }
6061
6062 return callback.onSuccess('SUCCESS');
6063 });
6064 return undefined;
6065 }
6066 /**
6067 * This is used to get the device information using the current device key
6068 * @param {object} callback Result callback map.
6069 * @param {onFailure} callback.onFailure Called on any error.
6070 * @param {onSuccess<*>} callback.onSuccess Called on success with device data.
6071 * @returns {void}
6072 */
6073 ;
6074
6075 _proto.getDevice = function getDevice(callback) {
6076 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6077 return callback.onFailure(new Error('User is not authenticated'));
6078 }
6079
6080 this.client.request('GetDevice', {
6081 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6082 DeviceKey: this.deviceKey
6083 }, function (err, data) {
6084 if (err) {
6085 return callback.onFailure(err);
6086 }
6087
6088 return callback.onSuccess(data);
6089 });
6090 return undefined;
6091 }
6092 /**
6093 * This is used to forget a specific device
6094 * @param {string} deviceKey Device key.
6095 * @param {object} callback Result callback map.
6096 * @param {onFailure} callback.onFailure Called on any error.
6097 * @param {onSuccess<string>} callback.onSuccess Called on success.
6098 * @returns {void}
6099 */
6100 ;
6101
6102 _proto.forgetSpecificDevice = function forgetSpecificDevice(deviceKey, callback) {
6103 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6104 return callback.onFailure(new Error('User is not authenticated'));
6105 }
6106
6107 this.client.request('ForgetDevice', {
6108 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6109 DeviceKey: deviceKey
6110 }, function (err) {
6111 if (err) {
6112 return callback.onFailure(err);
6113 }
6114
6115 return callback.onSuccess('SUCCESS');
6116 });
6117 return undefined;
6118 }
6119 /**
6120 * This is used to forget the current device
6121 * @param {object} callback Result callback map.
6122 * @param {onFailure} callback.onFailure Called on any error.
6123 * @param {onSuccess<string>} callback.onSuccess Called on success.
6124 * @returns {void}
6125 */
6126 ;
6127
6128 _proto.forgetDevice = function forgetDevice(callback) {
6129 var _this15 = this;
6130
6131 this.forgetSpecificDevice(this.deviceKey, {
6132 onFailure: callback.onFailure,
6133 onSuccess: function onSuccess(result) {
6134 _this15.deviceKey = null;
6135 _this15.deviceGroupKey = null;
6136 _this15.randomPassword = null;
6137
6138 _this15.clearCachedDeviceKeyAndPassword();
6139
6140 return callback.onSuccess(result);
6141 }
6142 });
6143 }
6144 /**
6145 * This is used to set the device status as remembered
6146 * @param {object} callback Result callback map.
6147 * @param {onFailure} callback.onFailure Called on any error.
6148 * @param {onSuccess<string>} callback.onSuccess Called on success.
6149 * @returns {void}
6150 */
6151 ;
6152
6153 _proto.setDeviceStatusRemembered = function setDeviceStatusRemembered(callback) {
6154 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6155 return callback.onFailure(new Error('User is not authenticated'));
6156 }
6157
6158 this.client.request('UpdateDeviceStatus', {
6159 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6160 DeviceKey: this.deviceKey,
6161 DeviceRememberedStatus: 'remembered'
6162 }, function (err) {
6163 if (err) {
6164 return callback.onFailure(err);
6165 }
6166
6167 return callback.onSuccess('SUCCESS');
6168 });
6169 return undefined;
6170 }
6171 /**
6172 * This is used to set the device status as not remembered
6173 * @param {object} callback Result callback map.
6174 * @param {onFailure} callback.onFailure Called on any error.
6175 * @param {onSuccess<string>} callback.onSuccess Called on success.
6176 * @returns {void}
6177 */
6178 ;
6179
6180 _proto.setDeviceStatusNotRemembered = function setDeviceStatusNotRemembered(callback) {
6181 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6182 return callback.onFailure(new Error('User is not authenticated'));
6183 }
6184
6185 this.client.request('UpdateDeviceStatus', {
6186 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6187 DeviceKey: this.deviceKey,
6188 DeviceRememberedStatus: 'not_remembered'
6189 }, function (err) {
6190 if (err) {
6191 return callback.onFailure(err);
6192 }
6193
6194 return callback.onSuccess('SUCCESS');
6195 });
6196 return undefined;
6197 }
6198 /**
6199 * This is used to list all devices for a user
6200 *
6201 * @param {int} limit the number of devices returned in a call
6202 * @param {string | null} paginationToken the pagination token in case any was returned before
6203 * @param {object} callback Result callback map.
6204 * @param {onFailure} callback.onFailure Called on any error.
6205 * @param {onSuccess<*>} callback.onSuccess Called on success with device list.
6206 * @returns {void}
6207 */
6208 ;
6209
6210 _proto.listDevices = function listDevices(limit, paginationToken, callback) {
6211 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6212 return callback.onFailure(new Error('User is not authenticated'));
6213 }
6214
6215 var requestParams = {
6216 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6217 Limit: limit
6218 };
6219
6220 if (paginationToken) {
6221 requestParams.PaginationToken = paginationToken;
6222 }
6223
6224 this.client.request('ListDevices', requestParams, function (err, data) {
6225 if (err) {
6226 return callback.onFailure(err);
6227 }
6228
6229 return callback.onSuccess(data);
6230 });
6231 return undefined;
6232 }
6233 /**
6234 * This is used to globally revoke all tokens issued to a user
6235 * @param {object} callback Result callback map.
6236 * @param {onFailure} callback.onFailure Called on any error.
6237 * @param {onSuccess<string>} callback.onSuccess Called on success.
6238 * @returns {void}
6239 */
6240 ;
6241
6242 _proto.globalSignOut = function globalSignOut(callback) {
6243 var _this16 = this;
6244
6245 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
6246 return callback.onFailure(new Error('User is not authenticated'));
6247 }
6248
6249 this.client.request('GlobalSignOut', {
6250 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6251 }, function (err) {
6252 if (err) {
6253 return callback.onFailure(err);
6254 }
6255
6256 _this16.clearCachedUser();
6257
6258 return callback.onSuccess('SUCCESS');
6259 });
6260 return undefined;
6261 }
6262 /**
6263 * This is used for the user to signOut of the application and clear the cached tokens.
6264 * @returns {void}
6265 */
6266 ;
6267
6268 _proto.signOut = function signOut() {
6269 this.signInUserSession = null;
6270 this.clearCachedUser();
6271 }
6272 /**
6273 * This is used by a user trying to select a given MFA
6274 * @param {string} answerChallenge the mfa the user wants
6275 * @param {nodeCallback<string>} callback Called on success or error.
6276 * @returns {void}
6277 */
6278 ;
6279
6280 _proto.sendMFASelectionAnswer = function sendMFASelectionAnswer(answerChallenge, callback) {
6281 var _this17 = this;
6282
6283 var challengeResponses = {};
6284 challengeResponses.USERNAME = this.username;
6285 challengeResponses.ANSWER = answerChallenge;
6286 var jsonReq = {
6287 ChallengeName: 'SELECT_MFA_TYPE',
6288 ChallengeResponses: challengeResponses,
6289 ClientId: this.pool.getClientId(),
6290 Session: this.Session
6291 };
6292
6293 if (this.getUserContextData()) {
6294 jsonReq.UserContextData = this.getUserContextData();
6295 }
6296
6297 this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
6298 if (err) {
6299 return callback.onFailure(err);
6300 }
6301
6302 _this17.Session = data.Session;
6303
6304 if (answerChallenge === 'SMS_MFA') {
6305 return callback.mfaRequired(data.ChallengeName, data.ChallengeParameters);
6306 }
6307
6308 if (answerChallenge === 'SOFTWARE_TOKEN_MFA') {
6309 return callback.totpRequired(data.ChallengeName, data.ChallengeParameters);
6310 }
6311
6312 return undefined;
6313 });
6314 }
6315 /**
6316 * This returns the user context data for advanced security feature.
6317 * @returns {void}
6318 */
6319 ;
6320
6321 _proto.getUserContextData = function getUserContextData() {
6322 var pool = this.pool;
6323 return pool.getUserContextData(this.username);
6324 }
6325 /**
6326 * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA
6327 * @param {nodeCallback<string>} callback Called on success or error.
6328 * @returns {void}
6329 */
6330 ;
6331
6332 _proto.associateSoftwareToken = function associateSoftwareToken(callback) {
6333 var _this18 = this;
6334
6335 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
6336 this.client.request('AssociateSoftwareToken', {
6337 Session: this.Session
6338 }, function (err, data) {
6339 if (err) {
6340 return callback.onFailure(err);
6341 }
6342
6343 _this18.Session = data.Session;
6344 return callback.associateSecretCode(data.SecretCode);
6345 });
6346 } else {
6347 this.client.request('AssociateSoftwareToken', {
6348 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
6349 }, function (err, data) {
6350 if (err) {
6351 return callback.onFailure(err);
6352 }
6353
6354 return callback.associateSecretCode(data.SecretCode);
6355 });
6356 }
6357 }
6358 /**
6359 * This is used by an authenticated or a user trying to authenticate to verify a TOTP MFA
6360 * @param {string} totpCode The MFA code entered by the user.
6361 * @param {string} friendlyDeviceName The device name we are assigning to the device.
6362 * @param {nodeCallback<string>} callback Called on success or error.
6363 * @returns {void}
6364 */
6365 ;
6366
6367 _proto.verifySoftwareToken = function verifySoftwareToken(totpCode, friendlyDeviceName, callback) {
6368 var _this19 = this;
6369
6370 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
6371 this.client.request('VerifySoftwareToken', {
6372 Session: this.Session,
6373 UserCode: totpCode,
6374 FriendlyDeviceName: friendlyDeviceName
6375 }, function (err, data) {
6376 if (err) {
6377 return callback.onFailure(err);
6378 }
6379
6380 _this19.Session = data.Session;
6381 var challengeResponses = {};
6382 challengeResponses.USERNAME = _this19.username;
6383 var jsonReq = {
6384 ChallengeName: 'MFA_SETUP',
6385 ClientId: _this19.pool.getClientId(),
6386 ChallengeResponses: challengeResponses,
6387 Session: _this19.Session
6388 };
6389
6390 if (_this19.getUserContextData()) {
6391 jsonReq.UserContextData = _this19.getUserContextData();
6392 }
6393
6394 _this19.client.request('RespondToAuthChallenge', jsonReq, function (errRespond, dataRespond) {
6395 if (errRespond) {
6396 return callback.onFailure(errRespond);
6397 }
6398
6399 _this19.signInUserSession = _this19.getCognitoUserSession(dataRespond.AuthenticationResult);
6400
6401 _this19.cacheTokens();
6402
6403 return callback.onSuccess(_this19.signInUserSession);
6404 });
6405
6406 return undefined;
6407 });
6408 } else {
6409 this.client.request('VerifySoftwareToken', {
6410 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
6411 UserCode: totpCode,
6412 FriendlyDeviceName: friendlyDeviceName
6413 }, function (err, data) {
6414 if (err) {
6415 return callback.onFailure(err);
6416 }
6417
6418 return callback.onSuccess(data);
6419 });
6420 }
6421 };
6422
6423 return CognitoUser;
6424}();
6425
6426
6427
6428/***/ }),
6429/* 12 */
6430/***/ (function(module, __webpack_exports__, __webpack_require__) {
6431
6432"use strict";
6433/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CognitoUserSession; });
6434/*!
6435 * Copyright 2016 Amazon.com,
6436 * Inc. or its affiliates. All Rights Reserved.
6437 *
6438 * Licensed under the Amazon Software License (the "License").
6439 * You may not use this file except in compliance with the
6440 * License. A copy of the License is located at
6441 *
6442 * http://aws.amazon.com/asl/
6443 *
6444 * or in the "license" file accompanying this file. This file is
6445 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6446 * CONDITIONS OF ANY KIND, express or implied. See the License
6447 * for the specific language governing permissions and
6448 * limitations under the License.
6449 */
6450
6451/** @class */
6452var CognitoUserSession = /*#__PURE__*/function () {
6453 /**
6454 * Constructs a new CognitoUserSession object
6455 * @param {CognitoIdToken} IdToken The session's Id token.
6456 * @param {CognitoRefreshToken=} RefreshToken The session's refresh token.
6457 * @param {CognitoAccessToken} AccessToken The session's access token.
6458 * @param {int} ClockDrift The saved computer's clock drift or undefined to force calculation.
6459 */
6460 function CognitoUserSession(_temp) {
6461 var _ref = _temp === void 0 ? {} : _temp,
6462 IdToken = _ref.IdToken,
6463 RefreshToken = _ref.RefreshToken,
6464 AccessToken = _ref.AccessToken,
6465 ClockDrift = _ref.ClockDrift;
6466
6467 if (AccessToken == null || IdToken == null) {
6468 throw new Error('Id token and Access Token must be present.');
6469 }
6470
6471 this.idToken = IdToken;
6472 this.refreshToken = RefreshToken;
6473 this.accessToken = AccessToken;
6474 this.clockDrift = ClockDrift === undefined ? this.calculateClockDrift() : ClockDrift;
6475 }
6476 /**
6477 * @returns {CognitoIdToken} the session's Id token
6478 */
6479
6480
6481 var _proto = CognitoUserSession.prototype;
6482
6483 _proto.getIdToken = function getIdToken() {
6484 return this.idToken;
6485 }
6486 /**
6487 * @returns {CognitoRefreshToken} the session's refresh token
6488 */
6489 ;
6490
6491 _proto.getRefreshToken = function getRefreshToken() {
6492 return this.refreshToken;
6493 }
6494 /**
6495 * @returns {CognitoAccessToken} the session's access token
6496 */
6497 ;
6498
6499 _proto.getAccessToken = function getAccessToken() {
6500 return this.accessToken;
6501 }
6502 /**
6503 * @returns {int} the session's clock drift
6504 */
6505 ;
6506
6507 _proto.getClockDrift = function getClockDrift() {
6508 return this.clockDrift;
6509 }
6510 /**
6511 * @returns {int} the computer's clock drift
6512 */
6513 ;
6514
6515 _proto.calculateClockDrift = function calculateClockDrift() {
6516 var now = Math.floor(new Date() / 1000);
6517 var iat = Math.min(this.accessToken.getIssuedAt(), this.idToken.getIssuedAt());
6518 return now - iat;
6519 }
6520 /**
6521 * Checks to see if the session is still valid based on session expiry information found
6522 * in tokens and the current time (adjusted with clock drift)
6523 * @returns {boolean} if the session is still valid
6524 */
6525 ;
6526
6527 _proto.isValid = function isValid() {
6528 var now = Math.floor(new Date() / 1000);
6529 var adjusted = now - this.clockDrift;
6530 return adjusted < this.accessToken.getExpiration() && adjusted < this.idToken.getExpiration();
6531 };
6532
6533 return CognitoUserSession;
6534}();
6535
6536
6537
6538/***/ }),
6539/* 13 */
6540/***/ (function(module, __webpack_exports__, __webpack_require__) {
6541
6542"use strict";
6543/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DateHelper; });
6544/*!
6545 * Copyright 2016 Amazon.com,
6546 * Inc. or its affiliates. All Rights Reserved.
6547 *
6548 * Licensed under the Amazon Software License (the "License").
6549 * You may not use this file except in compliance with the
6550 * License. A copy of the License is located at
6551 *
6552 * http://aws.amazon.com/asl/
6553 *
6554 * or in the "license" file accompanying this file. This file is
6555 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6556 * CONDITIONS OF ANY KIND, express or implied. See the License
6557 * for the specific language governing permissions and
6558 * limitations under the License.
6559 */
6560var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
6561var weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
6562/** @class */
6563
6564var DateHelper = /*#__PURE__*/function () {
6565 function DateHelper() {}
6566
6567 var _proto = DateHelper.prototype;
6568
6569 /**
6570 * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format.
6571 */
6572 _proto.getNowString = function getNowString() {
6573 var now = new Date();
6574 var weekDay = weekNames[now.getUTCDay()];
6575 var month = monthNames[now.getUTCMonth()];
6576 var day = now.getUTCDate();
6577 var hours = now.getUTCHours();
6578
6579 if (hours < 10) {
6580 hours = "0" + hours;
6581 }
6582
6583 var minutes = now.getUTCMinutes();
6584
6585 if (minutes < 10) {
6586 minutes = "0" + minutes;
6587 }
6588
6589 var seconds = now.getUTCSeconds();
6590
6591 if (seconds < 10) {
6592 seconds = "0" + seconds;
6593 }
6594
6595 var year = now.getUTCFullYear(); // ddd MMM D HH:mm:ss UTC YYYY
6596
6597 var dateNow = weekDay + " " + month + " " + day + " " + hours + ":" + minutes + ":" + seconds + " UTC " + year;
6598 return dateNow;
6599 };
6600
6601 return DateHelper;
6602}();
6603
6604
6605
6606/***/ }),
6607/* 14 */
6608/***/ (function(module, __webpack_exports__, __webpack_require__) {
6609
6610"use strict";
6611/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CognitoUserAttribute; });
6612/*!
6613 * Copyright 2016 Amazon.com,
6614 * Inc. or its affiliates. All Rights Reserved.
6615 *
6616 * Licensed under the Amazon Software License (the "License").
6617 * You may not use this file except in compliance with the
6618 * License. A copy of the License is located at
6619 *
6620 * http://aws.amazon.com/asl/
6621 *
6622 * or in the "license" file accompanying this file. This file is
6623 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6624 * CONDITIONS OF ANY KIND, express or implied. See the License
6625 * for the specific language governing permissions and
6626 * limitations under the License.
6627 */
6628
6629/** @class */
6630var CognitoUserAttribute = /*#__PURE__*/function () {
6631 /**
6632 * Constructs a new CognitoUserAttribute object
6633 * @param {string=} Name The record's name
6634 * @param {string=} Value The record's value
6635 */
6636 function CognitoUserAttribute(_temp) {
6637 var _ref = _temp === void 0 ? {} : _temp,
6638 Name = _ref.Name,
6639 Value = _ref.Value;
6640
6641 this.Name = Name || '';
6642 this.Value = Value || '';
6643 }
6644 /**
6645 * @returns {string} the record's value.
6646 */
6647
6648
6649 var _proto = CognitoUserAttribute.prototype;
6650
6651 _proto.getValue = function getValue() {
6652 return this.Value;
6653 }
6654 /**
6655 * Sets the record's value.
6656 * @param {string} value The new value.
6657 * @returns {CognitoUserAttribute} The record for method chaining.
6658 */
6659 ;
6660
6661 _proto.setValue = function setValue(value) {
6662 this.Value = value;
6663 return this;
6664 }
6665 /**
6666 * @returns {string} the record's name.
6667 */
6668 ;
6669
6670 _proto.getName = function getName() {
6671 return this.Name;
6672 }
6673 /**
6674 * Sets the record's name
6675 * @param {string} name The new name.
6676 * @returns {CognitoUserAttribute} The record for method chaining.
6677 */
6678 ;
6679
6680 _proto.setName = function setName(name) {
6681 this.Name = name;
6682 return this;
6683 }
6684 /**
6685 * @returns {string} a string representation of the record.
6686 */
6687 ;
6688
6689 _proto.toString = function toString() {
6690 return JSON.stringify(this);
6691 }
6692 /**
6693 * @returns {object} a flat object representing the record.
6694 */
6695 ;
6696
6697 _proto.toJSON = function toJSON() {
6698 return {
6699 Name: this.Name,
6700 Value: this.Value
6701 };
6702 };
6703
6704 return CognitoUserAttribute;
6705}();
6706
6707
6708
6709/***/ }),
6710/* 15 */
6711/***/ (function(module, __webpack_exports__, __webpack_require__) {
6712
6713"use strict";
6714/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StorageHelper; });
6715/*!
6716 * Copyright 2016 Amazon.com,
6717 * Inc. or its affiliates. All Rights Reserved.
6718 *
6719 * Licensed under the Amazon Software License (the "License").
6720 * You may not use this file except in compliance with the
6721 * License. A copy of the License is located at
6722 *
6723 * http://aws.amazon.com/asl/
6724 *
6725 * or in the "license" file accompanying this file. This file is
6726 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6727 * CONDITIONS OF ANY KIND, express or implied. See the License
6728 * for the specific language governing permissions and
6729 * limitations under the License.
6730 */
6731var dataMemory = {};
6732/** @class */
6733
6734var MemoryStorage = /*#__PURE__*/function () {
6735 function MemoryStorage() {}
6736
6737 /**
6738 * This is used to set a specific item in storage
6739 * @param {string} key - the key for the item
6740 * @param {object} value - the value
6741 * @returns {string} value that was set
6742 */
6743 MemoryStorage.setItem = function setItem(key, value) {
6744 dataMemory[key] = value;
6745 return dataMemory[key];
6746 }
6747 /**
6748 * This is used to get a specific key from storage
6749 * @param {string} key - the key for the item
6750 * This is used to clear the storage
6751 * @returns {string} the data item
6752 */
6753 ;
6754
6755 MemoryStorage.getItem = function getItem(key) {
6756 return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined;
6757 }
6758 /**
6759 * This is used to remove an item from storage
6760 * @param {string} key - the key being set
6761 * @returns {string} value - value that was deleted
6762 */
6763 ;
6764
6765 MemoryStorage.removeItem = function removeItem(key) {
6766 return delete dataMemory[key];
6767 }
6768 /**
6769 * This is used to clear the storage
6770 * @returns {string} nothing
6771 */
6772 ;
6773
6774 MemoryStorage.clear = function clear() {
6775 dataMemory = {};
6776 return dataMemory;
6777 };
6778
6779 return MemoryStorage;
6780}();
6781/** @class */
6782
6783
6784var StorageHelper = /*#__PURE__*/function () {
6785 /**
6786 * This is used to get a storage object
6787 * @returns {object} the storage
6788 */
6789 function StorageHelper() {
6790 try {
6791 this.storageWindow = window.localStorage;
6792 this.storageWindow.setItem('aws.cognito.test-ls', 1);
6793 this.storageWindow.removeItem('aws.cognito.test-ls');
6794 } catch (exception) {
6795 this.storageWindow = MemoryStorage;
6796 }
6797 }
6798 /**
6799 * This is used to return the storage
6800 * @returns {object} the storage
6801 */
6802
6803
6804 var _proto = StorageHelper.prototype;
6805
6806 _proto.getStorage = function getStorage() {
6807 return this.storageWindow;
6808 };
6809
6810 return StorageHelper;
6811}();
6812
6813
6814
6815/***/ }),
6816/* 16 */
6817/***/ (function(module, __webpack_exports__, __webpack_require__) {
6818
6819"use strict";
6820Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
6821/* harmony default export */ __webpack_exports__["default"] = (function(e,n){return n=n||{},new Promise(function(t,r){var s=new XMLHttpRequest,o=[],u=[],i={},a=function(){return{ok:2==(s.status/100|0),statusText:s.statusText,status:s.status,url:s.responseURL,text:function(){return Promise.resolve(s.responseText)},json:function(){return Promise.resolve(JSON.parse(s.responseText))},blob:function(){return Promise.resolve(new Blob([s.response]))},clone:a,headers:{keys:function(){return o},entries:function(){return u},get:function(e){return i[e.toLowerCase()]},has:function(e){return e.toLowerCase()in i}}}};for(var l in s.open(n.method||"get",e,!0),s.onload=function(){s.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,n,t){o.push(n=n.toLowerCase()),u.push([n,t]),i[n]=i[n]?i[n]+","+t:t}),t(a())},s.onerror=r,s.withCredentials="include"==n.credentials,n.headers)s.setRequestHeader(l,n.headers[l]);s.send(n.body||null)})});
6822//# sourceMappingURL=unfetch.mjs.map
6823
6824
6825/***/ }),
6826/* 17 */
6827/***/ (function(module, __webpack_exports__, __webpack_require__) {
6828
6829"use strict";
6830/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return appendToCognitoUserAgent; });
6831// constructor
6832function UserAgent() {} // public
6833
6834
6835UserAgent.prototype.userAgent = 'aws-amplify/0.1.x js';
6836var appendToCognitoUserAgent = function appendToCognitoUserAgent(content) {
6837 if (!content) {
6838 return;
6839 }
6840
6841 if (UserAgent.prototype.userAgent && !UserAgent.prototype.userAgent.includes(content)) {
6842 UserAgent.prototype.userAgent = UserAgent.prototype.userAgent.concat(' ', content);
6843 }
6844
6845 if (!UserAgent.prototype.userAgent || UserAgent.prototype.userAgent === '') {
6846 UserAgent.prototype.userAgent = content;
6847 }
6848}; // class for defining the amzn user-agent
6849
6850/* harmony default export */ __webpack_exports__["b"] = (UserAgent);
6851
6852/***/ }),
6853/* 18 */
6854/***/ (function(module, __webpack_exports__, __webpack_require__) {
6855
6856"use strict";
6857Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
6858/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__AuthenticationDetails__ = __webpack_require__(19);
6859/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "AuthenticationDetails", function() { return __WEBPACK_IMPORTED_MODULE_0__AuthenticationDetails__["a"]; });
6860/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__AuthenticationHelper__ = __webpack_require__(2);
6861/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "AuthenticationHelper", function() { return __WEBPACK_IMPORTED_MODULE_1__AuthenticationHelper__["a"]; });
6862/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__CognitoAccessToken__ = __webpack_require__(7);
6863/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoAccessToken", function() { return __WEBPACK_IMPORTED_MODULE_2__CognitoAccessToken__["a"]; });
6864/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__CognitoIdToken__ = __webpack_require__(9);
6865/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoIdToken", function() { return __WEBPACK_IMPORTED_MODULE_3__CognitoIdToken__["a"]; });
6866/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CognitoRefreshToken__ = __webpack_require__(10);
6867/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoRefreshToken", function() { return __WEBPACK_IMPORTED_MODULE_4__CognitoRefreshToken__["a"]; });
6868/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__CognitoUser__ = __webpack_require__(11);
6869/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoUser", function() { return __WEBPACK_IMPORTED_MODULE_5__CognitoUser__["a"]; });
6870/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__CognitoUserAttribute__ = __webpack_require__(14);
6871/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoUserAttribute", function() { return __WEBPACK_IMPORTED_MODULE_6__CognitoUserAttribute__["a"]; });
6872/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__CognitoUserPool__ = __webpack_require__(26);
6873/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoUserPool", function() { return __WEBPACK_IMPORTED_MODULE_7__CognitoUserPool__["a"]; });
6874/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__CognitoUserSession__ = __webpack_require__(12);
6875/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CognitoUserSession", function() { return __WEBPACK_IMPORTED_MODULE_8__CognitoUserSession__["a"]; });
6876/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__CookieStorage__ = __webpack_require__(29);
6877/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CookieStorage", function() { return __WEBPACK_IMPORTED_MODULE_9__CookieStorage__["a"]; });
6878/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__DateHelper__ = __webpack_require__(13);
6879/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "DateHelper", function() { return __WEBPACK_IMPORTED_MODULE_10__DateHelper__["a"]; });
6880/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__UserAgent__ = __webpack_require__(17);
6881/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "appendToCognitoUserAgent", function() { return __WEBPACK_IMPORTED_MODULE_11__UserAgent__["a"]; });
6882/*!
6883 * Copyright 2016 Amazon.com,
6884 * Inc. or its affiliates. All Rights Reserved.
6885 *
6886 * Licensed under the Amazon Software License (the "License").
6887 * You may not use this file except in compliance with the
6888 * License. A copy of the License is located at
6889 *
6890 * http://aws.amazon.com/asl/
6891 *
6892 * or in the "license" file accompanying this file. This file is
6893 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6894 * CONDITIONS OF ANY KIND, express or implied. See the License
6895 * for the specific language governing permissions and
6896 * limitations under the License.
6897 */
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911/***/ }),
6912/* 19 */
6913/***/ (function(module, __webpack_exports__, __webpack_require__) {
6914
6915"use strict";
6916/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AuthenticationDetails; });
6917/*!
6918 * Copyright 2016 Amazon.com,
6919 * Inc. or its affiliates. All Rights Reserved.
6920 *
6921 * Licensed under the Amazon Software License (the "License").
6922 * You may not use this file except in compliance with the
6923 * License. A copy of the License is located at
6924 *
6925 * http://aws.amazon.com/asl/
6926 *
6927 * or in the "license" file accompanying this file. This file is
6928 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6929 * CONDITIONS OF ANY KIND, express or implied. See the License
6930 * for the specific language governing permissions and
6931 * limitations under the License.
6932 */
6933
6934/** @class */
6935var AuthenticationDetails = /*#__PURE__*/function () {
6936 /**
6937 * Constructs a new AuthenticationDetails object
6938 * @param {object=} data Creation options.
6939 * @param {string} data.Username User being authenticated.
6940 * @param {string} data.Password Plain-text password to authenticate with.
6941 * @param {(AttributeArg[])?} data.ValidationData Application extra metadata.
6942 * @param {(AttributeArg[])?} data.AuthParamaters Authentication paramaters for custom auth.
6943 */
6944 function AuthenticationDetails(data) {
6945 var _ref = data || {},
6946 ValidationData = _ref.ValidationData,
6947 Username = _ref.Username,
6948 Password = _ref.Password,
6949 AuthParameters = _ref.AuthParameters,
6950 ClientMetadata = _ref.ClientMetadata;
6951
6952 this.validationData = ValidationData || {};
6953 this.authParameters = AuthParameters || {};
6954 this.clientMetadata = ClientMetadata || {};
6955 this.username = Username;
6956 this.password = Password;
6957 }
6958 /**
6959 * @returns {string} the record's username
6960 */
6961
6962
6963 var _proto = AuthenticationDetails.prototype;
6964
6965 _proto.getUsername = function getUsername() {
6966 return this.username;
6967 }
6968 /**
6969 * @returns {string} the record's password
6970 */
6971 ;
6972
6973 _proto.getPassword = function getPassword() {
6974 return this.password;
6975 }
6976 /**
6977 * @returns {Array} the record's validationData
6978 */
6979 ;
6980
6981 _proto.getValidationData = function getValidationData() {
6982 return this.validationData;
6983 }
6984 /**
6985 * @returns {Array} the record's authParameters
6986 */
6987 ;
6988
6989 _proto.getAuthParameters = function getAuthParameters() {
6990 return this.authParameters;
6991 }
6992 /**
6993 * @returns {ClientMetadata} the clientMetadata for a Lambda trigger
6994 */
6995 ;
6996
6997 _proto.getClientMetadata = function getClientMetadata() {
6998 return this.clientMetadata;
6999 };
7000
7001 return AuthenticationDetails;
7002}();
7003
7004
7005
7006/***/ }),
7007/* 20 */
7008/***/ (function(module, exports) {
7009
7010var g;
7011
7012// This works in non-strict mode
7013g = (function() {
7014 return this;
7015})();
7016
7017try {
7018 // This works if eval is allowed (see CSP)
7019 g = g || Function("return this")() || (1,eval)("this");
7020} catch(e) {
7021 // This works if the window reference is available
7022 if(typeof window === "object")
7023 g = window;
7024}
7025
7026// g can still be undefined, but nothing to do about it...
7027// We return undefined, instead of nothing here, so it's
7028// easier to handle this case. if(!global) { ...}
7029
7030module.exports = g;
7031
7032
7033/***/ }),
7034/* 21 */
7035/***/ (function(module, exports, __webpack_require__) {
7036
7037"use strict";
7038
7039
7040exports.byteLength = byteLength
7041exports.toByteArray = toByteArray
7042exports.fromByteArray = fromByteArray
7043
7044var lookup = []
7045var revLookup = []
7046var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
7047
7048var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
7049for (var i = 0, len = code.length; i < len; ++i) {
7050 lookup[i] = code[i]
7051 revLookup[code.charCodeAt(i)] = i
7052}
7053
7054// Support decoding URL-safe base64 strings, as Node.js does.
7055// See: https://en.wikipedia.org/wiki/Base64#URL_applications
7056revLookup['-'.charCodeAt(0)] = 62
7057revLookup['_'.charCodeAt(0)] = 63
7058
7059function getLens (b64) {
7060 var len = b64.length
7061
7062 if (len % 4 > 0) {
7063 throw new Error('Invalid string. Length must be a multiple of 4')
7064 }
7065
7066 // Trim off extra bytes after placeholder bytes are found
7067 // See: https://github.com/beatgammit/base64-js/issues/42
7068 var validLen = b64.indexOf('=')
7069 if (validLen === -1) validLen = len
7070
7071 var placeHoldersLen = validLen === len
7072 ? 0
7073 : 4 - (validLen % 4)
7074
7075 return [validLen, placeHoldersLen]
7076}
7077
7078// base64 is 4/3 + up to two characters of the original data
7079function byteLength (b64) {
7080 var lens = getLens(b64)
7081 var validLen = lens[0]
7082 var placeHoldersLen = lens[1]
7083 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
7084}
7085
7086function _byteLength (b64, validLen, placeHoldersLen) {
7087 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
7088}
7089
7090function toByteArray (b64) {
7091 var tmp
7092 var lens = getLens(b64)
7093 var validLen = lens[0]
7094 var placeHoldersLen = lens[1]
7095
7096 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
7097
7098 var curByte = 0
7099
7100 // if there are placeholders, only get up to the last complete 4 chars
7101 var len = placeHoldersLen > 0
7102 ? validLen - 4
7103 : validLen
7104
7105 var i
7106 for (i = 0; i < len; i += 4) {
7107 tmp =
7108 (revLookup[b64.charCodeAt(i)] << 18) |
7109 (revLookup[b64.charCodeAt(i + 1)] << 12) |
7110 (revLookup[b64.charCodeAt(i + 2)] << 6) |
7111 revLookup[b64.charCodeAt(i + 3)]
7112 arr[curByte++] = (tmp >> 16) & 0xFF
7113 arr[curByte++] = (tmp >> 8) & 0xFF
7114 arr[curByte++] = tmp & 0xFF
7115 }
7116
7117 if (placeHoldersLen === 2) {
7118 tmp =
7119 (revLookup[b64.charCodeAt(i)] << 2) |
7120 (revLookup[b64.charCodeAt(i + 1)] >> 4)
7121 arr[curByte++] = tmp & 0xFF
7122 }
7123
7124 if (placeHoldersLen === 1) {
7125 tmp =
7126 (revLookup[b64.charCodeAt(i)] << 10) |
7127 (revLookup[b64.charCodeAt(i + 1)] << 4) |
7128 (revLookup[b64.charCodeAt(i + 2)] >> 2)
7129 arr[curByte++] = (tmp >> 8) & 0xFF
7130 arr[curByte++] = tmp & 0xFF
7131 }
7132
7133 return arr
7134}
7135
7136function tripletToBase64 (num) {
7137 return lookup[num >> 18 & 0x3F] +
7138 lookup[num >> 12 & 0x3F] +
7139 lookup[num >> 6 & 0x3F] +
7140 lookup[num & 0x3F]
7141}
7142
7143function encodeChunk (uint8, start, end) {
7144 var tmp
7145 var output = []
7146 for (var i = start; i < end; i += 3) {
7147 tmp =
7148 ((uint8[i] << 16) & 0xFF0000) +
7149 ((uint8[i + 1] << 8) & 0xFF00) +
7150 (uint8[i + 2] & 0xFF)
7151 output.push(tripletToBase64(tmp))
7152 }
7153 return output.join('')
7154}
7155
7156function fromByteArray (uint8) {
7157 var tmp
7158 var len = uint8.length
7159 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
7160 var parts = []
7161 var maxChunkLength = 16383 // must be multiple of 3
7162
7163 // go through the array every three bytes, we'll deal with trailing stuff later
7164 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
7165 parts.push(encodeChunk(
7166 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
7167 ))
7168 }
7169
7170 // pad the end with zeros, but make sure to not forget the extra bytes
7171 if (extraBytes === 1) {
7172 tmp = uint8[len - 1]
7173 parts.push(
7174 lookup[tmp >> 2] +
7175 lookup[(tmp << 4) & 0x3F] +
7176 '=='
7177 )
7178 } else if (extraBytes === 2) {
7179 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
7180 parts.push(
7181 lookup[tmp >> 10] +
7182 lookup[(tmp >> 4) & 0x3F] +
7183 lookup[(tmp << 2) & 0x3F] +
7184 '='
7185 )
7186 }
7187
7188 return parts.join('')
7189}
7190
7191
7192/***/ }),
7193/* 22 */
7194/***/ (function(module, exports) {
7195
7196exports.read = function (buffer, offset, isLE, mLen, nBytes) {
7197 var e, m
7198 var eLen = (nBytes * 8) - mLen - 1
7199 var eMax = (1 << eLen) - 1
7200 var eBias = eMax >> 1
7201 var nBits = -7
7202 var i = isLE ? (nBytes - 1) : 0
7203 var d = isLE ? -1 : 1
7204 var s = buffer[offset + i]
7205
7206 i += d
7207
7208 e = s & ((1 << (-nBits)) - 1)
7209 s >>= (-nBits)
7210 nBits += eLen
7211 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
7212
7213 m = e & ((1 << (-nBits)) - 1)
7214 e >>= (-nBits)
7215 nBits += mLen
7216 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
7217
7218 if (e === 0) {
7219 e = 1 - eBias
7220 } else if (e === eMax) {
7221 return m ? NaN : ((s ? -1 : 1) * Infinity)
7222 } else {
7223 m = m + Math.pow(2, mLen)
7224 e = e - eBias
7225 }
7226 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
7227}
7228
7229exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
7230 var e, m, c
7231 var eLen = (nBytes * 8) - mLen - 1
7232 var eMax = (1 << eLen) - 1
7233 var eBias = eMax >> 1
7234 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
7235 var i = isLE ? 0 : (nBytes - 1)
7236 var d = isLE ? 1 : -1
7237 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
7238
7239 value = Math.abs(value)
7240
7241 if (isNaN(value) || value === Infinity) {
7242 m = isNaN(value) ? 1 : 0
7243 e = eMax
7244 } else {
7245 e = Math.floor(Math.log(value) / Math.LN2)
7246 if (value * (c = Math.pow(2, -e)) < 1) {
7247 e--
7248 c *= 2
7249 }
7250 if (e + eBias >= 1) {
7251 value += rt / c
7252 } else {
7253 value += rt * Math.pow(2, 1 - eBias)
7254 }
7255 if (value * c >= 2) {
7256 e++
7257 c /= 2
7258 }
7259
7260 if (e + eBias >= eMax) {
7261 m = 0
7262 e = eMax
7263 } else if (e + eBias >= 1) {
7264 m = ((value * c) - 1) * Math.pow(2, mLen)
7265 e = e + eBias
7266 } else {
7267 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
7268 e = 0
7269 }
7270 }
7271
7272 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
7273
7274 e = (e << mLen) | m
7275 eLen += mLen
7276 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
7277
7278 buffer[offset + i - d] |= s * 128
7279}
7280
7281
7282/***/ }),
7283/* 23 */
7284/***/ (function(module, exports) {
7285
7286var toString = {}.toString;
7287
7288module.exports = Array.isArray || function (arr) {
7289 return toString.call(arr) == '[object Array]';
7290};
7291
7292
7293/***/ }),
7294/* 24 */
7295/***/ (function(module, exports, __webpack_require__) {
7296
7297;(function (root, factory) {
7298 if (true) {
7299 // CommonJS
7300 module.exports = exports = factory(__webpack_require__(0));
7301 }
7302 else if (typeof define === "function" && define.amd) {
7303 // AMD
7304 define(["./core"], factory);
7305 }
7306 else {
7307 // Global (browser)
7308 factory(root.CryptoJS);
7309 }
7310}(this, function (CryptoJS) {
7311
7312 (function () {
7313 // Shortcuts
7314 var C = CryptoJS;
7315 var C_lib = C.lib;
7316 var Base = C_lib.Base;
7317 var C_enc = C.enc;
7318 var Utf8 = C_enc.Utf8;
7319 var C_algo = C.algo;
7320
7321 /**
7322 * HMAC algorithm.
7323 */
7324 var HMAC = C_algo.HMAC = Base.extend({
7325 /**
7326 * Initializes a newly created HMAC.
7327 *
7328 * @param {Hasher} hasher The hash algorithm to use.
7329 * @param {WordArray|string} key The secret key.
7330 *
7331 * @example
7332 *
7333 * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
7334 */
7335 init: function (hasher, key) {
7336 // Init hasher
7337 hasher = this._hasher = new hasher.init();
7338
7339 // Convert string to WordArray, else assume WordArray already
7340 if (typeof key == 'string') {
7341 key = Utf8.parse(key);
7342 }
7343
7344 // Shortcuts
7345 var hasherBlockSize = hasher.blockSize;
7346 var hasherBlockSizeBytes = hasherBlockSize * 4;
7347
7348 // Allow arbitrary length keys
7349 if (key.sigBytes > hasherBlockSizeBytes) {
7350 key = hasher.finalize(key);
7351 }
7352
7353 // Clamp excess bits
7354 key.clamp();
7355
7356 // Clone key for inner and outer pads
7357 var oKey = this._oKey = key.clone();
7358 var iKey = this._iKey = key.clone();
7359
7360 // Shortcuts
7361 var oKeyWords = oKey.words;
7362 var iKeyWords = iKey.words;
7363
7364 // XOR keys with pad constants
7365 for (var i = 0; i < hasherBlockSize; i++) {
7366 oKeyWords[i] ^= 0x5c5c5c5c;
7367 iKeyWords[i] ^= 0x36363636;
7368 }
7369 oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
7370
7371 // Set initial values
7372 this.reset();
7373 },
7374
7375 /**
7376 * Resets this HMAC to its initial state.
7377 *
7378 * @example
7379 *
7380 * hmacHasher.reset();
7381 */
7382 reset: function () {
7383 // Shortcut
7384 var hasher = this._hasher;
7385
7386 // Reset
7387 hasher.reset();
7388 hasher.update(this._iKey);
7389 },
7390
7391 /**
7392 * Updates this HMAC with a message.
7393 *
7394 * @param {WordArray|string} messageUpdate The message to append.
7395 *
7396 * @return {HMAC} This HMAC instance.
7397 *
7398 * @example
7399 *
7400 * hmacHasher.update('message');
7401 * hmacHasher.update(wordArray);
7402 */
7403 update: function (messageUpdate) {
7404 this._hasher.update(messageUpdate);
7405
7406 // Chainable
7407 return this;
7408 },
7409
7410 /**
7411 * Finalizes the HMAC computation.
7412 * Note that the finalize operation is effectively a destructive, read-once operation.
7413 *
7414 * @param {WordArray|string} messageUpdate (Optional) A final message update.
7415 *
7416 * @return {WordArray} The HMAC.
7417 *
7418 * @example
7419 *
7420 * var hmac = hmacHasher.finalize();
7421 * var hmac = hmacHasher.finalize('message');
7422 * var hmac = hmacHasher.finalize(wordArray);
7423 */
7424 finalize: function (messageUpdate) {
7425 // Shortcut
7426 var hasher = this._hasher;
7427
7428 // Compute HMAC
7429 var innerHash = hasher.finalize(messageUpdate);
7430 hasher.reset();
7431 var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
7432
7433 return hmac;
7434 }
7435 });
7436 }());
7437
7438
7439}));
7440
7441/***/ }),
7442/* 25 */
7443/***/ (function(module, exports, __webpack_require__) {
7444
7445;(function (root, factory) {
7446 if (true) {
7447 // CommonJS
7448 module.exports = exports = factory(__webpack_require__(0));
7449 }
7450 else if (typeof define === "function" && define.amd) {
7451 // AMD
7452 define(["./core"], factory);
7453 }
7454 else {
7455 // Global (browser)
7456 factory(root.CryptoJS);
7457 }
7458}(this, function (CryptoJS) {
7459
7460 (function () {
7461 // Shortcuts
7462 var C = CryptoJS;
7463 var C_lib = C.lib;
7464 var WordArray = C_lib.WordArray;
7465 var C_enc = C.enc;
7466
7467 /**
7468 * Base64 encoding strategy.
7469 */
7470 var Base64 = C_enc.Base64 = {
7471 /**
7472 * Converts a word array to a Base64 string.
7473 *
7474 * @param {WordArray} wordArray The word array.
7475 *
7476 * @return {string} The Base64 string.
7477 *
7478 * @static
7479 *
7480 * @example
7481 *
7482 * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
7483 */
7484 stringify: function (wordArray) {
7485 // Shortcuts
7486 var words = wordArray.words;
7487 var sigBytes = wordArray.sigBytes;
7488 var map = this._map;
7489
7490 // Clamp excess bits
7491 wordArray.clamp();
7492
7493 // Convert
7494 var base64Chars = [];
7495 for (var i = 0; i < sigBytes; i += 3) {
7496 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
7497 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
7498 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
7499
7500 var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
7501
7502 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
7503 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
7504 }
7505 }
7506
7507 // Add padding
7508 var paddingChar = map.charAt(64);
7509 if (paddingChar) {
7510 while (base64Chars.length % 4) {
7511 base64Chars.push(paddingChar);
7512 }
7513 }
7514
7515 return base64Chars.join('');
7516 },
7517
7518 /**
7519 * Converts a Base64 string to a word array.
7520 *
7521 * @param {string} base64Str The Base64 string.
7522 *
7523 * @return {WordArray} The word array.
7524 *
7525 * @static
7526 *
7527 * @example
7528 *
7529 * var wordArray = CryptoJS.enc.Base64.parse(base64String);
7530 */
7531 parse: function (base64Str) {
7532 // Shortcuts
7533 var base64StrLength = base64Str.length;
7534 var map = this._map;
7535 var reverseMap = this._reverseMap;
7536
7537 if (!reverseMap) {
7538 reverseMap = this._reverseMap = [];
7539 for (var j = 0; j < map.length; j++) {
7540 reverseMap[map.charCodeAt(j)] = j;
7541 }
7542 }
7543
7544 // Ignore padding
7545 var paddingChar = map.charAt(64);
7546 if (paddingChar) {
7547 var paddingIndex = base64Str.indexOf(paddingChar);
7548 if (paddingIndex !== -1) {
7549 base64StrLength = paddingIndex;
7550 }
7551 }
7552
7553 // Convert
7554 return parseLoop(base64Str, base64StrLength, reverseMap);
7555
7556 },
7557
7558 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
7559 };
7560
7561 function parseLoop(base64Str, base64StrLength, reverseMap) {
7562 var words = [];
7563 var nBytes = 0;
7564 for (var i = 0; i < base64StrLength; i++) {
7565 if (i % 4) {
7566 var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
7567 var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
7568 words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
7569 nBytes++;
7570 }
7571 }
7572 return WordArray.create(words, nBytes);
7573 }
7574 }());
7575
7576
7577 return CryptoJS.enc.Base64;
7578
7579}));
7580
7581/***/ }),
7582/* 26 */
7583/***/ (function(module, __webpack_exports__, __webpack_require__) {
7584
7585"use strict";
7586/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CognitoUserPool; });
7587/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Client__ = __webpack_require__(27);
7588/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__CognitoUser__ = __webpack_require__(11);
7589/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__StorageHelper__ = __webpack_require__(15);
7590/*!
7591 * Copyright 2016 Amazon.com,
7592 * Inc. or its affiliates. All Rights Reserved.
7593 *
7594 * Licensed under the Amazon Software License (the "License").
7595 * You may not use this file except in compliance with the
7596 * License. A copy of the License is located at
7597 *
7598 * http://aws.amazon.com/asl/
7599 *
7600 * or in the "license" file accompanying this file. This file is
7601 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
7602 * CONDITIONS OF ANY KIND, express or implied. See the License
7603 * for the specific language governing permissions and
7604 * limitations under the License.
7605 */
7606
7607
7608
7609/** @class */
7610
7611var CognitoUserPool = /*#__PURE__*/function () {
7612 /**
7613 * Constructs a new CognitoUserPool object
7614 * @param {object} data Creation options.
7615 * @param {string} data.UserPoolId Cognito user pool id.
7616 * @param {string} data.ClientId User pool application client id.
7617 * @param {string} data.endpoint Optional custom service endpoint.
7618 * @param {object} data.fetchOptions Optional options for fetch API.
7619 * (only credentials option is supported)
7620 * @param {object} data.Storage Optional storage object.
7621 * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional:
7622 * boolean flag indicating if the data collection is enabled
7623 * to support cognito advanced security features. By default, this
7624 * flag is set to true.
7625 */
7626 function CognitoUserPool(data) {
7627 var _ref = data || {},
7628 UserPoolId = _ref.UserPoolId,
7629 ClientId = _ref.ClientId,
7630 endpoint = _ref.endpoint,
7631 fetchOptions = _ref.fetchOptions,
7632 AdvancedSecurityDataCollectionFlag = _ref.AdvancedSecurityDataCollectionFlag;
7633
7634 if (!UserPoolId || !ClientId) {
7635 throw new Error('Both UserPoolId and ClientId are required.');
7636 }
7637
7638 if (!/^[\w-]+_.+$/.test(UserPoolId)) {
7639 throw new Error('Invalid UserPoolId format.');
7640 }
7641
7642 var region = UserPoolId.split('_')[0];
7643 this.userPoolId = UserPoolId;
7644 this.clientId = ClientId;
7645 this.client = new __WEBPACK_IMPORTED_MODULE_0__Client__["a" /* default */](region, endpoint, fetchOptions);
7646 /**
7647 * By default, AdvancedSecurityDataCollectionFlag is set to true,
7648 * if no input value is provided.
7649 */
7650
7651 this.advancedSecurityDataCollectionFlag = AdvancedSecurityDataCollectionFlag !== false;
7652 this.storage = data.Storage || new __WEBPACK_IMPORTED_MODULE_2__StorageHelper__["a" /* default */]().getStorage();
7653 }
7654 /**
7655 * @returns {string} the user pool id
7656 */
7657
7658
7659 var _proto = CognitoUserPool.prototype;
7660
7661 _proto.getUserPoolId = function getUserPoolId() {
7662 return this.userPoolId;
7663 }
7664 /**
7665 * @returns {string} the client id
7666 */
7667 ;
7668
7669 _proto.getClientId = function getClientId() {
7670 return this.clientId;
7671 }
7672 /**
7673 * @typedef {object} SignUpResult
7674 * @property {CognitoUser} user New user.
7675 * @property {bool} userConfirmed If the user is already confirmed.
7676 */
7677
7678 /**
7679 * method for signing up a user
7680 * @param {string} username User's username.
7681 * @param {string} password Plain-text initial password entered by user.
7682 * @param {(AttributeArg[])=} userAttributes New user attributes.
7683 * @param {(AttributeArg[])=} validationData Application metadata.
7684 * @param {(AttributeArg[])=} clientMetadata Client metadata.
7685 * @param {nodeCallback<SignUpResult>} callback Called on error or with the new user.
7686 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
7687 * @returns {void}
7688 */
7689 ;
7690
7691 _proto.signUp = function signUp(username, password, userAttributes, validationData, callback, clientMetadata) {
7692 var _this = this;
7693
7694 var jsonReq = {
7695 ClientId: this.clientId,
7696 Username: username,
7697 Password: password,
7698 UserAttributes: userAttributes,
7699 ValidationData: validationData,
7700 ClientMetadata: clientMetadata
7701 };
7702
7703 if (this.getUserContextData(username)) {
7704 jsonReq.UserContextData = this.getUserContextData(username);
7705 }
7706
7707 this.client.request('SignUp', jsonReq, function (err, data) {
7708 if (err) {
7709 return callback(err, null);
7710 }
7711
7712 var cognitoUser = {
7713 Username: username,
7714 Pool: _this,
7715 Storage: _this.storage
7716 };
7717 var returnData = {
7718 user: new __WEBPACK_IMPORTED_MODULE_1__CognitoUser__["a" /* default */](cognitoUser),
7719 userConfirmed: data.UserConfirmed,
7720 userSub: data.UserSub,
7721 codeDeliveryDetails: data.CodeDeliveryDetails
7722 };
7723 return callback(null, returnData);
7724 });
7725 }
7726 /**
7727 * method for getting the current user of the application from the local storage
7728 *
7729 * @returns {CognitoUser} the user retrieved from storage
7730 */
7731 ;
7732
7733 _proto.getCurrentUser = function getCurrentUser() {
7734 var lastUserKey = "CognitoIdentityServiceProvider." + this.clientId + ".LastAuthUser";
7735 var lastAuthUser = this.storage.getItem(lastUserKey);
7736
7737 if (lastAuthUser) {
7738 var cognitoUser = {
7739 Username: lastAuthUser,
7740 Pool: this,
7741 Storage: this.storage
7742 };
7743 return new __WEBPACK_IMPORTED_MODULE_1__CognitoUser__["a" /* default */](cognitoUser);
7744 }
7745
7746 return null;
7747 }
7748 /**
7749 * This method returns the encoded data string used for cognito advanced security feature.
7750 * This would be generated only when developer has included the JS used for collecting the
7751 * data on their client. Please refer to documentation to know more about using AdvancedSecurity
7752 * features
7753 * @param {string} username the username for the context data
7754 * @returns {string} the user context data
7755 **/
7756 ;
7757
7758 _proto.getUserContextData = function getUserContextData(username) {
7759 if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') {
7760 return undefined;
7761 }
7762 /* eslint-disable */
7763
7764
7765 var amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData;
7766 /* eslint-enable */
7767
7768 if (this.advancedSecurityDataCollectionFlag) {
7769 var advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData(username, this.userPoolId, this.clientId);
7770
7771 if (advancedSecurityData) {
7772 var userContextData = {
7773 EncodedData: advancedSecurityData
7774 };
7775 return userContextData;
7776 }
7777 }
7778
7779 return {};
7780 };
7781
7782 return CognitoUserPool;
7783}();
7784
7785
7786
7787/***/ }),
7788/* 27 */
7789/***/ (function(module, __webpack_exports__, __webpack_require__) {
7790
7791"use strict";
7792/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Client; });
7793/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_isomorphic_unfetch__ = __webpack_require__(28);
7794/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_isomorphic_unfetch___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_isomorphic_unfetch__);
7795/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__UserAgent__ = __webpack_require__(17);
7796function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
7797
7798function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
7799
7800function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
7801
7802function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
7803
7804function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
7805
7806function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
7807
7808function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
7809
7810
7811
7812
7813var CognitoError = /*#__PURE__*/function (_Error) {
7814 _inheritsLoose(CognitoError, _Error);
7815
7816 function CognitoError(message, code, name, statusCode) {
7817 var _this;
7818
7819 _this = _Error.call(this, message) || this;
7820 _this.code = code;
7821 _this.name = name;
7822 _this.statusCode = statusCode;
7823 return _this;
7824 }
7825
7826 return CognitoError;
7827}( /*#__PURE__*/_wrapNativeSuper(Error));
7828/** @class */
7829
7830
7831var Client = /*#__PURE__*/function () {
7832 /**
7833 * Constructs a new AWS Cognito Identity Provider client object
7834 * @param {string} region AWS region
7835 * @param {string} endpoint endpoint
7836 * @param {object} fetchOptions options for fetch API (only credentials is supported)
7837 */
7838 function Client(region, endpoint, fetchOptions) {
7839 this.endpoint = endpoint || "https://cognito-idp." + region + ".amazonaws.com/";
7840
7841 var _ref = fetchOptions || {},
7842 credentials = _ref.credentials;
7843
7844 this.fetchOptions = credentials ? {
7845 credentials: credentials
7846 } : {};
7847 }
7848 /**
7849 * Makes an unauthenticated request on AWS Cognito Identity Provider API
7850 * using fetch
7851 * @param {string} operation API operation
7852 * @param {object} params Input parameters
7853 * @returns Promise<object>
7854 */
7855
7856
7857 var _proto = Client.prototype;
7858
7859 _proto.promisifyRequest = function promisifyRequest(operation, params) {
7860 var _this2 = this;
7861
7862 return new Promise(function (resolve, reject) {
7863 _this2.request(operation, params, function (err, data) {
7864 if (err) {
7865 reject(new CognitoError(err.message, err.code, err.name, err.statusCode));
7866 } else {
7867 resolve(data);
7868 }
7869 });
7870 });
7871 }
7872 /**
7873 * Makes an unauthenticated request on AWS Cognito Identity Provider API
7874 * using fetch
7875 * @param {string} operation API operation
7876 * @param {object} params Input parameters
7877 * @param {function} callback Callback called when a response is returned
7878 * @returns {void}
7879 */
7880 ;
7881
7882 _proto.request = function request(operation, params, callback) {
7883 var headers = {
7884 'Content-Type': 'application/x-amz-json-1.1',
7885 'X-Amz-Target': "AWSCognitoIdentityProviderService." + operation,
7886 'X-Amz-User-Agent': __WEBPACK_IMPORTED_MODULE_1__UserAgent__["b" /* default */].prototype.userAgent
7887 };
7888 var options = Object.assign({}, this.fetchOptions, {
7889 headers: headers,
7890 method: 'POST',
7891 mode: 'cors',
7892 cache: 'no-cache',
7893 body: JSON.stringify(params)
7894 });
7895 var response;
7896 var responseJsonData;
7897 fetch(this.endpoint, options).then(function (resp) {
7898 response = resp;
7899 return resp;
7900 }, function (err) {
7901 // If error happens here, the request failed
7902 // if it is TypeError throw network error
7903 if (err instanceof TypeError) {
7904 throw new Error('Network error');
7905 }
7906
7907 throw err;
7908 }).then(function (resp) {
7909 return resp.json()["catch"](function () {
7910 return {};
7911 });
7912 }).then(function (data) {
7913 // return parsed body stream
7914 if (response.ok) return callback(null, data);
7915 responseJsonData = data; // Taken from aws-sdk-js/lib/protocol/json.js
7916 // eslint-disable-next-line no-underscore-dangle
7917
7918 var code = (data.__type || data.code).split('#').pop();
7919 var error = {
7920 code: code,
7921 name: code,
7922 message: data.message || data.Message || null
7923 };
7924 return callback(error);
7925 })["catch"](function (err) {
7926 // first check if we have a service error
7927 if (response && response.headers && response.headers.get('x-amzn-errortype')) {
7928 try {
7929 var code = response.headers.get('x-amzn-errortype').split(':')[0];
7930 var error = {
7931 code: code,
7932 name: code,
7933 statusCode: response.status,
7934 message: response.status ? response.status.toString() : null
7935 };
7936 return callback(error);
7937 } catch (ex) {
7938 return callback(err);
7939 } // otherwise check if error is Network error
7940
7941 } else if (err instanceof Error && err.message === 'Network error') {
7942 var _error = {
7943 code: 'NetworkError',
7944 name: err.name,
7945 message: err.message
7946 };
7947 return callback(_error);
7948 } else {
7949 return callback(err);
7950 }
7951 });
7952 };
7953
7954 return Client;
7955}();
7956
7957
7958
7959/***/ }),
7960/* 28 */
7961/***/ (function(module, exports, __webpack_require__) {
7962
7963module.exports = window.fetch || (window.fetch = __webpack_require__(16).default || __webpack_require__(16));
7964
7965
7966/***/ }),
7967/* 29 */
7968/***/ (function(module, __webpack_exports__, __webpack_require__) {
7969
7970"use strict";
7971/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CookieStorage; });
7972/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_js_cookie__ = __webpack_require__(30);
7973/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_js_cookie___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_js_cookie__);
7974
7975/** @class */
7976
7977var CookieStorage = /*#__PURE__*/function () {
7978 /**
7979 * Constructs a new CookieStorage object
7980 * @param {object} data Creation options.
7981 * @param {string} data.domain Cookies domain (mandatory).
7982 * @param {string} data.path Cookies path (default: '/')
7983 * @param {integer} data.expires Cookie expiration (in days, default: 365)
7984 * @param {boolean} data.secure Cookie secure flag (default: true)
7985 * @param {string} data.sameSite Cookie request behaviour (default: null)
7986 */
7987 function CookieStorage(data) {
7988 if (data.domain) {
7989 this.domain = data.domain;
7990 } else {
7991 throw new Error('The domain of cookieStorage can not be undefined.');
7992 }
7993
7994 if (data.path) {
7995 this.path = data.path;
7996 } else {
7997 this.path = '/';
7998 }
7999
8000 if (Object.prototype.hasOwnProperty.call(data, 'expires')) {
8001 this.expires = data.expires;
8002 } else {
8003 this.expires = 365;
8004 }
8005
8006 if (Object.prototype.hasOwnProperty.call(data, 'secure')) {
8007 this.secure = data.secure;
8008 } else {
8009 this.secure = true;
8010 }
8011
8012 if (Object.prototype.hasOwnProperty.call(data, 'sameSite')) {
8013 if (!['strict', 'lax', 'none'].includes(data.sameSite)) {
8014 throw new Error('The sameSite value of cookieStorage must be "lax", "strict" or "none".');
8015 }
8016
8017 if (data.sameSite === 'none' && !this.secure) {
8018 throw new Error('sameSite = None requires the Secure attribute in latest browser versions.');
8019 }
8020
8021 this.sameSite = data.sameSite;
8022 } else {
8023 this.sameSite = null;
8024 }
8025 }
8026 /**
8027 * This is used to set a specific item in storage
8028 * @param {string} key - the key for the item
8029 * @param {object} value - the value
8030 * @returns {string} value that was set
8031 */
8032
8033
8034 var _proto = CookieStorage.prototype;
8035
8036 _proto.setItem = function setItem(key, value) {
8037 var options = {
8038 path: this.path,
8039 expires: this.expires,
8040 domain: this.domain,
8041 secure: this.secure
8042 };
8043
8044 if (this.sameSite) {
8045 options.sameSite = this.sameSite;
8046 }
8047
8048 __WEBPACK_IMPORTED_MODULE_0_js_cookie__["set"](key, value, options);
8049 return __WEBPACK_IMPORTED_MODULE_0_js_cookie__["get"](key);
8050 }
8051 /**
8052 * This is used to get a specific key from storage
8053 * @param {string} key - the key for the item
8054 * This is used to clear the storage
8055 * @returns {string} the data item
8056 */
8057 ;
8058
8059 _proto.getItem = function getItem(key) {
8060 return __WEBPACK_IMPORTED_MODULE_0_js_cookie__["get"](key);
8061 }
8062 /**
8063 * This is used to remove an item from storage
8064 * @param {string} key - the key being set
8065 * @returns {string} value - value that was deleted
8066 */
8067 ;
8068
8069 _proto.removeItem = function removeItem(key) {
8070 var options = {
8071 path: this.path,
8072 expires: this.expires,
8073 domain: this.domain,
8074 secure: this.secure
8075 };
8076
8077 if (this.sameSite) {
8078 options.sameSite = this.sameSite;
8079 }
8080
8081 return __WEBPACK_IMPORTED_MODULE_0_js_cookie__["remove"](key, options);
8082 }
8083 /**
8084 * This is used to clear the storage
8085 * @returns {string} nothing
8086 */
8087 ;
8088
8089 _proto.clear = function clear() {
8090 var cookies = __WEBPACK_IMPORTED_MODULE_0_js_cookie__["get"]();
8091 var index;
8092
8093 for (index = 0; index < cookies.length; ++index) {
8094 __WEBPACK_IMPORTED_MODULE_0_js_cookie__["remove"](cookies[index]);
8095 }
8096
8097 return {};
8098 };
8099
8100 return CookieStorage;
8101}();
8102
8103
8104
8105/***/ }),
8106/* 30 */
8107/***/ (function(module, exports, __webpack_require__) {
8108
8109var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
8110 * JavaScript Cookie v2.2.1
8111 * https://github.com/js-cookie/js-cookie
8112 *
8113 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
8114 * Released under the MIT license
8115 */
8116;(function (factory) {
8117 var registeredInModuleLoader;
8118 if (true) {
8119 !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
8120 __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
8121 (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
8122 __WEBPACK_AMD_DEFINE_FACTORY__),
8123 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
8124 registeredInModuleLoader = true;
8125 }
8126 if (true) {
8127 module.exports = factory();
8128 registeredInModuleLoader = true;
8129 }
8130 if (!registeredInModuleLoader) {
8131 var OldCookies = window.Cookies;
8132 var api = window.Cookies = factory();
8133 api.noConflict = function () {
8134 window.Cookies = OldCookies;
8135 return api;
8136 };
8137 }
8138}(function () {
8139 function extend () {
8140 var i = 0;
8141 var result = {};
8142 for (; i < arguments.length; i++) {
8143 var attributes = arguments[ i ];
8144 for (var key in attributes) {
8145 result[key] = attributes[key];
8146 }
8147 }
8148 return result;
8149 }
8150
8151 function decode (s) {
8152 return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
8153 }
8154
8155 function init (converter) {
8156 function api() {}
8157
8158 function set (key, value, attributes) {
8159 if (typeof document === 'undefined') {
8160 return;
8161 }
8162
8163 attributes = extend({
8164 path: '/'
8165 }, api.defaults, attributes);
8166
8167 if (typeof attributes.expires === 'number') {
8168 attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
8169 }
8170
8171 // We're using "expires" because "max-age" is not supported by IE
8172 attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
8173
8174 try {
8175 var result = JSON.stringify(value);
8176 if (/^[\{\[]/.test(result)) {
8177 value = result;
8178 }
8179 } catch (e) {}
8180
8181 value = converter.write ?
8182 converter.write(value, key) :
8183 encodeURIComponent(String(value))
8184 .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
8185
8186 key = encodeURIComponent(String(key))
8187 .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
8188 .replace(/[\(\)]/g, escape);
8189
8190 var stringifiedAttributes = '';
8191 for (var attributeName in attributes) {
8192 if (!attributes[attributeName]) {
8193 continue;
8194 }
8195 stringifiedAttributes += '; ' + attributeName;
8196 if (attributes[attributeName] === true) {
8197 continue;
8198 }
8199
8200 // Considers RFC 6265 section 5.2:
8201 // ...
8202 // 3. If the remaining unparsed-attributes contains a %x3B (";")
8203 // character:
8204 // Consume the characters of the unparsed-attributes up to,
8205 // not including, the first %x3B (";") character.
8206 // ...
8207 stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
8208 }
8209
8210 return (document.cookie = key + '=' + value + stringifiedAttributes);
8211 }
8212
8213 function get (key, json) {
8214 if (typeof document === 'undefined') {
8215 return;
8216 }
8217
8218 var jar = {};
8219 // To prevent the for loop in the first place assign an empty array
8220 // in case there are no cookies at all.
8221 var cookies = document.cookie ? document.cookie.split('; ') : [];
8222 var i = 0;
8223
8224 for (; i < cookies.length; i++) {
8225 var parts = cookies[i].split('=');
8226 var cookie = parts.slice(1).join('=');
8227
8228 if (!json && cookie.charAt(0) === '"') {
8229 cookie = cookie.slice(1, -1);
8230 }
8231
8232 try {
8233 var name = decode(parts[0]);
8234 cookie = (converter.read || converter)(cookie, name) ||
8235 decode(cookie);
8236
8237 if (json) {
8238 try {
8239 cookie = JSON.parse(cookie);
8240 } catch (e) {}
8241 }
8242
8243 jar[name] = cookie;
8244
8245 if (key === name) {
8246 break;
8247 }
8248 } catch (e) {}
8249 }
8250
8251 return key ? jar[key] : jar;
8252 }
8253
8254 api.set = set;
8255 api.get = function (key) {
8256 return get(key, false /* read as raw */);
8257 };
8258 api.getJSON = function (key) {
8259 return get(key, true /* read as json */);
8260 };
8261 api.remove = function (key, attributes) {
8262 set(key, '', extend(attributes, {
8263 expires: -1
8264 }));
8265 };
8266
8267 api.defaults = {};
8268
8269 api.withConverter = init;
8270
8271 return api;
8272 }
8273
8274 return init(function () {});
8275}));
8276
8277
8278/***/ })
8279/******/ ]);
8280});
\No newline at end of file