UNPKG

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