alova
Version:
The Request Toolkit For Ultimate Efficiency
2 lines (1 loc) • 10.9 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).alova={})}(this,(function(t){"use strict";const e="undefined",a=Promise,o=t=>a.resolve(t),s=Object,n=RegExp,r=void 0,c=null,i=!0,l=!1,h=(t,e,a)=>t.then(e,a),u=(t,e)=>t.finally(e),d=(t,e,a)=>JSON.stringify(t,e,a),p=t=>s.keys(t),f=(t,e)=>t.forEach(e),m=(t,...e)=>t.push(...e),y=(t,e)=>t.map(e),g=(t,e)=>t.filter(e),w=t=>t.length,C=t=>Array.isArray(t),v=(t,e)=>delete t[e],b=t=>typeof t,S=typeof window===e&&(typeof process!==e?!process.browser:typeof Deno!==e),$="memory",k="restore",x=()=>{},E=t=>t,T=t=>"function"===b(t),D=t=>"string"===b(t),H=t=>s.prototype.toString.call(t),R=t=>"[object Object]"===H(t),U=(t,e)=>t instanceof e,j=t=>t?t.getTime():Date.now(),M=t=>t.context,O=t=>t.config,P=t=>t.options,A=t=>t.key;const q=t=>{const{cacheFor:e}=O(t),a=t=>{return"number"!==b(e=t)||Number.isNaN(e)?j(t||r):j()+t;var e};let o=$,s=()=>0,n=l,c=r;const i=T(e);if(!i){let i=e;if(R(e)){const{mode:t=$,expire:a,tag:s}=e||{};o=t,n=t===k,c=s?s.toString():r,i=a}s=e=>a(T(i)?i({method:t,mode:e}):i)}return{f:e,c:i,e:s,m:o,s:n,t:c}},N=(t,...e)=>new t(...e),F=(t,e)=>"$a."+t+e,L=t=>t.startsWith("$a."),I=(t,e,a)=>{const o=/^https?:\/\//i.test(e);o||(t=t.endsWith("/")?t.slice(0,-1):t,""!==e&&(e=e.startsWith("/")?e:`/${e}`));const s=o?e:t+e,n=D(a)?a:y(g(p(a),(t=>a[t]!==r)),(t=>`${t}=${a[t]}`)).join("&");return n?+s.includes("?")?`${s}&${n}`:`${s}?${n}`:s},B=t=>{if(C(t))return y(t,B);if(R(t)&&t.constructor===s){const e={};return f(p(t),(a=>{e[a]=B(t[a])})),e}return t};class _ extends Error{constructor(t,e,a){super(e+(a?`\n\nFor detailed: https://alova.js.org/error#${a}`:"")),this.name=`[alova${t?`/${t}`:""}]`}}const W=()=>{const t={};return{eventMap:t,on(e,a){const o=t[e]=t[e]||[];return m(o,a),()=>{t[e]=g(o,(t=>t!==a))}},off(e,a){const o=t[e];if(o)if(a){const t=o.indexOf(a);t>-1&&o.splice(t,1)}else delete t[e]},emit(e,a){const o=t[e]||[];return y(o,(t=>t(a)))}}};t.globalConfigMap={autoHitCache:"global",ssr:S};const G="color: black; font-size: 12px; font-weight: bolder";var J=(e,a,o,s)=>{const n=console,r=(...t)=>console.log(...t),{url:c}=a,i=o===k,l="[42m%s[49m",h="[32m%s[39m",u=` [HitCache]${c} `,d=()=>Array(w(u)+1).join("^");t.globalConfigMap.ssr?(r(l,u),r(h," Cache ",e),r(h," Mode ",o),i&&r(h," Tag ",s),r(h,d())):(n.groupCollapsed?n.groupCollapsed("%cHitCache","padding: 2px 6px; background: #c4fcd3; color: #53b56d;",c):r(l,u),r("%c[Cache]",G,e),r("%c[Mode]",G,o),i&&r("%c[Tag]",G,s),r("%c[Method]",G,a),n.groupEnd?n.groupEnd():r(h,d()))};const K=t=>`hss.${t}`,z="hsr.",Q=t=>z+t,V="$$hsrs",X="__$<>$__",Y=(t,e)=>{t[e]=0},Z=async(t,e,o,s,c,i,l)=>{if(s>j()&&o){const h=F(t,e);if(await c.set(h,g([o,s===1/0?r:s,l],Boolean)),i){const t={},e=[];f(i,(a=>{const o=U(a,n),s=o?a.source+(a.flags?X+a.flags:""):a;s&&(o&&!t[s]&&m(e,s),Y(t,o?Q(s):K(s)))}));const o=y(p(t),(async t=>{const e=await c.get(t)||{};Y(e,h),await c.set(t,e)})),s=async()=>{if(w(e)){const t=await c.get(V)||[];m(t,...e),await c.set(V,t)}};await a.all([...o,s()])}}},tt=async(t,e,a)=>{const o=F(t,e);await a.remove(o)},et=async(t,e,a,o)=>{const s=await a.get(F(t,e));if(s){const[n,r,c]=s;if(c===o&&(!r||r>j()))return s;await tt(t,e,a)}},at=async(t,e,a,o)=>{const s=await et(t,e,a,o);return s?s[0]:r},ot=async t=>a.all(t.map((t=>t.clear())));var st=t=>{const{data:e,config:a}=t,o={...a},{headers:n={},params:r={}}=o,c=M(t);o.headers={...n},o.params=D(r)?r:{...r};return((t,...e)=>s.assign(t,...e))(N(ut,t.type,c,t.url,o,e),{...t,config:o})};const nt="l2",rt="all",ct=async e=>{const{autoHitCache:o}=t.globalConfigMap,{l1Cache:s,l2Cache:r}=M(e),c=A(e),{name:i}=O(e),l={global:[...St,...$t],self:[s,r],close:[]}[o];l&&w(l)&&await a.all(y(l,(t=>(async(t,e,o)=>{const s=`${e}`,r={},c=K(t);let i;if(r[c]=await o.get(c),e){const t=K(s);r[t]=await o.get(t),i=await o.get(V);const e=[];i&&w(i)&&(f(i,(t=>{const[a,o]=t.split(X);N(n,a,o).test(s)&&m(e,t)})),await a.all(y(e,(async t=>{const e=Q(t);r[e]=await o.get(e)}))))}const l=async t=>{try{await o.remove(t);for(const e in r){const a=r[e];a&&v(a,t)}}catch(t){}},h={};await a.all(y(p(r),(async t=>{const e=r[t];if(e){const t=[];for(const a in e)h[a]||(Y(h,a),m(t,l(a)));await a.all(t)}})));const u=w(i||[]);await a.all(y(p(r),(async t=>{const e=r[t];e&&(w(p(e))?await o.set(t,e):(await o.remove(t),t.includes(z)&&i&&(i=g(i,(e=>Q(e)!==t)))))}))),u!==w(i||[])&&await o.set(V,i)})(c,i,t))))},it={};function lt(t,e){let o,s=i;const n=N(a,(t=>{o=t}));return{abort:()=>{h(n,(t=>t&&t.abort()))},onDownload:t=>{h(n,(e=>e&&e.onDownload&&e.onDownload(t)))},onUpload:t=>{h(n,(e=>e&&e.onUpload&&e.onUpload(t)))},response:async()=>{const{beforeRequest:n=x,responded:d,requestAdapter:p,cacheLogger:f}=(t=>P(M(t)))(t),m=A(t),{s:y,t:g,m:w,e:C}=q(t),{id:b,l1Cache:S,l2Cache:D,snapshots:j}=M(t),{cacheFor:N}=O(t),{hitSource:F}=t;let L=await(T(N)?N():e?r:at(b,m,S));if(w===k&&!L&&!e){const t=await et(b,m,D,g);if(t){const[e,a]=t;await Z(b,m,e,a,S,F),L=e}}const _=st(t);await n(_);const{baseURL:W,url:G,type:K,data:z}=_,{params:Q={},headers:V={},transform:X=E,shareRequest:Y}=O(_),tt=it[b]=it[b]||{},ot=_.data,nt=(t=>{const e=H(t);return/^\[object (Blob|FormData|ReadableStream|URLSearchParams)\]$/i.test(e)||U(t,ArrayBuffer)})(ot);let rt=nt?r:tt[m],lt=E,ht=r,ut=x;if(T(d))lt=d;else if(R(d)){const{onSuccess:t,onError:e,onComplete:a}=d;lt=T(t)?t:lt,ht=T(e)?e:ht,ut=T(a)?a:ut}if(L!==r)return o(),_.fromCache=i,(pt=J,T(dt=f)?dt:[l,c].includes(dt)?x:pt)(L,_,w,g),ut(_),L;var dt,pt;if(s=l,!Y||!rt){const t=p({url:I(W,G,Q),type:K,data:z,headers:V},_);rt=tt[m]=t}o(rt);const ft=async(e,o,s=true)=>{const n=await e,r=await X(n,o||{});j.save(t);try{await ct(_)}catch(t){}if((!ot||!nt)&&s)try{await a.all([Z(b,m,r,C($),S,F),y&&Z(b,m,r,C(k),D,F,g)])}catch(t){}return B(r)};return u(h(a.all([rt.response(),rt.headers()]),(([t,e])=>(v(tt,m),ft(lt(t,_),e))),(t=>{return v(tt,m),T(ht)?ft(ht(t,_),r,l):(e=t,a.reject(e));var e})),(()=>{ut(_)}))},fromCache:()=>s}}const ht=(t,e)=>()=>{const a=e.indexOf(t);a>=0&&e.splice(a,1)};class ut{constructor(t,e,a,s,n){this.dhs=[],this.uhs=[],this.fromCache=r;const c=()=>c.a();c.a=()=>o(),t=t.toUpperCase();const i=this,l=P(e);i.abort=c,i.baseURL=l.baseURL||"",i.url=a,i.type=t,i.context=e;const h={},u="cacheFor",d=R(l[u])?l[u][t]:r,p=s&&s.hitSource;f(["timeout","shareRequest"],(t=>{l[t]!==r&&(h[t]=l[t])})),d!==r&&(h[u]=d),p&&(i.hitSource=y(C(p)?p:[p],(t=>U(t,ut)?A(t):t)),v(s,"hitSource")),i.config={...h,headers:{},params:{},...s||{}},i.data=n,i.meta=s?s.meta:i.meta,i.key=i.generateKey()}onDownload(t){return m(this.dhs,t),ht(t,this.dhs)}onUpload(t){return m(this.uhs,t),ht(t,this.uhs)}send(t=l){const e=this,{response:a,onDownload:o,onUpload:s,abort:n,fromCache:c}=lt(e,t);w(e.dhs)>0&&o(((t,a)=>f(e.dhs,(e=>e({loaded:t,total:a}))))),w(e.uhs)>0&&s(((t,a)=>f(e.uhs,(e=>e({loaded:t,total:a})))));const{promise:i,resolve:h}=function(){let t,e;return{promise:new Promise(((a,o)=>{t=a,e=o})),resolve:t,reject:e}}();return e.abort.a=()=>(n(),i),e.fromCache=r,e.promise=a().then((t=>(e.fromCache=c(),t))).finally((()=>{((t,e=0)=>{setTimeout(t,e)})(h)})),e.promise}setName(t){O(this).name=t}generateKey(){return(t=>{const{params:e,headers:a}=O(t);return d([t.type,t.url,e,t.data,a])})(this)}then(t,e){return h(this.send(),t,e)}catch(t){return((t,e)=>t.catch(e))(this.send(),t)}finally(t){return u(this.send(),t)}}const dt=((t="")=>(e,a,o)=>{if(!e)throw N(_,t,a,o)})(),pt="success",ft=()=>{const t=W(),e=localStorage,a={set:(a,o)=>{e.setItem(a,d(o)),t.emit(pt,{type:"set",key:a,value:o,container:e})},get:a=>{const o=e.getItem(a),s=o?(t=>JSON.parse(t))(o):o;return t.emit(pt,{type:"get",key:a,value:s,container:e}),s},remove:a=>{e.removeItem(a),t.emit(pt,{type:"remove",key:a,container:e})},clear:()=>{for(let t=e.length-1;t>=0;t-=1){const a=e.key(t);a&&L(a)&&e.removeItem(a)}t.emit(pt,{type:"clear",key:"",container:e})},emitter:t};return a},mt=Set;class yt{constructor(t){this.records={},this.occupy=0,dt(t>=0,"expected snapshots limit to be >= 0"),this.capacity=t}save(t){const{name:e}=O(t),{records:a,occupy:o,capacity:s}=this;if(e&&o<s){(a[e]=a[e]||N(mt)).add(t),this.occupy+=1}}match(t,e=!0){let a,o,s,r=t;R(t)&&(r=t.name,s=t.filter),U(r,n)?o=r:D(r)&&(a=r);const{records:c}=this;let i=N(mt);a?i=c[a]||i:o&&f(g(p(c),(t=>o.test(t))),(t=>{c[t].forEach((t=>i.add(t)))}));const l=T(s)?g([...i],s):[...i];return e?l:l[0]}}const gt="GET",wt={cacheFor:{[gt]:3e5},shareRequest:i,snapshots:1e3};let Ct=0;class vt{constructor(t){var e,a;const o=this;o.id=(t.id||(Ct+=1)).toString(),o.l1Cache=t.l1Cache||(()=>{let t={};const e=W(),a={set(a,o){t[a]=o,e.emit(pt,{type:"set",key:a,value:o,container:t})},get:a=>{const o=t[a];return e.emit(pt,{type:"get",key:a,value:o,container:t}),o},remove(a){v(t,a),e.emit(pt,{type:"remove",key:a,container:t})},clear:()=>{t={},e.emit(pt,{type:"clear",key:"",container:t})},emitter:e};return a})(),o.l2Cache=t.l2Cache||("undefined"!=typeof localStorage?ft():(()=>{const t=()=>{dt(l,"l2Cache is not defined.")};return{set:()=>{t()},get:()=>(t(),r),remove:()=>{t()},clear:()=>{}}})()),o.options={...wt,...t},o.snapshots=N(yt,null!==(a=null!==(e=t.snapshots)&&void 0!==e?e:wt.snapshots)&&void 0!==a?a:0)}Request(t){return N(ut,t.method||gt,this,t.url,t,t.data)}Get(t,e){return N(ut,gt,this,t,e)}Post(t,e,a){return N(ut,"POST",this,t,a,e)}Delete(t,e,a){return N(ut,"DELETE",this,t,a,e)}Put(t,e,a){return N(ut,"PUT",this,t,a,e)}Head(t,e){return N(ut,"HEAD",this,t,e)}Patch(t,e,a){return N(ut,"PATCH",this,t,a,e)}Options(t,e){return N(ut,"OPTIONS",this,t,e)}}let bt=r;const St=[],$t=[];t.Method=ut,t.createAlova=t=>{const e=N(vt,t),a=e.options.statesHook;bt&&a&&dt(bt.name===a.name,"expected to use the same `statesHook`"),bt=a;const{l1Cache:o,l2Cache:s}=e;return!St.includes(o)&&m(St,o),!$t.includes(s)&&m($t,s),e},t.globalConfig=e=>{t.globalConfigMap={...t.globalConfigMap,...e}},t.hitCacheBySource=ct,t.invalidateCache=async t=>{if(!t)return void await a.all([ot(St),ot($t)]);const e=(C(t)?t:[t]).map((t=>{const{id:e,l1Cache:s,l2Cache:n}=M(t),{c:r,m:c}=q(t);if(r)return;const i=A(t);return a.all([tt(e,i,s),c===k?tt(e,i,n):o()])}));await a.all(e)},t.promiseStatesHook=()=>(dt(bt,"`statesHook` is not set in alova instance"),bt),t.queryCache=async(t,{policy:e=rt}={})=>{if(t&&t.key){const{id:a,l1Cache:o,l2Cache:s}=M(t),n=A(t),{f:c,c:i,s:l,e:h,t:u}=q(t);if(i)return c();let d=e!==nt?await at(a,n,o):r;return e===nt?d=await at(a,n,s,u):e!==rt||d||l&&h(k)>j()&&(d=await at(a,n,s,u)),d}},t.setCache=async(t,e,{policy:o=rt}={})=>{const s=(C(t)?t:[t]).map((async t=>{const{hitSource:s}=t,{id:n,l1Cache:c,l2Cache:i}=M(t),l=A(t),{e:h,s:u,t:d,c:p}=q(t);if(p)return;let f=e;if(T(e)){let t=o!==nt?await at(n,l,c):r;if((o===nt||o===rt&&!t&&u&&h(k)>j())&&(t=await at(n,l,i,d)),f=e(t),f===r)return}return a.all([o!==nt&&Z(n,l,f,h($),c,s),o===nt||o===rt&&u?Z(n,l,f,h(k),i,s,d):r])}));return a.all(s)}}));