UNPKG

15.1 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 Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], 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, options) {
150 if (!(type in this.listeners)) {
151 this.listeners[type] = [];
152 }
153
154 this.listeners[type].push({
155 callback: callback,
156 options: options
157 });
158 }
159 }, {
160 key: "removeEventListener",
161 value: function removeEventListener(type, callback) {
162 if (!(type in this.listeners)) {
163 return;
164 }
165
166 var stack = this.listeners[type];
167
168 for (var i = 0, l = stack.length; i < l; i++) {
169 if (stack[i].callback === callback) {
170 stack.splice(i, 1);
171 return;
172 }
173 }
174 }
175 }, {
176 key: "dispatchEvent",
177 value: function dispatchEvent(event) {
178 if (!(event.type in this.listeners)) {
179 return;
180 }
181
182 var stack = this.listeners[event.type];
183 var stackToCall = stack.slice();
184
185 for (var i = 0, l = stackToCall.length; i < l; i++) {
186 var listener = stackToCall[i];
187
188 try {
189 listener.callback.call(this, event);
190 } catch (e) {
191 Promise.resolve().then(function () {
192 throw e;
193 });
194 }
195
196 if (listener.options && listener.options.once) {
197 this.removeEventListener(event.type, listener.callback);
198 }
199 }
200
201 return !event.defaultPrevented;
202 }
203 }]);
204
205 return Emitter;
206}();
207
208var AbortSignal = /*#__PURE__*/function (_Emitter) {
209 _inherits(AbortSignal, _Emitter);
210
211 var _super = _createSuper(AbortSignal);
212
213 function AbortSignal() {
214 var _this;
215
216 _classCallCheck(this, AbortSignal);
217
218 _this = _super.call(this); // Some versions of babel does not transpile super() correctly for IE <= 10, if the parent
219 // constructor has failed to run, then "this.listeners" will still be undefined and then we call
220 // the parent constructor directly instead as a workaround. For general details, see babel bug:
221 // https://github.com/babel/babel/issues/3041
222 // This hack was added as a fix for the issue described here:
223 // https://github.com/Financial-Times/polyfill-library/pull/59#issuecomment-477558042
224
225 if (!_this.listeners) {
226 Emitter.call(_assertThisInitialized(_this));
227 } // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and
228 // we want Object.keys(new AbortController().signal) to be [] for compat with the native impl
229
230
231 Object.defineProperty(_assertThisInitialized(_this), 'aborted', {
232 value: false,
233 writable: true,
234 configurable: true
235 });
236 Object.defineProperty(_assertThisInitialized(_this), 'onabort', {
237 value: null,
238 writable: true,
239 configurable: true
240 });
241 return _this;
242 }
243
244 _createClass(AbortSignal, [{
245 key: "toString",
246 value: function toString() {
247 return '[object AbortSignal]';
248 }
249 }, {
250 key: "dispatchEvent",
251 value: function dispatchEvent(event) {
252 if (event.type === 'abort') {
253 this.aborted = true;
254
255 if (typeof this.onabort === 'function') {
256 this.onabort.call(this, event);
257 }
258 }
259
260 _get(_getPrototypeOf(AbortSignal.prototype), "dispatchEvent", this).call(this, event);
261 }
262 }]);
263
264 return AbortSignal;
265}(Emitter);
266var AbortController = /*#__PURE__*/function () {
267 function AbortController() {
268 _classCallCheck(this, AbortController);
269
270 // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and
271 // we want Object.keys(new AbortController()) to be [] for compat with the native impl
272 Object.defineProperty(this, 'signal', {
273 value: new AbortSignal(),
274 writable: true,
275 configurable: true
276 });
277 }
278
279 _createClass(AbortController, [{
280 key: "abort",
281 value: function abort() {
282 var event;
283
284 try {
285 event = new Event('abort');
286 } catch (e) {
287 if (typeof document !== 'undefined') {
288 if (!document.createEvent) {
289 // For Internet Explorer 8:
290 event = document.createEventObject();
291 event.type = 'abort';
292 } else {
293 // For Internet Explorer 11:
294 event = document.createEvent('Event');
295 event.initEvent('abort', false, false);
296 }
297 } else {
298 // Fallback where document isn't available:
299 event = {
300 type: 'abort',
301 bubbles: false,
302 cancelable: false
303 };
304 }
305 }
306
307 this.signal.dispatchEvent(event);
308 }
309 }, {
310 key: "toString",
311 value: function toString() {
312 return '[object AbortController]';
313 }
314 }]);
315
316 return AbortController;
317}();
318
319if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
320 // These are necessary to make sure that we get correct output for:
321 // Object.prototype.toString.call(new AbortController())
322 AbortController.prototype[Symbol.toStringTag] = 'AbortController';
323 AbortSignal.prototype[Symbol.toStringTag] = 'AbortSignal';
324}
325
326function polyfillNeeded(self) {
327 if (self.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
328 console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill');
329 return true;
330 } // Note that the "unfetch" minimal fetch polyfill defines fetch() without
331 // defining window.Request, and this polyfill need to work on top of unfetch
332 // so the below feature detection needs the !self.AbortController part.
333 // The Request.prototype check is also needed because Safari versions 11.1.2
334 // up to and including 12.1.x has a window.AbortController present but still
335 // does NOT correctly implement abortable fetch:
336 // https://bugs.webkit.org/show_bug.cgi?id=174980#c2
337
338
339 return typeof self.Request === 'function' && !self.Request.prototype.hasOwnProperty('signal') || !self.AbortController;
340}
341
342/**
343 * Note: the "fetch.Request" default value is available for fetch imported from
344 * the "node-fetch" package and not in browsers. This is OK since browsers
345 * will be importing umd-polyfill.js from that path "self" is passed the
346 * decorator so the default value will not be used (because browsers that define
347 * fetch also has Request). One quirky setup where self.fetch exists but
348 * self.Request does not is when the "unfetch" minimal fetch polyfill is used
349 * on top of IE11; for this case the browser will try to use the fetch.Request
350 * default value which in turn will be undefined but then then "if (Request)"
351 * will ensure that you get a patched fetch but still no Request (as expected).
352 * @param {fetch, Request = fetch.Request}
353 * @returns {fetch: abortableFetch, Request: AbortableRequest}
354 */
355
356function abortableFetchDecorator(patchTargets) {
357 if ('function' === typeof patchTargets) {
358 patchTargets = {
359 fetch: patchTargets
360 };
361 }
362
363 var _patchTargets = patchTargets,
364 fetch = _patchTargets.fetch,
365 _patchTargets$Request = _patchTargets.Request,
366 NativeRequest = _patchTargets$Request === void 0 ? fetch.Request : _patchTargets$Request,
367 NativeAbortController = _patchTargets.AbortController,
368 _patchTargets$__FORCE = _patchTargets.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,
369 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL = _patchTargets$__FORCE === void 0 ? false : _patchTargets$__FORCE;
370
371 if (!polyfillNeeded({
372 fetch: fetch,
373 Request: NativeRequest,
374 AbortController: NativeAbortController,
375 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL: __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL
376 })) {
377 return {
378 fetch: fetch,
379 Request: Request
380 };
381 }
382
383 var Request = NativeRequest; // Note that the "unfetch" minimal fetch polyfill defines fetch() without
384 // defining window.Request, and this polyfill need to work on top of unfetch
385 // hence we only patch it if it's available. Also we don't patch it if signal
386 // is already available on the Request prototype because in this case support
387 // is present and the patching below can cause a crash since it assigns to
388 // request.signal which is technically a read-only property. This latter error
389 // happens when you run the main5.js node-fetch example in the repo
390 // "abortcontroller-polyfill-examples". The exact error is:
391 // request.signal = init.signal;
392 // ^
393 // TypeError: Cannot set property signal of #<Request> which has only a getter
394
395 if (Request && !Request.prototype.hasOwnProperty('signal') || __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
396 Request = function Request(input, init) {
397 var signal;
398
399 if (init && init.signal) {
400 signal = init.signal; // Never pass init.signal to the native Request implementation when the polyfill has
401 // been installed because if we're running on top of a browser with a
402 // working native AbortController (i.e. the polyfill was installed due to
403 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
404 // fake AbortSignal to the native fetch will trigger:
405 // TypeError: Failed to construct 'Request': member signal is not of type AbortSignal.
406
407 delete init.signal;
408 }
409
410 var request = new NativeRequest(input, init);
411
412 if (signal) {
413 Object.defineProperty(request, 'signal', {
414 writable: false,
415 enumerable: false,
416 configurable: true,
417 value: signal
418 });
419 }
420
421 return request;
422 };
423
424 Request.prototype = NativeRequest.prototype;
425 }
426
427 var realFetch = fetch;
428
429 var abortableFetch = function abortableFetch(input, init) {
430 var signal = Request && Request.prototype.isPrototypeOf(input) ? input.signal : init ? init.signal : undefined;
431
432 if (signal) {
433 var abortError;
434
435 try {
436 abortError = new DOMException('Aborted', 'AbortError');
437 } catch (err) {
438 // IE 11 does not support calling the DOMException constructor, use a
439 // regular error object on it instead.
440 abortError = new Error('Aborted');
441 abortError.name = 'AbortError';
442 } // Return early if already aborted, thus avoiding making an HTTP request
443
444
445 if (signal.aborted) {
446 return Promise.reject(abortError);
447 } // Turn an event into a promise, reject it once `abort` is dispatched
448
449
450 var cancellation = new Promise(function (_, reject) {
451 signal.addEventListener('abort', function () {
452 return reject(abortError);
453 }, {
454 once: true
455 });
456 });
457
458 if (init && init.signal) {
459 // Never pass .signal to the native implementation when the polyfill has
460 // been installed because if we're running on top of a browser with a
461 // working native AbortController (i.e. the polyfill was installed due to
462 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
463 // fake AbortSignal to the native fetch will trigger:
464 // TypeError: Failed to execute 'fetch' on 'Window': member signal is not of type AbortSignal.
465 delete init.signal;
466 } // Return the fastest promise (don't need to wait for request to finish)
467
468
469 return Promise.race([cancellation, realFetch(input, init)]);
470 }
471
472 return realFetch(input, init);
473 };
474
475 return {
476 fetch: abortableFetch,
477 Request: Request
478 };
479}
480
481exports.AbortController = AbortController;
482exports.AbortSignal = AbortSignal;
483exports.abortableFetch = abortableFetchDecorator;