· 4 years ago · Jul 08, 2021, 09:18 PM
1(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2'use strict'
3
4exports.byteLength = byteLength
5exports.toByteArray = toByteArray
6exports.fromByteArray = fromByteArray
7
8var lookup = []
9var revLookup = []
10var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
11
12var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
13for (var i = 0, len = code.length; i < len; ++i) {
14 lookup[i] = code[i]
15 revLookup[code.charCodeAt(i)] = i
16}
17
18// Support decoding URL-safe base64 strings, as Node.js does.
19// See: https://en.wikipedia.org/wiki/Base64#URL_applications
20revLookup['-'.charCodeAt(0)] = 62
21revLookup['_'.charCodeAt(0)] = 63
22
23function getLens (b64) {
24 var len = b64.length
25
26 if (len % 4 > 0) {
27 throw new Error('Invalid string. Length must be a multiple of 4')
28 }
29
30 // Trim off extra bytes after placeholder bytes are found
31 // See: https://github.com/beatgammit/base64-js/issues/42
32 var validLen = b64.indexOf('=')
33 if (validLen === -1) validLen = len
34
35 var placeHoldersLen = validLen === len
36 ? 0
37 : 4 - (validLen % 4)
38
39 return [validLen, placeHoldersLen]
40}
41
42// base64 is 4/3 + up to two characters of the original data
43function byteLength (b64) {
44 var lens = getLens(b64)
45 var validLen = lens[0]
46 var placeHoldersLen = lens[1]
47 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
48}
49
50function _byteLength (b64, validLen, placeHoldersLen) {
51 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
52}
53
54function toByteArray (b64) {
55 var tmp
56 var lens = getLens(b64)
57 var validLen = lens[0]
58 var placeHoldersLen = lens[1]
59
60 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
61
62 var curByte = 0
63
64 // if there are placeholders, only get up to the last complete 4 chars
65 var len = placeHoldersLen > 0
66 ? validLen - 4
67 : validLen
68
69 var i
70 for (i = 0; i < len; i += 4) {
71 tmp =
72 (revLookup[b64.charCodeAt(i)] << 18) |
73 (revLookup[b64.charCodeAt(i + 1)] << 12) |
74 (revLookup[b64.charCodeAt(i + 2)] << 6) |
75 revLookup[b64.charCodeAt(i + 3)]
76 arr[curByte++] = (tmp >> 16) & 0xFF
77 arr[curByte++] = (tmp >> 8) & 0xFF
78 arr[curByte++] = tmp & 0xFF
79 }
80
81 if (placeHoldersLen === 2) {
82 tmp =
83 (revLookup[b64.charCodeAt(i)] << 2) |
84 (revLookup[b64.charCodeAt(i + 1)] >> 4)
85 arr[curByte++] = tmp & 0xFF
86 }
87
88 if (placeHoldersLen === 1) {
89 tmp =
90 (revLookup[b64.charCodeAt(i)] << 10) |
91 (revLookup[b64.charCodeAt(i + 1)] << 4) |
92 (revLookup[b64.charCodeAt(i + 2)] >> 2)
93 arr[curByte++] = (tmp >> 8) & 0xFF
94 arr[curByte++] = tmp & 0xFF
95 }
96
97 return arr
98}
99
100function tripletToBase64 (num) {
101 return lookup[num >> 18 & 0x3F] +
102 lookup[num >> 12 & 0x3F] +
103 lookup[num >> 6 & 0x3F] +
104 lookup[num & 0x3F]
105}
106
107function encodeChunk (uint8, start, end) {
108 var tmp
109 var output = []
110 for (var i = start; i < end; i += 3) {
111 tmp =
112 ((uint8[i] << 16) & 0xFF0000) +
113 ((uint8[i + 1] << 8) & 0xFF00) +
114 (uint8[i + 2] & 0xFF)
115 output.push(tripletToBase64(tmp))
116 }
117 return output.join('')
118}
119
120function fromByteArray (uint8) {
121 var tmp
122 var len = uint8.length
123 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
124 var parts = []
125 var maxChunkLength = 16383 // must be multiple of 3
126
127 // go through the array every three bytes, we'll deal with trailing stuff later
128 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
129 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
130 }
131
132 // pad the end with zeros, but make sure to not forget the extra bytes
133 if (extraBytes === 1) {
134 tmp = uint8[len - 1]
135 parts.push(
136 lookup[tmp >> 2] +
137 lookup[(tmp << 4) & 0x3F] +
138 '=='
139 )
140 } else if (extraBytes === 2) {
141 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
142 parts.push(
143 lookup[tmp >> 10] +
144 lookup[(tmp >> 4) & 0x3F] +
145 lookup[(tmp << 2) & 0x3F] +
146 '='
147 )
148 }
149
150 return parts.join('')
151}
152
153},{}],2:[function(require,module,exports){
154
155},{}],3:[function(require,module,exports){
156(function (Buffer){(function (){
157/*!
158 * The buffer module from node.js, for the browser.
159 *
160 * @author Feross Aboukhadijeh <https://feross.org>
161 * @license MIT
162 */
163/* eslint-disable no-proto */
164
165'use strict'
166
167var base64 = require('base64-js')
168var ieee754 = require('ieee754')
169
170exports.Buffer = Buffer
171exports.SlowBuffer = SlowBuffer
172exports.INSPECT_MAX_BYTES = 50
173
174var K_MAX_LENGTH = 0x7fffffff
175exports.kMaxLength = K_MAX_LENGTH
176
177/**
178 * If `Buffer.TYPED_ARRAY_SUPPORT`:
179 * === true Use Uint8Array implementation (fastest)
180 * === false Print warning and recommend using `buffer` v4.x which has an Object
181 * implementation (most compatible, even IE6)
182 *
183 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
184 * Opera 11.6+, iOS 4.2+.
185 *
186 * We report that the browser does not support typed arrays if the are not subclassable
187 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
188 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
189 * for __proto__ and has a buggy typed array implementation.
190 */
191Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
192
193if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
194 typeof console.error === 'function') {
195 console.error(
196 'This browser lacks typed array (Uint8Array) support which is required by ' +
197 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
198 )
199}
200
201function typedArraySupport () {
202 // Can typed array instances can be augmented?
203 try {
204 var arr = new Uint8Array(1)
205 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
206 return arr.foo() === 42
207 } catch (e) {
208 return false
209 }
210}
211
212Object.defineProperty(Buffer.prototype, 'parent', {
213 enumerable: true,
214 get: function () {
215 if (!Buffer.isBuffer(this)) return undefined
216 return this.buffer
217 }
218})
219
220Object.defineProperty(Buffer.prototype, 'offset', {
221 enumerable: true,
222 get: function () {
223 if (!Buffer.isBuffer(this)) return undefined
224 return this.byteOffset
225 }
226})
227
228function createBuffer (length) {
229 if (length > K_MAX_LENGTH) {
230 throw new RangeError('The value "' + length + '" is invalid for option "size"')
231 }
232 // Return an augmented `Uint8Array` instance
233 var buf = new Uint8Array(length)
234 buf.__proto__ = Buffer.prototype
235 return buf
236}
237
238/**
239 * The Buffer constructor returns instances of `Uint8Array` that have their
240 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
241 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
242 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
243 * returns a single octet.
244 *
245 * The `Uint8Array` prototype remains unmodified.
246 */
247
248function Buffer (arg, encodingOrOffset, length) {
249 // Common case.
250 if (typeof arg === 'number') {
251 if (typeof encodingOrOffset === 'string') {
252 throw new TypeError(
253 'The "string" argument must be of type string. Received type number'
254 )
255 }
256 return allocUnsafe(arg)
257 }
258 return from(arg, encodingOrOffset, length)
259}
260
261// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
262if (typeof Symbol !== 'undefined' && Symbol.species != null &&
263 Buffer[Symbol.species] === Buffer) {
264 Object.defineProperty(Buffer, Symbol.species, {
265 value: null,
266 configurable: true,
267 enumerable: false,
268 writable: false
269 })
270}
271
272Buffer.poolSize = 8192 // not used by this implementation
273
274function from (value, encodingOrOffset, length) {
275 if (typeof value === 'string') {
276 return fromString(value, encodingOrOffset)
277 }
278
279 if (ArrayBuffer.isView(value)) {
280 return fromArrayLike(value)
281 }
282
283 if (value == null) {
284 throw TypeError(
285 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
286 'or Array-like Object. Received type ' + (typeof value)
287 )
288 }
289
290 if (isInstance(value, ArrayBuffer) ||
291 (value && isInstance(value.buffer, ArrayBuffer))) {
292 return fromArrayBuffer(value, encodingOrOffset, length)
293 }
294
295 if (typeof value === 'number') {
296 throw new TypeError(
297 'The "value" argument must not be of type number. Received type number'
298 )
299 }
300
301 var valueOf = value.valueOf && value.valueOf()
302 if (valueOf != null && valueOf !== value) {
303 return Buffer.from(valueOf, encodingOrOffset, length)
304 }
305
306 var b = fromObject(value)
307 if (b) return b
308
309 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
310 typeof value[Symbol.toPrimitive] === 'function') {
311 return Buffer.from(
312 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
313 )
314 }
315
316 throw new TypeError(
317 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
318 'or Array-like Object. Received type ' + (typeof value)
319 )
320}
321
322/**
323 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
324 * if value is a number.
325 * Buffer.from(str[, encoding])
326 * Buffer.from(array)
327 * Buffer.from(buffer)
328 * Buffer.from(arrayBuffer[, byteOffset[, length]])
329 **/
330Buffer.from = function (value, encodingOrOffset, length) {
331 return from(value, encodingOrOffset, length)
332}
333
334// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
335// https://github.com/feross/buffer/pull/148
336Buffer.prototype.__proto__ = Uint8Array.prototype
337Buffer.__proto__ = Uint8Array
338
339function assertSize (size) {
340 if (typeof size !== 'number') {
341 throw new TypeError('"size" argument must be of type number')
342 } else if (size < 0) {
343 throw new RangeError('The value "' + size + '" is invalid for option "size"')
344 }
345}
346
347function alloc (size, fill, encoding) {
348 assertSize(size)
349 if (size <= 0) {
350 return createBuffer(size)
351 }
352 if (fill !== undefined) {
353 // Only pay attention to encoding if it's a string. This
354 // prevents accidentally sending in a number that would
355 // be interpretted as a start offset.
356 return typeof encoding === 'string'
357 ? createBuffer(size).fill(fill, encoding)
358 : createBuffer(size).fill(fill)
359 }
360 return createBuffer(size)
361}
362
363/**
364 * Creates a new filled Buffer instance.
365 * alloc(size[, fill[, encoding]])
366 **/
367Buffer.alloc = function (size, fill, encoding) {
368 return alloc(size, fill, encoding)
369}
370
371function allocUnsafe (size) {
372 assertSize(size)
373 return createBuffer(size < 0 ? 0 : checked(size) | 0)
374}
375
376/**
377 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
378 * */
379Buffer.allocUnsafe = function (size) {
380 return allocUnsafe(size)
381}
382/**
383 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
384 */
385Buffer.allocUnsafeSlow = function (size) {
386 return allocUnsafe(size)
387}
388
389function fromString (string, encoding) {
390 if (typeof encoding !== 'string' || encoding === '') {
391 encoding = 'utf8'
392 }
393
394 if (!Buffer.isEncoding(encoding)) {
395 throw new TypeError('Unknown encoding: ' + encoding)
396 }
397
398 var length = byteLength(string, encoding) | 0
399 var buf = createBuffer(length)
400
401 var actual = buf.write(string, encoding)
402
403 if (actual !== length) {
404 // Writing a hex string, for example, that contains invalid characters will
405 // cause everything after the first invalid character to be ignored. (e.g.
406 // 'abxxcd' will be treated as 'ab')
407 buf = buf.slice(0, actual)
408 }
409
410 return buf
411}
412
413function fromArrayLike (array) {
414 var length = array.length < 0 ? 0 : checked(array.length) | 0
415 var buf = createBuffer(length)
416 for (var i = 0; i < length; i += 1) {
417 buf[i] = array[i] & 255
418 }
419 return buf
420}
421
422function fromArrayBuffer (array, byteOffset, length) {
423 if (byteOffset < 0 || array.byteLength < byteOffset) {
424 throw new RangeError('"offset" is outside of buffer bounds')
425 }
426
427 if (array.byteLength < byteOffset + (length || 0)) {
428 throw new RangeError('"length" is outside of buffer bounds')
429 }
430
431 var buf
432 if (byteOffset === undefined && length === undefined) {
433 buf = new Uint8Array(array)
434 } else if (length === undefined) {
435 buf = new Uint8Array(array, byteOffset)
436 } else {
437 buf = new Uint8Array(array, byteOffset, length)
438 }
439
440 // Return an augmented `Uint8Array` instance
441 buf.__proto__ = Buffer.prototype
442 return buf
443}
444
445function fromObject (obj) {
446 if (Buffer.isBuffer(obj)) {
447 var len = checked(obj.length) | 0
448 var buf = createBuffer(len)
449
450 if (buf.length === 0) {
451 return buf
452 }
453
454 obj.copy(buf, 0, 0, len)
455 return buf
456 }
457
458 if (obj.length !== undefined) {
459 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
460 return createBuffer(0)
461 }
462 return fromArrayLike(obj)
463 }
464
465 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
466 return fromArrayLike(obj.data)
467 }
468}
469
470function checked (length) {
471 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
472 // length is NaN (which is otherwise coerced to zero.)
473 if (length >= K_MAX_LENGTH) {
474 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
475 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
476 }
477 return length | 0
478}
479
480function SlowBuffer (length) {
481 if (+length != length) { // eslint-disable-line eqeqeq
482 length = 0
483 }
484 return Buffer.alloc(+length)
485}
486
487Buffer.isBuffer = function isBuffer (b) {
488 return b != null && b._isBuffer === true &&
489 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
490}
491
492Buffer.compare = function compare (a, b) {
493 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
494 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
495 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
496 throw new TypeError(
497 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
498 )
499 }
500
501 if (a === b) return 0
502
503 var x = a.length
504 var y = b.length
505
506 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
507 if (a[i] !== b[i]) {
508 x = a[i]
509 y = b[i]
510 break
511 }
512 }
513
514 if (x < y) return -1
515 if (y < x) return 1
516 return 0
517}
518
519Buffer.isEncoding = function isEncoding (encoding) {
520 switch (String(encoding).toLowerCase()) {
521 case 'hex':
522 case 'utf8':
523 case 'utf-8':
524 case 'ascii':
525 case 'latin1':
526 case 'binary':
527 case 'base64':
528 case 'ucs2':
529 case 'ucs-2':
530 case 'utf16le':
531 case 'utf-16le':
532 return true
533 default:
534 return false
535 }
536}
537
538Buffer.concat = function concat (list, length) {
539 if (!Array.isArray(list)) {
540 throw new TypeError('"list" argument must be an Array of Buffers')
541 }
542
543 if (list.length === 0) {
544 return Buffer.alloc(0)
545 }
546
547 var i
548 if (length === undefined) {
549 length = 0
550 for (i = 0; i < list.length; ++i) {
551 length += list[i].length
552 }
553 }
554
555 var buffer = Buffer.allocUnsafe(length)
556 var pos = 0
557 for (i = 0; i < list.length; ++i) {
558 var buf = list[i]
559 if (isInstance(buf, Uint8Array)) {
560 buf = Buffer.from(buf)
561 }
562 if (!Buffer.isBuffer(buf)) {
563 throw new TypeError('"list" argument must be an Array of Buffers')
564 }
565 buf.copy(buffer, pos)
566 pos += buf.length
567 }
568 return buffer
569}
570
571function byteLength (string, encoding) {
572 if (Buffer.isBuffer(string)) {
573 return string.length
574 }
575 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
576 return string.byteLength
577 }
578 if (typeof string !== 'string') {
579 throw new TypeError(
580 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
581 'Received type ' + typeof string
582 )
583 }
584
585 var len = string.length
586 var mustMatch = (arguments.length > 2 && arguments[2] === true)
587 if (!mustMatch && len === 0) return 0
588
589 // Use a for loop to avoid recursion
590 var loweredCase = false
591 for (;;) {
592 switch (encoding) {
593 case 'ascii':
594 case 'latin1':
595 case 'binary':
596 return len
597 case 'utf8':
598 case 'utf-8':
599 return utf8ToBytes(string).length
600 case 'ucs2':
601 case 'ucs-2':
602 case 'utf16le':
603 case 'utf-16le':
604 return len * 2
605 case 'hex':
606 return len >>> 1
607 case 'base64':
608 return base64ToBytes(string).length
609 default:
610 if (loweredCase) {
611 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
612 }
613 encoding = ('' + encoding).toLowerCase()
614 loweredCase = true
615 }
616 }
617}
618Buffer.byteLength = byteLength
619
620function slowToString (encoding, start, end) {
621 var loweredCase = false
622
623 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
624 // property of a typed array.
625
626 // This behaves neither like String nor Uint8Array in that we set start/end
627 // to their upper/lower bounds if the value passed is out of range.
628 // undefined is handled specially as per ECMA-262 6th Edition,
629 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
630 if (start === undefined || start < 0) {
631 start = 0
632 }
633 // Return early if start > this.length. Done here to prevent potential uint32
634 // coercion fail below.
635 if (start > this.length) {
636 return ''
637 }
638
639 if (end === undefined || end > this.length) {
640 end = this.length
641 }
642
643 if (end <= 0) {
644 return ''
645 }
646
647 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
648 end >>>= 0
649 start >>>= 0
650
651 if (end <= start) {
652 return ''
653 }
654
655 if (!encoding) encoding = 'utf8'
656
657 while (true) {
658 switch (encoding) {
659 case 'hex':
660 return hexSlice(this, start, end)
661
662 case 'utf8':
663 case 'utf-8':
664 return utf8Slice(this, start, end)
665
666 case 'ascii':
667 return asciiSlice(this, start, end)
668
669 case 'latin1':
670 case 'binary':
671 return latin1Slice(this, start, end)
672
673 case 'base64':
674 return base64Slice(this, start, end)
675
676 case 'ucs2':
677 case 'ucs-2':
678 case 'utf16le':
679 case 'utf-16le':
680 return utf16leSlice(this, start, end)
681
682 default:
683 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
684 encoding = (encoding + '').toLowerCase()
685 loweredCase = true
686 }
687 }
688}
689
690// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
691// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
692// reliably in a browserify context because there could be multiple different
693// copies of the 'buffer' package in use. This method works even for Buffer
694// instances that were created from another copy of the `buffer` package.
695// See: https://github.com/feross/buffer/issues/154
696Buffer.prototype._isBuffer = true
697
698function swap (b, n, m) {
699 var i = b[n]
700 b[n] = b[m]
701 b[m] = i
702}
703
704Buffer.prototype.swap16 = function swap16 () {
705 var len = this.length
706 if (len % 2 !== 0) {
707 throw new RangeError('Buffer size must be a multiple of 16-bits')
708 }
709 for (var i = 0; i < len; i += 2) {
710 swap(this, i, i + 1)
711 }
712 return this
713}
714
715Buffer.prototype.swap32 = function swap32 () {
716 var len = this.length
717 if (len % 4 !== 0) {
718 throw new RangeError('Buffer size must be a multiple of 32-bits')
719 }
720 for (var i = 0; i < len; i += 4) {
721 swap(this, i, i + 3)
722 swap(this, i + 1, i + 2)
723 }
724 return this
725}
726
727Buffer.prototype.swap64 = function swap64 () {
728 var len = this.length
729 if (len % 8 !== 0) {
730 throw new RangeError('Buffer size must be a multiple of 64-bits')
731 }
732 for (var i = 0; i < len; i += 8) {
733 swap(this, i, i + 7)
734 swap(this, i + 1, i + 6)
735 swap(this, i + 2, i + 5)
736 swap(this, i + 3, i + 4)
737 }
738 return this
739}
740
741Buffer.prototype.toString = function toString () {
742 var length = this.length
743 if (length === 0) return ''
744 if (arguments.length === 0) return utf8Slice(this, 0, length)
745 return slowToString.apply(this, arguments)
746}
747
748Buffer.prototype.toLocaleString = Buffer.prototype.toString
749
750Buffer.prototype.equals = function equals (b) {
751 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
752 if (this === b) return true
753 return Buffer.compare(this, b) === 0
754}
755
756Buffer.prototype.inspect = function inspect () {
757 var str = ''
758 var max = exports.INSPECT_MAX_BYTES
759 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
760 if (this.length > max) str += ' ... '
761 return '<Buffer ' + str + '>'
762}
763
764Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
765 if (isInstance(target, Uint8Array)) {
766 target = Buffer.from(target, target.offset, target.byteLength)
767 }
768 if (!Buffer.isBuffer(target)) {
769 throw new TypeError(
770 'The "target" argument must be one of type Buffer or Uint8Array. ' +
771 'Received type ' + (typeof target)
772 )
773 }
774
775 if (start === undefined) {
776 start = 0
777 }
778 if (end === undefined) {
779 end = target ? target.length : 0
780 }
781 if (thisStart === undefined) {
782 thisStart = 0
783 }
784 if (thisEnd === undefined) {
785 thisEnd = this.length
786 }
787
788 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
789 throw new RangeError('out of range index')
790 }
791
792 if (thisStart >= thisEnd && start >= end) {
793 return 0
794 }
795 if (thisStart >= thisEnd) {
796 return -1
797 }
798 if (start >= end) {
799 return 1
800 }
801
802 start >>>= 0
803 end >>>= 0
804 thisStart >>>= 0
805 thisEnd >>>= 0
806
807 if (this === target) return 0
808
809 var x = thisEnd - thisStart
810 var y = end - start
811 var len = Math.min(x, y)
812
813 var thisCopy = this.slice(thisStart, thisEnd)
814 var targetCopy = target.slice(start, end)
815
816 for (var i = 0; i < len; ++i) {
817 if (thisCopy[i] !== targetCopy[i]) {
818 x = thisCopy[i]
819 y = targetCopy[i]
820 break
821 }
822 }
823
824 if (x < y) return -1
825 if (y < x) return 1
826 return 0
827}
828
829// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
830// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
831//
832// Arguments:
833// - buffer - a Buffer to search
834// - val - a string, Buffer, or number
835// - byteOffset - an index into `buffer`; will be clamped to an int32
836// - encoding - an optional encoding, relevant is val is a string
837// - dir - true for indexOf, false for lastIndexOf
838function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
839 // Empty buffer means no match
840 if (buffer.length === 0) return -1
841
842 // Normalize byteOffset
843 if (typeof byteOffset === 'string') {
844 encoding = byteOffset
845 byteOffset = 0
846 } else if (byteOffset > 0x7fffffff) {
847 byteOffset = 0x7fffffff
848 } else if (byteOffset < -0x80000000) {
849 byteOffset = -0x80000000
850 }
851 byteOffset = +byteOffset // Coerce to Number.
852 if (numberIsNaN(byteOffset)) {
853 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
854 byteOffset = dir ? 0 : (buffer.length - 1)
855 }
856
857 // Normalize byteOffset: negative offsets start from the end of the buffer
858 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
859 if (byteOffset >= buffer.length) {
860 if (dir) return -1
861 else byteOffset = buffer.length - 1
862 } else if (byteOffset < 0) {
863 if (dir) byteOffset = 0
864 else return -1
865 }
866
867 // Normalize val
868 if (typeof val === 'string') {
869 val = Buffer.from(val, encoding)
870 }
871
872 // Finally, search either indexOf (if dir is true) or lastIndexOf
873 if (Buffer.isBuffer(val)) {
874 // Special case: looking for empty string/buffer always fails
875 if (val.length === 0) {
876 return -1
877 }
878 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
879 } else if (typeof val === 'number') {
880 val = val & 0xFF // Search for a byte value [0-255]
881 if (typeof Uint8Array.prototype.indexOf === 'function') {
882 if (dir) {
883 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
884 } else {
885 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
886 }
887 }
888 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
889 }
890
891 throw new TypeError('val must be string, number or Buffer')
892}
893
894function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
895 var indexSize = 1
896 var arrLength = arr.length
897 var valLength = val.length
898
899 if (encoding !== undefined) {
900 encoding = String(encoding).toLowerCase()
901 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
902 encoding === 'utf16le' || encoding === 'utf-16le') {
903 if (arr.length < 2 || val.length < 2) {
904 return -1
905 }
906 indexSize = 2
907 arrLength /= 2
908 valLength /= 2
909 byteOffset /= 2
910 }
911 }
912
913 function read (buf, i) {
914 if (indexSize === 1) {
915 return buf[i]
916 } else {
917 return buf.readUInt16BE(i * indexSize)
918 }
919 }
920
921 var i
922 if (dir) {
923 var foundIndex = -1
924 for (i = byteOffset; i < arrLength; i++) {
925 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
926 if (foundIndex === -1) foundIndex = i
927 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
928 } else {
929 if (foundIndex !== -1) i -= i - foundIndex
930 foundIndex = -1
931 }
932 }
933 } else {
934 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
935 for (i = byteOffset; i >= 0; i--) {
936 var found = true
937 for (var j = 0; j < valLength; j++) {
938 if (read(arr, i + j) !== read(val, j)) {
939 found = false
940 break
941 }
942 }
943 if (found) return i
944 }
945 }
946
947 return -1
948}
949
950Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
951 return this.indexOf(val, byteOffset, encoding) !== -1
952}
953
954Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
955 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
956}
957
958Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
959 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
960}
961
962function hexWrite (buf, string, offset, length) {
963 offset = Number(offset) || 0
964 var remaining = buf.length - offset
965 if (!length) {
966 length = remaining
967 } else {
968 length = Number(length)
969 if (length > remaining) {
970 length = remaining
971 }
972 }
973
974 var strLen = string.length
975
976 if (length > strLen / 2) {
977 length = strLen / 2
978 }
979 for (var i = 0; i < length; ++i) {
980 var parsed = parseInt(string.substr(i * 2, 2), 16)
981 if (numberIsNaN(parsed)) return i
982 buf[offset + i] = parsed
983 }
984 return i
985}
986
987function utf8Write (buf, string, offset, length) {
988 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
989}
990
991function asciiWrite (buf, string, offset, length) {
992 return blitBuffer(asciiToBytes(string), buf, offset, length)
993}
994
995function latin1Write (buf, string, offset, length) {
996 return asciiWrite(buf, string, offset, length)
997}
998
999function base64Write (buf, string, offset, length) {
1000 return blitBuffer(base64ToBytes(string), buf, offset, length)
1001}
1002
1003function ucs2Write (buf, string, offset, length) {
1004 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1005}
1006
1007Buffer.prototype.write = function write (string, offset, length, encoding) {
1008 // Buffer#write(string)
1009 if (offset === undefined) {
1010 encoding = 'utf8'
1011 length = this.length
1012 offset = 0
1013 // Buffer#write(string, encoding)
1014 } else if (length === undefined && typeof offset === 'string') {
1015 encoding = offset
1016 length = this.length
1017 offset = 0
1018 // Buffer#write(string, offset[, length][, encoding])
1019 } else if (isFinite(offset)) {
1020 offset = offset >>> 0
1021 if (isFinite(length)) {
1022 length = length >>> 0
1023 if (encoding === undefined) encoding = 'utf8'
1024 } else {
1025 encoding = length
1026 length = undefined
1027 }
1028 } else {
1029 throw new Error(
1030 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1031 )
1032 }
1033
1034 var remaining = this.length - offset
1035 if (length === undefined || length > remaining) length = remaining
1036
1037 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1038 throw new RangeError('Attempt to write outside buffer bounds')
1039 }
1040
1041 if (!encoding) encoding = 'utf8'
1042
1043 var loweredCase = false
1044 for (;;) {
1045 switch (encoding) {
1046 case 'hex':
1047 return hexWrite(this, string, offset, length)
1048
1049 case 'utf8':
1050 case 'utf-8':
1051 return utf8Write(this, string, offset, length)
1052
1053 case 'ascii':
1054 return asciiWrite(this, string, offset, length)
1055
1056 case 'latin1':
1057 case 'binary':
1058 return latin1Write(this, string, offset, length)
1059
1060 case 'base64':
1061 // Warning: maxLength not taken into account in base64Write
1062 return base64Write(this, string, offset, length)
1063
1064 case 'ucs2':
1065 case 'ucs-2':
1066 case 'utf16le':
1067 case 'utf-16le':
1068 return ucs2Write(this, string, offset, length)
1069
1070 default:
1071 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1072 encoding = ('' + encoding).toLowerCase()
1073 loweredCase = true
1074 }
1075 }
1076}
1077
1078Buffer.prototype.toJSON = function toJSON () {
1079 return {
1080 type: 'Buffer',
1081 data: Array.prototype.slice.call(this._arr || this, 0)
1082 }
1083}
1084
1085function base64Slice (buf, start, end) {
1086 if (start === 0 && end === buf.length) {
1087 return base64.fromByteArray(buf)
1088 } else {
1089 return base64.fromByteArray(buf.slice(start, end))
1090 }
1091}
1092
1093function utf8Slice (buf, start, end) {
1094 end = Math.min(buf.length, end)
1095 var res = []
1096
1097 var i = start
1098 while (i < end) {
1099 var firstByte = buf[i]
1100 var codePoint = null
1101 var bytesPerSequence = (firstByte > 0xEF) ? 4
1102 : (firstByte > 0xDF) ? 3
1103 : (firstByte > 0xBF) ? 2
1104 : 1
1105
1106 if (i + bytesPerSequence <= end) {
1107 var secondByte, thirdByte, fourthByte, tempCodePoint
1108
1109 switch (bytesPerSequence) {
1110 case 1:
1111 if (firstByte < 0x80) {
1112 codePoint = firstByte
1113 }
1114 break
1115 case 2:
1116 secondByte = buf[i + 1]
1117 if ((secondByte & 0xC0) === 0x80) {
1118 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1119 if (tempCodePoint > 0x7F) {
1120 codePoint = tempCodePoint
1121 }
1122 }
1123 break
1124 case 3:
1125 secondByte = buf[i + 1]
1126 thirdByte = buf[i + 2]
1127 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1128 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1129 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1130 codePoint = tempCodePoint
1131 }
1132 }
1133 break
1134 case 4:
1135 secondByte = buf[i + 1]
1136 thirdByte = buf[i + 2]
1137 fourthByte = buf[i + 3]
1138 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1139 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1140 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1141 codePoint = tempCodePoint
1142 }
1143 }
1144 }
1145 }
1146
1147 if (codePoint === null) {
1148 // we did not generate a valid codePoint so insert a
1149 // replacement char (U+FFFD) and advance only 1 byte
1150 codePoint = 0xFFFD
1151 bytesPerSequence = 1
1152 } else if (codePoint > 0xFFFF) {
1153 // encode to utf16 (surrogate pair dance)
1154 codePoint -= 0x10000
1155 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1156 codePoint = 0xDC00 | codePoint & 0x3FF
1157 }
1158
1159 res.push(codePoint)
1160 i += bytesPerSequence
1161 }
1162
1163 return decodeCodePointsArray(res)
1164}
1165
1166// Based on http://stackoverflow.com/a/22747272/680742, the browser with
1167// the lowest limit is Chrome, with 0x10000 args.
1168// We go 1 magnitude less, for safety
1169var MAX_ARGUMENTS_LENGTH = 0x1000
1170
1171function decodeCodePointsArray (codePoints) {
1172 var len = codePoints.length
1173 if (len <= MAX_ARGUMENTS_LENGTH) {
1174 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1175 }
1176
1177 // Decode in chunks to avoid "call stack size exceeded".
1178 var res = ''
1179 var i = 0
1180 while (i < len) {
1181 res += String.fromCharCode.apply(
1182 String,
1183 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1184 )
1185 }
1186 return res
1187}
1188
1189function asciiSlice (buf, start, end) {
1190 var ret = ''
1191 end = Math.min(buf.length, end)
1192
1193 for (var i = start; i < end; ++i) {
1194 ret += String.fromCharCode(buf[i] & 0x7F)
1195 }
1196 return ret
1197}
1198
1199function latin1Slice (buf, start, end) {
1200 var ret = ''
1201 end = Math.min(buf.length, end)
1202
1203 for (var i = start; i < end; ++i) {
1204 ret += String.fromCharCode(buf[i])
1205 }
1206 return ret
1207}
1208
1209function hexSlice (buf, start, end) {
1210 var len = buf.length
1211
1212 if (!start || start < 0) start = 0
1213 if (!end || end < 0 || end > len) end = len
1214
1215 var out = ''
1216 for (var i = start; i < end; ++i) {
1217 out += toHex(buf[i])
1218 }
1219 return out
1220}
1221
1222function utf16leSlice (buf, start, end) {
1223 var bytes = buf.slice(start, end)
1224 var res = ''
1225 for (var i = 0; i < bytes.length; i += 2) {
1226 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1227 }
1228 return res
1229}
1230
1231Buffer.prototype.slice = function slice (start, end) {
1232 var len = this.length
1233 start = ~~start
1234 end = end === undefined ? len : ~~end
1235
1236 if (start < 0) {
1237 start += len
1238 if (start < 0) start = 0
1239 } else if (start > len) {
1240 start = len
1241 }
1242
1243 if (end < 0) {
1244 end += len
1245 if (end < 0) end = 0
1246 } else if (end > len) {
1247 end = len
1248 }
1249
1250 if (end < start) end = start
1251
1252 var newBuf = this.subarray(start, end)
1253 // Return an augmented `Uint8Array` instance
1254 newBuf.__proto__ = Buffer.prototype
1255 return newBuf
1256}
1257
1258/*
1259 * Need to make sure that buffer isn't trying to write out of bounds.
1260 */
1261function checkOffset (offset, ext, length) {
1262 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1263 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1264}
1265
1266Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1267 offset = offset >>> 0
1268 byteLength = byteLength >>> 0
1269 if (!noAssert) checkOffset(offset, byteLength, this.length)
1270
1271 var val = this[offset]
1272 var mul = 1
1273 var i = 0
1274 while (++i < byteLength && (mul *= 0x100)) {
1275 val += this[offset + i] * mul
1276 }
1277
1278 return val
1279}
1280
1281Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1282 offset = offset >>> 0
1283 byteLength = byteLength >>> 0
1284 if (!noAssert) {
1285 checkOffset(offset, byteLength, this.length)
1286 }
1287
1288 var val = this[offset + --byteLength]
1289 var mul = 1
1290 while (byteLength > 0 && (mul *= 0x100)) {
1291 val += this[offset + --byteLength] * mul
1292 }
1293
1294 return val
1295}
1296
1297Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1298 offset = offset >>> 0
1299 if (!noAssert) checkOffset(offset, 1, this.length)
1300 return this[offset]
1301}
1302
1303Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1304 offset = offset >>> 0
1305 if (!noAssert) checkOffset(offset, 2, this.length)
1306 return this[offset] | (this[offset + 1] << 8)
1307}
1308
1309Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1310 offset = offset >>> 0
1311 if (!noAssert) checkOffset(offset, 2, this.length)
1312 return (this[offset] << 8) | this[offset + 1]
1313}
1314
1315Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1316 offset = offset >>> 0
1317 if (!noAssert) checkOffset(offset, 4, this.length)
1318
1319 return ((this[offset]) |
1320 (this[offset + 1] << 8) |
1321 (this[offset + 2] << 16)) +
1322 (this[offset + 3] * 0x1000000)
1323}
1324
1325Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1326 offset = offset >>> 0
1327 if (!noAssert) checkOffset(offset, 4, this.length)
1328
1329 return (this[offset] * 0x1000000) +
1330 ((this[offset + 1] << 16) |
1331 (this[offset + 2] << 8) |
1332 this[offset + 3])
1333}
1334
1335Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1336 offset = offset >>> 0
1337 byteLength = byteLength >>> 0
1338 if (!noAssert) checkOffset(offset, byteLength, this.length)
1339
1340 var val = this[offset]
1341 var mul = 1
1342 var i = 0
1343 while (++i < byteLength && (mul *= 0x100)) {
1344 val += this[offset + i] * mul
1345 }
1346 mul *= 0x80
1347
1348 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1349
1350 return val
1351}
1352
1353Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1354 offset = offset >>> 0
1355 byteLength = byteLength >>> 0
1356 if (!noAssert) checkOffset(offset, byteLength, this.length)
1357
1358 var i = byteLength
1359 var mul = 1
1360 var val = this[offset + --i]
1361 while (i > 0 && (mul *= 0x100)) {
1362 val += this[offset + --i] * mul
1363 }
1364 mul *= 0x80
1365
1366 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1367
1368 return val
1369}
1370
1371Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1372 offset = offset >>> 0
1373 if (!noAssert) checkOffset(offset, 1, this.length)
1374 if (!(this[offset] & 0x80)) return (this[offset])
1375 return ((0xff - this[offset] + 1) * -1)
1376}
1377
1378Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1379 offset = offset >>> 0
1380 if (!noAssert) checkOffset(offset, 2, this.length)
1381 var val = this[offset] | (this[offset + 1] << 8)
1382 return (val & 0x8000) ? val | 0xFFFF0000 : val
1383}
1384
1385Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1386 offset = offset >>> 0
1387 if (!noAssert) checkOffset(offset, 2, this.length)
1388 var val = this[offset + 1] | (this[offset] << 8)
1389 return (val & 0x8000) ? val | 0xFFFF0000 : val
1390}
1391
1392Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1393 offset = offset >>> 0
1394 if (!noAssert) checkOffset(offset, 4, this.length)
1395
1396 return (this[offset]) |
1397 (this[offset + 1] << 8) |
1398 (this[offset + 2] << 16) |
1399 (this[offset + 3] << 24)
1400}
1401
1402Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1403 offset = offset >>> 0
1404 if (!noAssert) checkOffset(offset, 4, this.length)
1405
1406 return (this[offset] << 24) |
1407 (this[offset + 1] << 16) |
1408 (this[offset + 2] << 8) |
1409 (this[offset + 3])
1410}
1411
1412Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1413 offset = offset >>> 0
1414 if (!noAssert) checkOffset(offset, 4, this.length)
1415 return ieee754.read(this, offset, true, 23, 4)
1416}
1417
1418Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1419 offset = offset >>> 0
1420 if (!noAssert) checkOffset(offset, 4, this.length)
1421 return ieee754.read(this, offset, false, 23, 4)
1422}
1423
1424Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1425 offset = offset >>> 0
1426 if (!noAssert) checkOffset(offset, 8, this.length)
1427 return ieee754.read(this, offset, true, 52, 8)
1428}
1429
1430Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1431 offset = offset >>> 0
1432 if (!noAssert) checkOffset(offset, 8, this.length)
1433 return ieee754.read(this, offset, false, 52, 8)
1434}
1435
1436function checkInt (buf, value, offset, ext, max, min) {
1437 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1438 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1439 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1440}
1441
1442Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1443 value = +value
1444 offset = offset >>> 0
1445 byteLength = byteLength >>> 0
1446 if (!noAssert) {
1447 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1448 checkInt(this, value, offset, byteLength, maxBytes, 0)
1449 }
1450
1451 var mul = 1
1452 var i = 0
1453 this[offset] = value & 0xFF
1454 while (++i < byteLength && (mul *= 0x100)) {
1455 this[offset + i] = (value / mul) & 0xFF
1456 }
1457
1458 return offset + byteLength
1459}
1460
1461Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1462 value = +value
1463 offset = offset >>> 0
1464 byteLength = byteLength >>> 0
1465 if (!noAssert) {
1466 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1467 checkInt(this, value, offset, byteLength, maxBytes, 0)
1468 }
1469
1470 var i = byteLength - 1
1471 var mul = 1
1472 this[offset + i] = value & 0xFF
1473 while (--i >= 0 && (mul *= 0x100)) {
1474 this[offset + i] = (value / mul) & 0xFF
1475 }
1476
1477 return offset + byteLength
1478}
1479
1480Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1481 value = +value
1482 offset = offset >>> 0
1483 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1484 this[offset] = (value & 0xff)
1485 return offset + 1
1486}
1487
1488Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1489 value = +value
1490 offset = offset >>> 0
1491 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1492 this[offset] = (value & 0xff)
1493 this[offset + 1] = (value >>> 8)
1494 return offset + 2
1495}
1496
1497Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1498 value = +value
1499 offset = offset >>> 0
1500 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1501 this[offset] = (value >>> 8)
1502 this[offset + 1] = (value & 0xff)
1503 return offset + 2
1504}
1505
1506Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1507 value = +value
1508 offset = offset >>> 0
1509 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1510 this[offset + 3] = (value >>> 24)
1511 this[offset + 2] = (value >>> 16)
1512 this[offset + 1] = (value >>> 8)
1513 this[offset] = (value & 0xff)
1514 return offset + 4
1515}
1516
1517Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1518 value = +value
1519 offset = offset >>> 0
1520 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1521 this[offset] = (value >>> 24)
1522 this[offset + 1] = (value >>> 16)
1523 this[offset + 2] = (value >>> 8)
1524 this[offset + 3] = (value & 0xff)
1525 return offset + 4
1526}
1527
1528Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1529 value = +value
1530 offset = offset >>> 0
1531 if (!noAssert) {
1532 var limit = Math.pow(2, (8 * byteLength) - 1)
1533
1534 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1535 }
1536
1537 var i = 0
1538 var mul = 1
1539 var sub = 0
1540 this[offset] = value & 0xFF
1541 while (++i < byteLength && (mul *= 0x100)) {
1542 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1543 sub = 1
1544 }
1545 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1546 }
1547
1548 return offset + byteLength
1549}
1550
1551Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1552 value = +value
1553 offset = offset >>> 0
1554 if (!noAssert) {
1555 var limit = Math.pow(2, (8 * byteLength) - 1)
1556
1557 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1558 }
1559
1560 var i = byteLength - 1
1561 var mul = 1
1562 var sub = 0
1563 this[offset + i] = value & 0xFF
1564 while (--i >= 0 && (mul *= 0x100)) {
1565 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1566 sub = 1
1567 }
1568 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1569 }
1570
1571 return offset + byteLength
1572}
1573
1574Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1575 value = +value
1576 offset = offset >>> 0
1577 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1578 if (value < 0) value = 0xff + value + 1
1579 this[offset] = (value & 0xff)
1580 return offset + 1
1581}
1582
1583Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1584 value = +value
1585 offset = offset >>> 0
1586 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1587 this[offset] = (value & 0xff)
1588 this[offset + 1] = (value >>> 8)
1589 return offset + 2
1590}
1591
1592Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1593 value = +value
1594 offset = offset >>> 0
1595 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1596 this[offset] = (value >>> 8)
1597 this[offset + 1] = (value & 0xff)
1598 return offset + 2
1599}
1600
1601Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1602 value = +value
1603 offset = offset >>> 0
1604 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1605 this[offset] = (value & 0xff)
1606 this[offset + 1] = (value >>> 8)
1607 this[offset + 2] = (value >>> 16)
1608 this[offset + 3] = (value >>> 24)
1609 return offset + 4
1610}
1611
1612Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1613 value = +value
1614 offset = offset >>> 0
1615 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1616 if (value < 0) value = 0xffffffff + value + 1
1617 this[offset] = (value >>> 24)
1618 this[offset + 1] = (value >>> 16)
1619 this[offset + 2] = (value >>> 8)
1620 this[offset + 3] = (value & 0xff)
1621 return offset + 4
1622}
1623
1624function checkIEEE754 (buf, value, offset, ext, max, min) {
1625 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1626 if (offset < 0) throw new RangeError('Index out of range')
1627}
1628
1629function writeFloat (buf, value, offset, littleEndian, noAssert) {
1630 value = +value
1631 offset = offset >>> 0
1632 if (!noAssert) {
1633 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1634 }
1635 ieee754.write(buf, value, offset, littleEndian, 23, 4)
1636 return offset + 4
1637}
1638
1639Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1640 return writeFloat(this, value, offset, true, noAssert)
1641}
1642
1643Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1644 return writeFloat(this, value, offset, false, noAssert)
1645}
1646
1647function writeDouble (buf, value, offset, littleEndian, noAssert) {
1648 value = +value
1649 offset = offset >>> 0
1650 if (!noAssert) {
1651 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1652 }
1653 ieee754.write(buf, value, offset, littleEndian, 52, 8)
1654 return offset + 8
1655}
1656
1657Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1658 return writeDouble(this, value, offset, true, noAssert)
1659}
1660
1661Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1662 return writeDouble(this, value, offset, false, noAssert)
1663}
1664
1665// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1666Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1667 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
1668 if (!start) start = 0
1669 if (!end && end !== 0) end = this.length
1670 if (targetStart >= target.length) targetStart = target.length
1671 if (!targetStart) targetStart = 0
1672 if (end > 0 && end < start) end = start
1673
1674 // Copy 0 bytes; we're done
1675 if (end === start) return 0
1676 if (target.length === 0 || this.length === 0) return 0
1677
1678 // Fatal error conditions
1679 if (targetStart < 0) {
1680 throw new RangeError('targetStart out of bounds')
1681 }
1682 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
1683 if (end < 0) throw new RangeError('sourceEnd out of bounds')
1684
1685 // Are we oob?
1686 if (end > this.length) end = this.length
1687 if (target.length - targetStart < end - start) {
1688 end = target.length - targetStart + start
1689 }
1690
1691 var len = end - start
1692
1693 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
1694 // Use built-in when available, missing from IE11
1695 this.copyWithin(targetStart, start, end)
1696 } else if (this === target && start < targetStart && targetStart < end) {
1697 // descending copy from end
1698 for (var i = len - 1; i >= 0; --i) {
1699 target[i + targetStart] = this[i + start]
1700 }
1701 } else {
1702 Uint8Array.prototype.set.call(
1703 target,
1704 this.subarray(start, end),
1705 targetStart
1706 )
1707 }
1708
1709 return len
1710}
1711
1712// Usage:
1713// buffer.fill(number[, offset[, end]])
1714// buffer.fill(buffer[, offset[, end]])
1715// buffer.fill(string[, offset[, end]][, encoding])
1716Buffer.prototype.fill = function fill (val, start, end, encoding) {
1717 // Handle string cases:
1718 if (typeof val === 'string') {
1719 if (typeof start === 'string') {
1720 encoding = start
1721 start = 0
1722 end = this.length
1723 } else if (typeof end === 'string') {
1724 encoding = end
1725 end = this.length
1726 }
1727 if (encoding !== undefined && typeof encoding !== 'string') {
1728 throw new TypeError('encoding must be a string')
1729 }
1730 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1731 throw new TypeError('Unknown encoding: ' + encoding)
1732 }
1733 if (val.length === 1) {
1734 var code = val.charCodeAt(0)
1735 if ((encoding === 'utf8' && code < 128) ||
1736 encoding === 'latin1') {
1737 // Fast path: If `val` fits into a single byte, use that numeric value.
1738 val = code
1739 }
1740 }
1741 } else if (typeof val === 'number') {
1742 val = val & 255
1743 }
1744
1745 // Invalid ranges are not set to a default, so can range check early.
1746 if (start < 0 || this.length < start || this.length < end) {
1747 throw new RangeError('Out of range index')
1748 }
1749
1750 if (end <= start) {
1751 return this
1752 }
1753
1754 start = start >>> 0
1755 end = end === undefined ? this.length : end >>> 0
1756
1757 if (!val) val = 0
1758
1759 var i
1760 if (typeof val === 'number') {
1761 for (i = start; i < end; ++i) {
1762 this[i] = val
1763 }
1764 } else {
1765 var bytes = Buffer.isBuffer(val)
1766 ? val
1767 : Buffer.from(val, encoding)
1768 var len = bytes.length
1769 if (len === 0) {
1770 throw new TypeError('The value "' + val +
1771 '" is invalid for argument "value"')
1772 }
1773 for (i = 0; i < end - start; ++i) {
1774 this[i + start] = bytes[i % len]
1775 }
1776 }
1777
1778 return this
1779}
1780
1781// HELPER FUNCTIONS
1782// ================
1783
1784var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
1785
1786function base64clean (str) {
1787 // Node takes equal signs as end of the Base64 encoding
1788 str = str.split('=')[0]
1789 // Node strips out invalid characters like \n and \t from the string, base64-js does not
1790 str = str.trim().replace(INVALID_BASE64_RE, '')
1791 // Node converts strings with length < 2 to ''
1792 if (str.length < 2) return ''
1793 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1794 while (str.length % 4 !== 0) {
1795 str = str + '='
1796 }
1797 return str
1798}
1799
1800function toHex (n) {
1801 if (n < 16) return '0' + n.toString(16)
1802 return n.toString(16)
1803}
1804
1805function utf8ToBytes (string, units) {
1806 units = units || Infinity
1807 var codePoint
1808 var length = string.length
1809 var leadSurrogate = null
1810 var bytes = []
1811
1812 for (var i = 0; i < length; ++i) {
1813 codePoint = string.charCodeAt(i)
1814
1815 // is surrogate component
1816 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1817 // last char was a lead
1818 if (!leadSurrogate) {
1819 // no lead yet
1820 if (codePoint > 0xDBFF) {
1821 // unexpected trail
1822 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1823 continue
1824 } else if (i + 1 === length) {
1825 // unpaired lead
1826 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1827 continue
1828 }
1829
1830 // valid lead
1831 leadSurrogate = codePoint
1832
1833 continue
1834 }
1835
1836 // 2 leads in a row
1837 if (codePoint < 0xDC00) {
1838 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1839 leadSurrogate = codePoint
1840 continue
1841 }
1842
1843 // valid surrogate pair
1844 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
1845 } else if (leadSurrogate) {
1846 // valid bmp char, but last char was a lead
1847 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1848 }
1849
1850 leadSurrogate = null
1851
1852 // encode utf8
1853 if (codePoint < 0x80) {
1854 if ((units -= 1) < 0) break
1855 bytes.push(codePoint)
1856 } else if (codePoint < 0x800) {
1857 if ((units -= 2) < 0) break
1858 bytes.push(
1859 codePoint >> 0x6 | 0xC0,
1860 codePoint & 0x3F | 0x80
1861 )
1862 } else if (codePoint < 0x10000) {
1863 if ((units -= 3) < 0) break
1864 bytes.push(
1865 codePoint >> 0xC | 0xE0,
1866 codePoint >> 0x6 & 0x3F | 0x80,
1867 codePoint & 0x3F | 0x80
1868 )
1869 } else if (codePoint < 0x110000) {
1870 if ((units -= 4) < 0) break
1871 bytes.push(
1872 codePoint >> 0x12 | 0xF0,
1873 codePoint >> 0xC & 0x3F | 0x80,
1874 codePoint >> 0x6 & 0x3F | 0x80,
1875 codePoint & 0x3F | 0x80
1876 )
1877 } else {
1878 throw new Error('Invalid code point')
1879 }
1880 }
1881
1882 return bytes
1883}
1884
1885function asciiToBytes (str) {
1886 var byteArray = []
1887 for (var i = 0; i < str.length; ++i) {
1888 // Node's code seems to be doing this and not & 0x7F..
1889 byteArray.push(str.charCodeAt(i) & 0xFF)
1890 }
1891 return byteArray
1892}
1893
1894function utf16leToBytes (str, units) {
1895 var c, hi, lo
1896 var byteArray = []
1897 for (var i = 0; i < str.length; ++i) {
1898 if ((units -= 2) < 0) break
1899
1900 c = str.charCodeAt(i)
1901 hi = c >> 8
1902 lo = c % 256
1903 byteArray.push(lo)
1904 byteArray.push(hi)
1905 }
1906
1907 return byteArray
1908}
1909
1910function base64ToBytes (str) {
1911 return base64.toByteArray(base64clean(str))
1912}
1913
1914function blitBuffer (src, dst, offset, length) {
1915 for (var i = 0; i < length; ++i) {
1916 if ((i + offset >= dst.length) || (i >= src.length)) break
1917 dst[i + offset] = src[i]
1918 }
1919 return i
1920}
1921
1922// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
1923// the `instanceof` check but they should be treated as of that type.
1924// See: https://github.com/feross/buffer/issues/166
1925function isInstance (obj, type) {
1926 return obj instanceof type ||
1927 (obj != null && obj.constructor != null && obj.constructor.name != null &&
1928 obj.constructor.name === type.name)
1929}
1930function numberIsNaN (obj) {
1931 // For IE11 support
1932 return obj !== obj // eslint-disable-line no-self-compare
1933}
1934
1935}).call(this)}).call(this,require("buffer").Buffer)
1936},{"base64-js":1,"buffer":3,"ieee754":7}],4:[function(require,module,exports){
1937module.exports = {
1938 "100": "Continue",
1939 "101": "Switching Protocols",
1940 "102": "Processing",
1941 "200": "OK",
1942 "201": "Created",
1943 "202": "Accepted",
1944 "203": "Non-Authoritative Information",
1945 "204": "No Content",
1946 "205": "Reset Content",
1947 "206": "Partial Content",
1948 "207": "Multi-Status",
1949 "208": "Already Reported",
1950 "226": "IM Used",
1951 "300": "Multiple Choices",
1952 "301": "Moved Permanently",
1953 "302": "Found",
1954 "303": "See Other",
1955 "304": "Not Modified",
1956 "305": "Use Proxy",
1957 "307": "Temporary Redirect",
1958 "308": "Permanent Redirect",
1959 "400": "Bad Request",
1960 "401": "Unauthorized",
1961 "402": "Payment Required",
1962 "403": "Forbidden",
1963 "404": "Not Found",
1964 "405": "Method Not Allowed",
1965 "406": "Not Acceptable",
1966 "407": "Proxy Authentication Required",
1967 "408": "Request Timeout",
1968 "409": "Conflict",
1969 "410": "Gone",
1970 "411": "Length Required",
1971 "412": "Precondition Failed",
1972 "413": "Payload Too Large",
1973 "414": "URI Too Long",
1974 "415": "Unsupported Media Type",
1975 "416": "Range Not Satisfiable",
1976 "417": "Expectation Failed",
1977 "418": "I'm a teapot",
1978 "421": "Misdirected Request",
1979 "422": "Unprocessable Entity",
1980 "423": "Locked",
1981 "424": "Failed Dependency",
1982 "425": "Unordered Collection",
1983 "426": "Upgrade Required",
1984 "428": "Precondition Required",
1985 "429": "Too Many Requests",
1986 "431": "Request Header Fields Too Large",
1987 "451": "Unavailable For Legal Reasons",
1988 "500": "Internal Server Error",
1989 "501": "Not Implemented",
1990 "502": "Bad Gateway",
1991 "503": "Service Unavailable",
1992 "504": "Gateway Timeout",
1993 "505": "HTTP Version Not Supported",
1994 "506": "Variant Also Negotiates",
1995 "507": "Insufficient Storage",
1996 "508": "Loop Detected",
1997 "509": "Bandwidth Limit Exceeded",
1998 "510": "Not Extended",
1999 "511": "Network Authentication Required"
2000}
2001
2002},{}],5:[function(require,module,exports){
2003// Copyright Joyent, Inc. and other Node contributors.
2004//
2005// Permission is hereby granted, free of charge, to any person obtaining a
2006// copy of this software and associated documentation files (the
2007// "Software"), to deal in the Software without restriction, including
2008// without limitation the rights to use, copy, modify, merge, publish,
2009// distribute, sublicense, and/or sell copies of the Software, and to permit
2010// persons to whom the Software is furnished to do so, subject to the
2011// following conditions:
2012//
2013// The above copyright notice and this permission notice shall be included
2014// in all copies or substantial portions of the Software.
2015//
2016// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2017// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2018// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2019// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2020// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2021// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2022// USE OR OTHER DEALINGS IN THE SOFTWARE.
2023
2024'use strict';
2025
2026var R = typeof Reflect === 'object' ? Reflect : null
2027var ReflectApply = R && typeof R.apply === 'function'
2028 ? R.apply
2029 : function ReflectApply(target, receiver, args) {
2030 return Function.prototype.apply.call(target, receiver, args);
2031 }
2032
2033var ReflectOwnKeys
2034if (R && typeof R.ownKeys === 'function') {
2035 ReflectOwnKeys = R.ownKeys
2036} else if (Object.getOwnPropertySymbols) {
2037 ReflectOwnKeys = function ReflectOwnKeys(target) {
2038 return Object.getOwnPropertyNames(target)
2039 .concat(Object.getOwnPropertySymbols(target));
2040 };
2041} else {
2042 ReflectOwnKeys = function ReflectOwnKeys(target) {
2043 return Object.getOwnPropertyNames(target);
2044 };
2045}
2046
2047function ProcessEmitWarning(warning) {
2048 if (console && console.warn) console.warn(warning);
2049}
2050
2051var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
2052 return value !== value;
2053}
2054
2055function EventEmitter() {
2056 EventEmitter.init.call(this);
2057}
2058module.exports = EventEmitter;
2059module.exports.once = once;
2060
2061// Backwards-compat with node 0.10.x
2062EventEmitter.EventEmitter = EventEmitter;
2063
2064EventEmitter.prototype._events = undefined;
2065EventEmitter.prototype._eventsCount = 0;
2066EventEmitter.prototype._maxListeners = undefined;
2067
2068// By default EventEmitters will print a warning if more than 10 listeners are
2069// added to it. This is a useful default which helps finding memory leaks.
2070var defaultMaxListeners = 10;
2071
2072function checkListener(listener) {
2073 if (typeof listener !== 'function') {
2074 throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
2075 }
2076}
2077
2078Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
2079 enumerable: true,
2080 get: function() {
2081 return defaultMaxListeners;
2082 },
2083 set: function(arg) {
2084 if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
2085 throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
2086 }
2087 defaultMaxListeners = arg;
2088 }
2089});
2090
2091EventEmitter.init = function() {
2092
2093 if (this._events === undefined ||
2094 this._events === Object.getPrototypeOf(this)._events) {
2095 this._events = Object.create(null);
2096 this._eventsCount = 0;
2097 }
2098
2099 this._maxListeners = this._maxListeners || undefined;
2100};
2101
2102// Obviously not all Emitters should be limited to 10. This function allows
2103// that to be increased. Set to zero for unlimited.
2104EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
2105 if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
2106 throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
2107 }
2108 this._maxListeners = n;
2109 return this;
2110};
2111
2112function _getMaxListeners(that) {
2113 if (that._maxListeners === undefined)
2114 return EventEmitter.defaultMaxListeners;
2115 return that._maxListeners;
2116}
2117
2118EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
2119 return _getMaxListeners(this);
2120};
2121
2122EventEmitter.prototype.emit = function emit(type) {
2123 var args = [];
2124 for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
2125 var doError = (type === 'error');
2126
2127 var events = this._events;
2128 if (events !== undefined)
2129 doError = (doError && events.error === undefined);
2130 else if (!doError)
2131 return false;
2132
2133 // If there is no 'error' event listener then throw.
2134 if (doError) {
2135 var er;
2136 if (args.length > 0)
2137 er = args[0];
2138 if (er instanceof Error) {
2139 // Note: The comments on the `throw` lines are intentional, they show
2140 // up in Node's output if this results in an unhandled exception.
2141 throw er; // Unhandled 'error' event
2142 }
2143 // At least give some kind of context to the user
2144 var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
2145 err.context = er;
2146 throw err; // Unhandled 'error' event
2147 }
2148
2149 var handler = events[type];
2150
2151 if (handler === undefined)
2152 return false;
2153
2154 if (typeof handler === 'function') {
2155 ReflectApply(handler, this, args);
2156 } else {
2157 var len = handler.length;
2158 var listeners = arrayClone(handler, len);
2159 for (var i = 0; i < len; ++i)
2160 ReflectApply(listeners[i], this, args);
2161 }
2162
2163 return true;
2164};
2165
2166function _addListener(target, type, listener, prepend) {
2167 var m;
2168 var events;
2169 var existing;
2170
2171 checkListener(listener);
2172
2173 events = target._events;
2174 if (events === undefined) {
2175 events = target._events = Object.create(null);
2176 target._eventsCount = 0;
2177 } else {
2178 // To avoid recursion in the case that type === "newListener"! Before
2179 // adding it to the listeners, first emit "newListener".
2180 if (events.newListener !== undefined) {
2181 target.emit('newListener', type,
2182 listener.listener ? listener.listener : listener);
2183
2184 // Re-assign `events` because a newListener handler could have caused the
2185 // this._events to be assigned to a new object
2186 events = target._events;
2187 }
2188 existing = events[type];
2189 }
2190
2191 if (existing === undefined) {
2192 // Optimize the case of one listener. Don't need the extra array object.
2193 existing = events[type] = listener;
2194 ++target._eventsCount;
2195 } else {
2196 if (typeof existing === 'function') {
2197 // Adding the second element, need to change to array.
2198 existing = events[type] =
2199 prepend ? [listener, existing] : [existing, listener];
2200 // If we've already got an array, just append.
2201 } else if (prepend) {
2202 existing.unshift(listener);
2203 } else {
2204 existing.push(listener);
2205 }
2206
2207 // Check for listener leak
2208 m = _getMaxListeners(target);
2209 if (m > 0 && existing.length > m && !existing.warned) {
2210 existing.warned = true;
2211 // No error code for this since it is a Warning
2212 // eslint-disable-next-line no-restricted-syntax
2213 var w = new Error('Possible EventEmitter memory leak detected. ' +
2214 existing.length + ' ' + String(type) + ' listeners ' +
2215 'added. Use emitter.setMaxListeners() to ' +
2216 'increase limit');
2217 w.name = 'MaxListenersExceededWarning';
2218 w.emitter = target;
2219 w.type = type;
2220 w.count = existing.length;
2221 ProcessEmitWarning(w);
2222 }
2223 }
2224
2225 return target;
2226}
2227
2228EventEmitter.prototype.addListener = function addListener(type, listener) {
2229 return _addListener(this, type, listener, false);
2230};
2231
2232EventEmitter.prototype.on = EventEmitter.prototype.addListener;
2233
2234EventEmitter.prototype.prependListener =
2235 function prependListener(type, listener) {
2236 return _addListener(this, type, listener, true);
2237 };
2238
2239function onceWrapper() {
2240 if (!this.fired) {
2241 this.target.removeListener(this.type, this.wrapFn);
2242 this.fired = true;
2243 if (arguments.length === 0)
2244 return this.listener.call(this.target);
2245 return this.listener.apply(this.target, arguments);
2246 }
2247}
2248
2249function _onceWrap(target, type, listener) {
2250 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
2251 var wrapped = onceWrapper.bind(state);
2252 wrapped.listener = listener;
2253 state.wrapFn = wrapped;
2254 return wrapped;
2255}
2256
2257EventEmitter.prototype.once = function once(type, listener) {
2258 checkListener(listener);
2259 this.on(type, _onceWrap(this, type, listener));
2260 return this;
2261};
2262
2263EventEmitter.prototype.prependOnceListener =
2264 function prependOnceListener(type, listener) {
2265 checkListener(listener);
2266 this.prependListener(type, _onceWrap(this, type, listener));
2267 return this;
2268 };
2269
2270// Emits a 'removeListener' event if and only if the listener was removed.
2271EventEmitter.prototype.removeListener =
2272 function removeListener(type, listener) {
2273 var list, events, position, i, originalListener;
2274
2275 checkListener(listener);
2276
2277 events = this._events;
2278 if (events === undefined)
2279 return this;
2280
2281 list = events[type];
2282 if (list === undefined)
2283 return this;
2284
2285 if (list === listener || list.listener === listener) {
2286 if (--this._eventsCount === 0)
2287 this._events = Object.create(null);
2288 else {
2289 delete events[type];
2290 if (events.removeListener)
2291 this.emit('removeListener', type, list.listener || listener);
2292 }
2293 } else if (typeof list !== 'function') {
2294 position = -1;
2295
2296 for (i = list.length - 1; i >= 0; i--) {
2297 if (list[i] === listener || list[i].listener === listener) {
2298 originalListener = list[i].listener;
2299 position = i;
2300 break;
2301 }
2302 }
2303
2304 if (position < 0)
2305 return this;
2306
2307 if (position === 0)
2308 list.shift();
2309 else {
2310 spliceOne(list, position);
2311 }
2312
2313 if (list.length === 1)
2314 events[type] = list[0];
2315
2316 if (events.removeListener !== undefined)
2317 this.emit('removeListener', type, originalListener || listener);
2318 }
2319
2320 return this;
2321 };
2322
2323EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
2324
2325EventEmitter.prototype.removeAllListeners =
2326 function removeAllListeners(type) {
2327 var listeners, events, i;
2328
2329 events = this._events;
2330 if (events === undefined)
2331 return this;
2332
2333 // not listening for removeListener, no need to emit
2334 if (events.removeListener === undefined) {
2335 if (arguments.length === 0) {
2336 this._events = Object.create(null);
2337 this._eventsCount = 0;
2338 } else if (events[type] !== undefined) {
2339 if (--this._eventsCount === 0)
2340 this._events = Object.create(null);
2341 else
2342 delete events[type];
2343 }
2344 return this;
2345 }
2346
2347 // emit removeListener for all listeners on all events
2348 if (arguments.length === 0) {
2349 var keys = Object.keys(events);
2350 var key;
2351 for (i = 0; i < keys.length; ++i) {
2352 key = keys[i];
2353 if (key === 'removeListener') continue;
2354 this.removeAllListeners(key);
2355 }
2356 this.removeAllListeners('removeListener');
2357 this._events = Object.create(null);
2358 this._eventsCount = 0;
2359 return this;
2360 }
2361
2362 listeners = events[type];
2363
2364 if (typeof listeners === 'function') {
2365 this.removeListener(type, listeners);
2366 } else if (listeners !== undefined) {
2367 // LIFO order
2368 for (i = listeners.length - 1; i >= 0; i--) {
2369 this.removeListener(type, listeners[i]);
2370 }
2371 }
2372
2373 return this;
2374 };
2375
2376function _listeners(target, type, unwrap) {
2377 var events = target._events;
2378
2379 if (events === undefined)
2380 return [];
2381
2382 var evlistener = events[type];
2383 if (evlistener === undefined)
2384 return [];
2385
2386 if (typeof evlistener === 'function')
2387 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
2388
2389 return unwrap ?
2390 unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
2391}
2392
2393EventEmitter.prototype.listeners = function listeners(type) {
2394 return _listeners(this, type, true);
2395};
2396
2397EventEmitter.prototype.rawListeners = function rawListeners(type) {
2398 return _listeners(this, type, false);
2399};
2400
2401EventEmitter.listenerCount = function(emitter, type) {
2402 if (typeof emitter.listenerCount === 'function') {
2403 return emitter.listenerCount(type);
2404 } else {
2405 return listenerCount.call(emitter, type);
2406 }
2407};
2408
2409EventEmitter.prototype.listenerCount = listenerCount;
2410function listenerCount(type) {
2411 var events = this._events;
2412
2413 if (events !== undefined) {
2414 var evlistener = events[type];
2415
2416 if (typeof evlistener === 'function') {
2417 return 1;
2418 } else if (evlistener !== undefined) {
2419 return evlistener.length;
2420 }
2421 }
2422
2423 return 0;
2424}
2425
2426EventEmitter.prototype.eventNames = function eventNames() {
2427 return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
2428};
2429
2430function arrayClone(arr, n) {
2431 var copy = new Array(n);
2432 for (var i = 0; i < n; ++i)
2433 copy[i] = arr[i];
2434 return copy;
2435}
2436
2437function spliceOne(list, index) {
2438 for (; index + 1 < list.length; index++)
2439 list[index] = list[index + 1];
2440 list.pop();
2441}
2442
2443function unwrapListeners(arr) {
2444 var ret = new Array(arr.length);
2445 for (var i = 0; i < ret.length; ++i) {
2446 ret[i] = arr[i].listener || arr[i];
2447 }
2448 return ret;
2449}
2450
2451function once(emitter, name) {
2452 return new Promise(function (resolve, reject) {
2453 function errorListener(err) {
2454 emitter.removeListener(name, resolver);
2455 reject(err);
2456 }
2457
2458 function resolver() {
2459 if (typeof emitter.removeListener === 'function') {
2460 emitter.removeListener('error', errorListener);
2461 }
2462 resolve([].slice.call(arguments));
2463 };
2464
2465 eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
2466 if (name !== 'error') {
2467 addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
2468 }
2469 });
2470}
2471
2472function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
2473 if (typeof emitter.on === 'function') {
2474 eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
2475 }
2476}
2477
2478function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
2479 if (typeof emitter.on === 'function') {
2480 if (flags.once) {
2481 emitter.once(name, listener);
2482 } else {
2483 emitter.on(name, listener);
2484 }
2485 } else if (typeof emitter.addEventListener === 'function') {
2486 // EventTarget does not have `error` event semantics like Node
2487 // EventEmitters, we do not listen for `error` events here.
2488 emitter.addEventListener(name, function wrapListener(arg) {
2489 // IE does not have builtin `{ once: true }` support so we
2490 // have to do it manually.
2491 if (flags.once) {
2492 emitter.removeEventListener(name, wrapListener);
2493 }
2494 listener(arg);
2495 });
2496 } else {
2497 throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
2498 }
2499}
2500
2501},{}],6:[function(require,module,exports){
2502var http = require('http')
2503var url = require('url')
2504
2505var https = module.exports
2506
2507for (var key in http) {
2508 if (http.hasOwnProperty(key)) https[key] = http[key]
2509}
2510
2511https.request = function (params, cb) {
2512 params = validateParams(params)
2513 return http.request.call(this, params, cb)
2514}
2515
2516https.get = function (params, cb) {
2517 params = validateParams(params)
2518 return http.get.call(this, params, cb)
2519}
2520
2521function validateParams (params) {
2522 if (typeof params === 'string') {
2523 params = url.parse(params)
2524 }
2525 if (!params.protocol) {
2526 params.protocol = 'https:'
2527 }
2528 if (params.protocol !== 'https:') {
2529 throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
2530 }
2531 return params
2532}
2533
2534},{"http":18,"url":38}],7:[function(require,module,exports){
2535/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
2536exports.read = function (buffer, offset, isLE, mLen, nBytes) {
2537 var e, m
2538 var eLen = (nBytes * 8) - mLen - 1
2539 var eMax = (1 << eLen) - 1
2540 var eBias = eMax >> 1
2541 var nBits = -7
2542 var i = isLE ? (nBytes - 1) : 0
2543 var d = isLE ? -1 : 1
2544 var s = buffer[offset + i]
2545
2546 i += d
2547
2548 e = s & ((1 << (-nBits)) - 1)
2549 s >>= (-nBits)
2550 nBits += eLen
2551 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
2552
2553 m = e & ((1 << (-nBits)) - 1)
2554 e >>= (-nBits)
2555 nBits += mLen
2556 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
2557
2558 if (e === 0) {
2559 e = 1 - eBias
2560 } else if (e === eMax) {
2561 return m ? NaN : ((s ? -1 : 1) * Infinity)
2562 } else {
2563 m = m + Math.pow(2, mLen)
2564 e = e - eBias
2565 }
2566 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
2567}
2568
2569exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
2570 var e, m, c
2571 var eLen = (nBytes * 8) - mLen - 1
2572 var eMax = (1 << eLen) - 1
2573 var eBias = eMax >> 1
2574 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
2575 var i = isLE ? 0 : (nBytes - 1)
2576 var d = isLE ? 1 : -1
2577 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
2578
2579 value = Math.abs(value)
2580
2581 if (isNaN(value) || value === Infinity) {
2582 m = isNaN(value) ? 1 : 0
2583 e = eMax
2584 } else {
2585 e = Math.floor(Math.log(value) / Math.LN2)
2586 if (value * (c = Math.pow(2, -e)) < 1) {
2587 e--
2588 c *= 2
2589 }
2590 if (e + eBias >= 1) {
2591 value += rt / c
2592 } else {
2593 value += rt * Math.pow(2, 1 - eBias)
2594 }
2595 if (value * c >= 2) {
2596 e++
2597 c /= 2
2598 }
2599
2600 if (e + eBias >= eMax) {
2601 m = 0
2602 e = eMax
2603 } else if (e + eBias >= 1) {
2604 m = ((value * c) - 1) * Math.pow(2, mLen)
2605 e = e + eBias
2606 } else {
2607 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
2608 e = 0
2609 }
2610 }
2611
2612 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2613
2614 e = (e << mLen) | m
2615 eLen += mLen
2616 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2617
2618 buffer[offset + i - d] |= s * 128
2619}
2620
2621},{}],8:[function(require,module,exports){
2622if (typeof Object.create === 'function') {
2623 // implementation from standard node.js 'util' module
2624 module.exports = function inherits(ctor, superCtor) {
2625 if (superCtor) {
2626 ctor.super_ = superCtor
2627 ctor.prototype = Object.create(superCtor.prototype, {
2628 constructor: {
2629 value: ctor,
2630 enumerable: false,
2631 writable: true,
2632 configurable: true
2633 }
2634 })
2635 }
2636 };
2637} else {
2638 // old school shim for old browsers
2639 module.exports = function inherits(ctor, superCtor) {
2640 if (superCtor) {
2641 ctor.super_ = superCtor
2642 var TempCtor = function () {}
2643 TempCtor.prototype = superCtor.prototype
2644 ctor.prototype = new TempCtor()
2645 ctor.prototype.constructor = ctor
2646 }
2647 }
2648}
2649
2650},{}],9:[function(require,module,exports){
2651var wrappy = require('wrappy')
2652module.exports = wrappy(once)
2653module.exports.strict = wrappy(onceStrict)
2654
2655once.proto = once(function () {
2656 Object.defineProperty(Function.prototype, 'once', {
2657 value: function () {
2658 return once(this)
2659 },
2660 configurable: true
2661 })
2662
2663 Object.defineProperty(Function.prototype, 'onceStrict', {
2664 value: function () {
2665 return onceStrict(this)
2666 },
2667 configurable: true
2668 })
2669})
2670
2671function once (fn) {
2672 var f = function () {
2673 if (f.called) return f.value
2674 f.called = true
2675 return f.value = fn.apply(this, arguments)
2676 }
2677 f.called = false
2678 return f
2679}
2680
2681function onceStrict (fn) {
2682 var f = function () {
2683 if (f.called)
2684 throw new Error(f.onceError)
2685 f.called = true
2686 return f.value = fn.apply(this, arguments)
2687 }
2688 var name = fn.name || 'Function wrapped with `once`'
2689 f.onceError = name + " shouldn't be called more than once"
2690 f.called = false
2691 return f
2692}
2693
2694},{"wrappy":41}],10:[function(require,module,exports){
2695// shim for using process in browser
2696var process = module.exports = {};
2697
2698// cached from whatever global is present so that test runners that stub it
2699// don't break things. But we need to wrap it in a try catch in case it is
2700// wrapped in strict mode code which doesn't define any globals. It's inside a
2701// function because try/catches deoptimize in certain engines.
2702
2703var cachedSetTimeout;
2704var cachedClearTimeout;
2705
2706function defaultSetTimout() {
2707 throw new Error('setTimeout has not been defined');
2708}
2709function defaultClearTimeout () {
2710 throw new Error('clearTimeout has not been defined');
2711}
2712(function () {
2713 try {
2714 if (typeof setTimeout === 'function') {
2715 cachedSetTimeout = setTimeout;
2716 } else {
2717 cachedSetTimeout = defaultSetTimout;
2718 }
2719 } catch (e) {
2720 cachedSetTimeout = defaultSetTimout;
2721 }
2722 try {
2723 if (typeof clearTimeout === 'function') {
2724 cachedClearTimeout = clearTimeout;
2725 } else {
2726 cachedClearTimeout = defaultClearTimeout;
2727 }
2728 } catch (e) {
2729 cachedClearTimeout = defaultClearTimeout;
2730 }
2731} ())
2732function runTimeout(fun) {
2733 if (cachedSetTimeout === setTimeout) {
2734 //normal enviroments in sane situations
2735 return setTimeout(fun, 0);
2736 }
2737 // if setTimeout wasn't available but was latter defined
2738 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
2739 cachedSetTimeout = setTimeout;
2740 return setTimeout(fun, 0);
2741 }
2742 try {
2743 // when when somebody has screwed with setTimeout but no I.E. maddness
2744 return cachedSetTimeout(fun, 0);
2745 } catch(e){
2746 try {
2747 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
2748 return cachedSetTimeout.call(null, fun, 0);
2749 } catch(e){
2750 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
2751 return cachedSetTimeout.call(this, fun, 0);
2752 }
2753 }
2754
2755
2756}
2757function runClearTimeout(marker) {
2758 if (cachedClearTimeout === clearTimeout) {
2759 //normal enviroments in sane situations
2760 return clearTimeout(marker);
2761 }
2762 // if clearTimeout wasn't available but was latter defined
2763 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
2764 cachedClearTimeout = clearTimeout;
2765 return clearTimeout(marker);
2766 }
2767 try {
2768 // when when somebody has screwed with setTimeout but no I.E. maddness
2769 return cachedClearTimeout(marker);
2770 } catch (e){
2771 try {
2772 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
2773 return cachedClearTimeout.call(null, marker);
2774 } catch (e){
2775 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
2776 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
2777 return cachedClearTimeout.call(this, marker);
2778 }
2779 }
2780
2781
2782
2783}
2784var queue = [];
2785var draining = false;
2786var currentQueue;
2787var queueIndex = -1;
2788
2789function cleanUpNextTick() {
2790 if (!draining || !currentQueue) {
2791 return;
2792 }
2793 draining = false;
2794 if (currentQueue.length) {
2795 queue = currentQueue.concat(queue);
2796 } else {
2797 queueIndex = -1;
2798 }
2799 if (queue.length) {
2800 drainQueue();
2801 }
2802}
2803
2804function drainQueue() {
2805 if (draining) {
2806 return;
2807 }
2808 var timeout = runTimeout(cleanUpNextTick);
2809 draining = true;
2810
2811 var len = queue.length;
2812 while(len) {
2813 currentQueue = queue;
2814 queue = [];
2815 while (++queueIndex < len) {
2816 if (currentQueue) {
2817 currentQueue[queueIndex].run();
2818 }
2819 }
2820 queueIndex = -1;
2821 len = queue.length;
2822 }
2823 currentQueue = null;
2824 draining = false;
2825 runClearTimeout(timeout);
2826}
2827
2828process.nextTick = function (fun) {
2829 var args = new Array(arguments.length - 1);
2830 if (arguments.length > 1) {
2831 for (var i = 1; i < arguments.length; i++) {
2832 args[i - 1] = arguments[i];
2833 }
2834 }
2835 queue.push(new Item(fun, args));
2836 if (queue.length === 1 && !draining) {
2837 runTimeout(drainQueue);
2838 }
2839};
2840
2841// v8 likes predictible objects
2842function Item(fun, array) {
2843 this.fun = fun;
2844 this.array = array;
2845}
2846Item.prototype.run = function () {
2847 this.fun.apply(null, this.array);
2848};
2849process.title = 'browser';
2850process.browser = true;
2851process.env = {};
2852process.argv = [];
2853process.version = ''; // empty string to avoid regexp issues
2854process.versions = {};
2855
2856function noop() {}
2857
2858process.on = noop;
2859process.addListener = noop;
2860process.once = noop;
2861process.off = noop;
2862process.removeListener = noop;
2863process.removeAllListeners = noop;
2864process.emit = noop;
2865process.prependListener = noop;
2866process.prependOnceListener = noop;
2867
2868process.listeners = function (name) { return [] }
2869
2870process.binding = function (name) {
2871 throw new Error('process.binding is not supported');
2872};
2873
2874process.cwd = function () { return '/' };
2875process.chdir = function (dir) {
2876 throw new Error('process.chdir is not supported');
2877};
2878process.umask = function() { return 0; };
2879
2880},{}],11:[function(require,module,exports){
2881(function (global){(function (){
2882/*! https://mths.be/punycode v1.4.1 by @mathias */
2883;(function(root) {
2884
2885 /** Detect free variables */
2886 var freeExports = typeof exports == 'object' && exports &&
2887 !exports.nodeType && exports;
2888 var freeModule = typeof module == 'object' && module &&
2889 !module.nodeType && module;
2890 var freeGlobal = typeof global == 'object' && global;
2891 if (
2892 freeGlobal.global === freeGlobal ||
2893 freeGlobal.window === freeGlobal ||
2894 freeGlobal.self === freeGlobal
2895 ) {
2896 root = freeGlobal;
2897 }
2898
2899 /**
2900 * The `punycode` object.
2901 * @name punycode
2902 * @type Object
2903 */
2904 var punycode,
2905
2906 /** Highest positive signed 32-bit float value */
2907 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
2908
2909 /** Bootstring parameters */
2910 base = 36,
2911 tMin = 1,
2912 tMax = 26,
2913 skew = 38,
2914 damp = 700,
2915 initialBias = 72,
2916 initialN = 128, // 0x80
2917 delimiter = '-', // '\x2D'
2918
2919 /** Regular expressions */
2920 regexPunycode = /^xn--/,
2921 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
2922 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
2923
2924 /** Error messages */
2925 errors = {
2926 'overflow': 'Overflow: input needs wider integers to process',
2927 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
2928 'invalid-input': 'Invalid input'
2929 },
2930
2931 /** Convenience shortcuts */
2932 baseMinusTMin = base - tMin,
2933 floor = Math.floor,
2934 stringFromCharCode = String.fromCharCode,
2935
2936 /** Temporary variable */
2937 key;
2938
2939 /*--------------------------------------------------------------------------*/
2940
2941 /**
2942 * A generic error utility function.
2943 * @private
2944 * @param {String} type The error type.
2945 * @returns {Error} Throws a `RangeError` with the applicable error message.
2946 */
2947 function error(type) {
2948 throw new RangeError(errors[type]);
2949 }
2950
2951 /**
2952 * A generic `Array#map` utility function.
2953 * @private
2954 * @param {Array} array The array to iterate over.
2955 * @param {Function} callback The function that gets called for every array
2956 * item.
2957 * @returns {Array} A new array of values returned by the callback function.
2958 */
2959 function map(array, fn) {
2960 var length = array.length;
2961 var result = [];
2962 while (length--) {
2963 result[length] = fn(array[length]);
2964 }
2965 return result;
2966 }
2967
2968 /**
2969 * A simple `Array#map`-like wrapper to work with domain name strings or email
2970 * addresses.
2971 * @private
2972 * @param {String} domain The domain name or email address.
2973 * @param {Function} callback The function that gets called for every
2974 * character.
2975 * @returns {Array} A new string of characters returned by the callback
2976 * function.
2977 */
2978 function mapDomain(string, fn) {
2979 var parts = string.split('@');
2980 var result = '';
2981 if (parts.length > 1) {
2982 // In email addresses, only the domain name should be punycoded. Leave
2983 // the local part (i.e. everything up to `@`) intact.
2984 result = parts[0] + '@';
2985 string = parts[1];
2986 }
2987 // Avoid `split(regex)` for IE8 compatibility. See #17.
2988 string = string.replace(regexSeparators, '\x2E');
2989 var labels = string.split('.');
2990 var encoded = map(labels, fn).join('.');
2991 return result + encoded;
2992 }
2993
2994 /**
2995 * Creates an array containing the numeric code points of each Unicode
2996 * character in the string. While JavaScript uses UCS-2 internally,
2997 * this function will convert a pair of surrogate halves (each of which
2998 * UCS-2 exposes as separate characters) into a single code point,
2999 * matching UTF-16.
3000 * @see `punycode.ucs2.encode`
3001 * @see <https://mathiasbynens.be/notes/javascript-encoding>
3002 * @memberOf punycode.ucs2
3003 * @name decode
3004 * @param {String} string The Unicode input string (UCS-2).
3005 * @returns {Array} The new array of code points.
3006 */
3007 function ucs2decode(string) {
3008 var output = [],
3009 counter = 0,
3010 length = string.length,
3011 value,
3012 extra;
3013 while (counter < length) {
3014 value = string.charCodeAt(counter++);
3015 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
3016 // high surrogate, and there is a next character
3017 extra = string.charCodeAt(counter++);
3018 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
3019 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
3020 } else {
3021 // unmatched surrogate; only append this code unit, in case the next
3022 // code unit is the high surrogate of a surrogate pair
3023 output.push(value);
3024 counter--;
3025 }
3026 } else {
3027 output.push(value);
3028 }
3029 }
3030 return output;
3031 }
3032
3033 /**
3034 * Creates a string based on an array of numeric code points.
3035 * @see `punycode.ucs2.decode`
3036 * @memberOf punycode.ucs2
3037 * @name encode
3038 * @param {Array} codePoints The array of numeric code points.
3039 * @returns {String} The new Unicode string (UCS-2).
3040 */
3041 function ucs2encode(array) {
3042 return map(array, function(value) {
3043 var output = '';
3044 if (value > 0xFFFF) {
3045 value -= 0x10000;
3046 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
3047 value = 0xDC00 | value & 0x3FF;
3048 }
3049 output += stringFromCharCode(value);
3050 return output;
3051 }).join('');
3052 }
3053
3054 /**
3055 * Converts a basic code point into a digit/integer.
3056 * @see `digitToBasic()`
3057 * @private
3058 * @param {Number} codePoint The basic numeric code point value.
3059 * @returns {Number} The numeric value of a basic code point (for use in
3060 * representing integers) in the range `0` to `base - 1`, or `base` if
3061 * the code point does not represent a value.
3062 */
3063 function basicToDigit(codePoint) {
3064 if (codePoint - 48 < 10) {
3065 return codePoint - 22;
3066 }
3067 if (codePoint - 65 < 26) {
3068 return codePoint - 65;
3069 }
3070 if (codePoint - 97 < 26) {
3071 return codePoint - 97;
3072 }
3073 return base;
3074 }
3075
3076 /**
3077 * Converts a digit/integer into a basic code point.
3078 * @see `basicToDigit()`
3079 * @private
3080 * @param {Number} digit The numeric value of a basic code point.
3081 * @returns {Number} The basic code point whose value (when used for
3082 * representing integers) is `digit`, which needs to be in the range
3083 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
3084 * used; else, the lowercase form is used. The behavior is undefined
3085 * if `flag` is non-zero and `digit` has no uppercase form.
3086 */
3087 function digitToBasic(digit, flag) {
3088 // 0..25 map to ASCII a..z or A..Z
3089 // 26..35 map to ASCII 0..9
3090 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
3091 }
3092
3093 /**
3094 * Bias adaptation function as per section 3.4 of RFC 3492.
3095 * https://tools.ietf.org/html/rfc3492#section-3.4
3096 * @private
3097 */
3098 function adapt(delta, numPoints, firstTime) {
3099 var k = 0;
3100 delta = firstTime ? floor(delta / damp) : delta >> 1;
3101 delta += floor(delta / numPoints);
3102 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
3103 delta = floor(delta / baseMinusTMin);
3104 }
3105 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
3106 }
3107
3108 /**
3109 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
3110 * symbols.
3111 * @memberOf punycode
3112 * @param {String} input The Punycode string of ASCII-only symbols.
3113 * @returns {String} The resulting string of Unicode symbols.
3114 */
3115 function decode(input) {
3116 // Don't use UCS-2
3117 var output = [],
3118 inputLength = input.length,
3119 out,
3120 i = 0,
3121 n = initialN,
3122 bias = initialBias,
3123 basic,
3124 j,
3125 index,
3126 oldi,
3127 w,
3128 k,
3129 digit,
3130 t,
3131 /** Cached calculation results */
3132 baseMinusT;
3133
3134 // Handle the basic code points: let `basic` be the number of input code
3135 // points before the last delimiter, or `0` if there is none, then copy
3136 // the first basic code points to the output.
3137
3138 basic = input.lastIndexOf(delimiter);
3139 if (basic < 0) {
3140 basic = 0;
3141 }
3142
3143 for (j = 0; j < basic; ++j) {
3144 // if it's not a basic code point
3145 if (input.charCodeAt(j) >= 0x80) {
3146 error('not-basic');
3147 }
3148 output.push(input.charCodeAt(j));
3149 }
3150
3151 // Main decoding loop: start just after the last delimiter if any basic code
3152 // points were copied; start at the beginning otherwise.
3153
3154 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
3155
3156 // `index` is the index of the next character to be consumed.
3157 // Decode a generalized variable-length integer into `delta`,
3158 // which gets added to `i`. The overflow checking is easier
3159 // if we increase `i` as we go, then subtract off its starting
3160 // value at the end to obtain `delta`.
3161 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
3162
3163 if (index >= inputLength) {
3164 error('invalid-input');
3165 }
3166
3167 digit = basicToDigit(input.charCodeAt(index++));
3168
3169 if (digit >= base || digit > floor((maxInt - i) / w)) {
3170 error('overflow');
3171 }
3172
3173 i += digit * w;
3174 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
3175
3176 if (digit < t) {
3177 break;
3178 }
3179
3180 baseMinusT = base - t;
3181 if (w > floor(maxInt / baseMinusT)) {
3182 error('overflow');
3183 }
3184
3185 w *= baseMinusT;
3186
3187 }
3188
3189 out = output.length + 1;
3190 bias = adapt(i - oldi, out, oldi == 0);
3191
3192 // `i` was supposed to wrap around from `out` to `0`,
3193 // incrementing `n` each time, so we'll fix that now:
3194 if (floor(i / out) > maxInt - n) {
3195 error('overflow');
3196 }
3197
3198 n += floor(i / out);
3199 i %= out;
3200
3201 // Insert `n` at position `i` of the output
3202 output.splice(i++, 0, n);
3203
3204 }
3205
3206 return ucs2encode(output);
3207 }
3208
3209 /**
3210 * Converts a string of Unicode symbols (e.g. a domain name label) to a
3211 * Punycode string of ASCII-only symbols.
3212 * @memberOf punycode
3213 * @param {String} input The string of Unicode symbols.
3214 * @returns {String} The resulting Punycode string of ASCII-only symbols.
3215 */
3216 function encode(input) {
3217 var n,
3218 delta,
3219 handledCPCount,
3220 basicLength,
3221 bias,
3222 j,
3223 m,
3224 q,
3225 k,
3226 t,
3227 currentValue,
3228 output = [],
3229 /** `inputLength` will hold the number of code points in `input`. */
3230 inputLength,
3231 /** Cached calculation results */
3232 handledCPCountPlusOne,
3233 baseMinusT,
3234 qMinusT;
3235
3236 // Convert the input in UCS-2 to Unicode
3237 input = ucs2decode(input);
3238
3239 // Cache the length
3240 inputLength = input.length;
3241
3242 // Initialize the state
3243 n = initialN;
3244 delta = 0;
3245 bias = initialBias;
3246
3247 // Handle the basic code points
3248 for (j = 0; j < inputLength; ++j) {
3249 currentValue = input[j];
3250 if (currentValue < 0x80) {
3251 output.push(stringFromCharCode(currentValue));
3252 }
3253 }
3254
3255 handledCPCount = basicLength = output.length;
3256
3257 // `handledCPCount` is the number of code points that have been handled;
3258 // `basicLength` is the number of basic code points.
3259
3260 // Finish the basic string - if it is not empty - with a delimiter
3261 if (basicLength) {
3262 output.push(delimiter);
3263 }
3264
3265 // Main encoding loop:
3266 while (handledCPCount < inputLength) {
3267
3268 // All non-basic code points < n have been handled already. Find the next
3269 // larger one:
3270 for (m = maxInt, j = 0; j < inputLength; ++j) {
3271 currentValue = input[j];
3272 if (currentValue >= n && currentValue < m) {
3273 m = currentValue;
3274 }
3275 }
3276
3277 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
3278 // but guard against overflow
3279 handledCPCountPlusOne = handledCPCount + 1;
3280 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
3281 error('overflow');
3282 }
3283
3284 delta += (m - n) * handledCPCountPlusOne;
3285 n = m;
3286
3287 for (j = 0; j < inputLength; ++j) {
3288 currentValue = input[j];
3289
3290 if (currentValue < n && ++delta > maxInt) {
3291 error('overflow');
3292 }
3293
3294 if (currentValue == n) {
3295 // Represent delta as a generalized variable-length integer
3296 for (q = delta, k = base; /* no condition */; k += base) {
3297 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
3298 if (q < t) {
3299 break;
3300 }
3301 qMinusT = q - t;
3302 baseMinusT = base - t;
3303 output.push(
3304 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
3305 );
3306 q = floor(qMinusT / baseMinusT);
3307 }
3308
3309 output.push(stringFromCharCode(digitToBasic(q, 0)));
3310 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
3311 delta = 0;
3312 ++handledCPCount;
3313 }
3314 }
3315
3316 ++delta;
3317 ++n;
3318
3319 }
3320 return output.join('');
3321 }
3322
3323 /**
3324 * Converts a Punycode string representing a domain name or an email address
3325 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
3326 * it doesn't matter if you call it on a string that has already been
3327 * converted to Unicode.
3328 * @memberOf punycode
3329 * @param {String} input The Punycoded domain name or email address to
3330 * convert to Unicode.
3331 * @returns {String} The Unicode representation of the given Punycode
3332 * string.
3333 */
3334 function toUnicode(input) {
3335 return mapDomain(input, function(string) {
3336 return regexPunycode.test(string)
3337 ? decode(string.slice(4).toLowerCase())
3338 : string;
3339 });
3340 }
3341
3342 /**
3343 * Converts a Unicode string representing a domain name or an email address to
3344 * Punycode. Only the non-ASCII parts of the domain name will be converted,
3345 * i.e. it doesn't matter if you call it with a domain that's already in
3346 * ASCII.
3347 * @memberOf punycode
3348 * @param {String} input The domain name or email address to convert, as a
3349 * Unicode string.
3350 * @returns {String} The Punycode representation of the given domain name or
3351 * email address.
3352 */
3353 function toASCII(input) {
3354 return mapDomain(input, function(string) {
3355 return regexNonASCII.test(string)
3356 ? 'xn--' + encode(string)
3357 : string;
3358 });
3359 }
3360
3361 /*--------------------------------------------------------------------------*/
3362
3363 /** Define the public API */
3364 punycode = {
3365 /**
3366 * A string representing the current Punycode.js version number.
3367 * @memberOf punycode
3368 * @type String
3369 */
3370 'version': '1.4.1',
3371 /**
3372 * An object of methods to convert from JavaScript's internal character
3373 * representation (UCS-2) to Unicode code points, and back.
3374 * @see <https://mathiasbynens.be/notes/javascript-encoding>
3375 * @memberOf punycode
3376 * @type Object
3377 */
3378 'ucs2': {
3379 'decode': ucs2decode,
3380 'encode': ucs2encode
3381 },
3382 'decode': decode,
3383 'encode': encode,
3384 'toASCII': toASCII,
3385 'toUnicode': toUnicode
3386 };
3387
3388 /** Expose `punycode` */
3389 // Some AMD build optimizers, like r.js, check for specific condition patterns
3390 // like the following:
3391 if (
3392 typeof define == 'function' &&
3393 typeof define.amd == 'object' &&
3394 define.amd
3395 ) {
3396 define('punycode', function() {
3397 return punycode;
3398 });
3399 } else if (freeExports && freeModule) {
3400 if (module.exports == freeExports) {
3401 // in Node.js, io.js, or RingoJS v0.8.0+
3402 freeModule.exports = punycode;
3403 } else {
3404 // in Narwhal or RingoJS v0.7.0-
3405 for (key in punycode) {
3406 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
3407 }
3408 }
3409 } else {
3410 // in Rhino or a web browser
3411 root.punycode = punycode;
3412 }
3413
3414}(this));
3415
3416}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3417},{}],12:[function(require,module,exports){
3418// Copyright Joyent, Inc. and other Node contributors.
3419//
3420// Permission is hereby granted, free of charge, to any person obtaining a
3421// copy of this software and associated documentation files (the
3422// "Software"), to deal in the Software without restriction, including
3423// without limitation the rights to use, copy, modify, merge, publish,
3424// distribute, sublicense, and/or sell copies of the Software, and to permit
3425// persons to whom the Software is furnished to do so, subject to the
3426// following conditions:
3427//
3428// The above copyright notice and this permission notice shall be included
3429// in all copies or substantial portions of the Software.
3430//
3431// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3432// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3433// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3434// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3435// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3436// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3437// USE OR OTHER DEALINGS IN THE SOFTWARE.
3438
3439'use strict';
3440
3441// If obj.hasOwnProperty has been overridden, then calling
3442// obj.hasOwnProperty(prop) will break.
3443// See: https://github.com/joyent/node/issues/1707
3444function hasOwnProperty(obj, prop) {
3445 return Object.prototype.hasOwnProperty.call(obj, prop);
3446}
3447
3448module.exports = function(qs, sep, eq, options) {
3449 sep = sep || '&';
3450 eq = eq || '=';
3451 var obj = {};
3452
3453 if (typeof qs !== 'string' || qs.length === 0) {
3454 return obj;
3455 }
3456
3457 var regexp = /\+/g;
3458 qs = qs.split(sep);
3459
3460 var maxKeys = 1000;
3461 if (options && typeof options.maxKeys === 'number') {
3462 maxKeys = options.maxKeys;
3463 }
3464
3465 var len = qs.length;
3466 // maxKeys <= 0 means that we should not limit keys count
3467 if (maxKeys > 0 && len > maxKeys) {
3468 len = maxKeys;
3469 }
3470
3471 for (var i = 0; i < len; ++i) {
3472 var x = qs[i].replace(regexp, '%20'),
3473 idx = x.indexOf(eq),
3474 kstr, vstr, k, v;
3475
3476 if (idx >= 0) {
3477 kstr = x.substr(0, idx);
3478 vstr = x.substr(idx + 1);
3479 } else {
3480 kstr = x;
3481 vstr = '';
3482 }
3483
3484 k = decodeURIComponent(kstr);
3485 v = decodeURIComponent(vstr);
3486
3487 if (!hasOwnProperty(obj, k)) {
3488 obj[k] = v;
3489 } else if (isArray(obj[k])) {
3490 obj[k].push(v);
3491 } else {
3492 obj[k] = [obj[k], v];
3493 }
3494 }
3495
3496 return obj;
3497};
3498
3499var isArray = Array.isArray || function (xs) {
3500 return Object.prototype.toString.call(xs) === '[object Array]';
3501};
3502
3503},{}],13:[function(require,module,exports){
3504// Copyright Joyent, Inc. and other Node contributors.
3505//
3506// Permission is hereby granted, free of charge, to any person obtaining a
3507// copy of this software and associated documentation files (the
3508// "Software"), to deal in the Software without restriction, including
3509// without limitation the rights to use, copy, modify, merge, publish,
3510// distribute, sublicense, and/or sell copies of the Software, and to permit
3511// persons to whom the Software is furnished to do so, subject to the
3512// following conditions:
3513//
3514// The above copyright notice and this permission notice shall be included
3515// in all copies or substantial portions of the Software.
3516//
3517// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3518// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3519// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3520// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3521// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3522// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3523// USE OR OTHER DEALINGS IN THE SOFTWARE.
3524
3525'use strict';
3526
3527var stringifyPrimitive = function(v) {
3528 switch (typeof v) {
3529 case 'string':
3530 return v;
3531
3532 case 'boolean':
3533 return v ? 'true' : 'false';
3534
3535 case 'number':
3536 return isFinite(v) ? v : '';
3537
3538 default:
3539 return '';
3540 }
3541};
3542
3543module.exports = function(obj, sep, eq, name) {
3544 sep = sep || '&';
3545 eq = eq || '=';
3546 if (obj === null) {
3547 obj = undefined;
3548 }
3549
3550 if (typeof obj === 'object') {
3551 return map(objectKeys(obj), function(k) {
3552 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
3553 if (isArray(obj[k])) {
3554 return map(obj[k], function(v) {
3555 return ks + encodeURIComponent(stringifyPrimitive(v));
3556 }).join(sep);
3557 } else {
3558 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
3559 }
3560 }).join(sep);
3561
3562 }
3563
3564 if (!name) return '';
3565 return encodeURIComponent(stringifyPrimitive(name)) + eq +
3566 encodeURIComponent(stringifyPrimitive(obj));
3567};
3568
3569var isArray = Array.isArray || function (xs) {
3570 return Object.prototype.toString.call(xs) === '[object Array]';
3571};
3572
3573function map (xs, f) {
3574 if (xs.map) return xs.map(f);
3575 var res = [];
3576 for (var i = 0; i < xs.length; i++) {
3577 res.push(f(xs[i], i));
3578 }
3579 return res;
3580}
3581
3582var objectKeys = Object.keys || function (obj) {
3583 var res = [];
3584 for (var key in obj) {
3585 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
3586 }
3587 return res;
3588};
3589
3590},{}],14:[function(require,module,exports){
3591'use strict';
3592
3593exports.decode = exports.parse = require('./decode');
3594exports.encode = exports.stringify = require('./encode');
3595
3596},{"./decode":12,"./encode":13}],15:[function(require,module,exports){
3597/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
3598/* eslint-disable node/no-deprecated-api */
3599var buffer = require('buffer')
3600var Buffer = buffer.Buffer
3601
3602// alternative to using Object.keys for old browsers
3603function copyProps (src, dst) {
3604 for (var key in src) {
3605 dst[key] = src[key]
3606 }
3607}
3608if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
3609 module.exports = buffer
3610} else {
3611 // Copy properties from require('buffer')
3612 copyProps(buffer, exports)
3613 exports.Buffer = SafeBuffer
3614}
3615
3616function SafeBuffer (arg, encodingOrOffset, length) {
3617 return Buffer(arg, encodingOrOffset, length)
3618}
3619
3620SafeBuffer.prototype = Object.create(Buffer.prototype)
3621
3622// Copy static methods from Buffer
3623copyProps(Buffer, SafeBuffer)
3624
3625SafeBuffer.from = function (arg, encodingOrOffset, length) {
3626 if (typeof arg === 'number') {
3627 throw new TypeError('Argument must not be a number')
3628 }
3629 return Buffer(arg, encodingOrOffset, length)
3630}
3631
3632SafeBuffer.alloc = function (size, fill, encoding) {
3633 if (typeof size !== 'number') {
3634 throw new TypeError('Argument must be a number')
3635 }
3636 var buf = Buffer(size)
3637 if (fill !== undefined) {
3638 if (typeof encoding === 'string') {
3639 buf.fill(fill, encoding)
3640 } else {
3641 buf.fill(fill)
3642 }
3643 } else {
3644 buf.fill(0)
3645 }
3646 return buf
3647}
3648
3649SafeBuffer.allocUnsafe = function (size) {
3650 if (typeof size !== 'number') {
3651 throw new TypeError('Argument must be a number')
3652 }
3653 return Buffer(size)
3654}
3655
3656SafeBuffer.allocUnsafeSlow = function (size) {
3657 if (typeof size !== 'number') {
3658 throw new TypeError('Argument must be a number')
3659 }
3660 return buffer.SlowBuffer(size)
3661}
3662
3663},{"buffer":3}],16:[function(require,module,exports){
3664(function (Buffer){(function (){
3665/*! simple-concat. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
3666module.exports = function (stream, cb) {
3667 var chunks = []
3668 stream.on('data', function (chunk) {
3669 chunks.push(chunk)
3670 })
3671 stream.once('end', function () {
3672 if (cb) cb(null, Buffer.concat(chunks))
3673 cb = null
3674 })
3675 stream.once('error', function (err) {
3676 if (cb) cb(err)
3677 cb = null
3678 })
3679}
3680
3681}).call(this)}).call(this,require("buffer").Buffer)
3682},{"buffer":3}],17:[function(require,module,exports){
3683(function (Buffer){(function (){
3684/*! simple-get. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
3685module.exports = simpleGet
3686
3687const concat = require('simple-concat')
3688const decompressResponse = require('decompress-response') // excluded from browser build
3689const http = require('http')
3690const https = require('https')
3691const once = require('once')
3692const querystring = require('querystring')
3693const url = require('url')
3694
3695const isStream = o => o !== null && typeof o === 'object' && typeof o.pipe === 'function'
3696
3697function simpleGet (opts, cb) {
3698 opts = Object.assign({ maxRedirects: 10 }, typeof opts === 'string' ? { url: opts } : opts)
3699 cb = once(cb)
3700
3701 if (opts.url) {
3702 const { hostname, port, protocol, auth, path } = url.parse(opts.url) // eslint-disable-line node/no-deprecated-api
3703 delete opts.url
3704 if (!hostname && !port && !protocol && !auth) opts.path = path // Relative redirect
3705 else Object.assign(opts, { hostname, port, protocol, auth, path }) // Absolute redirect
3706 }
3707
3708 const headers = { 'accept-encoding': 'gzip, deflate' }
3709 if (opts.headers) Object.keys(opts.headers).forEach(k => (headers[k.toLowerCase()] = opts.headers[k]))
3710 opts.headers = headers
3711
3712 let body
3713 if (opts.body) {
3714 body = opts.json && !isStream(opts.body) ? JSON.stringify(opts.body) : opts.body
3715 } else if (opts.form) {
3716 body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form)
3717 opts.headers['content-type'] = 'application/x-www-form-urlencoded'
3718 }
3719
3720 if (body) {
3721 if (!opts.method) opts.method = 'POST'
3722 if (!isStream(body)) opts.headers['content-length'] = Buffer.byteLength(body)
3723 if (opts.json && !opts.form) opts.headers['content-type'] = 'application/json'
3724 }
3725 delete opts.body; delete opts.form
3726
3727 if (opts.json) opts.headers.accept = 'application/json'
3728 if (opts.method) opts.method = opts.method.toUpperCase()
3729
3730 const protocol = opts.protocol === 'https:' ? https : http // Support http/https urls
3731 const req = protocol.request(opts, res => {
3732 if (opts.followRedirects !== false && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
3733 opts.url = res.headers.location // Follow 3xx redirects
3734 delete opts.headers.host // Discard `host` header on redirect (see #32)
3735 res.resume() // Discard response
3736
3737 if (opts.method === 'POST' && [301, 302].includes(res.statusCode)) {
3738 opts.method = 'GET' // On 301/302 redirect, change POST to GET (see #35)
3739 delete opts.headers['content-length']; delete opts.headers['content-type']
3740 }
3741
3742 if (opts.maxRedirects-- === 0) return cb(new Error('too many redirects'))
3743 else return simpleGet(opts, cb)
3744 }
3745
3746 const tryUnzip = typeof decompressResponse === 'function' && opts.method !== 'HEAD'
3747 cb(null, tryUnzip ? decompressResponse(res) : res)
3748 })
3749 req.on('timeout', () => {
3750 req.abort()
3751 cb(new Error('Request timed out'))
3752 })
3753 req.on('error', cb)
3754
3755 if (isStream(body)) body.on('error', cb).pipe(req)
3756 else req.end(body)
3757
3758 return req
3759}
3760
3761simpleGet.concat = (opts, cb) => {
3762 return simpleGet(opts, (err, res) => {
3763 if (err) return cb(err)
3764 concat(res, (err, data) => {
3765 if (err) return cb(err)
3766 if (opts.json) {
3767 try {
3768 data = JSON.parse(data.toString())
3769 } catch (err) {
3770 return cb(err, res, data)
3771 }
3772 }
3773 cb(null, res, data)
3774 })
3775 })
3776}
3777
3778;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(method => {
3779 simpleGet[method] = (opts, cb) => {
3780 if (typeof opts === 'string') opts = { url: opts }
3781 return simpleGet(Object.assign({ method: method.toUpperCase() }, opts), cb)
3782 }
3783})
3784
3785}).call(this)}).call(this,require("buffer").Buffer)
3786},{"buffer":3,"decompress-response":2,"http":18,"https":6,"once":9,"querystring":14,"simple-concat":16,"url":38}],18:[function(require,module,exports){
3787(function (global){(function (){
3788var ClientRequest = require('./lib/request')
3789var response = require('./lib/response')
3790var extend = require('xtend')
3791var statusCodes = require('builtin-status-codes')
3792var url = require('url')
3793
3794var http = exports
3795
3796http.request = function (opts, cb) {
3797 if (typeof opts === 'string')
3798 opts = url.parse(opts)
3799 else
3800 opts = extend(opts)
3801
3802 // Normally, the page is loaded from http or https, so not specifying a protocol
3803 // will result in a (valid) protocol-relative url. However, this won't work if
3804 // the protocol is something else, like 'file:'
3805 var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
3806
3807 var protocol = opts.protocol || defaultProtocol
3808 var host = opts.hostname || opts.host
3809 var port = opts.port
3810 var path = opts.path || '/'
3811
3812 // Necessary for IPv6 addresses
3813 if (host && host.indexOf(':') !== -1)
3814 host = '[' + host + ']'
3815
3816 // This may be a relative url. The browser should always be able to interpret it correctly.
3817 opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
3818 opts.method = (opts.method || 'GET').toUpperCase()
3819 opts.headers = opts.headers || {}
3820
3821 // Also valid opts.auth, opts.mode
3822
3823 var req = new ClientRequest(opts)
3824 if (cb)
3825 req.on('response', cb)
3826 return req
3827}
3828
3829http.get = function get (opts, cb) {
3830 var req = http.request(opts, cb)
3831 req.end()
3832 return req
3833}
3834
3835http.ClientRequest = ClientRequest
3836http.IncomingMessage = response.IncomingMessage
3837
3838http.Agent = function () {}
3839http.Agent.defaultMaxSockets = 4
3840
3841http.globalAgent = new http.Agent()
3842
3843http.STATUS_CODES = statusCodes
3844
3845http.METHODS = [
3846 'CHECKOUT',
3847 'CONNECT',
3848 'COPY',
3849 'DELETE',
3850 'GET',
3851 'HEAD',
3852 'LOCK',
3853 'M-SEARCH',
3854 'MERGE',
3855 'MKACTIVITY',
3856 'MKCOL',
3857 'MOVE',
3858 'NOTIFY',
3859 'OPTIONS',
3860 'PATCH',
3861 'POST',
3862 'PROPFIND',
3863 'PROPPATCH',
3864 'PURGE',
3865 'PUT',
3866 'REPORT',
3867 'SEARCH',
3868 'SUBSCRIBE',
3869 'TRACE',
3870 'UNLOCK',
3871 'UNSUBSCRIBE'
3872]
3873}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3874},{"./lib/request":20,"./lib/response":21,"builtin-status-codes":4,"url":38,"xtend":42}],19:[function(require,module,exports){
3875(function (global){(function (){
3876exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
3877
3878exports.writableStream = isFunction(global.WritableStream)
3879
3880exports.abortController = isFunction(global.AbortController)
3881
3882// The xhr request to example.com may violate some restrictive CSP configurations,
3883// so if we're running in a browser that supports `fetch`, avoid calling getXHR()
3884// and assume support for certain features below.
3885var xhr
3886function getXHR () {
3887 // Cache the xhr value
3888 if (xhr !== undefined) return xhr
3889
3890 if (global.XMLHttpRequest) {
3891 xhr = new global.XMLHttpRequest()
3892 // If XDomainRequest is available (ie only, where xhr might not work
3893 // cross domain), use the page location. Otherwise use example.com
3894 // Note: this doesn't actually make an http request.
3895 try {
3896 xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
3897 } catch(e) {
3898 xhr = null
3899 }
3900 } else {
3901 // Service workers don't have XHR
3902 xhr = null
3903 }
3904 return xhr
3905}
3906
3907function checkTypeSupport (type) {
3908 var xhr = getXHR()
3909 if (!xhr) return false
3910 try {
3911 xhr.responseType = type
3912 return xhr.responseType === type
3913 } catch (e) {}
3914 return false
3915}
3916
3917// If fetch is supported, then arraybuffer will be supported too. Skip calling
3918// checkTypeSupport(), since that calls getXHR().
3919exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer')
3920
3921// These next two tests unavoidably show warnings in Chrome. Since fetch will always
3922// be used if it's available, just return false for these to avoid the warnings.
3923exports.msstream = !exports.fetch && checkTypeSupport('ms-stream')
3924exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer')
3925
3926// If fetch is supported, then overrideMimeType will be supported too. Skip calling
3927// getXHR().
3928exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
3929
3930function isFunction (value) {
3931 return typeof value === 'function'
3932}
3933
3934xhr = null // Help gc
3935
3936}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3937},{}],20:[function(require,module,exports){
3938(function (process,global,Buffer){(function (){
3939var capability = require('./capability')
3940var inherits = require('inherits')
3941var response = require('./response')
3942var stream = require('readable-stream')
3943
3944var IncomingMessage = response.IncomingMessage
3945var rStates = response.readyStates
3946
3947function decideMode (preferBinary, useFetch) {
3948 if (capability.fetch && useFetch) {
3949 return 'fetch'
3950 } else if (capability.mozchunkedarraybuffer) {
3951 return 'moz-chunked-arraybuffer'
3952 } else if (capability.msstream) {
3953 return 'ms-stream'
3954 } else if (capability.arraybuffer && preferBinary) {
3955 return 'arraybuffer'
3956 } else {
3957 return 'text'
3958 }
3959}
3960
3961var ClientRequest = module.exports = function (opts) {
3962 var self = this
3963 stream.Writable.call(self)
3964
3965 self._opts = opts
3966 self._body = []
3967 self._headers = {}
3968 if (opts.auth)
3969 self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64'))
3970 Object.keys(opts.headers).forEach(function (name) {
3971 self.setHeader(name, opts.headers[name])
3972 })
3973
3974 var preferBinary
3975 var useFetch = true
3976 if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
3977 // If the use of XHR should be preferred. Not typically needed.
3978 useFetch = false
3979 preferBinary = true
3980 } else if (opts.mode === 'prefer-streaming') {
3981 // If streaming is a high priority but binary compatibility and
3982 // the accuracy of the 'content-type' header aren't
3983 preferBinary = false
3984 } else if (opts.mode === 'allow-wrong-content-type') {
3985 // If streaming is more important than preserving the 'content-type' header
3986 preferBinary = !capability.overrideMimeType
3987 } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
3988 // Use binary if text streaming may corrupt data or the content-type header, or for speed
3989 preferBinary = true
3990 } else {
3991 throw new Error('Invalid value for opts.mode')
3992 }
3993 self._mode = decideMode(preferBinary, useFetch)
3994 self._fetchTimer = null
3995 self._socketTimeout = null
3996 self._socketTimer = null
3997
3998 self.on('finish', function () {
3999 self._onFinish()
4000 })
4001}
4002
4003inherits(ClientRequest, stream.Writable)
4004
4005ClientRequest.prototype.setHeader = function (name, value) {
4006 var self = this
4007 var lowerName = name.toLowerCase()
4008 // This check is not necessary, but it prevents warnings from browsers about setting unsafe
4009 // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
4010 // http-browserify did it, so I will too.
4011 if (unsafeHeaders.indexOf(lowerName) !== -1)
4012 return
4013
4014 self._headers[lowerName] = {
4015 name: name,
4016 value: value
4017 }
4018}
4019
4020ClientRequest.prototype.getHeader = function (name) {
4021 var header = this._headers[name.toLowerCase()]
4022 if (header)
4023 return header.value
4024 return null
4025}
4026
4027ClientRequest.prototype.removeHeader = function (name) {
4028 var self = this
4029 delete self._headers[name.toLowerCase()]
4030}
4031
4032ClientRequest.prototype._onFinish = function () {
4033 var self = this
4034
4035 if (self._destroyed)
4036 return
4037 var opts = self._opts
4038
4039 if ('timeout' in opts && opts.timeout !== 0) {
4040 self.setTimeout(opts.timeout)
4041 }
4042
4043 var headersObj = self._headers
4044 var body = null
4045 if (opts.method !== 'GET' && opts.method !== 'HEAD') {
4046 body = new Blob(self._body, {
4047 type: (headersObj['content-type'] || {}).value || ''
4048 });
4049 }
4050
4051 // create flattened list of headers
4052 var headersList = []
4053 Object.keys(headersObj).forEach(function (keyName) {
4054 var name = headersObj[keyName].name
4055 var value = headersObj[keyName].value
4056 if (Array.isArray(value)) {
4057 value.forEach(function (v) {
4058 headersList.push([name, v])
4059 })
4060 } else {
4061 headersList.push([name, value])
4062 }
4063 })
4064
4065 if (self._mode === 'fetch') {
4066 var signal = null
4067 if (capability.abortController) {
4068 var controller = new AbortController()
4069 signal = controller.signal
4070 self._fetchAbortController = controller
4071
4072 if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
4073 self._fetchTimer = global.setTimeout(function () {
4074 self.emit('requestTimeout')
4075 if (self._fetchAbortController)
4076 self._fetchAbortController.abort()
4077 }, opts.requestTimeout)
4078 }
4079 }
4080
4081 global.fetch(self._opts.url, {
4082 method: self._opts.method,
4083 headers: headersList,
4084 body: body || undefined,
4085 mode: 'cors',
4086 credentials: opts.withCredentials ? 'include' : 'same-origin',
4087 signal: signal
4088 }).then(function (response) {
4089 self._fetchResponse = response
4090 self._resetTimers(false)
4091 self._connect()
4092 }, function (reason) {
4093 self._resetTimers(true)
4094 if (!self._destroyed)
4095 self.emit('error', reason)
4096 })
4097 } else {
4098 var xhr = self._xhr = new global.XMLHttpRequest()
4099 try {
4100 xhr.open(self._opts.method, self._opts.url, true)
4101 } catch (err) {
4102 process.nextTick(function () {
4103 self.emit('error', err)
4104 })
4105 return
4106 }
4107
4108 // Can't set responseType on really old browsers
4109 if ('responseType' in xhr)
4110 xhr.responseType = self._mode
4111
4112 if ('withCredentials' in xhr)
4113 xhr.withCredentials = !!opts.withCredentials
4114
4115 if (self._mode === 'text' && 'overrideMimeType' in xhr)
4116 xhr.overrideMimeType('text/plain; charset=x-user-defined')
4117
4118 if ('requestTimeout' in opts) {
4119 xhr.timeout = opts.requestTimeout
4120 xhr.ontimeout = function () {
4121 self.emit('requestTimeout')
4122 }
4123 }
4124
4125 headersList.forEach(function (header) {
4126 xhr.setRequestHeader(header[0], header[1])
4127 })
4128
4129 self._response = null
4130 xhr.onreadystatechange = function () {
4131 switch (xhr.readyState) {
4132 case rStates.LOADING:
4133 case rStates.DONE:
4134 self._onXHRProgress()
4135 break
4136 }
4137 }
4138 // Necessary for streaming in Firefox, since xhr.response is ONLY defined
4139 // in onprogress, not in onreadystatechange with xhr.readyState = 3
4140 if (self._mode === 'moz-chunked-arraybuffer') {
4141 xhr.onprogress = function () {
4142 self._onXHRProgress()
4143 }
4144 }
4145
4146 xhr.onerror = function () {
4147 if (self._destroyed)
4148 return
4149 self._resetTimers(true)
4150 self.emit('error', new Error('XHR error'))
4151 }
4152
4153 try {
4154 xhr.send(body)
4155 } catch (err) {
4156 process.nextTick(function () {
4157 self.emit('error', err)
4158 })
4159 return
4160 }
4161 }
4162}
4163
4164/**
4165 * Checks if xhr.status is readable and non-zero, indicating no error.
4166 * Even though the spec says it should be available in readyState 3,
4167 * accessing it throws an exception in IE8
4168 */
4169function statusValid (xhr) {
4170 try {
4171 var status = xhr.status
4172 return (status !== null && status !== 0)
4173 } catch (e) {
4174 return false
4175 }
4176}
4177
4178ClientRequest.prototype._onXHRProgress = function () {
4179 var self = this
4180
4181 self._resetTimers(false)
4182
4183 if (!statusValid(self._xhr) || self._destroyed)
4184 return
4185
4186 if (!self._response)
4187 self._connect()
4188
4189 self._response._onXHRProgress(self._resetTimers.bind(self))
4190}
4191
4192ClientRequest.prototype._connect = function () {
4193 var self = this
4194
4195 if (self._destroyed)
4196 return
4197
4198 self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._resetTimers.bind(self))
4199 self._response.on('error', function(err) {
4200 self.emit('error', err)
4201 })
4202
4203 self.emit('response', self._response)
4204}
4205
4206ClientRequest.prototype._write = function (chunk, encoding, cb) {
4207 var self = this
4208
4209 self._body.push(chunk)
4210 cb()
4211}
4212
4213ClientRequest.prototype._resetTimers = function (done) {
4214 var self = this
4215
4216 global.clearTimeout(self._socketTimer)
4217 self._socketTimer = null
4218
4219 if (done) {
4220 global.clearTimeout(self._fetchTimer)
4221 self._fetchTimer = null
4222 } else if (self._socketTimeout) {
4223 self._socketTimer = global.setTimeout(function () {
4224 self.emit('timeout')
4225 }, self._socketTimeout)
4226 }
4227}
4228
4229ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function (err) {
4230 var self = this
4231 self._destroyed = true
4232 self._resetTimers(true)
4233 if (self._response)
4234 self._response._destroyed = true
4235 if (self._xhr)
4236 self._xhr.abort()
4237 else if (self._fetchAbortController)
4238 self._fetchAbortController.abort()
4239
4240 if (err)
4241 self.emit('error', err)
4242}
4243
4244ClientRequest.prototype.end = function (data, encoding, cb) {
4245 var self = this
4246 if (typeof data === 'function') {
4247 cb = data
4248 data = undefined
4249 }
4250
4251 stream.Writable.prototype.end.call(self, data, encoding, cb)
4252}
4253
4254ClientRequest.prototype.setTimeout = function (timeout, cb) {
4255 var self = this
4256
4257 if (cb)
4258 self.once('timeout', cb)
4259
4260 self._socketTimeout = timeout
4261 self._resetTimers(false)
4262}
4263
4264ClientRequest.prototype.flushHeaders = function () {}
4265ClientRequest.prototype.setNoDelay = function () {}
4266ClientRequest.prototype.setSocketKeepAlive = function () {}
4267
4268// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
4269var unsafeHeaders = [
4270 'accept-charset',
4271 'accept-encoding',
4272 'access-control-request-headers',
4273 'access-control-request-method',
4274 'connection',
4275 'content-length',
4276 'cookie',
4277 'cookie2',
4278 'date',
4279 'dnt',
4280 'expect',
4281 'host',
4282 'keep-alive',
4283 'origin',
4284 'referer',
4285 'te',
4286 'trailer',
4287 'transfer-encoding',
4288 'upgrade',
4289 'via'
4290]
4291
4292}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
4293},{"./capability":19,"./response":21,"_process":10,"buffer":3,"inherits":8,"readable-stream":36}],21:[function(require,module,exports){
4294(function (process,global,Buffer){(function (){
4295var capability = require('./capability')
4296var inherits = require('inherits')
4297var stream = require('readable-stream')
4298
4299var rStates = exports.readyStates = {
4300 UNSENT: 0,
4301 OPENED: 1,
4302 HEADERS_RECEIVED: 2,
4303 LOADING: 3,
4304 DONE: 4
4305}
4306
4307var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, resetTimers) {
4308 var self = this
4309 stream.Readable.call(self)
4310
4311 self._mode = mode
4312 self.headers = {}
4313 self.rawHeaders = []
4314 self.trailers = {}
4315 self.rawTrailers = []
4316
4317 // Fake the 'close' event, but only once 'end' fires
4318 self.on('end', function () {
4319 // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
4320 process.nextTick(function () {
4321 self.emit('close')
4322 })
4323 })
4324
4325 if (mode === 'fetch') {
4326 self._fetchResponse = response
4327
4328 self.url = response.url
4329 self.statusCode = response.status
4330 self.statusMessage = response.statusText
4331
4332 response.headers.forEach(function (header, key){
4333 self.headers[key.toLowerCase()] = header
4334 self.rawHeaders.push(key, header)
4335 })
4336
4337 if (capability.writableStream) {
4338 var writable = new WritableStream({
4339 write: function (chunk) {
4340 resetTimers(false)
4341 return new Promise(function (resolve, reject) {
4342 if (self._destroyed) {
4343 reject()
4344 } else if(self.push(Buffer.from(chunk))) {
4345 resolve()
4346 } else {
4347 self._resumeFetch = resolve
4348 }
4349 })
4350 },
4351 close: function () {
4352 resetTimers(true)
4353 if (!self._destroyed)
4354 self.push(null)
4355 },
4356 abort: function (err) {
4357 resetTimers(true)
4358 if (!self._destroyed)
4359 self.emit('error', err)
4360 }
4361 })
4362
4363 try {
4364 response.body.pipeTo(writable).catch(function (err) {
4365 resetTimers(true)
4366 if (!self._destroyed)
4367 self.emit('error', err)
4368 })
4369 return
4370 } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
4371 }
4372 // fallback for when writableStream or pipeTo aren't available
4373 var reader = response.body.getReader()
4374 function read () {
4375 reader.read().then(function (result) {
4376 if (self._destroyed)
4377 return
4378 resetTimers(result.done)
4379 if (result.done) {
4380 self.push(null)
4381 return
4382 }
4383 self.push(Buffer.from(result.value))
4384 read()
4385 }).catch(function (err) {
4386 resetTimers(true)
4387 if (!self._destroyed)
4388 self.emit('error', err)
4389 })
4390 }
4391 read()
4392 } else {
4393 self._xhr = xhr
4394 self._pos = 0
4395
4396 self.url = xhr.responseURL
4397 self.statusCode = xhr.status
4398 self.statusMessage = xhr.statusText
4399 var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
4400 headers.forEach(function (header) {
4401 var matches = header.match(/^([^:]+):\s*(.*)/)
4402 if (matches) {
4403 var key = matches[1].toLowerCase()
4404 if (key === 'set-cookie') {
4405 if (self.headers[key] === undefined) {
4406 self.headers[key] = []
4407 }
4408 self.headers[key].push(matches[2])
4409 } else if (self.headers[key] !== undefined) {
4410 self.headers[key] += ', ' + matches[2]
4411 } else {
4412 self.headers[key] = matches[2]
4413 }
4414 self.rawHeaders.push(matches[1], matches[2])
4415 }
4416 })
4417
4418 self._charset = 'x-user-defined'
4419 if (!capability.overrideMimeType) {
4420 var mimeType = self.rawHeaders['mime-type']
4421 if (mimeType) {
4422 var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
4423 if (charsetMatch) {
4424 self._charset = charsetMatch[1].toLowerCase()
4425 }
4426 }
4427 if (!self._charset)
4428 self._charset = 'utf-8' // best guess
4429 }
4430 }
4431}
4432
4433inherits(IncomingMessage, stream.Readable)
4434
4435IncomingMessage.prototype._read = function () {
4436 var self = this
4437
4438 var resolve = self._resumeFetch
4439 if (resolve) {
4440 self._resumeFetch = null
4441 resolve()
4442 }
4443}
4444
4445IncomingMessage.prototype._onXHRProgress = function (resetTimers) {
4446 var self = this
4447
4448 var xhr = self._xhr
4449
4450 var response = null
4451 switch (self._mode) {
4452 case 'text':
4453 response = xhr.responseText
4454 if (response.length > self._pos) {
4455 var newData = response.substr(self._pos)
4456 if (self._charset === 'x-user-defined') {
4457 var buffer = Buffer.alloc(newData.length)
4458 for (var i = 0; i < newData.length; i++)
4459 buffer[i] = newData.charCodeAt(i) & 0xff
4460
4461 self.push(buffer)
4462 } else {
4463 self.push(newData, self._charset)
4464 }
4465 self._pos = response.length
4466 }
4467 break
4468 case 'arraybuffer':
4469 if (xhr.readyState !== rStates.DONE || !xhr.response)
4470 break
4471 response = xhr.response
4472 self.push(Buffer.from(new Uint8Array(response)))
4473 break
4474 case 'moz-chunked-arraybuffer': // take whole
4475 response = xhr.response
4476 if (xhr.readyState !== rStates.LOADING || !response)
4477 break
4478 self.push(Buffer.from(new Uint8Array(response)))
4479 break
4480 case 'ms-stream':
4481 response = xhr.response
4482 if (xhr.readyState !== rStates.LOADING)
4483 break
4484 var reader = new global.MSStreamReader()
4485 reader.onprogress = function () {
4486 if (reader.result.byteLength > self._pos) {
4487 self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos))))
4488 self._pos = reader.result.byteLength
4489 }
4490 }
4491 reader.onload = function () {
4492 resetTimers(true)
4493 self.push(null)
4494 }
4495 // reader.onerror = ??? // TODO: this
4496 reader.readAsArrayBuffer(response)
4497 break
4498 }
4499
4500 // The ms-stream case handles end separately in reader.onload()
4501 if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
4502 resetTimers(true)
4503 self.push(null)
4504 }
4505}
4506
4507}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
4508},{"./capability":19,"_process":10,"buffer":3,"inherits":8,"readable-stream":36}],22:[function(require,module,exports){
4509'use strict';
4510
4511function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
4512
4513var codes = {};
4514
4515function createErrorType(code, message, Base) {
4516 if (!Base) {
4517 Base = Error;
4518 }
4519
4520 function getMessage(arg1, arg2, arg3) {
4521 if (typeof message === 'string') {
4522 return message;
4523 } else {
4524 return message(arg1, arg2, arg3);
4525 }
4526 }
4527
4528 var NodeError =
4529 /*#__PURE__*/
4530 function (_Base) {
4531 _inheritsLoose(NodeError, _Base);
4532
4533 function NodeError(arg1, arg2, arg3) {
4534 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
4535 }
4536
4537 return NodeError;
4538 }(Base);
4539
4540 NodeError.prototype.name = Base.name;
4541 NodeError.prototype.code = code;
4542 codes[code] = NodeError;
4543} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
4544
4545
4546function oneOf(expected, thing) {
4547 if (Array.isArray(expected)) {
4548 var len = expected.length;
4549 expected = expected.map(function (i) {
4550 return String(i);
4551 });
4552
4553 if (len > 2) {
4554 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
4555 } else if (len === 2) {
4556 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
4557 } else {
4558 return "of ".concat(thing, " ").concat(expected[0]);
4559 }
4560 } else {
4561 return "of ".concat(thing, " ").concat(String(expected));
4562 }
4563} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
4564
4565
4566function startsWith(str, search, pos) {
4567 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
4568} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
4569
4570
4571function endsWith(str, search, this_len) {
4572 if (this_len === undefined || this_len > str.length) {
4573 this_len = str.length;
4574 }
4575
4576 return str.substring(this_len - search.length, this_len) === search;
4577} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
4578
4579
4580function includes(str, search, start) {
4581 if (typeof start !== 'number') {
4582 start = 0;
4583 }
4584
4585 if (start + search.length > str.length) {
4586 return false;
4587 } else {
4588 return str.indexOf(search, start) !== -1;
4589 }
4590}
4591
4592createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
4593 return 'The value "' + value + '" is invalid for option "' + name + '"';
4594}, TypeError);
4595createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
4596 // determiner: 'must be' or 'must not be'
4597 var determiner;
4598
4599 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
4600 determiner = 'must not be';
4601 expected = expected.replace(/^not /, '');
4602 } else {
4603 determiner = 'must be';
4604 }
4605
4606 var msg;
4607
4608 if (endsWith(name, ' argument')) {
4609 // For cases like 'first argument'
4610 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
4611 } else {
4612 var type = includes(name, '.') ? 'property' : 'argument';
4613 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
4614 }
4615
4616 msg += ". Received type ".concat(typeof actual);
4617 return msg;
4618}, TypeError);
4619createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
4620createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
4621 return 'The ' + name + ' method is not implemented';
4622});
4623createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
4624createErrorType('ERR_STREAM_DESTROYED', function (name) {
4625 return 'Cannot call ' + name + ' after a stream was destroyed';
4626});
4627createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
4628createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
4629createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
4630createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
4631createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
4632 return 'Unknown encoding: ' + arg;
4633}, TypeError);
4634createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
4635module.exports.codes = codes;
4636
4637},{}],23:[function(require,module,exports){
4638(function (process){(function (){
4639// Copyright Joyent, Inc. and other Node contributors.
4640//
4641// Permission is hereby granted, free of charge, to any person obtaining a
4642// copy of this software and associated documentation files (the
4643// "Software"), to deal in the Software without restriction, including
4644// without limitation the rights to use, copy, modify, merge, publish,
4645// distribute, sublicense, and/or sell copies of the Software, and to permit
4646// persons to whom the Software is furnished to do so, subject to the
4647// following conditions:
4648//
4649// The above copyright notice and this permission notice shall be included
4650// in all copies or substantial portions of the Software.
4651//
4652// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4653// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4654// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4655// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4656// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4657// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4658// USE OR OTHER DEALINGS IN THE SOFTWARE.
4659// a duplex stream is just a stream that is both readable and writable.
4660// Since JS doesn't have multiple prototypal inheritance, this class
4661// prototypally inherits from Readable, and then parasitically from
4662// Writable.
4663'use strict';
4664/*<replacement>*/
4665
4666var objectKeys = Object.keys || function (obj) {
4667 var keys = [];
4668
4669 for (var key in obj) {
4670 keys.push(key);
4671 }
4672
4673 return keys;
4674};
4675/*</replacement>*/
4676
4677
4678module.exports = Duplex;
4679
4680var Readable = require('./_stream_readable');
4681
4682var Writable = require('./_stream_writable');
4683
4684require('inherits')(Duplex, Readable);
4685
4686{
4687 // Allow the keys array to be GC'ed.
4688 var keys = objectKeys(Writable.prototype);
4689
4690 for (var v = 0; v < keys.length; v++) {
4691 var method = keys[v];
4692 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
4693 }
4694}
4695
4696function Duplex(options) {
4697 if (!(this instanceof Duplex)) return new Duplex(options);
4698 Readable.call(this, options);
4699 Writable.call(this, options);
4700 this.allowHalfOpen = true;
4701
4702 if (options) {
4703 if (options.readable === false) this.readable = false;
4704 if (options.writable === false) this.writable = false;
4705
4706 if (options.allowHalfOpen === false) {
4707 this.allowHalfOpen = false;
4708 this.once('end', onend);
4709 }
4710 }
4711}
4712
4713Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
4714 // making it explicit this property is not enumerable
4715 // because otherwise some prototype manipulation in
4716 // userland will fail
4717 enumerable: false,
4718 get: function get() {
4719 return this._writableState.highWaterMark;
4720 }
4721});
4722Object.defineProperty(Duplex.prototype, 'writableBuffer', {
4723 // making it explicit this property is not enumerable
4724 // because otherwise some prototype manipulation in
4725 // userland will fail
4726 enumerable: false,
4727 get: function get() {
4728 return this._writableState && this._writableState.getBuffer();
4729 }
4730});
4731Object.defineProperty(Duplex.prototype, 'writableLength', {
4732 // making it explicit this property is not enumerable
4733 // because otherwise some prototype manipulation in
4734 // userland will fail
4735 enumerable: false,
4736 get: function get() {
4737 return this._writableState.length;
4738 }
4739}); // the no-half-open enforcer
4740
4741function onend() {
4742 // If the writable side ended, then we're ok.
4743 if (this._writableState.ended) return; // no more data can be written.
4744 // But allow more writes to happen in this tick.
4745
4746 process.nextTick(onEndNT, this);
4747}
4748
4749function onEndNT(self) {
4750 self.end();
4751}
4752
4753Object.defineProperty(Duplex.prototype, 'destroyed', {
4754 // making it explicit this property is not enumerable
4755 // because otherwise some prototype manipulation in
4756 // userland will fail
4757 enumerable: false,
4758 get: function get() {
4759 if (this._readableState === undefined || this._writableState === undefined) {
4760 return false;
4761 }
4762
4763 return this._readableState.destroyed && this._writableState.destroyed;
4764 },
4765 set: function set(value) {
4766 // we ignore the value if the stream
4767 // has not been initialized yet
4768 if (this._readableState === undefined || this._writableState === undefined) {
4769 return;
4770 } // backward compatibility, the user is explicitly
4771 // managing destroyed
4772
4773
4774 this._readableState.destroyed = value;
4775 this._writableState.destroyed = value;
4776 }
4777});
4778}).call(this)}).call(this,require('_process'))
4779},{"./_stream_readable":25,"./_stream_writable":27,"_process":10,"inherits":8}],24:[function(require,module,exports){
4780// Copyright Joyent, Inc. and other Node contributors.
4781//
4782// Permission is hereby granted, free of charge, to any person obtaining a
4783// copy of this software and associated documentation files (the
4784// "Software"), to deal in the Software without restriction, including
4785// without limitation the rights to use, copy, modify, merge, publish,
4786// distribute, sublicense, and/or sell copies of the Software, and to permit
4787// persons to whom the Software is furnished to do so, subject to the
4788// following conditions:
4789//
4790// The above copyright notice and this permission notice shall be included
4791// in all copies or substantial portions of the Software.
4792//
4793// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4794// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4795// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4796// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4797// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4798// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4799// USE OR OTHER DEALINGS IN THE SOFTWARE.
4800// a passthrough stream.
4801// basically just the most minimal sort of Transform stream.
4802// Every written chunk gets output as-is.
4803'use strict';
4804
4805module.exports = PassThrough;
4806
4807var Transform = require('./_stream_transform');
4808
4809require('inherits')(PassThrough, Transform);
4810
4811function PassThrough(options) {
4812 if (!(this instanceof PassThrough)) return new PassThrough(options);
4813 Transform.call(this, options);
4814}
4815
4816PassThrough.prototype._transform = function (chunk, encoding, cb) {
4817 cb(null, chunk);
4818};
4819},{"./_stream_transform":26,"inherits":8}],25:[function(require,module,exports){
4820(function (process,global){(function (){
4821// Copyright Joyent, Inc. and other Node contributors.
4822//
4823// Permission is hereby granted, free of charge, to any person obtaining a
4824// copy of this software and associated documentation files (the
4825// "Software"), to deal in the Software without restriction, including
4826// without limitation the rights to use, copy, modify, merge, publish,
4827// distribute, sublicense, and/or sell copies of the Software, and to permit
4828// persons to whom the Software is furnished to do so, subject to the
4829// following conditions:
4830//
4831// The above copyright notice and this permission notice shall be included
4832// in all copies or substantial portions of the Software.
4833//
4834// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4835// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4836// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4837// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4838// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4839// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4840// USE OR OTHER DEALINGS IN THE SOFTWARE.
4841'use strict';
4842
4843module.exports = Readable;
4844/*<replacement>*/
4845
4846var Duplex;
4847/*</replacement>*/
4848
4849Readable.ReadableState = ReadableState;
4850/*<replacement>*/
4851
4852var EE = require('events').EventEmitter;
4853
4854var EElistenerCount = function EElistenerCount(emitter, type) {
4855 return emitter.listeners(type).length;
4856};
4857/*</replacement>*/
4858
4859/*<replacement>*/
4860
4861
4862var Stream = require('./internal/streams/stream');
4863/*</replacement>*/
4864
4865
4866var Buffer = require('buffer').Buffer;
4867
4868var OurUint8Array = global.Uint8Array || function () {};
4869
4870function _uint8ArrayToBuffer(chunk) {
4871 return Buffer.from(chunk);
4872}
4873
4874function _isUint8Array(obj) {
4875 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
4876}
4877/*<replacement>*/
4878
4879
4880var debugUtil = require('util');
4881
4882var debug;
4883
4884if (debugUtil && debugUtil.debuglog) {
4885 debug = debugUtil.debuglog('stream');
4886} else {
4887 debug = function debug() {};
4888}
4889/*</replacement>*/
4890
4891
4892var BufferList = require('./internal/streams/buffer_list');
4893
4894var destroyImpl = require('./internal/streams/destroy');
4895
4896var _require = require('./internal/streams/state'),
4897 getHighWaterMark = _require.getHighWaterMark;
4898
4899var _require$codes = require('../errors').codes,
4900 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
4901 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
4902 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
4903 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
4904
4905
4906var StringDecoder;
4907var createReadableStreamAsyncIterator;
4908var from;
4909
4910require('inherits')(Readable, Stream);
4911
4912var errorOrDestroy = destroyImpl.errorOrDestroy;
4913var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
4914
4915function prependListener(emitter, event, fn) {
4916 // Sadly this is not cacheable as some libraries bundle their own
4917 // event emitter implementation with them.
4918 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
4919 // userland ones. NEVER DO THIS. This is here only because this code needs
4920 // to continue to work with older versions of Node.js that do not include
4921 // the prependListener() method. The goal is to eventually remove this hack.
4922
4923 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
4924}
4925
4926function ReadableState(options, stream, isDuplex) {
4927 Duplex = Duplex || require('./_stream_duplex');
4928 options = options || {}; // Duplex streams are both readable and writable, but share
4929 // the same options object.
4930 // However, some cases require setting options to different
4931 // values for the readable and the writable sides of the duplex stream.
4932 // These options can be provided separately as readableXXX and writableXXX.
4933
4934 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
4935 // make all the buffer merging and length checks go away
4936
4937 this.objectMode = !!options.objectMode;
4938 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
4939 // Note: 0 is a valid value, means "don't call _read preemptively ever"
4940
4941 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
4942 // linked list can remove elements from the beginning faster than
4943 // array.shift()
4944
4945 this.buffer = new BufferList();
4946 this.length = 0;
4947 this.pipes = null;
4948 this.pipesCount = 0;
4949 this.flowing = null;
4950 this.ended = false;
4951 this.endEmitted = false;
4952 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
4953 // immediately, or on a later tick. We set this to true at first, because
4954 // any actions that shouldn't happen until "later" should generally also
4955 // not happen before the first read call.
4956
4957 this.sync = true; // whenever we return null, then we set a flag to say
4958 // that we're awaiting a 'readable' event emission.
4959
4960 this.needReadable = false;
4961 this.emittedReadable = false;
4962 this.readableListening = false;
4963 this.resumeScheduled = false;
4964 this.paused = true; // Should close be emitted on destroy. Defaults to true.
4965
4966 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
4967
4968 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
4969
4970 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
4971 // encoding is 'binary' so we have to make this configurable.
4972 // Everything else in the universe uses 'utf8', though.
4973
4974 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
4975
4976 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
4977
4978 this.readingMore = false;
4979 this.decoder = null;
4980 this.encoding = null;
4981
4982 if (options.encoding) {
4983 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
4984 this.decoder = new StringDecoder(options.encoding);
4985 this.encoding = options.encoding;
4986 }
4987}
4988
4989function Readable(options) {
4990 Duplex = Duplex || require('./_stream_duplex');
4991 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
4992 // the ReadableState constructor, at least with V8 6.5
4993
4994 var isDuplex = this instanceof Duplex;
4995 this._readableState = new ReadableState(options, this, isDuplex); // legacy
4996
4997 this.readable = true;
4998
4999 if (options) {
5000 if (typeof options.read === 'function') this._read = options.read;
5001 if (typeof options.destroy === 'function') this._destroy = options.destroy;
5002 }
5003
5004 Stream.call(this);
5005}
5006
5007Object.defineProperty(Readable.prototype, 'destroyed', {
5008 // making it explicit this property is not enumerable
5009 // because otherwise some prototype manipulation in
5010 // userland will fail
5011 enumerable: false,
5012 get: function get() {
5013 if (this._readableState === undefined) {
5014 return false;
5015 }
5016
5017 return this._readableState.destroyed;
5018 },
5019 set: function set(value) {
5020 // we ignore the value if the stream
5021 // has not been initialized yet
5022 if (!this._readableState) {
5023 return;
5024 } // backward compatibility, the user is explicitly
5025 // managing destroyed
5026
5027
5028 this._readableState.destroyed = value;
5029 }
5030});
5031Readable.prototype.destroy = destroyImpl.destroy;
5032Readable.prototype._undestroy = destroyImpl.undestroy;
5033
5034Readable.prototype._destroy = function (err, cb) {
5035 cb(err);
5036}; // Manually shove something into the read() buffer.
5037// This returns true if the highWaterMark has not been hit yet,
5038// similar to how Writable.write() returns true if you should
5039// write() some more.
5040
5041
5042Readable.prototype.push = function (chunk, encoding) {
5043 var state = this._readableState;
5044 var skipChunkCheck;
5045
5046 if (!state.objectMode) {
5047 if (typeof chunk === 'string') {
5048 encoding = encoding || state.defaultEncoding;
5049
5050 if (encoding !== state.encoding) {
5051 chunk = Buffer.from(chunk, encoding);
5052 encoding = '';
5053 }
5054
5055 skipChunkCheck = true;
5056 }
5057 } else {
5058 skipChunkCheck = true;
5059 }
5060
5061 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
5062}; // Unshift should *always* be something directly out of read()
5063
5064
5065Readable.prototype.unshift = function (chunk) {
5066 return readableAddChunk(this, chunk, null, true, false);
5067};
5068
5069function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
5070 debug('readableAddChunk', chunk);
5071 var state = stream._readableState;
5072
5073 if (chunk === null) {
5074 state.reading = false;
5075 onEofChunk(stream, state);
5076 } else {
5077 var er;
5078 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
5079
5080 if (er) {
5081 errorOrDestroy(stream, er);
5082 } else if (state.objectMode || chunk && chunk.length > 0) {
5083 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
5084 chunk = _uint8ArrayToBuffer(chunk);
5085 }
5086
5087 if (addToFront) {
5088 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
5089 } else if (state.ended) {
5090 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
5091 } else if (state.destroyed) {
5092 return false;
5093 } else {
5094 state.reading = false;
5095
5096 if (state.decoder && !encoding) {
5097 chunk = state.decoder.write(chunk);
5098 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
5099 } else {
5100 addChunk(stream, state, chunk, false);
5101 }
5102 }
5103 } else if (!addToFront) {
5104 state.reading = false;
5105 maybeReadMore(stream, state);
5106 }
5107 } // We can push more data if we are below the highWaterMark.
5108 // Also, if we have no data yet, we can stand some more bytes.
5109 // This is to work around cases where hwm=0, such as the repl.
5110
5111
5112 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
5113}
5114
5115function addChunk(stream, state, chunk, addToFront) {
5116 if (state.flowing && state.length === 0 && !state.sync) {
5117 state.awaitDrain = 0;
5118 stream.emit('data', chunk);
5119 } else {
5120 // update the buffer info.
5121 state.length += state.objectMode ? 1 : chunk.length;
5122 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
5123 if (state.needReadable) emitReadable(stream);
5124 }
5125
5126 maybeReadMore(stream, state);
5127}
5128
5129function chunkInvalid(state, chunk) {
5130 var er;
5131
5132 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
5133 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
5134 }
5135
5136 return er;
5137}
5138
5139Readable.prototype.isPaused = function () {
5140 return this._readableState.flowing === false;
5141}; // backwards compatibility.
5142
5143
5144Readable.prototype.setEncoding = function (enc) {
5145 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
5146 var decoder = new StringDecoder(enc);
5147 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
5148
5149 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
5150
5151 var p = this._readableState.buffer.head;
5152 var content = '';
5153
5154 while (p !== null) {
5155 content += decoder.write(p.data);
5156 p = p.next;
5157 }
5158
5159 this._readableState.buffer.clear();
5160
5161 if (content !== '') this._readableState.buffer.push(content);
5162 this._readableState.length = content.length;
5163 return this;
5164}; // Don't raise the hwm > 1GB
5165
5166
5167var MAX_HWM = 0x40000000;
5168
5169function computeNewHighWaterMark(n) {
5170 if (n >= MAX_HWM) {
5171 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
5172 n = MAX_HWM;
5173 } else {
5174 // Get the next highest power of 2 to prevent increasing hwm excessively in
5175 // tiny amounts
5176 n--;
5177 n |= n >>> 1;
5178 n |= n >>> 2;
5179 n |= n >>> 4;
5180 n |= n >>> 8;
5181 n |= n >>> 16;
5182 n++;
5183 }
5184
5185 return n;
5186} // This function is designed to be inlinable, so please take care when making
5187// changes to the function body.
5188
5189
5190function howMuchToRead(n, state) {
5191 if (n <= 0 || state.length === 0 && state.ended) return 0;
5192 if (state.objectMode) return 1;
5193
5194 if (n !== n) {
5195 // Only flow one buffer at a time
5196 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
5197 } // If we're asking for more than the current hwm, then raise the hwm.
5198
5199
5200 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
5201 if (n <= state.length) return n; // Don't have enough
5202
5203 if (!state.ended) {
5204 state.needReadable = true;
5205 return 0;
5206 }
5207
5208 return state.length;
5209} // you can override either this method, or the async _read(n) below.
5210
5211
5212Readable.prototype.read = function (n) {
5213 debug('read', n);
5214 n = parseInt(n, 10);
5215 var state = this._readableState;
5216 var nOrig = n;
5217 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
5218 // already have a bunch of data in the buffer, then just trigger
5219 // the 'readable' event and move on.
5220
5221 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
5222 debug('read: emitReadable', state.length, state.ended);
5223 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
5224 return null;
5225 }
5226
5227 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
5228
5229 if (n === 0 && state.ended) {
5230 if (state.length === 0) endReadable(this);
5231 return null;
5232 } // All the actual chunk generation logic needs to be
5233 // *below* the call to _read. The reason is that in certain
5234 // synthetic stream cases, such as passthrough streams, _read
5235 // may be a completely synchronous operation which may change
5236 // the state of the read buffer, providing enough data when
5237 // before there was *not* enough.
5238 //
5239 // So, the steps are:
5240 // 1. Figure out what the state of things will be after we do
5241 // a read from the buffer.
5242 //
5243 // 2. If that resulting state will trigger a _read, then call _read.
5244 // Note that this may be asynchronous, or synchronous. Yes, it is
5245 // deeply ugly to write APIs this way, but that still doesn't mean
5246 // that the Readable class should behave improperly, as streams are
5247 // designed to be sync/async agnostic.
5248 // Take note if the _read call is sync or async (ie, if the read call
5249 // has returned yet), so that we know whether or not it's safe to emit
5250 // 'readable' etc.
5251 //
5252 // 3. Actually pull the requested chunks out of the buffer and return.
5253 // if we need a readable event, then we need to do some reading.
5254
5255
5256 var doRead = state.needReadable;
5257 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
5258
5259 if (state.length === 0 || state.length - n < state.highWaterMark) {
5260 doRead = true;
5261 debug('length less than watermark', doRead);
5262 } // however, if we've ended, then there's no point, and if we're already
5263 // reading, then it's unnecessary.
5264
5265
5266 if (state.ended || state.reading) {
5267 doRead = false;
5268 debug('reading or ended', doRead);
5269 } else if (doRead) {
5270 debug('do read');
5271 state.reading = true;
5272 state.sync = true; // if the length is currently zero, then we *need* a readable event.
5273
5274 if (state.length === 0) state.needReadable = true; // call internal read method
5275
5276 this._read(state.highWaterMark);
5277
5278 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
5279 // and we need to re-evaluate how much data we can return to the user.
5280
5281 if (!state.reading) n = howMuchToRead(nOrig, state);
5282 }
5283
5284 var ret;
5285 if (n > 0) ret = fromList(n, state);else ret = null;
5286
5287 if (ret === null) {
5288 state.needReadable = state.length <= state.highWaterMark;
5289 n = 0;
5290 } else {
5291 state.length -= n;
5292 state.awaitDrain = 0;
5293 }
5294
5295 if (state.length === 0) {
5296 // If we have nothing in the buffer, then we want to know
5297 // as soon as we *do* get something into the buffer.
5298 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
5299
5300 if (nOrig !== n && state.ended) endReadable(this);
5301 }
5302
5303 if (ret !== null) this.emit('data', ret);
5304 return ret;
5305};
5306
5307function onEofChunk(stream, state) {
5308 debug('onEofChunk');
5309 if (state.ended) return;
5310
5311 if (state.decoder) {
5312 var chunk = state.decoder.end();
5313
5314 if (chunk && chunk.length) {
5315 state.buffer.push(chunk);
5316 state.length += state.objectMode ? 1 : chunk.length;
5317 }
5318 }
5319
5320 state.ended = true;
5321
5322 if (state.sync) {
5323 // if we are sync, wait until next tick to emit the data.
5324 // Otherwise we risk emitting data in the flow()
5325 // the readable code triggers during a read() call
5326 emitReadable(stream);
5327 } else {
5328 // emit 'readable' now to make sure it gets picked up.
5329 state.needReadable = false;
5330
5331 if (!state.emittedReadable) {
5332 state.emittedReadable = true;
5333 emitReadable_(stream);
5334 }
5335 }
5336} // Don't emit readable right away in sync mode, because this can trigger
5337// another read() call => stack overflow. This way, it might trigger
5338// a nextTick recursion warning, but that's not so bad.
5339
5340
5341function emitReadable(stream) {
5342 var state = stream._readableState;
5343 debug('emitReadable', state.needReadable, state.emittedReadable);
5344 state.needReadable = false;
5345
5346 if (!state.emittedReadable) {
5347 debug('emitReadable', state.flowing);
5348 state.emittedReadable = true;
5349 process.nextTick(emitReadable_, stream);
5350 }
5351}
5352
5353function emitReadable_(stream) {
5354 var state = stream._readableState;
5355 debug('emitReadable_', state.destroyed, state.length, state.ended);
5356
5357 if (!state.destroyed && (state.length || state.ended)) {
5358 stream.emit('readable');
5359 state.emittedReadable = false;
5360 } // The stream needs another readable event if
5361 // 1. It is not flowing, as the flow mechanism will take
5362 // care of it.
5363 // 2. It is not ended.
5364 // 3. It is below the highWaterMark, so we can schedule
5365 // another readable later.
5366
5367
5368 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
5369 flow(stream);
5370} // at this point, the user has presumably seen the 'readable' event,
5371// and called read() to consume some data. that may have triggered
5372// in turn another _read(n) call, in which case reading = true if
5373// it's in progress.
5374// However, if we're not ended, or reading, and the length < hwm,
5375// then go ahead and try to read some more preemptively.
5376
5377
5378function maybeReadMore(stream, state) {
5379 if (!state.readingMore) {
5380 state.readingMore = true;
5381 process.nextTick(maybeReadMore_, stream, state);
5382 }
5383}
5384
5385function maybeReadMore_(stream, state) {
5386 // Attempt to read more data if we should.
5387 //
5388 // The conditions for reading more data are (one of):
5389 // - Not enough data buffered (state.length < state.highWaterMark). The loop
5390 // is responsible for filling the buffer with enough data if such data
5391 // is available. If highWaterMark is 0 and we are not in the flowing mode
5392 // we should _not_ attempt to buffer any extra data. We'll get more data
5393 // when the stream consumer calls read() instead.
5394 // - No data in the buffer, and the stream is in flowing mode. In this mode
5395 // the loop below is responsible for ensuring read() is called. Failing to
5396 // call read here would abort the flow and there's no other mechanism for
5397 // continuing the flow if the stream consumer has just subscribed to the
5398 // 'data' event.
5399 //
5400 // In addition to the above conditions to keep reading data, the following
5401 // conditions prevent the data from being read:
5402 // - The stream has ended (state.ended).
5403 // - There is already a pending 'read' operation (state.reading). This is a
5404 // case where the the stream has called the implementation defined _read()
5405 // method, but they are processing the call asynchronously and have _not_
5406 // called push() with new data. In this case we skip performing more
5407 // read()s. The execution ends in this method again after the _read() ends
5408 // up calling push() with more data.
5409 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
5410 var len = state.length;
5411 debug('maybeReadMore read 0');
5412 stream.read(0);
5413 if (len === state.length) // didn't get any data, stop spinning.
5414 break;
5415 }
5416
5417 state.readingMore = false;
5418} // abstract method. to be overridden in specific implementation classes.
5419// call cb(er, data) where data is <= n in length.
5420// for virtual (non-string, non-buffer) streams, "length" is somewhat
5421// arbitrary, and perhaps not very meaningful.
5422
5423
5424Readable.prototype._read = function (n) {
5425 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
5426};
5427
5428Readable.prototype.pipe = function (dest, pipeOpts) {
5429 var src = this;
5430 var state = this._readableState;
5431
5432 switch (state.pipesCount) {
5433 case 0:
5434 state.pipes = dest;
5435 break;
5436
5437 case 1:
5438 state.pipes = [state.pipes, dest];
5439 break;
5440
5441 default:
5442 state.pipes.push(dest);
5443 break;
5444 }
5445
5446 state.pipesCount += 1;
5447 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
5448 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
5449 var endFn = doEnd ? onend : unpipe;
5450 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
5451 dest.on('unpipe', onunpipe);
5452
5453 function onunpipe(readable, unpipeInfo) {
5454 debug('onunpipe');
5455
5456 if (readable === src) {
5457 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
5458 unpipeInfo.hasUnpiped = true;
5459 cleanup();
5460 }
5461 }
5462 }
5463
5464 function onend() {
5465 debug('onend');
5466 dest.end();
5467 } // when the dest drains, it reduces the awaitDrain counter
5468 // on the source. This would be more elegant with a .once()
5469 // handler in flow(), but adding and removing repeatedly is
5470 // too slow.
5471
5472
5473 var ondrain = pipeOnDrain(src);
5474 dest.on('drain', ondrain);
5475 var cleanedUp = false;
5476
5477 function cleanup() {
5478 debug('cleanup'); // cleanup event handlers once the pipe is broken
5479
5480 dest.removeListener('close', onclose);
5481 dest.removeListener('finish', onfinish);
5482 dest.removeListener('drain', ondrain);
5483 dest.removeListener('error', onerror);
5484 dest.removeListener('unpipe', onunpipe);
5485 src.removeListener('end', onend);
5486 src.removeListener('end', unpipe);
5487 src.removeListener('data', ondata);
5488 cleanedUp = true; // if the reader is waiting for a drain event from this
5489 // specific writer, then it would cause it to never start
5490 // flowing again.
5491 // So, if this is awaiting a drain, then we just call it now.
5492 // If we don't know, then assume that we are waiting for one.
5493
5494 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
5495 }
5496
5497 src.on('data', ondata);
5498
5499 function ondata(chunk) {
5500 debug('ondata');
5501 var ret = dest.write(chunk);
5502 debug('dest.write', ret);
5503
5504 if (ret === false) {
5505 // If the user unpiped during `dest.write()`, it is possible
5506 // to get stuck in a permanently paused state if that write
5507 // also returned false.
5508 // => Check whether `dest` is still a piping destination.
5509 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
5510 debug('false write response, pause', state.awaitDrain);
5511 state.awaitDrain++;
5512 }
5513
5514 src.pause();
5515 }
5516 } // if the dest has an error, then stop piping into it.
5517 // however, don't suppress the throwing behavior for this.
5518
5519
5520 function onerror(er) {
5521 debug('onerror', er);
5522 unpipe();
5523 dest.removeListener('error', onerror);
5524 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
5525 } // Make sure our error handler is attached before userland ones.
5526
5527
5528 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
5529
5530 function onclose() {
5531 dest.removeListener('finish', onfinish);
5532 unpipe();
5533 }
5534
5535 dest.once('close', onclose);
5536
5537 function onfinish() {
5538 debug('onfinish');
5539 dest.removeListener('close', onclose);
5540 unpipe();
5541 }
5542
5543 dest.once('finish', onfinish);
5544
5545 function unpipe() {
5546 debug('unpipe');
5547 src.unpipe(dest);
5548 } // tell the dest that it's being piped to
5549
5550
5551 dest.emit('pipe', src); // start the flow if it hasn't been started already.
5552
5553 if (!state.flowing) {
5554 debug('pipe resume');
5555 src.resume();
5556 }
5557
5558 return dest;
5559};
5560
5561function pipeOnDrain(src) {
5562 return function pipeOnDrainFunctionResult() {
5563 var state = src._readableState;
5564 debug('pipeOnDrain', state.awaitDrain);
5565 if (state.awaitDrain) state.awaitDrain--;
5566
5567 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
5568 state.flowing = true;
5569 flow(src);
5570 }
5571 };
5572}
5573
5574Readable.prototype.unpipe = function (dest) {
5575 var state = this._readableState;
5576 var unpipeInfo = {
5577 hasUnpiped: false
5578 }; // if we're not piping anywhere, then do nothing.
5579
5580 if (state.pipesCount === 0) return this; // just one destination. most common case.
5581
5582 if (state.pipesCount === 1) {
5583 // passed in one, but it's not the right one.
5584 if (dest && dest !== state.pipes) return this;
5585 if (!dest) dest = state.pipes; // got a match.
5586
5587 state.pipes = null;
5588 state.pipesCount = 0;
5589 state.flowing = false;
5590 if (dest) dest.emit('unpipe', this, unpipeInfo);
5591 return this;
5592 } // slow case. multiple pipe destinations.
5593
5594
5595 if (!dest) {
5596 // remove all.
5597 var dests = state.pipes;
5598 var len = state.pipesCount;
5599 state.pipes = null;
5600 state.pipesCount = 0;
5601 state.flowing = false;
5602
5603 for (var i = 0; i < len; i++) {
5604 dests[i].emit('unpipe', this, {
5605 hasUnpiped: false
5606 });
5607 }
5608
5609 return this;
5610 } // try to find the right one.
5611
5612
5613 var index = indexOf(state.pipes, dest);
5614 if (index === -1) return this;
5615 state.pipes.splice(index, 1);
5616 state.pipesCount -= 1;
5617 if (state.pipesCount === 1) state.pipes = state.pipes[0];
5618 dest.emit('unpipe', this, unpipeInfo);
5619 return this;
5620}; // set up data events if they are asked for
5621// Ensure readable listeners eventually get something
5622
5623
5624Readable.prototype.on = function (ev, fn) {
5625 var res = Stream.prototype.on.call(this, ev, fn);
5626 var state = this._readableState;
5627
5628 if (ev === 'data') {
5629 // update readableListening so that resume() may be a no-op
5630 // a few lines down. This is needed to support once('readable').
5631 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
5632
5633 if (state.flowing !== false) this.resume();
5634 } else if (ev === 'readable') {
5635 if (!state.endEmitted && !state.readableListening) {
5636 state.readableListening = state.needReadable = true;
5637 state.flowing = false;
5638 state.emittedReadable = false;
5639 debug('on readable', state.length, state.reading);
5640
5641 if (state.length) {
5642 emitReadable(this);
5643 } else if (!state.reading) {
5644 process.nextTick(nReadingNextTick, this);
5645 }
5646 }
5647 }
5648
5649 return res;
5650};
5651
5652Readable.prototype.addListener = Readable.prototype.on;
5653
5654Readable.prototype.removeListener = function (ev, fn) {
5655 var res = Stream.prototype.removeListener.call(this, ev, fn);
5656
5657 if (ev === 'readable') {
5658 // We need to check if there is someone still listening to
5659 // readable and reset the state. However this needs to happen
5660 // after readable has been emitted but before I/O (nextTick) to
5661 // support once('readable', fn) cycles. This means that calling
5662 // resume within the same tick will have no
5663 // effect.
5664 process.nextTick(updateReadableListening, this);
5665 }
5666
5667 return res;
5668};
5669
5670Readable.prototype.removeAllListeners = function (ev) {
5671 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
5672
5673 if (ev === 'readable' || ev === undefined) {
5674 // We need to check if there is someone still listening to
5675 // readable and reset the state. However this needs to happen
5676 // after readable has been emitted but before I/O (nextTick) to
5677 // support once('readable', fn) cycles. This means that calling
5678 // resume within the same tick will have no
5679 // effect.
5680 process.nextTick(updateReadableListening, this);
5681 }
5682
5683 return res;
5684};
5685
5686function updateReadableListening(self) {
5687 var state = self._readableState;
5688 state.readableListening = self.listenerCount('readable') > 0;
5689
5690 if (state.resumeScheduled && !state.paused) {
5691 // flowing needs to be set to true now, otherwise
5692 // the upcoming resume will not flow.
5693 state.flowing = true; // crude way to check if we should resume
5694 } else if (self.listenerCount('data') > 0) {
5695 self.resume();
5696 }
5697}
5698
5699function nReadingNextTick(self) {
5700 debug('readable nexttick read 0');
5701 self.read(0);
5702} // pause() and resume() are remnants of the legacy readable stream API
5703// If the user uses them, then switch into old mode.
5704
5705
5706Readable.prototype.resume = function () {
5707 var state = this._readableState;
5708
5709 if (!state.flowing) {
5710 debug('resume'); // we flow only if there is no one listening
5711 // for readable, but we still have to call
5712 // resume()
5713
5714 state.flowing = !state.readableListening;
5715 resume(this, state);
5716 }
5717
5718 state.paused = false;
5719 return this;
5720};
5721
5722function resume(stream, state) {
5723 if (!state.resumeScheduled) {
5724 state.resumeScheduled = true;
5725 process.nextTick(resume_, stream, state);
5726 }
5727}
5728
5729function resume_(stream, state) {
5730 debug('resume', state.reading);
5731
5732 if (!state.reading) {
5733 stream.read(0);
5734 }
5735
5736 state.resumeScheduled = false;
5737 stream.emit('resume');
5738 flow(stream);
5739 if (state.flowing && !state.reading) stream.read(0);
5740}
5741
5742Readable.prototype.pause = function () {
5743 debug('call pause flowing=%j', this._readableState.flowing);
5744
5745 if (this._readableState.flowing !== false) {
5746 debug('pause');
5747 this._readableState.flowing = false;
5748 this.emit('pause');
5749 }
5750
5751 this._readableState.paused = true;
5752 return this;
5753};
5754
5755function flow(stream) {
5756 var state = stream._readableState;
5757 debug('flow', state.flowing);
5758
5759 while (state.flowing && stream.read() !== null) {
5760 ;
5761 }
5762} // wrap an old-style stream as the async data source.
5763// This is *not* part of the readable stream interface.
5764// It is an ugly unfortunate mess of history.
5765
5766
5767Readable.prototype.wrap = function (stream) {
5768 var _this = this;
5769
5770 var state = this._readableState;
5771 var paused = false;
5772 stream.on('end', function () {
5773 debug('wrapped end');
5774
5775 if (state.decoder && !state.ended) {
5776 var chunk = state.decoder.end();
5777 if (chunk && chunk.length) _this.push(chunk);
5778 }
5779
5780 _this.push(null);
5781 });
5782 stream.on('data', function (chunk) {
5783 debug('wrapped data');
5784 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
5785
5786 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
5787
5788 var ret = _this.push(chunk);
5789
5790 if (!ret) {
5791 paused = true;
5792 stream.pause();
5793 }
5794 }); // proxy all the other methods.
5795 // important when wrapping filters and duplexes.
5796
5797 for (var i in stream) {
5798 if (this[i] === undefined && typeof stream[i] === 'function') {
5799 this[i] = function methodWrap(method) {
5800 return function methodWrapReturnFunction() {
5801 return stream[method].apply(stream, arguments);
5802 };
5803 }(i);
5804 }
5805 } // proxy certain important events.
5806
5807
5808 for (var n = 0; n < kProxyEvents.length; n++) {
5809 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
5810 } // when we try to consume some more bytes, simply unpause the
5811 // underlying stream.
5812
5813
5814 this._read = function (n) {
5815 debug('wrapped _read', n);
5816
5817 if (paused) {
5818 paused = false;
5819 stream.resume();
5820 }
5821 };
5822
5823 return this;
5824};
5825
5826if (typeof Symbol === 'function') {
5827 Readable.prototype[Symbol.asyncIterator] = function () {
5828 if (createReadableStreamAsyncIterator === undefined) {
5829 createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
5830 }
5831
5832 return createReadableStreamAsyncIterator(this);
5833 };
5834}
5835
5836Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
5837 // making it explicit this property is not enumerable
5838 // because otherwise some prototype manipulation in
5839 // userland will fail
5840 enumerable: false,
5841 get: function get() {
5842 return this._readableState.highWaterMark;
5843 }
5844});
5845Object.defineProperty(Readable.prototype, 'readableBuffer', {
5846 // making it explicit this property is not enumerable
5847 // because otherwise some prototype manipulation in
5848 // userland will fail
5849 enumerable: false,
5850 get: function get() {
5851 return this._readableState && this._readableState.buffer;
5852 }
5853});
5854Object.defineProperty(Readable.prototype, 'readableFlowing', {
5855 // making it explicit this property is not enumerable
5856 // because otherwise some prototype manipulation in
5857 // userland will fail
5858 enumerable: false,
5859 get: function get() {
5860 return this._readableState.flowing;
5861 },
5862 set: function set(state) {
5863 if (this._readableState) {
5864 this._readableState.flowing = state;
5865 }
5866 }
5867}); // exposed for testing purposes only.
5868
5869Readable._fromList = fromList;
5870Object.defineProperty(Readable.prototype, 'readableLength', {
5871 // making it explicit this property is not enumerable
5872 // because otherwise some prototype manipulation in
5873 // userland will fail
5874 enumerable: false,
5875 get: function get() {
5876 return this._readableState.length;
5877 }
5878}); // Pluck off n bytes from an array of buffers.
5879// Length is the combined lengths of all the buffers in the list.
5880// This function is designed to be inlinable, so please take care when making
5881// changes to the function body.
5882
5883function fromList(n, state) {
5884 // nothing buffered
5885 if (state.length === 0) return null;
5886 var ret;
5887 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
5888 // read it all, truncate the list
5889 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
5890 state.buffer.clear();
5891 } else {
5892 // read part of list
5893 ret = state.buffer.consume(n, state.decoder);
5894 }
5895 return ret;
5896}
5897
5898function endReadable(stream) {
5899 var state = stream._readableState;
5900 debug('endReadable', state.endEmitted);
5901
5902 if (!state.endEmitted) {
5903 state.ended = true;
5904 process.nextTick(endReadableNT, state, stream);
5905 }
5906}
5907
5908function endReadableNT(state, stream) {
5909 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
5910
5911 if (!state.endEmitted && state.length === 0) {
5912 state.endEmitted = true;
5913 stream.readable = false;
5914 stream.emit('end');
5915
5916 if (state.autoDestroy) {
5917 // In case of duplex streams we need a way to detect
5918 // if the writable side is ready for autoDestroy as well
5919 var wState = stream._writableState;
5920
5921 if (!wState || wState.autoDestroy && wState.finished) {
5922 stream.destroy();
5923 }
5924 }
5925 }
5926}
5927
5928if (typeof Symbol === 'function') {
5929 Readable.from = function (iterable, opts) {
5930 if (from === undefined) {
5931 from = require('./internal/streams/from');
5932 }
5933
5934 return from(Readable, iterable, opts);
5935 };
5936}
5937
5938function indexOf(xs, x) {
5939 for (var i = 0, l = xs.length; i < l; i++) {
5940 if (xs[i] === x) return i;
5941 }
5942
5943 return -1;
5944}
5945}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5946},{"../errors":22,"./_stream_duplex":23,"./internal/streams/async_iterator":28,"./internal/streams/buffer_list":29,"./internal/streams/destroy":30,"./internal/streams/from":32,"./internal/streams/state":34,"./internal/streams/stream":35,"_process":10,"buffer":3,"events":5,"inherits":8,"string_decoder/":37,"util":2}],26:[function(require,module,exports){
5947// Copyright Joyent, Inc. and other Node contributors.
5948//
5949// Permission is hereby granted, free of charge, to any person obtaining a
5950// copy of this software and associated documentation files (the
5951// "Software"), to deal in the Software without restriction, including
5952// without limitation the rights to use, copy, modify, merge, publish,
5953// distribute, sublicense, and/or sell copies of the Software, and to permit
5954// persons to whom the Software is furnished to do so, subject to the
5955// following conditions:
5956//
5957// The above copyright notice and this permission notice shall be included
5958// in all copies or substantial portions of the Software.
5959//
5960// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5961// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5962// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5963// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5964// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5965// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5966// USE OR OTHER DEALINGS IN THE SOFTWARE.
5967// a transform stream is a readable/writable stream where you do
5968// something with the data. Sometimes it's called a "filter",
5969// but that's not a great name for it, since that implies a thing where
5970// some bits pass through, and others are simply ignored. (That would
5971// be a valid example of a transform, of course.)
5972//
5973// While the output is causally related to the input, it's not a
5974// necessarily symmetric or synchronous transformation. For example,
5975// a zlib stream might take multiple plain-text writes(), and then
5976// emit a single compressed chunk some time in the future.
5977//
5978// Here's how this works:
5979//
5980// The Transform stream has all the aspects of the readable and writable
5981// stream classes. When you write(chunk), that calls _write(chunk,cb)
5982// internally, and returns false if there's a lot of pending writes
5983// buffered up. When you call read(), that calls _read(n) until
5984// there's enough pending readable data buffered up.
5985//
5986// In a transform stream, the written data is placed in a buffer. When
5987// _read(n) is called, it transforms the queued up data, calling the
5988// buffered _write cb's as it consumes chunks. If consuming a single
5989// written chunk would result in multiple output chunks, then the first
5990// outputted bit calls the readcb, and subsequent chunks just go into
5991// the read buffer, and will cause it to emit 'readable' if necessary.
5992//
5993// This way, back-pressure is actually determined by the reading side,
5994// since _read has to be called to start processing a new chunk. However,
5995// a pathological inflate type of transform can cause excessive buffering
5996// here. For example, imagine a stream where every byte of input is
5997// interpreted as an integer from 0-255, and then results in that many
5998// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
5999// 1kb of data being output. In this case, you could write a very small
6000// amount of input, and end up with a very large amount of output. In
6001// such a pathological inflating mechanism, there'd be no way to tell
6002// the system to stop doing the transform. A single 4MB write could
6003// cause the system to run out of memory.
6004//
6005// However, even in such a pathological case, only a single written chunk
6006// would be consumed, and then the rest would wait (un-transformed) until
6007// the results of the previous transformed chunk were consumed.
6008'use strict';
6009
6010module.exports = Transform;
6011
6012var _require$codes = require('../errors').codes,
6013 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
6014 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
6015 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
6016 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
6017
6018var Duplex = require('./_stream_duplex');
6019
6020require('inherits')(Transform, Duplex);
6021
6022function afterTransform(er, data) {
6023 var ts = this._transformState;
6024 ts.transforming = false;
6025 var cb = ts.writecb;
6026
6027 if (cb === null) {
6028 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
6029 }
6030
6031 ts.writechunk = null;
6032 ts.writecb = null;
6033 if (data != null) // single equals check for both `null` and `undefined`
6034 this.push(data);
6035 cb(er);
6036 var rs = this._readableState;
6037 rs.reading = false;
6038
6039 if (rs.needReadable || rs.length < rs.highWaterMark) {
6040 this._read(rs.highWaterMark);
6041 }
6042}
6043
6044function Transform(options) {
6045 if (!(this instanceof Transform)) return new Transform(options);
6046 Duplex.call(this, options);
6047 this._transformState = {
6048 afterTransform: afterTransform.bind(this),
6049 needTransform: false,
6050 transforming: false,
6051 writecb: null,
6052 writechunk: null,
6053 writeencoding: null
6054 }; // start out asking for a readable event once data is transformed.
6055
6056 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
6057 // that Readable wants before the first _read call, so unset the
6058 // sync guard flag.
6059
6060 this._readableState.sync = false;
6061
6062 if (options) {
6063 if (typeof options.transform === 'function') this._transform = options.transform;
6064 if (typeof options.flush === 'function') this._flush = options.flush;
6065 } // When the writable side finishes, then flush out anything remaining.
6066
6067
6068 this.on('prefinish', prefinish);
6069}
6070
6071function prefinish() {
6072 var _this = this;
6073
6074 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
6075 this._flush(function (er, data) {
6076 done(_this, er, data);
6077 });
6078 } else {
6079 done(this, null, null);
6080 }
6081}
6082
6083Transform.prototype.push = function (chunk, encoding) {
6084 this._transformState.needTransform = false;
6085 return Duplex.prototype.push.call(this, chunk, encoding);
6086}; // This is the part where you do stuff!
6087// override this function in implementation classes.
6088// 'chunk' is an input chunk.
6089//
6090// Call `push(newChunk)` to pass along transformed output
6091// to the readable side. You may call 'push' zero or more times.
6092//
6093// Call `cb(err)` when you are done with this chunk. If you pass
6094// an error, then that'll put the hurt on the whole operation. If you
6095// never call cb(), then you'll never get another chunk.
6096
6097
6098Transform.prototype._transform = function (chunk, encoding, cb) {
6099 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
6100};
6101
6102Transform.prototype._write = function (chunk, encoding, cb) {
6103 var ts = this._transformState;
6104 ts.writecb = cb;
6105 ts.writechunk = chunk;
6106 ts.writeencoding = encoding;
6107
6108 if (!ts.transforming) {
6109 var rs = this._readableState;
6110 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
6111 }
6112}; // Doesn't matter what the args are here.
6113// _transform does all the work.
6114// That we got here means that the readable side wants more data.
6115
6116
6117Transform.prototype._read = function (n) {
6118 var ts = this._transformState;
6119
6120 if (ts.writechunk !== null && !ts.transforming) {
6121 ts.transforming = true;
6122
6123 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
6124 } else {
6125 // mark that we need a transform, so that any data that comes in
6126 // will get processed, now that we've asked for it.
6127 ts.needTransform = true;
6128 }
6129};
6130
6131Transform.prototype._destroy = function (err, cb) {
6132 Duplex.prototype._destroy.call(this, err, function (err2) {
6133 cb(err2);
6134 });
6135};
6136
6137function done(stream, er, data) {
6138 if (er) return stream.emit('error', er);
6139 if (data != null) // single equals check for both `null` and `undefined`
6140 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
6141 // if there's nothing in the write buffer, then that means
6142 // that nothing more will ever be provided
6143
6144 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
6145 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
6146 return stream.push(null);
6147}
6148},{"../errors":22,"./_stream_duplex":23,"inherits":8}],27:[function(require,module,exports){
6149(function (process,global){(function (){
6150// Copyright Joyent, Inc. and other Node contributors.
6151//
6152// Permission is hereby granted, free of charge, to any person obtaining a
6153// copy of this software and associated documentation files (the
6154// "Software"), to deal in the Software without restriction, including
6155// without limitation the rights to use, copy, modify, merge, publish,
6156// distribute, sublicense, and/or sell copies of the Software, and to permit
6157// persons to whom the Software is furnished to do so, subject to the
6158// following conditions:
6159//
6160// The above copyright notice and this permission notice shall be included
6161// in all copies or substantial portions of the Software.
6162//
6163// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6164// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6165// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6166// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6167// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6168// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6169// USE OR OTHER DEALINGS IN THE SOFTWARE.
6170// A bit simpler than readable streams.
6171// Implement an async ._write(chunk, encoding, cb), and it'll handle all
6172// the drain event emission and buffering.
6173'use strict';
6174
6175module.exports = Writable;
6176/* <replacement> */
6177
6178function WriteReq(chunk, encoding, cb) {
6179 this.chunk = chunk;
6180 this.encoding = encoding;
6181 this.callback = cb;
6182 this.next = null;
6183} // It seems a linked list but it is not
6184// there will be only 2 of these for each stream
6185
6186
6187function CorkedRequest(state) {
6188 var _this = this;
6189
6190 this.next = null;
6191 this.entry = null;
6192
6193 this.finish = function () {
6194 onCorkedFinish(_this, state);
6195 };
6196}
6197/* </replacement> */
6198
6199/*<replacement>*/
6200
6201
6202var Duplex;
6203/*</replacement>*/
6204
6205Writable.WritableState = WritableState;
6206/*<replacement>*/
6207
6208var internalUtil = {
6209 deprecate: require('util-deprecate')
6210};
6211/*</replacement>*/
6212
6213/*<replacement>*/
6214
6215var Stream = require('./internal/streams/stream');
6216/*</replacement>*/
6217
6218
6219var Buffer = require('buffer').Buffer;
6220
6221var OurUint8Array = global.Uint8Array || function () {};
6222
6223function _uint8ArrayToBuffer(chunk) {
6224 return Buffer.from(chunk);
6225}
6226
6227function _isUint8Array(obj) {
6228 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6229}
6230
6231var destroyImpl = require('./internal/streams/destroy');
6232
6233var _require = require('./internal/streams/state'),
6234 getHighWaterMark = _require.getHighWaterMark;
6235
6236var _require$codes = require('../errors').codes,
6237 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
6238 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
6239 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
6240 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
6241 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
6242 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
6243 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
6244 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
6245
6246var errorOrDestroy = destroyImpl.errorOrDestroy;
6247
6248require('inherits')(Writable, Stream);
6249
6250function nop() {}
6251
6252function WritableState(options, stream, isDuplex) {
6253 Duplex = Duplex || require('./_stream_duplex');
6254 options = options || {}; // Duplex streams are both readable and writable, but share
6255 // the same options object.
6256 // However, some cases require setting options to different
6257 // values for the readable and the writable sides of the duplex stream,
6258 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
6259
6260 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
6261 // contains buffers or objects.
6262
6263 this.objectMode = !!options.objectMode;
6264 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
6265 // Note: 0 is a valid value, means that we always return false if
6266 // the entire buffer is not flushed immediately on write()
6267
6268 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
6269
6270 this.finalCalled = false; // drain event flag.
6271
6272 this.needDrain = false; // at the start of calling end()
6273
6274 this.ending = false; // when end() has been called, and returned
6275
6276 this.ended = false; // when 'finish' is emitted
6277
6278 this.finished = false; // has it been destroyed
6279
6280 this.destroyed = false; // should we decode strings into buffers before passing to _write?
6281 // this is here so that some node-core streams can optimize string
6282 // handling at a lower level.
6283
6284 var noDecode = options.decodeStrings === false;
6285 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
6286 // encoding is 'binary' so we have to make this configurable.
6287 // Everything else in the universe uses 'utf8', though.
6288
6289 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
6290 // of how much we're waiting to get pushed to some underlying
6291 // socket or file.
6292
6293 this.length = 0; // a flag to see when we're in the middle of a write.
6294
6295 this.writing = false; // when true all writes will be buffered until .uncork() call
6296
6297 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
6298 // or on a later tick. We set this to true at first, because any
6299 // actions that shouldn't happen until "later" should generally also
6300 // not happen before the first write call.
6301
6302 this.sync = true; // a flag to know if we're processing previously buffered items, which
6303 // may call the _write() callback in the same tick, so that we don't
6304 // end up in an overlapped onwrite situation.
6305
6306 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
6307
6308 this.onwrite = function (er) {
6309 onwrite(stream, er);
6310 }; // the callback that the user supplies to write(chunk,encoding,cb)
6311
6312
6313 this.writecb = null; // the amount that is being written when _write is called.
6314
6315 this.writelen = 0;
6316 this.bufferedRequest = null;
6317 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
6318 // this must be 0 before 'finish' can be emitted
6319
6320 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
6321 // This is relevant for synchronous Transform streams
6322
6323 this.prefinished = false; // True if the error was already emitted and should not be thrown again
6324
6325 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
6326
6327 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
6328
6329 this.autoDestroy = !!options.autoDestroy; // count buffered requests
6330
6331 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
6332 // one allocated and free to use, and we maintain at most two
6333
6334 this.corkedRequestsFree = new CorkedRequest(this);
6335}
6336
6337WritableState.prototype.getBuffer = function getBuffer() {
6338 var current = this.bufferedRequest;
6339 var out = [];
6340
6341 while (current) {
6342 out.push(current);
6343 current = current.next;
6344 }
6345
6346 return out;
6347};
6348
6349(function () {
6350 try {
6351 Object.defineProperty(WritableState.prototype, 'buffer', {
6352 get: internalUtil.deprecate(function writableStateBufferGetter() {
6353 return this.getBuffer();
6354 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
6355 });
6356 } catch (_) {}
6357})(); // Test _writableState for inheritance to account for Duplex streams,
6358// whose prototype chain only points to Readable.
6359
6360
6361var realHasInstance;
6362
6363if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
6364 realHasInstance = Function.prototype[Symbol.hasInstance];
6365 Object.defineProperty(Writable, Symbol.hasInstance, {
6366 value: function value(object) {
6367 if (realHasInstance.call(this, object)) return true;
6368 if (this !== Writable) return false;
6369 return object && object._writableState instanceof WritableState;
6370 }
6371 });
6372} else {
6373 realHasInstance = function realHasInstance(object) {
6374 return object instanceof this;
6375 };
6376}
6377
6378function Writable(options) {
6379 Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
6380 // `realHasInstance` is necessary because using plain `instanceof`
6381 // would return false, as no `_writableState` property is attached.
6382 // Trying to use the custom `instanceof` for Writable here will also break the
6383 // Node.js LazyTransform implementation, which has a non-trivial getter for
6384 // `_writableState` that would lead to infinite recursion.
6385 // Checking for a Stream.Duplex instance is faster here instead of inside
6386 // the WritableState constructor, at least with V8 6.5
6387
6388 var isDuplex = this instanceof Duplex;
6389 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
6390 this._writableState = new WritableState(options, this, isDuplex); // legacy.
6391
6392 this.writable = true;
6393
6394 if (options) {
6395 if (typeof options.write === 'function') this._write = options.write;
6396 if (typeof options.writev === 'function') this._writev = options.writev;
6397 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6398 if (typeof options.final === 'function') this._final = options.final;
6399 }
6400
6401 Stream.call(this);
6402} // Otherwise people can pipe Writable streams, which is just wrong.
6403
6404
6405Writable.prototype.pipe = function () {
6406 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
6407};
6408
6409function writeAfterEnd(stream, cb) {
6410 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
6411
6412 errorOrDestroy(stream, er);
6413 process.nextTick(cb, er);
6414} // Checks that a user-supplied chunk is valid, especially for the particular
6415// mode the stream is in. Currently this means that `null` is never accepted
6416// and undefined/non-string values are only allowed in object mode.
6417
6418
6419function validChunk(stream, state, chunk, cb) {
6420 var er;
6421
6422 if (chunk === null) {
6423 er = new ERR_STREAM_NULL_VALUES();
6424 } else if (typeof chunk !== 'string' && !state.objectMode) {
6425 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
6426 }
6427
6428 if (er) {
6429 errorOrDestroy(stream, er);
6430 process.nextTick(cb, er);
6431 return false;
6432 }
6433
6434 return true;
6435}
6436
6437Writable.prototype.write = function (chunk, encoding, cb) {
6438 var state = this._writableState;
6439 var ret = false;
6440
6441 var isBuf = !state.objectMode && _isUint8Array(chunk);
6442
6443 if (isBuf && !Buffer.isBuffer(chunk)) {
6444 chunk = _uint8ArrayToBuffer(chunk);
6445 }
6446
6447 if (typeof encoding === 'function') {
6448 cb = encoding;
6449 encoding = null;
6450 }
6451
6452 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
6453 if (typeof cb !== 'function') cb = nop;
6454 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
6455 state.pendingcb++;
6456 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
6457 }
6458 return ret;
6459};
6460
6461Writable.prototype.cork = function () {
6462 this._writableState.corked++;
6463};
6464
6465Writable.prototype.uncork = function () {
6466 var state = this._writableState;
6467
6468 if (state.corked) {
6469 state.corked--;
6470 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
6471 }
6472};
6473
6474Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
6475 // node::ParseEncoding() requires lower case.
6476 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
6477 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
6478 this._writableState.defaultEncoding = encoding;
6479 return this;
6480};
6481
6482Object.defineProperty(Writable.prototype, 'writableBuffer', {
6483 // making it explicit this property is not enumerable
6484 // because otherwise some prototype manipulation in
6485 // userland will fail
6486 enumerable: false,
6487 get: function get() {
6488 return this._writableState && this._writableState.getBuffer();
6489 }
6490});
6491
6492function decodeChunk(state, chunk, encoding) {
6493 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
6494 chunk = Buffer.from(chunk, encoding);
6495 }
6496
6497 return chunk;
6498}
6499
6500Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
6501 // making it explicit this property is not enumerable
6502 // because otherwise some prototype manipulation in
6503 // userland will fail
6504 enumerable: false,
6505 get: function get() {
6506 return this._writableState.highWaterMark;
6507 }
6508}); // if we're already writing something, then just put this
6509// in the queue, and wait our turn. Otherwise, call _write
6510// If we return false, then we need a drain event, so set that flag.
6511
6512function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
6513 if (!isBuf) {
6514 var newChunk = decodeChunk(state, chunk, encoding);
6515
6516 if (chunk !== newChunk) {
6517 isBuf = true;
6518 encoding = 'buffer';
6519 chunk = newChunk;
6520 }
6521 }
6522
6523 var len = state.objectMode ? 1 : chunk.length;
6524 state.length += len;
6525 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
6526
6527 if (!ret) state.needDrain = true;
6528
6529 if (state.writing || state.corked) {
6530 var last = state.lastBufferedRequest;
6531 state.lastBufferedRequest = {
6532 chunk: chunk,
6533 encoding: encoding,
6534 isBuf: isBuf,
6535 callback: cb,
6536 next: null
6537 };
6538
6539 if (last) {
6540 last.next = state.lastBufferedRequest;
6541 } else {
6542 state.bufferedRequest = state.lastBufferedRequest;
6543 }
6544
6545 state.bufferedRequestCount += 1;
6546 } else {
6547 doWrite(stream, state, false, len, chunk, encoding, cb);
6548 }
6549
6550 return ret;
6551}
6552
6553function doWrite(stream, state, writev, len, chunk, encoding, cb) {
6554 state.writelen = len;
6555 state.writecb = cb;
6556 state.writing = true;
6557 state.sync = true;
6558 if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
6559 state.sync = false;
6560}
6561
6562function onwriteError(stream, state, sync, er, cb) {
6563 --state.pendingcb;
6564
6565 if (sync) {
6566 // defer the callback if we are being called synchronously
6567 // to avoid piling up things on the stack
6568 process.nextTick(cb, er); // this can emit finish, and it will always happen
6569 // after error
6570
6571 process.nextTick(finishMaybe, stream, state);
6572 stream._writableState.errorEmitted = true;
6573 errorOrDestroy(stream, er);
6574 } else {
6575 // the caller expect this to happen before if
6576 // it is async
6577 cb(er);
6578 stream._writableState.errorEmitted = true;
6579 errorOrDestroy(stream, er); // this can emit finish, but finish must
6580 // always follow error
6581
6582 finishMaybe(stream, state);
6583 }
6584}
6585
6586function onwriteStateUpdate(state) {
6587 state.writing = false;
6588 state.writecb = null;
6589 state.length -= state.writelen;
6590 state.writelen = 0;
6591}
6592
6593function onwrite(stream, er) {
6594 var state = stream._writableState;
6595 var sync = state.sync;
6596 var cb = state.writecb;
6597 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
6598 onwriteStateUpdate(state);
6599 if (er) onwriteError(stream, state, sync, er, cb);else {
6600 // Check if we're actually ready to finish, but don't emit yet
6601 var finished = needFinish(state) || stream.destroyed;
6602
6603 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
6604 clearBuffer(stream, state);
6605 }
6606
6607 if (sync) {
6608 process.nextTick(afterWrite, stream, state, finished, cb);
6609 } else {
6610 afterWrite(stream, state, finished, cb);
6611 }
6612 }
6613}
6614
6615function afterWrite(stream, state, finished, cb) {
6616 if (!finished) onwriteDrain(stream, state);
6617 state.pendingcb--;
6618 cb();
6619 finishMaybe(stream, state);
6620} // Must force callback to be called on nextTick, so that we don't
6621// emit 'drain' before the write() consumer gets the 'false' return
6622// value, and has a chance to attach a 'drain' listener.
6623
6624
6625function onwriteDrain(stream, state) {
6626 if (state.length === 0 && state.needDrain) {
6627 state.needDrain = false;
6628 stream.emit('drain');
6629 }
6630} // if there's something in the buffer waiting, then process it
6631
6632
6633function clearBuffer(stream, state) {
6634 state.bufferProcessing = true;
6635 var entry = state.bufferedRequest;
6636
6637 if (stream._writev && entry && entry.next) {
6638 // Fast case, write everything using _writev()
6639 var l = state.bufferedRequestCount;
6640 var buffer = new Array(l);
6641 var holder = state.corkedRequestsFree;
6642 holder.entry = entry;
6643 var count = 0;
6644 var allBuffers = true;
6645
6646 while (entry) {
6647 buffer[count] = entry;
6648 if (!entry.isBuf) allBuffers = false;
6649 entry = entry.next;
6650 count += 1;
6651 }
6652
6653 buffer.allBuffers = allBuffers;
6654 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
6655 // as the hot path ends with doWrite
6656
6657 state.pendingcb++;
6658 state.lastBufferedRequest = null;
6659
6660 if (holder.next) {
6661 state.corkedRequestsFree = holder.next;
6662 holder.next = null;
6663 } else {
6664 state.corkedRequestsFree = new CorkedRequest(state);
6665 }
6666
6667 state.bufferedRequestCount = 0;
6668 } else {
6669 // Slow case, write chunks one-by-one
6670 while (entry) {
6671 var chunk = entry.chunk;
6672 var encoding = entry.encoding;
6673 var cb = entry.callback;
6674 var len = state.objectMode ? 1 : chunk.length;
6675 doWrite(stream, state, false, len, chunk, encoding, cb);
6676 entry = entry.next;
6677 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
6678 // it means that we need to wait until it does.
6679 // also, that means that the chunk and cb are currently
6680 // being processed, so move the buffer counter past them.
6681
6682 if (state.writing) {
6683 break;
6684 }
6685 }
6686
6687 if (entry === null) state.lastBufferedRequest = null;
6688 }
6689
6690 state.bufferedRequest = entry;
6691 state.bufferProcessing = false;
6692}
6693
6694Writable.prototype._write = function (chunk, encoding, cb) {
6695 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
6696};
6697
6698Writable.prototype._writev = null;
6699
6700Writable.prototype.end = function (chunk, encoding, cb) {
6701 var state = this._writableState;
6702
6703 if (typeof chunk === 'function') {
6704 cb = chunk;
6705 chunk = null;
6706 encoding = null;
6707 } else if (typeof encoding === 'function') {
6708 cb = encoding;
6709 encoding = null;
6710 }
6711
6712 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
6713
6714 if (state.corked) {
6715 state.corked = 1;
6716 this.uncork();
6717 } // ignore unnecessary end() calls.
6718
6719
6720 if (!state.ending) endWritable(this, state, cb);
6721 return this;
6722};
6723
6724Object.defineProperty(Writable.prototype, 'writableLength', {
6725 // making it explicit this property is not enumerable
6726 // because otherwise some prototype manipulation in
6727 // userland will fail
6728 enumerable: false,
6729 get: function get() {
6730 return this._writableState.length;
6731 }
6732});
6733
6734function needFinish(state) {
6735 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
6736}
6737
6738function callFinal(stream, state) {
6739 stream._final(function (err) {
6740 state.pendingcb--;
6741
6742 if (err) {
6743 errorOrDestroy(stream, err);
6744 }
6745
6746 state.prefinished = true;
6747 stream.emit('prefinish');
6748 finishMaybe(stream, state);
6749 });
6750}
6751
6752function prefinish(stream, state) {
6753 if (!state.prefinished && !state.finalCalled) {
6754 if (typeof stream._final === 'function' && !state.destroyed) {
6755 state.pendingcb++;
6756 state.finalCalled = true;
6757 process.nextTick(callFinal, stream, state);
6758 } else {
6759 state.prefinished = true;
6760 stream.emit('prefinish');
6761 }
6762 }
6763}
6764
6765function finishMaybe(stream, state) {
6766 var need = needFinish(state);
6767
6768 if (need) {
6769 prefinish(stream, state);
6770
6771 if (state.pendingcb === 0) {
6772 state.finished = true;
6773 stream.emit('finish');
6774
6775 if (state.autoDestroy) {
6776 // In case of duplex streams we need a way to detect
6777 // if the readable side is ready for autoDestroy as well
6778 var rState = stream._readableState;
6779
6780 if (!rState || rState.autoDestroy && rState.endEmitted) {
6781 stream.destroy();
6782 }
6783 }
6784 }
6785 }
6786
6787 return need;
6788}
6789
6790function endWritable(stream, state, cb) {
6791 state.ending = true;
6792 finishMaybe(stream, state);
6793
6794 if (cb) {
6795 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
6796 }
6797
6798 state.ended = true;
6799 stream.writable = false;
6800}
6801
6802function onCorkedFinish(corkReq, state, err) {
6803 var entry = corkReq.entry;
6804 corkReq.entry = null;
6805
6806 while (entry) {
6807 var cb = entry.callback;
6808 state.pendingcb--;
6809 cb(err);
6810 entry = entry.next;
6811 } // reuse the free corkReq.
6812
6813
6814 state.corkedRequestsFree.next = corkReq;
6815}
6816
6817Object.defineProperty(Writable.prototype, 'destroyed', {
6818 // making it explicit this property is not enumerable
6819 // because otherwise some prototype manipulation in
6820 // userland will fail
6821 enumerable: false,
6822 get: function get() {
6823 if (this._writableState === undefined) {
6824 return false;
6825 }
6826
6827 return this._writableState.destroyed;
6828 },
6829 set: function set(value) {
6830 // we ignore the value if the stream
6831 // has not been initialized yet
6832 if (!this._writableState) {
6833 return;
6834 } // backward compatibility, the user is explicitly
6835 // managing destroyed
6836
6837
6838 this._writableState.destroyed = value;
6839 }
6840});
6841Writable.prototype.destroy = destroyImpl.destroy;
6842Writable.prototype._undestroy = destroyImpl.undestroy;
6843
6844Writable.prototype._destroy = function (err, cb) {
6845 cb(err);
6846};
6847}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6848},{"../errors":22,"./_stream_duplex":23,"./internal/streams/destroy":30,"./internal/streams/state":34,"./internal/streams/stream":35,"_process":10,"buffer":3,"inherits":8,"util-deprecate":40}],28:[function(require,module,exports){
6849(function (process){(function (){
6850'use strict';
6851
6852var _Object$setPrototypeO;
6853
6854function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6855
6856var finished = require('./end-of-stream');
6857
6858var kLastResolve = Symbol('lastResolve');
6859var kLastReject = Symbol('lastReject');
6860var kError = Symbol('error');
6861var kEnded = Symbol('ended');
6862var kLastPromise = Symbol('lastPromise');
6863var kHandlePromise = Symbol('handlePromise');
6864var kStream = Symbol('stream');
6865
6866function createIterResult(value, done) {
6867 return {
6868 value: value,
6869 done: done
6870 };
6871}
6872
6873function readAndResolve(iter) {
6874 var resolve = iter[kLastResolve];
6875
6876 if (resolve !== null) {
6877 var data = iter[kStream].read(); // we defer if data is null
6878 // we can be expecting either 'end' or
6879 // 'error'
6880
6881 if (data !== null) {
6882 iter[kLastPromise] = null;
6883 iter[kLastResolve] = null;
6884 iter[kLastReject] = null;
6885 resolve(createIterResult(data, false));
6886 }
6887 }
6888}
6889
6890function onReadable(iter) {
6891 // we wait for the next tick, because it might
6892 // emit an error with process.nextTick
6893 process.nextTick(readAndResolve, iter);
6894}
6895
6896function wrapForNext(lastPromise, iter) {
6897 return function (resolve, reject) {
6898 lastPromise.then(function () {
6899 if (iter[kEnded]) {
6900 resolve(createIterResult(undefined, true));
6901 return;
6902 }
6903
6904 iter[kHandlePromise](resolve, reject);
6905 }, reject);
6906 };
6907}
6908
6909var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
6910var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
6911 get stream() {
6912 return this[kStream];
6913 },
6914
6915 next: function next() {
6916 var _this = this;
6917
6918 // if we have detected an error in the meanwhile
6919 // reject straight away
6920 var error = this[kError];
6921
6922 if (error !== null) {
6923 return Promise.reject(error);
6924 }
6925
6926 if (this[kEnded]) {
6927 return Promise.resolve(createIterResult(undefined, true));
6928 }
6929
6930 if (this[kStream].destroyed) {
6931 // We need to defer via nextTick because if .destroy(err) is
6932 // called, the error will be emitted via nextTick, and
6933 // we cannot guarantee that there is no error lingering around
6934 // waiting to be emitted.
6935 return new Promise(function (resolve, reject) {
6936 process.nextTick(function () {
6937 if (_this[kError]) {
6938 reject(_this[kError]);
6939 } else {
6940 resolve(createIterResult(undefined, true));
6941 }
6942 });
6943 });
6944 } // if we have multiple next() calls
6945 // we will wait for the previous Promise to finish
6946 // this logic is optimized to support for await loops,
6947 // where next() is only called once at a time
6948
6949
6950 var lastPromise = this[kLastPromise];
6951 var promise;
6952
6953 if (lastPromise) {
6954 promise = new Promise(wrapForNext(lastPromise, this));
6955 } else {
6956 // fast path needed to support multiple this.push()
6957 // without triggering the next() queue
6958 var data = this[kStream].read();
6959
6960 if (data !== null) {
6961 return Promise.resolve(createIterResult(data, false));
6962 }
6963
6964 promise = new Promise(this[kHandlePromise]);
6965 }
6966
6967 this[kLastPromise] = promise;
6968 return promise;
6969 }
6970}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
6971 return this;
6972}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
6973 var _this2 = this;
6974
6975 // destroy(err, cb) is a private API
6976 // we can guarantee we have that here, because we control the
6977 // Readable class this is attached to
6978 return new Promise(function (resolve, reject) {
6979 _this2[kStream].destroy(null, function (err) {
6980 if (err) {
6981 reject(err);
6982 return;
6983 }
6984
6985 resolve(createIterResult(undefined, true));
6986 });
6987 });
6988}), _Object$setPrototypeO), AsyncIteratorPrototype);
6989
6990var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
6991 var _Object$create;
6992
6993 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
6994 value: stream,
6995 writable: true
6996 }), _defineProperty(_Object$create, kLastResolve, {
6997 value: null,
6998 writable: true
6999 }), _defineProperty(_Object$create, kLastReject, {
7000 value: null,
7001 writable: true
7002 }), _defineProperty(_Object$create, kError, {
7003 value: null,
7004 writable: true
7005 }), _defineProperty(_Object$create, kEnded, {
7006 value: stream._readableState.endEmitted,
7007 writable: true
7008 }), _defineProperty(_Object$create, kHandlePromise, {
7009 value: function value(resolve, reject) {
7010 var data = iterator[kStream].read();
7011
7012 if (data) {
7013 iterator[kLastPromise] = null;
7014 iterator[kLastResolve] = null;
7015 iterator[kLastReject] = null;
7016 resolve(createIterResult(data, false));
7017 } else {
7018 iterator[kLastResolve] = resolve;
7019 iterator[kLastReject] = reject;
7020 }
7021 },
7022 writable: true
7023 }), _Object$create));
7024 iterator[kLastPromise] = null;
7025 finished(stream, function (err) {
7026 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
7027 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
7028 // returned by next() and store the error
7029
7030 if (reject !== null) {
7031 iterator[kLastPromise] = null;
7032 iterator[kLastResolve] = null;
7033 iterator[kLastReject] = null;
7034 reject(err);
7035 }
7036
7037 iterator[kError] = err;
7038 return;
7039 }
7040
7041 var resolve = iterator[kLastResolve];
7042
7043 if (resolve !== null) {
7044 iterator[kLastPromise] = null;
7045 iterator[kLastResolve] = null;
7046 iterator[kLastReject] = null;
7047 resolve(createIterResult(undefined, true));
7048 }
7049
7050 iterator[kEnded] = true;
7051 });
7052 stream.on('readable', onReadable.bind(null, iterator));
7053 return iterator;
7054};
7055
7056module.exports = createReadableStreamAsyncIterator;
7057}).call(this)}).call(this,require('_process'))
7058},{"./end-of-stream":31,"_process":10}],29:[function(require,module,exports){
7059'use strict';
7060
7061function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
7062
7063function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
7064
7065function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
7066
7067function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
7068
7069function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
7070
7071function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
7072
7073var _require = require('buffer'),
7074 Buffer = _require.Buffer;
7075
7076var _require2 = require('util'),
7077 inspect = _require2.inspect;
7078
7079var custom = inspect && inspect.custom || 'inspect';
7080
7081function copyBuffer(src, target, offset) {
7082 Buffer.prototype.copy.call(src, target, offset);
7083}
7084
7085module.exports =
7086/*#__PURE__*/
7087function () {
7088 function BufferList() {
7089 _classCallCheck(this, BufferList);
7090
7091 this.head = null;
7092 this.tail = null;
7093 this.length = 0;
7094 }
7095
7096 _createClass(BufferList, [{
7097 key: "push",
7098 value: function push(v) {
7099 var entry = {
7100 data: v,
7101 next: null
7102 };
7103 if (this.length > 0) this.tail.next = entry;else this.head = entry;
7104 this.tail = entry;
7105 ++this.length;
7106 }
7107 }, {
7108 key: "unshift",
7109 value: function unshift(v) {
7110 var entry = {
7111 data: v,
7112 next: this.head
7113 };
7114 if (this.length === 0) this.tail = entry;
7115 this.head = entry;
7116 ++this.length;
7117 }
7118 }, {
7119 key: "shift",
7120 value: function shift() {
7121 if (this.length === 0) return;
7122 var ret = this.head.data;
7123 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
7124 --this.length;
7125 return ret;
7126 }
7127 }, {
7128 key: "clear",
7129 value: function clear() {
7130 this.head = this.tail = null;
7131 this.length = 0;
7132 }
7133 }, {
7134 key: "join",
7135 value: function join(s) {
7136 if (this.length === 0) return '';
7137 var p = this.head;
7138 var ret = '' + p.data;
7139
7140 while (p = p.next) {
7141 ret += s + p.data;
7142 }
7143
7144 return ret;
7145 }
7146 }, {
7147 key: "concat",
7148 value: function concat(n) {
7149 if (this.length === 0) return Buffer.alloc(0);
7150 var ret = Buffer.allocUnsafe(n >>> 0);
7151 var p = this.head;
7152 var i = 0;
7153
7154 while (p) {
7155 copyBuffer(p.data, ret, i);
7156 i += p.data.length;
7157 p = p.next;
7158 }
7159
7160 return ret;
7161 } // Consumes a specified amount of bytes or characters from the buffered data.
7162
7163 }, {
7164 key: "consume",
7165 value: function consume(n, hasStrings) {
7166 var ret;
7167
7168 if (n < this.head.data.length) {
7169 // `slice` is the same for buffers and strings.
7170 ret = this.head.data.slice(0, n);
7171 this.head.data = this.head.data.slice(n);
7172 } else if (n === this.head.data.length) {
7173 // First chunk is a perfect match.
7174 ret = this.shift();
7175 } else {
7176 // Result spans more than one buffer.
7177 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
7178 }
7179
7180 return ret;
7181 }
7182 }, {
7183 key: "first",
7184 value: function first() {
7185 return this.head.data;
7186 } // Consumes a specified amount of characters from the buffered data.
7187
7188 }, {
7189 key: "_getString",
7190 value: function _getString(n) {
7191 var p = this.head;
7192 var c = 1;
7193 var ret = p.data;
7194 n -= ret.length;
7195
7196 while (p = p.next) {
7197 var str = p.data;
7198 var nb = n > str.length ? str.length : n;
7199 if (nb === str.length) ret += str;else ret += str.slice(0, n);
7200 n -= nb;
7201
7202 if (n === 0) {
7203 if (nb === str.length) {
7204 ++c;
7205 if (p.next) this.head = p.next;else this.head = this.tail = null;
7206 } else {
7207 this.head = p;
7208 p.data = str.slice(nb);
7209 }
7210
7211 break;
7212 }
7213
7214 ++c;
7215 }
7216
7217 this.length -= c;
7218 return ret;
7219 } // Consumes a specified amount of bytes from the buffered data.
7220
7221 }, {
7222 key: "_getBuffer",
7223 value: function _getBuffer(n) {
7224 var ret = Buffer.allocUnsafe(n);
7225 var p = this.head;
7226 var c = 1;
7227 p.data.copy(ret);
7228 n -= p.data.length;
7229
7230 while (p = p.next) {
7231 var buf = p.data;
7232 var nb = n > buf.length ? buf.length : n;
7233 buf.copy(ret, ret.length - n, 0, nb);
7234 n -= nb;
7235
7236 if (n === 0) {
7237 if (nb === buf.length) {
7238 ++c;
7239 if (p.next) this.head = p.next;else this.head = this.tail = null;
7240 } else {
7241 this.head = p;
7242 p.data = buf.slice(nb);
7243 }
7244
7245 break;
7246 }
7247
7248 ++c;
7249 }
7250
7251 this.length -= c;
7252 return ret;
7253 } // Make sure the linked list only shows the minimal necessary information.
7254
7255 }, {
7256 key: custom,
7257 value: function value(_, options) {
7258 return inspect(this, _objectSpread({}, options, {
7259 // Only inspect one level.
7260 depth: 0,
7261 // It should not recurse.
7262 customInspect: false
7263 }));
7264 }
7265 }]);
7266
7267 return BufferList;
7268}();
7269},{"buffer":3,"util":2}],30:[function(require,module,exports){
7270(function (process){(function (){
7271'use strict'; // undocumented cb() API, needed for core, not for public API
7272
7273function destroy(err, cb) {
7274 var _this = this;
7275
7276 var readableDestroyed = this._readableState && this._readableState.destroyed;
7277 var writableDestroyed = this._writableState && this._writableState.destroyed;
7278
7279 if (readableDestroyed || writableDestroyed) {
7280 if (cb) {
7281 cb(err);
7282 } else if (err) {
7283 if (!this._writableState) {
7284 process.nextTick(emitErrorNT, this, err);
7285 } else if (!this._writableState.errorEmitted) {
7286 this._writableState.errorEmitted = true;
7287 process.nextTick(emitErrorNT, this, err);
7288 }
7289 }
7290
7291 return this;
7292 } // we set destroyed to true before firing error callbacks in order
7293 // to make it re-entrance safe in case destroy() is called within callbacks
7294
7295
7296 if (this._readableState) {
7297 this._readableState.destroyed = true;
7298 } // if this is a duplex stream mark the writable part as destroyed as well
7299
7300
7301 if (this._writableState) {
7302 this._writableState.destroyed = true;
7303 }
7304
7305 this._destroy(err || null, function (err) {
7306 if (!cb && err) {
7307 if (!_this._writableState) {
7308 process.nextTick(emitErrorAndCloseNT, _this, err);
7309 } else if (!_this._writableState.errorEmitted) {
7310 _this._writableState.errorEmitted = true;
7311 process.nextTick(emitErrorAndCloseNT, _this, err);
7312 } else {
7313 process.nextTick(emitCloseNT, _this);
7314 }
7315 } else if (cb) {
7316 process.nextTick(emitCloseNT, _this);
7317 cb(err);
7318 } else {
7319 process.nextTick(emitCloseNT, _this);
7320 }
7321 });
7322
7323 return this;
7324}
7325
7326function emitErrorAndCloseNT(self, err) {
7327 emitErrorNT(self, err);
7328 emitCloseNT(self);
7329}
7330
7331function emitCloseNT(self) {
7332 if (self._writableState && !self._writableState.emitClose) return;
7333 if (self._readableState && !self._readableState.emitClose) return;
7334 self.emit('close');
7335}
7336
7337function undestroy() {
7338 if (this._readableState) {
7339 this._readableState.destroyed = false;
7340 this._readableState.reading = false;
7341 this._readableState.ended = false;
7342 this._readableState.endEmitted = false;
7343 }
7344
7345 if (this._writableState) {
7346 this._writableState.destroyed = false;
7347 this._writableState.ended = false;
7348 this._writableState.ending = false;
7349 this._writableState.finalCalled = false;
7350 this._writableState.prefinished = false;
7351 this._writableState.finished = false;
7352 this._writableState.errorEmitted = false;
7353 }
7354}
7355
7356function emitErrorNT(self, err) {
7357 self.emit('error', err);
7358}
7359
7360function errorOrDestroy(stream, err) {
7361 // We have tests that rely on errors being emitted
7362 // in the same tick, so changing this is semver major.
7363 // For now when you opt-in to autoDestroy we allow
7364 // the error to be emitted nextTick. In a future
7365 // semver major update we should change the default to this.
7366 var rState = stream._readableState;
7367 var wState = stream._writableState;
7368 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
7369}
7370
7371module.exports = {
7372 destroy: destroy,
7373 undestroy: undestroy,
7374 errorOrDestroy: errorOrDestroy
7375};
7376}).call(this)}).call(this,require('_process'))
7377},{"_process":10}],31:[function(require,module,exports){
7378// Ported from https://github.com/mafintosh/end-of-stream with
7379// permission from the author, Mathias Buus (@mafintosh).
7380'use strict';
7381
7382var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
7383
7384function once(callback) {
7385 var called = false;
7386 return function () {
7387 if (called) return;
7388 called = true;
7389
7390 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
7391 args[_key] = arguments[_key];
7392 }
7393
7394 callback.apply(this, args);
7395 };
7396}
7397
7398function noop() {}
7399
7400function isRequest(stream) {
7401 return stream.setHeader && typeof stream.abort === 'function';
7402}
7403
7404function eos(stream, opts, callback) {
7405 if (typeof opts === 'function') return eos(stream, null, opts);
7406 if (!opts) opts = {};
7407 callback = once(callback || noop);
7408 var readable = opts.readable || opts.readable !== false && stream.readable;
7409 var writable = opts.writable || opts.writable !== false && stream.writable;
7410
7411 var onlegacyfinish = function onlegacyfinish() {
7412 if (!stream.writable) onfinish();
7413 };
7414
7415 var writableEnded = stream._writableState && stream._writableState.finished;
7416
7417 var onfinish = function onfinish() {
7418 writable = false;
7419 writableEnded = true;
7420 if (!readable) callback.call(stream);
7421 };
7422
7423 var readableEnded = stream._readableState && stream._readableState.endEmitted;
7424
7425 var onend = function onend() {
7426 readable = false;
7427 readableEnded = true;
7428 if (!writable) callback.call(stream);
7429 };
7430
7431 var onerror = function onerror(err) {
7432 callback.call(stream, err);
7433 };
7434
7435 var onclose = function onclose() {
7436 var err;
7437
7438 if (readable && !readableEnded) {
7439 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
7440 return callback.call(stream, err);
7441 }
7442
7443 if (writable && !writableEnded) {
7444 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
7445 return callback.call(stream, err);
7446 }
7447 };
7448
7449 var onrequest = function onrequest() {
7450 stream.req.on('finish', onfinish);
7451 };
7452
7453 if (isRequest(stream)) {
7454 stream.on('complete', onfinish);
7455 stream.on('abort', onclose);
7456 if (stream.req) onrequest();else stream.on('request', onrequest);
7457 } else if (writable && !stream._writableState) {
7458 // legacy streams
7459 stream.on('end', onlegacyfinish);
7460 stream.on('close', onlegacyfinish);
7461 }
7462
7463 stream.on('end', onend);
7464 stream.on('finish', onfinish);
7465 if (opts.error !== false) stream.on('error', onerror);
7466 stream.on('close', onclose);
7467 return function () {
7468 stream.removeListener('complete', onfinish);
7469 stream.removeListener('abort', onclose);
7470 stream.removeListener('request', onrequest);
7471 if (stream.req) stream.req.removeListener('finish', onfinish);
7472 stream.removeListener('end', onlegacyfinish);
7473 stream.removeListener('close', onlegacyfinish);
7474 stream.removeListener('finish', onfinish);
7475 stream.removeListener('end', onend);
7476 stream.removeListener('error', onerror);
7477 stream.removeListener('close', onclose);
7478 };
7479}
7480
7481module.exports = eos;
7482},{"../../../errors":22}],32:[function(require,module,exports){
7483module.exports = function () {
7484 throw new Error('Readable.from is not available in the browser')
7485};
7486
7487},{}],33:[function(require,module,exports){
7488// Ported from https://github.com/mafintosh/pump with
7489// permission from the author, Mathias Buus (@mafintosh).
7490'use strict';
7491
7492var eos;
7493
7494function once(callback) {
7495 var called = false;
7496 return function () {
7497 if (called) return;
7498 called = true;
7499 callback.apply(void 0, arguments);
7500 };
7501}
7502
7503var _require$codes = require('../../../errors').codes,
7504 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
7505 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
7506
7507function noop(err) {
7508 // Rethrow the error if it exists to avoid swallowing it
7509 if (err) throw err;
7510}
7511
7512function isRequest(stream) {
7513 return stream.setHeader && typeof stream.abort === 'function';
7514}
7515
7516function destroyer(stream, reading, writing, callback) {
7517 callback = once(callback);
7518 var closed = false;
7519 stream.on('close', function () {
7520 closed = true;
7521 });
7522 if (eos === undefined) eos = require('./end-of-stream');
7523 eos(stream, {
7524 readable: reading,
7525 writable: writing
7526 }, function (err) {
7527 if (err) return callback(err);
7528 closed = true;
7529 callback();
7530 });
7531 var destroyed = false;
7532 return function (err) {
7533 if (closed) return;
7534 if (destroyed) return;
7535 destroyed = true; // request.destroy just do .end - .abort is what we want
7536
7537 if (isRequest(stream)) return stream.abort();
7538 if (typeof stream.destroy === 'function') return stream.destroy();
7539 callback(err || new ERR_STREAM_DESTROYED('pipe'));
7540 };
7541}
7542
7543function call(fn) {
7544 fn();
7545}
7546
7547function pipe(from, to) {
7548 return from.pipe(to);
7549}
7550
7551function popCallback(streams) {
7552 if (!streams.length) return noop;
7553 if (typeof streams[streams.length - 1] !== 'function') return noop;
7554 return streams.pop();
7555}
7556
7557function pipeline() {
7558 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
7559 streams[_key] = arguments[_key];
7560 }
7561
7562 var callback = popCallback(streams);
7563 if (Array.isArray(streams[0])) streams = streams[0];
7564
7565 if (streams.length < 2) {
7566 throw new ERR_MISSING_ARGS('streams');
7567 }
7568
7569 var error;
7570 var destroys = streams.map(function (stream, i) {
7571 var reading = i < streams.length - 1;
7572 var writing = i > 0;
7573 return destroyer(stream, reading, writing, function (err) {
7574 if (!error) error = err;
7575 if (err) destroys.forEach(call);
7576 if (reading) return;
7577 destroys.forEach(call);
7578 callback(error);
7579 });
7580 });
7581 return streams.reduce(pipe);
7582}
7583
7584module.exports = pipeline;
7585},{"../../../errors":22,"./end-of-stream":31}],34:[function(require,module,exports){
7586'use strict';
7587
7588var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
7589
7590function highWaterMarkFrom(options, isDuplex, duplexKey) {
7591 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
7592}
7593
7594function getHighWaterMark(state, options, duplexKey, isDuplex) {
7595 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
7596
7597 if (hwm != null) {
7598 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
7599 var name = isDuplex ? duplexKey : 'highWaterMark';
7600 throw new ERR_INVALID_OPT_VALUE(name, hwm);
7601 }
7602
7603 return Math.floor(hwm);
7604 } // Default value
7605
7606
7607 return state.objectMode ? 16 : 16 * 1024;
7608}
7609
7610module.exports = {
7611 getHighWaterMark: getHighWaterMark
7612};
7613},{"../../../errors":22}],35:[function(require,module,exports){
7614module.exports = require('events').EventEmitter;
7615
7616},{"events":5}],36:[function(require,module,exports){
7617exports = module.exports = require('./lib/_stream_readable.js');
7618exports.Stream = exports;
7619exports.Readable = exports;
7620exports.Writable = require('./lib/_stream_writable.js');
7621exports.Duplex = require('./lib/_stream_duplex.js');
7622exports.Transform = require('./lib/_stream_transform.js');
7623exports.PassThrough = require('./lib/_stream_passthrough.js');
7624exports.finished = require('./lib/internal/streams/end-of-stream.js');
7625exports.pipeline = require('./lib/internal/streams/pipeline.js');
7626
7627},{"./lib/_stream_duplex.js":23,"./lib/_stream_passthrough.js":24,"./lib/_stream_readable.js":25,"./lib/_stream_transform.js":26,"./lib/_stream_writable.js":27,"./lib/internal/streams/end-of-stream.js":31,"./lib/internal/streams/pipeline.js":33}],37:[function(require,module,exports){
7628// Copyright Joyent, Inc. and other Node contributors.
7629//
7630// Permission is hereby granted, free of charge, to any person obtaining a
7631// copy of this software and associated documentation files (the
7632// "Software"), to deal in the Software without restriction, including
7633// without limitation the rights to use, copy, modify, merge, publish,
7634// distribute, sublicense, and/or sell copies of the Software, and to permit
7635// persons to whom the Software is furnished to do so, subject to the
7636// following conditions:
7637//
7638// The above copyright notice and this permission notice shall be included
7639// in all copies or substantial portions of the Software.
7640//
7641// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7642// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7643// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7644// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7645// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7646// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7647// USE OR OTHER DEALINGS IN THE SOFTWARE.
7648
7649'use strict';
7650
7651/*<replacement>*/
7652
7653var Buffer = require('safe-buffer').Buffer;
7654/*</replacement>*/
7655
7656var isEncoding = Buffer.isEncoding || function (encoding) {
7657 encoding = '' + encoding;
7658 switch (encoding && encoding.toLowerCase()) {
7659 case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
7660 return true;
7661 default:
7662 return false;
7663 }
7664};
7665
7666function _normalizeEncoding(enc) {
7667 if (!enc) return 'utf8';
7668 var retried;
7669 while (true) {
7670 switch (enc) {
7671 case 'utf8':
7672 case 'utf-8':
7673 return 'utf8';
7674 case 'ucs2':
7675 case 'ucs-2':
7676 case 'utf16le':
7677 case 'utf-16le':
7678 return 'utf16le';
7679 case 'latin1':
7680 case 'binary':
7681 return 'latin1';
7682 case 'base64':
7683 case 'ascii':
7684 case 'hex':
7685 return enc;
7686 default:
7687 if (retried) return; // undefined
7688 enc = ('' + enc).toLowerCase();
7689 retried = true;
7690 }
7691 }
7692};
7693
7694// Do not cache `Buffer.isEncoding` when checking encoding names as some
7695// modules monkey-patch it to support additional encodings
7696function normalizeEncoding(enc) {
7697 var nenc = _normalizeEncoding(enc);
7698 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
7699 return nenc || enc;
7700}
7701
7702// StringDecoder provides an interface for efficiently splitting a series of
7703// buffers into a series of JS strings without breaking apart multi-byte
7704// characters.
7705exports.StringDecoder = StringDecoder;
7706function StringDecoder(encoding) {
7707 this.encoding = normalizeEncoding(encoding);
7708 var nb;
7709 switch (this.encoding) {
7710 case 'utf16le':
7711 this.text = utf16Text;
7712 this.end = utf16End;
7713 nb = 4;
7714 break;
7715 case 'utf8':
7716 this.fillLast = utf8FillLast;
7717 nb = 4;
7718 break;
7719 case 'base64':
7720 this.text = base64Text;
7721 this.end = base64End;
7722 nb = 3;
7723 break;
7724 default:
7725 this.write = simpleWrite;
7726 this.end = simpleEnd;
7727 return;
7728 }
7729 this.lastNeed = 0;
7730 this.lastTotal = 0;
7731 this.lastChar = Buffer.allocUnsafe(nb);
7732}
7733
7734StringDecoder.prototype.write = function (buf) {
7735 if (buf.length === 0) return '';
7736 var r;
7737 var i;
7738 if (this.lastNeed) {
7739 r = this.fillLast(buf);
7740 if (r === undefined) return '';
7741 i = this.lastNeed;
7742 this.lastNeed = 0;
7743 } else {
7744 i = 0;
7745 }
7746 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
7747 return r || '';
7748};
7749
7750StringDecoder.prototype.end = utf8End;
7751
7752// Returns only complete characters in a Buffer
7753StringDecoder.prototype.text = utf8Text;
7754
7755// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
7756StringDecoder.prototype.fillLast = function (buf) {
7757 if (this.lastNeed <= buf.length) {
7758 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
7759 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
7760 }
7761 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
7762 this.lastNeed -= buf.length;
7763};
7764
7765// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
7766// continuation byte. If an invalid byte is detected, -2 is returned.
7767function utf8CheckByte(byte) {
7768 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
7769 return byte >> 6 === 0x02 ? -1 : -2;
7770}
7771
7772// Checks at most 3 bytes at the end of a Buffer in order to detect an
7773// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
7774// needed to complete the UTF-8 character (if applicable) are returned.
7775function utf8CheckIncomplete(self, buf, i) {
7776 var j = buf.length - 1;
7777 if (j < i) return 0;
7778 var nb = utf8CheckByte(buf[j]);
7779 if (nb >= 0) {
7780 if (nb > 0) self.lastNeed = nb - 1;
7781 return nb;
7782 }
7783 if (--j < i || nb === -2) return 0;
7784 nb = utf8CheckByte(buf[j]);
7785 if (nb >= 0) {
7786 if (nb > 0) self.lastNeed = nb - 2;
7787 return nb;
7788 }
7789 if (--j < i || nb === -2) return 0;
7790 nb = utf8CheckByte(buf[j]);
7791 if (nb >= 0) {
7792 if (nb > 0) {
7793 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
7794 }
7795 return nb;
7796 }
7797 return 0;
7798}
7799
7800// Validates as many continuation bytes for a multi-byte UTF-8 character as
7801// needed or are available. If we see a non-continuation byte where we expect
7802// one, we "replace" the validated continuation bytes we've seen so far with
7803// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
7804// behavior. The continuation byte check is included three times in the case
7805// where all of the continuation bytes for a character exist in the same buffer.
7806// It is also done this way as a slight performance increase instead of using a
7807// loop.
7808function utf8CheckExtraBytes(self, buf, p) {
7809 if ((buf[0] & 0xC0) !== 0x80) {
7810 self.lastNeed = 0;
7811 return '\ufffd';
7812 }
7813 if (self.lastNeed > 1 && buf.length > 1) {
7814 if ((buf[1] & 0xC0) !== 0x80) {
7815 self.lastNeed = 1;
7816 return '\ufffd';
7817 }
7818 if (self.lastNeed > 2 && buf.length > 2) {
7819 if ((buf[2] & 0xC0) !== 0x80) {
7820 self.lastNeed = 2;
7821 return '\ufffd';
7822 }
7823 }
7824 }
7825}
7826
7827// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
7828function utf8FillLast(buf) {
7829 var p = this.lastTotal - this.lastNeed;
7830 var r = utf8CheckExtraBytes(this, buf, p);
7831 if (r !== undefined) return r;
7832 if (this.lastNeed <= buf.length) {
7833 buf.copy(this.lastChar, p, 0, this.lastNeed);
7834 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
7835 }
7836 buf.copy(this.lastChar, p, 0, buf.length);
7837 this.lastNeed -= buf.length;
7838}
7839
7840// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
7841// partial character, the character's bytes are buffered until the required
7842// number of bytes are available.
7843function utf8Text(buf, i) {
7844 var total = utf8CheckIncomplete(this, buf, i);
7845 if (!this.lastNeed) return buf.toString('utf8', i);
7846 this.lastTotal = total;
7847 var end = buf.length - (total - this.lastNeed);
7848 buf.copy(this.lastChar, 0, end);
7849 return buf.toString('utf8', i, end);
7850}
7851
7852// For UTF-8, a replacement character is added when ending on a partial
7853// character.
7854function utf8End(buf) {
7855 var r = buf && buf.length ? this.write(buf) : '';
7856 if (this.lastNeed) return r + '\ufffd';
7857 return r;
7858}
7859
7860// UTF-16LE typically needs two bytes per character, but even if we have an even
7861// number of bytes available, we need to check if we end on a leading/high
7862// surrogate. In that case, we need to wait for the next two bytes in order to
7863// decode the last character properly.
7864function utf16Text(buf, i) {
7865 if ((buf.length - i) % 2 === 0) {
7866 var r = buf.toString('utf16le', i);
7867 if (r) {
7868 var c = r.charCodeAt(r.length - 1);
7869 if (c >= 0xD800 && c <= 0xDBFF) {
7870 this.lastNeed = 2;
7871 this.lastTotal = 4;
7872 this.lastChar[0] = buf[buf.length - 2];
7873 this.lastChar[1] = buf[buf.length - 1];
7874 return r.slice(0, -1);
7875 }
7876 }
7877 return r;
7878 }
7879 this.lastNeed = 1;
7880 this.lastTotal = 2;
7881 this.lastChar[0] = buf[buf.length - 1];
7882 return buf.toString('utf16le', i, buf.length - 1);
7883}
7884
7885// For UTF-16LE we do not explicitly append special replacement characters if we
7886// end on a partial character, we simply let v8 handle that.
7887function utf16End(buf) {
7888 var r = buf && buf.length ? this.write(buf) : '';
7889 if (this.lastNeed) {
7890 var end = this.lastTotal - this.lastNeed;
7891 return r + this.lastChar.toString('utf16le', 0, end);
7892 }
7893 return r;
7894}
7895
7896function base64Text(buf, i) {
7897 var n = (buf.length - i) % 3;
7898 if (n === 0) return buf.toString('base64', i);
7899 this.lastNeed = 3 - n;
7900 this.lastTotal = 3;
7901 if (n === 1) {
7902 this.lastChar[0] = buf[buf.length - 1];
7903 } else {
7904 this.lastChar[0] = buf[buf.length - 2];
7905 this.lastChar[1] = buf[buf.length - 1];
7906 }
7907 return buf.toString('base64', i, buf.length - n);
7908}
7909
7910function base64End(buf) {
7911 var r = buf && buf.length ? this.write(buf) : '';
7912 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
7913 return r;
7914}
7915
7916// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
7917function simpleWrite(buf) {
7918 return buf.toString(this.encoding);
7919}
7920
7921function simpleEnd(buf) {
7922 return buf && buf.length ? this.write(buf) : '';
7923}
7924},{"safe-buffer":15}],38:[function(require,module,exports){
7925// Copyright Joyent, Inc. and other Node contributors.
7926//
7927// Permission is hereby granted, free of charge, to any person obtaining a
7928// copy of this software and associated documentation files (the
7929// "Software"), to deal in the Software without restriction, including
7930// without limitation the rights to use, copy, modify, merge, publish,
7931// distribute, sublicense, and/or sell copies of the Software, and to permit
7932// persons to whom the Software is furnished to do so, subject to the
7933// following conditions:
7934//
7935// The above copyright notice and this permission notice shall be included
7936// in all copies or substantial portions of the Software.
7937//
7938// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7939// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7940// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7941// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7942// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7943// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7944// USE OR OTHER DEALINGS IN THE SOFTWARE.
7945
7946'use strict';
7947
7948var punycode = require('punycode');
7949var util = require('./util');
7950
7951exports.parse = urlParse;
7952exports.resolve = urlResolve;
7953exports.resolveObject = urlResolveObject;
7954exports.format = urlFormat;
7955
7956exports.Url = Url;
7957
7958function Url() {
7959 this.protocol = null;
7960 this.slashes = null;
7961 this.auth = null;
7962 this.host = null;
7963 this.port = null;
7964 this.hostname = null;
7965 this.hash = null;
7966 this.search = null;
7967 this.query = null;
7968 this.pathname = null;
7969 this.path = null;
7970 this.href = null;
7971}
7972
7973// Reference: RFC 3986, RFC 1808, RFC 2396
7974
7975// define these here so at least they only have to be
7976// compiled once on the first module load.
7977var protocolPattern = /^([a-z0-9.+-]+:)/i,
7978 portPattern = /:[0-9]*$/,
7979
7980 // Special case for a simple path URL
7981 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
7982
7983 // RFC 2396: characters reserved for delimiting URLs.
7984 // We actually just auto-escape these.
7985 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
7986
7987 // RFC 2396: characters not allowed for various reasons.
7988 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
7989
7990 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
7991 autoEscape = ['\''].concat(unwise),
7992 // Characters that are never ever allowed in a hostname.
7993 // Note that any invalid chars are also handled, but these
7994 // are the ones that are *expected* to be seen, so we fast-path
7995 // them.
7996 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
7997 hostEndingChars = ['/', '?', '#'],
7998 hostnameMaxLen = 255,
7999 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
8000 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
8001 // protocols that can allow "unsafe" and "unwise" chars.
8002 unsafeProtocol = {
8003 'javascript': true,
8004 'javascript:': true
8005 },
8006 // protocols that never have a hostname.
8007 hostlessProtocol = {
8008 'javascript': true,
8009 'javascript:': true
8010 },
8011 // protocols that always contain a // bit.
8012 slashedProtocol = {
8013 'http': true,
8014 'https': true,
8015 'ftp': true,
8016 'gopher': true,
8017 'file': true,
8018 'http:': true,
8019 'https:': true,
8020 'ftp:': true,
8021 'gopher:': true,
8022 'file:': true
8023 },
8024 querystring = require('querystring');
8025
8026function urlParse(url, parseQueryString, slashesDenoteHost) {
8027 if (url && util.isObject(url) && url instanceof Url) return url;
8028
8029 var u = new Url;
8030 u.parse(url, parseQueryString, slashesDenoteHost);
8031 return u;
8032}
8033
8034Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
8035 if (!util.isString(url)) {
8036 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
8037 }
8038
8039 // Copy chrome, IE, opera backslash-handling behavior.
8040 // Back slashes before the query string get converted to forward slashes
8041 // See: https://code.google.com/p/chromium/issues/detail?id=25916
8042 var queryIndex = url.indexOf('?'),
8043 splitter =
8044 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
8045 uSplit = url.split(splitter),
8046 slashRegex = /\\/g;
8047 uSplit[0] = uSplit[0].replace(slashRegex, '/');
8048 url = uSplit.join(splitter);
8049
8050 var rest = url;
8051
8052 // trim before proceeding.
8053 // This is to support parse stuff like " http://foo.com \n"
8054 rest = rest.trim();
8055
8056 if (!slashesDenoteHost && url.split('#').length === 1) {
8057 // Try fast path regexp
8058 var simplePath = simplePathPattern.exec(rest);
8059 if (simplePath) {
8060 this.path = rest;
8061 this.href = rest;
8062 this.pathname = simplePath[1];
8063 if (simplePath[2]) {
8064 this.search = simplePath[2];
8065 if (parseQueryString) {
8066 this.query = querystring.parse(this.search.substr(1));
8067 } else {
8068 this.query = this.search.substr(1);
8069 }
8070 } else if (parseQueryString) {
8071 this.search = '';
8072 this.query = {};
8073 }
8074 return this;
8075 }
8076 }
8077
8078 var proto = protocolPattern.exec(rest);
8079 if (proto) {
8080 proto = proto[0];
8081 var lowerProto = proto.toLowerCase();
8082 this.protocol = lowerProto;
8083 rest = rest.substr(proto.length);
8084 }
8085
8086 // figure out if it's got a host
8087 // user@server is *always* interpreted as a hostname, and url
8088 // resolution will treat //foo/bar as host=foo,path=bar because that's
8089 // how the browser resolves relative URLs.
8090 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
8091 var slashes = rest.substr(0, 2) === '//';
8092 if (slashes && !(proto && hostlessProtocol[proto])) {
8093 rest = rest.substr(2);
8094 this.slashes = true;
8095 }
8096 }
8097
8098 if (!hostlessProtocol[proto] &&
8099 (slashes || (proto && !slashedProtocol[proto]))) {
8100
8101 // there's a hostname.
8102 // the first instance of /, ?, ;, or # ends the host.
8103 //
8104 // If there is an @ in the hostname, then non-host chars *are* allowed
8105 // to the left of the last @ sign, unless some host-ending character
8106 // comes *before* the @-sign.
8107 // URLs are obnoxious.
8108 //
8109 // ex:
8110 // http://a@b@c/ => user:a@b host:c
8111 // http://a@b?@c => user:a host:c path:/?@c
8112
8113 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
8114 // Review our test case against browsers more comprehensively.
8115
8116 // find the first instance of any hostEndingChars
8117 var hostEnd = -1;
8118 for (var i = 0; i < hostEndingChars.length; i++) {
8119 var hec = rest.indexOf(hostEndingChars[i]);
8120 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
8121 hostEnd = hec;
8122 }
8123
8124 // at this point, either we have an explicit point where the
8125 // auth portion cannot go past, or the last @ char is the decider.
8126 var auth, atSign;
8127 if (hostEnd === -1) {
8128 // atSign can be anywhere.
8129 atSign = rest.lastIndexOf('@');
8130 } else {
8131 // atSign must be in auth portion.
8132 // http://a@b/c@d => host:b auth:a path:/c@d
8133 atSign = rest.lastIndexOf('@', hostEnd);
8134 }
8135
8136 // Now we have a portion which is definitely the auth.
8137 // Pull that off.
8138 if (atSign !== -1) {
8139 auth = rest.slice(0, atSign);
8140 rest = rest.slice(atSign + 1);
8141 this.auth = decodeURIComponent(auth);
8142 }
8143
8144 // the host is the remaining to the left of the first non-host char
8145 hostEnd = -1;
8146 for (var i = 0; i < nonHostChars.length; i++) {
8147 var hec = rest.indexOf(nonHostChars[i]);
8148 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
8149 hostEnd = hec;
8150 }
8151 // if we still have not hit it, then the entire thing is a host.
8152 if (hostEnd === -1)
8153 hostEnd = rest.length;
8154
8155 this.host = rest.slice(0, hostEnd);
8156 rest = rest.slice(hostEnd);
8157
8158 // pull out port.
8159 this.parseHost();
8160
8161 // we've indicated that there is a hostname,
8162 // so even if it's empty, it has to be present.
8163 this.hostname = this.hostname || '';
8164
8165 // if hostname begins with [ and ends with ]
8166 // assume that it's an IPv6 address.
8167 var ipv6Hostname = this.hostname[0] === '[' &&
8168 this.hostname[this.hostname.length - 1] === ']';
8169
8170 // validate a little.
8171 if (!ipv6Hostname) {
8172 var hostparts = this.hostname.split(/\./);
8173 for (var i = 0, l = hostparts.length; i < l; i++) {
8174 var part = hostparts[i];
8175 if (!part) continue;
8176 if (!part.match(hostnamePartPattern)) {
8177 var newpart = '';
8178 for (var j = 0, k = part.length; j < k; j++) {
8179 if (part.charCodeAt(j) > 127) {
8180 // we replace non-ASCII char with a temporary placeholder
8181 // we need this to make sure size of hostname is not
8182 // broken by replacing non-ASCII by nothing
8183 newpart += 'x';
8184 } else {
8185 newpart += part[j];
8186 }
8187 }
8188 // we test again with ASCII char only
8189 if (!newpart.match(hostnamePartPattern)) {
8190 var validParts = hostparts.slice(0, i);
8191 var notHost = hostparts.slice(i + 1);
8192 var bit = part.match(hostnamePartStart);
8193 if (bit) {
8194 validParts.push(bit[1]);
8195 notHost.unshift(bit[2]);
8196 }
8197 if (notHost.length) {
8198 rest = '/' + notHost.join('.') + rest;
8199 }
8200 this.hostname = validParts.join('.');
8201 break;
8202 }
8203 }
8204 }
8205 }
8206
8207 if (this.hostname.length > hostnameMaxLen) {
8208 this.hostname = '';
8209 } else {
8210 // hostnames are always lower case.
8211 this.hostname = this.hostname.toLowerCase();
8212 }
8213
8214 if (!ipv6Hostname) {
8215 // IDNA Support: Returns a punycoded representation of "domain".
8216 // It only converts parts of the domain name that
8217 // have non-ASCII characters, i.e. it doesn't matter if
8218 // you call it with a domain that already is ASCII-only.
8219 this.hostname = punycode.toASCII(this.hostname);
8220 }
8221
8222 var p = this.port ? ':' + this.port : '';
8223 var h = this.hostname || '';
8224 this.host = h + p;
8225 this.href += this.host;
8226
8227 // strip [ and ] from the hostname
8228 // the host field still retains them, though
8229 if (ipv6Hostname) {
8230 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
8231 if (rest[0] !== '/') {
8232 rest = '/' + rest;
8233 }
8234 }
8235 }
8236
8237 // now rest is set to the post-host stuff.
8238 // chop off any delim chars.
8239 if (!unsafeProtocol[lowerProto]) {
8240
8241 // First, make 100% sure that any "autoEscape" chars get
8242 // escaped, even if encodeURIComponent doesn't think they
8243 // need to be.
8244 for (var i = 0, l = autoEscape.length; i < l; i++) {
8245 var ae = autoEscape[i];
8246 if (rest.indexOf(ae) === -1)
8247 continue;
8248 var esc = encodeURIComponent(ae);
8249 if (esc === ae) {
8250 esc = escape(ae);
8251 }
8252 rest = rest.split(ae).join(esc);
8253 }
8254 }
8255
8256
8257 // chop off from the tail first.
8258 var hash = rest.indexOf('#');
8259 if (hash !== -1) {
8260 // got a fragment string.
8261 this.hash = rest.substr(hash);
8262 rest = rest.slice(0, hash);
8263 }
8264 var qm = rest.indexOf('?');
8265 if (qm !== -1) {
8266 this.search = rest.substr(qm);
8267 this.query = rest.substr(qm + 1);
8268 if (parseQueryString) {
8269 this.query = querystring.parse(this.query);
8270 }
8271 rest = rest.slice(0, qm);
8272 } else if (parseQueryString) {
8273 // no query string, but parseQueryString still requested
8274 this.search = '';
8275 this.query = {};
8276 }
8277 if (rest) this.pathname = rest;
8278 if (slashedProtocol[lowerProto] &&
8279 this.hostname && !this.pathname) {
8280 this.pathname = '/';
8281 }
8282
8283 //to support http.request
8284 if (this.pathname || this.search) {
8285 var p = this.pathname || '';
8286 var s = this.search || '';
8287 this.path = p + s;
8288 }
8289
8290 // finally, reconstruct the href based on what has been validated.
8291 this.href = this.format();
8292 return this;
8293};
8294
8295// format a parsed object into a url string
8296function urlFormat(obj) {
8297 // ensure it's an object, and not a string url.
8298 // If it's an obj, this is a no-op.
8299 // this way, you can call url_format() on strings
8300 // to clean up potentially wonky urls.
8301 if (util.isString(obj)) obj = urlParse(obj);
8302 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
8303 return obj.format();
8304}
8305
8306Url.prototype.format = function() {
8307 var auth = this.auth || '';
8308 if (auth) {
8309 auth = encodeURIComponent(auth);
8310 auth = auth.replace(/%3A/i, ':');
8311 auth += '@';
8312 }
8313
8314 var protocol = this.protocol || '',
8315 pathname = this.pathname || '',
8316 hash = this.hash || '',
8317 host = false,
8318 query = '';
8319
8320 if (this.host) {
8321 host = auth + this.host;
8322 } else if (this.hostname) {
8323 host = auth + (this.hostname.indexOf(':') === -1 ?
8324 this.hostname :
8325 '[' + this.hostname + ']');
8326 if (this.port) {
8327 host += ':' + this.port;
8328 }
8329 }
8330
8331 if (this.query &&
8332 util.isObject(this.query) &&
8333 Object.keys(this.query).length) {
8334 query = querystring.stringify(this.query);
8335 }
8336
8337 var search = this.search || (query && ('?' + query)) || '';
8338
8339 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
8340
8341 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
8342 // unless they had them to begin with.
8343 if (this.slashes ||
8344 (!protocol || slashedProtocol[protocol]) && host !== false) {
8345 host = '//' + (host || '');
8346 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
8347 } else if (!host) {
8348 host = '';
8349 }
8350
8351 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
8352 if (search && search.charAt(0) !== '?') search = '?' + search;
8353
8354 pathname = pathname.replace(/[?#]/g, function(match) {
8355 return encodeURIComponent(match);
8356 });
8357 search = search.replace('#', '%23');
8358
8359 return protocol + host + pathname + search + hash;
8360};
8361
8362function urlResolve(source, relative) {
8363 return urlParse(source, false, true).resolve(relative);
8364}
8365
8366Url.prototype.resolve = function(relative) {
8367 return this.resolveObject(urlParse(relative, false, true)).format();
8368};
8369
8370function urlResolveObject(source, relative) {
8371 if (!source) return relative;
8372 return urlParse(source, false, true).resolveObject(relative);
8373}
8374
8375Url.prototype.resolveObject = function(relative) {
8376 if (util.isString(relative)) {
8377 var rel = new Url();
8378 rel.parse(relative, false, true);
8379 relative = rel;
8380 }
8381
8382 var result = new Url();
8383 var tkeys = Object.keys(this);
8384 for (var tk = 0; tk < tkeys.length; tk++) {
8385 var tkey = tkeys[tk];
8386 result[tkey] = this[tkey];
8387 }
8388
8389 // hash is always overridden, no matter what.
8390 // even href="" will remove it.
8391 result.hash = relative.hash;
8392
8393 // if the relative url is empty, then there's nothing left to do here.
8394 if (relative.href === '') {
8395 result.href = result.format();
8396 return result;
8397 }
8398
8399 // hrefs like //foo/bar always cut to the protocol.
8400 if (relative.slashes && !relative.protocol) {
8401 // take everything except the protocol from relative
8402 var rkeys = Object.keys(relative);
8403 for (var rk = 0; rk < rkeys.length; rk++) {
8404 var rkey = rkeys[rk];
8405 if (rkey !== 'protocol')
8406 result[rkey] = relative[rkey];
8407 }
8408
8409 //urlParse appends trailing / to urls like http://www.example.com
8410 if (slashedProtocol[result.protocol] &&
8411 result.hostname && !result.pathname) {
8412 result.path = result.pathname = '/';
8413 }
8414
8415 result.href = result.format();
8416 return result;
8417 }
8418
8419 if (relative.protocol && relative.protocol !== result.protocol) {
8420 // if it's a known url protocol, then changing
8421 // the protocol does weird things
8422 // first, if it's not file:, then we MUST have a host,
8423 // and if there was a path
8424 // to begin with, then we MUST have a path.
8425 // if it is file:, then the host is dropped,
8426 // because that's known to be hostless.
8427 // anything else is assumed to be absolute.
8428 if (!slashedProtocol[relative.protocol]) {
8429 var keys = Object.keys(relative);
8430 for (var v = 0; v < keys.length; v++) {
8431 var k = keys[v];
8432 result[k] = relative[k];
8433 }
8434 result.href = result.format();
8435 return result;
8436 }
8437
8438 result.protocol = relative.protocol;
8439 if (!relative.host && !hostlessProtocol[relative.protocol]) {
8440 var relPath = (relative.pathname || '').split('/');
8441 while (relPath.length && !(relative.host = relPath.shift()));
8442 if (!relative.host) relative.host = '';
8443 if (!relative.hostname) relative.hostname = '';
8444 if (relPath[0] !== '') relPath.unshift('');
8445 if (relPath.length < 2) relPath.unshift('');
8446 result.pathname = relPath.join('/');
8447 } else {
8448 result.pathname = relative.pathname;
8449 }
8450 result.search = relative.search;
8451 result.query = relative.query;
8452 result.host = relative.host || '';
8453 result.auth = relative.auth;
8454 result.hostname = relative.hostname || relative.host;
8455 result.port = relative.port;
8456 // to support http.request
8457 if (result.pathname || result.search) {
8458 var p = result.pathname || '';
8459 var s = result.search || '';
8460 result.path = p + s;
8461 }
8462 result.slashes = result.slashes || relative.slashes;
8463 result.href = result.format();
8464 return result;
8465 }
8466
8467 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
8468 isRelAbs = (
8469 relative.host ||
8470 relative.pathname && relative.pathname.charAt(0) === '/'
8471 ),
8472 mustEndAbs = (isRelAbs || isSourceAbs ||
8473 (result.host && relative.pathname)),
8474 removeAllDots = mustEndAbs,
8475 srcPath = result.pathname && result.pathname.split('/') || [],
8476 relPath = relative.pathname && relative.pathname.split('/') || [],
8477 psychotic = result.protocol && !slashedProtocol[result.protocol];
8478
8479 // if the url is a non-slashed url, then relative
8480 // links like ../.. should be able
8481 // to crawl up to the hostname, as well. This is strange.
8482 // result.protocol has already been set by now.
8483 // Later on, put the first path part into the host field.
8484 if (psychotic) {
8485 result.hostname = '';
8486 result.port = null;
8487 if (result.host) {
8488 if (srcPath[0] === '') srcPath[0] = result.host;
8489 else srcPath.unshift(result.host);
8490 }
8491 result.host = '';
8492 if (relative.protocol) {
8493 relative.hostname = null;
8494 relative.port = null;
8495 if (relative.host) {
8496 if (relPath[0] === '') relPath[0] = relative.host;
8497 else relPath.unshift(relative.host);
8498 }
8499 relative.host = null;
8500 }
8501 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
8502 }
8503
8504 if (isRelAbs) {
8505 // it's absolute.
8506 result.host = (relative.host || relative.host === '') ?
8507 relative.host : result.host;
8508 result.hostname = (relative.hostname || relative.hostname === '') ?
8509 relative.hostname : result.hostname;
8510 result.search = relative.search;
8511 result.query = relative.query;
8512 srcPath = relPath;
8513 // fall through to the dot-handling below.
8514 } else if (relPath.length) {
8515 // it's relative
8516 // throw away the existing file, and take the new path instead.
8517 if (!srcPath) srcPath = [];
8518 srcPath.pop();
8519 srcPath = srcPath.concat(relPath);
8520 result.search = relative.search;
8521 result.query = relative.query;
8522 } else if (!util.isNullOrUndefined(relative.search)) {
8523 // just pull out the search.
8524 // like href='?foo'.
8525 // Put this after the other two cases because it simplifies the booleans
8526 if (psychotic) {
8527 result.hostname = result.host = srcPath.shift();
8528 //occationaly the auth can get stuck only in host
8529 //this especially happens in cases like
8530 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
8531 var authInHost = result.host && result.host.indexOf('@') > 0 ?
8532 result.host.split('@') : false;
8533 if (authInHost) {
8534 result.auth = authInHost.shift();
8535 result.host = result.hostname = authInHost.shift();
8536 }
8537 }
8538 result.search = relative.search;
8539 result.query = relative.query;
8540 //to support http.request
8541 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
8542 result.path = (result.pathname ? result.pathname : '') +
8543 (result.search ? result.search : '');
8544 }
8545 result.href = result.format();
8546 return result;
8547 }
8548
8549 if (!srcPath.length) {
8550 // no path at all. easy.
8551 // we've already handled the other stuff above.
8552 result.pathname = null;
8553 //to support http.request
8554 if (result.search) {
8555 result.path = '/' + result.search;
8556 } else {
8557 result.path = null;
8558 }
8559 result.href = result.format();
8560 return result;
8561 }
8562
8563 // if a url ENDs in . or .., then it must get a trailing slash.
8564 // however, if it ends in anything else non-slashy,
8565 // then it must NOT get a trailing slash.
8566 var last = srcPath.slice(-1)[0];
8567 var hasTrailingSlash = (
8568 (result.host || relative.host || srcPath.length > 1) &&
8569 (last === '.' || last === '..') || last === '');
8570
8571 // strip single dots, resolve double dots to parent dir
8572 // if the path tries to go above the root, `up` ends up > 0
8573 var up = 0;
8574 for (var i = srcPath.length; i >= 0; i--) {
8575 last = srcPath[i];
8576 if (last === '.') {
8577 srcPath.splice(i, 1);
8578 } else if (last === '..') {
8579 srcPath.splice(i, 1);
8580 up++;
8581 } else if (up) {
8582 srcPath.splice(i, 1);
8583 up--;
8584 }
8585 }
8586
8587 // if the path is allowed to go above the root, restore leading ..s
8588 if (!mustEndAbs && !removeAllDots) {
8589 for (; up--; up) {
8590 srcPath.unshift('..');
8591 }
8592 }
8593
8594 if (mustEndAbs && srcPath[0] !== '' &&
8595 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
8596 srcPath.unshift('');
8597 }
8598
8599 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
8600 srcPath.push('');
8601 }
8602
8603 var isAbsolute = srcPath[0] === '' ||
8604 (srcPath[0] && srcPath[0].charAt(0) === '/');
8605
8606 // put the host back
8607 if (psychotic) {
8608 result.hostname = result.host = isAbsolute ? '' :
8609 srcPath.length ? srcPath.shift() : '';
8610 //occationaly the auth can get stuck only in host
8611 //this especially happens in cases like
8612 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
8613 var authInHost = result.host && result.host.indexOf('@') > 0 ?
8614 result.host.split('@') : false;
8615 if (authInHost) {
8616 result.auth = authInHost.shift();
8617 result.host = result.hostname = authInHost.shift();
8618 }
8619 }
8620
8621 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
8622
8623 if (mustEndAbs && !isAbsolute) {
8624 srcPath.unshift('');
8625 }
8626
8627 if (!srcPath.length) {
8628 result.pathname = null;
8629 result.path = null;
8630 } else {
8631 result.pathname = srcPath.join('/');
8632 }
8633
8634 //to support request.http
8635 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
8636 result.path = (result.pathname ? result.pathname : '') +
8637 (result.search ? result.search : '');
8638 }
8639 result.auth = relative.auth || result.auth;
8640 result.slashes = result.slashes || relative.slashes;
8641 result.href = result.format();
8642 return result;
8643};
8644
8645Url.prototype.parseHost = function() {
8646 var host = this.host;
8647 var port = portPattern.exec(host);
8648 if (port) {
8649 port = port[0];
8650 if (port !== ':') {
8651 this.port = port.substr(1);
8652 }
8653 host = host.substr(0, host.length - port.length);
8654 }
8655 if (host) this.hostname = host;
8656};
8657
8658},{"./util":39,"punycode":11,"querystring":14}],39:[function(require,module,exports){
8659'use strict';
8660
8661module.exports = {
8662 isString: function(arg) {
8663 return typeof(arg) === 'string';
8664 },
8665 isObject: function(arg) {
8666 return typeof(arg) === 'object' && arg !== null;
8667 },
8668 isNull: function(arg) {
8669 return arg === null;
8670 },
8671 isNullOrUndefined: function(arg) {
8672 return arg == null;
8673 }
8674};
8675
8676},{}],40:[function(require,module,exports){
8677(function (global){(function (){
8678
8679/**
8680 * Module exports.
8681 */
8682
8683module.exports = deprecate;
8684
8685/**
8686 * Mark that a method should not be used.
8687 * Returns a modified function which warns once by default.
8688 *
8689 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
8690 *
8691 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
8692 * will throw an Error when invoked.
8693 *
8694 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
8695 * will invoke `console.trace()` instead of `console.error()`.
8696 *
8697 * @param {Function} fn - the function to deprecate
8698 * @param {String} msg - the string to print to the console when `fn` is invoked
8699 * @returns {Function} a new "deprecated" version of `fn`
8700 * @api public
8701 */
8702
8703function deprecate (fn, msg) {
8704 if (config('noDeprecation')) {
8705 return fn;
8706 }
8707
8708 var warned = false;
8709 function deprecated() {
8710 if (!warned) {
8711 if (config('throwDeprecation')) {
8712 throw new Error(msg);
8713 } else if (config('traceDeprecation')) {
8714 console.trace(msg);
8715 } else {
8716 console.warn(msg);
8717 }
8718 warned = true;
8719 }
8720 return fn.apply(this, arguments);
8721 }
8722
8723 return deprecated;
8724}
8725
8726/**
8727 * Checks `localStorage` for boolean values for the given `name`.
8728 *
8729 * @param {String} name
8730 * @returns {Boolean}
8731 * @api private
8732 */
8733
8734function config (name) {
8735 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
8736 try {
8737 if (!global.localStorage) return false;
8738 } catch (_) {
8739 return false;
8740 }
8741 var val = global.localStorage[name];
8742 if (null == val) return false;
8743 return String(val).toLowerCase() === 'true';
8744}
8745
8746}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8747},{}],41:[function(require,module,exports){
8748// Returns a wrapper function that returns a wrapped callback
8749// The wrapper function should do some stuff, and return a
8750// presumably different callback function.
8751// This makes sure that own properties are retained, so that
8752// decorations and such are not lost along the way.
8753module.exports = wrappy
8754function wrappy (fn, cb) {
8755 if (fn && cb) return wrappy(fn)(cb)
8756
8757 if (typeof fn !== 'function')
8758 throw new TypeError('need wrapper function')
8759
8760 Object.keys(fn).forEach(function (k) {
8761 wrapper[k] = fn[k]
8762 })
8763
8764 return wrapper
8765
8766 function wrapper() {
8767 var args = new Array(arguments.length)
8768 for (var i = 0; i < args.length; i++) {
8769 args[i] = arguments[i]
8770 }
8771 var ret = fn.apply(this, args)
8772 var cb = args[args.length-1]
8773 if (typeof ret === 'function' && ret !== cb) {
8774 Object.keys(cb).forEach(function (k) {
8775 ret[k] = cb[k]
8776 })
8777 }
8778 return ret
8779 }
8780}
8781
8782},{}],42:[function(require,module,exports){
8783module.exports = extend
8784
8785var hasOwnProperty = Object.prototype.hasOwnProperty;
8786
8787function extend() {
8788 var target = {}
8789
8790 for (var i = 0; i < arguments.length; i++) {
8791 var source = arguments[i]
8792
8793 for (var key in source) {
8794 if (hasOwnProperty.call(source, key)) {
8795 target[key] = source[key]
8796 }
8797 }
8798 }
8799
8800 return target
8801}
8802
8803},{}],43:[function(require,module,exports){
8804window.x = require('simple-get')
8805
8806},{"simple-get":17}]},{},[43]);