UNPKG

76.1 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3 typeof define === 'function' && define.amd ? define(['exports'], factory) :
4 (global = global || self, factory(global.CommercetoolsSdkMiddlewareAuth = {}));
5}(this, (function (exports) { 'use strict';
6
7 function _defineProperty(obj, key, value) {
8 if (key in obj) {
9 Object.defineProperty(obj, key, {
10 value: value,
11 enumerable: true,
12 configurable: true,
13 writable: true
14 });
15 } else {
16 obj[key] = value;
17 }
18
19 return obj;
20 }
21
22 function ownKeys(object, enumerableOnly) {
23 var keys = Object.keys(object);
24
25 if (Object.getOwnPropertySymbols) {
26 var symbols = Object.getOwnPropertySymbols(object);
27 if (enumerableOnly) symbols = symbols.filter(function (sym) {
28 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
29 });
30 keys.push.apply(keys, symbols);
31 }
32
33 return keys;
34 }
35
36 function _objectSpread2(target) {
37 for (var i = 1; i < arguments.length; i++) {
38 var source = arguments[i] != null ? arguments[i] : {};
39
40 if (i % 2) {
41 ownKeys(Object(source), true).forEach(function (key) {
42 _defineProperty(target, key, source[key]);
43 });
44 } else if (Object.getOwnPropertyDescriptors) {
45 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
46 } else {
47 ownKeys(Object(source)).forEach(function (key) {
48 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
49 });
50 }
51 }
52
53 return target;
54 }
55
56 var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
57
58 var lookup = [];
59 var revLookup = [];
60 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
61 var inited = false;
62
63 function init() {
64 inited = true;
65 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
66
67 for (var i = 0, len = code.length; i < len; ++i) {
68 lookup[i] = code[i];
69 revLookup[code.charCodeAt(i)] = i;
70 }
71
72 revLookup['-'.charCodeAt(0)] = 62;
73 revLookup['_'.charCodeAt(0)] = 63;
74 }
75
76 function toByteArray(b64) {
77 if (!inited) {
78 init();
79 }
80
81 var i, j, l, tmp, placeHolders, arr;
82 var len = b64.length;
83
84 if (len % 4 > 0) {
85 throw new Error('Invalid string. Length must be a multiple of 4');
86 } // the number of equal signs (place holders)
87 // if there are two placeholders, than the two characters before it
88 // represent one byte
89 // if there is only one, then the three characters before it represent 2 bytes
90 // this is just a cheap hack to not do indexOf twice
91
92
93 placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data
94
95 arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars
96
97 l = placeHolders > 0 ? len - 4 : len;
98 var L = 0;
99
100 for (i = 0, j = 0; i < l; i += 4, j += 3) {
101 tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
102 arr[L++] = tmp >> 16 & 0xFF;
103 arr[L++] = tmp >> 8 & 0xFF;
104 arr[L++] = tmp & 0xFF;
105 }
106
107 if (placeHolders === 2) {
108 tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
109 arr[L++] = tmp & 0xFF;
110 } else if (placeHolders === 1) {
111 tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
112 arr[L++] = tmp >> 8 & 0xFF;
113 arr[L++] = tmp & 0xFF;
114 }
115
116 return arr;
117 }
118
119 function tripletToBase64(num) {
120 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
121 }
122
123 function encodeChunk(uint8, start, end) {
124 var tmp;
125 var output = [];
126
127 for (var i = start; i < end; i += 3) {
128 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
129 output.push(tripletToBase64(tmp));
130 }
131
132 return output.join('');
133 }
134
135 function fromByteArray(uint8) {
136 if (!inited) {
137 init();
138 }
139
140 var tmp;
141 var len = uint8.length;
142 var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
143
144 var output = '';
145 var parts = [];
146 var maxChunkLength = 16383; // must be multiple of 3
147 // go through the array every three bytes, we'll deal with trailing stuff later
148
149 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
150 parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
151 } // pad the end with zeros, but make sure to not forget the extra bytes
152
153
154 if (extraBytes === 1) {
155 tmp = uint8[len - 1];
156 output += lookup[tmp >> 2];
157 output += lookup[tmp << 4 & 0x3F];
158 output += '==';
159 } else if (extraBytes === 2) {
160 tmp = (uint8[len - 2] << 8) + uint8[len - 1];
161 output += lookup[tmp >> 10];
162 output += lookup[tmp >> 4 & 0x3F];
163 output += lookup[tmp << 2 & 0x3F];
164 output += '=';
165 }
166
167 parts.push(output);
168 return parts.join('');
169 }
170
171 function read(buffer, offset, isLE, mLen, nBytes) {
172 var e, m;
173 var eLen = nBytes * 8 - mLen - 1;
174 var eMax = (1 << eLen) - 1;
175 var eBias = eMax >> 1;
176 var nBits = -7;
177 var i = isLE ? nBytes - 1 : 0;
178 var d = isLE ? -1 : 1;
179 var s = buffer[offset + i];
180 i += d;
181 e = s & (1 << -nBits) - 1;
182 s >>= -nBits;
183 nBits += eLen;
184
185 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
186
187 m = e & (1 << -nBits) - 1;
188 e >>= -nBits;
189 nBits += mLen;
190
191 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
192
193 if (e === 0) {
194 e = 1 - eBias;
195 } else if (e === eMax) {
196 return m ? NaN : (s ? -1 : 1) * Infinity;
197 } else {
198 m = m + Math.pow(2, mLen);
199 e = e - eBias;
200 }
201
202 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
203 }
204 function write(buffer, value, offset, isLE, mLen, nBytes) {
205 var e, m, c;
206 var eLen = nBytes * 8 - mLen - 1;
207 var eMax = (1 << eLen) - 1;
208 var eBias = eMax >> 1;
209 var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
210 var i = isLE ? 0 : nBytes - 1;
211 var d = isLE ? 1 : -1;
212 var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
213 value = Math.abs(value);
214
215 if (isNaN(value) || value === Infinity) {
216 m = isNaN(value) ? 1 : 0;
217 e = eMax;
218 } else {
219 e = Math.floor(Math.log(value) / Math.LN2);
220
221 if (value * (c = Math.pow(2, -e)) < 1) {
222 e--;
223 c *= 2;
224 }
225
226 if (e + eBias >= 1) {
227 value += rt / c;
228 } else {
229 value += rt * Math.pow(2, 1 - eBias);
230 }
231
232 if (value * c >= 2) {
233 e++;
234 c /= 2;
235 }
236
237 if (e + eBias >= eMax) {
238 m = 0;
239 e = eMax;
240 } else if (e + eBias >= 1) {
241 m = (value * c - 1) * Math.pow(2, mLen);
242 e = e + eBias;
243 } else {
244 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
245 e = 0;
246 }
247 }
248
249 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
250
251 e = e << mLen | m;
252 eLen += mLen;
253
254 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
255
256 buffer[offset + i - d] |= s * 128;
257 }
258
259 var toString = {}.toString;
260 var isArray = Array.isArray || function (arr) {
261 return toString.call(arr) == '[object Array]';
262 };
263
264 var INSPECT_MAX_BYTES = 50;
265 /**
266 * If `Buffer.TYPED_ARRAY_SUPPORT`:
267 * === true Use Uint8Array implementation (fastest)
268 * === false Use Object implementation (most compatible, even IE6)
269 *
270 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
271 * Opera 11.6+, iOS 4.2+.
272 *
273 * Due to various browser bugs, sometimes the Object implementation will be used even
274 * when the browser supports typed arrays.
275 *
276 * Note:
277 *
278 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
279 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
280 *
281 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
282 *
283 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
284 * incorrect length in some situations.
285
286 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
287 * get the Object implementation, which is slower but behaves correctly.
288 */
289
290 Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true;
291
292 function kMaxLength() {
293 return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff;
294 }
295
296 function createBuffer(that, length) {
297 if (kMaxLength() < length) {
298 throw new RangeError('Invalid typed array length');
299 }
300
301 if (Buffer.TYPED_ARRAY_SUPPORT) {
302 // Return an augmented `Uint8Array` instance, for best performance
303 that = new Uint8Array(length);
304 that.__proto__ = Buffer.prototype;
305 } else {
306 // Fallback: Return an object instance of the Buffer class
307 if (that === null) {
308 that = new Buffer(length);
309 }
310
311 that.length = length;
312 }
313
314 return that;
315 }
316 /**
317 * The Buffer constructor returns instances of `Uint8Array` that have their
318 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
319 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
320 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
321 * returns a single octet.
322 *
323 * The `Uint8Array` prototype remains unmodified.
324 */
325
326
327 function Buffer(arg, encodingOrOffset, length) {
328 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
329 return new Buffer(arg, encodingOrOffset, length);
330 } // Common case.
331
332
333 if (typeof arg === 'number') {
334 if (typeof encodingOrOffset === 'string') {
335 throw new Error('If encoding is specified then the first argument must be a string');
336 }
337
338 return allocUnsafe(this, arg);
339 }
340
341 return from(this, arg, encodingOrOffset, length);
342 }
343 Buffer.poolSize = 8192; // not used by this implementation
344 // TODO: Legacy, not needed anymore. Remove in next major version.
345
346 Buffer._augment = function (arr) {
347 arr.__proto__ = Buffer.prototype;
348 return arr;
349 };
350
351 function from(that, value, encodingOrOffset, length) {
352 if (typeof value === 'number') {
353 throw new TypeError('"value" argument must not be a number');
354 }
355
356 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
357 return fromArrayBuffer(that, value, encodingOrOffset, length);
358 }
359
360 if (typeof value === 'string') {
361 return fromString(that, value, encodingOrOffset);
362 }
363
364 return fromObject(that, value);
365 }
366 /**
367 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
368 * if value is a number.
369 * Buffer.from(str[, encoding])
370 * Buffer.from(array)
371 * Buffer.from(buffer)
372 * Buffer.from(arrayBuffer[, byteOffset[, length]])
373 **/
374
375
376 Buffer.from = function (value, encodingOrOffset, length) {
377 return from(null, value, encodingOrOffset, length);
378 };
379
380 if (Buffer.TYPED_ARRAY_SUPPORT) {
381 Buffer.prototype.__proto__ = Uint8Array.prototype;
382 Buffer.__proto__ = Uint8Array;
383 }
384
385 function assertSize(size) {
386 if (typeof size !== 'number') {
387 throw new TypeError('"size" argument must be a number');
388 } else if (size < 0) {
389 throw new RangeError('"size" argument must not be negative');
390 }
391 }
392
393 function alloc(that, size, fill, encoding) {
394 assertSize(size);
395
396 if (size <= 0) {
397 return createBuffer(that, size);
398 }
399
400 if (fill !== undefined) {
401 // Only pay attention to encoding if it's a string. This
402 // prevents accidentally sending in a number that would
403 // be interpretted as a start offset.
404 return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill);
405 }
406
407 return createBuffer(that, size);
408 }
409 /**
410 * Creates a new filled Buffer instance.
411 * alloc(size[, fill[, encoding]])
412 **/
413
414
415 Buffer.alloc = function (size, fill, encoding) {
416 return alloc(null, size, fill, encoding);
417 };
418
419 function allocUnsafe(that, size) {
420 assertSize(size);
421 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
422
423 if (!Buffer.TYPED_ARRAY_SUPPORT) {
424 for (var i = 0; i < size; ++i) {
425 that[i] = 0;
426 }
427 }
428
429 return that;
430 }
431 /**
432 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
433 * */
434
435
436 Buffer.allocUnsafe = function (size) {
437 return allocUnsafe(null, size);
438 };
439 /**
440 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
441 */
442
443
444 Buffer.allocUnsafeSlow = function (size) {
445 return allocUnsafe(null, size);
446 };
447
448 function fromString(that, string, encoding) {
449 if (typeof encoding !== 'string' || encoding === '') {
450 encoding = 'utf8';
451 }
452
453 if (!Buffer.isEncoding(encoding)) {
454 throw new TypeError('"encoding" must be a valid string encoding');
455 }
456
457 var length = byteLength(string, encoding) | 0;
458 that = createBuffer(that, length);
459 var actual = that.write(string, encoding);
460
461 if (actual !== length) {
462 // Writing a hex string, for example, that contains invalid characters will
463 // cause everything after the first invalid character to be ignored. (e.g.
464 // 'abxxcd' will be treated as 'ab')
465 that = that.slice(0, actual);
466 }
467
468 return that;
469 }
470
471 function fromArrayLike(that, array) {
472 var length = array.length < 0 ? 0 : checked(array.length) | 0;
473 that = createBuffer(that, length);
474
475 for (var i = 0; i < length; i += 1) {
476 that[i] = array[i] & 255;
477 }
478
479 return that;
480 }
481
482 function fromArrayBuffer(that, array, byteOffset, length) {
483 array.byteLength; // this throws if `array` is not a valid ArrayBuffer
484
485 if (byteOffset < 0 || array.byteLength < byteOffset) {
486 throw new RangeError('\'offset\' is out of bounds');
487 }
488
489 if (array.byteLength < byteOffset + (length || 0)) {
490 throw new RangeError('\'length\' is out of bounds');
491 }
492
493 if (byteOffset === undefined && length === undefined) {
494 array = new Uint8Array(array);
495 } else if (length === undefined) {
496 array = new Uint8Array(array, byteOffset);
497 } else {
498 array = new Uint8Array(array, byteOffset, length);
499 }
500
501 if (Buffer.TYPED_ARRAY_SUPPORT) {
502 // Return an augmented `Uint8Array` instance, for best performance
503 that = array;
504 that.__proto__ = Buffer.prototype;
505 } else {
506 // Fallback: Return an object instance of the Buffer class
507 that = fromArrayLike(that, array);
508 }
509
510 return that;
511 }
512
513 function fromObject(that, obj) {
514 if (internalIsBuffer(obj)) {
515 var len = checked(obj.length) | 0;
516 that = createBuffer(that, len);
517
518 if (that.length === 0) {
519 return that;
520 }
521
522 obj.copy(that, 0, 0, len);
523 return that;
524 }
525
526 if (obj) {
527 if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) {
528 if (typeof obj.length !== 'number' || isnan(obj.length)) {
529 return createBuffer(that, 0);
530 }
531
532 return fromArrayLike(that, obj);
533 }
534
535 if (obj.type === 'Buffer' && isArray(obj.data)) {
536 return fromArrayLike(that, obj.data);
537 }
538 }
539
540 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.');
541 }
542
543 function checked(length) {
544 // Note: cannot use `length < kMaxLength()` here because that fails when
545 // length is NaN (which is otherwise coerced to zero.)
546 if (length >= kMaxLength()) {
547 throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes');
548 }
549
550 return length | 0;
551 }
552 Buffer.isBuffer = isBuffer;
553
554 function internalIsBuffer(b) {
555 return !!(b != null && b._isBuffer);
556 }
557
558 Buffer.compare = function compare(a, b) {
559 if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
560 throw new TypeError('Arguments must be Buffers');
561 }
562
563 if (a === b) return 0;
564 var x = a.length;
565 var y = b.length;
566
567 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
568 if (a[i] !== b[i]) {
569 x = a[i];
570 y = b[i];
571 break;
572 }
573 }
574
575 if (x < y) return -1;
576 if (y < x) return 1;
577 return 0;
578 };
579
580 Buffer.isEncoding = function isEncoding(encoding) {
581 switch (String(encoding).toLowerCase()) {
582 case 'hex':
583 case 'utf8':
584 case 'utf-8':
585 case 'ascii':
586 case 'latin1':
587 case 'binary':
588 case 'base64':
589 case 'ucs2':
590 case 'ucs-2':
591 case 'utf16le':
592 case 'utf-16le':
593 return true;
594
595 default:
596 return false;
597 }
598 };
599
600 Buffer.concat = function concat(list, length) {
601 if (!isArray(list)) {
602 throw new TypeError('"list" argument must be an Array of Buffers');
603 }
604
605 if (list.length === 0) {
606 return Buffer.alloc(0);
607 }
608
609 var i;
610
611 if (length === undefined) {
612 length = 0;
613
614 for (i = 0; i < list.length; ++i) {
615 length += list[i].length;
616 }
617 }
618
619 var buffer = Buffer.allocUnsafe(length);
620 var pos = 0;
621
622 for (i = 0; i < list.length; ++i) {
623 var buf = list[i];
624
625 if (!internalIsBuffer(buf)) {
626 throw new TypeError('"list" argument must be an Array of Buffers');
627 }
628
629 buf.copy(buffer, pos);
630 pos += buf.length;
631 }
632
633 return buffer;
634 };
635
636 function byteLength(string, encoding) {
637 if (internalIsBuffer(string)) {
638 return string.length;
639 }
640
641 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
642 return string.byteLength;
643 }
644
645 if (typeof string !== 'string') {
646 string = '' + string;
647 }
648
649 var len = string.length;
650 if (len === 0) return 0; // Use a for loop to avoid recursion
651
652 var loweredCase = false;
653
654 for (;;) {
655 switch (encoding) {
656 case 'ascii':
657 case 'latin1':
658 case 'binary':
659 return len;
660
661 case 'utf8':
662 case 'utf-8':
663 case undefined:
664 return utf8ToBytes(string).length;
665
666 case 'ucs2':
667 case 'ucs-2':
668 case 'utf16le':
669 case 'utf-16le':
670 return len * 2;
671
672 case 'hex':
673 return len >>> 1;
674
675 case 'base64':
676 return base64ToBytes(string).length;
677
678 default:
679 if (loweredCase) return utf8ToBytes(string).length; // assume utf8
680
681 encoding = ('' + encoding).toLowerCase();
682 loweredCase = true;
683 }
684 }
685 }
686
687 Buffer.byteLength = byteLength;
688
689 function slowToString(encoding, start, end) {
690 var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
691 // property of a typed array.
692 // This behaves neither like String nor Uint8Array in that we set start/end
693 // to their upper/lower bounds if the value passed is out of range.
694 // undefined is handled specially as per ECMA-262 6th Edition,
695 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
696
697 if (start === undefined || start < 0) {
698 start = 0;
699 } // Return early if start > this.length. Done here to prevent potential uint32
700 // coercion fail below.
701
702
703 if (start > this.length) {
704 return '';
705 }
706
707 if (end === undefined || end > this.length) {
708 end = this.length;
709 }
710
711 if (end <= 0) {
712 return '';
713 } // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
714
715
716 end >>>= 0;
717 start >>>= 0;
718
719 if (end <= start) {
720 return '';
721 }
722
723 if (!encoding) encoding = 'utf8';
724
725 while (true) {
726 switch (encoding) {
727 case 'hex':
728 return hexSlice(this, start, end);
729
730 case 'utf8':
731 case 'utf-8':
732 return utf8Slice(this, start, end);
733
734 case 'ascii':
735 return asciiSlice(this, start, end);
736
737 case 'latin1':
738 case 'binary':
739 return latin1Slice(this, start, end);
740
741 case 'base64':
742 return base64Slice(this, start, end);
743
744 case 'ucs2':
745 case 'ucs-2':
746 case 'utf16le':
747 case 'utf-16le':
748 return utf16leSlice(this, start, end);
749
750 default:
751 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
752 encoding = (encoding + '').toLowerCase();
753 loweredCase = true;
754 }
755 }
756 } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
757 // Buffer instances.
758
759
760 Buffer.prototype._isBuffer = true;
761
762 function swap(b, n, m) {
763 var i = b[n];
764 b[n] = b[m];
765 b[m] = i;
766 }
767
768 Buffer.prototype.swap16 = function swap16() {
769 var len = this.length;
770
771 if (len % 2 !== 0) {
772 throw new RangeError('Buffer size must be a multiple of 16-bits');
773 }
774
775 for (var i = 0; i < len; i += 2) {
776 swap(this, i, i + 1);
777 }
778
779 return this;
780 };
781
782 Buffer.prototype.swap32 = function swap32() {
783 var len = this.length;
784
785 if (len % 4 !== 0) {
786 throw new RangeError('Buffer size must be a multiple of 32-bits');
787 }
788
789 for (var i = 0; i < len; i += 4) {
790 swap(this, i, i + 3);
791 swap(this, i + 1, i + 2);
792 }
793
794 return this;
795 };
796
797 Buffer.prototype.swap64 = function swap64() {
798 var len = this.length;
799
800 if (len % 8 !== 0) {
801 throw new RangeError('Buffer size must be a multiple of 64-bits');
802 }
803
804 for (var i = 0; i < len; i += 8) {
805 swap(this, i, i + 7);
806 swap(this, i + 1, i + 6);
807 swap(this, i + 2, i + 5);
808 swap(this, i + 3, i + 4);
809 }
810
811 return this;
812 };
813
814 Buffer.prototype.toString = function toString() {
815 var length = this.length | 0;
816 if (length === 0) return '';
817 if (arguments.length === 0) return utf8Slice(this, 0, length);
818 return slowToString.apply(this, arguments);
819 };
820
821 Buffer.prototype.equals = function equals(b) {
822 if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer');
823 if (this === b) return true;
824 return Buffer.compare(this, b) === 0;
825 };
826
827 Buffer.prototype.inspect = function inspect() {
828 var str = '';
829 var max = INSPECT_MAX_BYTES;
830
831 if (this.length > 0) {
832 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
833 if (this.length > max) str += ' ... ';
834 }
835
836 return '<Buffer ' + str + '>';
837 };
838
839 Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
840 if (!internalIsBuffer(target)) {
841 throw new TypeError('Argument must be a Buffer');
842 }
843
844 if (start === undefined) {
845 start = 0;
846 }
847
848 if (end === undefined) {
849 end = target ? target.length : 0;
850 }
851
852 if (thisStart === undefined) {
853 thisStart = 0;
854 }
855
856 if (thisEnd === undefined) {
857 thisEnd = this.length;
858 }
859
860 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
861 throw new RangeError('out of range index');
862 }
863
864 if (thisStart >= thisEnd && start >= end) {
865 return 0;
866 }
867
868 if (thisStart >= thisEnd) {
869 return -1;
870 }
871
872 if (start >= end) {
873 return 1;
874 }
875
876 start >>>= 0;
877 end >>>= 0;
878 thisStart >>>= 0;
879 thisEnd >>>= 0;
880 if (this === target) return 0;
881 var x = thisEnd - thisStart;
882 var y = end - start;
883 var len = Math.min(x, y);
884 var thisCopy = this.slice(thisStart, thisEnd);
885 var targetCopy = target.slice(start, end);
886
887 for (var i = 0; i < len; ++i) {
888 if (thisCopy[i] !== targetCopy[i]) {
889 x = thisCopy[i];
890 y = targetCopy[i];
891 break;
892 }
893 }
894
895 if (x < y) return -1;
896 if (y < x) return 1;
897 return 0;
898 }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
899 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
900 //
901 // Arguments:
902 // - buffer - a Buffer to search
903 // - val - a string, Buffer, or number
904 // - byteOffset - an index into `buffer`; will be clamped to an int32
905 // - encoding - an optional encoding, relevant is val is a string
906 // - dir - true for indexOf, false for lastIndexOf
907
908
909 function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
910 // Empty buffer means no match
911 if (buffer.length === 0) return -1; // Normalize byteOffset
912
913 if (typeof byteOffset === 'string') {
914 encoding = byteOffset;
915 byteOffset = 0;
916 } else if (byteOffset > 0x7fffffff) {
917 byteOffset = 0x7fffffff;
918 } else if (byteOffset < -0x80000000) {
919 byteOffset = -0x80000000;
920 }
921
922 byteOffset = +byteOffset; // Coerce to Number.
923
924 if (isNaN(byteOffset)) {
925 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
926 byteOffset = dir ? 0 : buffer.length - 1;
927 } // Normalize byteOffset: negative offsets start from the end of the buffer
928
929
930 if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
931
932 if (byteOffset >= buffer.length) {
933 if (dir) return -1;else byteOffset = buffer.length - 1;
934 } else if (byteOffset < 0) {
935 if (dir) byteOffset = 0;else return -1;
936 } // Normalize val
937
938
939 if (typeof val === 'string') {
940 val = Buffer.from(val, encoding);
941 } // Finally, search either indexOf (if dir is true) or lastIndexOf
942
943
944 if (internalIsBuffer(val)) {
945 // Special case: looking for empty string/buffer always fails
946 if (val.length === 0) {
947 return -1;
948 }
949
950 return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
951 } else if (typeof val === 'number') {
952 val = val & 0xFF; // Search for a byte value [0-255]
953
954 if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') {
955 if (dir) {
956 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
957 } else {
958 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
959 }
960 }
961
962 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
963 }
964
965 throw new TypeError('val must be string, number or Buffer');
966 }
967
968 function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
969 var indexSize = 1;
970 var arrLength = arr.length;
971 var valLength = val.length;
972
973 if (encoding !== undefined) {
974 encoding = String(encoding).toLowerCase();
975
976 if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
977 if (arr.length < 2 || val.length < 2) {
978 return -1;
979 }
980
981 indexSize = 2;
982 arrLength /= 2;
983 valLength /= 2;
984 byteOffset /= 2;
985 }
986 }
987
988 function read(buf, i) {
989 if (indexSize === 1) {
990 return buf[i];
991 } else {
992 return buf.readUInt16BE(i * indexSize);
993 }
994 }
995
996 var i;
997
998 if (dir) {
999 var foundIndex = -1;
1000
1001 for (i = byteOffset; i < arrLength; i++) {
1002 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1003 if (foundIndex === -1) foundIndex = i;
1004 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
1005 } else {
1006 if (foundIndex !== -1) i -= i - foundIndex;
1007 foundIndex = -1;
1008 }
1009 }
1010 } else {
1011 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
1012
1013 for (i = byteOffset; i >= 0; i--) {
1014 var found = true;
1015
1016 for (var j = 0; j < valLength; j++) {
1017 if (read(arr, i + j) !== read(val, j)) {
1018 found = false;
1019 break;
1020 }
1021 }
1022
1023 if (found) return i;
1024 }
1025 }
1026
1027 return -1;
1028 }
1029
1030 Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
1031 return this.indexOf(val, byteOffset, encoding) !== -1;
1032 };
1033
1034 Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
1035 return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
1036 };
1037
1038 Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
1039 return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
1040 };
1041
1042 function hexWrite(buf, string, offset, length) {
1043 offset = Number(offset) || 0;
1044 var remaining = buf.length - offset;
1045
1046 if (!length) {
1047 length = remaining;
1048 } else {
1049 length = Number(length);
1050
1051 if (length > remaining) {
1052 length = remaining;
1053 }
1054 } // must be an even number of digits
1055
1056
1057 var strLen = string.length;
1058 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string');
1059
1060 if (length > strLen / 2) {
1061 length = strLen / 2;
1062 }
1063
1064 for (var i = 0; i < length; ++i) {
1065 var parsed = parseInt(string.substr(i * 2, 2), 16);
1066 if (isNaN(parsed)) return i;
1067 buf[offset + i] = parsed;
1068 }
1069
1070 return i;
1071 }
1072
1073 function utf8Write(buf, string, offset, length) {
1074 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
1075 }
1076
1077 function asciiWrite(buf, string, offset, length) {
1078 return blitBuffer(asciiToBytes(string), buf, offset, length);
1079 }
1080
1081 function latin1Write(buf, string, offset, length) {
1082 return asciiWrite(buf, string, offset, length);
1083 }
1084
1085 function base64Write(buf, string, offset, length) {
1086 return blitBuffer(base64ToBytes(string), buf, offset, length);
1087 }
1088
1089 function ucs2Write(buf, string, offset, length) {
1090 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
1091 }
1092
1093 Buffer.prototype.write = function write(string, offset, length, encoding) {
1094 // Buffer#write(string)
1095 if (offset === undefined) {
1096 encoding = 'utf8';
1097 length = this.length;
1098 offset = 0; // Buffer#write(string, encoding)
1099 } else if (length === undefined && typeof offset === 'string') {
1100 encoding = offset;
1101 length = this.length;
1102 offset = 0; // Buffer#write(string, offset[, length][, encoding])
1103 } else if (isFinite(offset)) {
1104 offset = offset | 0;
1105
1106 if (isFinite(length)) {
1107 length = length | 0;
1108 if (encoding === undefined) encoding = 'utf8';
1109 } else {
1110 encoding = length;
1111 length = undefined;
1112 } // legacy write(string, encoding, offset, length) - remove in v0.13
1113
1114 } else {
1115 throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
1116 }
1117
1118 var remaining = this.length - offset;
1119 if (length === undefined || length > remaining) length = remaining;
1120
1121 if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
1122 throw new RangeError('Attempt to write outside buffer bounds');
1123 }
1124
1125 if (!encoding) encoding = 'utf8';
1126 var loweredCase = false;
1127
1128 for (;;) {
1129 switch (encoding) {
1130 case 'hex':
1131 return hexWrite(this, string, offset, length);
1132
1133 case 'utf8':
1134 case 'utf-8':
1135 return utf8Write(this, string, offset, length);
1136
1137 case 'ascii':
1138 return asciiWrite(this, string, offset, length);
1139
1140 case 'latin1':
1141 case 'binary':
1142 return latin1Write(this, string, offset, length);
1143
1144 case 'base64':
1145 // Warning: maxLength not taken into account in base64Write
1146 return base64Write(this, string, offset, length);
1147
1148 case 'ucs2':
1149 case 'ucs-2':
1150 case 'utf16le':
1151 case 'utf-16le':
1152 return ucs2Write(this, string, offset, length);
1153
1154 default:
1155 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
1156 encoding = ('' + encoding).toLowerCase();
1157 loweredCase = true;
1158 }
1159 }
1160 };
1161
1162 Buffer.prototype.toJSON = function toJSON() {
1163 return {
1164 type: 'Buffer',
1165 data: Array.prototype.slice.call(this._arr || this, 0)
1166 };
1167 };
1168
1169 function base64Slice(buf, start, end) {
1170 if (start === 0 && end === buf.length) {
1171 return fromByteArray(buf);
1172 } else {
1173 return fromByteArray(buf.slice(start, end));
1174 }
1175 }
1176
1177 function utf8Slice(buf, start, end) {
1178 end = Math.min(buf.length, end);
1179 var res = [];
1180 var i = start;
1181
1182 while (i < end) {
1183 var firstByte = buf[i];
1184 var codePoint = null;
1185 var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
1186
1187 if (i + bytesPerSequence <= end) {
1188 var secondByte, thirdByte, fourthByte, tempCodePoint;
1189
1190 switch (bytesPerSequence) {
1191 case 1:
1192 if (firstByte < 0x80) {
1193 codePoint = firstByte;
1194 }
1195
1196 break;
1197
1198 case 2:
1199 secondByte = buf[i + 1];
1200
1201 if ((secondByte & 0xC0) === 0x80) {
1202 tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
1203
1204 if (tempCodePoint > 0x7F) {
1205 codePoint = tempCodePoint;
1206 }
1207 }
1208
1209 break;
1210
1211 case 3:
1212 secondByte = buf[i + 1];
1213 thirdByte = buf[i + 2];
1214
1215 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1216 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
1217
1218 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1219 codePoint = tempCodePoint;
1220 }
1221 }
1222
1223 break;
1224
1225 case 4:
1226 secondByte = buf[i + 1];
1227 thirdByte = buf[i + 2];
1228 fourthByte = buf[i + 3];
1229
1230 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1231 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
1232
1233 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1234 codePoint = tempCodePoint;
1235 }
1236 }
1237
1238 }
1239 }
1240
1241 if (codePoint === null) {
1242 // we did not generate a valid codePoint so insert a
1243 // replacement char (U+FFFD) and advance only 1 byte
1244 codePoint = 0xFFFD;
1245 bytesPerSequence = 1;
1246 } else if (codePoint > 0xFFFF) {
1247 // encode to utf16 (surrogate pair dance)
1248 codePoint -= 0x10000;
1249 res.push(codePoint >>> 10 & 0x3FF | 0xD800);
1250 codePoint = 0xDC00 | codePoint & 0x3FF;
1251 }
1252
1253 res.push(codePoint);
1254 i += bytesPerSequence;
1255 }
1256
1257 return decodeCodePointsArray(res);
1258 } // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1259 // the lowest limit is Chrome, with 0x10000 args.
1260 // We go 1 magnitude less, for safety
1261
1262
1263 var MAX_ARGUMENTS_LENGTH = 0x1000;
1264
1265 function decodeCodePointsArray(codePoints) {
1266 var len = codePoints.length;
1267
1268 if (len <= MAX_ARGUMENTS_LENGTH) {
1269 return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
1270 } // Decode in chunks to avoid "call stack size exceeded".
1271
1272
1273 var res = '';
1274 var i = 0;
1275
1276 while (i < len) {
1277 res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
1278 }
1279
1280 return res;
1281 }
1282
1283 function asciiSlice(buf, start, end) {
1284 var ret = '';
1285 end = Math.min(buf.length, end);
1286
1287 for (var i = start; i < end; ++i) {
1288 ret += String.fromCharCode(buf[i] & 0x7F);
1289 }
1290
1291 return ret;
1292 }
1293
1294 function latin1Slice(buf, start, end) {
1295 var ret = '';
1296 end = Math.min(buf.length, end);
1297
1298 for (var i = start; i < end; ++i) {
1299 ret += String.fromCharCode(buf[i]);
1300 }
1301
1302 return ret;
1303 }
1304
1305 function hexSlice(buf, start, end) {
1306 var len = buf.length;
1307 if (!start || start < 0) start = 0;
1308 if (!end || end < 0 || end > len) end = len;
1309 var out = '';
1310
1311 for (var i = start; i < end; ++i) {
1312 out += toHex(buf[i]);
1313 }
1314
1315 return out;
1316 }
1317
1318 function utf16leSlice(buf, start, end) {
1319 var bytes = buf.slice(start, end);
1320 var res = '';
1321
1322 for (var i = 0; i < bytes.length; i += 2) {
1323 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1324 }
1325
1326 return res;
1327 }
1328
1329 Buffer.prototype.slice = function slice(start, end) {
1330 var len = this.length;
1331 start = ~~start;
1332 end = end === undefined ? len : ~~end;
1333
1334 if (start < 0) {
1335 start += len;
1336 if (start < 0) start = 0;
1337 } else if (start > len) {
1338 start = len;
1339 }
1340
1341 if (end < 0) {
1342 end += len;
1343 if (end < 0) end = 0;
1344 } else if (end > len) {
1345 end = len;
1346 }
1347
1348 if (end < start) end = start;
1349 var newBuf;
1350
1351 if (Buffer.TYPED_ARRAY_SUPPORT) {
1352 newBuf = this.subarray(start, end);
1353 newBuf.__proto__ = Buffer.prototype;
1354 } else {
1355 var sliceLen = end - start;
1356 newBuf = new Buffer(sliceLen, undefined);
1357
1358 for (var i = 0; i < sliceLen; ++i) {
1359 newBuf[i] = this[i + start];
1360 }
1361 }
1362
1363 return newBuf;
1364 };
1365 /*
1366 * Need to make sure that buffer isn't trying to write out of bounds.
1367 */
1368
1369
1370 function checkOffset(offset, ext, length) {
1371 if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
1372 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
1373 }
1374
1375 Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
1376 offset = offset | 0;
1377 byteLength = byteLength | 0;
1378 if (!noAssert) checkOffset(offset, byteLength, this.length);
1379 var val = this[offset];
1380 var mul = 1;
1381 var i = 0;
1382
1383 while (++i < byteLength && (mul *= 0x100)) {
1384 val += this[offset + i] * mul;
1385 }
1386
1387 return val;
1388 };
1389
1390 Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
1391 offset = offset | 0;
1392 byteLength = byteLength | 0;
1393
1394 if (!noAssert) {
1395 checkOffset(offset, byteLength, this.length);
1396 }
1397
1398 var val = this[offset + --byteLength];
1399 var mul = 1;
1400
1401 while (byteLength > 0 && (mul *= 0x100)) {
1402 val += this[offset + --byteLength] * mul;
1403 }
1404
1405 return val;
1406 };
1407
1408 Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
1409 if (!noAssert) checkOffset(offset, 1, this.length);
1410 return this[offset];
1411 };
1412
1413 Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
1414 if (!noAssert) checkOffset(offset, 2, this.length);
1415 return this[offset] | this[offset + 1] << 8;
1416 };
1417
1418 Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
1419 if (!noAssert) checkOffset(offset, 2, this.length);
1420 return this[offset] << 8 | this[offset + 1];
1421 };
1422
1423 Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
1424 if (!noAssert) checkOffset(offset, 4, this.length);
1425 return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
1426 };
1427
1428 Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
1429 if (!noAssert) checkOffset(offset, 4, this.length);
1430 return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
1431 };
1432
1433 Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
1434 offset = offset | 0;
1435 byteLength = byteLength | 0;
1436 if (!noAssert) checkOffset(offset, byteLength, this.length);
1437 var val = this[offset];
1438 var mul = 1;
1439 var i = 0;
1440
1441 while (++i < byteLength && (mul *= 0x100)) {
1442 val += this[offset + i] * mul;
1443 }
1444
1445 mul *= 0x80;
1446 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1447 return val;
1448 };
1449
1450 Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
1451 offset = offset | 0;
1452 byteLength = byteLength | 0;
1453 if (!noAssert) checkOffset(offset, byteLength, this.length);
1454 var i = byteLength;
1455 var mul = 1;
1456 var val = this[offset + --i];
1457
1458 while (i > 0 && (mul *= 0x100)) {
1459 val += this[offset + --i] * mul;
1460 }
1461
1462 mul *= 0x80;
1463 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1464 return val;
1465 };
1466
1467 Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
1468 if (!noAssert) checkOffset(offset, 1, this.length);
1469 if (!(this[offset] & 0x80)) return this[offset];
1470 return (0xff - this[offset] + 1) * -1;
1471 };
1472
1473 Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
1474 if (!noAssert) checkOffset(offset, 2, this.length);
1475 var val = this[offset] | this[offset + 1] << 8;
1476 return val & 0x8000 ? val | 0xFFFF0000 : val;
1477 };
1478
1479 Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
1480 if (!noAssert) checkOffset(offset, 2, this.length);
1481 var val = this[offset + 1] | this[offset] << 8;
1482 return val & 0x8000 ? val | 0xFFFF0000 : val;
1483 };
1484
1485 Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
1486 if (!noAssert) checkOffset(offset, 4, this.length);
1487 return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
1488 };
1489
1490 Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
1491 if (!noAssert) checkOffset(offset, 4, this.length);
1492 return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
1493 };
1494
1495 Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
1496 if (!noAssert) checkOffset(offset, 4, this.length);
1497 return read(this, offset, true, 23, 4);
1498 };
1499
1500 Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
1501 if (!noAssert) checkOffset(offset, 4, this.length);
1502 return read(this, offset, false, 23, 4);
1503 };
1504
1505 Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
1506 if (!noAssert) checkOffset(offset, 8, this.length);
1507 return read(this, offset, true, 52, 8);
1508 };
1509
1510 Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
1511 if (!noAssert) checkOffset(offset, 8, this.length);
1512 return read(this, offset, false, 52, 8);
1513 };
1514
1515 function checkInt(buf, value, offset, ext, max, min) {
1516 if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
1517 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
1518 if (offset + ext > buf.length) throw new RangeError('Index out of range');
1519 }
1520
1521 Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
1522 value = +value;
1523 offset = offset | 0;
1524 byteLength = byteLength | 0;
1525
1526 if (!noAssert) {
1527 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1528 checkInt(this, value, offset, byteLength, maxBytes, 0);
1529 }
1530
1531 var mul = 1;
1532 var i = 0;
1533 this[offset] = value & 0xFF;
1534
1535 while (++i < byteLength && (mul *= 0x100)) {
1536 this[offset + i] = value / mul & 0xFF;
1537 }
1538
1539 return offset + byteLength;
1540 };
1541
1542 Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
1543 value = +value;
1544 offset = offset | 0;
1545 byteLength = byteLength | 0;
1546
1547 if (!noAssert) {
1548 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1549 checkInt(this, value, offset, byteLength, maxBytes, 0);
1550 }
1551
1552 var i = byteLength - 1;
1553 var mul = 1;
1554 this[offset + i] = value & 0xFF;
1555
1556 while (--i >= 0 && (mul *= 0x100)) {
1557 this[offset + i] = value / mul & 0xFF;
1558 }
1559
1560 return offset + byteLength;
1561 };
1562
1563 Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
1564 value = +value;
1565 offset = offset | 0;
1566 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
1567 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1568 this[offset] = value & 0xff;
1569 return offset + 1;
1570 };
1571
1572 function objectWriteUInt16(buf, value, offset, littleEndian) {
1573 if (value < 0) value = 0xffff + value + 1;
1574
1575 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
1576 buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
1577 }
1578 }
1579
1580 Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
1581 value = +value;
1582 offset = offset | 0;
1583 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1584
1585 if (Buffer.TYPED_ARRAY_SUPPORT) {
1586 this[offset] = value & 0xff;
1587 this[offset + 1] = value >>> 8;
1588 } else {
1589 objectWriteUInt16(this, value, offset, true);
1590 }
1591
1592 return offset + 2;
1593 };
1594
1595 Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
1596 value = +value;
1597 offset = offset | 0;
1598 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1599
1600 if (Buffer.TYPED_ARRAY_SUPPORT) {
1601 this[offset] = value >>> 8;
1602 this[offset + 1] = value & 0xff;
1603 } else {
1604 objectWriteUInt16(this, value, offset, false);
1605 }
1606
1607 return offset + 2;
1608 };
1609
1610 function objectWriteUInt32(buf, value, offset, littleEndian) {
1611 if (value < 0) value = 0xffffffff + value + 1;
1612
1613 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
1614 buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff;
1615 }
1616 }
1617
1618 Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
1619 value = +value;
1620 offset = offset | 0;
1621 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1622
1623 if (Buffer.TYPED_ARRAY_SUPPORT) {
1624 this[offset + 3] = value >>> 24;
1625 this[offset + 2] = value >>> 16;
1626 this[offset + 1] = value >>> 8;
1627 this[offset] = value & 0xff;
1628 } else {
1629 objectWriteUInt32(this, value, offset, true);
1630 }
1631
1632 return offset + 4;
1633 };
1634
1635 Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
1636 value = +value;
1637 offset = offset | 0;
1638 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1639
1640 if (Buffer.TYPED_ARRAY_SUPPORT) {
1641 this[offset] = value >>> 24;
1642 this[offset + 1] = value >>> 16;
1643 this[offset + 2] = value >>> 8;
1644 this[offset + 3] = value & 0xff;
1645 } else {
1646 objectWriteUInt32(this, value, offset, false);
1647 }
1648
1649 return offset + 4;
1650 };
1651
1652 Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
1653 value = +value;
1654 offset = offset | 0;
1655
1656 if (!noAssert) {
1657 var limit = Math.pow(2, 8 * byteLength - 1);
1658 checkInt(this, value, offset, byteLength, limit - 1, -limit);
1659 }
1660
1661 var i = 0;
1662 var mul = 1;
1663 var sub = 0;
1664 this[offset] = value & 0xFF;
1665
1666 while (++i < byteLength && (mul *= 0x100)) {
1667 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1668 sub = 1;
1669 }
1670
1671 this[offset + i] = (value / mul >> 0) - sub & 0xFF;
1672 }
1673
1674 return offset + byteLength;
1675 };
1676
1677 Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
1678 value = +value;
1679 offset = offset | 0;
1680
1681 if (!noAssert) {
1682 var limit = Math.pow(2, 8 * byteLength - 1);
1683 checkInt(this, value, offset, byteLength, limit - 1, -limit);
1684 }
1685
1686 var i = byteLength - 1;
1687 var mul = 1;
1688 var sub = 0;
1689 this[offset + i] = value & 0xFF;
1690
1691 while (--i >= 0 && (mul *= 0x100)) {
1692 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1693 sub = 1;
1694 }
1695
1696 this[offset + i] = (value / mul >> 0) - sub & 0xFF;
1697 }
1698
1699 return offset + byteLength;
1700 };
1701
1702 Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
1703 value = +value;
1704 offset = offset | 0;
1705 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
1706 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1707 if (value < 0) value = 0xff + value + 1;
1708 this[offset] = value & 0xff;
1709 return offset + 1;
1710 };
1711
1712 Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
1713 value = +value;
1714 offset = offset | 0;
1715 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1716
1717 if (Buffer.TYPED_ARRAY_SUPPORT) {
1718 this[offset] = value & 0xff;
1719 this[offset + 1] = value >>> 8;
1720 } else {
1721 objectWriteUInt16(this, value, offset, true);
1722 }
1723
1724 return offset + 2;
1725 };
1726
1727 Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
1728 value = +value;
1729 offset = offset | 0;
1730 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1731
1732 if (Buffer.TYPED_ARRAY_SUPPORT) {
1733 this[offset] = value >>> 8;
1734 this[offset + 1] = value & 0xff;
1735 } else {
1736 objectWriteUInt16(this, value, offset, false);
1737 }
1738
1739 return offset + 2;
1740 };
1741
1742 Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
1743 value = +value;
1744 offset = offset | 0;
1745 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1746
1747 if (Buffer.TYPED_ARRAY_SUPPORT) {
1748 this[offset] = value & 0xff;
1749 this[offset + 1] = value >>> 8;
1750 this[offset + 2] = value >>> 16;
1751 this[offset + 3] = value >>> 24;
1752 } else {
1753 objectWriteUInt32(this, value, offset, true);
1754 }
1755
1756 return offset + 4;
1757 };
1758
1759 Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
1760 value = +value;
1761 offset = offset | 0;
1762 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1763 if (value < 0) value = 0xffffffff + value + 1;
1764
1765 if (Buffer.TYPED_ARRAY_SUPPORT) {
1766 this[offset] = value >>> 24;
1767 this[offset + 1] = value >>> 16;
1768 this[offset + 2] = value >>> 8;
1769 this[offset + 3] = value & 0xff;
1770 } else {
1771 objectWriteUInt32(this, value, offset, false);
1772 }
1773
1774 return offset + 4;
1775 };
1776
1777 function checkIEEE754(buf, value, offset, ext, max, min) {
1778 if (offset + ext > buf.length) throw new RangeError('Index out of range');
1779 if (offset < 0) throw new RangeError('Index out of range');
1780 }
1781
1782 function writeFloat(buf, value, offset, littleEndian, noAssert) {
1783 if (!noAssert) {
1784 checkIEEE754(buf, value, offset, 4);
1785 }
1786
1787 write(buf, value, offset, littleEndian, 23, 4);
1788 return offset + 4;
1789 }
1790
1791 Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
1792 return writeFloat(this, value, offset, true, noAssert);
1793 };
1794
1795 Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
1796 return writeFloat(this, value, offset, false, noAssert);
1797 };
1798
1799 function writeDouble(buf, value, offset, littleEndian, noAssert) {
1800 if (!noAssert) {
1801 checkIEEE754(buf, value, offset, 8);
1802 }
1803
1804 write(buf, value, offset, littleEndian, 52, 8);
1805 return offset + 8;
1806 }
1807
1808 Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
1809 return writeDouble(this, value, offset, true, noAssert);
1810 };
1811
1812 Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
1813 return writeDouble(this, value, offset, false, noAssert);
1814 }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1815
1816
1817 Buffer.prototype.copy = function copy(target, targetStart, start, end) {
1818 if (!start) start = 0;
1819 if (!end && end !== 0) end = this.length;
1820 if (targetStart >= target.length) targetStart = target.length;
1821 if (!targetStart) targetStart = 0;
1822 if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done
1823
1824 if (end === start) return 0;
1825 if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions
1826
1827 if (targetStart < 0) {
1828 throw new RangeError('targetStart out of bounds');
1829 }
1830
1831 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds');
1832 if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob?
1833
1834 if (end > this.length) end = this.length;
1835
1836 if (target.length - targetStart < end - start) {
1837 end = target.length - targetStart + start;
1838 }
1839
1840 var len = end - start;
1841 var i;
1842
1843 if (this === target && start < targetStart && targetStart < end) {
1844 // descending copy from end
1845 for (i = len - 1; i >= 0; --i) {
1846 target[i + targetStart] = this[i + start];
1847 }
1848 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1849 // ascending copy from start
1850 for (i = 0; i < len; ++i) {
1851 target[i + targetStart] = this[i + start];
1852 }
1853 } else {
1854 Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
1855 }
1856
1857 return len;
1858 }; // Usage:
1859 // buffer.fill(number[, offset[, end]])
1860 // buffer.fill(buffer[, offset[, end]])
1861 // buffer.fill(string[, offset[, end]][, encoding])
1862
1863
1864 Buffer.prototype.fill = function fill(val, start, end, encoding) {
1865 // Handle string cases:
1866 if (typeof val === 'string') {
1867 if (typeof start === 'string') {
1868 encoding = start;
1869 start = 0;
1870 end = this.length;
1871 } else if (typeof end === 'string') {
1872 encoding = end;
1873 end = this.length;
1874 }
1875
1876 if (val.length === 1) {
1877 var code = val.charCodeAt(0);
1878
1879 if (code < 256) {
1880 val = code;
1881 }
1882 }
1883
1884 if (encoding !== undefined && typeof encoding !== 'string') {
1885 throw new TypeError('encoding must be a string');
1886 }
1887
1888 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1889 throw new TypeError('Unknown encoding: ' + encoding);
1890 }
1891 } else if (typeof val === 'number') {
1892 val = val & 255;
1893 } // Invalid ranges are not set to a default, so can range check early.
1894
1895
1896 if (start < 0 || this.length < start || this.length < end) {
1897 throw new RangeError('Out of range index');
1898 }
1899
1900 if (end <= start) {
1901 return this;
1902 }
1903
1904 start = start >>> 0;
1905 end = end === undefined ? this.length : end >>> 0;
1906 if (!val) val = 0;
1907 var i;
1908
1909 if (typeof val === 'number') {
1910 for (i = start; i < end; ++i) {
1911 this[i] = val;
1912 }
1913 } else {
1914 var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString());
1915 var len = bytes.length;
1916
1917 for (i = 0; i < end - start; ++i) {
1918 this[i + start] = bytes[i % len];
1919 }
1920 }
1921
1922 return this;
1923 }; // HELPER FUNCTIONS
1924 // ================
1925
1926
1927 var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
1928
1929 function base64clean(str) {
1930 // Node strips out invalid characters like \n and \t from the string, base64-js does not
1931 str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to ''
1932
1933 if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1934
1935 while (str.length % 4 !== 0) {
1936 str = str + '=';
1937 }
1938
1939 return str;
1940 }
1941
1942 function stringtrim(str) {
1943 if (str.trim) return str.trim();
1944 return str.replace(/^\s+|\s+$/g, '');
1945 }
1946
1947 function toHex(n) {
1948 if (n < 16) return '0' + n.toString(16);
1949 return n.toString(16);
1950 }
1951
1952 function utf8ToBytes(string, units) {
1953 units = units || Infinity;
1954 var codePoint;
1955 var length = string.length;
1956 var leadSurrogate = null;
1957 var bytes = [];
1958
1959 for (var i = 0; i < length; ++i) {
1960 codePoint = string.charCodeAt(i); // is surrogate component
1961
1962 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1963 // last char was a lead
1964 if (!leadSurrogate) {
1965 // no lead yet
1966 if (codePoint > 0xDBFF) {
1967 // unexpected trail
1968 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1969 continue;
1970 } else if (i + 1 === length) {
1971 // unpaired lead
1972 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1973 continue;
1974 } // valid lead
1975
1976
1977 leadSurrogate = codePoint;
1978 continue;
1979 } // 2 leads in a row
1980
1981
1982 if (codePoint < 0xDC00) {
1983 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1984 leadSurrogate = codePoint;
1985 continue;
1986 } // valid surrogate pair
1987
1988
1989 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
1990 } else if (leadSurrogate) {
1991 // valid bmp char, but last char was a lead
1992 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1993 }
1994
1995 leadSurrogate = null; // encode utf8
1996
1997 if (codePoint < 0x80) {
1998 if ((units -= 1) < 0) break;
1999 bytes.push(codePoint);
2000 } else if (codePoint < 0x800) {
2001 if ((units -= 2) < 0) break;
2002 bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
2003 } else if (codePoint < 0x10000) {
2004 if ((units -= 3) < 0) break;
2005 bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
2006 } else if (codePoint < 0x110000) {
2007 if ((units -= 4) < 0) break;
2008 bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
2009 } else {
2010 throw new Error('Invalid code point');
2011 }
2012 }
2013
2014 return bytes;
2015 }
2016
2017 function asciiToBytes(str) {
2018 var byteArray = [];
2019
2020 for (var i = 0; i < str.length; ++i) {
2021 // Node's code seems to be doing this and not & 0x7F..
2022 byteArray.push(str.charCodeAt(i) & 0xFF);
2023 }
2024
2025 return byteArray;
2026 }
2027
2028 function utf16leToBytes(str, units) {
2029 var c, hi, lo;
2030 var byteArray = [];
2031
2032 for (var i = 0; i < str.length; ++i) {
2033 if ((units -= 2) < 0) break;
2034 c = str.charCodeAt(i);
2035 hi = c >> 8;
2036 lo = c % 256;
2037 byteArray.push(lo);
2038 byteArray.push(hi);
2039 }
2040
2041 return byteArray;
2042 }
2043
2044 function base64ToBytes(str) {
2045 return toByteArray(base64clean(str));
2046 }
2047
2048 function blitBuffer(src, dst, offset, length) {
2049 for (var i = 0; i < length; ++i) {
2050 if (i + offset >= dst.length || i >= src.length) break;
2051 dst[i + offset] = src[i];
2052 }
2053
2054 return i;
2055 }
2056
2057 function isnan(val) {
2058 return val !== val; // eslint-disable-line no-self-compare
2059 } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
2060 // The _isBuffer check is for Safari 5-7 support, because it's missing
2061 // Object.prototype.constructor. Remove this eventually
2062
2063
2064 function isBuffer(obj) {
2065 return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj));
2066 }
2067
2068 function isFastBuffer(obj) {
2069 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
2070 } // For Node v0.10 support. Remove this eventually.
2071
2072
2073 function isSlowBuffer(obj) {
2074 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0));
2075 }
2076
2077 // POST https://{host}/oauth/token?grant_type=client_credentials&scope={scope}
2078 // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
2079 function buildRequestForClientCredentialsFlow(options) {
2080 if (!options) throw new Error('Missing required options');
2081 if (!options.host) throw new Error('Missing required option (host)');
2082 if (!options.projectKey) throw new Error('Missing required option (projectKey)');
2083 if (!options.credentials) throw new Error('Missing required option (credentials)');
2084 var _options$credentials = options.credentials,
2085 clientId = _options$credentials.clientId,
2086 clientSecret = _options$credentials.clientSecret;
2087 if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
2088 var scope = options.scopes ? options.scopes.join(' ') : undefined;
2089 var basicAuth = Buffer.from("".concat(clientId, ":").concat(clientSecret)).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
2090 // other oauth endpoints.
2091
2092 var oauthUri = options.oauthUri || '/oauth/token';
2093 var url = options.host.replace(/\/$/, '') + oauthUri;
2094 var body = "grant_type=client_credentials".concat(scope ? "&scope=".concat(scope) : '');
2095 return {
2096 basicAuth: basicAuth,
2097 url: url,
2098 body: body
2099 };
2100 }
2101 function buildRequestForPasswordFlow(options) {
2102 if (!options) throw new Error('Missing required options');
2103 if (!options.host) throw new Error('Missing required option (host)');
2104 if (!options.projectKey) throw new Error('Missing required option (projectKey)');
2105 if (!options.credentials) throw new Error('Missing required option (credentials)');
2106 var _options$credentials2 = options.credentials,
2107 clientId = _options$credentials2.clientId,
2108 clientSecret = _options$credentials2.clientSecret,
2109 user = _options$credentials2.user;
2110 var pKey = options.projectKey;
2111 if (!(clientId && clientSecret && user)) throw new Error('Missing required credentials (clientId, clientSecret, user)');
2112 var username = user.username,
2113 password = user.password;
2114 if (!(username && password)) throw new Error('Missing required user credentials (username, password)');
2115 var scope = (options.scopes || []).join(' ');
2116 var scopeStr = scope ? "&scope=".concat(scope) : '';
2117 var basicAuth = Buffer.from("".concat(clientId, ":").concat(clientSecret)).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
2118 // other oauth endpoints.
2119
2120 var oauthUri = options.oauthUri || "/oauth/".concat(pKey, "/customers/token");
2121 var url = options.host.replace(/\/$/, '') + oauthUri; // eslint-disable-next-line max-len
2122 // encode username and password as requested by platform
2123
2124 var body = "grant_type=password&username=".concat(encodeURIComponent(username), "&password=").concat(encodeURIComponent(password)).concat(scopeStr);
2125 return {
2126 basicAuth: basicAuth,
2127 url: url,
2128 body: body
2129 };
2130 }
2131 function buildRequestForRefreshTokenFlow(options) {
2132 if (!options) throw new Error('Missing required options');
2133 if (!options.host) throw new Error('Missing required option (host)');
2134 if (!options.projectKey) throw new Error('Missing required option (projectKey)');
2135 if (!options.credentials) throw new Error('Missing required option (credentials)');
2136 if (!options.refreshToken) throw new Error('Missing required option (refreshToken)');
2137 var _options$credentials3 = options.credentials,
2138 clientId = _options$credentials3.clientId,
2139 clientSecret = _options$credentials3.clientSecret;
2140 if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
2141 var basicAuth = Buffer.from("".concat(clientId, ":").concat(clientSecret)).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
2142 // other oauth endpoints.
2143
2144 var oauthUri = options.oauthUri || '/oauth/token';
2145 var url = options.host.replace(/\/$/, '') + oauthUri;
2146 var body = "grant_type=refresh_token&refresh_token=".concat(encodeURIComponent(options.refreshToken));
2147 return {
2148 basicAuth: basicAuth,
2149 url: url,
2150 body: body
2151 };
2152 }
2153 function buildRequestForAnonymousSessionFlow(options) {
2154 if (!options) throw new Error('Missing required options');
2155 if (!options.projectKey) throw new Error('Missing required option (projectKey)');
2156 var pKey = options.projectKey; // eslint-disable-next-line no-param-reassign
2157
2158 options.oauthUri = options.oauthUri || "/oauth/".concat(pKey, "/anonymous/token");
2159 var result = buildRequestForClientCredentialsFlow(options);
2160 if (options.credentials.anonymousId) result.body += "&anonymous_id=".concat(options.credentials.anonymousId);
2161 return _objectSpread2({}, result);
2162 }
2163
2164 function buildTokenCacheKey(options) {
2165 return {
2166 clientId: options.credentials.clientId,
2167 host: options.host,
2168 projectKey: options.projectKey
2169 };
2170 }
2171
2172 function mergeAuthHeader(token, req) {
2173 return _objectSpread2({}, req, {
2174 headers: _objectSpread2({}, req.headers, {
2175 Authorization: "Bearer ".concat(token)
2176 })
2177 });
2178 }
2179
2180 function calculateExpirationTime(expiresIn) {
2181 return Date.now() + expiresIn * 1000 - // Add a gap of 2 hours before expiration time.
2182 2 * 60 * 60 * 1000;
2183 }
2184
2185 function executeRequest(_ref) {
2186 var fetcher = _ref.fetcher,
2187 url = _ref.url,
2188 basicAuth = _ref.basicAuth,
2189 body = _ref.body,
2190 tokenCache = _ref.tokenCache,
2191 requestState = _ref.requestState,
2192 pendingTasks = _ref.pendingTasks,
2193 response = _ref.response,
2194 tokenCacheKey = _ref.tokenCacheKey;
2195 fetcher(url, {
2196 method: 'POST',
2197 headers: {
2198 Authorization: "Basic ".concat(basicAuth),
2199 'Content-Length': Buffer.byteLength(body).toString(),
2200 'Content-Type': 'application/x-www-form-urlencoded'
2201 },
2202 body: body
2203 }).then(function (res) {
2204 if (res.ok) return res.json().then(function (_ref2) {
2205 var token = _ref2.access_token,
2206 expiresIn = _ref2.expires_in,
2207 refreshToken = _ref2.refresh_token;
2208 var expirationTime = calculateExpirationTime(expiresIn); // Cache new token
2209
2210 tokenCache.set({
2211 token: token,
2212 expirationTime: expirationTime,
2213 refreshToken: refreshToken
2214 }, tokenCacheKey); // Dispatch all pending requests
2215
2216 requestState.set(false); // Freeze and copy pending queue, reset original one for accepting
2217 // new pending tasks
2218
2219 var executionQueue = pendingTasks.slice(); // eslint-disable-next-line no-param-reassign
2220
2221 pendingTasks = [];
2222 executionQueue.forEach(function (task) {
2223 // Assign the new token in the request header
2224 var requestWithAuth = mergeAuthHeader(token, task.request); // console.log('test', cache, pendingTasks)
2225 // Continue by calling the task's own next function
2226
2227 task.next(requestWithAuth, task.response);
2228 });
2229 }); // Handle error response
2230
2231 return res.text().then(function (text) {
2232 var parsed;
2233
2234 try {
2235 parsed = JSON.parse(text);
2236 } catch (error) {
2237 /* noop */
2238 }
2239
2240 var error = new Error(parsed ? parsed.message : text);
2241 if (parsed) error.body = parsed;
2242 response.reject(error);
2243 });
2244 }).catch(function (error) {
2245 if (response && typeof response.reject === 'function') response.reject(error);
2246 });
2247 }
2248
2249 function authMiddlewareBase(_ref3, next, userOptions) {
2250 var request = _ref3.request,
2251 response = _ref3.response,
2252 url = _ref3.url,
2253 basicAuth = _ref3.basicAuth,
2254 body = _ref3.body,
2255 pendingTasks = _ref3.pendingTasks,
2256 requestState = _ref3.requestState,
2257 tokenCache = _ref3.tokenCache,
2258 tokenCacheKey = _ref3.tokenCacheKey,
2259 fetcher = _ref3.fetch;
2260 if (!fetcher && typeof fetch === 'undefined') throw new Error('`fetch` is not available. Please pass in `fetch` as an option or have it globally available.');
2261 if (!fetcher) // eslint-disable-next-line
2262 fetcher = fetch; // Check if there is already a `Authorization` header in the request.
2263 // If so, then go directly to the next middleware.
2264
2265 if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
2266 next(request, response);
2267 return;
2268 } // If there was a token in the tokenCache, and it's not expired, append
2269 // the token in the `Authorization` header.
2270
2271
2272 var tokenObj = tokenCache.get(tokenCacheKey);
2273
2274 if (tokenObj && tokenObj.token && Date.now() < tokenObj.expirationTime) {
2275 var requestWithAuth = mergeAuthHeader(tokenObj.token, request);
2276 next(requestWithAuth, response);
2277 return;
2278 } // Keep pending tasks until a token is fetched
2279 // Save next function as well, to call it once the token has been fetched, which prevents
2280 // unexpected behaviour in a context in which the next function uses global vars
2281 // or Promises to capture the token to hand it to other libraries, e.g. Apollo
2282
2283
2284 pendingTasks.push({
2285 request: request,
2286 response: response,
2287 next: next
2288 }); // If a token is currently being fetched, just wait ;)
2289
2290 if (requestState.get()) return; // Mark that a token is being fetched
2291
2292 requestState.set(true); // If there was a refreshToken in the tokenCache, and there was an expired
2293 // token or no token in the tokenCache, use the refreshToken flow
2294
2295 if (tokenObj && tokenObj.refreshToken && (!tokenObj.token || tokenObj.token && Date.now() > tokenObj.expirationTime)) {
2296 if (!userOptions) throw new Error('Missing required options') // eslint-disable-next-line
2297 ;
2298 executeRequest(_objectSpread2({
2299 fetcher: fetcher
2300 }, buildRequestForRefreshTokenFlow(_objectSpread2({}, userOptions, {
2301 refreshToken: tokenObj.refreshToken
2302 })), {
2303 tokenCacheKey: tokenCacheKey,
2304 tokenCache: tokenCache,
2305 requestState: requestState,
2306 pendingTasks: pendingTasks,
2307 response: response
2308 }));
2309 return;
2310 } // Token and refreshToken are not present or invalid. Request a new token...
2311
2312
2313 executeRequest({
2314 fetcher: fetcher,
2315 url: url,
2316 basicAuth: basicAuth,
2317 body: body,
2318 tokenCacheKey: tokenCacheKey,
2319 tokenCache: tokenCache,
2320 requestState: requestState,
2321 pendingTasks: pendingTasks,
2322 response: response
2323 });
2324 }
2325
2326 function store(initVal) {
2327 var value = initVal;
2328 return {
2329 get: function get() {
2330 return value;
2331 },
2332 set: function set(val) {
2333 value = val;
2334 return value;
2335 }
2336 };
2337 }
2338
2339 function createAuthMiddlewareForClientCredentialsFlow(options) {
2340 var tokenCache = options.tokenCache || store({
2341 token: '',
2342 expirationTime: -1
2343 });
2344 var requestState = store(false);
2345 var pendingTasks = [];
2346 return function (next) {
2347 return function (request, response) {
2348 // Check if there is already a `Authorization` header in the request.
2349 // If so, then go directly to the next middleware.
2350 if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
2351 next(request, response);
2352 return;
2353 }
2354
2355 var params = _objectSpread2({
2356 request: request,
2357 response: response
2358 }, buildRequestForClientCredentialsFlow(options), {
2359 pendingTasks: pendingTasks,
2360 requestState: requestState,
2361 tokenCache: tokenCache,
2362 tokenCacheKey: buildTokenCacheKey(options),
2363 fetch: options.fetch
2364 });
2365
2366 authMiddlewareBase(params, next);
2367 };
2368 };
2369 }
2370
2371 function createAuthMiddlewareForPasswordFlow(options) {
2372 var tokenCache = store({});
2373 var pendingTasks = [];
2374 var requestState = store(false);
2375 return function (next) {
2376 return function (request, response) {
2377 // Check if there is already a `Authorization` header in the request.
2378 // If so, then go directly to the next middleware.
2379 if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
2380 next(request, response);
2381 return;
2382 }
2383
2384 var params = _objectSpread2({
2385 request: request,
2386 response: response
2387 }, buildRequestForPasswordFlow(options), {
2388 pendingTasks: pendingTasks,
2389 requestState: requestState,
2390 tokenCache: tokenCache,
2391 fetch: options.fetch
2392 });
2393
2394 authMiddlewareBase(params, next, options);
2395 };
2396 };
2397 }
2398
2399 function createAuthMiddlewareForRefreshTokenFlow(options) {
2400 var tokenCache = store({});
2401 var pendingTasks = [];
2402 var requestState = store(false);
2403 return function (next) {
2404 return function (request, response) {
2405 // Check if there is already a `Authorization` header in the request.
2406 // If so, then go directly to the next middleware.
2407 if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
2408 next(request, response);
2409 return;
2410 }
2411
2412 var params = _objectSpread2({
2413 request: request,
2414 response: response
2415 }, buildRequestForRefreshTokenFlow(options), {
2416 pendingTasks: pendingTasks,
2417 requestState: requestState,
2418 tokenCache: tokenCache,
2419 fetch: options.fetch
2420 });
2421
2422 authMiddlewareBase(params, next);
2423 };
2424 };
2425 }
2426
2427 function createAuthMiddlewareForAnonymousSessionFlow(options) {
2428 var tokenCache = store({});
2429 var pendingTasks = [];
2430 var requestState = store(false);
2431 return function (next) {
2432 return function (request, response) {
2433 // Check if there is already a `Authorization` header in the request.
2434 // If so, then go directly to the next middleware.
2435 if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
2436 next(request, response);
2437 return;
2438 }
2439
2440 var params = _objectSpread2({
2441 request: request,
2442 response: response
2443 }, buildRequestForAnonymousSessionFlow(options), {
2444 pendingTasks: pendingTasks,
2445 requestState: requestState,
2446 tokenCache: tokenCache,
2447 fetch: options.fetch
2448 });
2449
2450 authMiddlewareBase(params, next, options);
2451 };
2452 };
2453 }
2454
2455 function createAuthMiddlewareWithExistingToken() {
2456 var authorization = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
2457 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2458 return function (next) {
2459 return function (request, response) {
2460 if (typeof authorization !== 'string') throw new Error('authorization must be a string');
2461 var force = options.force === undefined ? true : options.force;
2462 /** The request will not be modified if:
2463 * 1. no argument is passed
2464 * 2. force is false and authorization header exists
2465 */
2466
2467 if (!authorization || (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) && force === false) {
2468 return next(request, response);
2469 }
2470
2471 var requestWithAuth = _objectSpread2({}, request, {
2472 headers: _objectSpread2({}, request.headers, {
2473 Authorization: authorization
2474 })
2475 });
2476
2477 return next(requestWithAuth, response);
2478 };
2479 };
2480 }
2481
2482 var MANAGE_PROJECT = 'manage_project';
2483 var MANAGE_PRODUCTS = 'manage_products';
2484 var VIEW_PRODUCTS = 'view_products';
2485 var MANAGE_ORDERS = 'manage_orders';
2486 var VIEW_ORDERS = 'view_orders';
2487 var MANAGE_MY_ORDERS = 'manage_my_orders';
2488 var MANAGE_CUSTOMERS = 'manage_customers';
2489 var VIEW_CUSTOMERS = 'view_customers';
2490 var MANAGE_MY_PROFILE = 'manage_my_profile';
2491 var MANAGE_TYPES = 'manage_types';
2492 var VIEW_TYPES = 'view_types';
2493 var MANAGE_PAYMENTS = 'manage_payments';
2494 var VIEW_PAYMENTS = 'view_payments';
2495 var CREATE_ANONYMOUS_TOKEN = 'create_anonymous_token';
2496 var MANAGE_SUBSCRIPTIONS = 'manage_subscriptions';
2497
2498 var scopes = /*#__PURE__*/Object.freeze({
2499 __proto__: null,
2500 MANAGE_PROJECT: MANAGE_PROJECT,
2501 MANAGE_PRODUCTS: MANAGE_PRODUCTS,
2502 VIEW_PRODUCTS: VIEW_PRODUCTS,
2503 MANAGE_ORDERS: MANAGE_ORDERS,
2504 VIEW_ORDERS: VIEW_ORDERS,
2505 MANAGE_MY_ORDERS: MANAGE_MY_ORDERS,
2506 MANAGE_CUSTOMERS: MANAGE_CUSTOMERS,
2507 VIEW_CUSTOMERS: VIEW_CUSTOMERS,
2508 MANAGE_MY_PROFILE: MANAGE_MY_PROFILE,
2509 MANAGE_TYPES: MANAGE_TYPES,
2510 VIEW_TYPES: VIEW_TYPES,
2511 MANAGE_PAYMENTS: MANAGE_PAYMENTS,
2512 VIEW_PAYMENTS: VIEW_PAYMENTS,
2513 CREATE_ANONYMOUS_TOKEN: CREATE_ANONYMOUS_TOKEN,
2514 MANAGE_SUBSCRIPTIONS: MANAGE_SUBSCRIPTIONS
2515 });
2516
2517 exports.createAuthMiddlewareForAnonymousSessionFlow = createAuthMiddlewareForAnonymousSessionFlow;
2518 exports.createAuthMiddlewareForClientCredentialsFlow = createAuthMiddlewareForClientCredentialsFlow;
2519 exports.createAuthMiddlewareForPasswordFlow = createAuthMiddlewareForPasswordFlow;
2520 exports.createAuthMiddlewareForRefreshTokenFlow = createAuthMiddlewareForRefreshTokenFlow;
2521 exports.createAuthMiddlewareWithExistingToken = createAuthMiddlewareWithExistingToken;
2522 exports.scopes = scopes;
2523
2524 Object.defineProperty(exports, '__esModule', { value: true });
2525
2526})));