UNPKG

12.2 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var classCallCheck = function (instance, Constructor) {
6 if (!(instance instanceof Constructor)) {
7 throw new TypeError("Cannot call a class as a function");
8 }
9};
10
11var createClass = function () {
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 return function (Constructor, protoProps, staticProps) {
23 if (protoProps) defineProperties(Constructor.prototype, protoProps);
24 if (staticProps) defineProperties(Constructor, staticProps);
25 return Constructor;
26 };
27}();
28
29var get = function get(object, property, receiver) {
30 if (object === null) object = Function.prototype;
31 var desc = Object.getOwnPropertyDescriptor(object, property);
32
33 if (desc === undefined) {
34 var parent = Object.getPrototypeOf(object);
35
36 if (parent === null) {
37 return undefined;
38 } else {
39 return get(parent, property, receiver);
40 }
41 } else if ("value" in desc) {
42 return desc.value;
43 } else {
44 var getter = desc.get;
45
46 if (getter === undefined) {
47 return undefined;
48 }
49
50 return getter.call(receiver);
51 }
52};
53
54var inherits = function (subClass, superClass) {
55 if (typeof superClass !== "function" && superClass !== null) {
56 throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
57 }
58
59 subClass.prototype = Object.create(superClass && superClass.prototype, {
60 constructor: {
61 value: subClass,
62 enumerable: false,
63 writable: true,
64 configurable: true
65 }
66 });
67 if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
68};
69
70var possibleConstructorReturn = function (self, call) {
71 if (!self) {
72 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
73 }
74
75 return call && (typeof call === "object" || typeof call === "function") ? call : self;
76};
77
78var Emitter = function () {
79 function Emitter() {
80 classCallCheck(this, Emitter);
81
82 this.listeners = {};
83 }
84
85 createClass(Emitter, [{
86 key: 'addEventListener',
87 value: function addEventListener(type, callback) {
88 if (!(type in this.listeners)) {
89 this.listeners[type] = [];
90 }
91 this.listeners[type].push(callback);
92 }
93 }, {
94 key: 'removeEventListener',
95 value: function removeEventListener(type, callback) {
96 if (!(type in this.listeners)) {
97 return;
98 }
99 var stack = this.listeners[type];
100 for (var i = 0, l = stack.length; i < l; i++) {
101 if (stack[i] === callback) {
102 stack.splice(i, 1);
103 return;
104 }
105 }
106 }
107 }, {
108 key: 'dispatchEvent',
109 value: function dispatchEvent(event) {
110 var _this = this;
111
112 if (!(event.type in this.listeners)) {
113 return;
114 }
115 var debounce = function debounce(callback) {
116 setTimeout(function () {
117 return callback.call(_this, event);
118 });
119 };
120 var stack = this.listeners[event.type];
121 for (var i = 0, l = stack.length; i < l; i++) {
122 debounce(stack[i]);
123 }
124 return !event.defaultPrevented;
125 }
126 }]);
127 return Emitter;
128}();
129
130var AbortSignal = function (_Emitter) {
131 inherits(AbortSignal, _Emitter);
132
133 function AbortSignal() {
134 classCallCheck(this, AbortSignal);
135
136 var _this2 = possibleConstructorReturn(this, (AbortSignal.__proto__ || Object.getPrototypeOf(AbortSignal)).call(this));
137
138 _this2.aborted = false;
139 _this2.onabort = null;
140 return _this2;
141 }
142
143 createClass(AbortSignal, [{
144 key: 'toString',
145 value: function toString() {
146 return '[object AbortSignal]';
147 }
148 }, {
149 key: 'dispatchEvent',
150 value: function dispatchEvent(event) {
151 if (event.type === 'abort') {
152 this.aborted = true;
153 if (typeof this.onabort === 'function') {
154 this.onabort.call(this, event);
155 }
156 }
157
158 get(AbortSignal.prototype.__proto__ || Object.getPrototypeOf(AbortSignal.prototype), 'dispatchEvent', this).call(this, event);
159 }
160 }]);
161 return AbortSignal;
162}(Emitter);
163
164var AbortController = function () {
165 function AbortController() {
166 classCallCheck(this, AbortController);
167
168 this.signal = new AbortSignal();
169 }
170
171 createClass(AbortController, [{
172 key: 'abort',
173 value: function abort() {
174 var event = void 0;
175 try {
176 event = new Event('abort');
177 } catch (e) {
178 if (typeof document !== 'undefined') {
179 if (!document.createEvent) {
180 // For Internet Explorer 8:
181 event = document.createEventObject();
182 event.type = 'abort';
183 } else {
184 // For Internet Explorer 11:
185 event = document.createEvent('Event');
186 event.initEvent('abort', false, false);
187 }
188 } else {
189 // Fallback where document isn't available:
190 event = {
191 type: 'abort',
192 bubbles: false,
193 cancelable: false
194 };
195 }
196 }
197 this.signal.dispatchEvent(event);
198 }
199 }, {
200 key: 'toString',
201 value: function toString() {
202 return '[object AbortController]';
203 }
204 }]);
205 return AbortController;
206}();
207
208if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
209 // These are necessary to make sure that we get correct output for:
210 // Object.prototype.toString.call(new AbortController())
211 AbortController.prototype[Symbol.toStringTag] = 'AbortController';
212 AbortSignal.prototype[Symbol.toStringTag] = 'AbortSignal';
213}
214
215function polyfillNeeded(self) {
216 if (self.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
217 console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill');
218 return true;
219 }
220
221 // Note that the "unfetch" minimal fetch polyfill defines fetch() without
222 // defining window.Request, and this polyfill need to work on top of unfetch
223 // so the below feature detection needs the !self.AbortController part.
224 // The Request.prototype check is also needed because Safari versions 11.1.2
225 // up to and including 12.1.x has a window.AbortController present but still
226 // does NOT correctly implement abortable fetch:
227 // https://bugs.webkit.org/show_bug.cgi?id=174980#c2
228 return typeof self.Request === 'function' && !self.Request.prototype.hasOwnProperty('signal') || !self.AbortController;
229}
230
231/**
232 * Note: the "fetch.Request" default value is available for fetch imported from
233 * the "node-fetch" package and not in browsers. This is OK since browsers
234 * will be importing umd-polyfill.js from that path "self" is passed the
235 * decorator so the default value will not be used (because browsers that define
236 * fetch also has Request). One quirky setup where self.fetch exists but
237 * self.Request does not is when the "unfetch" minimal fetch polyfill is used
238 * on top of IE11; for this case the browser will try to use the fetch.Request
239 * default value which in turn will be undefined but then then "if (Request)"
240 * will ensure that you get a patched fetch but still no Request (as expected).
241 * @param {fetch, Request = fetch.Request}
242 * @returns {fetch: abortableFetch, Request: AbortableRequest}
243 */
244function abortableFetchDecorator(patchTargets) {
245 if ('function' === typeof patchTargets) {
246 patchTargets = { fetch: patchTargets };
247 }
248
249 var _patchTargets = patchTargets,
250 fetch = _patchTargets.fetch,
251 _patchTargets$Request = _patchTargets.Request,
252 NativeRequest = _patchTargets$Request === undefined ? fetch.Request : _patchTargets$Request,
253 NativeAbortController = _patchTargets.AbortController,
254 _patchTargets$__FORCE = _patchTargets.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,
255 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL = _patchTargets$__FORCE === undefined ? false : _patchTargets$__FORCE;
256
257 if (!polyfillNeeded({ fetch: fetch, Request: NativeRequest, AbortController: NativeAbortController, __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL: __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL })) {
258 return { fetch: fetch, Request: Request };
259 }
260
261 var Request = NativeRequest;
262 // Note that the "unfetch" minimal fetch polyfill defines fetch() without
263 // defining window.Request, and this polyfill need to work on top of unfetch
264 // hence we only patch it if it's available. Also we don't patch it if signal
265 // is already available on the Request prototype because in this case support
266 // is present and the patching below can cause a crash since it assigns to
267 // request.signal which is technically a read-only property. This latter error
268 // happens when you run the main5.js node-fetch example in the repo
269 // "abortcontroller-polyfill-examples". The exact error is:
270 // request.signal = init.signal;
271 // ^
272 // TypeError: Cannot set property signal of #<Request> which has only a getter
273 if (Request && !Request.prototype.hasOwnProperty('signal') || __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
274 Request = function Request(input, init) {
275 var signal = void 0;
276 if (init && init.signal) {
277 signal = init.signal;
278 // Never pass init.signal to the native Request implementation when the polyfill has
279 // been installed because if we're running on top of a browser with a
280 // working native AbortController (i.e. the polyfill was installed due to
281 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
282 // fake AbortSignal to the native fetch will trigger:
283 // TypeError: Failed to construct 'Request': member signal is not of type AbortSignal.
284 delete init.signal;
285 }
286 var request = new NativeRequest(input, init);
287 if (signal) {
288 Object.defineProperty(request, 'signal', {
289 writable: false,
290 enumerable: false,
291 configurable: true,
292 value: signal
293 });
294 }
295 return request;
296 };
297 Request.prototype = NativeRequest.prototype;
298 }
299
300 var realFetch = fetch;
301 var abortableFetch = function abortableFetch(input, init) {
302 var signal = Request && Request.prototype.isPrototypeOf(input) ? input.signal : init ? init.signal : undefined;
303
304 if (signal) {
305 var abortError = void 0;
306 try {
307 abortError = new DOMException('Aborted', 'AbortError');
308 } catch (err) {
309 // IE 11 does not support calling the DOMException constructor, use a
310 // regular error object on it instead.
311 abortError = new Error('Aborted');
312 abortError.name = 'AbortError';
313 }
314
315 // Return early if already aborted, thus avoiding making an HTTP request
316 if (signal.aborted) {
317 return Promise.reject(abortError);
318 }
319
320 // Turn an event into a promise, reject it once `abort` is dispatched
321 var cancellation = new Promise(function (_, reject) {
322 signal.addEventListener('abort', function () {
323 return reject(abortError);
324 }, { once: true });
325 });
326
327 if (init && init.signal) {
328 // Never pass .signal to the native implementation when the polyfill has
329 // been installed because if we're running on top of a browser with a
330 // working native AbortController (i.e. the polyfill was installed due to
331 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
332 // fake AbortSignal to the native fetch will trigger:
333 // TypeError: Failed to execute 'fetch' on 'Window': member signal is not of type AbortSignal.
334 delete init.signal;
335 }
336 // Return the fastest promise (don't need to wait for request to finish)
337 return Promise.race([cancellation, realFetch(input, init)]);
338 }
339
340 return realFetch(input, init);
341 };
342
343 return { fetch: abortableFetch, Request: Request };
344}
345
346exports.AbortController = AbortController;
347exports.AbortSignal = AbortSignal;
348exports.abortableFetch = abortableFetchDecorator;