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