UNPKG

16.6 kBJavaScriptView Raw
1(function (factory) {
2 typeof define === 'function' && define.amd ? define(factory) :
3 factory();
4}((function () { 'use strict';
5
6 function _classCallCheck(instance, Constructor) {
7 if (!(instance instanceof Constructor)) {
8 throw new TypeError("Cannot call a class as a function");
9 }
10 }
11
12 function _defineProperties(target, props) {
13 for (var i = 0; i < props.length; i++) {
14 var descriptor = props[i];
15 descriptor.enumerable = descriptor.enumerable || false;
16 descriptor.configurable = true;
17 if ("value" in descriptor) descriptor.writable = true;
18 Object.defineProperty(target, descriptor.key, descriptor);
19 }
20 }
21
22 function _createClass(Constructor, protoProps, staticProps) {
23 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
24 if (staticProps) _defineProperties(Constructor, staticProps);
25 return Constructor;
26 }
27
28 function _inherits(subClass, superClass) {
29 if (typeof superClass !== "function" && superClass !== null) {
30 throw new TypeError("Super expression must either be null or a function");
31 }
32
33 subClass.prototype = Object.create(superClass && superClass.prototype, {
34 constructor: {
35 value: subClass,
36 writable: true,
37 configurable: true
38 }
39 });
40 if (superClass) _setPrototypeOf(subClass, superClass);
41 }
42
43 function _getPrototypeOf(o) {
44 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
45 return o.__proto__ || Object.getPrototypeOf(o);
46 };
47 return _getPrototypeOf(o);
48 }
49
50 function _setPrototypeOf(o, p) {
51 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
52 o.__proto__ = p;
53 return o;
54 };
55
56 return _setPrototypeOf(o, p);
57 }
58
59 function _isNativeReflectConstruct() {
60 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
61 if (Reflect.construct.sham) return false;
62 if (typeof Proxy === "function") return true;
63
64 try {
65 Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
66 return true;
67 } catch (e) {
68 return false;
69 }
70 }
71
72 function _assertThisInitialized(self) {
73 if (self === void 0) {
74 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
75 }
76
77 return self;
78 }
79
80 function _possibleConstructorReturn(self, call) {
81 if (call && (typeof call === "object" || typeof call === "function")) {
82 return call;
83 }
84
85 return _assertThisInitialized(self);
86 }
87
88 function _createSuper(Derived) {
89 var hasNativeReflectConstruct = _isNativeReflectConstruct();
90
91 return function _createSuperInternal() {
92 var Super = _getPrototypeOf(Derived),
93 result;
94
95 if (hasNativeReflectConstruct) {
96 var NewTarget = _getPrototypeOf(this).constructor;
97
98 result = Reflect.construct(Super, arguments, NewTarget);
99 } else {
100 result = Super.apply(this, arguments);
101 }
102
103 return _possibleConstructorReturn(this, result);
104 };
105 }
106
107 function _superPropBase(object, property) {
108 while (!Object.prototype.hasOwnProperty.call(object, property)) {
109 object = _getPrototypeOf(object);
110 if (object === null) break;
111 }
112
113 return object;
114 }
115
116 function _get(target, property, receiver) {
117 if (typeof Reflect !== "undefined" && Reflect.get) {
118 _get = Reflect.get;
119 } else {
120 _get = function _get(target, property, receiver) {
121 var base = _superPropBase(target, property);
122
123 if (!base) return;
124 var desc = Object.getOwnPropertyDescriptor(base, property);
125
126 if (desc.get) {
127 return desc.get.call(receiver);
128 }
129
130 return desc.value;
131 };
132 }
133
134 return _get(target, property, receiver || target);
135 }
136
137 var Emitter = /*#__PURE__*/function () {
138 function Emitter() {
139 _classCallCheck(this, Emitter);
140
141 Object.defineProperty(this, 'listeners', {
142 value: {},
143 writable: true,
144 configurable: true
145 });
146 }
147
148 _createClass(Emitter, [{
149 key: "addEventListener",
150 value: function addEventListener(type, callback, options) {
151 if (!(type in this.listeners)) {
152 this.listeners[type] = [];
153 }
154
155 this.listeners[type].push({
156 callback: callback,
157 options: options
158 });
159 }
160 }, {
161 key: "removeEventListener",
162 value: function removeEventListener(type, callback) {
163 if (!(type in this.listeners)) {
164 return;
165 }
166
167 var stack = this.listeners[type];
168
169 for (var i = 0, l = stack.length; i < l; i++) {
170 if (stack[i].callback === callback) {
171 stack.splice(i, 1);
172 return;
173 }
174 }
175 }
176 }, {
177 key: "dispatchEvent",
178 value: function dispatchEvent(event) {
179 if (!(event.type in this.listeners)) {
180 return;
181 }
182
183 var stack = this.listeners[event.type];
184 var stackToCall = stack.slice();
185
186 for (var i = 0, l = stackToCall.length; i < l; i++) {
187 var listener = stackToCall[i];
188
189 try {
190 listener.callback.call(this, event);
191 } catch (e) {
192 Promise.resolve().then(function () {
193 throw e;
194 });
195 }
196
197 if (listener.options && listener.options.once) {
198 this.removeEventListener(event.type, listener.callback);
199 }
200 }
201
202 return !event.defaultPrevented;
203 }
204 }]);
205
206 return Emitter;
207 }();
208
209 var AbortSignal = /*#__PURE__*/function (_Emitter) {
210 _inherits(AbortSignal, _Emitter);
211
212 var _super = _createSuper(AbortSignal);
213
214 function AbortSignal() {
215 var _this;
216
217 _classCallCheck(this, AbortSignal);
218
219 _this = _super.call(this); // Some versions of babel does not transpile super() correctly for IE <= 10, if the parent
220 // constructor has failed to run, then "this.listeners" will still be undefined and then we call
221 // the parent constructor directly instead as a workaround. For general details, see babel bug:
222 // https://github.com/babel/babel/issues/3041
223 // This hack was added as a fix for the issue described here:
224 // https://github.com/Financial-Times/polyfill-library/pull/59#issuecomment-477558042
225
226 if (!_this.listeners) {
227 Emitter.call(_assertThisInitialized(_this));
228 } // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and
229 // we want Object.keys(new AbortController().signal) to be [] for compat with the native impl
230
231
232 Object.defineProperty(_assertThisInitialized(_this), 'aborted', {
233 value: false,
234 writable: true,
235 configurable: true
236 });
237 Object.defineProperty(_assertThisInitialized(_this), 'onabort', {
238 value: null,
239 writable: true,
240 configurable: true
241 });
242 return _this;
243 }
244
245 _createClass(AbortSignal, [{
246 key: "toString",
247 value: function toString() {
248 return '[object AbortSignal]';
249 }
250 }, {
251 key: "dispatchEvent",
252 value: function dispatchEvent(event) {
253 if (event.type === 'abort') {
254 this.aborted = true;
255
256 if (typeof this.onabort === 'function') {
257 this.onabort.call(this, event);
258 }
259 }
260
261 _get(_getPrototypeOf(AbortSignal.prototype), "dispatchEvent", this).call(this, event);
262 }
263 }]);
264
265 return AbortSignal;
266 }(Emitter);
267 var AbortController = /*#__PURE__*/function () {
268 function AbortController() {
269 _classCallCheck(this, AbortController);
270
271 // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and
272 // we want Object.keys(new AbortController()) to be [] for compat with the native impl
273 Object.defineProperty(this, 'signal', {
274 value: new AbortSignal(),
275 writable: true,
276 configurable: true
277 });
278 }
279
280 _createClass(AbortController, [{
281 key: "abort",
282 value: function abort() {
283 var event;
284
285 try {
286 event = new Event('abort');
287 } catch (e) {
288 if (typeof document !== 'undefined') {
289 if (!document.createEvent) {
290 // For Internet Explorer 8:
291 event = document.createEventObject();
292 event.type = 'abort';
293 } else {
294 // For Internet Explorer 11:
295 event = document.createEvent('Event');
296 event.initEvent('abort', false, false);
297 }
298 } else {
299 // Fallback where document isn't available:
300 event = {
301 type: 'abort',
302 bubbles: false,
303 cancelable: false
304 };
305 }
306 }
307
308 this.signal.dispatchEvent(event);
309 }
310 }, {
311 key: "toString",
312 value: function toString() {
313 return '[object AbortController]';
314 }
315 }]);
316
317 return AbortController;
318 }();
319
320 if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
321 // These are necessary to make sure that we get correct output for:
322 // Object.prototype.toString.call(new AbortController())
323 AbortController.prototype[Symbol.toStringTag] = 'AbortController';
324 AbortSignal.prototype[Symbol.toStringTag] = 'AbortSignal';
325 }
326
327 function polyfillNeeded(self) {
328 if (self.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
329 console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill');
330 return true;
331 } // Note that the "unfetch" minimal fetch polyfill defines fetch() without
332 // defining window.Request, and this polyfill need to work on top of unfetch
333 // so the below feature detection needs the !self.AbortController part.
334 // The Request.prototype check is also needed because Safari versions 11.1.2
335 // up to and including 12.1.x has a window.AbortController present but still
336 // does NOT correctly implement abortable fetch:
337 // https://bugs.webkit.org/show_bug.cgi?id=174980#c2
338
339
340 return typeof self.Request === 'function' && !self.Request.prototype.hasOwnProperty('signal') || !self.AbortController;
341 }
342
343 /**
344 * Note: the "fetch.Request" default value is available for fetch imported from
345 * the "node-fetch" package and not in browsers. This is OK since browsers
346 * will be importing umd-polyfill.js from that path "self" is passed the
347 * decorator so the default value will not be used (because browsers that define
348 * fetch also has Request). One quirky setup where self.fetch exists but
349 * self.Request does not is when the "unfetch" minimal fetch polyfill is used
350 * on top of IE11; for this case the browser will try to use the fetch.Request
351 * default value which in turn will be undefined but then then "if (Request)"
352 * will ensure that you get a patched fetch but still no Request (as expected).
353 * @param {fetch, Request = fetch.Request}
354 * @returns {fetch: abortableFetch, Request: AbortableRequest}
355 */
356
357 function abortableFetchDecorator(patchTargets) {
358 if ('function' === typeof patchTargets) {
359 patchTargets = {
360 fetch: patchTargets
361 };
362 }
363
364 var _patchTargets = patchTargets,
365 fetch = _patchTargets.fetch,
366 _patchTargets$Request = _patchTargets.Request,
367 NativeRequest = _patchTargets$Request === void 0 ? fetch.Request : _patchTargets$Request,
368 NativeAbortController = _patchTargets.AbortController,
369 _patchTargets$__FORCE = _patchTargets.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,
370 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL = _patchTargets$__FORCE === void 0 ? false : _patchTargets$__FORCE;
371
372 if (!polyfillNeeded({
373 fetch: fetch,
374 Request: NativeRequest,
375 AbortController: NativeAbortController,
376 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL: __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL
377 })) {
378 return {
379 fetch: fetch,
380 Request: Request
381 };
382 }
383
384 var Request = NativeRequest; // Note that the "unfetch" minimal fetch polyfill defines fetch() without
385 // defining window.Request, and this polyfill need to work on top of unfetch
386 // hence we only patch it if it's available. Also we don't patch it if signal
387 // is already available on the Request prototype because in this case support
388 // is present and the patching below can cause a crash since it assigns to
389 // request.signal which is technically a read-only property. This latter error
390 // happens when you run the main5.js node-fetch example in the repo
391 // "abortcontroller-polyfill-examples". The exact error is:
392 // request.signal = init.signal;
393 // ^
394 // TypeError: Cannot set property signal of #<Request> which has only a getter
395
396 if (Request && !Request.prototype.hasOwnProperty('signal') || __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
397 Request = function Request(input, init) {
398 var signal;
399
400 if (init && init.signal) {
401 signal = init.signal; // Never pass init.signal to the native Request implementation when the polyfill has
402 // been installed because if we're running on top of a browser with a
403 // working native AbortController (i.e. the polyfill was installed due to
404 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
405 // fake AbortSignal to the native fetch will trigger:
406 // TypeError: Failed to construct 'Request': member signal is not of type AbortSignal.
407
408 delete init.signal;
409 }
410
411 var request = new NativeRequest(input, init);
412
413 if (signal) {
414 Object.defineProperty(request, 'signal', {
415 writable: false,
416 enumerable: false,
417 configurable: true,
418 value: signal
419 });
420 }
421
422 return request;
423 };
424
425 Request.prototype = NativeRequest.prototype;
426 }
427
428 var realFetch = fetch;
429
430 var abortableFetch = function abortableFetch(input, init) {
431 var signal = Request && Request.prototype.isPrototypeOf(input) ? input.signal : init ? init.signal : undefined;
432
433 if (signal) {
434 var abortError;
435
436 try {
437 abortError = new DOMException('Aborted', 'AbortError');
438 } catch (err) {
439 // IE 11 does not support calling the DOMException constructor, use a
440 // regular error object on it instead.
441 abortError = new Error('Aborted');
442 abortError.name = 'AbortError';
443 } // Return early if already aborted, thus avoiding making an HTTP request
444
445
446 if (signal.aborted) {
447 return Promise.reject(abortError);
448 } // Turn an event into a promise, reject it once `abort` is dispatched
449
450
451 var cancellation = new Promise(function (_, reject) {
452 signal.addEventListener('abort', function () {
453 return reject(abortError);
454 }, {
455 once: true
456 });
457 });
458
459 if (init && init.signal) {
460 // Never pass .signal to the native implementation when the polyfill has
461 // been installed because if we're running on top of a browser with a
462 // working native AbortController (i.e. the polyfill was installed due to
463 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
464 // fake AbortSignal to the native fetch will trigger:
465 // TypeError: Failed to execute 'fetch' on 'Window': member signal is not of type AbortSignal.
466 delete init.signal;
467 } // Return the fastest promise (don't need to wait for request to finish)
468
469
470 return Promise.race([cancellation, realFetch(input, init)]);
471 }
472
473 return realFetch(input, init);
474 };
475
476 return {
477 fetch: abortableFetch,
478 Request: Request
479 };
480 }
481
482 (function (self) {
483
484 if (!polyfillNeeded(self)) {
485 return;
486 }
487
488 if (!self.fetch) {
489 console.warn('fetch() is not available, cannot install abortcontroller-polyfill');
490 return;
491 }
492
493 var _abortableFetch = abortableFetchDecorator(self),
494 fetch = _abortableFetch.fetch,
495 Request = _abortableFetch.Request;
496
497 self.fetch = fetch;
498 self.Request = Request;
499 Object.defineProperty(self, 'AbortController', {
500 writable: true,
501 enumerable: false,
502 configurable: true,
503 value: AbortController
504 });
505 Object.defineProperty(self, 'AbortSignal', {
506 writable: true,
507 enumerable: false,
508 configurable: true,
509 value: AbortSignal
510 });
511 })(typeof self !== 'undefined' ? self : global);
512
513})));