UNPKG

17.2 kBJavaScriptView Raw
1(function () {
2 "use strict";
3
4 var support = {
5 searchParams: "URLSearchParams" in global,
6 iterable: "Symbol" in global && "iterator" in Symbol,
7 blob:
8 "FileReader" in global &&
9 "Blob" in global &&
10 (function () {
11 try {
12 new Blob();
13 return true;
14 } catch (e) {
15 return false;
16 }
17 })(),
18 formData: "FormData" in global,
19 arrayBuffer: "ArrayBuffer" in global
20 };
21
22 function isDataView(obj) {
23 return obj && DataView.prototype.isPrototypeOf(obj);
24 }
25
26 if (support.arrayBuffer) {
27 var viewClasses = [
28 "[object Int8Array]",
29 "[object Uint8Array]",
30 "[object Uint8ClampedArray]",
31 "[object Int16Array]",
32 "[object Uint16Array]",
33 "[object Int32Array]",
34 "[object Uint32Array]",
35 "[object Float32Array]",
36 "[object Float64Array]"
37 ];
38
39 var isArrayBufferView =
40 ArrayBuffer.isView ||
41 function (obj) {
42 return (
43 obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
44 );
45 };
46 }
47
48 function normalizeName(name) {
49 if (typeof name !== "string") {
50 name = String(name);
51 }
52 if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) {
53 throw new TypeError("Invalid character in header field name");
54 }
55 return name.toLowerCase();
56 }
57
58 function normalizeValue(value) {
59 if (typeof value !== "string") {
60 value = String(value);
61 }
62 return value;
63 }
64
65 // Build a destructive iterator for the value list
66 function iteratorFor(items) {
67 var iterator = {
68 next: function () {
69 var value = items.shift();
70 return { done: value === undefined, value: value };
71 }
72 };
73
74 if (support.iterable) {
75 iterator[Symbol.iterator] = function () {
76 return iterator;
77 };
78 }
79
80 return iterator;
81 }
82
83 function Headers(headers) {
84 this.map = {};
85
86 if (headers instanceof Headers) {
87 headers.forEach(function (value, name) {
88 this.append(name, value);
89 }, this);
90 } else if (Array.isArray(headers)) {
91 headers.forEach(function (header) {
92 this.append(header[0], header[1]);
93 }, this);
94 } else if (headers) {
95 Object.getOwnPropertyNames(headers).forEach(function (name) {
96 this.append(name, headers[name]);
97 }, this);
98 }
99 }
100
101 Headers.prototype.append = function (name, value) {
102 name = normalizeName(name);
103 value = normalizeValue(value);
104 var oldValue = this.map[name];
105 this.map[name] = oldValue ? oldValue + ", " + value : value;
106 };
107
108 Headers.prototype["delete"] = function (name) {
109 delete this.map[normalizeName(name)];
110 };
111
112 Headers.prototype.get = function (name) {
113 name = normalizeName(name);
114 return this.has(name) ? this.map[name] : null;
115 };
116
117 Headers.prototype.has = function (name) {
118 return this.map.hasOwnProperty(normalizeName(name));
119 };
120
121 Headers.prototype.set = function (name, value) {
122 this.map[normalizeName(name)] = normalizeValue(value);
123 };
124
125 Headers.prototype.forEach = function (callback, thisArg) {
126 for (var name in this.map) {
127 if (this.map.hasOwnProperty(name)) {
128 callback.call(thisArg, this.map[name], name, this);
129 }
130 }
131 };
132
133 Headers.prototype.keys = function () {
134 var items = [];
135 this.forEach(function (value, name) {
136 items.push(name);
137 });
138 return iteratorFor(items);
139 };
140
141 Headers.prototype.values = function () {
142 var items = [];
143 this.forEach(function (value) {
144 items.push(value);
145 });
146 return iteratorFor(items);
147 };
148
149 Headers.prototype.entries = function () {
150 var items = [];
151 this.forEach(function (value, name) {
152 items.push([name, value]);
153 });
154 return iteratorFor(items);
155 };
156
157 if (support.iterable) {
158 Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
159 }
160
161 function consumed(body) {
162 if (body.bodyUsed) {
163 return Promise.reject(new TypeError("Already read"));
164 }
165 body.bodyUsed = true;
166 }
167
168 function fileReaderReady(reader) {
169 return new Promise(function (resolve, reject) {
170 reader.onload = function () {
171 resolve(reader.result);
172 };
173 reader.onerror = function () {
174 reject(reader.error);
175 };
176 });
177 }
178
179 function readBlobAsArrayBuffer(blob) {
180 var reader = new FileReader();
181 var promise = fileReaderReady(reader);
182 reader.readAsArrayBuffer(blob);
183 return promise;
184 }
185
186 function readBlobAsText(blob) {
187 var reader = new FileReader();
188 var promise = fileReaderReady(reader);
189 reader.readAsText(blob);
190 return promise;
191 }
192
193 function readArrayBufferAsText(buf) {
194 var view = new Uint8Array(buf);
195 var chars = new Array(view.length);
196
197 for (var i = 0; i < view.length; i++) {
198 chars[i] = String.fromCharCode(view[i]);
199 }
200 return chars.join("");
201 }
202
203 function bufferClone(buf) {
204 if (buf.slice) {
205 return buf.slice(0);
206 } else {
207 var view = new Uint8Array(buf.byteLength);
208 view.set(new Uint8Array(buf));
209 return view.buffer;
210 }
211 }
212
213 function Body() {
214 this.bodyUsed = false;
215
216 this._initBody = function (body) {
217 this._bodyInit = body;
218 if (!body) {
219 this._bodyText = "";
220 } else if (typeof body === "string") {
221 this._bodyText = body;
222 } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
223 this._bodyBlob = body;
224 } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
225 this._bodyFormData = body;
226 } else if (
227 support.searchParams &&
228 URLSearchParams.prototype.isPrototypeOf(body)
229 ) {
230 this._bodyText = body.toString();
231 } else if (support.arrayBuffer && support.blob && isDataView(body)) {
232 this._bodyArrayBuffer = bufferClone(body.buffer);
233 // IE 10-11 can't handle a DataView body.
234 this._bodyInit = new Blob([this._bodyArrayBuffer]);
235 } else if (
236 support.arrayBuffer &&
237 (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))
238 ) {
239 this._bodyArrayBuffer = bufferClone(body);
240 } else {
241 this._bodyText = body = Object.prototype.toString.call(body);
242 }
243
244 if (!this.headers.get("content-type")) {
245 if (typeof body === "string") {
246 this.headers.set("content-type", "text/plain;charset=UTF-8");
247 } else if (this._bodyBlob && this._bodyBlob.type) {
248 this.headers.set("content-type", this._bodyBlob.type);
249 } else if (
250 support.searchParams &&
251 URLSearchParams.prototype.isPrototypeOf(body)
252 ) {
253 this.headers.set(
254 "content-type",
255 "application/x-www-form-urlencoded;charset=UTF-8"
256 );
257 }
258 }
259 };
260
261 if (support.blob) {
262 this.blob = function () {
263 var rejected = consumed(this);
264 if (rejected) {
265 return rejected;
266 }
267
268 if (this._bodyBlob) {
269 return Promise.resolve(this._bodyBlob);
270 } else if (this._bodyArrayBuffer) {
271 return Promise.resolve(new Blob([this._bodyArrayBuffer]));
272 } else if (this._bodyFormData) {
273 throw new Error("could not read FormData body as blob");
274 } else {
275 return Promise.resolve(new Blob([this._bodyText]));
276 }
277 };
278
279 this.arrayBuffer = function () {
280 if (this._bodyArrayBuffer) {
281 return consumed(this) || Promise.resolve(this._bodyArrayBuffer);
282 } else {
283 return this.blob().then(readBlobAsArrayBuffer);
284 }
285 };
286 }
287
288 this.text = function () {
289 var rejected = consumed(this);
290 if (rejected) {
291 return rejected;
292 }
293
294 if (this._bodyBlob) {
295 return readBlobAsText(this._bodyBlob);
296 } else if (this._bodyArrayBuffer) {
297 return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
298 } else if (this._bodyFormData) {
299 throw new Error("could not read FormData body as text");
300 } else {
301 return Promise.resolve(this._bodyText);
302 }
303 };
304
305 if (support.formData) {
306 this.formData = function () {
307 return this.text().then(decode);
308 };
309 }
310
311 this.json = function () {
312 return this.text().then(JSON.parse);
313 };
314
315 return this;
316 }
317
318 // HTTP methods whose capitalization should be normalized
319 var methods = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"];
320
321 function normalizeMethod(method) {
322 var upcased = method.toUpperCase();
323 return methods.indexOf(upcased) > -1 ? upcased : method;
324 }
325
326 function Request(input, options) {
327 options = options || {};
328 var body = options.body;
329
330 if (input instanceof Request) {
331 if (input.bodyUsed) {
332 throw new TypeError("Already read");
333 }
334 this.url = input.url;
335 this.credentials = input.credentials;
336 if (!options.headers) {
337 this.headers = new Headers(input.headers);
338 }
339 this.method = input.method;
340 this.mode = input.mode;
341 this.signal = input.signal;
342 if (!body && input._bodyInit != null) {
343 body = input._bodyInit;
344 input.bodyUsed = true;
345 }
346 } else {
347 this.url = String(input);
348 }
349
350 this.credentials = options.credentials || this.credentials || "same-origin";
351 if (options.headers || !this.headers) {
352 this.headers = new Headers(options.headers);
353 }
354 this.method = normalizeMethod(options.method || this.method || "GET");
355 this.mode = options.mode || this.mode || null;
356 this.signal = options.signal || this.signal;
357 this.referrer = null;
358
359 if ((this.method === "GET" || this.method === "HEAD") && body) {
360 throw new TypeError("Body not allowed for GET or HEAD requests");
361 }
362 this._initBody(body);
363 }
364
365 Request.prototype.clone = function () {
366 return new Request(this, { body: this._bodyInit });
367 };
368
369 function decode(body) {
370 var form = new FormData();
371 body
372 .trim()
373 .split("&")
374 .forEach(function (bytes) {
375 if (bytes) {
376 var split = bytes.split("=");
377 var name = split.shift().replace(/\+/g, " ");
378 var value = split.join("=").replace(/\+/g, " ");
379 form.append(decodeURIComponent(name), decodeURIComponent(value));
380 }
381 });
382 return form;
383 }
384
385 function parseHeaders(rawHeaders) {
386 var headers = new Headers();
387 // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
388 // https://tools.ietf.org/html/rfc7230#section-3.2
389 var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " ");
390 preProcessedHeaders.split(/\r?\n/).forEach(function (line) {
391 var parts = line.split(":");
392 var key = parts.shift().trim();
393 if (key) {
394 var value = parts.join(":").trim();
395 headers.append(key, value);
396 }
397 });
398 return headers;
399 }
400
401 Body.call(Request.prototype);
402
403 function Response(bodyInit, options) {
404 if (!options) {
405 options = {};
406 }
407
408 this.type = "default";
409 this.status = options.status === undefined ? 200 : options.status;
410 this.ok = this.status >= 200 && this.status < 300;
411 this.statusText = "statusText" in options ? options.statusText : "OK";
412 this.headers = new Headers(options.headers);
413 this.url = options.url || "";
414 this._initBody(bodyInit);
415 }
416
417 Body.call(Response.prototype);
418
419 Response.prototype.clone = function () {
420 return new Response(this._bodyInit, {
421 status: this.status,
422 statusText: this.statusText,
423 headers: new Headers(this.headers),
424 url: this.url
425 });
426 };
427
428 Response.error = function () {
429 var response = new Response(null, { status: 0, statusText: "" });
430 response.type = "error";
431 return response;
432 };
433
434 var redirectStatuses = [301, 302, 303, 307, 308];
435
436 Response.redirect = function (url, status) {
437 if (redirectStatuses.indexOf(status) === -1) {
438 throw new RangeError("Invalid status code");
439 }
440
441 return new Response(null, { status: status, headers: { location: url } });
442 };
443
444 exports.DOMException = global.DOMException;
445 try {
446 new exports.DOMException();
447 } catch (err) {
448 exports.DOMException = function (message, name) {
449 this.message = message;
450 this.name = name;
451 var error = Error(message);
452 this.stack = error.stack;
453 };
454 exports.DOMException.prototype = Object.create(Error.prototype);
455 exports.DOMException.prototype.constructor = exports.DOMException;
456 }
457
458 function fetch(input, init) {
459 return new Promise(function (resolve, reject) {
460 var request = new Request(input, init);
461
462 if (request.signal && request.signal.aborted) {
463 return reject(new exports.DOMException("Aborted", "AbortError"));
464 }
465
466 var xhr = new XMLHttpRequest();
467
468 function abortXhr() {
469 xhr.abort();
470 }
471
472 xhr.onload = function () {
473 var options = {
474 status: xhr.status,
475 statusText: xhr.statusText,
476 headers: parseHeaders(xhr.getAllResponseHeaders() || "")
477 };
478 options.url =
479 "responseURL" in xhr
480 ? xhr.responseURL
481 : options.headers.get("X-Request-URL");
482 var body = "response" in xhr ? xhr.response : xhr.responseText;
483 resolve(new Response(body, options));
484 };
485
486 xhr.onerror = function () {
487 reject(new TypeError("Network request failed"));
488 };
489
490 xhr.ontimeout = function () {
491 reject(new TypeError("Network request failed"));
492 };
493
494 xhr.onabort = function () {
495 reject(new exports.DOMException("Aborted", "AbortError"));
496 };
497
498 xhr.open(request.method, request.url, true);
499
500 if (request.credentials === "include") {
501 xhr.withCredentials = true;
502 } else if (request.credentials === "omit") {
503 xhr.withCredentials = false;
504 }
505
506 if ("responseType" in xhr && support.blob) {
507 xhr.responseType = "blob";
508 }
509
510 request.headers.forEach(function (value, name) {
511 xhr.setRequestHeader(name, value);
512 });
513
514 if (request.signal) {
515 request.signal.addEventListener("abort", abortXhr);
516
517 xhr.onreadystatechange = function () {
518 // DONE (success or failure)
519 if (xhr.readyState === 4) {
520 request.signal.removeEventListener("abort", abortXhr);
521 }
522 };
523 }
524
525 xhr.send(
526 typeof request._bodyInit === "undefined" ? null : request._bodyInit
527 );
528 });
529 }
530
531 fetch.polyfill = true;
532
533 exports.Headers = Headers;
534 exports.Request = Request;
535 exports.Response = Response;
536 exports.fetch = fetch;
537
538 Object.defineProperty(exports, "__esModule", { value: true });
539})();