honoka
Version:
Just a fetch() API wrapper for both Browser and Node.js.
9 lines (7 loc) • 15.5 kB
JavaScript
/**
* honoka v0.5.2
* (c) 2020 kokororin
* Released under the MIT License.
* https://github.com/kokororin/honoka#readme
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).honoka=e()}(this,(function(){"use strict";var t="URLSearchParams"in self,e="Symbol"in self&&"iterator"in Symbol,r="FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(t){return!1}}(),n="FormData"in self,o="ArrayBuffer"in self;if(o)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=ArrayBuffer.isView||function(t){return t&&i.indexOf(Object.prototype.toString.call(t))>-1};function s(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function c(t){return"string"!=typeof t&&(t=String(t)),t}function u(t){var r={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return e&&(r[Symbol.iterator]=function(){return r}),r}function f(t){this.map={},t instanceof f?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function p(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function d(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function l(t){var e=new FileReader,r=d(e);return e.readAsArrayBuffer(t),r}function h(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function y(){return this.bodyUsed=!1,this._initBody=function(e){var i;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:r&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:n&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:t&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o&&r&&((i=e)&&DataView.prototype.isPrototypeOf(i))?(this._bodyArrayBuffer=h(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o&&(ArrayBuffer.prototype.isPrototypeOf(e)||a(e))?this._bodyArrayBuffer=h(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r&&(this.blob=function(){var t=p(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(l)}),this.text=function(){var t,e,r,n=p(this);if(n)return n;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,r=d(e),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},n&&(this.formData=function(){return this.text().then(v)}),this.json=function(){return this.text().then(JSON.parse)},this}f.prototype.append=function(t,e){t=s(t),e=c(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},f.prototype.delete=function(t){delete this.map[s(t)]},f.prototype.get=function(t){return t=s(t),this.has(t)?this.map[t]:null},f.prototype.has=function(t){return this.map.hasOwnProperty(s(t))},f.prototype.set=function(t,e){this.map[s(t)]=c(e)},f.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},f.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),u(t)},f.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),u(t)},f.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),u(t)},e&&(f.prototype[Symbol.iterator]=f.prototype.entries);var b=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function m(t,e){var r,n,o=(e=e||{}).body;if(t instanceof m){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new f(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new f(e.headers)),this.method=(r=e.method||this.method||"GET",n=r.toUpperCase(),b.indexOf(n)>-1?n:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function v(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}})),e}function g(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new f(e.headers),this.url=e.url||"",this._initBody(t)}m.prototype.clone=function(){return new m(this,{body:this._bodyInit})},y.call(m.prototype),y.call(g.prototype),g.prototype.clone=function(){return new g(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},g.error=function(){var t=new g(null,{status:0,statusText:""});return t.type="error",t};var w=[301,302,303,307,308];g.redirect=function(t,e){if(-1===w.indexOf(e))throw new RangeError("Invalid status code");return new g(null,{status:e,headers:{location:t}})};var A=self.DOMException;try{new A}catch(t){(A=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack}).prototype=Object.create(Error.prototype),A.prototype.constructor=A}function O(t,e){return new Promise((function(n,o){var i=new m(t,e);if(i.signal&&i.signal.aborted)return o(new A("Aborted","AbortError"));var a=new XMLHttpRequest;function s(){a.abort()}a.onload=function(){var t,e,r={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new f,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}})),e)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var o="response"in a?a.response:a.responseText;n(new g(o,r))},a.onerror=function(){o(new TypeError("Network request failed"))},a.ontimeout=function(){o(new TypeError("Network request failed"))},a.onabort=function(){o(new A("Aborted","AbortError"))},a.open(i.method,i.url,!0),"include"===i.credentials?a.withCredentials=!0:"omit"===i.credentials&&(a.withCredentials=!1),"responseType"in a&&r&&(a.responseType="blob"),i.headers.forEach((function(t,e){a.setRequestHeader(e,t)})),i.signal&&(i.signal.addEventListener("abort",s),a.onreadystatechange=function(){4===a.readyState&&i.signal.removeEventListener("abort",s)}),a.send(void 0===i._bodyInit?null:i._bodyInit)}))}O.polyfill=!0,self.fetch||(self.fetch=O,self.Headers=f,self.Request=m,self.Response=g);var E=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n};var j=function(t){if(Array.isArray(t))return E(t)};var T=function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)};var x=function(t,e){if(t){if("string"==typeof t)return E(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(r):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?E(t,e):void 0}};var _=function(){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 S=function(t){return j(t)||T(t)||x(t)||_()},U="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var P=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){function e(r){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?t.exports=e=function(t){return typeof t}:t.exports=e=function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(r)}t.exports=e})),B=Object.prototype.hasOwnProperty,C=Object.prototype.toString,R=function(t,e,r){if("[object Function]"!==C.call(e))throw new TypeError("iterator must be a function");var n=t.length;if(n===+n)for(var o=0;o<n;o++)e.call(r,t[o],o,t);else for(var i in t)B.call(t,i)&&e.call(r,t[i],i,t)},I=Object.prototype.hasOwnProperty,F=function(t,e,r){var n=arguments.length>=3;if(n&&t.reduce)return t.reduce(e,r);if(t.reduce)return t.reduce(e);for(var o=0;o<t.length;o++)I.call(t,o)&&(n?r=e(r,t[o],o):(r=t[o],n=!0));return r},L=t=>{if("[object Object]"!==Object.prototype.toString.call(t))return!1;const e=Object.getPrototypeOf(t);return null===e||e===Object.prototype};const{hasOwnProperty:D}=Object.prototype,{propertyIsEnumerable:k}=Object,q=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),N=U,H={concatArrays:!1,ignoreUndefined:!1},$=t=>{const e=[];for(const r in t)D.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(t);for(const n of r)k.call(t,n)&&e.push(n)}return e};function G(t){return Array.isArray(t)?function(t){const e=t.slice(0,0);return $(t).forEach(r=>{q(e,r,G(t[r]))}),e}(t):L(t)?function(t){const e=null===Object.getPrototypeOf(t)?Object.create(null):{};return $(t).forEach(r=>{q(e,r,G(t[r]))}),e}(t):t}const J=(t,e,r,n)=>(r.forEach(r=>{void 0===e[r]&&n.ignoreUndefined||(r in t&&t[r]!==Object.getPrototypeOf(t)?q(t,r,M(t[r],e[r],n)):q(t,r,G(e[r])))}),t);function M(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?((t,e,r)=>{let n=t.slice(0,0),o=0;return[t,e].forEach(e=>{const i=[];for(let r=0;r<e.length;r++)D.call(e,r)&&(i.push(String(r)),q(n,o++,e===t?e[r]:G(e[r])));n=J(n,e,$(e).filter(t=>!i.includes(t)),r)}),n})(t,e,r):L(e)&&L(t)?J(t,e,$(e),r):G(e)}var z=function(...t){const e=M(G(H),this!==N&&this||{},H);let r={_:{}};for(const n of t)if(void 0!==n){if(!L(n))throw new TypeError("`"+n+"` is not an Option Object");r=M(r,{_:n},e)}return r._},V=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}},X=function(t,e,r,n){return e=e||"&",r=r||"=",null===t&&(t=void 0),"object"==typeof t?Object.keys(t).map((function(n){var o=encodeURIComponent(V(n))+r;return Array.isArray(t[n])?t[n].map((function(t){return o+encodeURIComponent(V(t))})).join(e):o+encodeURIComponent(V(t[n]))})).join(e):n?encodeURIComponent(V(n))+r+encodeURIComponent(V(t)):""},K=["get","delete","head","options","post","put","patch"],Q=/([[\]().?/*{}+$^:])/g;function W(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:" \\s ";e=(e+"").replace(Q,"$1");var r=new RegExp("^[".concat(e,"]+"),"g");return String(t).replace(r,"")}function Y(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:" \\s ";e=(e+"").replace(Q,"\\$1");var r=new RegExp("[".concat(e,"]+$"),"g");return String(t).replace(r,"")}function Z(t){return null!==t&&"object"===P(t)}function tt(t){return"string"==typeof t}function et(t){return"undefined"!=typeof FormData&&t instanceof FormData}function rt(){return!(void 0===global.process||!global.process.versions||!global.process.versions.node)}function nt(t){return/^(?:[a-z]+:)?\/\//i.test(t)}function ot(t,e){if(!e)return t;var r=[];return R(e,(function(t,e){Z(t)&&(t=JSON.stringify(t)),r.push("".concat(encodeURIComponent(e),"=").concat(encodeURIComponent(t)))})),t+=(-1===t.indexOf("?")?"?":"&")+r.join("&")}function it(t){var e=function(t){return(t=String(t)).charAt(0).toUpperCase()+t.substr(1)};R(t,(function(r,n){if(-1===K.indexOf(n)){var o=e(n.toLowerCase().replace("_","-").replace(/-(\w)/g,(function(t,r){return"-"+e(r)})));delete t[n],t[o]=r}}))}var at={baseURL:"",timeout:0,method:"get",headers:{},dataType:"auto",expectedStatus:function(t){return t>=200&&t<400}};R(["delete","get","head"],(function(t){at.headers[t]={}})),R(["post","put","patch"],(function(t){at.headers[t]={"Content-Type":"application/json"}}));var st={},ct=[];function ut(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((e=z(at,e)).method=e.method.toLowerCase(),"string"!=typeof t)throw new TypeError("Argument 1 expected string but got ".concat(P(t)));nt(t)||(t="".concat(Y(e.baseURL,"/"),"/").concat(W(t,"/"))),"get"===e.method&&Z(e.data)&&(t=ot(t,e.data)),it(e.headers);var r=at.headers[e.method];Z(r)&&(e.headers=z(r,e.headers)),R(K,(function(t){return delete e.headers[t]}));var n=tt(e.headers["Content-Type"]);n&&e.headers["Content-Type"].match(/application\/json/i)?e.body=JSON.stringify(e.data):n&&e.headers["Content-Type"].match(/application\/x-www-form-urlencoded/i)?e.body=X(e.data):e.data&&"get"!==e.method&&"head"!==e.method&&(e.body=e.data),(et(e.data)||n&&e.headers["Content-Type"].match(/multipart\/form-data/i))&&delete e.headers["Content-Type"];var o=F(st.get(),(function(t,e){return[e].concat(S(t))}),[]);return e.ignoreInterceptors||R(o,(function(t){if(t.request){var r=t.request(e);if(!Z(r))throw new Error("Apply request interceptor failed, please check your interceptor");e=r}})),new Promise((function(r,n){e.timeout>0&&setTimeout((function(){n(new Error("Request timeout"))}),e.timeout),fetch(t,e).then((function(t){var r,o=t.clone();switch(e.dataType.toLowerCase()){case"arraybuffer":r=o.arrayBuffer();break;case"blob":r=o.blob();break;case"json":r=o.json();break;case"buffer":rt()||n(new Error('"buffer" is not supported in browser')),r=o.buffer();break;case"text":default:r=o.text();break;case"":case"auto":r=o.text()}return t.data=r,t})).then((function(t){t.data.then((function(i){var a=t.clone();if(t.data=i,""===e.dataType.toLowerCase()||"auto"===e.dataType.toLowerCase()){var s=t.headers.get("Content-Type");s&&s.match(/application\/json/i)&&(t.data=JSON.parse(t.data))}if(!e.ignoreInterceptors)for(var c=0;c<o.length;c++){var u=o[c];if(u.response){var f=u.response(t);if(f instanceof Error){n(f);break}f?t=f:n(new Error("Apply response interceptor failed, please check your interceptor"))}}e.expectedStatus(a.status)?r(t):n(new Error("Unexpected status code: ".concat(a.status)))}))})).catch(n)}))}return st.register=function(t){return ct.push(t),function(){var e=ct.indexOf(t);e>=0&&ct.splice(e,1)}},st.clear=function(){ct.length=0},st.get=function(){return ct},ut.defaults=at,ut.interceptors=st,ut.version="0.5.2",R(K,(function(t){ut[t]=function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return r.method=t,ut(e,r)}})),ut}));