6 lines
14 KiB
JavaScript
6 lines
14 KiB
JavaScript
/**
|
|
* xe-ajax.js v4.0.5
|
|
* MIT License.
|
|
* @preserve
|
|
*/
|
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.XEAjax=e()}(this,function(){"use strict";var e="undefined",a=encodeURIComponent,r=typeof window===e&&typeof process!==e,t=typeof AbortController!==e&&typeof AbortSignal!==e,n=typeof console===e?"":console,o="";function u(t){return!!t&&t.constructor===Object}function c(t){return!!t&&t.constructor===Array}function s(t,e){for(var n=t.length-1;0<=n;n--)if(e===t[n])return n;return-1}function f(t,e,n){for(var r in t)t.hasOwnProperty(r)&&e.call(n,t[r],r,t)}function i(t){return t.origin||(r?"":o.origin||o.protocol+"//"+o.host)}r||(o=location);var y={IS_N:r,IS_F:!r&&!!self.fetch,IS_A:!(typeof Blob===e||typeof FormData===e||typeof FileReader===e),IS_FAC:t,IS_DP:Object.defineProperty&&{}.__defineGetter__,isFData:function(t){return typeof FormData!==e&&t instanceof FormData},isURLSParams:function(t){return typeof URLSearchParams!==e&&t instanceof URLSearchParams},isCrossOrigin:function(t){if(!r){var e=(""+t).match(/(\w+:)\/{2}((.*?)\/|(.*)$)/);if(e&&2<e.length)return e[1]!==o.protocol||e[2].split("/")[0]!==o.host}return!1},isStr:function(t){return"string"==typeof t},isObj:function(t){return t&&"object"==typeof t},isPlainObject:u,isFn:function(t){return"function"==typeof t},createErr:function(t){return new Error(t)},err:n.error?function(t){n.error(t)}:function(){},getOrigin:i,getBaseURL:function(t){if(t.baseURL)return t.baseURL;if(r)return"";var e=o.pathname,n=s(e,"/")+1;return i(t)+(n===e.length?e:e.substring(0,n))},objectEach:f,serialize:function(t){var n,r=[];return f(t,function(t,e){void 0!==t&&(n=c(t),u(t)||n?r=r.concat(function r(t,o,s){var i=[];return f(t,function(t,e){var n=c(t);u(t)||n?i=i.concat(r(t,o+"["+e+"]",n)):i.push(a(o+"["+(s?"":e)+"]")+"="+a(null===t?"":t))}),i}(t,e,n)):r.push(a(e)+"="+a(null===t?"":t)))}),r.join("&").replace(/%20/g,"+")},assign:Object.assign||function(t){for(var e,n=arguments,r=1,o=n.length;r<o;r++)for(var s in e=n[r])e.hasOwnProperty(s)&&(t[s]=e[s]);return t},trim:function(t){return(""+t).replace(/(^\s*)|(\s*$)/g,"")},includes:function(t,e){return-1<s(t,e)},arrayEach:function(t,e,n){for(var r=0,o=t.length;r<o;r++)e.call(n,t[r],r,t)},headersEach:function(t,e){t&&t.forEach&&t.forEach(e)}},d={method:"GET",mode:"cors",cache:"default",credentials:"same-origin",redirect:"follow",bodyType:"json-data",headers:{Accept:"application/json, text/plain, */*"}};function h(t){Object.assign(this,{autoCompute:!0,fixed:2,meanSpeed:0,onDownloadProgress:null,onUploadProgress:null},t,{_progress:{value:0,total:0,loaded:0}})}function l(t){return(""+t).toLowerCase()}function p(t,e){var n,r,o;this.$index=0,this.$list=(n=t,r=e,o=[],y.objectEach(n,function(t,e){o.push([e,t,[e,t]][r])}),o),this.next=function(){return e=(t=this).$list[this.$index],{done:r=t.$index++>=t.$list.length,value:r?n:e};var t,e,n,r}}function g(t){var n=this;n._d={},y[t instanceof m?"headersEach":"objectEach"](t,function(t,e){n.set(e,t)})}y.IS_DP&&y.arrayEach("time,speed,loaded,value,total,remaining".split(","),function(t){Object.defineProperty(h.prototype,t,{get:function(){return this._progress[t]}})});var v=g.prototype;v.set=function(t,e){this._d[l(t)]=e},v.get=function(t){var e=l(t);return this.has(e)?this._d[e]:null},v.append=function(t,e){var n=l(t),r=this._d;this.has(n)?r[n]=r[n]+", "+e:r[n]=""+e},v.has=function(t){return this._d.hasOwnProperty(l(t))},v.keys=function(){return new p(this._d,0)},v.values=function(){return new p(this._d,1)},v.entries=function(){return new p(this._d,2)},v.delete=function(t){delete this._d[l(t)]},v.forEach=function(t,e){y.objectEach(this._d,t,e)};var m="undefined"==typeof Headers?g:Headers;function b(r,t,e){this.locked=!1,this._getBody=function(){var n=this;return y.IS_DP?e._response.bodyUsed=!0:e.bodyUsed=!0,new Promise(function(t,e){n.locked?e(y.createErr("body stream already read")):(n.locked=!0,t(r))})}}function _(){this.onaborted=null,y.IS_DP?this._store={aborted:!1}:this.aborted=!1}y.IS_DP&&Object.defineProperty(_.prototype,"aborted",{get:function(){return this._store.aborted}});var P=[];function w(t){for(var e=0,n=P.length;e<n;e++)if(t===P[e][0])return e;return-1}function R(){this.signal=new _}_.prototype.install=function(t){var e=t.signal;if(e){var n=w(e);-1<n?P[n][1].push(t):P.push([e,[t]])}},R.prototype.abort=function(){var t=w(this.signal);if(-1<t){var n=P[t];y.arrayEach(n[1],function(t){var e=n[0];t.abort(),y.IS_DP?e._store.aborted=!0:e.aborted=!0}),P.splice(t,1)}};var S={resolves:[],rejects:[]},E={resolves:[],rejects:[]};function x(t,e){y.includes(t,e)||t.push(e)}function j(n){return function(t,e){t&&x(n.resolves,t),e&&x(n.rejects,e)}}function T(t,r,e){var n=Promise.resolve(e);return y.arrayEach(t,function(t){n=n.then(function(n){return new Promise(function(e){t(n,function(t){e(t&&t.body&&t.status?N.toResponse(t,r):n)},r)})}).catch(y.err)}),n}var O={interceptors:{request:{use:j(S)},response:{use:j(E)}},requests:function(t){var e=Promise.resolve(t);return y.arrayEach(S.resolves,function(n){e=e.then(function(e){return new Promise(function(t){n(e,function(){t(e)})})}).catch(y.err)}),e},toResolves:function(t,e,n,r){T(E.resolves,t,e).then(n)},toRejects:function(t,e,n,r){T(E.rejects,t,e).then(function(t){(N.isResponse(t)?n:r)(t)})}};function D(t){y.assign(this,{url:"",body:"",params:"",signal:""},t),this.headers=new m(t.headers),this.method=this.method.toLocaleUpperCase(),this.bodyType=this.bodyType.toLowerCase();var e=this.signal;e&&e.install&&e.install(this)}var A=D.prototype,I=/(\w+:)\/{2}.+/;function U(t){return 200<=t.status&&t.status<300}function F(t,e,n){this._body=t,this._request=n;var r=e.status,o=n.validateStatus||U,s=this._response={body:new b(t,n,this),bodyUsed:!1,url:n.url,status:r,statusText:e.statusText,redirected:302===r,headers:new m(e.headers||{}),type:"basic"};y.IS_DP?s.ok=o(this):(y.assign(this,s),this.ok=o(this))}A.abort=function(){this.xhr&&(this.xhr.abort(),this._noA&&this.xhr.onabort()),this.$abort=!0},A.getUrl=function(){var t,e=this.url,n=this.params,r=y.getOrigin(this),o=this.transformParams,s=y.includes(["no-store","no-cache","reload"],this.cache)?{_t:(new Date).getTime()}:{};return e?(o&&(n=this.params=o(n||{},this)),(n=!n||y.isFData(n)||y.isURLSParams(n)?y.serialize(s):y.isStr(n)?n:(this.paramsSerializer||y.serialize)(y.assign(s,n),this))&&(e+=(-1===e.indexOf("?")?"?":"&")+n),I.test(e)?e:0===e.indexOf("//")?((t=r.match(I))?t[1]:y.IS_N?"":location.protocol)+e:0===e.indexOf("/")?r+e:y.getBaseURL(this).replace(/\/$/,"")+"/"+e):e},A.getBody=function(){var t=null,e=this.body,n=this.method,r=this.transformBody,o=this.stringifyBody;if(e){if("GET"===n||"HEAD"===n)throw y.createErr("Request with GET/HEAD method cannot have body");r&&(e=this.body=r(e,this)||e),t=o?o(e,this):y.isURLSParams(e)?e.toString():y.isFData(e)||y.isStr(e)?e:"form-data"===this.bodyType?y.serialize(e):JSON.stringify(e)}return t};var C=decodeURIComponent,q=F.prototype;function B(t,n){return new Promise(function(t,e){n.onload=function(){t(n.result)},n.onerror=function(){e(n.error)}})}function L(t){return t&&t.constructor===F}function $(t){return y.isStr(t)?t:JSON.stringify(t)}function H(t,e,n){var r={status:e.status,statusText:e.statusText,headers:e.headers};return new F(t=y.IS_A?t instanceof Blob?t:new Blob([$(t)]):$(t),r,n)}y.IS_DP&&y.arrayEach("body,bodyUsed,url,headers,status,statusText,ok,redirected,type".split(","),function(t){Object.defineProperty(q,t,{get:function(){return this._response[t]}})}),q.clone=function(){if(this.bodyUsed)throw y.createErr("Failed to execute 'clone' on 'Response': Response body is already used");return new F(this._body,this,this._request)},q.json=function(){return this.text().then(function(t){return JSON.parse(t)})},q.text=function(){return this.body._getBody(this)},y.IS_A&&(q.text=function(){var r=this._request;return this.blob().then(function(t){var e=new FileReader,n=B(r,e);return e.readAsText(t),n})},q.blob=function(){return this.body._getBody(this)},q.arrayBuffer=function(){var r=this._request;return this.blob().then(function(t){var e=new FileReader,n=B(r,e);return e.readAsArrayBuffer(t),n})},q.formData=function(){return this.text().then(function(t){var o=new FormData;return y.arrayEach(y.trim(t).split("&"),function(t){if(t){var e=t.split("="),n=e.shift().replace(/\+/g," "),r=e.join("=").replace(/\+/g," ");o.append(C(n),C(r))}}),o})});var N={getResponse:H,isResponse:L,toResponse:function(e,n){return(t=e)&&"undefined"!=typeof Response&&t.constructor===Response?n.validateStatus?e.text().then(function(t){return H(t,e,n)}):Promise.resolve(e):Promise.resolve(L(e)?e:H(e.body,e,n));var t}};function k(t,e,n){var r,o,s,i,a=!1,u=t.getUrl(),c=t.timeout,f=t.credentials,d=t.$XMLHttpRequest||XMLHttpRequest,h=t.xhr=new d,l=t.progress,p=function(){try{e(N.getResponse(h[y.IS_A?"response":"responseText"],{status:h.status,statusText:h.statusText,headers:function(t){var e,n={},r=y.trim(t.getAllResponseHeaders());r&&y.arrayEach(r.split("\n"),function(t){e=t.indexOf(":"),n[y.trim(t.slice(0,e))]=y.trim(t.slice(e+1))});return n}(h)},t))}catch(t){e({status:0,body:null})}a=!0};if("same-origin"===t.mode&&y.isCrossOrigin(u))throw n(),y.createErr("Fetch API cannot load "+u+'. Request mode is "same-origin" but the URL\'s origin is not same as the request origin '+y.getOrigin(t)+".");h._request=t,void 0===h.onload?h.onreadystatechange=function(){4===h.readyState&&p()}:h.onload=p,h.ontimeout=p,h.onerror=function(){n()},t._noA=void 0===h.onabort,h.onabort=function(){a||(a=!0,n("ERR_A"))},l&&(r=l.onUploadProgress,o=l.onDownloadProgress,s=l.autoCompute,i=h.upload,r&&i&&(s?J(i,r,l):i.onprogress=r),o&&(s?J(h,o,l):h.onprogress=o)),h.open(t.method,u,!0),y.headersEach(t.headers,function(t,e){h.setRequestHeader(e,t)}),c&&(h.timeout=c),y.IS_A&&(h.responseType="blob"),"include"===f?h.withCredentials=!0:"omit"===f&&(h.withCredentials=!1),h.send(t.getBody()),t.$abort&&h.abort()}function J(t,a,u){var e=(new Date).getTime(),c=[],f=y.IS_DP?u._progress:u,d=u.meanSpeed;if(f.value=0,f.time=e,t.onprogress=function(t){var e=(new Date).getTime(),n=f.time,r=f.loaded?f.loaded.value:0,o=t.total,s=t.loaded,i=(s-r)/(e-n)*1e3;t.lengthComputable&&(f.value=Math.round(s/o*100)),f.total=X(o,u),f.loaded=X(s,u),f.speed=X(i,u),f.time=e,f.remaining=Math.ceil((o-s)/i),c.push({total:o,loaded:s,speed:i,evnt:t}),d||a(t)},d)var n,r,o,s,i,h=setInterval(function(){if(f.value<100){if(r=c.length){for(s={},o=i=0;o<r;o++)s=c[0],i+=s.speed;n=i/r,f.speed=X(n,u),f.remaining=Math.ceil((s.total-s.loaded)/n),c=[],a(s.evnt)}}else clearInterval(h)},d)}var G=["B","KB","MB","GB","TB"],z=1024,M=G.length;function X(t,e){for(var n="",r=t,o=0;o<M&&(n=G[o],z<=r);o++)r/=z;return{value:t,size:parseFloat(r.toFixed(e.fixed)),unit:n}}function K(e,n,r){var t=e.$fetch||self.fetch,o={_request:e,body:e.getBody()},s=e.signal;y.arrayEach("method,headers,signal,mode,cache,credentials,redirect,referrer,referrerPolicy,keepalive,integrity".split(","),function(t){e[t]&&(o[t]=e[t])}),s&&s.aborted?r("ERR_A"):t(e.getUrl(),o).then(function(t){N.toResponse(t,e).then(n)}).catch(function(t){r()})}var W=y.IS_N?sendHttp:y.IS_F?function(t){return function(t,e){if(!t.progress&&!t.timeout){if(t.$fetch)return e?k:K;if(y.IS_F)return y.IS_FAC?K:e?k:K}return k}(t,t.signal).apply(this,arguments)}:k,Q=0,V="undefined"==typeof window?"":window,Y=V?V.document:"";function Z(t,e,n){var r=t.script,o=Y.body;r.parentNode===o&&o.removeChild(r);try{delete V[e]}catch(t){V[e]=n}}var tt={ERR_A:"The user aborted a request",ERR_F:"Network request failed"};function et(t){var i=new D(y.assign({},d,{headers:y.assign({},d.headers)},t));return new Promise(function(e,n){var t,r,o,s;return r=(t=i).headers,o=t.body,s=t.method,o&&"GET"!==s&&"HEAD"!==s&&(y.isFData(o)||r.set("Content-Type",y.isURLSParams(o)||"form-data"===t.bodyType?"application/x-www-form-urlencoded":"application/json; charset=utf-8")),y.isCrossOrigin(t.getUrl())&&r.set("X-Requested-With","XMLHttpRequest"),O.requests(i).then(function(){(i.jsonp?function(e,n,t){var r,o,s=!1,i=e.timeout,a=e.jsonpCallback,u=clearTimeout,c=e.script=Y.createElement("script");if(a||(a=e.jsonpCallback="jsonp_xe_"+(new Date).getTime()+"_"+ ++Q),y.isFn(e.$jsonp))return e.$jsonp(c,e).then(function(t){N.toResponse({status:200,body:t},e).then(n)}).catch(function(){t()});r=e.getUrl(),V[a]=function(t){s||(u(o),Z(e,a),n({status:200,body:t}))},c.type="text/javascript",c.src=r+(-1===r.indexOf("?")?"?":"&")+e.jsonp+"="+a,c.onerror=function(){s||(u(o),Z(e,a),t())},i&&(o=setTimeout(function(){s=!0,Z(e,a),n({status:0,body:null})},i)),Y.body.appendChild(c)}:W)(i,function(t){O.toResolves(i,N.toResponse(t,i),e,n)},function(t){O.toRejects(i,y.createErr(tt[t||"ERR_F"]),e,n)})})})}function nt(t,e,n){return y.assign({method:t},e,n)}function rt(t){return function(){return et(t.apply(this,arguments))}}function ot(t,e,n,r,o){return t?{data:e,status:n,statusText:r,headers:o}:e}function st(t,s){return function(){return et(t.apply(this,arguments)).catch(function(t){return Promise.reject(ot(s,"","failed",t.message||t,{}),this)}).then(function(o){return new Promise(function(t,e){var r=o.ok?t:e;o.text().then(function(e){try{return JSON.parse(e)}catch(t){return e}}).catch(function(t){return""}).then(function(t){var e,n;r(ot(s,t,o.status,o.statusText,(e=o,n={},y.headersEach(e.headers,function(t,e){n[e]=t}),n)))})},this)})}}function it(t){return st(t,!0)}function at(t){return st(t)}function ut(n){return function(t,e){return nt(n,{url:t},e)}}function ct(r,o){return function(t,e,n){return nt(r,y.assign({url:t,params:e},o),n)}}function ft(r){return function(t,e,n){return nt(r,{url:t,body:e},n)}}et.interceptors=O.interceptors,et.serialize=y.serialize,et.Progress=h,et.AbortController=R,et.headers=m,et.request=D,et.response=F,et.use=function(t){t.install(et)},et.setup=function(t){y.assign(d,t)};var dt=ut("HEAD"),ht=ut("DELETE"),lt=ct("GET",{jsonp:"callback"}),pt=ct("GET"),yt=ft("POST"),gt=ft("PUT"),vt=ft("PATCH"),mt={doAll:function(t){return Promise.all(t.map(function(t){return t instanceof Promise?t:y.isObj(t)?et(t):t}))},ajax:et,fetch:rt(ut("GET")),fetchGet:rt(pt),fetchPost:rt(yt),fetchPut:rt(gt),fetchDelete:rt(ht),fetchPatch:rt(vt),fetchHead:rt(dt),fetchJsonp:rt(lt),doGet:it(pt),doPost:it(yt),doPut:it(gt),doDelete:it(ht),doPatch:it(vt),doHead:it(dt),doJsonp:it(lt),getJSON:at(pt),postJSON:at(yt),putJSON:at(gt),deleteJSON:at(ht),patchJSON:at(vt),headJSON:at(dt),get:at(pt),post:at(yt),put:at(gt),delete:at(ht),patch:at(vt),head:at(dt),jsonp:at(lt)};return et.mixin=function(t){y.objectEach(t,function(e,t){et[t]=y.isFn(e)?function(){var t=e.apply(et.$context,arguments);return et.$context=null,t}:e})},y.assign(et,mt),et}); |