· 5 years ago · Nov 04, 2020, 03:16 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(
130 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
131 ))
132 }
133
134 // pad the end with zeros, but make sure to not forget the extra bytes
135 if (extraBytes === 1) {
136 tmp = uint8[len - 1]
137 parts.push(
138 lookup[tmp >> 2] +
139 lookup[(tmp << 4) & 0x3F] +
140 '=='
141 )
142 } else if (extraBytes === 2) {
143 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
144 parts.push(
145 lookup[tmp >> 10] +
146 lookup[(tmp >> 4) & 0x3F] +
147 lookup[(tmp << 2) & 0x3F] +
148 '='
149 )
150 }
151
152 return parts.join('')
153}
154
155},{}],2:[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":2,"ieee754":3}],3:[function(require,module,exports){
1937/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
1938exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1939 var e, m
1940 var eLen = (nBytes * 8) - mLen - 1
1941 var eMax = (1 << eLen) - 1
1942 var eBias = eMax >> 1
1943 var nBits = -7
1944 var i = isLE ? (nBytes - 1) : 0
1945 var d = isLE ? -1 : 1
1946 var s = buffer[offset + i]
1947
1948 i += d
1949
1950 e = s & ((1 << (-nBits)) - 1)
1951 s >>= (-nBits)
1952 nBits += eLen
1953 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
1954
1955 m = e & ((1 << (-nBits)) - 1)
1956 e >>= (-nBits)
1957 nBits += mLen
1958 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
1959
1960 if (e === 0) {
1961 e = 1 - eBias
1962 } else if (e === eMax) {
1963 return m ? NaN : ((s ? -1 : 1) * Infinity)
1964 } else {
1965 m = m + Math.pow(2, mLen)
1966 e = e - eBias
1967 }
1968 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
1969}
1970
1971exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
1972 var e, m, c
1973 var eLen = (nBytes * 8) - mLen - 1
1974 var eMax = (1 << eLen) - 1
1975 var eBias = eMax >> 1
1976 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
1977 var i = isLE ? 0 : (nBytes - 1)
1978 var d = isLE ? 1 : -1
1979 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
1980
1981 value = Math.abs(value)
1982
1983 if (isNaN(value) || value === Infinity) {
1984 m = isNaN(value) ? 1 : 0
1985 e = eMax
1986 } else {
1987 e = Math.floor(Math.log(value) / Math.LN2)
1988 if (value * (c = Math.pow(2, -e)) < 1) {
1989 e--
1990 c *= 2
1991 }
1992 if (e + eBias >= 1) {
1993 value += rt / c
1994 } else {
1995 value += rt * Math.pow(2, 1 - eBias)
1996 }
1997 if (value * c >= 2) {
1998 e++
1999 c /= 2
2000 }
2001
2002 if (e + eBias >= eMax) {
2003 m = 0
2004 e = eMax
2005 } else if (e + eBias >= 1) {
2006 m = ((value * c) - 1) * Math.pow(2, mLen)
2007 e = e + eBias
2008 } else {
2009 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
2010 e = 0
2011 }
2012 }
2013
2014 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2015
2016 e = (e << mLen) | m
2017 eLen += mLen
2018 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2019
2020 buffer[offset + i - d] |= s * 128
2021}
2022
2023},{}],4:[function(require,module,exports){
2024"use strict";
2025// Copyright (c) .NET Foundation. All rights reserved.
2026// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
2027Object.defineProperty(exports, "__esModule", { value: true });
2028// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController
2029// We don't actually ever use the API being polyfilled, we always use the polyfill because
2030// it's a very new API right now.
2031// Not exported from index.
2032/** @private */
2033var AbortController = /** @class */ (function () {
2034 function AbortController() {
2035 this.isAborted = false;
2036 this.onabort = null;
2037 }
2038 AbortController.prototype.abort = function () {
2039 if (!this.isAborted) {
2040 this.isAborted = true;
2041 if (this.onabort) {
2042 this.onabort();
2043 }
2044 }
2045 };
2046 Object.defineProperty(AbortController.prototype, "signal", {
2047 get: function () {
2048 return this;
2049 },
2050 enumerable: true,
2051 configurable: true
2052 });
2053 Object.defineProperty(AbortController.prototype, "aborted", {
2054 get: function () {
2055 return this.isAborted;
2056 },
2057 enumerable: true,
2058 configurable: true
2059 });
2060 return AbortController;
2061}());
2062exports.AbortController = AbortController;
2063
2064},{}],5:[function(require,module,exports){
2065"use strict";
2066// Copyright (c) .NET Foundation. All rights reserved.
2067// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
2068var __extends = (this && this.__extends) || (function () {
2069 var extendStatics = Object.setPrototypeOf ||
2070 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
2071 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
2072 return function (d, b) {
2073 extendStatics(d, b);
2074 function __() { this.constructor = d; }
2075 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2076 };
2077})();
2078Object.defineProperty(exports, "__esModule", { value: true });
2079var Errors_1 = require("./Errors");
2080var HttpClient_1 = require("./HttpClient");
2081var NodeHttpClient_1 = require("./NodeHttpClient");
2082var XhrHttpClient_1 = require("./XhrHttpClient");
2083/** Default implementation of {@link @microsoft/signalr.HttpClient}. */
2084var DefaultHttpClient = /** @class */ (function (_super) {
2085 __extends(DefaultHttpClient, _super);
2086 /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */
2087 function DefaultHttpClient(logger) {
2088 var _this = _super.call(this) || this;
2089 if (typeof XMLHttpRequest !== "undefined") {
2090 _this.httpClient = new XhrHttpClient_1.XhrHttpClient(logger);
2091 }
2092 else {
2093 _this.httpClient = new NodeHttpClient_1.NodeHttpClient(logger);
2094 }
2095 return _this;
2096 }
2097 /** @inheritDoc */
2098 DefaultHttpClient.prototype.send = function (request) {
2099 // Check that abort was not signaled before calling send
2100 if (request.abortSignal && request.abortSignal.aborted) {
2101 return Promise.reject(new Errors_1.AbortError());
2102 }
2103 if (!request.method) {
2104 return Promise.reject(new Error("No method defined."));
2105 }
2106 if (!request.url) {
2107 return Promise.reject(new Error("No url defined."));
2108 }
2109 return this.httpClient.send(request);
2110 };
2111 DefaultHttpClient.prototype.getCookieString = function (url) {
2112 return this.httpClient.getCookieString(url);
2113 };
2114 return DefaultHttpClient;
2115}(HttpClient_1.HttpClient));
2116exports.DefaultHttpClient = DefaultHttpClient;
2117
2118},{"./Errors":7,"./HttpClient":9,"./NodeHttpClient":19,"./XhrHttpClient":25}],6:[function(require,module,exports){
2119"use strict";
2120// Copyright (c) .NET Foundation. All rights reserved.
2121// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
2122Object.defineProperty(exports, "__esModule", { value: true });
2123// 0, 2, 10, 30 second delays before reconnect attempts.
2124var DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];
2125/** @private */
2126var DefaultReconnectPolicy = /** @class */ (function () {
2127 function DefaultReconnectPolicy(retryDelays) {
2128 this.retryDelays = retryDelays !== undefined ? retryDelays.concat([null]) : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;
2129 }
2130 DefaultReconnectPolicy.prototype.nextRetryDelayInMilliseconds = function (retryContext) {
2131 return this.retryDelays[retryContext.previousRetryCount];
2132 };
2133 return DefaultReconnectPolicy;
2134}());
2135exports.DefaultReconnectPolicy = DefaultReconnectPolicy;
2136
2137},{}],7:[function(require,module,exports){
2138"use strict";
2139// Copyright (c) .NET Foundation. All rights reserved.
2140// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
2141var __extends = (this && this.__extends) || (function () {
2142 var extendStatics = Object.setPrototypeOf ||
2143 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
2144 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
2145 return function (d, b) {
2146 extendStatics(d, b);
2147 function __() { this.constructor = d; }
2148 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2149 };
2150})();
2151Object.defineProperty(exports, "__esModule", { value: true });
2152/** Error thrown when an HTTP request fails. */
2153var HttpError = /** @class */ (function (_super) {
2154 __extends(HttpError, _super);
2155 /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.
2156 *
2157 * @param {string} errorMessage A descriptive error message.
2158 * @param {number} statusCode The HTTP status code represented by this error.
2159 */
2160 function HttpError(errorMessage, statusCode) {
2161 var _newTarget = this.constructor;
2162 var _this = this;
2163 var trueProto = _newTarget.prototype;
2164 _this = _super.call(this, errorMessage) || this;
2165 _this.statusCode = statusCode;
2166 // Workaround issue in Typescript compiler
2167 // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
2168 _this.__proto__ = trueProto;
2169 return _this;
2170 }
2171 return HttpError;
2172}(Error));
2173exports.HttpError = HttpError;
2174/** Error thrown when a timeout elapses. */
2175var TimeoutError = /** @class */ (function (_super) {
2176 __extends(TimeoutError, _super);
2177 /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.
2178 *
2179 * @param {string} errorMessage A descriptive error message.
2180 */
2181 function TimeoutError(errorMessage) {
2182 var _newTarget = this.constructor;
2183 if (errorMessage === void 0) { errorMessage = "A timeout occurred."; }
2184 var _this = this;
2185 var trueProto = _newTarget.prototype;
2186 _this = _super.call(this, errorMessage) || this;
2187 // Workaround issue in Typescript compiler
2188 // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
2189 _this.__proto__ = trueProto;
2190 return _this;
2191 }
2192 return TimeoutError;
2193}(Error));
2194exports.TimeoutError = TimeoutError;
2195/** Error thrown when an action is aborted. */
2196var AbortError = /** @class */ (function (_super) {
2197 __extends(AbortError, _super);
2198 /** Constructs a new instance of {@link AbortError}.
2199 *
2200 * @param {string} errorMessage A descriptive error message.
2201 */
2202 function AbortError(errorMessage) {
2203 var _newTarget = this.constructor;
2204 if (errorMessage === void 0) { errorMessage = "An abort occurred."; }
2205 var _this = this;
2206 var trueProto = _newTarget.prototype;
2207 _this = _super.call(this, errorMessage) || this;
2208 // Workaround issue in Typescript compiler
2209 // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
2210 _this.__proto__ = trueProto;
2211 return _this;
2212 }
2213 return AbortError;
2214}(Error));
2215exports.AbortError = AbortError;
2216
2217},{}],8:[function(require,module,exports){
2218(function (Buffer){(function (){
2219"use strict";
2220// Copyright (c) .NET Foundation. All rights reserved.
2221// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
2222Object.defineProperty(exports, "__esModule", { value: true });
2223var TextMessageFormat_1 = require("./TextMessageFormat");
2224var Utils_1 = require("./Utils");
2225/** @private */
2226var HandshakeProtocol = /** @class */ (function () {
2227 function HandshakeProtocol() {
2228 }
2229 // Handshake request is always JSON
2230 HandshakeProtocol.prototype.writeHandshakeRequest = function (handshakeRequest) {
2231 return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(handshakeRequest));
2232 };
2233 HandshakeProtocol.prototype.parseHandshakeResponse = function (data) {
2234 var responseMessage;
2235 var messageData;
2236 var remainingData;
2237 if (Utils_1.isArrayBuffer(data) || (typeof Buffer !== "undefined" && data instanceof Buffer)) {
2238 // Format is binary but still need to read JSON text from handshake response
2239 var binaryData = new Uint8Array(data);
2240 var separatorIndex = binaryData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparatorCode);
2241 if (separatorIndex === -1) {
2242 throw new Error("Message is incomplete.");
2243 }
2244 // content before separator is handshake response
2245 // optional content after is additional messages
2246 var responseLength = separatorIndex + 1;
2247 messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength));
2248 remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
2249 }
2250 else {
2251 var textData = data;
2252 var separatorIndex = textData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparator);
2253 if (separatorIndex === -1) {
2254 throw new Error("Message is incomplete.");
2255 }
2256 // content before separator is handshake response
2257 // optional content after is additional messages
2258 var responseLength = separatorIndex + 1;
2259 messageData = textData.substring(0, responseLength);
2260 remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
2261 }
2262 // At this point we should have just the single handshake message
2263 var messages = TextMessageFormat_1.TextMessageFormat.parse(messageData);
2264 var response = JSON.parse(messages[0]);
2265 if (response.type) {
2266 throw new Error("Expected a handshake response from the server.");
2267 }
2268 responseMessage = response;
2269 // multiple messages could have arrived with handshake
2270 // return additional data to be parsed as usual, or null if all parsed
2271 return [remainingData, responseMessage];
2272 };
2273 return HandshakeProtocol;
2274}());
2275exports.HandshakeProtocol = HandshakeProtocol;
2276
2277}).call(this)}).call(this,require("buffer").Buffer)
2278},{"./TextMessageFormat":22,"./Utils":23,"buffer":2}],9:[function(require,module,exports){
2279"use strict";
2280// Copyright (c) .NET Foundation. All rights reserved.
2281// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
2282var __assign = (this && this.__assign) || Object.assign || function(t) {
2283 for (var s, i = 1, n = arguments.length; i < n; i++) {
2284 s = arguments[i];
2285 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2286 t[p] = s[p];
2287 }
2288 return t;
2289};
2290Object.defineProperty(exports, "__esModule", { value: true });
2291/** Represents an HTTP response. */
2292var HttpResponse = /** @class */ (function () {
2293 function HttpResponse(statusCode, statusText, content) {
2294 this.statusCode = statusCode;
2295 this.statusText = statusText;
2296 this.content = content;
2297 }
2298 return HttpResponse;
2299}());
2300exports.HttpResponse = HttpResponse;
2301/** Abstraction over an HTTP client.
2302 *
2303 * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.
2304 */
2305var HttpClient = /** @class */ (function () {
2306 function HttpClient() {
2307 }
2308 HttpClient.prototype.get = function (url, options) {
2309 return this.send(__assign({}, options, { method: "GET", url: url }));
2310 };
2311 HttpClient.prototype.post = function (url, options) {
2312 return this.send(__assign({}, options, { method: "POST", url: url }));
2313 };
2314 HttpClient.prototype.delete = function (url, options) {
2315 return this.send(__assign({}, options, { method: "DELETE", url: url }));
2316 };
2317 /** Gets all cookies that apply to the specified URL.
2318 *
2319 * @param url The URL that the cookies are valid for.
2320 * @returns {string} A string containing all the key-value cookie pairs for the specified URL.
2321 */
2322 // @ts-ignore
2323 HttpClient.prototype.getCookieString = function (url) {
2324 return "";
2325 };
2326 return HttpClient;
2327}());
2328exports.HttpClient = HttpClient;
2329
2330},{}],10:[function(require,module,exports){
2331"use strict";
2332// Copyright (c) .NET Foundation. All rights reserved.
2333// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
2334var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2335 return new (P || (P = Promise))(function (resolve, reject) {
2336 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2337 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2338 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
2339 step((generator = generator.apply(thisArg, _arguments || [])).next());
2340 });
2341};
2342var __generator = (this && this.__generator) || function (thisArg, body) {
2343 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
2344 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2345 function verb(n) { return function (v) { return step([n, v]); }; }
2346 function step(op) {
2347 if (f) throw new TypeError("Generator is already executing.");
2348 while (_) try {
2349 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2350 if (y = 0, t) op = [op[0] & 2, t.value];
2351 switch (op[0]) {
2352 case 0: case 1: t = op; break;
2353 case 4: _.label++; return { value: op[1], done: false };
2354 case 5: _.label++; y = op[1]; op = [0]; continue;
2355 case 7: op = _.ops.pop(); _.trys.pop(); continue;
2356 default:
2357 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2358 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2359 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2360 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2361 if (t[2]) _.ops.pop();
2362 _.trys.pop(); continue;
2363 }
2364 op = body.call(thisArg, _);
2365 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2366 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2367 }
2368};
2369Object.defineProperty(exports, "__esModule", { value: true });
2370var DefaultHttpClient_1 = require("./DefaultHttpClient");
2371var ILogger_1 = require("./ILogger");
2372var ITransport_1 = require("./ITransport");
2373var LongPollingTransport_1 = require("./LongPollingTransport");
2374var ServerSentEventsTransport_1 = require("./ServerSentEventsTransport");
2375var Utils_1 = require("./Utils");
2376var WebSocketTransport_1 = require("./WebSocketTransport");
2377var MAX_REDIRECTS = 100;
2378var WebSocketModule = null;
2379var EventSourceModule = null;
2380if (Utils_1.Platform.isNode && typeof require !== "undefined") {
2381 // In order to ignore the dynamic require in webpack builds we need to do this magic
2382 // @ts-ignore: TS doesn't know about these names
2383 var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
2384 WebSocketModule = requireFunc("ws");
2385 EventSourceModule = requireFunc("eventsource");
2386}
2387/** @private */
2388var HttpConnection = /** @class */ (function () {
2389 function HttpConnection(url, options) {
2390 if (options === void 0) { options = {}; }
2391 this.features = {};
2392 this.negotiateVersion = 1;
2393 Utils_1.Arg.isRequired(url, "url");
2394 this.logger = Utils_1.createLogger(options.logger);
2395 this.baseUrl = this.resolveUrl(url);
2396 options = options || {};
2397 options.logMessageContent = options.logMessageContent || false;
2398 if (!Utils_1.Platform.isNode && typeof WebSocket !== "undefined" && !options.WebSocket) {
2399 options.WebSocket = WebSocket;
2400 }
2401 else if (Utils_1.Platform.isNode && !options.WebSocket) {
2402 if (WebSocketModule) {
2403 options.WebSocket = WebSocketModule;
2404 }
2405 }
2406 if (!Utils_1.Platform.isNode && typeof EventSource !== "undefined" && !options.EventSource) {
2407 options.EventSource = EventSource;
2408 }
2409 else if (Utils_1.Platform.isNode && !options.EventSource) {
2410 if (typeof EventSourceModule !== "undefined") {
2411 options.EventSource = EventSourceModule;
2412 }
2413 }
2414 this.httpClient = options.httpClient || new DefaultHttpClient_1.DefaultHttpClient(this.logger);
2415 this.connectionState = "Disconnected" /* Disconnected */;
2416 this.connectionStarted = false;
2417 this.options = options;
2418 this.onreceive = null;
2419 this.onclose = null;
2420 }
2421 HttpConnection.prototype.start = function (transferFormat) {
2422 return __awaiter(this, void 0, void 0, function () {
2423 var message, message;
2424 return __generator(this, function (_a) {
2425 switch (_a.label) {
2426 case 0:
2427 transferFormat = transferFormat || ITransport_1.TransferFormat.Binary;
2428 Utils_1.Arg.isIn(transferFormat, ITransport_1.TransferFormat, "transferFormat");
2429 this.logger.log(ILogger_1.LogLevel.Debug, "Starting connection with transfer format '" + ITransport_1.TransferFormat[transferFormat] + "'.");
2430 if (this.connectionState !== "Disconnected" /* Disconnected */) {
2431 return [2 /*return*/, Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."))];
2432 }
2433 this.connectionState = "Connecting " /* Connecting */;
2434 this.startInternalPromise = this.startInternal(transferFormat);
2435 return [4 /*yield*/, this.startInternalPromise];
2436 case 1:
2437 _a.sent();
2438 if (!(this.connectionState === "Disconnecting" /* Disconnecting */)) return [3 /*break*/, 3];
2439 message = "Failed to start the HttpConnection before stop() was called.";
2440 this.logger.log(ILogger_1.LogLevel.Error, message);
2441 // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.
2442 return [4 /*yield*/, this.stopPromise];
2443 case 2:
2444 // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.
2445 _a.sent();
2446 return [2 /*return*/, Promise.reject(new Error(message))];
2447 case 3:
2448 if (this.connectionState !== "Connected" /* Connected */) {
2449 message = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";
2450 this.logger.log(ILogger_1.LogLevel.Error, message);
2451 return [2 /*return*/, Promise.reject(new Error(message))];
2452 }
2453 _a.label = 4;
2454 case 4:
2455 this.connectionStarted = true;
2456 return [2 /*return*/];
2457 }
2458 });
2459 });
2460 };
2461 HttpConnection.prototype.send = function (data) {
2462 if (this.connectionState !== "Connected" /* Connected */) {
2463 return Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State."));
2464 }
2465 if (!this.sendQueue) {
2466 this.sendQueue = new TransportSendQueue(this.transport);
2467 }
2468 // Transport will not be null if state is connected
2469 return this.sendQueue.send(data);
2470 };
2471 HttpConnection.prototype.stop = function (error) {
2472 return __awaiter(this, void 0, void 0, function () {
2473 var _this = this;
2474 return __generator(this, function (_a) {
2475 switch (_a.label) {
2476 case 0:
2477 if (this.connectionState === "Disconnected" /* Disconnected */) {
2478 this.logger.log(ILogger_1.LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnected state.");
2479 return [2 /*return*/, Promise.resolve()];
2480 }
2481 if (this.connectionState === "Disconnecting" /* Disconnecting */) {
2482 this.logger.log(ILogger_1.LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnecting state.");
2483 return [2 /*return*/, this.stopPromise];
2484 }
2485 this.connectionState = "Disconnecting" /* Disconnecting */;
2486 this.stopPromise = new Promise(function (resolve) {
2487 // Don't complete stop() until stopConnection() completes.
2488 _this.stopPromiseResolver = resolve;
2489 });
2490 // stopInternal should never throw so just observe it.
2491 return [4 /*yield*/, this.stopInternal(error)];
2492 case 1:
2493 // stopInternal should never throw so just observe it.
2494 _a.sent();
2495 return [4 /*yield*/, this.stopPromise];
2496 case 2:
2497 _a.sent();
2498 return [2 /*return*/];
2499 }
2500 });
2501 });
2502 };
2503 HttpConnection.prototype.stopInternal = function (error) {
2504 return __awaiter(this, void 0, void 0, function () {
2505 var e_1, e_2;
2506 return __generator(this, function (_a) {
2507 switch (_a.label) {
2508 case 0:
2509 // Set error as soon as possible otherwise there is a race between
2510 // the transport closing and providing an error and the error from a close message
2511 // We would prefer the close message error.
2512 this.stopError = error;
2513 _a.label = 1;
2514 case 1:
2515 _a.trys.push([1, 3, , 4]);
2516 return [4 /*yield*/, this.startInternalPromise];
2517 case 2:
2518 _a.sent();
2519 return [3 /*break*/, 4];
2520 case 3:
2521 e_1 = _a.sent();
2522 return [3 /*break*/, 4];
2523 case 4:
2524 if (!this.transport) return [3 /*break*/, 9];
2525 _a.label = 5;
2526 case 5:
2527 _a.trys.push([5, 7, , 8]);
2528 return [4 /*yield*/, this.transport.stop()];
2529 case 6:
2530 _a.sent();
2531 return [3 /*break*/, 8];
2532 case 7:
2533 e_2 = _a.sent();
2534 this.logger.log(ILogger_1.LogLevel.Error, "HttpConnection.transport.stop() threw error '" + e_2 + "'.");
2535 this.stopConnection();
2536 return [3 /*break*/, 8];
2537 case 8:
2538 this.transport = undefined;
2539 return [3 /*break*/, 10];
2540 case 9:
2541 this.logger.log(ILogger_1.LogLevel.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.");
2542 this.stopConnection();
2543 _a.label = 10;
2544 case 10: return [2 /*return*/];
2545 }
2546 });
2547 });
2548 };
2549 HttpConnection.prototype.startInternal = function (transferFormat) {
2550 return __awaiter(this, void 0, void 0, function () {
2551 var url, negotiateResponse, redirects, _loop_1, this_1, e_3;
2552 return __generator(this, function (_a) {
2553 switch (_a.label) {
2554 case 0:
2555 url = this.baseUrl;
2556 this.accessTokenFactory = this.options.accessTokenFactory;
2557 _a.label = 1;
2558 case 1:
2559 _a.trys.push([1, 12, , 13]);
2560 if (!this.options.skipNegotiation) return [3 /*break*/, 5];
2561 if (!(this.options.transport === ITransport_1.HttpTransportType.WebSockets)) return [3 /*break*/, 3];
2562 // No need to add a connection ID in this case
2563 this.transport = this.constructTransport(ITransport_1.HttpTransportType.WebSockets);
2564 // We should just call connect directly in this case.
2565 // No fallback or negotiate in this case.
2566 return [4 /*yield*/, this.startTransport(url, transferFormat)];
2567 case 2:
2568 // We should just call connect directly in this case.
2569 // No fallback or negotiate in this case.
2570 _a.sent();
2571 return [3 /*break*/, 4];
2572 case 3: throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");
2573 case 4: return [3 /*break*/, 11];
2574 case 5:
2575 negotiateResponse = null;
2576 redirects = 0;
2577 _loop_1 = function () {
2578 var accessToken_1;
2579 return __generator(this, function (_a) {
2580 switch (_a.label) {
2581 case 0: return [4 /*yield*/, this_1.getNegotiationResponse(url)];
2582 case 1:
2583 negotiateResponse = _a.sent();
2584 // the user tries to stop the connection when it is being started
2585 if (this_1.connectionState === "Disconnecting" /* Disconnecting */ || this_1.connectionState === "Disconnected" /* Disconnected */) {
2586 throw new Error("The connection was stopped during negotiation.");
2587 }
2588 if (negotiateResponse.error) {
2589 throw new Error(negotiateResponse.error);
2590 }
2591 if (negotiateResponse.ProtocolVersion) {
2592 throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");
2593 }
2594 if (negotiateResponse.url) {
2595 url = negotiateResponse.url;
2596 }
2597 if (negotiateResponse.accessToken) {
2598 accessToken_1 = negotiateResponse.accessToken;
2599 this_1.accessTokenFactory = function () { return accessToken_1; };
2600 }
2601 redirects++;
2602 return [2 /*return*/];
2603 }
2604 });
2605 };
2606 this_1 = this;
2607 _a.label = 6;
2608 case 6: return [5 /*yield**/, _loop_1()];
2609 case 7:
2610 _a.sent();
2611 _a.label = 8;
2612 case 8:
2613 if (negotiateResponse.url && redirects < MAX_REDIRECTS) return [3 /*break*/, 6];
2614 _a.label = 9;
2615 case 9:
2616 if (redirects === MAX_REDIRECTS && negotiateResponse.url) {
2617 throw new Error("Negotiate redirection limit exceeded.");
2618 }
2619 return [4 /*yield*/, this.createTransport(url, this.options.transport, negotiateResponse, transferFormat)];
2620 case 10:
2621 _a.sent();
2622 _a.label = 11;
2623 case 11:
2624 if (this.transport instanceof LongPollingTransport_1.LongPollingTransport) {
2625 this.features.inherentKeepAlive = true;
2626 }
2627 if (this.connectionState === "Connecting " /* Connecting */) {
2628 // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.
2629 // start() will handle the case when stop was called and startInternal exits still in the disconnecting state.
2630 this.logger.log(ILogger_1.LogLevel.Debug, "The HttpConnection connected successfully.");
2631 this.connectionState = "Connected" /* Connected */;
2632 }
2633 return [3 /*break*/, 13];
2634 case 12:
2635 e_3 = _a.sent();
2636 this.logger.log(ILogger_1.LogLevel.Error, "Failed to start the connection: " + e_3);
2637 this.connectionState = "Disconnected" /* Disconnected */;
2638 this.transport = undefined;
2639 return [2 /*return*/, Promise.reject(e_3)];
2640 case 13: return [2 /*return*/];
2641 }
2642 });
2643 });
2644 };
2645 HttpConnection.prototype.getNegotiationResponse = function (url) {
2646 return __awaiter(this, void 0, void 0, function () {
2647 var _a, headers, token, negotiateUrl, response, negotiateResponse, e_4;
2648 return __generator(this, function (_b) {
2649 switch (_b.label) {
2650 case 0:
2651 if (!this.accessTokenFactory) return [3 /*break*/, 2];
2652 return [4 /*yield*/, this.accessTokenFactory()];
2653 case 1:
2654 token = _b.sent();
2655 if (token) {
2656 headers = (_a = {},
2657 _a["Authorization"] = "Bearer " + token,
2658 _a);
2659 }
2660 _b.label = 2;
2661 case 2:
2662 negotiateUrl = this.resolveNegotiateUrl(url);
2663 this.logger.log(ILogger_1.LogLevel.Debug, "Sending negotiation request: " + negotiateUrl + ".");
2664 _b.label = 3;
2665 case 3:
2666 _b.trys.push([3, 5, , 6]);
2667 return [4 /*yield*/, this.httpClient.post(negotiateUrl, {
2668 content: "",
2669 headers: headers,
2670 })];
2671 case 4:
2672 response = _b.sent();
2673 if (response.statusCode !== 200) {
2674 return [2 /*return*/, Promise.reject(new Error("Unexpected status code returned from negotiate " + response.statusCode))];
2675 }
2676 negotiateResponse = JSON.parse(response.content);
2677 if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {
2678 // Negotiate version 0 doesn't use connectionToken
2679 // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version
2680 negotiateResponse.connectionToken = negotiateResponse.connectionId;
2681 }
2682 return [2 /*return*/, negotiateResponse];
2683 case 5:
2684 e_4 = _b.sent();
2685 this.logger.log(ILogger_1.LogLevel.Error, "Failed to complete negotiation with the server: " + e_4);
2686 return [2 /*return*/, Promise.reject(e_4)];
2687 case 6: return [2 /*return*/];
2688 }
2689 });
2690 });
2691 };
2692 HttpConnection.prototype.createConnectUrl = function (url, connectionToken) {
2693 if (!connectionToken) {
2694 return url;
2695 }
2696 return url + (url.indexOf("?") === -1 ? "?" : "&") + ("id=" + connectionToken);
2697 };
2698 HttpConnection.prototype.createTransport = function (url, requestedTransport, negotiateResponse, requestedTransferFormat) {
2699 return __awaiter(this, void 0, void 0, function () {
2700 var connectUrl, transportExceptions, transports, negotiate, _i, transports_1, endpoint, transportOrError, ex_1, ex_2, message;
2701 return __generator(this, function (_a) {
2702 switch (_a.label) {
2703 case 0:
2704 connectUrl = this.createConnectUrl(url, negotiateResponse.connectionToken);
2705 if (!this.isITransport(requestedTransport)) return [3 /*break*/, 2];
2706 this.logger.log(ILogger_1.LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly.");
2707 this.transport = requestedTransport;
2708 return [4 /*yield*/, this.startTransport(connectUrl, requestedTransferFormat)];
2709 case 1:
2710 _a.sent();
2711 this.connectionId = negotiateResponse.connectionId;
2712 return [2 /*return*/];
2713 case 2:
2714 transportExceptions = [];
2715 transports = negotiateResponse.availableTransports || [];
2716 negotiate = negotiateResponse;
2717 _i = 0, transports_1 = transports;
2718 _a.label = 3;
2719 case 3:
2720 if (!(_i < transports_1.length)) return [3 /*break*/, 13];
2721 endpoint = transports_1[_i];
2722 transportOrError = this.resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat);
2723 if (!(transportOrError instanceof Error)) return [3 /*break*/, 4];
2724 // Store the error and continue, we don't want to cause a re-negotiate in these cases
2725 transportExceptions.push(endpoint.transport + " failed: " + transportOrError);
2726 return [3 /*break*/, 12];
2727 case 4:
2728 if (!this.isITransport(transportOrError)) return [3 /*break*/, 12];
2729 this.transport = transportOrError;
2730 if (!!negotiate) return [3 /*break*/, 9];
2731 _a.label = 5;
2732 case 5:
2733 _a.trys.push([5, 7, , 8]);
2734 return [4 /*yield*/, this.getNegotiationResponse(url)];
2735 case 6:
2736 negotiate = _a.sent();
2737 return [3 /*break*/, 8];
2738 case 7:
2739 ex_1 = _a.sent();
2740 return [2 /*return*/, Promise.reject(ex_1)];
2741 case 8:
2742 connectUrl = this.createConnectUrl(url, negotiate.connectionToken);
2743 _a.label = 9;
2744 case 9:
2745 _a.trys.push([9, 11, , 12]);
2746 return [4 /*yield*/, this.startTransport(connectUrl, requestedTransferFormat)];
2747 case 10:
2748 _a.sent();
2749 this.connectionId = negotiate.connectionId;
2750 return [2 /*return*/];
2751 case 11:
2752 ex_2 = _a.sent();
2753 this.logger.log(ILogger_1.LogLevel.Error, "Failed to start the transport '" + endpoint.transport + "': " + ex_2);
2754 negotiate = undefined;
2755 transportExceptions.push(endpoint.transport + " failed: " + ex_2);
2756 if (this.connectionState !== "Connecting " /* Connecting */) {
2757 message = "Failed to select transport before stop() was called.";
2758 this.logger.log(ILogger_1.LogLevel.Debug, message);
2759 return [2 /*return*/, Promise.reject(new Error(message))];
2760 }
2761 return [3 /*break*/, 12];
2762 case 12:
2763 _i++;
2764 return [3 /*break*/, 3];
2765 case 13:
2766 if (transportExceptions.length > 0) {
2767 return [2 /*return*/, Promise.reject(new Error("Unable to connect to the server with any of the available transports. " + transportExceptions.join(" ")))];
2768 }
2769 return [2 /*return*/, Promise.reject(new Error("None of the transports supported by the client are supported by the server."))];
2770 }
2771 });
2772 });
2773 };
2774 HttpConnection.prototype.constructTransport = function (transport) {
2775 switch (transport) {
2776 case ITransport_1.HttpTransportType.WebSockets:
2777 if (!this.options.WebSocket) {
2778 throw new Error("'WebSocket' is not supported in your environment.");
2779 }
2780 return new WebSocketTransport_1.WebSocketTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.WebSocket);
2781 case ITransport_1.HttpTransportType.ServerSentEvents:
2782 if (!this.options.EventSource) {
2783 throw new Error("'EventSource' is not supported in your environment.");
2784 }
2785 return new ServerSentEventsTransport_1.ServerSentEventsTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.EventSource);
2786 case ITransport_1.HttpTransportType.LongPolling:
2787 return new LongPollingTransport_1.LongPollingTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false);
2788 default:
2789 throw new Error("Unknown transport: " + transport + ".");
2790 }
2791 };
2792 HttpConnection.prototype.startTransport = function (url, transferFormat) {
2793 var _this = this;
2794 this.transport.onreceive = this.onreceive;
2795 this.transport.onclose = function (e) { return _this.stopConnection(e); };
2796 return this.transport.connect(url, transferFormat);
2797 };
2798 HttpConnection.prototype.resolveTransportOrError = function (endpoint, requestedTransport, requestedTransferFormat) {
2799 var transport = ITransport_1.HttpTransportType[endpoint.transport];
2800 if (transport === null || transport === undefined) {
2801 this.logger.log(ILogger_1.LogLevel.Debug, "Skipping transport '" + endpoint.transport + "' because it is not supported by this client.");
2802 return new Error("Skipping transport '" + endpoint.transport + "' because it is not supported by this client.");
2803 }
2804 else {
2805 if (transportMatches(requestedTransport, transport)) {
2806 var transferFormats = endpoint.transferFormats.map(function (s) { return ITransport_1.TransferFormat[s]; });
2807 if (transferFormats.indexOf(requestedTransferFormat) >= 0) {
2808 if ((transport === ITransport_1.HttpTransportType.WebSockets && !this.options.WebSocket) ||
2809 (transport === ITransport_1.HttpTransportType.ServerSentEvents && !this.options.EventSource)) {
2810 this.logger.log(ILogger_1.LogLevel.Debug, "Skipping transport '" + ITransport_1.HttpTransportType[transport] + "' because it is not supported in your environment.'");
2811 return new Error("'" + ITransport_1.HttpTransportType[transport] + "' is not supported in your environment.");
2812 }
2813 else {
2814 this.logger.log(ILogger_1.LogLevel.Debug, "Selecting transport '" + ITransport_1.HttpTransportType[transport] + "'.");
2815 try {
2816 return this.constructTransport(transport);
2817 }
2818 catch (ex) {
2819 return ex;
2820 }
2821 }
2822 }
2823 else {
2824 this.logger.log(ILogger_1.LogLevel.Debug, "Skipping transport '" + ITransport_1.HttpTransportType[transport] + "' because it does not support the requested transfer format '" + ITransport_1.TransferFormat[requestedTransferFormat] + "'.");
2825 return new Error("'" + ITransport_1.HttpTransportType[transport] + "' does not support " + ITransport_1.TransferFormat[requestedTransferFormat] + ".");
2826 }
2827 }
2828 else {
2829 this.logger.log(ILogger_1.LogLevel.Debug, "Skipping transport '" + ITransport_1.HttpTransportType[transport] + "' because it was disabled by the client.");
2830 return new Error("'" + ITransport_1.HttpTransportType[transport] + "' is disabled by the client.");
2831 }
2832 }
2833 };
2834 HttpConnection.prototype.isITransport = function (transport) {
2835 return transport && typeof (transport) === "object" && "connect" in transport;
2836 };
2837 HttpConnection.prototype.stopConnection = function (error) {
2838 var _this = this;
2839 this.logger.log(ILogger_1.LogLevel.Debug, "HttpConnection.stopConnection(" + error + ") called while in state " + this.connectionState + ".");
2840 this.transport = undefined;
2841 // If we have a stopError, it takes precedence over the error from the transport
2842 error = this.stopError || error;
2843 this.stopError = undefined;
2844 if (this.connectionState === "Disconnected" /* Disconnected */) {
2845 this.logger.log(ILogger_1.LogLevel.Debug, "Call to HttpConnection.stopConnection(" + error + ") was ignored because the connection is already in the disconnected state.");
2846 return;
2847 }
2848 if (this.connectionState === "Connecting " /* Connecting */) {
2849 this.logger.log(ILogger_1.LogLevel.Warning, "Call to HttpConnection.stopConnection(" + error + ") was ignored because the connection hasn't yet left the in the connecting state.");
2850 return;
2851 }
2852 if (this.connectionState === "Disconnecting" /* Disconnecting */) {
2853 // A call to stop() induced this call to stopConnection and needs to be completed.
2854 // Any stop() awaiters will be scheduled to continue after the onclose callback fires.
2855 this.stopPromiseResolver();
2856 }
2857 if (error) {
2858 this.logger.log(ILogger_1.LogLevel.Error, "Connection disconnected with error '" + error + "'.");
2859 }
2860 else {
2861 this.logger.log(ILogger_1.LogLevel.Information, "Connection disconnected.");
2862 }
2863 if (this.sendQueue) {
2864 this.sendQueue.stop().catch(function (e) {
2865 _this.logger.log(ILogger_1.LogLevel.Error, "TransportSendQueue.stop() threw error '" + e + "'.");
2866 });
2867 this.sendQueue = undefined;
2868 }
2869 this.connectionId = undefined;
2870 this.connectionState = "Disconnected" /* Disconnected */;
2871 if (this.connectionStarted) {
2872 this.connectionStarted = false;
2873 try {
2874 if (this.onclose) {
2875 this.onclose(error);
2876 }
2877 }
2878 catch (e) {
2879 this.logger.log(ILogger_1.LogLevel.Error, "HttpConnection.onclose(" + error + ") threw error '" + e + "'.");
2880 }
2881 }
2882 };
2883 HttpConnection.prototype.resolveUrl = function (url) {
2884 // startsWith is not supported in IE
2885 if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) {
2886 return url;
2887 }
2888 if (!Utils_1.Platform.isBrowser || !window.document) {
2889 throw new Error("Cannot resolve '" + url + "'.");
2890 }
2891 // Setting the url to the href propery of an anchor tag handles normalization
2892 // for us. There are 3 main cases.
2893 // 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b"
2894 // 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b"
2895 // 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b"
2896 var aTag = window.document.createElement("a");
2897 aTag.href = url;
2898 this.logger.log(ILogger_1.LogLevel.Information, "Normalizing '" + url + "' to '" + aTag.href + "'.");
2899 return aTag.href;
2900 };
2901 HttpConnection.prototype.resolveNegotiateUrl = function (url) {
2902 var index = url.indexOf("?");
2903 var negotiateUrl = url.substring(0, index === -1 ? url.length : index);
2904 if (negotiateUrl[negotiateUrl.length - 1] !== "/") {
2905 negotiateUrl += "/";
2906 }
2907 negotiateUrl += "negotiate";
2908 negotiateUrl += index === -1 ? "" : url.substring(index);
2909 if (negotiateUrl.indexOf("negotiateVersion") === -1) {
2910 negotiateUrl += index === -1 ? "?" : "&";
2911 negotiateUrl += "negotiateVersion=" + this.negotiateVersion;
2912 }
2913 return negotiateUrl;
2914 };
2915 return HttpConnection;
2916}());
2917exports.HttpConnection = HttpConnection;
2918function transportMatches(requestedTransport, actualTransport) {
2919 return !requestedTransport || ((actualTransport & requestedTransport) !== 0);
2920}
2921/** @private */
2922var TransportSendQueue = /** @class */ (function () {
2923 function TransportSendQueue(transport) {
2924 this.transport = transport;
2925 this.buffer = [];
2926 this.executing = true;
2927 this.sendBufferedData = new PromiseSource();
2928 this.transportResult = new PromiseSource();
2929 this.sendLoopPromise = this.sendLoop();
2930 }
2931 TransportSendQueue.prototype.send = function (data) {
2932 this.bufferData(data);
2933 if (!this.transportResult) {
2934 this.transportResult = new PromiseSource();
2935 }
2936 return this.transportResult.promise;
2937 };
2938 TransportSendQueue.prototype.stop = function () {
2939 this.executing = false;
2940 this.sendBufferedData.resolve();
2941 return this.sendLoopPromise;
2942 };
2943 TransportSendQueue.prototype.bufferData = function (data) {
2944 if (this.buffer.length && typeof (this.buffer[0]) !== typeof (data)) {
2945 throw new Error("Expected data to be of type " + typeof (this.buffer) + " but was of type " + typeof (data));
2946 }
2947 this.buffer.push(data);
2948 this.sendBufferedData.resolve();
2949 };
2950 TransportSendQueue.prototype.sendLoop = function () {
2951 return __awaiter(this, void 0, void 0, function () {
2952 var transportResult, data, error_1;
2953 return __generator(this, function (_a) {
2954 switch (_a.label) {
2955 case 0:
2956 if (!true) return [3 /*break*/, 6];
2957 return [4 /*yield*/, this.sendBufferedData.promise];
2958 case 1:
2959 _a.sent();
2960 if (!this.executing) {
2961 if (this.transportResult) {
2962 this.transportResult.reject("Connection stopped.");
2963 }
2964 return [3 /*break*/, 6];
2965 }
2966 this.sendBufferedData = new PromiseSource();
2967 transportResult = this.transportResult;
2968 this.transportResult = undefined;
2969 data = typeof (this.buffer[0]) === "string" ?
2970 this.buffer.join("") :
2971 TransportSendQueue.concatBuffers(this.buffer);
2972 this.buffer.length = 0;
2973 _a.label = 2;
2974 case 2:
2975 _a.trys.push([2, 4, , 5]);
2976 return [4 /*yield*/, this.transport.send(data)];
2977 case 3:
2978 _a.sent();
2979 transportResult.resolve();
2980 return [3 /*break*/, 5];
2981 case 4:
2982 error_1 = _a.sent();
2983 transportResult.reject(error_1);
2984 return [3 /*break*/, 5];
2985 case 5: return [3 /*break*/, 0];
2986 case 6: return [2 /*return*/];
2987 }
2988 });
2989 });
2990 };
2991 TransportSendQueue.concatBuffers = function (arrayBuffers) {
2992 var totalLength = arrayBuffers.map(function (b) { return b.byteLength; }).reduce(function (a, b) { return a + b; });
2993 var result = new Uint8Array(totalLength);
2994 var offset = 0;
2995 for (var _i = 0, arrayBuffers_1 = arrayBuffers; _i < arrayBuffers_1.length; _i++) {
2996 var item = arrayBuffers_1[_i];
2997 result.set(new Uint8Array(item), offset);
2998 offset += item.byteLength;
2999 }
3000 return result;
3001 };
3002 return TransportSendQueue;
3003}());
3004exports.TransportSendQueue = TransportSendQueue;
3005var PromiseSource = /** @class */ (function () {
3006 function PromiseSource() {
3007 var _this = this;
3008 this.promise = new Promise(function (resolve, reject) {
3009 var _a;
3010 return _a = [resolve, reject], _this.resolver = _a[0], _this.rejecter = _a[1], _a;
3011 });
3012 }
3013 PromiseSource.prototype.resolve = function () {
3014 this.resolver();
3015 };
3016 PromiseSource.prototype.reject = function (reason) {
3017 this.rejecter(reason);
3018 };
3019 return PromiseSource;
3020}());
3021
3022},{"./DefaultHttpClient":5,"./ILogger":14,"./ITransport":15,"./LongPollingTransport":18,"./ServerSentEventsTransport":20,"./Utils":23,"./WebSocketTransport":24}],11:[function(require,module,exports){
3023"use strict";
3024// Copyright (c) .NET Foundation. All rights reserved.
3025// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3026var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3027 return new (P || (P = Promise))(function (resolve, reject) {
3028 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
3029 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
3030 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
3031 step((generator = generator.apply(thisArg, _arguments || [])).next());
3032 });
3033};
3034var __generator = (this && this.__generator) || function (thisArg, body) {
3035 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
3036 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
3037 function verb(n) { return function (v) { return step([n, v]); }; }
3038 function step(op) {
3039 if (f) throw new TypeError("Generator is already executing.");
3040 while (_) try {
3041 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
3042 if (y = 0, t) op = [op[0] & 2, t.value];
3043 switch (op[0]) {
3044 case 0: case 1: t = op; break;
3045 case 4: _.label++; return { value: op[1], done: false };
3046 case 5: _.label++; y = op[1]; op = [0]; continue;
3047 case 7: op = _.ops.pop(); _.trys.pop(); continue;
3048 default:
3049 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
3050 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
3051 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
3052 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
3053 if (t[2]) _.ops.pop();
3054 _.trys.pop(); continue;
3055 }
3056 op = body.call(thisArg, _);
3057 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
3058 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
3059 }
3060};
3061Object.defineProperty(exports, "__esModule", { value: true });
3062var HandshakeProtocol_1 = require("./HandshakeProtocol");
3063var IHubProtocol_1 = require("./IHubProtocol");
3064var ILogger_1 = require("./ILogger");
3065var Subject_1 = require("./Subject");
3066var Utils_1 = require("./Utils");
3067var DEFAULT_TIMEOUT_IN_MS = 30 * 1000;
3068var DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;
3069/** Describes the current state of the {@link HubConnection} to the server. */
3070var HubConnectionState;
3071(function (HubConnectionState) {
3072 /** The hub connection is disconnected. */
3073 HubConnectionState["Disconnected"] = "Disconnected";
3074 /** The hub connection is connecting. */
3075 HubConnectionState["Connecting"] = "Connecting";
3076 /** The hub connection is connected. */
3077 HubConnectionState["Connected"] = "Connected";
3078 /** The hub connection is disconnecting. */
3079 HubConnectionState["Disconnecting"] = "Disconnecting";
3080 /** The hub connection is reconnecting. */
3081 HubConnectionState["Reconnecting"] = "Reconnecting";
3082})(HubConnectionState = exports.HubConnectionState || (exports.HubConnectionState = {}));
3083/** Represents a connection to a SignalR Hub. */
3084var HubConnection = /** @class */ (function () {
3085 function HubConnection(connection, logger, protocol, reconnectPolicy) {
3086 var _this = this;
3087 Utils_1.Arg.isRequired(connection, "connection");
3088 Utils_1.Arg.isRequired(logger, "logger");
3089 Utils_1.Arg.isRequired(protocol, "protocol");
3090 this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS;
3091 this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS;
3092 this.logger = logger;
3093 this.protocol = protocol;
3094 this.connection = connection;
3095 this.reconnectPolicy = reconnectPolicy;
3096 this.handshakeProtocol = new HandshakeProtocol_1.HandshakeProtocol();
3097 this.connection.onreceive = function (data) { return _this.processIncomingData(data); };
3098 this.connection.onclose = function (error) { return _this.connectionClosed(error); };
3099 this.callbacks = {};
3100 this.methods = {};
3101 this.closedCallbacks = [];
3102 this.reconnectingCallbacks = [];
3103 this.reconnectedCallbacks = [];
3104 this.invocationId = 0;
3105 this.receivedHandshakeResponse = false;
3106 this.connectionState = HubConnectionState.Disconnected;
3107 this.connectionStarted = false;
3108 this.cachedPingMessage = this.protocol.writeMessage({ type: IHubProtocol_1.MessageType.Ping });
3109 }
3110 /** @internal */
3111 // Using a public static factory method means we can have a private constructor and an _internal_
3112 // create method that can be used by HubConnectionBuilder. An "internal" constructor would just
3113 // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a
3114 // public parameter-less constructor.
3115 HubConnection.create = function (connection, logger, protocol, reconnectPolicy) {
3116 return new HubConnection(connection, logger, protocol, reconnectPolicy);
3117 };
3118 Object.defineProperty(HubConnection.prototype, "state", {
3119 /** Indicates the state of the {@link HubConnection} to the server. */
3120 get: function () {
3121 return this.connectionState;
3122 },
3123 enumerable: true,
3124 configurable: true
3125 });
3126 Object.defineProperty(HubConnection.prototype, "connectionId", {
3127 /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
3128 * in the disconnected state or if the negotiation step was skipped.
3129 */
3130 get: function () {
3131 return this.connection ? (this.connection.connectionId || null) : null;
3132 },
3133 enumerable: true,
3134 configurable: true
3135 });
3136 Object.defineProperty(HubConnection.prototype, "baseUrl", {
3137 /** Indicates the url of the {@link HubConnection} to the server. */
3138 get: function () {
3139 return this.connection.baseUrl || "";
3140 },
3141 /**
3142 * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
3143 * Reconnecting states.
3144 * @param {string} url The url to connect to.
3145 */
3146 set: function (url) {
3147 if (this.connectionState !== HubConnectionState.Disconnected && this.connectionState !== HubConnectionState.Reconnecting) {
3148 throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");
3149 }
3150 if (!url) {
3151 throw new Error("The HubConnection url must be a valid url.");
3152 }
3153 this.connection.baseUrl = url;
3154 },
3155 enumerable: true,
3156 configurable: true
3157 });
3158 /** Starts the connection.
3159 *
3160 * @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
3161 */
3162 HubConnection.prototype.start = function () {
3163 this.startPromise = this.startWithStateTransitions();
3164 return this.startPromise;
3165 };
3166 HubConnection.prototype.startWithStateTransitions = function () {
3167 return __awaiter(this, void 0, void 0, function () {
3168 var e_1;
3169 return __generator(this, function (_a) {
3170 switch (_a.label) {
3171 case 0:
3172 if (this.connectionState !== HubConnectionState.Disconnected) {
3173 return [2 /*return*/, Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."))];
3174 }
3175 this.connectionState = HubConnectionState.Connecting;
3176 this.logger.log(ILogger_1.LogLevel.Debug, "Starting HubConnection.");
3177 _a.label = 1;
3178 case 1:
3179 _a.trys.push([1, 3, , 4]);
3180 return [4 /*yield*/, this.startInternal()];
3181 case 2:
3182 _a.sent();
3183 this.connectionState = HubConnectionState.Connected;
3184 this.connectionStarted = true;
3185 this.logger.log(ILogger_1.LogLevel.Debug, "HubConnection connected successfully.");
3186 return [3 /*break*/, 4];
3187 case 3:
3188 e_1 = _a.sent();
3189 this.connectionState = HubConnectionState.Disconnected;
3190 this.logger.log(ILogger_1.LogLevel.Debug, "HubConnection failed to start successfully because of error '" + e_1 + "'.");
3191 return [2 /*return*/, Promise.reject(e_1)];
3192 case 4: return [2 /*return*/];
3193 }
3194 });
3195 });
3196 };
3197 HubConnection.prototype.startInternal = function () {
3198 return __awaiter(this, void 0, void 0, function () {
3199 var handshakePromise, handshakeRequest, e_2;
3200 var _this = this;
3201 return __generator(this, function (_a) {
3202 switch (_a.label) {
3203 case 0:
3204 this.stopDuringStartError = undefined;
3205 this.receivedHandshakeResponse = false;
3206 handshakePromise = new Promise(function (resolve, reject) {
3207 _this.handshakeResolver = resolve;
3208 _this.handshakeRejecter = reject;
3209 });
3210 return [4 /*yield*/, this.connection.start(this.protocol.transferFormat)];
3211 case 1:
3212 _a.sent();
3213 _a.label = 2;
3214 case 2:
3215 _a.trys.push([2, 5, , 7]);
3216 handshakeRequest = {
3217 protocol: this.protocol.name,
3218 version: this.protocol.version,
3219 };
3220 this.logger.log(ILogger_1.LogLevel.Debug, "Sending handshake request.");
3221 return [4 /*yield*/, this.sendMessage(this.handshakeProtocol.writeHandshakeRequest(handshakeRequest))];
3222 case 3:
3223 _a.sent();
3224 this.logger.log(ILogger_1.LogLevel.Information, "Using HubProtocol '" + this.protocol.name + "'.");
3225 // defensively cleanup timeout in case we receive a message from the server before we finish start
3226 this.cleanupTimeout();
3227 this.resetTimeoutPeriod();
3228 this.resetKeepAliveInterval();
3229 return [4 /*yield*/, handshakePromise];
3230 case 4:
3231 _a.sent();
3232 // It's important to check the stopDuringStartError instead of just relying on the handshakePromise
3233 // being rejected on close, because this continuation can run after both the handshake completed successfully
3234 // and the connection was closed.
3235 if (this.stopDuringStartError) {
3236 // It's important to throw instead of returning a rejected promise, because we don't want to allow any state
3237 // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise
3238 // will cause the calling continuation to get scheduled to run later.
3239 throw this.stopDuringStartError;
3240 }
3241 return [3 /*break*/, 7];
3242 case 5:
3243 e_2 = _a.sent();
3244 this.logger.log(ILogger_1.LogLevel.Debug, "Hub handshake failed with error '" + e_2 + "' during start(). Stopping HubConnection.");
3245 this.cleanupTimeout();
3246 this.cleanupPingTimer();
3247 // HttpConnection.stop() should not complete until after the onclose callback is invoked.
3248 // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
3249 return [4 /*yield*/, this.connection.stop(e_2)];
3250 case 6:
3251 // HttpConnection.stop() should not complete until after the onclose callback is invoked.
3252 // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
3253 _a.sent();
3254 throw e_2;
3255 case 7: return [2 /*return*/];
3256 }
3257 });
3258 });
3259 };
3260 /** Stops the connection.
3261 *
3262 * @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
3263 */
3264 HubConnection.prototype.stop = function () {
3265 return __awaiter(this, void 0, void 0, function () {
3266 var startPromise, e_3;
3267 return __generator(this, function (_a) {
3268 switch (_a.label) {
3269 case 0:
3270 startPromise = this.startPromise;
3271 this.stopPromise = this.stopInternal();
3272 return [4 /*yield*/, this.stopPromise];
3273 case 1:
3274 _a.sent();
3275 _a.label = 2;
3276 case 2:
3277 _a.trys.push([2, 4, , 5]);
3278 // Awaiting undefined continues immediately
3279 return [4 /*yield*/, startPromise];
3280 case 3:
3281 // Awaiting undefined continues immediately
3282 _a.sent();
3283 return [3 /*break*/, 5];
3284 case 4:
3285 e_3 = _a.sent();
3286 return [3 /*break*/, 5];
3287 case 5: return [2 /*return*/];
3288 }
3289 });
3290 });
3291 };
3292 HubConnection.prototype.stopInternal = function (error) {
3293 if (this.connectionState === HubConnectionState.Disconnected) {
3294 this.logger.log(ILogger_1.LogLevel.Debug, "Call to HubConnection.stop(" + error + ") ignored because it is already in the disconnected state.");
3295 return Promise.resolve();
3296 }
3297 if (this.connectionState === HubConnectionState.Disconnecting) {
3298 this.logger.log(ILogger_1.LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnecting state.");
3299 return this.stopPromise;
3300 }
3301 this.connectionState = HubConnectionState.Disconnecting;
3302 this.logger.log(ILogger_1.LogLevel.Debug, "Stopping HubConnection.");
3303 if (this.reconnectDelayHandle) {
3304 // We're in a reconnect delay which means the underlying connection is currently already stopped.
3305 // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and
3306 // fire the onclose callbacks.
3307 this.logger.log(ILogger_1.LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting.");
3308 clearTimeout(this.reconnectDelayHandle);
3309 this.reconnectDelayHandle = undefined;
3310 this.completeClose();
3311 return Promise.resolve();
3312 }
3313 this.cleanupTimeout();
3314 this.cleanupPingTimer();
3315 this.stopDuringStartError = error || new Error("The connection was stopped before the hub handshake could complete.");
3316 // HttpConnection.stop() should not complete until after either HttpConnection.start() fails
3317 // or the onclose callback is invoked. The onclose callback will transition the HubConnection
3318 // to the disconnected state if need be before HttpConnection.stop() completes.
3319 return this.connection.stop(error);
3320 };
3321 /** Invokes a streaming hub method on the server using the specified name and arguments.
3322 *
3323 * @typeparam T The type of the items returned by the server.
3324 * @param {string} methodName The name of the server method to invoke.
3325 * @param {any[]} args The arguments used to invoke the server method.
3326 * @returns {IStreamResult<T>} An object that yields results from the server as they are received.
3327 */
3328 HubConnection.prototype.stream = function (methodName) {
3329 var _this = this;
3330 var args = [];
3331 for (var _i = 1; _i < arguments.length; _i++) {
3332 args[_i - 1] = arguments[_i];
3333 }
3334 var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
3335 var invocationDescriptor = this.createStreamInvocation(methodName, args, streamIds);
3336 var promiseQueue;
3337 var subject = new Subject_1.Subject();
3338 subject.cancelCallback = function () {
3339 var cancelInvocation = _this.createCancelInvocation(invocationDescriptor.invocationId);
3340 delete _this.callbacks[invocationDescriptor.invocationId];
3341 return promiseQueue.then(function () {
3342 return _this.sendWithProtocol(cancelInvocation);
3343 });
3344 };
3345 this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) {
3346 if (error) {
3347 subject.error(error);
3348 return;
3349 }
3350 else if (invocationEvent) {
3351 // invocationEvent will not be null when an error is not passed to the callback
3352 if (invocationEvent.type === IHubProtocol_1.MessageType.Completion) {
3353 if (invocationEvent.error) {
3354 subject.error(new Error(invocationEvent.error));
3355 }
3356 else {
3357 subject.complete();
3358 }
3359 }
3360 else {
3361 subject.next((invocationEvent.item));
3362 }
3363 }
3364 };
3365 promiseQueue = this.sendWithProtocol(invocationDescriptor)
3366 .catch(function (e) {
3367 subject.error(e);
3368 delete _this.callbacks[invocationDescriptor.invocationId];
3369 });
3370 this.launchStreams(streams, promiseQueue);
3371 return subject;
3372 };
3373 HubConnection.prototype.sendMessage = function (message) {
3374 this.resetKeepAliveInterval();
3375 return this.connection.send(message);
3376 };
3377 /**
3378 * Sends a js object to the server.
3379 * @param message The js object to serialize and send.
3380 */
3381 HubConnection.prototype.sendWithProtocol = function (message) {
3382 return this.sendMessage(this.protocol.writeMessage(message));
3383 };
3384 /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
3385 *
3386 * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
3387 * be processing the invocation.
3388 *
3389 * @param {string} methodName The name of the server method to invoke.
3390 * @param {any[]} args The arguments used to invoke the server method.
3391 * @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
3392 */
3393 HubConnection.prototype.send = function (methodName) {
3394 var args = [];
3395 for (var _i = 1; _i < arguments.length; _i++) {
3396 args[_i - 1] = arguments[_i];
3397 }
3398 var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
3399 var sendPromise = this.sendWithProtocol(this.createInvocation(methodName, args, true, streamIds));
3400 this.launchStreams(streams, sendPromise);
3401 return sendPromise;
3402 };
3403 /** Invokes a hub method on the server using the specified name and arguments.
3404 *
3405 * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
3406 * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
3407 * resolving the Promise.
3408 *
3409 * @typeparam T The expected return type.
3410 * @param {string} methodName The name of the server method to invoke.
3411 * @param {any[]} args The arguments used to invoke the server method.
3412 * @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
3413 */
3414 HubConnection.prototype.invoke = function (methodName) {
3415 var _this = this;
3416 var args = [];
3417 for (var _i = 1; _i < arguments.length; _i++) {
3418 args[_i - 1] = arguments[_i];
3419 }
3420 var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
3421 var invocationDescriptor = this.createInvocation(methodName, args, false, streamIds);
3422 var p = new Promise(function (resolve, reject) {
3423 // invocationId will always have a value for a non-blocking invocation
3424 _this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) {
3425 if (error) {
3426 reject(error);
3427 return;
3428 }
3429 else if (invocationEvent) {
3430 // invocationEvent will not be null when an error is not passed to the callback
3431 if (invocationEvent.type === IHubProtocol_1.MessageType.Completion) {
3432 if (invocationEvent.error) {
3433 reject(new Error(invocationEvent.error));
3434 }
3435 else {
3436 resolve(invocationEvent.result);
3437 }
3438 }
3439 else {
3440 reject(new Error("Unexpected message type: " + invocationEvent.type));
3441 }
3442 }
3443 };
3444 var promiseQueue = _this.sendWithProtocol(invocationDescriptor)
3445 .catch(function (e) {
3446 reject(e);
3447 // invocationId will always have a value for a non-blocking invocation
3448 delete _this.callbacks[invocationDescriptor.invocationId];
3449 });
3450 _this.launchStreams(streams, promiseQueue);
3451 });
3452 return p;
3453 };
3454 /** Registers a handler that will be invoked when the hub method with the specified method name is invoked.
3455 *
3456 * @param {string} methodName The name of the hub method to define.
3457 * @param {Function} newMethod The handler that will be raised when the hub method is invoked.
3458 */
3459 HubConnection.prototype.on = function (methodName, newMethod) {
3460 if (!methodName || !newMethod) {
3461 return;
3462 }
3463 methodName = methodName.toLowerCase();
3464 if (!this.methods[methodName]) {
3465 this.methods[methodName] = [];
3466 }
3467 // Preventing adding the same handler multiple times.
3468 if (this.methods[methodName].indexOf(newMethod) !== -1) {
3469 return;
3470 }
3471 this.methods[methodName].push(newMethod);
3472 };
3473 HubConnection.prototype.off = function (methodName, method) {
3474 if (!methodName) {
3475 return;
3476 }
3477 methodName = methodName.toLowerCase();
3478 var handlers = this.methods[methodName];
3479 if (!handlers) {
3480 return;
3481 }
3482 if (method) {
3483 var removeIdx = handlers.indexOf(method);
3484 if (removeIdx !== -1) {
3485 handlers.splice(removeIdx, 1);
3486 if (handlers.length === 0) {
3487 delete this.methods[methodName];
3488 }
3489 }
3490 }
3491 else {
3492 delete this.methods[methodName];
3493 }
3494 };
3495 /** Registers a handler that will be invoked when the connection is closed.
3496 *
3497 * @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any).
3498 */
3499 HubConnection.prototype.onclose = function (callback) {
3500 if (callback) {
3501 this.closedCallbacks.push(callback);
3502 }
3503 };
3504 /** Registers a handler that will be invoked when the connection starts reconnecting.
3505 *
3506 * @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).
3507 */
3508 HubConnection.prototype.onreconnecting = function (callback) {
3509 if (callback) {
3510 this.reconnectingCallbacks.push(callback);
3511 }
3512 };
3513 /** Registers a handler that will be invoked when the connection successfully reconnects.
3514 *
3515 * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
3516 */
3517 HubConnection.prototype.onreconnected = function (callback) {
3518 if (callback) {
3519 this.reconnectedCallbacks.push(callback);
3520 }
3521 };
3522 HubConnection.prototype.processIncomingData = function (data) {
3523 this.cleanupTimeout();
3524 if (!this.receivedHandshakeResponse) {
3525 data = this.processHandshakeResponse(data);
3526 this.receivedHandshakeResponse = true;
3527 }
3528 // Data may have all been read when processing handshake response
3529 if (data) {
3530 // Parse the messages
3531 var messages = this.protocol.parseMessages(data, this.logger);
3532 for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) {
3533 var message = messages_1[_i];
3534 switch (message.type) {
3535 case IHubProtocol_1.MessageType.Invocation:
3536 this.invokeClientMethod(message);
3537 break;
3538 case IHubProtocol_1.MessageType.StreamItem:
3539 case IHubProtocol_1.MessageType.Completion:
3540 var callback = this.callbacks[message.invocationId];
3541 if (callback) {
3542 if (message.type === IHubProtocol_1.MessageType.Completion) {
3543 delete this.callbacks[message.invocationId];
3544 }
3545 callback(message);
3546 }
3547 break;
3548 case IHubProtocol_1.MessageType.Ping:
3549 // Don't care about pings
3550 break;
3551 case IHubProtocol_1.MessageType.Close:
3552 this.logger.log(ILogger_1.LogLevel.Information, "Close message received from server.");
3553 var error = message.error ? new Error("Server returned an error on close: " + message.error) : undefined;
3554 if (message.allowReconnect === true) {
3555 // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,
3556 // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.
3557 // tslint:disable-next-line:no-floating-promises
3558 this.connection.stop(error);
3559 }
3560 else {
3561 // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.
3562 this.stopPromise = this.stopInternal(error);
3563 }
3564 break;
3565 default:
3566 this.logger.log(ILogger_1.LogLevel.Warning, "Invalid message type: " + message.type + ".");
3567 break;
3568 }
3569 }
3570 }
3571 this.resetTimeoutPeriod();
3572 };
3573 HubConnection.prototype.processHandshakeResponse = function (data) {
3574 var _a;
3575 var responseMessage;
3576 var remainingData;
3577 try {
3578 _a = this.handshakeProtocol.parseHandshakeResponse(data), remainingData = _a[0], responseMessage = _a[1];
3579 }
3580 catch (e) {
3581 var message = "Error parsing handshake response: " + e;
3582 this.logger.log(ILogger_1.LogLevel.Error, message);
3583 var error = new Error(message);
3584 this.handshakeRejecter(error);
3585 throw error;
3586 }
3587 if (responseMessage.error) {
3588 var message = "Server returned handshake error: " + responseMessage.error;
3589 this.logger.log(ILogger_1.LogLevel.Error, message);
3590 var error = new Error(message);
3591 this.handshakeRejecter(error);
3592 throw error;
3593 }
3594 else {
3595 this.logger.log(ILogger_1.LogLevel.Debug, "Server handshake complete.");
3596 }
3597 this.handshakeResolver();
3598 return remainingData;
3599 };
3600 HubConnection.prototype.resetKeepAliveInterval = function () {
3601 var _this = this;
3602 this.cleanupPingTimer();
3603 this.pingServerHandle = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
3604 var _a;
3605 return __generator(this, function (_b) {
3606 switch (_b.label) {
3607 case 0:
3608 if (!(this.connectionState === HubConnectionState.Connected)) return [3 /*break*/, 4];
3609 _b.label = 1;
3610 case 1:
3611 _b.trys.push([1, 3, , 4]);
3612 return [4 /*yield*/, this.sendMessage(this.cachedPingMessage)];
3613 case 2:
3614 _b.sent();
3615 return [3 /*break*/, 4];
3616 case 3:
3617 _a = _b.sent();
3618 // We don't care about the error. It should be seen elsewhere in the client.
3619 // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering
3620 this.cleanupPingTimer();
3621 return [3 /*break*/, 4];
3622 case 4: return [2 /*return*/];
3623 }
3624 });
3625 }); }, this.keepAliveIntervalInMilliseconds);
3626 };
3627 HubConnection.prototype.resetTimeoutPeriod = function () {
3628 var _this = this;
3629 if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
3630 // Set the timeout timer
3631 this.timeoutHandle = setTimeout(function () { return _this.serverTimeout(); }, this.serverTimeoutInMilliseconds);
3632 }
3633 };
3634 HubConnection.prototype.serverTimeout = function () {
3635 // The server hasn't talked to us in a while. It doesn't like us anymore ... :(
3636 // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.
3637 // tslint:disable-next-line:no-floating-promises
3638 this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
3639 };
3640 HubConnection.prototype.invokeClientMethod = function (invocationMessage) {
3641 var _this = this;
3642 var methods = this.methods[invocationMessage.target.toLowerCase()];
3643 if (methods) {
3644 try {
3645 methods.forEach(function (m) { return m.apply(_this, invocationMessage.arguments); });
3646 }
3647 catch (e) {
3648 this.logger.log(ILogger_1.LogLevel.Error, "A callback for the method " + invocationMessage.target.toLowerCase() + " threw error '" + e + "'.");
3649 }
3650 if (invocationMessage.invocationId) {
3651 // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.
3652 var message = "Server requested a response, which is not supported in this version of the client.";
3653 this.logger.log(ILogger_1.LogLevel.Error, message);
3654 // We don't want to wait on the stop itself.
3655 this.stopPromise = this.stopInternal(new Error(message));
3656 }
3657 }
3658 else {
3659 this.logger.log(ILogger_1.LogLevel.Warning, "No client method with the name '" + invocationMessage.target + "' found.");
3660 }
3661 };
3662 HubConnection.prototype.connectionClosed = function (error) {
3663 this.logger.log(ILogger_1.LogLevel.Debug, "HubConnection.connectionClosed(" + error + ") called while in state " + this.connectionState + ".");
3664 // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.
3665 this.stopDuringStartError = this.stopDuringStartError || error || new Error("The underlying connection was closed before the hub handshake could complete.");
3666 // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.
3667 // If it has already completed, this should just noop.
3668 if (this.handshakeResolver) {
3669 this.handshakeResolver();
3670 }
3671 this.cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
3672 this.cleanupTimeout();
3673 this.cleanupPingTimer();
3674 if (this.connectionState === HubConnectionState.Disconnecting) {
3675 this.completeClose(error);
3676 }
3677 else if (this.connectionState === HubConnectionState.Connected && this.reconnectPolicy) {
3678 // tslint:disable-next-line:no-floating-promises
3679 this.reconnect(error);
3680 }
3681 else if (this.connectionState === HubConnectionState.Connected) {
3682 this.completeClose(error);
3683 }
3684 // If none of the above if conditions were true were called the HubConnection must be in either:
3685 // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.
3686 // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt
3687 // and potentially continue the reconnect() loop.
3688 // 3. The Disconnected state in which case we're already done.
3689 };
3690 HubConnection.prototype.completeClose = function (error) {
3691 var _this = this;
3692 if (this.connectionStarted) {
3693 this.connectionState = HubConnectionState.Disconnected;
3694 this.connectionStarted = false;
3695 try {
3696 this.closedCallbacks.forEach(function (c) { return c.apply(_this, [error]); });
3697 }
3698 catch (e) {
3699 this.logger.log(ILogger_1.LogLevel.Error, "An onclose callback called with error '" + error + "' threw error '" + e + "'.");
3700 }
3701 }
3702 };
3703 HubConnection.prototype.reconnect = function (error) {
3704 return __awaiter(this, void 0, void 0, function () {
3705 var reconnectStartTime, previousReconnectAttempts, retryError, nextRetryDelay, e_4;
3706 var _this = this;
3707 return __generator(this, function (_a) {
3708 switch (_a.label) {
3709 case 0:
3710 reconnectStartTime = Date.now();
3711 previousReconnectAttempts = 0;
3712 retryError = error !== undefined ? error : new Error("Attempting to reconnect due to a unknown error.");
3713 nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, 0, retryError);
3714 if (nextRetryDelay === null) {
3715 this.logger.log(ILogger_1.LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
3716 this.completeClose(error);
3717 return [2 /*return*/];
3718 }
3719 this.connectionState = HubConnectionState.Reconnecting;
3720 if (error) {
3721 this.logger.log(ILogger_1.LogLevel.Information, "Connection reconnecting because of error '" + error + "'.");
3722 }
3723 else {
3724 this.logger.log(ILogger_1.LogLevel.Information, "Connection reconnecting.");
3725 }
3726 if (this.onreconnecting) {
3727 try {
3728 this.reconnectingCallbacks.forEach(function (c) { return c.apply(_this, [error]); });
3729 }
3730 catch (e) {
3731 this.logger.log(ILogger_1.LogLevel.Error, "An onreconnecting callback called with error '" + error + "' threw error '" + e + "'.");
3732 }
3733 // Exit early if an onreconnecting callback called connection.stop().
3734 if (this.connectionState !== HubConnectionState.Reconnecting) {
3735 this.logger.log(ILogger_1.LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");
3736 return [2 /*return*/];
3737 }
3738 }
3739 _a.label = 1;
3740 case 1:
3741 if (!(nextRetryDelay !== null)) return [3 /*break*/, 7];
3742 this.logger.log(ILogger_1.LogLevel.Information, "Reconnect attempt number " + previousReconnectAttempts + " will start in " + nextRetryDelay + " ms.");
3743 return [4 /*yield*/, new Promise(function (resolve) {
3744 _this.reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);
3745 })];
3746 case 2:
3747 _a.sent();
3748 this.reconnectDelayHandle = undefined;
3749 if (this.connectionState !== HubConnectionState.Reconnecting) {
3750 this.logger.log(ILogger_1.LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting.");
3751 return [2 /*return*/];
3752 }
3753 _a.label = 3;
3754 case 3:
3755 _a.trys.push([3, 5, , 6]);
3756 return [4 /*yield*/, this.startInternal()];
3757 case 4:
3758 _a.sent();
3759 this.connectionState = HubConnectionState.Connected;
3760 this.logger.log(ILogger_1.LogLevel.Information, "HubConnection reconnected successfully.");
3761 if (this.onreconnected) {
3762 try {
3763 this.reconnectedCallbacks.forEach(function (c) { return c.apply(_this, [_this.connection.connectionId]); });
3764 }
3765 catch (e) {
3766 this.logger.log(ILogger_1.LogLevel.Error, "An onreconnected callback called with connectionId '" + this.connection.connectionId + "; threw error '" + e + "'.");
3767 }
3768 }
3769 return [2 /*return*/];
3770 case 5:
3771 e_4 = _a.sent();
3772 this.logger.log(ILogger_1.LogLevel.Information, "Reconnect attempt failed because of error '" + e_4 + "'.");
3773 if (this.connectionState !== HubConnectionState.Reconnecting) {
3774 this.logger.log(ILogger_1.LogLevel.Debug, "Connection left the reconnecting state during reconnect attempt. Done reconnecting.");
3775 return [2 /*return*/];
3776 }
3777 retryError = e_4 instanceof Error ? e_4 : new Error(e_4.toString());
3778 nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);
3779 return [3 /*break*/, 6];
3780 case 6: return [3 /*break*/, 1];
3781 case 7:
3782 this.logger.log(ILogger_1.LogLevel.Information, "Reconnect retries have been exhausted after " + (Date.now() - reconnectStartTime) + " ms and " + previousReconnectAttempts + " failed attempts. Connection disconnecting.");
3783 this.completeClose();
3784 return [2 /*return*/];
3785 }
3786 });
3787 });
3788 };
3789 HubConnection.prototype.getNextRetryDelay = function (previousRetryCount, elapsedMilliseconds, retryReason) {
3790 try {
3791 return this.reconnectPolicy.nextRetryDelayInMilliseconds({
3792 elapsedMilliseconds: elapsedMilliseconds,
3793 previousRetryCount: previousRetryCount,
3794 retryReason: retryReason,
3795 });
3796 }
3797 catch (e) {
3798 this.logger.log(ILogger_1.LogLevel.Error, "IRetryPolicy.nextRetryDelayInMilliseconds(" + previousRetryCount + ", " + elapsedMilliseconds + ") threw error '" + e + "'.");
3799 return null;
3800 }
3801 };
3802 HubConnection.prototype.cancelCallbacksWithError = function (error) {
3803 var callbacks = this.callbacks;
3804 this.callbacks = {};
3805 Object.keys(callbacks)
3806 .forEach(function (key) {
3807 var callback = callbacks[key];
3808 callback(null, error);
3809 });
3810 };
3811 HubConnection.prototype.cleanupPingTimer = function () {
3812 if (this.pingServerHandle) {
3813 clearTimeout(this.pingServerHandle);
3814 }
3815 };
3816 HubConnection.prototype.cleanupTimeout = function () {
3817 if (this.timeoutHandle) {
3818 clearTimeout(this.timeoutHandle);
3819 }
3820 };
3821 HubConnection.prototype.createInvocation = function (methodName, args, nonblocking, streamIds) {
3822 if (nonblocking) {
3823 return {
3824 arguments: args,
3825 streamIds: streamIds,
3826 target: methodName,
3827 type: IHubProtocol_1.MessageType.Invocation,
3828 };
3829 }
3830 else {
3831 var invocationId = this.invocationId;
3832 this.invocationId++;
3833 return {
3834 arguments: args,
3835 invocationId: invocationId.toString(),
3836 streamIds: streamIds,
3837 target: methodName,
3838 type: IHubProtocol_1.MessageType.Invocation,
3839 };
3840 }
3841 };
3842 HubConnection.prototype.launchStreams = function (streams, promiseQueue) {
3843 var _this = this;
3844 if (streams.length === 0) {
3845 return;
3846 }
3847 // Synchronize stream data so they arrive in-order on the server
3848 if (!promiseQueue) {
3849 promiseQueue = Promise.resolve();
3850 }
3851 var _loop_1 = function (streamId) {
3852 streams[streamId].subscribe({
3853 complete: function () {
3854 promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createCompletionMessage(streamId)); });
3855 },
3856 error: function (err) {
3857 var message;
3858 if (err instanceof Error) {
3859 message = err.message;
3860 }
3861 else if (err && err.toString) {
3862 message = err.toString();
3863 }
3864 else {
3865 message = "Unknown error";
3866 }
3867 promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createCompletionMessage(streamId, message)); });
3868 },
3869 next: function (item) {
3870 promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createStreamItemMessage(streamId, item)); });
3871 },
3872 });
3873 };
3874 // We want to iterate over the keys, since the keys are the stream ids
3875 // tslint:disable-next-line:forin
3876 for (var streamId in streams) {
3877 _loop_1(streamId);
3878 }
3879 };
3880 HubConnection.prototype.replaceStreamingParams = function (args) {
3881 var streams = [];
3882 var streamIds = [];
3883 for (var i = 0; i < args.length; i++) {
3884 var argument = args[i];
3885 if (this.isObservable(argument)) {
3886 var streamId = this.invocationId;
3887 this.invocationId++;
3888 // Store the stream for later use
3889 streams[streamId] = argument;
3890 streamIds.push(streamId.toString());
3891 // remove stream from args
3892 args.splice(i, 1);
3893 }
3894 }
3895 return [streams, streamIds];
3896 };
3897 HubConnection.prototype.isObservable = function (arg) {
3898 // This allows other stream implementations to just work (like rxjs)
3899 return arg && arg.subscribe && typeof arg.subscribe === "function";
3900 };
3901 HubConnection.prototype.createStreamInvocation = function (methodName, args, streamIds) {
3902 var invocationId = this.invocationId;
3903 this.invocationId++;
3904 return {
3905 arguments: args,
3906 invocationId: invocationId.toString(),
3907 streamIds: streamIds,
3908 target: methodName,
3909 type: IHubProtocol_1.MessageType.StreamInvocation,
3910 };
3911 };
3912 HubConnection.prototype.createCancelInvocation = function (id) {
3913 return {
3914 invocationId: id,
3915 type: IHubProtocol_1.MessageType.CancelInvocation,
3916 };
3917 };
3918 HubConnection.prototype.createStreamItemMessage = function (id, item) {
3919 return {
3920 invocationId: id,
3921 item: item,
3922 type: IHubProtocol_1.MessageType.StreamItem,
3923 };
3924 };
3925 HubConnection.prototype.createCompletionMessage = function (id, error, result) {
3926 if (error) {
3927 return {
3928 error: error,
3929 invocationId: id,
3930 type: IHubProtocol_1.MessageType.Completion,
3931 };
3932 }
3933 return {
3934 invocationId: id,
3935 result: result,
3936 type: IHubProtocol_1.MessageType.Completion,
3937 };
3938 };
3939 return HubConnection;
3940}());
3941exports.HubConnection = HubConnection;
3942
3943},{"./HandshakeProtocol":8,"./IHubProtocol":13,"./ILogger":14,"./Subject":21,"./Utils":23}],12:[function(require,module,exports){
3944"use strict";
3945// Copyright (c) .NET Foundation. All rights reserved.
3946// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3947var __assign = (this && this.__assign) || Object.assign || function(t) {
3948 for (var s, i = 1, n = arguments.length; i < n; i++) {
3949 s = arguments[i];
3950 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
3951 t[p] = s[p];
3952 }
3953 return t;
3954};
3955Object.defineProperty(exports, "__esModule", { value: true });
3956var DefaultReconnectPolicy_1 = require("./DefaultReconnectPolicy");
3957var HttpConnection_1 = require("./HttpConnection");
3958var HubConnection_1 = require("./HubConnection");
3959var ILogger_1 = require("./ILogger");
3960var JsonHubProtocol_1 = require("./JsonHubProtocol");
3961var Loggers_1 = require("./Loggers");
3962var Utils_1 = require("./Utils");
3963// tslint:disable:object-literal-sort-keys
3964var LogLevelNameMapping = {
3965 trace: ILogger_1.LogLevel.Trace,
3966 debug: ILogger_1.LogLevel.Debug,
3967 info: ILogger_1.LogLevel.Information,
3968 information: ILogger_1.LogLevel.Information,
3969 warn: ILogger_1.LogLevel.Warning,
3970 warning: ILogger_1.LogLevel.Warning,
3971 error: ILogger_1.LogLevel.Error,
3972 critical: ILogger_1.LogLevel.Critical,
3973 none: ILogger_1.LogLevel.None,
3974};
3975function parseLogLevel(name) {
3976 // Case-insensitive matching via lower-casing
3977 // Yes, I know case-folding is a complicated problem in Unicode, but we only support
3978 // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.
3979 var mapping = LogLevelNameMapping[name.toLowerCase()];
3980 if (typeof mapping !== "undefined") {
3981 return mapping;
3982 }
3983 else {
3984 throw new Error("Unknown log level: " + name);
3985 }
3986}
3987/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */
3988var HubConnectionBuilder = /** @class */ (function () {
3989 function HubConnectionBuilder() {
3990 }
3991 HubConnectionBuilder.prototype.configureLogging = function (logging) {
3992 Utils_1.Arg.isRequired(logging, "logging");
3993 if (isLogger(logging)) {
3994 this.logger = logging;
3995 }
3996 else if (typeof logging === "string") {
3997 var logLevel = parseLogLevel(logging);
3998 this.logger = new Utils_1.ConsoleLogger(logLevel);
3999 }
4000 else {
4001 this.logger = new Utils_1.ConsoleLogger(logging);
4002 }
4003 return this;
4004 };
4005 HubConnectionBuilder.prototype.withUrl = function (url, transportTypeOrOptions) {
4006 Utils_1.Arg.isRequired(url, "url");
4007 this.url = url;
4008 // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed
4009 // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.
4010 if (typeof transportTypeOrOptions === "object") {
4011 this.httpConnectionOptions = __assign({}, this.httpConnectionOptions, transportTypeOrOptions);
4012 }
4013 else {
4014 this.httpConnectionOptions = __assign({}, this.httpConnectionOptions, { transport: transportTypeOrOptions });
4015 }
4016 return this;
4017 };
4018 /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.
4019 *
4020 * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.
4021 */
4022 HubConnectionBuilder.prototype.withHubProtocol = function (protocol) {
4023 Utils_1.Arg.isRequired(protocol, "protocol");
4024 this.protocol = protocol;
4025 return this;
4026 };
4027 HubConnectionBuilder.prototype.withAutomaticReconnect = function (retryDelaysOrReconnectPolicy) {
4028 if (this.reconnectPolicy) {
4029 throw new Error("A reconnectPolicy has already been set.");
4030 }
4031 if (!retryDelaysOrReconnectPolicy) {
4032 this.reconnectPolicy = new DefaultReconnectPolicy_1.DefaultReconnectPolicy();
4033 }
4034 else if (Array.isArray(retryDelaysOrReconnectPolicy)) {
4035 this.reconnectPolicy = new DefaultReconnectPolicy_1.DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);
4036 }
4037 else {
4038 this.reconnectPolicy = retryDelaysOrReconnectPolicy;
4039 }
4040 return this;
4041 };
4042 /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.
4043 *
4044 * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.
4045 */
4046 HubConnectionBuilder.prototype.build = function () {
4047 // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one
4048 // provided to configureLogger
4049 var httpConnectionOptions = this.httpConnectionOptions || {};
4050 // If it's 'null', the user **explicitly** asked for null, don't mess with it.
4051 if (httpConnectionOptions.logger === undefined) {
4052 // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.
4053 httpConnectionOptions.logger = this.logger;
4054 }
4055 // Now create the connection
4056 if (!this.url) {
4057 throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");
4058 }
4059 var connection = new HttpConnection_1.HttpConnection(this.url, httpConnectionOptions);
4060 return HubConnection_1.HubConnection.create(connection, this.logger || Loggers_1.NullLogger.instance, this.protocol || new JsonHubProtocol_1.JsonHubProtocol(), this.reconnectPolicy);
4061 };
4062 return HubConnectionBuilder;
4063}());
4064exports.HubConnectionBuilder = HubConnectionBuilder;
4065function isLogger(logger) {
4066 return logger.log !== undefined;
4067}
4068
4069},{"./DefaultReconnectPolicy":6,"./HttpConnection":10,"./HubConnection":11,"./ILogger":14,"./JsonHubProtocol":16,"./Loggers":17,"./Utils":23}],13:[function(require,module,exports){
4070"use strict";
4071// Copyright (c) .NET Foundation. All rights reserved.
4072// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4073Object.defineProperty(exports, "__esModule", { value: true });
4074/** Defines the type of a Hub Message. */
4075var MessageType;
4076(function (MessageType) {
4077 /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */
4078 MessageType[MessageType["Invocation"] = 1] = "Invocation";
4079 /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */
4080 MessageType[MessageType["StreamItem"] = 2] = "StreamItem";
4081 /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */
4082 MessageType[MessageType["Completion"] = 3] = "Completion";
4083 /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */
4084 MessageType[MessageType["StreamInvocation"] = 4] = "StreamInvocation";
4085 /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */
4086 MessageType[MessageType["CancelInvocation"] = 5] = "CancelInvocation";
4087 /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */
4088 MessageType[MessageType["Ping"] = 6] = "Ping";
4089 /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */
4090 MessageType[MessageType["Close"] = 7] = "Close";
4091})(MessageType = exports.MessageType || (exports.MessageType = {}));
4092
4093},{}],14:[function(require,module,exports){
4094"use strict";
4095// Copyright (c) .NET Foundation. All rights reserved.
4096// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4097Object.defineProperty(exports, "__esModule", { value: true });
4098// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.
4099/** Indicates the severity of a log message.
4100 *
4101 * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.
4102 */
4103var LogLevel;
4104(function (LogLevel) {
4105 /** Log level for very low severity diagnostic messages. */
4106 LogLevel[LogLevel["Trace"] = 0] = "Trace";
4107 /** Log level for low severity diagnostic messages. */
4108 LogLevel[LogLevel["Debug"] = 1] = "Debug";
4109 /** Log level for informational diagnostic messages. */
4110 LogLevel[LogLevel["Information"] = 2] = "Information";
4111 /** Log level for diagnostic messages that indicate a non-fatal problem. */
4112 LogLevel[LogLevel["Warning"] = 3] = "Warning";
4113 /** Log level for diagnostic messages that indicate a failure in the current operation. */
4114 LogLevel[LogLevel["Error"] = 4] = "Error";
4115 /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */
4116 LogLevel[LogLevel["Critical"] = 5] = "Critical";
4117 /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */
4118 LogLevel[LogLevel["None"] = 6] = "None";
4119})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
4120
4121},{}],15:[function(require,module,exports){
4122"use strict";
4123// Copyright (c) .NET Foundation. All rights reserved.
4124// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4125Object.defineProperty(exports, "__esModule", { value: true });
4126// This will be treated as a bit flag in the future, so we keep it using power-of-two values.
4127/** Specifies a specific HTTP transport type. */
4128var HttpTransportType;
4129(function (HttpTransportType) {
4130 /** Specifies no transport preference. */
4131 HttpTransportType[HttpTransportType["None"] = 0] = "None";
4132 /** Specifies the WebSockets transport. */
4133 HttpTransportType[HttpTransportType["WebSockets"] = 1] = "WebSockets";
4134 /** Specifies the Server-Sent Events transport. */
4135 HttpTransportType[HttpTransportType["ServerSentEvents"] = 2] = "ServerSentEvents";
4136 /** Specifies the Long Polling transport. */
4137 HttpTransportType[HttpTransportType["LongPolling"] = 4] = "LongPolling";
4138})(HttpTransportType = exports.HttpTransportType || (exports.HttpTransportType = {}));
4139/** Specifies the transfer format for a connection. */
4140var TransferFormat;
4141(function (TransferFormat) {
4142 /** Specifies that only text data will be transmitted over the connection. */
4143 TransferFormat[TransferFormat["Text"] = 1] = "Text";
4144 /** Specifies that binary data will be transmitted over the connection. */
4145 TransferFormat[TransferFormat["Binary"] = 2] = "Binary";
4146})(TransferFormat = exports.TransferFormat || (exports.TransferFormat = {}));
4147
4148},{}],16:[function(require,module,exports){
4149"use strict";
4150// Copyright (c) .NET Foundation. All rights reserved.
4151// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4152Object.defineProperty(exports, "__esModule", { value: true });
4153var IHubProtocol_1 = require("./IHubProtocol");
4154var ILogger_1 = require("./ILogger");
4155var ITransport_1 = require("./ITransport");
4156var Loggers_1 = require("./Loggers");
4157var TextMessageFormat_1 = require("./TextMessageFormat");
4158var JSON_HUB_PROTOCOL_NAME = "json";
4159/** Implements the JSON Hub Protocol. */
4160var JsonHubProtocol = /** @class */ (function () {
4161 function JsonHubProtocol() {
4162 /** @inheritDoc */
4163 this.name = JSON_HUB_PROTOCOL_NAME;
4164 /** @inheritDoc */
4165 this.version = 1;
4166 /** @inheritDoc */
4167 this.transferFormat = ITransport_1.TransferFormat.Text;
4168 }
4169 /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.
4170 *
4171 * @param {string} input A string containing the serialized representation.
4172 * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.
4173 */
4174 JsonHubProtocol.prototype.parseMessages = function (input, logger) {
4175 // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error.
4176 if (typeof input !== "string") {
4177 throw new Error("Invalid input for JSON hub protocol. Expected a string.");
4178 }
4179 if (!input) {
4180 return [];
4181 }
4182 if (logger === null) {
4183 logger = Loggers_1.NullLogger.instance;
4184 }
4185 // Parse the messages
4186 var messages = TextMessageFormat_1.TextMessageFormat.parse(input);
4187 var hubMessages = [];
4188 for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) {
4189 var message = messages_1[_i];
4190 var parsedMessage = JSON.parse(message);
4191 if (typeof parsedMessage.type !== "number") {
4192 throw new Error("Invalid payload.");
4193 }
4194 switch (parsedMessage.type) {
4195 case IHubProtocol_1.MessageType.Invocation:
4196 this.isInvocationMessage(parsedMessage);
4197 break;
4198 case IHubProtocol_1.MessageType.StreamItem:
4199 this.isStreamItemMessage(parsedMessage);
4200 break;
4201 case IHubProtocol_1.MessageType.Completion:
4202 this.isCompletionMessage(parsedMessage);
4203 break;
4204 case IHubProtocol_1.MessageType.Ping:
4205 // Single value, no need to validate
4206 break;
4207 case IHubProtocol_1.MessageType.Close:
4208 // All optional values, no need to validate
4209 break;
4210 default:
4211 // Future protocol changes can add message types, old clients can ignore them
4212 logger.log(ILogger_1.LogLevel.Information, "Unknown message type '" + parsedMessage.type + "' ignored.");
4213 continue;
4214 }
4215 hubMessages.push(parsedMessage);
4216 }
4217 return hubMessages;
4218 };
4219 /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.
4220 *
4221 * @param {HubMessage} message The message to write.
4222 * @returns {string} A string containing the serialized representation of the message.
4223 */
4224 JsonHubProtocol.prototype.writeMessage = function (message) {
4225 return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(message));
4226 };
4227 JsonHubProtocol.prototype.isInvocationMessage = function (message) {
4228 this.assertNotEmptyString(message.target, "Invalid payload for Invocation message.");
4229 if (message.invocationId !== undefined) {
4230 this.assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message.");
4231 }
4232 };
4233 JsonHubProtocol.prototype.isStreamItemMessage = function (message) {
4234 this.assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message.");
4235 if (message.item === undefined) {
4236 throw new Error("Invalid payload for StreamItem message.");
4237 }
4238 };
4239 JsonHubProtocol.prototype.isCompletionMessage = function (message) {
4240 if (message.result && message.error) {
4241 throw new Error("Invalid payload for Completion message.");
4242 }
4243 if (!message.result && message.error) {
4244 this.assertNotEmptyString(message.error, "Invalid payload for Completion message.");
4245 }
4246 this.assertNotEmptyString(message.invocationId, "Invalid payload for Completion message.");
4247 };
4248 JsonHubProtocol.prototype.assertNotEmptyString = function (value, errorMessage) {
4249 if (typeof value !== "string" || value === "") {
4250 throw new Error(errorMessage);
4251 }
4252 };
4253 return JsonHubProtocol;
4254}());
4255exports.JsonHubProtocol = JsonHubProtocol;
4256
4257},{"./IHubProtocol":13,"./ILogger":14,"./ITransport":15,"./Loggers":17,"./TextMessageFormat":22}],17:[function(require,module,exports){
4258"use strict";
4259// Copyright (c) .NET Foundation. All rights reserved.
4260// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4261Object.defineProperty(exports, "__esModule", { value: true });
4262/** A logger that does nothing when log messages are sent to it. */
4263var NullLogger = /** @class */ (function () {
4264 function NullLogger() {
4265 }
4266 /** @inheritDoc */
4267 // tslint:disable-next-line
4268 NullLogger.prototype.log = function (_logLevel, _message) {
4269 };
4270 /** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */
4271 NullLogger.instance = new NullLogger();
4272 return NullLogger;
4273}());
4274exports.NullLogger = NullLogger;
4275
4276},{}],18:[function(require,module,exports){
4277"use strict";
4278// Copyright (c) .NET Foundation. All rights reserved.
4279// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4280var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4281 return new (P || (P = Promise))(function (resolve, reject) {
4282 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
4283 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
4284 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
4285 step((generator = generator.apply(thisArg, _arguments || [])).next());
4286 });
4287};
4288var __generator = (this && this.__generator) || function (thisArg, body) {
4289 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
4290 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
4291 function verb(n) { return function (v) { return step([n, v]); }; }
4292 function step(op) {
4293 if (f) throw new TypeError("Generator is already executing.");
4294 while (_) try {
4295 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
4296 if (y = 0, t) op = [op[0] & 2, t.value];
4297 switch (op[0]) {
4298 case 0: case 1: t = op; break;
4299 case 4: _.label++; return { value: op[1], done: false };
4300 case 5: _.label++; y = op[1]; op = [0]; continue;
4301 case 7: op = _.ops.pop(); _.trys.pop(); continue;
4302 default:
4303 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
4304 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
4305 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
4306 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
4307 if (t[2]) _.ops.pop();
4308 _.trys.pop(); continue;
4309 }
4310 op = body.call(thisArg, _);
4311 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
4312 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
4313 }
4314};
4315Object.defineProperty(exports, "__esModule", { value: true });
4316var AbortController_1 = require("./AbortController");
4317var Errors_1 = require("./Errors");
4318var ILogger_1 = require("./ILogger");
4319var ITransport_1 = require("./ITransport");
4320var Utils_1 = require("./Utils");
4321// Not exported from 'index', this type is internal.
4322/** @private */
4323var LongPollingTransport = /** @class */ (function () {
4324 function LongPollingTransport(httpClient, accessTokenFactory, logger, logMessageContent) {
4325 this.httpClient = httpClient;
4326 this.accessTokenFactory = accessTokenFactory;
4327 this.logger = logger;
4328 this.pollAbort = new AbortController_1.AbortController();
4329 this.logMessageContent = logMessageContent;
4330 this.running = false;
4331 this.onreceive = null;
4332 this.onclose = null;
4333 }
4334 Object.defineProperty(LongPollingTransport.prototype, "pollAborted", {
4335 // This is an internal type, not exported from 'index' so this is really just internal.
4336 get: function () {
4337 return this.pollAbort.aborted;
4338 },
4339 enumerable: true,
4340 configurable: true
4341 });
4342 LongPollingTransport.prototype.connect = function (url, transferFormat) {
4343 return __awaiter(this, void 0, void 0, function () {
4344 var pollOptions, token, pollUrl, response;
4345 return __generator(this, function (_a) {
4346 switch (_a.label) {
4347 case 0:
4348 Utils_1.Arg.isRequired(url, "url");
4349 Utils_1.Arg.isRequired(transferFormat, "transferFormat");
4350 Utils_1.Arg.isIn(transferFormat, ITransport_1.TransferFormat, "transferFormat");
4351 this.url = url;
4352 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Connecting.");
4353 // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)
4354 if (transferFormat === ITransport_1.TransferFormat.Binary &&
4355 (typeof XMLHttpRequest !== "undefined" && typeof new XMLHttpRequest().responseType !== "string")) {
4356 throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");
4357 }
4358 pollOptions = {
4359 abortSignal: this.pollAbort.signal,
4360 headers: {},
4361 timeout: 100000,
4362 };
4363 if (transferFormat === ITransport_1.TransferFormat.Binary) {
4364 pollOptions.responseType = "arraybuffer";
4365 }
4366 return [4 /*yield*/, this.getAccessToken()];
4367 case 1:
4368 token = _a.sent();
4369 this.updateHeaderToken(pollOptions, token);
4370 pollUrl = url + "&_=" + Date.now();
4371 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) polling: " + pollUrl + ".");
4372 return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)];
4373 case 2:
4374 response = _a.sent();
4375 if (response.statusCode !== 200) {
4376 this.logger.log(ILogger_1.LogLevel.Error, "(LongPolling transport) Unexpected response code: " + response.statusCode + ".");
4377 // Mark running as false so that the poll immediately ends and runs the close logic
4378 this.closeError = new Errors_1.HttpError(response.statusText || "", response.statusCode);
4379 this.running = false;
4380 }
4381 else {
4382 this.running = true;
4383 }
4384 this.receiving = this.poll(this.url, pollOptions);
4385 return [2 /*return*/];
4386 }
4387 });
4388 });
4389 };
4390 LongPollingTransport.prototype.getAccessToken = function () {
4391 return __awaiter(this, void 0, void 0, function () {
4392 return __generator(this, function (_a) {
4393 switch (_a.label) {
4394 case 0:
4395 if (!this.accessTokenFactory) return [3 /*break*/, 2];
4396 return [4 /*yield*/, this.accessTokenFactory()];
4397 case 1: return [2 /*return*/, _a.sent()];
4398 case 2: return [2 /*return*/, null];
4399 }
4400 });
4401 });
4402 };
4403 LongPollingTransport.prototype.updateHeaderToken = function (request, token) {
4404 if (!request.headers) {
4405 request.headers = {};
4406 }
4407 if (token) {
4408 // tslint:disable-next-line:no-string-literal
4409 request.headers["Authorization"] = "Bearer " + token;
4410 return;
4411 }
4412 // tslint:disable-next-line:no-string-literal
4413 if (request.headers["Authorization"]) {
4414 // tslint:disable-next-line:no-string-literal
4415 delete request.headers["Authorization"];
4416 }
4417 };
4418 LongPollingTransport.prototype.poll = function (url, pollOptions) {
4419 return __awaiter(this, void 0, void 0, function () {
4420 var token, pollUrl, response, e_1;
4421 return __generator(this, function (_a) {
4422 switch (_a.label) {
4423 case 0:
4424 _a.trys.push([0, , 8, 9]);
4425 _a.label = 1;
4426 case 1:
4427 if (!this.running) return [3 /*break*/, 7];
4428 return [4 /*yield*/, this.getAccessToken()];
4429 case 2:
4430 token = _a.sent();
4431 this.updateHeaderToken(pollOptions, token);
4432 _a.label = 3;
4433 case 3:
4434 _a.trys.push([3, 5, , 6]);
4435 pollUrl = url + "&_=" + Date.now();
4436 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) polling: " + pollUrl + ".");
4437 return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)];
4438 case 4:
4439 response = _a.sent();
4440 if (response.statusCode === 204) {
4441 this.logger.log(ILogger_1.LogLevel.Information, "(LongPolling transport) Poll terminated by server.");
4442 this.running = false;
4443 }
4444 else if (response.statusCode !== 200) {
4445 this.logger.log(ILogger_1.LogLevel.Error, "(LongPolling transport) Unexpected response code: " + response.statusCode + ".");
4446 // Unexpected status code
4447 this.closeError = new Errors_1.HttpError(response.statusText || "", response.statusCode);
4448 this.running = false;
4449 }
4450 else {
4451 // Process the response
4452 if (response.content) {
4453 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) data received. " + Utils_1.getDataDetail(response.content, this.logMessageContent) + ".");
4454 if (this.onreceive) {
4455 this.onreceive(response.content);
4456 }
4457 }
4458 else {
4459 // This is another way timeout manifest.
4460 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
4461 }
4462 }
4463 return [3 /*break*/, 6];
4464 case 5:
4465 e_1 = _a.sent();
4466 if (!this.running) {
4467 // Log but disregard errors that occur after stopping
4468 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Poll errored after shutdown: " + e_1.message);
4469 }
4470 else {
4471 if (e_1 instanceof Errors_1.TimeoutError) {
4472 // Ignore timeouts and reissue the poll.
4473 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
4474 }
4475 else {
4476 // Close the connection with the error as the result.
4477 this.closeError = e_1;
4478 this.running = false;
4479 }
4480 }
4481 return [3 /*break*/, 6];
4482 case 6: return [3 /*break*/, 1];
4483 case 7: return [3 /*break*/, 9];
4484 case 8:
4485 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Polling complete.");
4486 // We will reach here with pollAborted==false when the server returned a response causing the transport to stop.
4487 // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.
4488 if (!this.pollAborted) {
4489 this.raiseOnClose();
4490 }
4491 return [7 /*endfinally*/];
4492 case 9: return [2 /*return*/];
4493 }
4494 });
4495 });
4496 };
4497 LongPollingTransport.prototype.send = function (data) {
4498 return __awaiter(this, void 0, void 0, function () {
4499 return __generator(this, function (_a) {
4500 if (!this.running) {
4501 return [2 /*return*/, Promise.reject(new Error("Cannot send until the transport is connected"))];
4502 }
4503 return [2 /*return*/, Utils_1.sendMessage(this.logger, "LongPolling", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent)];
4504 });
4505 });
4506 };
4507 LongPollingTransport.prototype.stop = function () {
4508 return __awaiter(this, void 0, void 0, function () {
4509 var deleteOptions, token;
4510 return __generator(this, function (_a) {
4511 switch (_a.label) {
4512 case 0:
4513 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Stopping polling.");
4514 // Tell receiving loop to stop, abort any current request, and then wait for it to finish
4515 this.running = false;
4516 this.pollAbort.abort();
4517 _a.label = 1;
4518 case 1:
4519 _a.trys.push([1, , 5, 6]);
4520 return [4 /*yield*/, this.receiving];
4521 case 2:
4522 _a.sent();
4523 // Send DELETE to clean up long polling on the server
4524 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) sending DELETE request to " + this.url + ".");
4525 deleteOptions = {
4526 headers: {},
4527 };
4528 return [4 /*yield*/, this.getAccessToken()];
4529 case 3:
4530 token = _a.sent();
4531 this.updateHeaderToken(deleteOptions, token);
4532 return [4 /*yield*/, this.httpClient.delete(this.url, deleteOptions)];
4533 case 4:
4534 _a.sent();
4535 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) DELETE request sent.");
4536 return [3 /*break*/, 6];
4537 case 5:
4538 this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Stop finished.");
4539 // Raise close event here instead of in polling
4540 // It needs to happen after the DELETE request is sent
4541 this.raiseOnClose();
4542 return [7 /*endfinally*/];
4543 case 6: return [2 /*return*/];
4544 }
4545 });
4546 });
4547 };
4548 LongPollingTransport.prototype.raiseOnClose = function () {
4549 if (this.onclose) {
4550 var logMessage = "(LongPolling transport) Firing onclose event.";
4551 if (this.closeError) {
4552 logMessage += " Error: " + this.closeError;
4553 }
4554 this.logger.log(ILogger_1.LogLevel.Trace, logMessage);
4555 this.onclose(this.closeError);
4556 }
4557 };
4558 return LongPollingTransport;
4559}());
4560exports.LongPollingTransport = LongPollingTransport;
4561
4562},{"./AbortController":4,"./Errors":7,"./ILogger":14,"./ITransport":15,"./Utils":23}],19:[function(require,module,exports){
4563(function (Buffer){(function (){
4564"use strict";
4565// Copyright (c) .NET Foundation. All rights reserved.
4566// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4567var __extends = (this && this.__extends) || (function () {
4568 var extendStatics = Object.setPrototypeOf ||
4569 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
4570 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
4571 return function (d, b) {
4572 extendStatics(d, b);
4573 function __() { this.constructor = d; }
4574 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4575 };
4576})();
4577var __assign = (this && this.__assign) || Object.assign || function(t) {
4578 for (var s, i = 1, n = arguments.length; i < n; i++) {
4579 s = arguments[i];
4580 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
4581 t[p] = s[p];
4582 }
4583 return t;
4584};
4585Object.defineProperty(exports, "__esModule", { value: true });
4586var Errors_1 = require("./Errors");
4587var HttpClient_1 = require("./HttpClient");
4588var ILogger_1 = require("./ILogger");
4589var Utils_1 = require("./Utils");
4590var requestModule;
4591if (typeof XMLHttpRequest === "undefined") {
4592 // In order to ignore the dynamic require in webpack builds we need to do this magic
4593 // @ts-ignore: TS doesn't know about these names
4594 var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
4595 requestModule = requireFunc("request");
4596}
4597/** @private */
4598var NodeHttpClient = /** @class */ (function (_super) {
4599 __extends(NodeHttpClient, _super);
4600 function NodeHttpClient(logger) {
4601 var _this = _super.call(this) || this;
4602 if (typeof requestModule === "undefined") {
4603 throw new Error("The 'request' module could not be loaded.");
4604 }
4605 _this.logger = logger;
4606 _this.cookieJar = requestModule.jar();
4607 _this.request = requestModule.defaults({ jar: _this.cookieJar });
4608 return _this;
4609 }
4610 NodeHttpClient.prototype.send = function (httpRequest) {
4611 var _this = this;
4612 // Check that abort was not signaled before calling send
4613 if (httpRequest.abortSignal) {
4614 if (httpRequest.abortSignal.aborted) {
4615 return Promise.reject(new Errors_1.AbortError());
4616 }
4617 }
4618 return new Promise(function (resolve, reject) {
4619 var requestBody;
4620 if (Utils_1.isArrayBuffer(httpRequest.content)) {
4621 requestBody = Buffer.from(httpRequest.content);
4622 }
4623 else {
4624 requestBody = httpRequest.content || "";
4625 }
4626 var currentRequest = _this.request(httpRequest.url, {
4627 body: requestBody,
4628 // If binary is expected 'null' should be used, otherwise for text 'utf8'
4629 encoding: httpRequest.responseType === "arraybuffer" ? null : "utf8",
4630 headers: __assign({
4631 // Tell auth middleware to 401 instead of redirecting
4632 "X-Requested-With": "XMLHttpRequest" }, httpRequest.headers),
4633 method: httpRequest.method,
4634 timeout: httpRequest.timeout,
4635 }, function (error, response, body) {
4636 if (httpRequest.abortSignal) {
4637 httpRequest.abortSignal.onabort = null;
4638 }
4639 if (error) {
4640 if (error.code === "ETIMEDOUT") {
4641 _this.logger.log(ILogger_1.LogLevel.Warning, "Timeout from HTTP request.");
4642 reject(new Errors_1.TimeoutError());
4643 }
4644 _this.logger.log(ILogger_1.LogLevel.Warning, "Error from HTTP request. " + error);
4645 reject(error);
4646 return;
4647 }
4648 if (response.statusCode >= 200 && response.statusCode < 300) {
4649 resolve(new HttpClient_1.HttpResponse(response.statusCode, response.statusMessage || "", body));
4650 }
4651 else {
4652 reject(new Errors_1.HttpError(response.statusMessage || "", response.statusCode || 0));
4653 }
4654 });
4655 if (httpRequest.abortSignal) {
4656 httpRequest.abortSignal.onabort = function () {
4657 currentRequest.abort();
4658 reject(new Errors_1.AbortError());
4659 };
4660 }
4661 });
4662 };
4663 NodeHttpClient.prototype.getCookieString = function (url) {
4664 return this.cookieJar.getCookieString(url);
4665 };
4666 return NodeHttpClient;
4667}(HttpClient_1.HttpClient));
4668exports.NodeHttpClient = NodeHttpClient;
4669
4670}).call(this)}).call(this,require("buffer").Buffer)
4671},{"./Errors":7,"./HttpClient":9,"./ILogger":14,"./Utils":23,"buffer":2}],20:[function(require,module,exports){
4672"use strict";
4673// Copyright (c) .NET Foundation. All rights reserved.
4674// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4675var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4676 return new (P || (P = Promise))(function (resolve, reject) {
4677 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
4678 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
4679 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
4680 step((generator = generator.apply(thisArg, _arguments || [])).next());
4681 });
4682};
4683var __generator = (this && this.__generator) || function (thisArg, body) {
4684 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
4685 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
4686 function verb(n) { return function (v) { return step([n, v]); }; }
4687 function step(op) {
4688 if (f) throw new TypeError("Generator is already executing.");
4689 while (_) try {
4690 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
4691 if (y = 0, t) op = [op[0] & 2, t.value];
4692 switch (op[0]) {
4693 case 0: case 1: t = op; break;
4694 case 4: _.label++; return { value: op[1], done: false };
4695 case 5: _.label++; y = op[1]; op = [0]; continue;
4696 case 7: op = _.ops.pop(); _.trys.pop(); continue;
4697 default:
4698 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
4699 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
4700 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
4701 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
4702 if (t[2]) _.ops.pop();
4703 _.trys.pop(); continue;
4704 }
4705 op = body.call(thisArg, _);
4706 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
4707 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
4708 }
4709};
4710Object.defineProperty(exports, "__esModule", { value: true });
4711var ILogger_1 = require("./ILogger");
4712var ITransport_1 = require("./ITransport");
4713var Utils_1 = require("./Utils");
4714/** @private */
4715var ServerSentEventsTransport = /** @class */ (function () {
4716 function ServerSentEventsTransport(httpClient, accessTokenFactory, logger, logMessageContent, eventSourceConstructor) {
4717 this.httpClient = httpClient;
4718 this.accessTokenFactory = accessTokenFactory;
4719 this.logger = logger;
4720 this.logMessageContent = logMessageContent;
4721 this.eventSourceConstructor = eventSourceConstructor;
4722 this.onreceive = null;
4723 this.onclose = null;
4724 }
4725 ServerSentEventsTransport.prototype.connect = function (url, transferFormat) {
4726 return __awaiter(this, void 0, void 0, function () {
4727 var token;
4728 var _this = this;
4729 return __generator(this, function (_a) {
4730 switch (_a.label) {
4731 case 0:
4732 Utils_1.Arg.isRequired(url, "url");
4733 Utils_1.Arg.isRequired(transferFormat, "transferFormat");
4734 Utils_1.Arg.isIn(transferFormat, ITransport_1.TransferFormat, "transferFormat");
4735 this.logger.log(ILogger_1.LogLevel.Trace, "(SSE transport) Connecting.");
4736 // set url before accessTokenFactory because this.url is only for send and we set the auth header instead of the query string for send
4737 this.url = url;
4738 if (!this.accessTokenFactory) return [3 /*break*/, 2];
4739 return [4 /*yield*/, this.accessTokenFactory()];
4740 case 1:
4741 token = _a.sent();
4742 if (token) {
4743 url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token));
4744 }
4745 _a.label = 2;
4746 case 2: return [2 /*return*/, new Promise(function (resolve, reject) {
4747 var opened = false;
4748 if (transferFormat !== ITransport_1.TransferFormat.Text) {
4749 reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));
4750 return;
4751 }
4752 var eventSource;
4753 if (Utils_1.Platform.isBrowser || Utils_1.Platform.isWebWorker) {
4754 eventSource = new _this.eventSourceConstructor(url, { withCredentials: true });
4755 }
4756 else {
4757 // Non-browser passes cookies via the dictionary
4758 var cookies = _this.httpClient.getCookieString(url);
4759 eventSource = new _this.eventSourceConstructor(url, { withCredentials: true, headers: { Cookie: cookies } });
4760 }
4761 try {
4762 eventSource.onmessage = function (e) {
4763 if (_this.onreceive) {
4764 try {
4765 _this.logger.log(ILogger_1.LogLevel.Trace, "(SSE transport) data received. " + Utils_1.getDataDetail(e.data, _this.logMessageContent) + ".");
4766 _this.onreceive(e.data);
4767 }
4768 catch (error) {
4769 _this.close(error);
4770 return;
4771 }
4772 }
4773 };
4774 eventSource.onerror = function (e) {
4775 var error = new Error(e.data || "Error occurred");
4776 if (opened) {
4777 _this.close(error);
4778 }
4779 else {
4780 reject(error);
4781 }
4782 };
4783 eventSource.onopen = function () {
4784 _this.logger.log(ILogger_1.LogLevel.Information, "SSE connected to " + _this.url);
4785 _this.eventSource = eventSource;
4786 opened = true;
4787 resolve();
4788 };
4789 }
4790 catch (e) {
4791 reject(e);
4792 return;
4793 }
4794 })];
4795 }
4796 });
4797 });
4798 };
4799 ServerSentEventsTransport.prototype.send = function (data) {
4800 return __awaiter(this, void 0, void 0, function () {
4801 return __generator(this, function (_a) {
4802 if (!this.eventSource) {
4803 return [2 /*return*/, Promise.reject(new Error("Cannot send until the transport is connected"))];
4804 }
4805 return [2 /*return*/, Utils_1.sendMessage(this.logger, "SSE", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent)];
4806 });
4807 });
4808 };
4809 ServerSentEventsTransport.prototype.stop = function () {
4810 this.close();
4811 return Promise.resolve();
4812 };
4813 ServerSentEventsTransport.prototype.close = function (e) {
4814 if (this.eventSource) {
4815 this.eventSource.close();
4816 this.eventSource = undefined;
4817 if (this.onclose) {
4818 this.onclose(e);
4819 }
4820 }
4821 };
4822 return ServerSentEventsTransport;
4823}());
4824exports.ServerSentEventsTransport = ServerSentEventsTransport;
4825
4826},{"./ILogger":14,"./ITransport":15,"./Utils":23}],21:[function(require,module,exports){
4827"use strict";
4828// Copyright (c) .NET Foundation. All rights reserved.
4829// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4830Object.defineProperty(exports, "__esModule", { value: true });
4831var Utils_1 = require("./Utils");
4832/** Stream implementation to stream items to the server. */
4833var Subject = /** @class */ (function () {
4834 function Subject() {
4835 this.observers = [];
4836 }
4837 Subject.prototype.next = function (item) {
4838 for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
4839 var observer = _a[_i];
4840 observer.next(item);
4841 }
4842 };
4843 Subject.prototype.error = function (err) {
4844 for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
4845 var observer = _a[_i];
4846 if (observer.error) {
4847 observer.error(err);
4848 }
4849 }
4850 };
4851 Subject.prototype.complete = function () {
4852 for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
4853 var observer = _a[_i];
4854 if (observer.complete) {
4855 observer.complete();
4856 }
4857 }
4858 };
4859 Subject.prototype.subscribe = function (observer) {
4860 this.observers.push(observer);
4861 return new Utils_1.SubjectSubscription(this, observer);
4862 };
4863 return Subject;
4864}());
4865exports.Subject = Subject;
4866
4867},{"./Utils":23}],22:[function(require,module,exports){
4868"use strict";
4869// Copyright (c) .NET Foundation. All rights reserved.
4870// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4871Object.defineProperty(exports, "__esModule", { value: true });
4872// Not exported from index
4873/** @private */
4874var TextMessageFormat = /** @class */ (function () {
4875 function TextMessageFormat() {
4876 }
4877 TextMessageFormat.write = function (output) {
4878 return "" + output + TextMessageFormat.RecordSeparator;
4879 };
4880 TextMessageFormat.parse = function (input) {
4881 if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {
4882 throw new Error("Message is incomplete.");
4883 }
4884 var messages = input.split(TextMessageFormat.RecordSeparator);
4885 messages.pop();
4886 return messages;
4887 };
4888 TextMessageFormat.RecordSeparatorCode = 0x1e;
4889 TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);
4890 return TextMessageFormat;
4891}());
4892exports.TextMessageFormat = TextMessageFormat;
4893
4894},{}],23:[function(require,module,exports){
4895"use strict";
4896// Copyright (c) .NET Foundation. All rights reserved.
4897// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
4898var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4899 return new (P || (P = Promise))(function (resolve, reject) {
4900 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
4901 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
4902 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
4903 step((generator = generator.apply(thisArg, _arguments || [])).next());
4904 });
4905};
4906var __generator = (this && this.__generator) || function (thisArg, body) {
4907 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
4908 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
4909 function verb(n) { return function (v) { return step([n, v]); }; }
4910 function step(op) {
4911 if (f) throw new TypeError("Generator is already executing.");
4912 while (_) try {
4913 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
4914 if (y = 0, t) op = [op[0] & 2, t.value];
4915 switch (op[0]) {
4916 case 0: case 1: t = op; break;
4917 case 4: _.label++; return { value: op[1], done: false };
4918 case 5: _.label++; y = op[1]; op = [0]; continue;
4919 case 7: op = _.ops.pop(); _.trys.pop(); continue;
4920 default:
4921 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
4922 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
4923 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
4924 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
4925 if (t[2]) _.ops.pop();
4926 _.trys.pop(); continue;
4927 }
4928 op = body.call(thisArg, _);
4929 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
4930 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
4931 }
4932};
4933Object.defineProperty(exports, "__esModule", { value: true });
4934var ILogger_1 = require("./ILogger");
4935var Loggers_1 = require("./Loggers");
4936/** @private */
4937var Arg = /** @class */ (function () {
4938 function Arg() {
4939 }
4940 Arg.isRequired = function (val, name) {
4941 if (val === null || val === undefined) {
4942 throw new Error("The '" + name + "' argument is required.");
4943 }
4944 };
4945 Arg.isIn = function (val, values, name) {
4946 // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.
4947 if (!(val in values)) {
4948 throw new Error("Unknown " + name + " value: " + val + ".");
4949 }
4950 };
4951 return Arg;
4952}());
4953exports.Arg = Arg;
4954/** @private */
4955var Platform = /** @class */ (function () {
4956 function Platform() {
4957 }
4958 Object.defineProperty(Platform, "isBrowser", {
4959 get: function () {
4960 return typeof window === "object";
4961 },
4962 enumerable: true,
4963 configurable: true
4964 });
4965 Object.defineProperty(Platform, "isWebWorker", {
4966 get: function () {
4967 return typeof self === "object" && "importScripts" in self;
4968 },
4969 enumerable: true,
4970 configurable: true
4971 });
4972 Object.defineProperty(Platform, "isNode", {
4973 get: function () {
4974 return !this.isBrowser && !this.isWebWorker;
4975 },
4976 enumerable: true,
4977 configurable: true
4978 });
4979 return Platform;
4980}());
4981exports.Platform = Platform;
4982/** @private */
4983function getDataDetail(data, includeContent) {
4984 var detail = "";
4985 if (isArrayBuffer(data)) {
4986 detail = "Binary data of length " + data.byteLength;
4987 if (includeContent) {
4988 detail += ". Content: '" + formatArrayBuffer(data) + "'";
4989 }
4990 }
4991 else if (typeof data === "string") {
4992 detail = "String data of length " + data.length;
4993 if (includeContent) {
4994 detail += ". Content: '" + data + "'";
4995 }
4996 }
4997 return detail;
4998}
4999exports.getDataDetail = getDataDetail;
5000/** @private */
5001function formatArrayBuffer(data) {
5002 var view = new Uint8Array(data);
5003 // Uint8Array.map only supports returning another Uint8Array?
5004 var str = "";
5005 view.forEach(function (num) {
5006 var pad = num < 16 ? "0" : "";
5007 str += "0x" + pad + num.toString(16) + " ";
5008 });
5009 // Trim of trailing space.
5010 return str.substr(0, str.length - 1);
5011}
5012exports.formatArrayBuffer = formatArrayBuffer;
5013// Also in signalr-protocol-msgpack/Utils.ts
5014/** @private */
5015function isArrayBuffer(val) {
5016 return val && typeof ArrayBuffer !== "undefined" &&
5017 (val instanceof ArrayBuffer ||
5018 // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof
5019 (val.constructor && val.constructor.name === "ArrayBuffer"));
5020}
5021exports.isArrayBuffer = isArrayBuffer;
5022/** @private */
5023function sendMessage(logger, transportName, httpClient, url, accessTokenFactory, content, logMessageContent) {
5024 return __awaiter(this, void 0, void 0, function () {
5025 var _a, headers, token, responseType, response;
5026 return __generator(this, function (_b) {
5027 switch (_b.label) {
5028 case 0:
5029 if (!accessTokenFactory) return [3 /*break*/, 2];
5030 return [4 /*yield*/, accessTokenFactory()];
5031 case 1:
5032 token = _b.sent();
5033 if (token) {
5034 headers = (_a = {},
5035 _a["Authorization"] = "Bearer " + token,
5036 _a);
5037 }
5038 _b.label = 2;
5039 case 2:
5040 logger.log(ILogger_1.LogLevel.Trace, "(" + transportName + " transport) sending data. " + getDataDetail(content, logMessageContent) + ".");
5041 responseType = isArrayBuffer(content) ? "arraybuffer" : "text";
5042 return [4 /*yield*/, httpClient.post(url, {
5043 content: content,
5044 headers: headers,
5045 responseType: responseType,
5046 })];
5047 case 3:
5048 response = _b.sent();
5049 logger.log(ILogger_1.LogLevel.Trace, "(" + transportName + " transport) request complete. Response status: " + response.statusCode + ".");
5050 return [2 /*return*/];
5051 }
5052 });
5053 });
5054}
5055exports.sendMessage = sendMessage;
5056/** @private */
5057function createLogger(logger) {
5058 if (logger === undefined) {
5059 return new ConsoleLogger(ILogger_1.LogLevel.Information);
5060 }
5061 if (logger === null) {
5062 return Loggers_1.NullLogger.instance;
5063 }
5064 if (logger.log) {
5065 return logger;
5066 }
5067 return new ConsoleLogger(logger);
5068}
5069exports.createLogger = createLogger;
5070/** @private */
5071var SubjectSubscription = /** @class */ (function () {
5072 function SubjectSubscription(subject, observer) {
5073 this.subject = subject;
5074 this.observer = observer;
5075 }
5076 SubjectSubscription.prototype.dispose = function () {
5077 var index = this.subject.observers.indexOf(this.observer);
5078 if (index > -1) {
5079 this.subject.observers.splice(index, 1);
5080 }
5081 if (this.subject.observers.length === 0 && this.subject.cancelCallback) {
5082 this.subject.cancelCallback().catch(function (_) { });
5083 }
5084 };
5085 return SubjectSubscription;
5086}());
5087exports.SubjectSubscription = SubjectSubscription;
5088/** @private */
5089var ConsoleLogger = /** @class */ (function () {
5090 function ConsoleLogger(minimumLogLevel) {
5091 this.minimumLogLevel = minimumLogLevel;
5092 this.outputConsole = console;
5093 }
5094 ConsoleLogger.prototype.log = function (logLevel, message) {
5095 if (logLevel >= this.minimumLogLevel) {
5096 switch (logLevel) {
5097 case ILogger_1.LogLevel.Critical:
5098 case ILogger_1.LogLevel.Error:
5099 this.outputConsole.error("[" + new Date().toISOString() + "] " + ILogger_1.LogLevel[logLevel] + ": " + message);
5100 break;
5101 case ILogger_1.LogLevel.Warning:
5102 this.outputConsole.warn("[" + new Date().toISOString() + "] " + ILogger_1.LogLevel[logLevel] + ": " + message);
5103 break;
5104 case ILogger_1.LogLevel.Information:
5105 this.outputConsole.info("[" + new Date().toISOString() + "] " + ILogger_1.LogLevel[logLevel] + ": " + message);
5106 break;
5107 default:
5108 // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug
5109 this.outputConsole.log("[" + new Date().toISOString() + "] " + ILogger_1.LogLevel[logLevel] + ": " + message);
5110 break;
5111 }
5112 }
5113 };
5114 return ConsoleLogger;
5115}());
5116exports.ConsoleLogger = ConsoleLogger;
5117
5118},{"./ILogger":14,"./Loggers":17}],24:[function(require,module,exports){
5119"use strict";
5120// Copyright (c) .NET Foundation. All rights reserved.
5121// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
5122var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5123 return new (P || (P = Promise))(function (resolve, reject) {
5124 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5125 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5126 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
5127 step((generator = generator.apply(thisArg, _arguments || [])).next());
5128 });
5129};
5130var __generator = (this && this.__generator) || function (thisArg, body) {
5131 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
5132 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
5133 function verb(n) { return function (v) { return step([n, v]); }; }
5134 function step(op) {
5135 if (f) throw new TypeError("Generator is already executing.");
5136 while (_) try {
5137 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
5138 if (y = 0, t) op = [op[0] & 2, t.value];
5139 switch (op[0]) {
5140 case 0: case 1: t = op; break;
5141 case 4: _.label++; return { value: op[1], done: false };
5142 case 5: _.label++; y = op[1]; op = [0]; continue;
5143 case 7: op = _.ops.pop(); _.trys.pop(); continue;
5144 default:
5145 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
5146 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
5147 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
5148 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
5149 if (t[2]) _.ops.pop();
5150 _.trys.pop(); continue;
5151 }
5152 op = body.call(thisArg, _);
5153 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
5154 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
5155 }
5156};
5157Object.defineProperty(exports, "__esModule", { value: true });
5158var ILogger_1 = require("./ILogger");
5159var ITransport_1 = require("./ITransport");
5160var Utils_1 = require("./Utils");
5161/** @private */
5162var WebSocketTransport = /** @class */ (function () {
5163 function WebSocketTransport(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor) {
5164 this.logger = logger;
5165 this.accessTokenFactory = accessTokenFactory;
5166 this.logMessageContent = logMessageContent;
5167 this.webSocketConstructor = webSocketConstructor;
5168 this.httpClient = httpClient;
5169 this.onreceive = null;
5170 this.onclose = null;
5171 }
5172 WebSocketTransport.prototype.connect = function (url, transferFormat) {
5173 return __awaiter(this, void 0, void 0, function () {
5174 var token;
5175 var _this = this;
5176 return __generator(this, function (_a) {
5177 switch (_a.label) {
5178 case 0:
5179 Utils_1.Arg.isRequired(url, "url");
5180 Utils_1.Arg.isRequired(transferFormat, "transferFormat");
5181 Utils_1.Arg.isIn(transferFormat, ITransport_1.TransferFormat, "transferFormat");
5182 this.logger.log(ILogger_1.LogLevel.Trace, "(WebSockets transport) Connecting.");
5183 if (!this.accessTokenFactory) return [3 /*break*/, 2];
5184 return [4 /*yield*/, this.accessTokenFactory()];
5185 case 1:
5186 token = _a.sent();
5187 if (token) {
5188 url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token));
5189 }
5190 _a.label = 2;
5191 case 2: return [2 /*return*/, new Promise(function (resolve, reject) {
5192 url = url.replace(/^http/, "ws");
5193 var webSocket;
5194 var cookies = _this.httpClient.getCookieString(url);
5195 var opened = false;
5196 if (Utils_1.Platform.isNode && cookies) {
5197 // Only pass cookies when in non-browser environments
5198 webSocket = new _this.webSocketConstructor(url, undefined, {
5199 headers: {
5200 Cookie: "" + cookies,
5201 },
5202 });
5203 }
5204 if (!webSocket) {
5205 // Chrome is not happy with passing 'undefined' as protocol
5206 webSocket = new _this.webSocketConstructor(url);
5207 }
5208 if (transferFormat === ITransport_1.TransferFormat.Binary) {
5209 webSocket.binaryType = "arraybuffer";
5210 }
5211 // tslint:disable-next-line:variable-name
5212 webSocket.onopen = function (_event) {
5213 _this.logger.log(ILogger_1.LogLevel.Information, "WebSocket connected to " + url + ".");
5214 _this.webSocket = webSocket;
5215 opened = true;
5216 resolve();
5217 };
5218 webSocket.onerror = function (event) {
5219 var error = null;
5220 // ErrorEvent is a browser only type we need to check if the type exists before using it
5221 if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
5222 error = event.error;
5223 }
5224 else {
5225 error = new Error("There was an error with the transport.");
5226 }
5227 reject(error);
5228 };
5229 webSocket.onmessage = function (message) {
5230 _this.logger.log(ILogger_1.LogLevel.Trace, "(WebSockets transport) data received. " + Utils_1.getDataDetail(message.data, _this.logMessageContent) + ".");
5231 if (_this.onreceive) {
5232 _this.onreceive(message.data);
5233 }
5234 };
5235 webSocket.onclose = function (event) {
5236 // Don't call close handler if connection was never established
5237 // We'll reject the connect call instead
5238 if (opened) {
5239 _this.close(event);
5240 }
5241 else {
5242 var error = null;
5243 // ErrorEvent is a browser only type we need to check if the type exists before using it
5244 if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
5245 error = event.error;
5246 }
5247 else {
5248 error = new Error("There was an error with the transport.");
5249 }
5250 reject(error);
5251 }
5252 };
5253 })];
5254 }
5255 });
5256 });
5257 };
5258 WebSocketTransport.prototype.send = function (data) {
5259 if (this.webSocket && this.webSocket.readyState === this.webSocketConstructor.OPEN) {
5260 this.logger.log(ILogger_1.LogLevel.Trace, "(WebSockets transport) sending data. " + Utils_1.getDataDetail(data, this.logMessageContent) + ".");
5261 this.webSocket.send(data);
5262 return Promise.resolve();
5263 }
5264 return Promise.reject("WebSocket is not in the OPEN state");
5265 };
5266 WebSocketTransport.prototype.stop = function () {
5267 if (this.webSocket) {
5268 // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning
5269 // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects
5270 this.close(undefined);
5271 }
5272 return Promise.resolve();
5273 };
5274 WebSocketTransport.prototype.close = function (event) {
5275 // webSocket will be null if the transport did not start successfully
5276 if (this.webSocket) {
5277 // Clear websocket handlers because we are considering the socket closed now
5278 this.webSocket.onclose = function () { };
5279 this.webSocket.onmessage = function () { };
5280 this.webSocket.onerror = function () { };
5281 this.webSocket.close();
5282 this.webSocket = undefined;
5283 }
5284 this.logger.log(ILogger_1.LogLevel.Trace, "(WebSockets transport) socket closed.");
5285 if (this.onclose) {
5286 if (event && (event.wasClean === false || event.code !== 1000)) {
5287 this.onclose(new Error("WebSocket closed with status code: " + event.code + " (" + event.reason + ")."));
5288 }
5289 else {
5290 this.onclose();
5291 }
5292 }
5293 };
5294 return WebSocketTransport;
5295}());
5296exports.WebSocketTransport = WebSocketTransport;
5297
5298},{"./ILogger":14,"./ITransport":15,"./Utils":23}],25:[function(require,module,exports){
5299"use strict";
5300// Copyright (c) .NET Foundation. All rights reserved.
5301// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
5302var __extends = (this && this.__extends) || (function () {
5303 var extendStatics = Object.setPrototypeOf ||
5304 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5305 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5306 return function (d, b) {
5307 extendStatics(d, b);
5308 function __() { this.constructor = d; }
5309 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5310 };
5311})();
5312Object.defineProperty(exports, "__esModule", { value: true });
5313var Errors_1 = require("./Errors");
5314var HttpClient_1 = require("./HttpClient");
5315var ILogger_1 = require("./ILogger");
5316var XhrHttpClient = /** @class */ (function (_super) {
5317 __extends(XhrHttpClient, _super);
5318 function XhrHttpClient(logger) {
5319 var _this = _super.call(this) || this;
5320 _this.logger = logger;
5321 return _this;
5322 }
5323 /** @inheritDoc */
5324 XhrHttpClient.prototype.send = function (request) {
5325 var _this = this;
5326 // Check that abort was not signaled before calling send
5327 if (request.abortSignal && request.abortSignal.aborted) {
5328 return Promise.reject(new Errors_1.AbortError());
5329 }
5330 if (!request.method) {
5331 return Promise.reject(new Error("No method defined."));
5332 }
5333 if (!request.url) {
5334 return Promise.reject(new Error("No url defined."));
5335 }
5336 return new Promise(function (resolve, reject) {
5337 var xhr = new XMLHttpRequest();
5338 xhr.open(request.method, request.url, true);
5339 xhr.withCredentials = true;
5340 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
5341 // Explicitly setting the Content-Type header for React Native on Android platform.
5342 xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
5343 var headers = request.headers;
5344 if (headers) {
5345 Object.keys(headers)
5346 .forEach(function (header) {
5347 xhr.setRequestHeader(header, headers[header]);
5348 });
5349 }
5350 if (request.responseType) {
5351 xhr.responseType = request.responseType;
5352 }
5353 if (request.abortSignal) {
5354 request.abortSignal.onabort = function () {
5355 xhr.abort();
5356 reject(new Errors_1.AbortError());
5357 };
5358 }
5359 if (request.timeout) {
5360 xhr.timeout = request.timeout;
5361 }
5362 xhr.onload = function () {
5363 if (request.abortSignal) {
5364 request.abortSignal.onabort = null;
5365 }
5366 if (xhr.status >= 200 && xhr.status < 300) {
5367 resolve(new HttpClient_1.HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));
5368 }
5369 else {
5370 reject(new Errors_1.HttpError(xhr.statusText, xhr.status));
5371 }
5372 };
5373 xhr.onerror = function () {
5374 _this.logger.log(ILogger_1.LogLevel.Warning, "Error from HTTP request. " + xhr.status + ": " + xhr.statusText + ".");
5375 reject(new Errors_1.HttpError(xhr.statusText, xhr.status));
5376 };
5377 xhr.ontimeout = function () {
5378 _this.logger.log(ILogger_1.LogLevel.Warning, "Timeout from HTTP request.");
5379 reject(new Errors_1.TimeoutError());
5380 };
5381 xhr.send(request.content || "");
5382 });
5383 };
5384 return XhrHttpClient;
5385}(HttpClient_1.HttpClient));
5386exports.XhrHttpClient = XhrHttpClient;
5387
5388},{"./Errors":7,"./HttpClient":9,"./ILogger":14}],26:[function(require,module,exports){
5389"use strict";
5390// Copyright (c) .NET Foundation. All rights reserved.
5391// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
5392Object.defineProperty(exports, "__esModule", { value: true });
5393// Version token that will be replaced by the prepack command
5394/** The version of the SignalR client. */
5395exports.VERSION = "3.1.9";
5396var Errors_1 = require("./Errors");
5397exports.AbortError = Errors_1.AbortError;
5398exports.HttpError = Errors_1.HttpError;
5399exports.TimeoutError = Errors_1.TimeoutError;
5400var HttpClient_1 = require("./HttpClient");
5401exports.HttpClient = HttpClient_1.HttpClient;
5402exports.HttpResponse = HttpClient_1.HttpResponse;
5403var DefaultHttpClient_1 = require("./DefaultHttpClient");
5404exports.DefaultHttpClient = DefaultHttpClient_1.DefaultHttpClient;
5405var HubConnection_1 = require("./HubConnection");
5406exports.HubConnection = HubConnection_1.HubConnection;
5407exports.HubConnectionState = HubConnection_1.HubConnectionState;
5408var HubConnectionBuilder_1 = require("./HubConnectionBuilder");
5409exports.HubConnectionBuilder = HubConnectionBuilder_1.HubConnectionBuilder;
5410var IHubProtocol_1 = require("./IHubProtocol");
5411exports.MessageType = IHubProtocol_1.MessageType;
5412var ILogger_1 = require("./ILogger");
5413exports.LogLevel = ILogger_1.LogLevel;
5414var ITransport_1 = require("./ITransport");
5415exports.HttpTransportType = ITransport_1.HttpTransportType;
5416exports.TransferFormat = ITransport_1.TransferFormat;
5417var Loggers_1 = require("./Loggers");
5418exports.NullLogger = Loggers_1.NullLogger;
5419var JsonHubProtocol_1 = require("./JsonHubProtocol");
5420exports.JsonHubProtocol = JsonHubProtocol_1.JsonHubProtocol;
5421var Subject_1 = require("./Subject");
5422exports.Subject = Subject_1.Subject;
5423
5424},{"./DefaultHttpClient":5,"./Errors":7,"./HttpClient":9,"./HubConnection":11,"./HubConnectionBuilder":12,"./IHubProtocol":13,"./ILogger":14,"./ITransport":15,"./JsonHubProtocol":16,"./Loggers":17,"./Subject":21}],27:[function(require,module,exports){
5425require('@microsoft/signalr')
5426},{"@microsoft/signalr":26}]},{},[27]);
5427