polyfill-library 4.0.0 → 4.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,1050 +1,1077 @@
1
1
 
2
2
  // EventSource
3
- /** @license
4
- * eventsource.js
5
- * Available under MIT License (MIT)
6
- * https://github.com/Yaffle/EventSource/
7
- */
8
-
9
- /*jslint indent: 2, vars: true, plusplus: true */
10
- /*global setTimeout, clearTimeout */
11
-
12
- (function (global) {
13
- "use strict";
14
-
15
- var setTimeout = global.setTimeout;
16
- var clearTimeout = global.clearTimeout;
17
- var XMLHttpRequest = global.XMLHttpRequest;
18
- var XDomainRequest = global.XDomainRequest;
19
- var ActiveXObject = global.ActiveXObject;
20
- var NativeEventSource = global.EventSource;
21
-
22
- var document = global.document;
23
- var Promise = global.Promise;
24
- var fetch = global.fetch;
25
- var Response = global.Response;
26
- var TextDecoder = global.TextDecoder;
27
- var TextEncoder = global.TextEncoder;
28
- var AbortController = global.AbortController;
29
-
30
- if (typeof window !== "undefined" && typeof document !== "undefined" && !("readyState" in document) && document.body == null) { // Firefox 2
31
- document.readyState = "loading";
32
- window.addEventListener("load", function (event) {
33
- document.readyState = "complete";
34
- }, false);
35
- }
36
-
37
- if (XMLHttpRequest == null && ActiveXObject != null) { // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6
38
- XMLHttpRequest = function () {
39
- return new ActiveXObject("Microsoft.XMLHTTP");
40
- };
41
- }
42
-
43
- if (Object.create == undefined) {
44
- Object.create = function (C) {
45
- function F(){}
46
- F.prototype = C;
47
- return new F();
48
- };
49
- }
50
-
51
- if (!Date.now) {
52
- Date.now = function now() {
53
- return new Date().getTime();
54
- };
55
- }
56
-
57
- // see #118 (Promise#finally with polyfilled Promise)
58
- // see #123 (data URLs crash Edge)
59
- // see #125 (CSP violations)
60
- // see pull/#138
61
- // => No way to polyfill Promise#finally
62
-
63
- if (AbortController == undefined) {
64
- var originalFetch2 = fetch;
65
- fetch = function (url, options) {
66
- var signal = options.signal;
67
- return originalFetch2(url, {headers: options.headers, credentials: options.credentials, cache: options.cache}).then(function (response) {
68
- var reader = response.body.getReader();
69
- signal._reader = reader;
70
- if (signal._aborted) {
71
- signal._reader.cancel();
72
- }
73
- return {
74
- status: response.status,
75
- statusText: response.statusText,
76
- headers: response.headers,
77
- body: {
78
- getReader: function () {
79
- return reader;
80
- }
81
- }
82
- };
83
- });
84
- };
85
- AbortController = function () {
86
- this.signal = {
87
- _reader: null,
88
- _aborted: false
89
- };
90
- this.abort = function () {
91
- if (this.signal._reader != null) {
92
- this.signal._reader.cancel();
93
- }
94
- this.signal._aborted = true;
95
- };
96
- };
97
- }
98
-
99
- function TextDecoderPolyfill() {
100
- this.bitsNeeded = 0;
101
- this.codePoint = 0;
102
- }
103
-
104
- TextDecoderPolyfill.prototype.decode = function (octets) {
105
- function valid(codePoint, shift, octetsCount) {
106
- if (octetsCount === 1) {
107
- return codePoint >= 0x0080 >> shift && codePoint << shift <= 0x07FF;
108
- }
109
- if (octetsCount === 2) {
110
- return codePoint >= 0x0800 >> shift && codePoint << shift <= 0xD7FF || codePoint >= 0xE000 >> shift && codePoint << shift <= 0xFFFF;
111
- }
112
- if (octetsCount === 3) {
113
- return codePoint >= 0x010000 >> shift && codePoint << shift <= 0x10FFFF;
114
- }
115
- throw new Error();
116
- }
117
- function octetsCount(bitsNeeded, codePoint) {
118
- if (bitsNeeded === 6 * 1) {
119
- return codePoint >> 6 > 15 ? 3 : codePoint > 31 ? 2 : 1;
120
- }
121
- if (bitsNeeded === 6 * 2) {
122
- return codePoint > 15 ? 3 : 2;
123
- }
124
- if (bitsNeeded === 6 * 3) {
125
- return 3;
126
- }
127
- throw new Error();
128
- }
129
- var REPLACER = 0xFFFD;
130
- var string = "";
131
- var bitsNeeded = this.bitsNeeded;
132
- var codePoint = this.codePoint;
133
- for (var i = 0; i < octets.length; i += 1) {
134
- var octet = octets[i];
135
- if (bitsNeeded !== 0) {
136
- if (octet < 128 || octet > 191 || !valid(codePoint << 6 | octet & 63, bitsNeeded - 6, octetsCount(bitsNeeded, codePoint))) {
137
- bitsNeeded = 0;
138
- codePoint = REPLACER;
139
- string += String.fromCharCode(codePoint);
140
- }
141
- }
142
- if (bitsNeeded === 0) {
143
- if (octet >= 0 && octet <= 127) {
144
- bitsNeeded = 0;
145
- codePoint = octet;
146
- } else if (octet >= 192 && octet <= 223) {
147
- bitsNeeded = 6 * 1;
148
- codePoint = octet & 31;
149
- } else if (octet >= 224 && octet <= 239) {
150
- bitsNeeded = 6 * 2;
151
- codePoint = octet & 15;
152
- } else if (octet >= 240 && octet <= 247) {
153
- bitsNeeded = 6 * 3;
154
- codePoint = octet & 7;
155
- } else {
156
- bitsNeeded = 0;
157
- codePoint = REPLACER;
158
- }
159
- if (bitsNeeded !== 0 && !valid(codePoint, bitsNeeded, octetsCount(bitsNeeded, codePoint))) {
160
- bitsNeeded = 0;
161
- codePoint = REPLACER;
162
- }
163
- } else {
164
- bitsNeeded -= 6;
165
- codePoint = codePoint << 6 | octet & 63;
166
- }
167
- if (bitsNeeded === 0) {
168
- if (codePoint <= 0xFFFF) {
169
- string += String.fromCharCode(codePoint);
170
- } else {
171
- string += String.fromCharCode(0xD800 + (codePoint - 0xFFFF - 1 >> 10));
172
- string += String.fromCharCode(0xDC00 + (codePoint - 0xFFFF - 1 & 0x3FF));
173
- }
174
- }
175
- }
176
- this.bitsNeeded = bitsNeeded;
177
- this.codePoint = codePoint;
178
- return string;
179
- };
180
-
181
- // Firefox < 38 throws an error with stream option
182
- var supportsStreamOption = function () {
183
- try {
184
- return new TextDecoder().decode(new TextEncoder().encode("test"), {stream: true}) === "test";
185
- } catch (error) {
186
- console.debug("TextDecoder does not support streaming option. Using polyfill instead: " + error);
187
- }
188
- return false;
189
- };
190
-
191
- // IE, Edge
192
- if (TextDecoder == undefined || TextEncoder == undefined || !supportsStreamOption()) {
193
- TextDecoder = TextDecoderPolyfill;
194
- }
195
-
196
- var k = function () {
197
- };
198
-
199
- function XHRWrapper(xhr) {
200
- this.withCredentials = false;
201
- this.readyState = 0;
202
- this.status = 0;
203
- this.statusText = "";
204
- this.responseText = "";
205
- this.onprogress = k;
206
- this.onload = k;
207
- this.onerror = k;
208
- this.onreadystatechange = k;
209
- this._contentType = "";
210
- this._xhr = xhr;
211
- this._sendTimeout = 0;
212
- this._abort = k;
213
- }
214
-
215
- XHRWrapper.prototype.open = function (method, url) {
216
- this._abort(true);
217
-
218
- var that = this;
219
- var xhr = this._xhr;
220
- var state = 1;
221
- var timeout = 0;
222
-
223
- this._abort = function (silent) {
224
- if (that._sendTimeout !== 0) {
225
- clearTimeout(that._sendTimeout);
226
- that._sendTimeout = 0;
227
- }
228
- if (state === 1 || state === 2 || state === 3) {
229
- state = 4;
230
- xhr.onload = k;
231
- xhr.onerror = k;
232
- xhr.onabort = k;
233
- xhr.onprogress = k;
234
- xhr.onreadystatechange = k;
235
- // IE 8 - 9: XDomainRequest#abort() does not fire any event
236
- // Opera < 10: XMLHttpRequest#abort() does not fire any event
237
- xhr.abort();
238
- if (timeout !== 0) {
239
- clearTimeout(timeout);
240
- timeout = 0;
241
- }
242
- if (!silent) {
243
- that.readyState = 4;
244
- that.onabort(null);
245
- that.onreadystatechange();
246
- }
247
- }
248
- state = 0;
249
- };
250
-
251
- var onStart = function () {
252
- if (state === 1) {
253
- //state = 2;
254
- var status = 0;
255
- var statusText = "";
256
- var contentType = undefined;
257
- if (!("contentType" in xhr)) {
258
- try {
259
- status = xhr.status;
260
- statusText = xhr.statusText;
261
- contentType = xhr.getResponseHeader("Content-Type");
262
- } catch (error) {
263
- // IE < 10 throws exception for `xhr.status` when xhr.readyState === 2 || xhr.readyState === 3
264
- // Opera < 11 throws exception for `xhr.status` when xhr.readyState === 2
265
- // https://bugs.webkit.org/show_bug.cgi?id=29121
266
- status = 0;
267
- statusText = "";
268
- contentType = undefined;
269
- // Firefox < 14, Chrome ?, Safari ?
270
- // https://bugs.webkit.org/show_bug.cgi?id=29658
271
- // https://bugs.webkit.org/show_bug.cgi?id=77854
272
- }
273
- } else {
274
- status = 200;
275
- statusText = "OK";
276
- contentType = xhr.contentType;
277
- }
278
- if (status !== 0) {
279
- state = 2;
280
- that.readyState = 2;
281
- that.status = status;
282
- that.statusText = statusText;
283
- that._contentType = contentType;
284
- that.onreadystatechange();
285
- }
286
- }
287
- };
288
- var onProgress = function () {
289
- onStart();
290
- if (state === 2 || state === 3) {
291
- state = 3;
292
- var responseText = "";
293
- try {
294
- responseText = xhr.responseText;
295
- } catch (error) {
296
- // IE 8 - 9 with XMLHttpRequest
297
- }
298
- that.readyState = 3;
299
- that.responseText = responseText;
300
- that.onprogress();
301
- }
302
- };
303
- var onFinish = function (type, event) {
304
- if (event == null || event.preventDefault == null) {
305
- event = {
306
- preventDefault: k
307
- };
308
- }
309
- // Firefox 52 fires "readystatechange" (xhr.readyState === 4) without final "readystatechange" (xhr.readyState === 3)
310
- // IE 8 fires "onload" without "onprogress"
311
- onProgress();
312
- if (state === 1 || state === 2 || state === 3) {
313
- state = 4;
314
- if (timeout !== 0) {
315
- clearTimeout(timeout);
316
- timeout = 0;
317
- }
318
- that.readyState = 4;
319
- if (type === "load") {
320
- that.onload(event);
321
- } else if (type === "error") {
322
- that.onerror(event);
323
- } else if (type === "abort") {
324
- that.onabort(event);
325
- } else {
326
- throw new TypeError();
327
- }
328
- that.onreadystatechange();
329
- }
330
- };
331
- var onReadyStateChange = function (event) {
332
- if (xhr != undefined) { // Opera 12
333
- if (xhr.readyState === 4) {
334
- if (!("onload" in xhr) || !("onerror" in xhr) || !("onabort" in xhr)) {
335
- onFinish(xhr.responseText === "" ? "error" : "load", event);
336
- }
337
- } else if (xhr.readyState === 3) {
338
- if (!("onprogress" in xhr)) { // testing XMLHttpRequest#responseText too many times is too slow in IE 11
339
- // and in Firefox 3.6
340
- onProgress();
341
- }
342
- } else if (xhr.readyState === 2) {
343
- onStart();
344
- }
345
- }
346
- };
347
- var onTimeout = function () {
348
- timeout = setTimeout(function () {
349
- onTimeout();
350
- }, 500);
351
- if (xhr.readyState === 3) {
352
- onProgress();
353
- }
354
- };
355
-
356
- // XDomainRequest#abort removes onprogress, onerror, onload
357
- if ("onload" in xhr) {
358
- xhr.onload = function (event) {
359
- onFinish("load", event);
360
- };
361
- }
362
- if ("onerror" in xhr) {
363
- xhr.onerror = function (event) {
364
- onFinish("error", event);
365
- };
366
- }
367
- // improper fix to match Firefox behaviour, but it is better than just ignore abort
368
- // see https://bugzilla.mozilla.org/show_bug.cgi?id=768596
369
- // https://bugzilla.mozilla.org/show_bug.cgi?id=880200
370
- // https://code.google.com/p/chromium/issues/detail?id=153570
371
- // IE 8 fires "onload" without "onprogress
372
- if ("onabort" in xhr) {
373
- xhr.onabort = function (event) {
374
- onFinish("abort", event);
375
- };
376
- }
377
-
378
- if ("onprogress" in xhr) {
379
- xhr.onprogress = onProgress;
380
- }
381
-
382
- // IE 8 - 9 (XMLHTTPRequest)
383
- // Opera < 12
384
- // Firefox < 3.5
385
- // Firefox 3.5 - 3.6 - ? < 9.0
386
- // onprogress is not fired sometimes or delayed
387
- // see also #64 (significant lag in IE 11)
388
- if ("onreadystatechange" in xhr) {
389
- xhr.onreadystatechange = function (event) {
390
- onReadyStateChange(event);
391
- };
392
- }
393
-
394
- if ("contentType" in xhr || !("ontimeout" in XMLHttpRequest.prototype)) {
395
- url += (url.indexOf("?") === -1 ? "?" : "&") + "padding=true";
396
- }
397
- xhr.open(method, url, true);
398
-
399
- if ("readyState" in xhr) {
400
- // workaround for Opera 12 issue with "progress" events
401
- // #91 (XMLHttpRequest onprogress not fired for streaming response in Edge 14-15-?)
402
- timeout = setTimeout(function () {
403
- onTimeout();
404
- }, 0);
405
- }
406
- };
407
- XHRWrapper.prototype.abort = function () {
408
- this._abort(false);
409
- };
410
- XHRWrapper.prototype.getResponseHeader = function (name) {
411
- return this._contentType;
412
- };
413
- XHRWrapper.prototype.setRequestHeader = function (name, value) {
414
- var xhr = this._xhr;
415
- if ("setRequestHeader" in xhr) {
416
- xhr.setRequestHeader(name, value);
417
- }
418
- };
419
- XHRWrapper.prototype.getAllResponseHeaders = function () {
420
- // XMLHttpRequest#getAllResponseHeaders returns null for CORS requests in Firefox 3.6.28
421
- return this._xhr.getAllResponseHeaders != undefined ? this._xhr.getAllResponseHeaders() || "" : "";
422
- };
423
- XHRWrapper.prototype.send = function () {
424
- // loading indicator in Safari < ? (6), Chrome < 14, Firefox
425
- // https://bugzilla.mozilla.org/show_bug.cgi?id=736723
426
- if ((!("ontimeout" in XMLHttpRequest.prototype) || (!("sendAsBinary" in XMLHttpRequest.prototype) && !("mozAnon" in XMLHttpRequest.prototype))) &&
427
- document != undefined &&
428
- document.readyState != undefined &&
429
- document.readyState !== "complete") {
430
- var that = this;
431
- that._sendTimeout = setTimeout(function () {
432
- that._sendTimeout = 0;
433
- that.send();
434
- }, 4);
435
- return;
436
- }
437
-
438
- var xhr = this._xhr;
439
- // withCredentials should be set after "open" for Safari and Chrome (< 19 ?)
440
- if ("withCredentials" in xhr) {
441
- xhr.withCredentials = this.withCredentials;
442
- }
443
- try {
444
- // xhr.send(); throws "Not enough arguments" in Firefox 3.0
445
- xhr.send(undefined);
446
- } catch (error1) {
447
- // Safari 5.1.7, Opera 12
448
- throw error1;
449
- }
450
- };
451
-
452
- function toLowerCase(name) {
453
- return name.replace(/[A-Z]/g, function (c) {
454
- return String.fromCharCode(c.charCodeAt(0) + 0x20);
455
- });
456
- }
457
-
458
- function HeadersPolyfill(all) {
459
- // Get headers: implemented according to mozilla's example code: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders#Example
460
- var map = Object.create(null);
461
- var array = all.split("\r\n");
462
- for (var i = 0; i < array.length; i += 1) {
463
- var line = array[i];
464
- var parts = line.split(": ");
465
- var name = parts.shift();
466
- var value = parts.join(": ");
467
- map[toLowerCase(name)] = value;
468
- }
469
- this._map = map;
470
- }
471
- HeadersPolyfill.prototype.get = function (name) {
472
- return this._map[toLowerCase(name)];
473
- };
474
-
475
- if (XMLHttpRequest != null && XMLHttpRequest.HEADERS_RECEIVED == null) { // IE < 9, Firefox 3.6
476
- XMLHttpRequest.HEADERS_RECEIVED = 2;
477
- }
478
-
479
- function XHRTransport() {
480
- }
481
-
482
- XHRTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
483
- xhr.open("GET", url);
484
- var offset = 0;
485
- xhr.onprogress = function () {
486
- var responseText = xhr.responseText;
487
- var chunk = responseText.slice(offset);
488
- offset += chunk.length;
489
- onProgressCallback(chunk);
490
- };
491
- xhr.onerror = function (event) {
492
- event.preventDefault();
493
- onFinishCallback(new Error("NetworkError"));
494
- };
495
- xhr.onload = function () {
496
- onFinishCallback(null);
497
- };
498
- xhr.onabort = function () {
499
- onFinishCallback(null);
500
- };
501
- xhr.onreadystatechange = function () {
502
- if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
503
- var status = xhr.status;
504
- var statusText = xhr.statusText;
505
- var contentType = xhr.getResponseHeader("Content-Type");
506
- var headers = xhr.getAllResponseHeaders();
507
- onStartCallback(status, statusText, contentType, new HeadersPolyfill(headers));
508
- }
509
- };
510
- xhr.withCredentials = withCredentials;
511
- for (var name in headers) {
512
- if (Object.prototype.hasOwnProperty.call(headers, name)) {
513
- xhr.setRequestHeader(name, headers[name]);
514
- }
515
- }
516
- xhr.send();
517
- return xhr;
518
- };
519
-
520
- function HeadersWrapper(headers) {
521
- this._headers = headers;
522
- }
523
- HeadersWrapper.prototype.get = function (name) {
524
- return this._headers.get(name);
525
- };
526
-
527
- function FetchTransport() {
528
- }
529
-
530
- FetchTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
531
- var reader = null;
532
- var controller = new AbortController();
533
- var signal = controller.signal;
534
- var textDecoder = new TextDecoder();
535
- fetch(url, {
536
- headers: headers,
537
- credentials: withCredentials ? "include" : "same-origin",
538
- signal: signal,
539
- cache: "no-store"
540
- }).then(function (response) {
541
- reader = response.body.getReader();
542
- onStartCallback(response.status, response.statusText, response.headers.get("Content-Type"), new HeadersWrapper(response.headers));
543
- // see https://github.com/promises-aplus/promises-spec/issues/179
544
- return new Promise(function (resolve, reject) {
545
- var readNextChunk = function () {
546
- reader.read().then(function (result) {
547
- if (result.done) {
548
- //Note: bytes in textDecoder are ignored
549
- resolve(undefined);
550
- } else {
551
- var chunk = textDecoder.decode(result.value, {stream: true});
552
- onProgressCallback(chunk);
553
- readNextChunk();
554
- }
555
- })["catch"](function (error) {
556
- reject(error);
557
- });
558
- };
559
- readNextChunk();
560
- });
561
- })["catch"](function (error) {
562
- if (error.name === "AbortError") {
563
- return undefined;
564
- } else {
565
- return error;
566
- }
567
- }).then(function (error) {
568
- onFinishCallback(error);
569
- });
570
- return {
571
- abort: function () {
572
- if (reader != null) {
573
- reader.cancel(); // https://bugzilla.mozilla.org/show_bug.cgi?id=1583815
574
- }
575
- controller.abort();
576
- }
577
- };
578
- };
579
-
580
- function EventTarget() {
581
- this._listeners = Object.create(null);
582
- }
583
-
584
- function throwError(e) {
585
- setTimeout(function () {
586
- throw e;
587
- }, 0);
588
- }
589
-
590
- EventTarget.prototype.dispatchEvent = function (event) {
591
- event.target = this;
592
- var typeListeners = this._listeners[event.type];
593
- if (typeListeners != undefined) {
594
- var length = typeListeners.length;
595
- for (var i = 0; i < length; i += 1) {
596
- var listener = typeListeners[i];
597
- try {
598
- if (typeof listener.handleEvent === "function") {
599
- listener.handleEvent(event);
600
- } else {
601
- listener.call(this, event);
602
- }
603
- } catch (e) {
604
- throwError(e);
605
- }
606
- }
607
- }
608
- };
609
- EventTarget.prototype.addEventListener = function (type, listener) {
610
- type = String(type);
611
- var listeners = this._listeners;
612
- var typeListeners = listeners[type];
613
- if (typeListeners == undefined) {
614
- typeListeners = [];
615
- listeners[type] = typeListeners;
616
- }
617
- var found = false;
618
- for (var i = 0; i < typeListeners.length; i += 1) {
619
- if (typeListeners[i] === listener) {
620
- found = true;
621
- }
622
- }
623
- if (!found) {
624
- typeListeners.push(listener);
625
- }
626
- };
627
- EventTarget.prototype.removeEventListener = function (type, listener) {
628
- type = String(type);
629
- var listeners = this._listeners;
630
- var typeListeners = listeners[type];
631
- if (typeListeners != undefined) {
632
- var filtered = [];
633
- for (var i = 0; i < typeListeners.length; i += 1) {
634
- if (typeListeners[i] !== listener) {
635
- filtered.push(typeListeners[i]);
636
- }
637
- }
638
- if (filtered.length === 0) {
639
- delete listeners[type];
640
- } else {
641
- listeners[type] = filtered;
642
- }
643
- }
644
- };
645
-
646
- function Event(type) {
647
- this.type = type;
648
- this.target = undefined;
649
- }
650
-
651
- function MessageEvent(type, options) {
652
- Event.call(this, type);
653
- this.data = options.data;
654
- this.lastEventId = options.lastEventId;
655
- }
656
-
657
- MessageEvent.prototype = Object.create(Event.prototype);
658
-
659
- function ConnectionEvent(type, options) {
660
- Event.call(this, type);
661
- this.status = options.status;
662
- this.statusText = options.statusText;
663
- this.headers = options.headers;
664
- }
665
-
666
- ConnectionEvent.prototype = Object.create(Event.prototype);
667
-
668
- function ErrorEvent(type, options) {
669
- Event.call(this, type);
670
- this.error = options.error;
671
- }
672
-
673
- ErrorEvent.prototype = Object.create(Event.prototype);
674
-
675
- var WAITING = -1;
676
- var CONNECTING = 0;
677
- var OPEN = 1;
678
- var CLOSED = 2;
679
-
680
- var AFTER_CR = -1;
681
- var FIELD_START = 0;
682
- var FIELD = 1;
683
- var VALUE_START = 2;
684
- var VALUE = 3;
685
-
686
- var contentTypeRegExp = /^text\/event\-stream(;.*)?$/i;
687
-
688
- var MINIMUM_DURATION = 1000;
689
- var MAXIMUM_DURATION = 18000000;
690
-
691
- var parseDuration = function (value, def) {
692
- var n = value == null ? def : parseInt(value, 10);
693
- if (n !== n) {
694
- n = def;
695
- }
696
- return clampDuration(n);
697
- };
698
- var clampDuration = function (n) {
699
- return Math.min(Math.max(n, MINIMUM_DURATION), MAXIMUM_DURATION);
700
- };
701
-
702
- var fire = function (that, f, event) {
703
- try {
704
- if (typeof f === "function") {
705
- f.call(that, event);
706
- }
707
- } catch (e) {
708
- throwError(e);
709
- }
710
- };
711
-
712
- function EventSourcePolyfill(url, options) {
713
- EventTarget.call(this);
714
- options = options || {};
715
-
716
- this.onopen = undefined;
717
- this.onmessage = undefined;
718
- this.onerror = undefined;
719
-
720
- this.url = undefined;
721
- this.readyState = undefined;
722
- this.withCredentials = undefined;
723
- this.headers = undefined;
724
-
725
- this._close = undefined;
726
-
727
- start(this, url, options);
728
- }
729
-
730
- function getBestXHRTransport() {
731
- return (XMLHttpRequest != undefined && ("withCredentials" in XMLHttpRequest.prototype)) || XDomainRequest == undefined
732
- ? new XMLHttpRequest()
733
- : new XDomainRequest();
734
- }
735
-
736
- var isFetchSupported = fetch != undefined && Response != undefined && "body" in Response.prototype;
737
-
738
- function start(es, url, options) {
739
- url = String(url);
740
- var withCredentials = Boolean(options.withCredentials);
741
- var lastEventIdQueryParameterName = options.lastEventIdQueryParameterName || "lastEventId";
742
-
743
- var initialRetry = clampDuration(1000);
744
- var heartbeatTimeout = parseDuration(options.heartbeatTimeout, 45000);
745
-
746
- var lastEventId = "";
747
- var retry = initialRetry;
748
- var wasActivity = false;
749
- var textLength = 0;
750
- var headers = options.headers || {};
751
- var TransportOption = options.Transport;
752
- var xhr = isFetchSupported && TransportOption == undefined ? undefined : new XHRWrapper(TransportOption != undefined ? new TransportOption() : getBestXHRTransport());
753
- var transport = TransportOption != null && typeof TransportOption !== "string" ? new TransportOption() : (xhr == undefined ? new FetchTransport() : new XHRTransport());
754
- var abortController = undefined;
755
- var timeout = 0;
756
- var currentState = WAITING;
757
- var dataBuffer = "";
758
- var lastEventIdBuffer = "";
759
- var eventTypeBuffer = "";
760
-
761
- var textBuffer = "";
762
- var state = FIELD_START;
763
- var fieldStart = 0;
764
- var valueStart = 0;
765
-
766
- var onStart = function (status, statusText, contentType, headers) {
767
- if (currentState === CONNECTING) {
768
- if (status === 200 && contentType != undefined && contentTypeRegExp.test(contentType)) {
769
- currentState = OPEN;
770
- wasActivity = Date.now();
771
- retry = initialRetry;
772
- es.readyState = OPEN;
773
- var event = new ConnectionEvent("open", {
774
- status: status,
775
- statusText: statusText,
776
- headers: headers
777
- });
778
- es.dispatchEvent(event);
779
- fire(es, es.onopen, event);
780
- } else {
781
- var message = "";
782
- if (status !== 200) {
783
- if (statusText) {
784
- statusText = statusText.replace(/\s+/g, " ");
785
- }
786
- message = "EventSource's response has a status " + status + " " + statusText + " that is not 200. Aborting the connection.";
787
- } else {
788
- message = "EventSource's response has a Content-Type specifying an unsupported type: " + (contentType == undefined ? "-" : contentType.replace(/\s+/g, " ")) + ". Aborting the connection.";
789
- }
790
- close();
791
- var event = new ConnectionEvent("error", {
792
- status: status,
793
- statusText: statusText,
794
- headers: headers
795
- });
796
- es.dispatchEvent(event);
797
- fire(es, es.onerror, event);
798
- console.error(message);
799
- }
800
- }
801
- };
802
-
803
- var onProgress = function (textChunk) {
804
- if (currentState === OPEN) {
805
- var n = -1;
806
- for (var i = 0; i < textChunk.length; i += 1) {
807
- var c = textChunk.charCodeAt(i);
808
- if (c === "\n".charCodeAt(0) || c === "\r".charCodeAt(0)) {
809
- n = i;
810
- }
811
- }
812
- var chunk = (n !== -1 ? textBuffer : "") + textChunk.slice(0, n + 1);
813
- textBuffer = (n === -1 ? textBuffer : "") + textChunk.slice(n + 1);
814
- if (textChunk !== "") {
815
- wasActivity = Date.now();
816
- textLength += textChunk.length;
817
- }
818
- for (var position = 0; position < chunk.length; position += 1) {
819
- var c = chunk.charCodeAt(position);
820
- if (state === AFTER_CR && c === "\n".charCodeAt(0)) {
821
- state = FIELD_START;
822
- } else {
823
- if (state === AFTER_CR) {
824
- state = FIELD_START;
825
- }
826
- if (c === "\r".charCodeAt(0) || c === "\n".charCodeAt(0)) {
827
- if (state !== FIELD_START) {
828
- if (state === FIELD) {
829
- valueStart = position + 1;
830
- }
831
- var field = chunk.slice(fieldStart, valueStart - 1);
832
- var value = chunk.slice(valueStart + (valueStart < position && chunk.charCodeAt(valueStart) === " ".charCodeAt(0) ? 1 : 0), position);
833
- if (field === "data") {
834
- dataBuffer += "\n";
835
- dataBuffer += value;
836
- } else if (field === "id") {
837
- lastEventIdBuffer = value;
838
- } else if (field === "event") {
839
- eventTypeBuffer = value;
840
- } else if (field === "retry") {
841
- initialRetry = parseDuration(value, initialRetry);
842
- retry = initialRetry;
843
- } else if (field === "heartbeatTimeout") {
844
- heartbeatTimeout = parseDuration(value, heartbeatTimeout);
845
- if (timeout !== 0) {
846
- clearTimeout(timeout);
847
- timeout = setTimeout(function () {
848
- onTimeout();
849
- }, heartbeatTimeout);
850
- }
851
- }
852
- }
853
- if (state === FIELD_START) {
854
- if (dataBuffer !== "") {
855
- lastEventId = lastEventIdBuffer;
856
- if (eventTypeBuffer === "") {
857
- eventTypeBuffer = "message";
858
- }
859
- var event = new MessageEvent(eventTypeBuffer, {
860
- data: dataBuffer.slice(1),
861
- lastEventId: lastEventIdBuffer
862
- });
863
- es.dispatchEvent(event);
864
- if (eventTypeBuffer === "open") {
865
- fire(es, es.onopen, event);
866
- } else if (eventTypeBuffer === "message") {
867
- fire(es, es.onmessage, event);
868
- } else if (eventTypeBuffer === "error") {
869
- fire(es, es.onerror, event);
870
- }
871
- if (currentState === CLOSED) {
872
- return;
873
- }
874
- }
875
- dataBuffer = "";
876
- eventTypeBuffer = "";
877
- }
878
- state = c === "\r".charCodeAt(0) ? AFTER_CR : FIELD_START;
879
- } else {
880
- if (state === FIELD_START) {
881
- fieldStart = position;
882
- state = FIELD;
883
- }
884
- if (state === FIELD) {
885
- if (c === ":".charCodeAt(0)) {
886
- valueStart = position + 1;
887
- state = VALUE_START;
888
- }
889
- } else if (state === VALUE_START) {
890
- state = VALUE;
891
- }
892
- }
893
- }
894
- }
895
- }
896
- };
897
-
898
- var onFinish = function (error) {
899
- if (currentState === OPEN || currentState === CONNECTING) {
900
- currentState = WAITING;
901
- if (timeout !== 0) {
902
- clearTimeout(timeout);
903
- timeout = 0;
904
- }
905
- timeout = setTimeout(function () {
906
- onTimeout();
907
- }, retry);
908
- retry = clampDuration(Math.min(initialRetry * 16, retry * 2));
909
-
910
- es.readyState = CONNECTING;
911
- var event = new ErrorEvent("error", {error: error});
912
- es.dispatchEvent(event);
913
- fire(es, es.onerror, event);
914
- if (error != undefined) {
915
- console.error(error);
916
- }
917
- }
918
- };
919
-
920
- var close = function () {
921
- currentState = CLOSED;
922
- if (abortController != undefined) {
923
- abortController.abort();
924
- abortController = undefined;
925
- }
926
- if (timeout !== 0) {
927
- clearTimeout(timeout);
928
- timeout = 0;
929
- }
930
- es.readyState = CLOSED;
931
- };
932
-
933
- var onTimeout = function () {
934
- timeout = 0;
935
-
936
- if (currentState !== WAITING) {
937
- if (!wasActivity && abortController != undefined) {
938
- onFinish(new Error("No activity within " + heartbeatTimeout + " milliseconds." + " " + (currentState === CONNECTING ? "No response received." : textLength + " chars received.") + " " + "Reconnecting."));
939
- if (abortController != undefined) {
940
- abortController.abort();
941
- abortController = undefined;
942
- }
943
- } else {
944
- var nextHeartbeat = Math.max((wasActivity || Date.now()) + heartbeatTimeout - Date.now(), 1);
945
- wasActivity = false;
946
- timeout = setTimeout(function () {
947
- onTimeout();
948
- }, nextHeartbeat);
949
- }
950
- return;
951
- }
952
-
953
- wasActivity = false;
954
- textLength = 0;
955
- timeout = setTimeout(function () {
956
- onTimeout();
957
- }, heartbeatTimeout);
958
-
959
- currentState = CONNECTING;
960
- dataBuffer = "";
961
- eventTypeBuffer = "";
962
- lastEventIdBuffer = lastEventId;
963
- textBuffer = "";
964
- fieldStart = 0;
965
- valueStart = 0;
966
- state = FIELD_START;
967
-
968
- // https://bugzilla.mozilla.org/show_bug.cgi?id=428916
969
- // Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers.
970
- var requestURL = url;
971
- if (url.slice(0, 5) !== "data:" && url.slice(0, 5) !== "blob:") {
972
- if (lastEventId !== "") {
973
- // Remove the lastEventId parameter if it's already part of the request URL.
974
- var i = url.indexOf("?");
975
- requestURL = i === -1 ? url : url.slice(0, i + 1) + url.slice(i + 1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g, function (p, paramName) {
976
- return paramName === lastEventIdQueryParameterName ? '' : p;
977
- });
978
- // Append the current lastEventId to the request URL.
979
- requestURL += (url.indexOf("?") === -1 ? "?" : "&") + lastEventIdQueryParameterName +"=" + encodeURIComponent(lastEventId);
980
- }
981
- }
982
- var withCredentials = es.withCredentials;
983
- var requestHeaders = {};
984
- requestHeaders["Accept"] = "text/event-stream";
985
- var headers = es.headers;
986
- if (headers != undefined) {
987
- for (var name in headers) {
988
- if (Object.prototype.hasOwnProperty.call(headers, name)) {
989
- requestHeaders[name] = headers[name];
990
- }
991
- }
992
- }
993
- try {
994
- abortController = transport.open(xhr, onStart, onProgress, onFinish, requestURL, withCredentials, requestHeaders);
995
- } catch (error) {
996
- close();
997
- throw error;
998
- }
999
- };
1000
-
1001
- es.url = url;
1002
- es.readyState = CONNECTING;
1003
- es.withCredentials = withCredentials;
1004
- es.headers = headers;
1005
- es._close = close;
1006
-
1007
- onTimeout();
1008
- }
1009
-
1010
- EventSourcePolyfill.prototype = Object.create(EventTarget.prototype);
1011
- EventSourcePolyfill.prototype.CONNECTING = CONNECTING;
1012
- EventSourcePolyfill.prototype.OPEN = OPEN;
1013
- EventSourcePolyfill.prototype.CLOSED = CLOSED;
1014
- EventSourcePolyfill.prototype.close = function () {
1015
- this._close();
1016
- };
1017
-
1018
- EventSourcePolyfill.CONNECTING = CONNECTING;
1019
- EventSourcePolyfill.OPEN = OPEN;
1020
- EventSourcePolyfill.CLOSED = CLOSED;
1021
- EventSourcePolyfill.prototype.withCredentials = undefined;
1022
-
1023
- var R = NativeEventSource
1024
- if (XMLHttpRequest != undefined && (NativeEventSource == undefined || !("withCredentials" in NativeEventSource.prototype))) {
1025
- // Why replace a native EventSource ?
1026
- // https://bugzilla.mozilla.org/show_bug.cgi?id=444328
1027
- // https://bugzilla.mozilla.org/show_bug.cgi?id=831392
1028
- // https://code.google.com/p/chromium/issues/detail?id=260144
1029
- // https://code.google.com/p/chromium/issues/detail?id=225654
1030
- // ...
1031
- R = EventSourcePolyfill;
1032
- }
1033
-
1034
- (function (factory) {
1035
- if (typeof module === "object" && typeof module.exports === "object") {
1036
- var v = factory(exports);
1037
- if (v !== undefined) module.exports = v;
1038
- }
1039
- else if (typeof define === "function" && define.amd) {
1040
- define(["exports"], factory);
1041
- }
1042
- else {
1043
- factory(global);
1044
- }
1045
- })(function (exports) {
1046
- exports.EventSourcePolyfill = EventSourcePolyfill;
1047
- exports.NativeEventSource = NativeEventSource;
1048
- exports.EventSource = R;
1049
- });
1050
- }(typeof globalThis === 'undefined' ? (typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : this) : globalThis));
3
+ (function(undefined) {
4
+ if (!("EventSource"in self&&"function"==typeof self.EventSource
5
+ )) {
6
+ // EventSource
7
+ /** @license
8
+ * eventsource.js
9
+ * Available under MIT License (MIT)
10
+ * https://github.com/Yaffle/EventSource/
11
+ *
12
+ * The MIT License (MIT)
13
+ *
14
+ * Copyright (c) 2012 vic99999@yandex.ru
15
+ *
16
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
17
+ * of this software and associated documentation files (the "Software"), to deal
18
+ * in the Software without restriction, including without limitation the rights
19
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20
+ * copies of the Software, and to permit persons to whom the Software is
21
+ * furnished to do so, subject to the following conditions:
22
+ *
23
+ * The above copyright notice and this permission notice shall be included in all
24
+ * copies or substantial portions of the Software.
25
+ *
26
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
+ * SOFTWARE.
33
+ */
34
+
35
+ /*jslint indent: 2, vars: true, plusplus: true */
36
+ /*global setTimeout, clearTimeout */
37
+
38
+ (function (global) {
39
+ "use strict";
40
+
41
+ var setTimeout = global.setTimeout;
42
+ var clearTimeout = global.clearTimeout;
43
+ var XMLHttpRequest = global.XMLHttpRequest;
44
+ var XDomainRequest = global.XDomainRequest;
45
+ var ActiveXObject = global.ActiveXObject;
46
+ var NativeEventSource = global.EventSource;
47
+
48
+ var document = global.document;
49
+ var Promise = global.Promise;
50
+ var fetch = global.fetch;
51
+ var Response = global.Response;
52
+ var TextDecoder = global.TextDecoder;
53
+ var TextEncoder = global.TextEncoder;
54
+ var AbortController = global.AbortController;
55
+
56
+ if (typeof window !== "undefined" && typeof document !== "undefined" && !("readyState" in document) && document.body == null) { // Firefox 2
57
+ document.readyState = "loading";
58
+ window.addEventListener("load", function (event) {
59
+ document.readyState = "complete";
60
+ }, false);
61
+ }
62
+
63
+ if (XMLHttpRequest == null && ActiveXObject != null) { // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6
64
+ XMLHttpRequest = function () {
65
+ return new ActiveXObject("Microsoft.XMLHTTP");
66
+ };
67
+ }
68
+
69
+ if (Object.create == undefined) {
70
+ Object.create = function (C) {
71
+ function F(){}
72
+ F.prototype = C;
73
+ return new F();
74
+ };
75
+ }
76
+
77
+ if (!Date.now) {
78
+ Date.now = function now() {
79
+ return new Date().getTime();
80
+ };
81
+ }
82
+
83
+ // see #118 (Promise#finally with polyfilled Promise)
84
+ // see #123 (data URLs crash Edge)
85
+ // see #125 (CSP violations)
86
+ // see pull/#138
87
+ // => No way to polyfill Promise#finally
88
+
89
+ if (AbortController == undefined) {
90
+ var originalFetch2 = fetch;
91
+ fetch = function (url, options) {
92
+ var signal = options.signal;
93
+ return originalFetch2(url, {headers: options.headers, credentials: options.credentials, cache: options.cache}).then(function (response) {
94
+ var reader = response.body.getReader();
95
+ signal._reader = reader;
96
+ if (signal._aborted) {
97
+ signal._reader.cancel();
98
+ }
99
+ return {
100
+ status: response.status,
101
+ statusText: response.statusText,
102
+ headers: response.headers,
103
+ body: {
104
+ getReader: function () {
105
+ return reader;
106
+ }
107
+ }
108
+ };
109
+ });
110
+ };
111
+ AbortController = function () {
112
+ this.signal = {
113
+ _reader: null,
114
+ _aborted: false
115
+ };
116
+ this.abort = function () {
117
+ if (this.signal._reader != null) {
118
+ this.signal._reader.cancel();
119
+ }
120
+ this.signal._aborted = true;
121
+ };
122
+ };
123
+ }
124
+
125
+ function TextDecoderPolyfill() {
126
+ this.bitsNeeded = 0;
127
+ this.codePoint = 0;
128
+ }
129
+
130
+ TextDecoderPolyfill.prototype.decode = function (octets) {
131
+ function valid(codePoint, shift, octetsCount) {
132
+ if (octetsCount === 1) {
133
+ return codePoint >= 0x0080 >> shift && codePoint << shift <= 0x07FF;
134
+ }
135
+ if (octetsCount === 2) {
136
+ return codePoint >= 0x0800 >> shift && codePoint << shift <= 0xD7FF || codePoint >= 0xE000 >> shift && codePoint << shift <= 0xFFFF;
137
+ }
138
+ if (octetsCount === 3) {
139
+ return codePoint >= 0x010000 >> shift && codePoint << shift <= 0x10FFFF;
140
+ }
141
+ throw new Error();
142
+ }
143
+ function octetsCount(bitsNeeded, codePoint) {
144
+ if (bitsNeeded === 6 * 1) {
145
+ return codePoint >> 6 > 15 ? 3 : codePoint > 31 ? 2 : 1;
146
+ }
147
+ if (bitsNeeded === 6 * 2) {
148
+ return codePoint > 15 ? 3 : 2;
149
+ }
150
+ if (bitsNeeded === 6 * 3) {
151
+ return 3;
152
+ }
153
+ throw new Error();
154
+ }
155
+ var REPLACER = 0xFFFD;
156
+ var string = "";
157
+ var bitsNeeded = this.bitsNeeded;
158
+ var codePoint = this.codePoint;
159
+ for (var i = 0; i < octets.length; i += 1) {
160
+ var octet = octets[i];
161
+ if (bitsNeeded !== 0) {
162
+ if (octet < 128 || octet > 191 || !valid(codePoint << 6 | octet & 63, bitsNeeded - 6, octetsCount(bitsNeeded, codePoint))) {
163
+ bitsNeeded = 0;
164
+ codePoint = REPLACER;
165
+ string += String.fromCharCode(codePoint);
166
+ }
167
+ }
168
+ if (bitsNeeded === 0) {
169
+ if (octet >= 0 && octet <= 127) {
170
+ bitsNeeded = 0;
171
+ codePoint = octet;
172
+ } else if (octet >= 192 && octet <= 223) {
173
+ bitsNeeded = 6 * 1;
174
+ codePoint = octet & 31;
175
+ } else if (octet >= 224 && octet <= 239) {
176
+ bitsNeeded = 6 * 2;
177
+ codePoint = octet & 15;
178
+ } else if (octet >= 240 && octet <= 247) {
179
+ bitsNeeded = 6 * 3;
180
+ codePoint = octet & 7;
181
+ } else {
182
+ bitsNeeded = 0;
183
+ codePoint = REPLACER;
184
+ }
185
+ if (bitsNeeded !== 0 && !valid(codePoint, bitsNeeded, octetsCount(bitsNeeded, codePoint))) {
186
+ bitsNeeded = 0;
187
+ codePoint = REPLACER;
188
+ }
189
+ } else {
190
+ bitsNeeded -= 6;
191
+ codePoint = codePoint << 6 | octet & 63;
192
+ }
193
+ if (bitsNeeded === 0) {
194
+ if (codePoint <= 0xFFFF) {
195
+ string += String.fromCharCode(codePoint);
196
+ } else {
197
+ string += String.fromCharCode(0xD800 + (codePoint - 0xFFFF - 1 >> 10));
198
+ string += String.fromCharCode(0xDC00 + (codePoint - 0xFFFF - 1 & 0x3FF));
199
+ }
200
+ }
201
+ }
202
+ this.bitsNeeded = bitsNeeded;
203
+ this.codePoint = codePoint;
204
+ return string;
205
+ };
206
+
207
+ // Firefox < 38 throws an error with stream option
208
+ var supportsStreamOption = function () {
209
+ try {
210
+ return new TextDecoder().decode(new TextEncoder().encode("test"), {stream: true}) === "test";
211
+ } catch (error) {
212
+ console.debug("TextDecoder does not support streaming option. Using polyfill instead: " + error);
213
+ }
214
+ return false;
215
+ };
216
+
217
+ // IE, Edge
218
+ if (TextDecoder == undefined || TextEncoder == undefined || !supportsStreamOption()) {
219
+ TextDecoder = TextDecoderPolyfill;
220
+ }
221
+
222
+ var k = function () {
223
+ };
224
+
225
+ function XHRWrapper(xhr) {
226
+ this.withCredentials = false;
227
+ this.readyState = 0;
228
+ this.status = 0;
229
+ this.statusText = "";
230
+ this.responseText = "";
231
+ this.onprogress = k;
232
+ this.onload = k;
233
+ this.onerror = k;
234
+ this.onreadystatechange = k;
235
+ this._contentType = "";
236
+ this._xhr = xhr;
237
+ this._sendTimeout = 0;
238
+ this._abort = k;
239
+ }
240
+
241
+ XHRWrapper.prototype.open = function (method, url) {
242
+ this._abort(true);
243
+
244
+ var that = this;
245
+ var xhr = this._xhr;
246
+ var state = 1;
247
+ var timeout = 0;
248
+
249
+ this._abort = function (silent) {
250
+ if (that._sendTimeout !== 0) {
251
+ clearTimeout(that._sendTimeout);
252
+ that._sendTimeout = 0;
253
+ }
254
+ if (state === 1 || state === 2 || state === 3) {
255
+ state = 4;
256
+ xhr.onload = k;
257
+ xhr.onerror = k;
258
+ xhr.onabort = k;
259
+ xhr.onprogress = k;
260
+ xhr.onreadystatechange = k;
261
+ // IE 8 - 9: XDomainRequest#abort() does not fire any event
262
+ // Opera < 10: XMLHttpRequest#abort() does not fire any event
263
+ xhr.abort();
264
+ if (timeout !== 0) {
265
+ clearTimeout(timeout);
266
+ timeout = 0;
267
+ }
268
+ if (!silent) {
269
+ that.readyState = 4;
270
+ that.onabort(null);
271
+ that.onreadystatechange();
272
+ }
273
+ }
274
+ state = 0;
275
+ };
276
+
277
+ var onStart = function () {
278
+ if (state === 1) {
279
+ //state = 2;
280
+ var status = 0;
281
+ var statusText = "";
282
+ var contentType = undefined;
283
+ if (!("contentType" in xhr)) {
284
+ try {
285
+ status = xhr.status;
286
+ statusText = xhr.statusText;
287
+ contentType = xhr.getResponseHeader("Content-Type");
288
+ } catch (error) {
289
+ // IE < 10 throws exception for `xhr.status` when xhr.readyState === 2 || xhr.readyState === 3
290
+ // Opera < 11 throws exception for `xhr.status` when xhr.readyState === 2
291
+ // https://bugs.webkit.org/show_bug.cgi?id=29121
292
+ status = 0;
293
+ statusText = "";
294
+ contentType = undefined;
295
+ // Firefox < 14, Chrome ?, Safari ?
296
+ // https://bugs.webkit.org/show_bug.cgi?id=29658
297
+ // https://bugs.webkit.org/show_bug.cgi?id=77854
298
+ }
299
+ } else {
300
+ status = 200;
301
+ statusText = "OK";
302
+ contentType = xhr.contentType;
303
+ }
304
+ if (status !== 0) {
305
+ state = 2;
306
+ that.readyState = 2;
307
+ that.status = status;
308
+ that.statusText = statusText;
309
+ that._contentType = contentType;
310
+ that.onreadystatechange();
311
+ }
312
+ }
313
+ };
314
+ var onProgress = function () {
315
+ onStart();
316
+ if (state === 2 || state === 3) {
317
+ state = 3;
318
+ var responseText = "";
319
+ try {
320
+ responseText = xhr.responseText;
321
+ } catch (error) {
322
+ // IE 8 - 9 with XMLHttpRequest
323
+ }
324
+ that.readyState = 3;
325
+ that.responseText = responseText;
326
+ that.onprogress();
327
+ }
328
+ };
329
+ var onFinish = function (type, event) {
330
+ if (event == null || event.preventDefault == null) {
331
+ event = {
332
+ preventDefault: k
333
+ };
334
+ }
335
+ // Firefox 52 fires "readystatechange" (xhr.readyState === 4) without final "readystatechange" (xhr.readyState === 3)
336
+ // IE 8 fires "onload" without "onprogress"
337
+ onProgress();
338
+ if (state === 1 || state === 2 || state === 3) {
339
+ state = 4;
340
+ if (timeout !== 0) {
341
+ clearTimeout(timeout);
342
+ timeout = 0;
343
+ }
344
+ that.readyState = 4;
345
+ if (type === "load") {
346
+ that.onload(event);
347
+ } else if (type === "error") {
348
+ that.onerror(event);
349
+ } else if (type === "abort") {
350
+ that.onabort(event);
351
+ } else {
352
+ throw new TypeError();
353
+ }
354
+ that.onreadystatechange();
355
+ }
356
+ };
357
+ var onReadyStateChange = function (event) {
358
+ if (xhr != undefined) { // Opera 12
359
+ if (xhr.readyState === 4) {
360
+ if (!("onload" in xhr) || !("onerror" in xhr) || !("onabort" in xhr)) {
361
+ onFinish(xhr.responseText === "" ? "error" : "load", event);
362
+ }
363
+ } else if (xhr.readyState === 3) {
364
+ if (!("onprogress" in xhr)) { // testing XMLHttpRequest#responseText too many times is too slow in IE 11
365
+ // and in Firefox 3.6
366
+ onProgress();
367
+ }
368
+ } else if (xhr.readyState === 2) {
369
+ onStart();
370
+ }
371
+ }
372
+ };
373
+ var onTimeout = function () {
374
+ timeout = setTimeout(function () {
375
+ onTimeout();
376
+ }, 500);
377
+ if (xhr.readyState === 3) {
378
+ onProgress();
379
+ }
380
+ };
381
+
382
+ // XDomainRequest#abort removes onprogress, onerror, onload
383
+ if ("onload" in xhr) {
384
+ xhr.onload = function (event) {
385
+ onFinish("load", event);
386
+ };
387
+ }
388
+ if ("onerror" in xhr) {
389
+ xhr.onerror = function (event) {
390
+ onFinish("error", event);
391
+ };
392
+ }
393
+ // improper fix to match Firefox behaviour, but it is better than just ignore abort
394
+ // see https://bugzilla.mozilla.org/show_bug.cgi?id=768596
395
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=880200
396
+ // https://code.google.com/p/chromium/issues/detail?id=153570
397
+ // IE 8 fires "onload" without "onprogress
398
+ if ("onabort" in xhr) {
399
+ xhr.onabort = function (event) {
400
+ onFinish("abort", event);
401
+ };
402
+ }
403
+
404
+ if ("onprogress" in xhr) {
405
+ xhr.onprogress = onProgress;
406
+ }
407
+
408
+ // IE 8 - 9 (XMLHTTPRequest)
409
+ // Opera < 12
410
+ // Firefox < 3.5
411
+ // Firefox 3.5 - 3.6 - ? < 9.0
412
+ // onprogress is not fired sometimes or delayed
413
+ // see also #64 (significant lag in IE 11)
414
+ if ("onreadystatechange" in xhr) {
415
+ xhr.onreadystatechange = function (event) {
416
+ onReadyStateChange(event);
417
+ };
418
+ }
419
+
420
+ if ("contentType" in xhr || !("ontimeout" in XMLHttpRequest.prototype)) {
421
+ url += (url.indexOf("?") === -1 ? "?" : "&") + "padding=true";
422
+ }
423
+ xhr.open(method, url, true);
424
+
425
+ if ("readyState" in xhr) {
426
+ // workaround for Opera 12 issue with "progress" events
427
+ // #91 (XMLHttpRequest onprogress not fired for streaming response in Edge 14-15-?)
428
+ timeout = setTimeout(function () {
429
+ onTimeout();
430
+ }, 0);
431
+ }
432
+ };
433
+ XHRWrapper.prototype.abort = function () {
434
+ this._abort(false);
435
+ };
436
+ XHRWrapper.prototype.getResponseHeader = function (name) {
437
+ return this._contentType;
438
+ };
439
+ XHRWrapper.prototype.setRequestHeader = function (name, value) {
440
+ var xhr = this._xhr;
441
+ if ("setRequestHeader" in xhr) {
442
+ xhr.setRequestHeader(name, value);
443
+ }
444
+ };
445
+ XHRWrapper.prototype.getAllResponseHeaders = function () {
446
+ // XMLHttpRequest#getAllResponseHeaders returns null for CORS requests in Firefox 3.6.28
447
+ return this._xhr.getAllResponseHeaders != undefined ? this._xhr.getAllResponseHeaders() || "" : "";
448
+ };
449
+ XHRWrapper.prototype.send = function () {
450
+ // loading indicator in Safari < ? (6), Chrome < 14, Firefox
451
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=736723
452
+ if ((!("ontimeout" in XMLHttpRequest.prototype) || (!("sendAsBinary" in XMLHttpRequest.prototype) && !("mozAnon" in XMLHttpRequest.prototype))) &&
453
+ document != undefined &&
454
+ document.readyState != undefined &&
455
+ document.readyState !== "complete") {
456
+ var that = this;
457
+ that._sendTimeout = setTimeout(function () {
458
+ that._sendTimeout = 0;
459
+ that.send();
460
+ }, 4);
461
+ return;
462
+ }
463
+
464
+ var xhr = this._xhr;
465
+ // withCredentials should be set after "open" for Safari and Chrome (< 19 ?)
466
+ if ("withCredentials" in xhr) {
467
+ xhr.withCredentials = this.withCredentials;
468
+ }
469
+ try {
470
+ // xhr.send(); throws "Not enough arguments" in Firefox 3.0
471
+ xhr.send(undefined);
472
+ } catch (error1) {
473
+ // Safari 5.1.7, Opera 12
474
+ throw error1;
475
+ }
476
+ };
477
+
478
+ function toLowerCase(name) {
479
+ return name.replace(/[A-Z]/g, function (c) {
480
+ return String.fromCharCode(c.charCodeAt(0) + 0x20);
481
+ });
482
+ }
483
+
484
+ function HeadersPolyfill(all) {
485
+ // Get headers: implemented according to mozilla's example code: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders#Example
486
+ var map = Object.create(null);
487
+ var array = all.split("\r\n");
488
+ for (var i = 0; i < array.length; i += 1) {
489
+ var line = array[i];
490
+ var parts = line.split(": ");
491
+ var name = parts.shift();
492
+ var value = parts.join(": ");
493
+ map[toLowerCase(name)] = value;
494
+ }
495
+ this._map = map;
496
+ }
497
+ HeadersPolyfill.prototype.get = function (name) {
498
+ return this._map[toLowerCase(name)];
499
+ };
500
+
501
+ if (XMLHttpRequest != null && XMLHttpRequest.HEADERS_RECEIVED == null) { // IE < 9, Firefox 3.6
502
+ XMLHttpRequest.HEADERS_RECEIVED = 2;
503
+ }
504
+
505
+ function XHRTransport() {
506
+ }
507
+
508
+ XHRTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
509
+ xhr.open("GET", url);
510
+ var offset = 0;
511
+ xhr.onprogress = function () {
512
+ var responseText = xhr.responseText;
513
+ var chunk = responseText.slice(offset);
514
+ offset += chunk.length;
515
+ onProgressCallback(chunk);
516
+ };
517
+ xhr.onerror = function (event) {
518
+ event.preventDefault();
519
+ onFinishCallback(new Error("NetworkError"));
520
+ };
521
+ xhr.onload = function () {
522
+ onFinishCallback(null);
523
+ };
524
+ xhr.onabort = function () {
525
+ onFinishCallback(null);
526
+ };
527
+ xhr.onreadystatechange = function () {
528
+ if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
529
+ var status = xhr.status;
530
+ var statusText = xhr.statusText;
531
+ var contentType = xhr.getResponseHeader("Content-Type");
532
+ var headers = xhr.getAllResponseHeaders();
533
+ onStartCallback(status, statusText, contentType, new HeadersPolyfill(headers));
534
+ }
535
+ };
536
+ xhr.withCredentials = withCredentials;
537
+ for (var name in headers) {
538
+ if (Object.prototype.hasOwnProperty.call(headers, name)) {
539
+ xhr.setRequestHeader(name, headers[name]);
540
+ }
541
+ }
542
+ xhr.send();
543
+ return xhr;
544
+ };
545
+
546
+ function HeadersWrapper(headers) {
547
+ this._headers = headers;
548
+ }
549
+ HeadersWrapper.prototype.get = function (name) {
550
+ return this._headers.get(name);
551
+ };
552
+
553
+ function FetchTransport() {
554
+ }
555
+
556
+ FetchTransport.prototype.open = function (xhr, onStartCallback, onProgressCallback, onFinishCallback, url, withCredentials, headers) {
557
+ var reader = null;
558
+ var controller = new AbortController();
559
+ var signal = controller.signal;
560
+ var textDecoder = new TextDecoder();
561
+ fetch(url, {
562
+ headers: headers,
563
+ credentials: withCredentials ? "include" : "same-origin",
564
+ signal: signal,
565
+ cache: "no-store"
566
+ }).then(function (response) {
567
+ reader = response.body.getReader();
568
+ onStartCallback(response.status, response.statusText, response.headers.get("Content-Type"), new HeadersWrapper(response.headers));
569
+ // see https://github.com/promises-aplus/promises-spec/issues/179
570
+ return new Promise(function (resolve, reject) {
571
+ var readNextChunk = function () {
572
+ reader.read().then(function (result) {
573
+ if (result.done) {
574
+ //Note: bytes in textDecoder are ignored
575
+ resolve(undefined);
576
+ } else {
577
+ var chunk = textDecoder.decode(result.value, {stream: true});
578
+ onProgressCallback(chunk);
579
+ readNextChunk();
580
+ }
581
+ })["catch"](function (error) {
582
+ reject(error);
583
+ });
584
+ };
585
+ readNextChunk();
586
+ });
587
+ })["catch"](function (error) {
588
+ if (error.name === "AbortError") {
589
+ return undefined;
590
+ } else {
591
+ return error;
592
+ }
593
+ }).then(function (error) {
594
+ onFinishCallback(error);
595
+ });
596
+ return {
597
+ abort: function () {
598
+ if (reader != null) {
599
+ reader.cancel(); // https://bugzilla.mozilla.org/show_bug.cgi?id=1583815
600
+ }
601
+ controller.abort();
602
+ }
603
+ };
604
+ };
605
+
606
+ function EventTarget() {
607
+ this._listeners = Object.create(null);
608
+ }
609
+
610
+ function throwError(e) {
611
+ setTimeout(function () {
612
+ throw e;
613
+ }, 0);
614
+ }
615
+
616
+ EventTarget.prototype.dispatchEvent = function (event) {
617
+ event.target = this;
618
+ var typeListeners = this._listeners[event.type];
619
+ if (typeListeners != undefined) {
620
+ var length = typeListeners.length;
621
+ for (var i = 0; i < length; i += 1) {
622
+ var listener = typeListeners[i];
623
+ try {
624
+ if (typeof listener.handleEvent === "function") {
625
+ listener.handleEvent(event);
626
+ } else {
627
+ listener.call(this, event);
628
+ }
629
+ } catch (e) {
630
+ throwError(e);
631
+ }
632
+ }
633
+ }
634
+ };
635
+ EventTarget.prototype.addEventListener = function (type, listener) {
636
+ type = String(type);
637
+ var listeners = this._listeners;
638
+ var typeListeners = listeners[type];
639
+ if (typeListeners == undefined) {
640
+ typeListeners = [];
641
+ listeners[type] = typeListeners;
642
+ }
643
+ var found = false;
644
+ for (var i = 0; i < typeListeners.length; i += 1) {
645
+ if (typeListeners[i] === listener) {
646
+ found = true;
647
+ }
648
+ }
649
+ if (!found) {
650
+ typeListeners.push(listener);
651
+ }
652
+ };
653
+ EventTarget.prototype.removeEventListener = function (type, listener) {
654
+ type = String(type);
655
+ var listeners = this._listeners;
656
+ var typeListeners = listeners[type];
657
+ if (typeListeners != undefined) {
658
+ var filtered = [];
659
+ for (var i = 0; i < typeListeners.length; i += 1) {
660
+ if (typeListeners[i] !== listener) {
661
+ filtered.push(typeListeners[i]);
662
+ }
663
+ }
664
+ if (filtered.length === 0) {
665
+ delete listeners[type];
666
+ } else {
667
+ listeners[type] = filtered;
668
+ }
669
+ }
670
+ };
671
+
672
+ function Event(type) {
673
+ this.type = type;
674
+ this.target = undefined;
675
+ }
676
+
677
+ function MessageEvent(type, options) {
678
+ Event.call(this, type);
679
+ this.data = options.data;
680
+ this.lastEventId = options.lastEventId;
681
+ }
682
+
683
+ MessageEvent.prototype = Object.create(Event.prototype);
684
+
685
+ function ConnectionEvent(type, options) {
686
+ Event.call(this, type);
687
+ this.status = options.status;
688
+ this.statusText = options.statusText;
689
+ this.headers = options.headers;
690
+ }
691
+
692
+ ConnectionEvent.prototype = Object.create(Event.prototype);
693
+
694
+ function ErrorEvent(type, options) {
695
+ Event.call(this, type);
696
+ this.error = options.error;
697
+ }
698
+
699
+ ErrorEvent.prototype = Object.create(Event.prototype);
700
+
701
+ var WAITING = -1;
702
+ var CONNECTING = 0;
703
+ var OPEN = 1;
704
+ var CLOSED = 2;
705
+
706
+ var AFTER_CR = -1;
707
+ var FIELD_START = 0;
708
+ var FIELD = 1;
709
+ var VALUE_START = 2;
710
+ var VALUE = 3;
711
+
712
+ var contentTypeRegExp = /^text\/event\-stream(;.*)?$/i;
713
+
714
+ var MINIMUM_DURATION = 1000;
715
+ var MAXIMUM_DURATION = 18000000;
716
+
717
+ var parseDuration = function (value, def) {
718
+ var n = value == null ? def : parseInt(value, 10);
719
+ if (n !== n) {
720
+ n = def;
721
+ }
722
+ return clampDuration(n);
723
+ };
724
+ var clampDuration = function (n) {
725
+ return Math.min(Math.max(n, MINIMUM_DURATION), MAXIMUM_DURATION);
726
+ };
727
+
728
+ var fire = function (that, f, event) {
729
+ try {
730
+ if (typeof f === "function") {
731
+ f.call(that, event);
732
+ }
733
+ } catch (e) {
734
+ throwError(e);
735
+ }
736
+ };
737
+
738
+ function EventSourcePolyfill(url, options) {
739
+ EventTarget.call(this);
740
+ options = options || {};
741
+
742
+ this.onopen = undefined;
743
+ this.onmessage = undefined;
744
+ this.onerror = undefined;
745
+
746
+ this.url = undefined;
747
+ this.readyState = undefined;
748
+ this.withCredentials = undefined;
749
+ this.headers = undefined;
750
+
751
+ this._close = undefined;
752
+
753
+ start(this, url, options);
754
+ }
755
+
756
+ function getBestXHRTransport() {
757
+ return (XMLHttpRequest != undefined && ("withCredentials" in XMLHttpRequest.prototype)) || XDomainRequest == undefined
758
+ ? new XMLHttpRequest()
759
+ : new XDomainRequest();
760
+ }
761
+
762
+ var isFetchSupported = fetch != undefined && Response != undefined && "body" in Response.prototype;
763
+
764
+ function start(es, url, options) {
765
+ url = String(url);
766
+ var withCredentials = Boolean(options.withCredentials);
767
+ var lastEventIdQueryParameterName = options.lastEventIdQueryParameterName || "lastEventId";
768
+
769
+ var initialRetry = clampDuration(1000);
770
+ var heartbeatTimeout = parseDuration(options.heartbeatTimeout, 45000);
771
+
772
+ var lastEventId = "";
773
+ var retry = initialRetry;
774
+ var wasActivity = false;
775
+ var textLength = 0;
776
+ var headers = options.headers || {};
777
+ var TransportOption = options.Transport;
778
+ var xhr = isFetchSupported && TransportOption == undefined ? undefined : new XHRWrapper(TransportOption != undefined ? new TransportOption() : getBestXHRTransport());
779
+ var transport = TransportOption != null && typeof TransportOption !== "string" ? new TransportOption() : (xhr == undefined ? new FetchTransport() : new XHRTransport());
780
+ var abortController = undefined;
781
+ var timeout = 0;
782
+ var currentState = WAITING;
783
+ var dataBuffer = "";
784
+ var lastEventIdBuffer = "";
785
+ var eventTypeBuffer = "";
786
+
787
+ var textBuffer = "";
788
+ var state = FIELD_START;
789
+ var fieldStart = 0;
790
+ var valueStart = 0;
791
+
792
+ var onStart = function (status, statusText, contentType, headers) {
793
+ if (currentState === CONNECTING) {
794
+ if (status === 200 && contentType != undefined && contentTypeRegExp.test(contentType)) {
795
+ currentState = OPEN;
796
+ wasActivity = Date.now();
797
+ retry = initialRetry;
798
+ es.readyState = OPEN;
799
+ var event = new ConnectionEvent("open", {
800
+ status: status,
801
+ statusText: statusText,
802
+ headers: headers
803
+ });
804
+ es.dispatchEvent(event);
805
+ fire(es, es.onopen, event);
806
+ } else {
807
+ var message = "";
808
+ if (status !== 200) {
809
+ if (statusText) {
810
+ statusText = statusText.replace(/\s+/g, " ");
811
+ }
812
+ message = "EventSource's response has a status " + status + " " + statusText + " that is not 200. Aborting the connection.";
813
+ } else {
814
+ message = "EventSource's response has a Content-Type specifying an unsupported type: " + (contentType == undefined ? "-" : contentType.replace(/\s+/g, " ")) + ". Aborting the connection.";
815
+ }
816
+ close();
817
+ var event = new ConnectionEvent("error", {
818
+ status: status,
819
+ statusText: statusText,
820
+ headers: headers
821
+ });
822
+ es.dispatchEvent(event);
823
+ fire(es, es.onerror, event);
824
+ console.error(message);
825
+ }
826
+ }
827
+ };
828
+
829
+ var onProgress = function (textChunk) {
830
+ if (currentState === OPEN) {
831
+ var n = -1;
832
+ for (var i = 0; i < textChunk.length; i += 1) {
833
+ var c = textChunk.charCodeAt(i);
834
+ if (c === "\n".charCodeAt(0) || c === "\r".charCodeAt(0)) {
835
+ n = i;
836
+ }
837
+ }
838
+ var chunk = (n !== -1 ? textBuffer : "") + textChunk.slice(0, n + 1);
839
+ textBuffer = (n === -1 ? textBuffer : "") + textChunk.slice(n + 1);
840
+ if (textChunk !== "") {
841
+ wasActivity = Date.now();
842
+ textLength += textChunk.length;
843
+ }
844
+ for (var position = 0; position < chunk.length; position += 1) {
845
+ var c = chunk.charCodeAt(position);
846
+ if (state === AFTER_CR && c === "\n".charCodeAt(0)) {
847
+ state = FIELD_START;
848
+ } else {
849
+ if (state === AFTER_CR) {
850
+ state = FIELD_START;
851
+ }
852
+ if (c === "\r".charCodeAt(0) || c === "\n".charCodeAt(0)) {
853
+ if (state !== FIELD_START) {
854
+ if (state === FIELD) {
855
+ valueStart = position + 1;
856
+ }
857
+ var field = chunk.slice(fieldStart, valueStart - 1);
858
+ var value = chunk.slice(valueStart + (valueStart < position && chunk.charCodeAt(valueStart) === " ".charCodeAt(0) ? 1 : 0), position);
859
+ if (field === "data") {
860
+ dataBuffer += "\n";
861
+ dataBuffer += value;
862
+ } else if (field === "id") {
863
+ lastEventIdBuffer = value;
864
+ } else if (field === "event") {
865
+ eventTypeBuffer = value;
866
+ } else if (field === "retry") {
867
+ initialRetry = parseDuration(value, initialRetry);
868
+ retry = initialRetry;
869
+ } else if (field === "heartbeatTimeout") {
870
+ heartbeatTimeout = parseDuration(value, heartbeatTimeout);
871
+ if (timeout !== 0) {
872
+ clearTimeout(timeout);
873
+ timeout = setTimeout(function () {
874
+ onTimeout();
875
+ }, heartbeatTimeout);
876
+ }
877
+ }
878
+ }
879
+ if (state === FIELD_START) {
880
+ if (dataBuffer !== "") {
881
+ lastEventId = lastEventIdBuffer;
882
+ if (eventTypeBuffer === "") {
883
+ eventTypeBuffer = "message";
884
+ }
885
+ var event = new MessageEvent(eventTypeBuffer, {
886
+ data: dataBuffer.slice(1),
887
+ lastEventId: lastEventIdBuffer
888
+ });
889
+ es.dispatchEvent(event);
890
+ if (eventTypeBuffer === "open") {
891
+ fire(es, es.onopen, event);
892
+ } else if (eventTypeBuffer === "message") {
893
+ fire(es, es.onmessage, event);
894
+ } else if (eventTypeBuffer === "error") {
895
+ fire(es, es.onerror, event);
896
+ }
897
+ if (currentState === CLOSED) {
898
+ return;
899
+ }
900
+ }
901
+ dataBuffer = "";
902
+ eventTypeBuffer = "";
903
+ }
904
+ state = c === "\r".charCodeAt(0) ? AFTER_CR : FIELD_START;
905
+ } else {
906
+ if (state === FIELD_START) {
907
+ fieldStart = position;
908
+ state = FIELD;
909
+ }
910
+ if (state === FIELD) {
911
+ if (c === ":".charCodeAt(0)) {
912
+ valueStart = position + 1;
913
+ state = VALUE_START;
914
+ }
915
+ } else if (state === VALUE_START) {
916
+ state = VALUE;
917
+ }
918
+ }
919
+ }
920
+ }
921
+ }
922
+ };
923
+
924
+ var onFinish = function (error) {
925
+ if (currentState === OPEN || currentState === CONNECTING) {
926
+ currentState = WAITING;
927
+ if (timeout !== 0) {
928
+ clearTimeout(timeout);
929
+ timeout = 0;
930
+ }
931
+ timeout = setTimeout(function () {
932
+ onTimeout();
933
+ }, retry);
934
+ retry = clampDuration(Math.min(initialRetry * 16, retry * 2));
935
+
936
+ es.readyState = CONNECTING;
937
+ var event = new ErrorEvent("error", {error: error});
938
+ es.dispatchEvent(event);
939
+ fire(es, es.onerror, event);
940
+ if (error != undefined) {
941
+ console.error(error);
942
+ }
943
+ }
944
+ };
945
+
946
+ var close = function () {
947
+ currentState = CLOSED;
948
+ if (abortController != undefined) {
949
+ abortController.abort();
950
+ abortController = undefined;
951
+ }
952
+ if (timeout !== 0) {
953
+ clearTimeout(timeout);
954
+ timeout = 0;
955
+ }
956
+ es.readyState = CLOSED;
957
+ };
958
+
959
+ var onTimeout = function () {
960
+ timeout = 0;
961
+
962
+ if (currentState !== WAITING) {
963
+ if (!wasActivity && abortController != undefined) {
964
+ onFinish(new Error("No activity within " + heartbeatTimeout + " milliseconds." + " " + (currentState === CONNECTING ? "No response received." : textLength + " chars received.") + " " + "Reconnecting."));
965
+ if (abortController != undefined) {
966
+ abortController.abort();
967
+ abortController = undefined;
968
+ }
969
+ } else {
970
+ var nextHeartbeat = Math.max((wasActivity || Date.now()) + heartbeatTimeout - Date.now(), 1);
971
+ wasActivity = false;
972
+ timeout = setTimeout(function () {
973
+ onTimeout();
974
+ }, nextHeartbeat);
975
+ }
976
+ return;
977
+ }
978
+
979
+ wasActivity = false;
980
+ textLength = 0;
981
+ timeout = setTimeout(function () {
982
+ onTimeout();
983
+ }, heartbeatTimeout);
984
+
985
+ currentState = CONNECTING;
986
+ dataBuffer = "";
987
+ eventTypeBuffer = "";
988
+ lastEventIdBuffer = lastEventId;
989
+ textBuffer = "";
990
+ fieldStart = 0;
991
+ valueStart = 0;
992
+ state = FIELD_START;
993
+
994
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=428916
995
+ // Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers.
996
+ var requestURL = url;
997
+ if (url.slice(0, 5) !== "data:" && url.slice(0, 5) !== "blob:") {
998
+ if (lastEventId !== "") {
999
+ // Remove the lastEventId parameter if it's already part of the request URL.
1000
+ var i = url.indexOf("?");
1001
+ requestURL = i === -1 ? url : url.slice(0, i + 1) + url.slice(i + 1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g, function (p, paramName) {
1002
+ return paramName === lastEventIdQueryParameterName ? '' : p;
1003
+ });
1004
+ // Append the current lastEventId to the request URL.
1005
+ requestURL += (url.indexOf("?") === -1 ? "?" : "&") + lastEventIdQueryParameterName +"=" + encodeURIComponent(lastEventId);
1006
+ }
1007
+ }
1008
+ var withCredentials = es.withCredentials;
1009
+ var requestHeaders = {};
1010
+ requestHeaders["Accept"] = "text/event-stream";
1011
+ var headers = es.headers;
1012
+ if (headers != undefined) {
1013
+ for (var name in headers) {
1014
+ if (Object.prototype.hasOwnProperty.call(headers, name)) {
1015
+ requestHeaders[name] = headers[name];
1016
+ }
1017
+ }
1018
+ }
1019
+ try {
1020
+ abortController = transport.open(xhr, onStart, onProgress, onFinish, requestURL, withCredentials, requestHeaders);
1021
+ } catch (error) {
1022
+ close();
1023
+ throw error;
1024
+ }
1025
+ };
1026
+
1027
+ es.url = url;
1028
+ es.readyState = CONNECTING;
1029
+ es.withCredentials = withCredentials;
1030
+ es.headers = headers;
1031
+ es._close = close;
1032
+
1033
+ onTimeout();
1034
+ }
1035
+
1036
+ EventSourcePolyfill.prototype = Object.create(EventTarget.prototype);
1037
+ EventSourcePolyfill.prototype.CONNECTING = CONNECTING;
1038
+ EventSourcePolyfill.prototype.OPEN = OPEN;
1039
+ EventSourcePolyfill.prototype.CLOSED = CLOSED;
1040
+ EventSourcePolyfill.prototype.close = function () {
1041
+ this._close();
1042
+ };
1043
+
1044
+ EventSourcePolyfill.CONNECTING = CONNECTING;
1045
+ EventSourcePolyfill.OPEN = OPEN;
1046
+ EventSourcePolyfill.CLOSED = CLOSED;
1047
+ EventSourcePolyfill.prototype.withCredentials = undefined;
1048
+
1049
+ var R = NativeEventSource
1050
+ if (XMLHttpRequest != undefined && (NativeEventSource == undefined || !("withCredentials" in NativeEventSource.prototype))) {
1051
+ // Why replace a native EventSource ?
1052
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=444328
1053
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=831392
1054
+ // https://code.google.com/p/chromium/issues/detail?id=260144
1055
+ // https://code.google.com/p/chromium/issues/detail?id=225654
1056
+ // ...
1057
+ R = EventSourcePolyfill;
1058
+ }
1059
+
1060
+ (function (factory) {
1061
+ if (typeof module === "object" && typeof module.exports === "object") {
1062
+ var v = factory(exports);
1063
+ if (v !== undefined) module.exports = v;
1064
+ }
1065
+ else if (typeof define === "function" && define.amd) {
1066
+ define(["exports"], factory);
1067
+ }
1068
+ else {
1069
+ factory(global);
1070
+ }
1071
+ })(function (exports) {
1072
+ exports.EventSourcePolyfill = EventSourcePolyfill;
1073
+ exports.NativeEventSource = NativeEventSource;
1074
+ exports.EventSource = R;
1075
+ });
1076
+ }(typeof globalThis === 'undefined' ? (typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : this) : globalThis));
1077
+ }}).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});