source: frontend/node_modules/whatwg-fetch/fetch.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 17.6 KB
Line 
1/* eslint-disable no-prototype-builtins */
2var g =
3 (typeof globalThis !== 'undefined' && globalThis) ||
4 (typeof self !== 'undefined' && self) ||
5 // eslint-disable-next-line no-undef
6 (typeof global !== 'undefined' && global) ||
7 {}
8
9var support = {
10 searchParams: 'URLSearchParams' in g,
11 iterable: 'Symbol' in g && 'iterator' in Symbol,
12 blob:
13 'FileReader' in g &&
14 'Blob' in g &&
15 (function() {
16 try {
17 new Blob()
18 return true
19 } catch (e) {
20 return false
21 }
22 })(),
23 formData: 'FormData' in g,
24 arrayBuffer: 'ArrayBuffer' in g
25}
26
27function isDataView(obj) {
28 return obj && DataView.prototype.isPrototypeOf(obj)
29}
30
31if (support.arrayBuffer) {
32 var viewClasses = [
33 '[object Int8Array]',
34 '[object Uint8Array]',
35 '[object Uint8ClampedArray]',
36 '[object Int16Array]',
37 '[object Uint16Array]',
38 '[object Int32Array]',
39 '[object Uint32Array]',
40 '[object Float32Array]',
41 '[object Float64Array]'
42 ]
43
44 var isArrayBufferView =
45 ArrayBuffer.isView ||
46 function(obj) {
47 return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
48 }
49}
50
51function normalizeName(name) {
52 if (typeof name !== 'string') {
53 name = String(name)
54 }
55 if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {
56 throw new TypeError('Invalid character in header field name: "' + name + '"')
57 }
58 return name.toLowerCase()
59}
60
61function normalizeValue(value) {
62 if (typeof value !== 'string') {
63 value = String(value)
64 }
65 return value
66}
67
68// Build a destructive iterator for the value list
69function iteratorFor(items) {
70 var iterator = {
71 next: function() {
72 var value = items.shift()
73 return {done: value === undefined, value: value}
74 }
75 }
76
77 if (support.iterable) {
78 iterator[Symbol.iterator] = function() {
79 return iterator
80 }
81 }
82
83 return iterator
84}
85
86export function Headers(headers) {
87 this.map = {}
88
89 if (headers instanceof Headers) {
90 headers.forEach(function(value, name) {
91 this.append(name, value)
92 }, this)
93 } else if (Array.isArray(headers)) {
94 headers.forEach(function(header) {
95 if (header.length != 2) {
96 throw new TypeError('Headers constructor: expected name/value pair to be length 2, found' + header.length)
97 }
98 this.append(header[0], header[1])
99 }, this)
100 } else if (headers) {
101 Object.getOwnPropertyNames(headers).forEach(function(name) {
102 this.append(name, headers[name])
103 }, this)
104 }
105}
106
107Headers.prototype.append = function(name, value) {
108 name = normalizeName(name)
109 value = normalizeValue(value)
110 var oldValue = this.map[name]
111 this.map[name] = oldValue ? oldValue + ', ' + value : value
112}
113
114Headers.prototype['delete'] = function(name) {
115 delete this.map[normalizeName(name)]
116}
117
118Headers.prototype.get = function(name) {
119 name = normalizeName(name)
120 return this.has(name) ? this.map[name] : null
121}
122
123Headers.prototype.has = function(name) {
124 return this.map.hasOwnProperty(normalizeName(name))
125}
126
127Headers.prototype.set = function(name, value) {
128 this.map[normalizeName(name)] = normalizeValue(value)
129}
130
131Headers.prototype.forEach = function(callback, thisArg) {
132 for (var name in this.map) {
133 if (this.map.hasOwnProperty(name)) {
134 callback.call(thisArg, this.map[name], name, this)
135 }
136 }
137}
138
139Headers.prototype.keys = function() {
140 var items = []
141 this.forEach(function(value, name) {
142 items.push(name)
143 })
144 return iteratorFor(items)
145}
146
147Headers.prototype.values = function() {
148 var items = []
149 this.forEach(function(value) {
150 items.push(value)
151 })
152 return iteratorFor(items)
153}
154
155Headers.prototype.entries = function() {
156 var items = []
157 this.forEach(function(value, name) {
158 items.push([name, value])
159 })
160 return iteratorFor(items)
161}
162
163if (support.iterable) {
164 Headers.prototype[Symbol.iterator] = Headers.prototype.entries
165}
166
167function consumed(body) {
168 if (body._noBody) return
169 if (body.bodyUsed) {
170 return Promise.reject(new TypeError('Already read'))
171 }
172 body.bodyUsed = true
173}
174
175function fileReaderReady(reader) {
176 return new Promise(function(resolve, reject) {
177 reader.onload = function() {
178 resolve(reader.result)
179 }
180 reader.onerror = function() {
181 reject(reader.error)
182 }
183 })
184}
185
186function readBlobAsArrayBuffer(blob) {
187 var reader = new FileReader()
188 var promise = fileReaderReady(reader)
189 reader.readAsArrayBuffer(blob)
190 return promise
191}
192
193function readBlobAsText(blob) {
194 var reader = new FileReader()
195 var promise = fileReaderReady(reader)
196 var match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type)
197 var encoding = match ? match[1] : 'utf-8'
198 reader.readAsText(blob, encoding)
199 return promise
200}
201
202function readArrayBufferAsText(buf) {
203 var view = new Uint8Array(buf)
204 var chars = new Array(view.length)
205
206 for (var i = 0; i < view.length; i++) {
207 chars[i] = String.fromCharCode(view[i])
208 }
209 return chars.join('')
210}
211
212function bufferClone(buf) {
213 if (buf.slice) {
214 return buf.slice(0)
215 } else {
216 var view = new Uint8Array(buf.byteLength)
217 view.set(new Uint8Array(buf))
218 return view.buffer
219 }
220}
221
222function Body() {
223 this.bodyUsed = false
224
225 this._initBody = function(body) {
226 /*
227 fetch-mock wraps the Response object in an ES6 Proxy to
228 provide useful test harness features such as flush. However, on
229 ES5 browsers without fetch or Proxy support pollyfills must be used;
230 the proxy-pollyfill is unable to proxy an attribute unless it exists
231 on the object before the Proxy is created. This change ensures
232 Response.bodyUsed exists on the instance, while maintaining the
233 semantic of setting Request.bodyUsed in the constructor before
234 _initBody is called.
235 */
236 // eslint-disable-next-line no-self-assign
237 this.bodyUsed = this.bodyUsed
238 this._bodyInit = body
239 if (!body) {
240 this._noBody = true;
241 this._bodyText = ''
242 } else if (typeof body === 'string') {
243 this._bodyText = body
244 } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
245 this._bodyBlob = body
246 } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
247 this._bodyFormData = body
248 } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
249 this._bodyText = body.toString()
250 } else if (support.arrayBuffer && support.blob && isDataView(body)) {
251 this._bodyArrayBuffer = bufferClone(body.buffer)
252 // IE 10-11 can't handle a DataView body.
253 this._bodyInit = new Blob([this._bodyArrayBuffer])
254 } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
255 this._bodyArrayBuffer = bufferClone(body)
256 } else {
257 this._bodyText = body = Object.prototype.toString.call(body)
258 }
259
260 if (!this.headers.get('content-type')) {
261 if (typeof body === 'string') {
262 this.headers.set('content-type', 'text/plain;charset=UTF-8')
263 } else if (this._bodyBlob && this._bodyBlob.type) {
264 this.headers.set('content-type', this._bodyBlob.type)
265 } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
266 this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
267 }
268 }
269 }
270
271 if (support.blob) {
272 this.blob = function() {
273 var rejected = consumed(this)
274 if (rejected) {
275 return rejected
276 }
277
278 if (this._bodyBlob) {
279 return Promise.resolve(this._bodyBlob)
280 } else if (this._bodyArrayBuffer) {
281 return Promise.resolve(new Blob([this._bodyArrayBuffer]))
282 } else if (this._bodyFormData) {
283 throw new Error('could not read FormData body as blob')
284 } else {
285 return Promise.resolve(new Blob([this._bodyText]))
286 }
287 }
288 }
289
290 this.arrayBuffer = function() {
291 if (this._bodyArrayBuffer) {
292 var isConsumed = consumed(this)
293 if (isConsumed) {
294 return isConsumed
295 } else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
296 return Promise.resolve(
297 this._bodyArrayBuffer.buffer.slice(
298 this._bodyArrayBuffer.byteOffset,
299 this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
300 )
301 )
302 } else {
303 return Promise.resolve(this._bodyArrayBuffer)
304 }
305 } else if (support.blob) {
306 return this.blob().then(readBlobAsArrayBuffer)
307 } else {
308 throw new Error('could not read as ArrayBuffer')
309 }
310 }
311
312 this.text = function() {
313 var rejected = consumed(this)
314 if (rejected) {
315 return rejected
316 }
317
318 if (this._bodyBlob) {
319 return readBlobAsText(this._bodyBlob)
320 } else if (this._bodyArrayBuffer) {
321 return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
322 } else if (this._bodyFormData) {
323 throw new Error('could not read FormData body as text')
324 } else {
325 return Promise.resolve(this._bodyText)
326 }
327 }
328
329 if (support.formData) {
330 this.formData = function() {
331 return this.text().then(decode)
332 }
333 }
334
335 this.json = function() {
336 return this.text().then(JSON.parse)
337 }
338
339 return this
340}
341
342// HTTP methods whose capitalization should be normalized
343var methods = ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE']
344
345function normalizeMethod(method) {
346 var upcased = method.toUpperCase()
347 return methods.indexOf(upcased) > -1 ? upcased : method
348}
349
350export function Request(input, options) {
351 if (!(this instanceof Request)) {
352 throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
353 }
354
355 options = options || {}
356 var body = options.body
357
358 if (input instanceof Request) {
359 if (input.bodyUsed) {
360 throw new TypeError('Already read')
361 }
362 this.url = input.url
363 this.credentials = input.credentials
364 if (!options.headers) {
365 this.headers = new Headers(input.headers)
366 }
367 this.method = input.method
368 this.mode = input.mode
369 this.signal = input.signal
370 if (!body && input._bodyInit != null) {
371 body = input._bodyInit
372 input.bodyUsed = true
373 }
374 } else {
375 this.url = String(input)
376 }
377
378 this.credentials = options.credentials || this.credentials || 'same-origin'
379 if (options.headers || !this.headers) {
380 this.headers = new Headers(options.headers)
381 }
382 this.method = normalizeMethod(options.method || this.method || 'GET')
383 this.mode = options.mode || this.mode || null
384 this.signal = options.signal || this.signal || (function () {
385 if ('AbortController' in g) {
386 var ctrl = new AbortController();
387 return ctrl.signal;
388 }
389 }());
390 this.referrer = null
391
392 if ((this.method === 'GET' || this.method === 'HEAD') && body) {
393 throw new TypeError('Body not allowed for GET or HEAD requests')
394 }
395 this._initBody(body)
396
397 if (this.method === 'GET' || this.method === 'HEAD') {
398 if (options.cache === 'no-store' || options.cache === 'no-cache') {
399 // Search for a '_' parameter in the query string
400 var reParamSearch = /([?&])_=[^&]*/
401 if (reParamSearch.test(this.url)) {
402 // If it already exists then set the value with the current time
403 this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime())
404 } else {
405 // Otherwise add a new '_' parameter to the end with the current time
406 var reQueryString = /\?/
407 this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime()
408 }
409 }
410 }
411}
412
413Request.prototype.clone = function() {
414 return new Request(this, {body: this._bodyInit})
415}
416
417function decode(body) {
418 var form = new FormData()
419 body
420 .trim()
421 .split('&')
422 .forEach(function(bytes) {
423 if (bytes) {
424 var split = bytes.split('=')
425 var name = split.shift().replace(/\+/g, ' ')
426 var value = split.join('=').replace(/\+/g, ' ')
427 form.append(decodeURIComponent(name), decodeURIComponent(value))
428 }
429 })
430 return form
431}
432
433function parseHeaders(rawHeaders) {
434 var headers = new Headers()
435 // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
436 // https://tools.ietf.org/html/rfc7230#section-3.2
437 var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ')
438 // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill
439 // https://github.com/github/fetch/issues/748
440 // https://github.com/zloirock/core-js/issues/751
441 preProcessedHeaders
442 .split('\r')
443 .map(function(header) {
444 return header.indexOf('\n') === 0 ? header.substr(1, header.length) : header
445 })
446 .forEach(function(line) {
447 var parts = line.split(':')
448 var key = parts.shift().trim()
449 if (key) {
450 var value = parts.join(':').trim()
451 try {
452 headers.append(key, value)
453 } catch (error) {
454 console.warn('Response ' + error.message)
455 }
456 }
457 })
458 return headers
459}
460
461Body.call(Request.prototype)
462
463export function Response(bodyInit, options) {
464 if (!(this instanceof Response)) {
465 throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
466 }
467 if (!options) {
468 options = {}
469 }
470
471 this.type = 'default'
472 this.status = options.status === undefined ? 200 : options.status
473 if (this.status < 200 || this.status > 599) {
474 throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].")
475 }
476 this.ok = this.status >= 200 && this.status < 300
477 this.statusText = options.statusText === undefined ? '' : '' + options.statusText
478 this.headers = new Headers(options.headers)
479 this.url = options.url || ''
480 this._initBody(bodyInit)
481}
482
483Body.call(Response.prototype)
484
485Response.prototype.clone = function() {
486 return new Response(this._bodyInit, {
487 status: this.status,
488 statusText: this.statusText,
489 headers: new Headers(this.headers),
490 url: this.url
491 })
492}
493
494Response.error = function() {
495 var response = new Response(null, {status: 200, statusText: ''})
496 response.ok = false
497 response.status = 0
498 response.type = 'error'
499 return response
500}
501
502var redirectStatuses = [301, 302, 303, 307, 308]
503
504Response.redirect = function(url, status) {
505 if (redirectStatuses.indexOf(status) === -1) {
506 throw new RangeError('Invalid status code')
507 }
508
509 return new Response(null, {status: status, headers: {location: url}})
510}
511
512export var DOMException = g.DOMException
513try {
514 new DOMException()
515} catch (err) {
516 DOMException = function(message, name) {
517 this.message = message
518 this.name = name
519 var error = Error(message)
520 this.stack = error.stack
521 }
522 DOMException.prototype = Object.create(Error.prototype)
523 DOMException.prototype.constructor = DOMException
524}
525
526export function fetch(input, init) {
527 return new Promise(function(resolve, reject) {
528 var request = new Request(input, init)
529
530 if (request.signal && request.signal.aborted) {
531 return reject(new DOMException('Aborted', 'AbortError'))
532 }
533
534 var xhr = new XMLHttpRequest()
535
536 function abortXhr() {
537 xhr.abort()
538 }
539
540 xhr.onload = function() {
541 var options = {
542 statusText: xhr.statusText,
543 headers: parseHeaders(xhr.getAllResponseHeaders() || '')
544 }
545 // This check if specifically for when a user fetches a file locally from the file system
546 // Only if the status is out of a normal range
547 if (request.url.indexOf('file://') === 0 && (xhr.status < 200 || xhr.status > 599)) {
548 options.status = 200;
549 } else {
550 options.status = xhr.status;
551 }
552 options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
553 var body = 'response' in xhr ? xhr.response : xhr.responseText
554 setTimeout(function() {
555 resolve(new Response(body, options))
556 }, 0)
557 }
558
559 xhr.onerror = function() {
560 setTimeout(function() {
561 reject(new TypeError('Network request failed'))
562 }, 0)
563 }
564
565 xhr.ontimeout = function() {
566 setTimeout(function() {
567 reject(new TypeError('Network request timed out'))
568 }, 0)
569 }
570
571 xhr.onabort = function() {
572 setTimeout(function() {
573 reject(new DOMException('Aborted', 'AbortError'))
574 }, 0)
575 }
576
577 function fixUrl(url) {
578 try {
579 return url === '' && g.location.href ? g.location.href : url
580 } catch (e) {
581 return url
582 }
583 }
584
585 xhr.open(request.method, fixUrl(request.url), true)
586
587 if (request.credentials === 'include') {
588 xhr.withCredentials = true
589 } else if (request.credentials === 'omit') {
590 xhr.withCredentials = false
591 }
592
593 if ('responseType' in xhr) {
594 if (support.blob) {
595 xhr.responseType = 'blob'
596 } else if (
597 support.arrayBuffer
598 ) {
599 xhr.responseType = 'arraybuffer'
600 }
601 }
602
603 if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers || (g.Headers && init.headers instanceof g.Headers))) {
604 var names = [];
605 Object.getOwnPropertyNames(init.headers).forEach(function(name) {
606 names.push(normalizeName(name))
607 xhr.setRequestHeader(name, normalizeValue(init.headers[name]))
608 })
609 request.headers.forEach(function(value, name) {
610 if (names.indexOf(name) === -1) {
611 xhr.setRequestHeader(name, value)
612 }
613 })
614 } else {
615 request.headers.forEach(function(value, name) {
616 xhr.setRequestHeader(name, value)
617 })
618 }
619
620 if (request.signal) {
621 request.signal.addEventListener('abort', abortXhr)
622
623 xhr.onreadystatechange = function() {
624 // DONE (success or failure)
625 if (xhr.readyState === 4) {
626 request.signal.removeEventListener('abort', abortXhr)
627 }
628 }
629 }
630
631 xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
632 })
633}
634
635fetch.polyfill = true
636
637if (!g.fetch) {
638 g.fetch = fetch
639 g.Headers = Headers
640 g.Request = Request
641 g.Response = Response
642}
Note: See TracBrowser for help on using the repository browser.