UNPKG

honoka

Version:

Just a fetch() API wrapper for both Browser and Node.js.

1,167 lines (945 loc) 32.4 kB
/** * honoka v0.5.2 * (c) 2020 kokororin * Released under the MIT License. * https://github.com/kokororin/honoka#readme */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.honoka = factory()); }(this, (function () { 'use strict'; var support = { searchParams: 'URLSearchParams' in self, iterable: 'Symbol' in self && 'iterator' in Symbol, blob: 'FileReader' in self && 'Blob' in self && function () { try { new Blob(); return true; } catch (e) { return false; } }(), formData: 'FormData' in self, arrayBuffer: 'ArrayBuffer' in self }; function isDataView(obj) { return obj && DataView.prototype.isPrototypeOf(obj); } if (support.arrayBuffer) { var viewClasses = ['[object Int8Array]', '[object Uint8Array]', '[object Uint8ClampedArray]', '[object Int16Array]', '[object Uint16Array]', '[object Int32Array]', '[object Uint32Array]', '[object Float32Array]', '[object Float64Array]']; var isArrayBufferView = ArrayBuffer.isView || function (obj) { return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1; }; } function normalizeName(name) { if (typeof name !== 'string') { name = String(name); } if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) { throw new TypeError('Invalid character in header field name'); } return name.toLowerCase(); } function normalizeValue(value) { if (typeof value !== 'string') { value = String(value); } return value; } // Build a destructive iterator for the value list function iteratorFor(items) { var iterator = { next: function () { var value = items.shift(); return { done: value === undefined, value: value }; } }; if (support.iterable) { iterator[Symbol.iterator] = function () { return iterator; }; } return iterator; } function Headers(headers) { this.map = {}; if (headers instanceof Headers) { headers.forEach(function (value, name) { this.append(name, value); }, this); } else if (Array.isArray(headers)) { headers.forEach(function (header) { this.append(header[0], header[1]); }, this); } else if (headers) { Object.getOwnPropertyNames(headers).forEach(function (name) { this.append(name, headers[name]); }, this); } } Headers.prototype.append = function (name, value) { name = normalizeName(name); value = normalizeValue(value); var oldValue = this.map[name]; this.map[name] = oldValue ? oldValue + ', ' + value : value; }; Headers.prototype['delete'] = function (name) { delete this.map[normalizeName(name)]; }; Headers.prototype.get = function (name) { name = normalizeName(name); return this.has(name) ? this.map[name] : null; }; Headers.prototype.has = function (name) { return this.map.hasOwnProperty(normalizeName(name)); }; Headers.prototype.set = function (name, value) { this.map[normalizeName(name)] = normalizeValue(value); }; Headers.prototype.forEach = function (callback, thisArg) { for (var name in this.map) { if (this.map.hasOwnProperty(name)) { callback.call(thisArg, this.map[name], name, this); } } }; Headers.prototype.keys = function () { var items = []; this.forEach(function (value, name) { items.push(name); }); return iteratorFor(items); }; Headers.prototype.values = function () { var items = []; this.forEach(function (value) { items.push(value); }); return iteratorFor(items); }; Headers.prototype.entries = function () { var items = []; this.forEach(function (value, name) { items.push([name, value]); }); return iteratorFor(items); }; if (support.iterable) { Headers.prototype[Symbol.iterator] = Headers.prototype.entries; } function consumed(body) { if (body.bodyUsed) { return Promise.reject(new TypeError('Already read')); } body.bodyUsed = true; } function fileReaderReady(reader) { return new Promise(function (resolve, reject) { reader.onload = function () { resolve(reader.result); }; reader.onerror = function () { reject(reader.error); }; }); } function readBlobAsArrayBuffer(blob) { var reader = new FileReader(); var promise = fileReaderReady(reader); reader.readAsArrayBuffer(blob); return promise; } function readBlobAsText(blob) { var reader = new FileReader(); var promise = fileReaderReady(reader); reader.readAsText(blob); return promise; } function readArrayBufferAsText(buf) { var view = new Uint8Array(buf); var chars = new Array(view.length); for (var i = 0; i < view.length; i++) { chars[i] = String.fromCharCode(view[i]); } return chars.join(''); } function bufferClone(buf) { if (buf.slice) { return buf.slice(0); } else { var view = new Uint8Array(buf.byteLength); view.set(new Uint8Array(buf)); return view.buffer; } } function Body() { this.bodyUsed = false; this._initBody = function (body) { this._bodyInit = body; if (!body) { this._bodyText = ''; } else if (typeof body === 'string') { this._bodyText = body; } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { this._bodyBlob = body; } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { this._bodyFormData = body; } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this._bodyText = body.toString(); } else if (support.arrayBuffer && support.blob && isDataView(body)) { this._bodyArrayBuffer = bufferClone(body.buffer); // IE 10-11 can't handle a DataView body. this._bodyInit = new Blob([this._bodyArrayBuffer]); } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { this._bodyArrayBuffer = bufferClone(body); } else { this._bodyText = body = Object.prototype.toString.call(body); } if (!this.headers.get('content-type')) { if (typeof body === 'string') { this.headers.set('content-type', 'text/plain;charset=UTF-8'); } else if (this._bodyBlob && this._bodyBlob.type) { this.headers.set('content-type', this._bodyBlob.type); } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); } } }; if (support.blob) { this.blob = function () { var rejected = consumed(this); if (rejected) { return rejected; } if (this._bodyBlob) { return Promise.resolve(this._bodyBlob); } else if (this._bodyArrayBuffer) { return Promise.resolve(new Blob([this._bodyArrayBuffer])); } else if (this._bodyFormData) { throw new Error('could not read FormData body as blob'); } else { return Promise.resolve(new Blob([this._bodyText])); } }; this.arrayBuffer = function () { if (this._bodyArrayBuffer) { return consumed(this) || Promise.resolve(this._bodyArrayBuffer); } else { return this.blob().then(readBlobAsArrayBuffer); } }; } this.text = function () { var rejected = consumed(this); if (rejected) { return rejected; } if (this._bodyBlob) { return readBlobAsText(this._bodyBlob); } else if (this._bodyArrayBuffer) { return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)); } else if (this._bodyFormData) { throw new Error('could not read FormData body as text'); } else { return Promise.resolve(this._bodyText); } }; if (support.formData) { this.formData = function () { return this.text().then(decode); }; } this.json = function () { return this.text().then(JSON.parse); }; return this; } // HTTP methods whose capitalization should be normalized var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; function normalizeMethod(method) { var upcased = method.toUpperCase(); return methods.indexOf(upcased) > -1 ? upcased : method; } function Request(input, options) { options = options || {}; var body = options.body; if (input instanceof Request) { if (input.bodyUsed) { throw new TypeError('Already read'); } this.url = input.url; this.credentials = input.credentials; if (!options.headers) { this.headers = new Headers(input.headers); } this.method = input.method; this.mode = input.mode; this.signal = input.signal; if (!body && input._bodyInit != null) { body = input._bodyInit; input.bodyUsed = true; } } else { this.url = String(input); } this.credentials = options.credentials || this.credentials || 'same-origin'; if (options.headers || !this.headers) { this.headers = new Headers(options.headers); } this.method = normalizeMethod(options.method || this.method || 'GET'); this.mode = options.mode || this.mode || null; this.signal = options.signal || this.signal; this.referrer = null; if ((this.method === 'GET' || this.method === 'HEAD') && body) { throw new TypeError('Body not allowed for GET or HEAD requests'); } this._initBody(body); } Request.prototype.clone = function () { return new Request(this, { body: this._bodyInit }); }; function decode(body) { var form = new FormData(); body.trim().split('&').forEach(function (bytes) { if (bytes) { var split = bytes.split('='); var name = split.shift().replace(/\+/g, ' '); var value = split.join('=').replace(/\+/g, ' '); form.append(decodeURIComponent(name), decodeURIComponent(value)); } }); return form; } function parseHeaders(rawHeaders) { var headers = new Headers(); // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space // https://tools.ietf.org/html/rfc7230#section-3.2 var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); preProcessedHeaders.split(/\r?\n/).forEach(function (line) { var parts = line.split(':'); var key = parts.shift().trim(); if (key) { var value = parts.join(':').trim(); headers.append(key, value); } }); return headers; } Body.call(Request.prototype); function Response(bodyInit, options) { if (!options) { options = {}; } this.type = 'default'; this.status = options.status === undefined ? 200 : options.status; this.ok = this.status >= 200 && this.status < 300; this.statusText = 'statusText' in options ? options.statusText : 'OK'; this.headers = new Headers(options.headers); this.url = options.url || ''; this._initBody(bodyInit); } Body.call(Response.prototype); Response.prototype.clone = function () { return new Response(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new Headers(this.headers), url: this.url }); }; Response.error = function () { var response = new Response(null, { status: 0, statusText: '' }); response.type = 'error'; return response; }; var redirectStatuses = [301, 302, 303, 307, 308]; Response.redirect = function (url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError('Invalid status code'); } return new Response(null, { status: status, headers: { location: url } }); }; var DOMException = self.DOMException; try { new DOMException(); } catch (err) { DOMException = function (message, name) { this.message = message; this.name = name; var error = Error(message); this.stack = error.stack; }; DOMException.prototype = Object.create(Error.prototype); DOMException.prototype.constructor = DOMException; } function fetch$1(input, init) { return new Promise(function (resolve, reject) { var request = new Request(input, init); if (request.signal && request.signal.aborted) { return reject(new DOMException('Aborted', 'AbortError')); } var xhr = new XMLHttpRequest(); function abortXhr() { xhr.abort(); } xhr.onload = function () { var options = { status: xhr.status, statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || '') }; options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); var body = 'response' in xhr ? xhr.response : xhr.responseText; resolve(new Response(body, options)); }; xhr.onerror = function () { reject(new TypeError('Network request failed')); }; xhr.ontimeout = function () { reject(new TypeError('Network request failed')); }; xhr.onabort = function () { reject(new DOMException('Aborted', 'AbortError')); }; xhr.open(request.method, request.url, true); if (request.credentials === 'include') { xhr.withCredentials = true; } else if (request.credentials === 'omit') { xhr.withCredentials = false; } if ('responseType' in xhr && support.blob) { xhr.responseType = 'blob'; } request.headers.forEach(function (value, name) { xhr.setRequestHeader(name, value); }); if (request.signal) { request.signal.addEventListener('abort', abortXhr); xhr.onreadystatechange = function () { // DONE (success or failure) if (xhr.readyState === 4) { request.signal.removeEventListener('abort', abortXhr); } }; } xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); }); } fetch$1.polyfill = true; if (!self.fetch) { self.fetch = fetch$1; self.Headers = Headers; self.Request = Request; self.Response = Response; } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var arrayLikeToArray = _arrayLikeToArray; function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return arrayLikeToArray(arr); } var arrayWithoutHoles = _arrayWithoutHoles; function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } var iterableToArray = _iterableToArray; function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); } var unsupportedIterableToArray = _unsupportedIterableToArray; function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var nonIterableSpread = _nonIterableSpread; function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); } var toConsumableArray = _toConsumableArray; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var _typeof_1 = createCommonjsModule(function (module) { function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { module.exports = _typeof = function _typeof(obj) { return typeof obj; }; } else { module.exports = _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } module.exports = _typeof; }); var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; var foreach = function forEach(obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; var hasOwn$1 = Object.prototype.hasOwnProperty; var arrayReduce = function (xs, f, acc) { var hasAcc = arguments.length >= 3; if (hasAcc && xs.reduce) return xs.reduce(f, acc); if (xs.reduce) return xs.reduce(f); for (var i = 0; i < xs.length; i++) { if (!hasOwn$1.call(xs, i)) continue; if (!hasAcc) { acc = xs[i]; hasAcc = true; continue; } acc = f(acc, xs[i], i); } return acc; }; var isPlainObj = value => { if (Object.prototype.toString.call(value) !== '[object Object]') { return false; } const prototype = Object.getPrototypeOf(value); return prototype === null || prototype === Object.prototype; }; const { hasOwnProperty } = Object.prototype; const { propertyIsEnumerable } = Object; const defineProperty = (obj, name, value) => Object.defineProperty(obj, name, { value, writable: true, enumerable: true, configurable: true }); const globalThis$1 = commonjsGlobal; const defaultMergeOpts = { concatArrays: false, ignoreUndefined: false }; const getEnumerableOwnPropertyKeys = value => { const keys = []; for (const key in value) { if (hasOwnProperty.call(value, key)) { keys.push(key); } } /* istanbul ignore else */ if (Object.getOwnPropertySymbols) { const symbols = Object.getOwnPropertySymbols(value); for (const symbol of symbols) { if (propertyIsEnumerable.call(value, symbol)) { keys.push(symbol); } } } return keys; }; function clone(value) { if (Array.isArray(value)) { return cloneArray(value); } if (isPlainObj(value)) { return cloneOptionObject(value); } return value; } function cloneArray(array) { const result = array.slice(0, 0); getEnumerableOwnPropertyKeys(array).forEach(key => { defineProperty(result, key, clone(array[key])); }); return result; } function cloneOptionObject(obj) { const result = Object.getPrototypeOf(obj) === null ? Object.create(null) : {}; getEnumerableOwnPropertyKeys(obj).forEach(key => { defineProperty(result, key, clone(obj[key])); }); return result; } /** * @param {*} merged already cloned * @param {*} source something to merge * @param {string[]} keys keys to merge * @param {Object} config Config Object * @returns {*} cloned Object */ const mergeKeys = (merged, source, keys, config) => { keys.forEach(key => { if (typeof source[key] === 'undefined' && config.ignoreUndefined) { return; } // Do not recurse into prototype chain of merged if (key in merged && merged[key] !== Object.getPrototypeOf(merged)) { defineProperty(merged, key, merge(merged[key], source[key], config)); } else { defineProperty(merged, key, clone(source[key])); } }); return merged; }; /** * @param {*} merged already cloned * @param {*} source something to merge * @param {Object} config Config Object * @returns {*} cloned Object * * see [Array.prototype.concat ( ...arguments )](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.concat) */ const concatArrays = (merged, source, config) => { let result = merged.slice(0, 0); let resultIndex = 0; [merged, source].forEach(array => { const indices = []; // `result.concat(array)` with cloning for (let k = 0; k < array.length; k++) { if (!hasOwnProperty.call(array, k)) { continue; } indices.push(String(k)); if (array === merged) { // Already cloned defineProperty(result, resultIndex++, array[k]); } else { defineProperty(result, resultIndex++, clone(array[k])); } } // Merge non-index keys result = mergeKeys(result, array, getEnumerableOwnPropertyKeys(array).filter(key => !indices.includes(key)), config); }); return result; }; /** * @param {*} merged already cloned * @param {*} source something to merge * @param {Object} config Config Object * @returns {*} cloned Object */ function merge(merged, source, config) { if (config.concatArrays && Array.isArray(merged) && Array.isArray(source)) { return concatArrays(merged, source, config); } if (!isPlainObj(source) || !isPlainObj(merged)) { return clone(source); } return mergeKeys(merged, source, getEnumerableOwnPropertyKeys(source), config); } var mergeOptions = function (...options) { const config = merge(clone(defaultMergeOpts), this !== globalThis$1 && this || {}, defaultMergeOpts); let merged = { _: {} }; for (const option of options) { if (option === undefined) { continue; } if (!isPlainObj(option)) { throw new TypeError('`' + option + '` is not an Option Object'); } merged = merge(merged, { _: option }, config); } return merged._; }; // Copyright Joyent, Inc. and other Node contributors. var stringifyPrimitive = function (v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; var encode = function (obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return Object.keys(obj).map(function (k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (Array.isArray(obj[k])) { return obj[k].map(function (v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var methods$1 = ['get', 'delete', 'head', 'options', 'post', 'put', 'patch']; var spaceChars = " \\s\xA0"; var symbolRegex = /([[\]().?/*{}+$^:])/g; function trimStart(str) { var charlist = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : spaceChars; charlist = (charlist + '').replace(symbolRegex, '$1'); var re = new RegExp("^[".concat(charlist, "]+"), 'g'); return String(str).replace(re, ''); } function trimEnd(str) { var charlist = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : spaceChars; charlist = (charlist + '').replace(symbolRegex, '\\$1'); var re = new RegExp("[".concat(charlist, "]+$"), 'g'); return String(str).replace(re, ''); } function isObject(value) { return value !== null && _typeof_1(value) === 'object'; } function isString(value) { return typeof value === 'string'; } function isFormData(value) { return typeof FormData !== 'undefined' && value instanceof FormData; } function isNode() { if (typeof global.process !== 'undefined' && /* istanbul ignore next */ global.process.versions && /* istanbul ignore next */ global.process.versions.node) { /* istanbul ignore next */ return true; } return false; } function isAbsoluteURL(url) { return /^(?:[a-z]+:)?\/\//i.test(url); } function buildURL(url, params) { if (!params) { return url; } var uris = []; foreach(params, function (value, key) { if (isObject(value)) { value = JSON.stringify(value); } uris.push("".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value))); }); url += (url.indexOf('?') === -1 ? '?' : '&') + uris.join('&'); return url; } function normalizeHeaders(headers) { var ucFirst = function ucFirst(str) { str = String(str); return str.charAt(0).toUpperCase() + str.substr(1); }; foreach(headers, function (value, key) { if (methods$1.indexOf(key) === -1) { var normalizedKey = ucFirst(key.toLowerCase().replace('_', '-').replace(/-(\w)/g, function ($0, $1) { return '-' + ucFirst($1); })); delete headers[key]; headers[normalizedKey] = value; } }); } var defaults = { baseURL: '', timeout: 0, method: 'get', headers: {}, dataType: 'auto', expectedStatus: function expectedStatus(status) { return status >= 200 && status < 400; } }; // set the default content-type of request methods foreach(['delete', 'get', 'head'], function (method) { defaults.headers[method] = {}; }); foreach(['post', 'put', 'patch'], function (method) { defaults.headers[method] = { 'Content-Type': 'application/json' }; }); var interceptors = {}; var container = []; interceptors.register = function (interceptor) { container.push(interceptor); return function () { var index = container.indexOf(interceptor); if (index >= 0) { container.splice(index, 1); } }; }; interceptors.clear = function () { container.length = 0; }; interceptors.get = function () { return container; }; function honoka(url) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options = mergeOptions(defaults, options); options.method = options.method.toLowerCase(); if (typeof url !== 'string') { throw new TypeError("Argument 1 expected string but got ".concat(_typeof_1(url))); } if (!isAbsoluteURL(url)) { url = "".concat(trimEnd(options.baseURL, '/'), "/").concat(trimStart(url, '/')); } if (options.method === 'get' && isObject(options.data)) { url = buildURL(url, options.data); } normalizeHeaders(options.headers); // Set default headers for specified methods var methodDefaultHeaders = defaults.headers[options.method]; if (isObject(methodDefaultHeaders)) { options.headers = mergeOptions(methodDefaultHeaders, options.headers); } foreach(methods$1, function (method) { return delete options.headers[method]; }); var isContentTypeString = isString(options.headers['Content-Type']); if (isContentTypeString && options.headers['Content-Type'].match(/application\/json/i)) { options.body = JSON.stringify(options.data); } else if (isContentTypeString && options.headers['Content-Type'].match(/application\/x-www-form-urlencoded/i)) { options.body = encode(options.data); } else if (options.data && options.method !== 'get' && options.method !== 'head') { options.body = options.data; } if (isFormData(options.data) || isContentTypeString && options.headers['Content-Type'].match(/multipart\/form-data/i)) { delete options.headers['Content-Type']; } // parse interceptors var reversedInterceptors = arrayReduce(interceptors.get(), function (array, interceptor) { return [interceptor].concat(toConsumableArray(array)); }, []); if (!options.ignoreInterceptors) { foreach(reversedInterceptors, function (interceptor) { if (interceptor.request) { var interceptedOptions = interceptor.request(options); if (isObject(interceptedOptions)) { options = interceptedOptions; } else { throw new Error('Apply request interceptor failed, please check your interceptor'); } } }); } return new Promise(function (resolve, reject) { if (options.timeout > 0) { setTimeout(function () { reject(new Error('Request timeout')); }, options.timeout); } fetch(url, options).then(function (response) { var clonedResponse = response.clone(); var data; switch (options.dataType.toLowerCase()) { case 'arraybuffer': data = clonedResponse.arrayBuffer(); break; case 'blob': data = clonedResponse.blob(); break; case 'json': data = clonedResponse.json(); break; case 'buffer': if (!isNode()) { reject(new Error('"buffer" is not supported in browser')); } data = clonedResponse.buffer(); break; case 'text': default: data = clonedResponse.text(); break; case '': case 'auto': data = clonedResponse.text(); break; } response.data = data; return response; }).then(function (response) { response.data.then(function (data) { var clonedResponse = response.clone(); response.data = data; if (options.dataType.toLowerCase() === '' || options.dataType.toLowerCase() === 'auto') { var contentType = response.headers.get('Content-Type'); if (contentType && contentType.match(/application\/json/i)) { response.data = JSON.parse(response.data); } } if (!options.ignoreInterceptors) { for (var i = 0; i < reversedInterceptors.length; i++) { var interceptor = reversedInterceptors[i]; if (interceptor.response) { var interceptedResponse = interceptor.response(response); if (interceptedResponse instanceof Error) { reject(interceptedResponse); break; } else if (interceptedResponse) { response = interceptedResponse; } else { reject(new Error('Apply response interceptor failed, please check your interceptor')); } } } } if (options.expectedStatus(clonedResponse.status)) { resolve(response); } else { reject(new Error("Unexpected status code: ".concat(clonedResponse.status))); } }); })["catch"](reject); }); } honoka.defaults = defaults; honoka.interceptors = interceptors; // Let's export the library version honoka.version = "0.5.2"; // Provide aliases for supported request methods foreach(methods$1, function (method) { honoka[method] = function (url) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options.method = method; return honoka(url, options); }; }); return honoka; })));