solid-request
Version:
solid-js use-request hooks library
2 lines (1 loc) • 14.7 kB
JavaScript
var Solid_request=function($){"use strict";const L={equals:(e,t)=>e===t};let se=fe;const P=1,D=2,je={owned:null,cleanups:null,context:null,owner:null};var v=null;let O=null,b=null,m=null,w=null,B=0;function E(e,t){t=t?Object.assign({},L,t):L;const n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0},r=i=>(typeof i=="function"&&(i=i(n.value)),le(n,i));return[ae.bind(n),r]}function T(e,t,n){se=_e;const r=ce(e,t,!1,P),i=ue&&he(v,ue.id);i&&(r.suspense=i),r.user=!0,w?w.push(r):M(r)}function R(e,t,n){n=n?Object.assign({},L,n):L;const r=ce(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,M(r),ae.bind(r)}function z(e){if(b===null)return e();const t=b;b=null;try{return e()}finally{b=t}}function oe(e,t,n){const r=Array.isArray(e);let i,s=n&&n.defer;return o=>{let u;if(r){u=Array(e.length);for(let c=0;c<e.length;c++)u[c]=e[c]()}else u=e();if(s){s=!1;return}const l=z(()=>t(u,i,o));return i=u,l}}function J(e){T(()=>z(e))}function x(e){return v===null||(v.cleanups===null?v.cleanups=[e]:v.cleanups.push(e)),e}let ue;function ae(){const e=O;if(this.sources&&(this.state||e))if(this.state===P||e)M(this);else{const t=m;m=null,q(()=>G(this),!1),m=t}if(b){const t=this.observers?this.observers.length:0;b.sources?(b.sources.push(this),b.sourceSlots.push(t)):(b.sources=[this],b.sourceSlots=[t]),this.observers?(this.observers.push(b),this.observerSlots.push(b.sources.length-1)):(this.observers=[b],this.observerSlots=[b.sources.length-1])}return this.value}function le(e,t,n){let r=e.value;return(!e.comparator||!e.comparator(r,t))&&(e.value=t,e.observers&&e.observers.length&&q(()=>{for(let i=0;i<e.observers.length;i+=1){const s=e.observers[i],o=O&&O.running;o&&O.disposed.has(s),(o&&!s.tState||!o&&!s.state)&&(s.pure?m.push(s):w.push(s),s.observers&&de(s)),o||(s.state=P)}if(m.length>1e6)throw m=[],new Error},!1)),t}function M(e){if(!e.fn)return;Y(e);const t=v,n=b,r=B;b=v=e,$e(e,e.value,r),b=n,v=t}function $e(e,t,n){let r;try{r=e.fn(t)}catch(i){return e.pure&&(e.state=P,e.owned&&e.owned.forEach(Y),e.owned=null),e.updatedAt=n+1,ge(i)}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?le(e,r):e.value=r,e.updatedAt=n)}function ce(e,t,n,r=P,i){const s={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:v,context:null,pure:n};return v===null||v!==je&&(v.owned?v.owned.push(s):v.owned=[s]),s}function H(e){const t=O;if(e.state===0||t)return;if(e.state===D||t)return G(e);if(e.suspense&&z(e.suspense.inFallback))return e.suspense.effects.push(e);const n=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<B);)(e.state||t)&&n.push(e);for(let r=n.length-1;r>=0;r--)if(e=n[r],e.state===P||t)M(e);else if(e.state===D||t){const i=m;m=null,q(()=>G(e,n[0]),!1),m=i}}function q(e,t){if(m)return e();let n=!1;t||(m=[]),w?n=!0:w=[],B++;try{const r=e();return xe(n),r}catch(r){n||(w=null),m=null,ge(r)}}function xe(e){if(m&&(fe(m),m=null),e)return;const t=w;w=null,t.length&&q(()=>se(t),!1)}function fe(e){for(let t=0;t<e.length;t++)H(e[t])}function _e(e){let t,n=0;for(t=0;t<e.length;t++){const r=e[t];r.user?e[n++]=r:H(r)}for(t=0;t<n;t++)H(e[t])}function G(e,t){const n=O;e.state=0;for(let r=0;r<e.sources.length;r+=1){const i=e.sources[r];i.sources&&(i.state===P||n?i!==t&&(!i.updatedAt||i.updatedAt<B)&&H(i):(i.state===D||n)&&G(i,t))}}function de(e){const t=O;for(let n=0;n<e.observers.length;n+=1){const r=e.observers[n];(!r.state||t)&&(r.state=D,r.pure?m.push(r):w.push(r),r.observers&&de(r))}}function Y(e){let t;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),r=e.sourceSlots.pop(),i=n.observers;if(i&&i.length){const s=i.pop(),o=n.observerSlots.pop();r<i.length&&(s.sourceSlots[o]=r,i[r]=s,n.observerSlots[r]=o)}}if(e.owned){for(t=0;t<e.owned.length;t++)Y(e.owned[t]);e.owned=null}if(e.cleanups){for(t=0;t<e.cleanups.length;t++)e.cleanups[t]();e.cleanups=null}e.state=0,e.context=null}function Ce(e){return e instanceof Error||typeof e=="string"?e:new Error("Unknown error")}function ge(e){throw e=Ce(e),e}function he(e,t){return e?e.context&&e.context[t]!==void 0?e.context[t]:he(e.owner,t):void 0}function Ue(e){return typeof e=="function"}function d(e){return Ue(e)?e():e}const be=(e,{manual:t,ready:n=!0,refreshDeps:r=[],refreshDepsAction:i})=>{const[s,o]=E(!1);return T(()=>{t||o(d(n))}),r instanceof Array?T(oe([s,...r],([u])=>{u&&!t&&u&&(i?i():e.refresh())})):T(oe(s,u=>{!t&&u&&(i?i():e.refresh())})),{onBefore:()=>{if(!d(n))return{stopNow:!0}}}};be.onInit=({ready:e=!0,manual:t})=>({loading:!t&&d(e)});const j=new Map,Fe=(e,t,n)=>{const r=j.get(e);r?.timer&&clearTimeout(r.timer);let i;t>-1&&(i=setTimeout(()=>{j.delete(e)},t)),j.set(e,{...n,timer:i})},Ne=e=>j.get(e),Le=e=>{e?(Array.isArray(e)?e:[e]).forEach(n=>j.delete(n)):j.clear()},I=new Map,De=e=>I.get(e),Be=(e,t)=>{I.set(e,t),t.then(n=>(I.delete(e),n)).catch(n=>{throw I.delete(e),n})},A={},Me=(e,t)=>{A[e]&&A[e].forEach(n=>n(t))},Z=(e,t)=>(A[e]||(A[e]=[]),A[e].push(t),function(){const r=A[e].indexOf(t);A[e].splice(r,1)}),He=(e,{cacheKey:t,cacheTime:n=5*60*1e3,staleTime:r=0,setCache:i,getCache:s})=>{let o,u;const l=(a,f)=>{i?i(f):Fe(a,n,f),Me(a,f.data)},c=(a,f=[])=>s?s(f):Ne(a);return T(()=>{if(!t)return;const a=c(t);a&&Object.hasOwnProperty.call(a,"data")&&(e.state.data=a.data,e.state.params=a.params,(r===-1||new Date().getTime()-a.time<=r)&&(e.state.loading=!1)),o=Z(t,f=>{e.setState({data:f})})}),J(()=>{x(()=>{o?.()})}),t?{onBefore:a=>{const f=c(t,a);return!f||!Object.hasOwnProperty.call(f,"data")?{}:r===-1||new Date().getTime()-f.time<=r?{loading:!1,data:f?.data,returnNow:!0}:{data:f?.data}},onRequest:(a,f)=>{let p=De(t);return p&&p!==u?{servicePromise:p}:(p=a(...f),u=p,Be(t,p),{servicePromise:p})},onSuccess:(a,f)=>{t&&(o?.(),l(t,{data:a,params:f,time:new Date().getTime()}),o=Z(t,p=>{e.setState({data:p})}))},onMutate:a=>{t&&(o?.(),l(t,{data:a,params:e.state.params,time:new Date().getTime()}),o=Z(t,f=>{e.setState({data:f})}))}}:{}};var W=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qe(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var k=qe,Ge=typeof W=="object"&&W&&W.Object===Object&&W,Ie=Ge,We=Ie,Ve=typeof self=="object"&&self&&self.Object===Object&&self,Xe=We||Ve||Function("return this")(),me=Xe,Qe=me,ze=function(){return Qe.Date.now()},Je=ze,Ye=/\s/;function Ze(e){for(var t=e.length;t--&&Ye.test(e.charAt(t)););return t}var ke=Ze,Ke=ke,et=/^\s+/;function tt(e){return e&&e.slice(0,Ke(e)+1).replace(et,"")}var nt=tt,rt=me,it=rt.Symbol,pe=it,ve=pe,Se=Object.prototype,st=Se.hasOwnProperty,ot=Se.toString,_=ve?ve.toStringTag:void 0;function ut(e){var t=st.call(e,_),n=e[_];try{e[_]=void 0;var r=!0}catch{}var i=ot.call(e);return r&&(t?e[_]=n:delete e[_]),i}var at=ut,lt=Object.prototype,ct=lt.toString;function ft(e){return ct.call(e)}var dt=ft,we=pe,gt=at,ht=dt,bt="[object Null]",mt="[object Undefined]",Te=we?we.toStringTag:void 0;function pt(e){return e==null?e===void 0?mt:bt:Te&&Te in Object(e)?gt(e):ht(e)}var vt=pt;function St(e){return e!=null&&typeof e=="object"}var wt=St,Tt=vt,yt=wt,Pt="[object Symbol]";function Ot(e){return typeof e=="symbol"||yt(e)&&Tt(e)==Pt}var Rt=Ot,At=nt,ye=k,Et=Rt,Pe=0/0,jt=/^[-+]0x[0-9a-f]+$/i,$t=/^0b[01]+$/i,xt=/^0o[0-7]+$/i,_t=parseInt;function Ct(e){if(typeof e=="number")return e;if(Et(e))return Pe;if(ye(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=ye(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=At(e);var n=$t.test(e);return n||xt.test(e)?_t(e.slice(2),n?2:8):jt.test(e)?Pe:+e}var Ut=Ct,Ft=k,K=Je,Oe=Ut,Nt="Expected a function",Lt=Math.max,Dt=Math.min;function Bt(e,t,n){var r,i,s,o,u,l,c=0,a=!1,f=!1,p=!0;if(typeof e!="function")throw new TypeError(Nt);t=Oe(t)||0,Ft(n)&&(a=!!n.leading,f="maxWait"in n,s=f?Lt(Oe(n.maxWait)||0,t):s,p="trailing"in n?!!n.trailing:p);function F(h){var y=r,N=i;return r=i=void 0,c=h,o=e.apply(N,y),o}function te(h){return c=h,u=setTimeout(g,t),a?F(h):o}function ne(h){var y=h-l,N=h-c,Ee=t-y;return f?Dt(Ee,s-N):Ee}function X(h){var y=h-l,N=h-c;return l===void 0||y>=t||y<0||f&&N>=s}function g(){var h=K();if(X(h))return S(h);u=setTimeout(g,ne(h))}function S(h){return u=void 0,p&&r?F(h):(r=i=void 0,o)}function Q(){u!==void 0&&clearTimeout(u),c=0,r=l=i=u=void 0}function re(){return u===void 0?o:S(K())}function ie(){var h=K(),y=X(h);if(r=arguments,i=this,l=h,y){if(u===void 0)return te(l);if(f)return clearTimeout(u),u=setTimeout(g,t),F(l)}return u===void 0&&(u=setTimeout(g,t)),o}return ie.cancel=Q,ie.flush=re,ie}var Re=Bt;const Mt=(e,{debounceWait:t,debounceLeading:n,debounceTrailing:r,debounceMaxWait:i})=>{const[s,o]=E(),u=R(()=>{const l={},c=d(n),a=d(r),f=d(i);return c!==void 0&&(l.leading=c),a!==void 0&&(l.trailing=a),f!==void 0&&(l.maxWait=f),l});return T(()=>{if(d(t)){const l=e.runAsync.bind(e);o(()=>Re(c=>{c()},d(t),u())),e.runAsync=(...c)=>new Promise((a,f)=>{s()?.(()=>{l(...c).then(a).catch(f)})}),x(()=>{s()?.cancel(),e.runAsync=l})}}),d(t)?{onCancel:()=>{s()?.cancel()}}:{}},Ht=(e,{loadingDelay:t})=>{let n;if(!d(t))return{};const r=()=>{n&&clearTimeout(n)};return{onBefore:()=>(r(),n=setTimeout(()=>{e.setState({loading:!0})},d(t)),{loading:!1}),onFinally:()=>{r()},onCancel:()=>{r()}}};function V(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}function ee(){return V()?document.visibilityState!=="hidden":!0}const C=[];function qt(e){return C.push(e),function(){const n=C.indexOf(e);C.splice(n,1)}}if(V()){const e=()=>{if(ee())for(let t=0;t<C.length;t++){const n=C[t];n()}};window.addEventListener("visibilitychange",e,!1)}const Gt=(e,{pollingInterval:t,pollingWhenHidden:n=!0,pollingErrorRetryCount:r=-1})=>{let i,s;const[o,u]=E(0),l=()=>{i&&clearInterval(i),s?.()};return T(()=>{d(t)||l()}),d(t)?{onBefore:()=>{l()},onError:()=>{u(c=>c+1)},onSuccess:()=>{u(()=>0)},onFinally:()=>{r===-1||r!==-1&&o()<=r?i=setTimeout(()=>{!n&&!ee()?s=qt(()=>{e.refresh()}):e.refresh()},d(t)):u(()=>0)},onCancel:()=>{l()}}:{}};function It(e,t){let n=!1;return(...r)=>{n||(n=!0,e(...r),setTimeout(()=>{n=!1},t))}}function Wt(){return V()&&typeof navigator.onLine<"u"?navigator.onLine:!0}const U=[];function Vt(e){return U.push(e),function(){const n=U.indexOf(e);U.splice(n,1)}}if(V()){const e=()=>{if(!(!ee()||!Wt()))for(let t=0;t<U.length;t++){const n=U[t];n()}};window.addEventListener("visibilitychange",e,!1),window.addEventListener("focus",e,!1)}const Xt=(e,{refreshOnWindowFocus:t,focusTimespan:n=5e3})=>{let r;const i=()=>{r?.()};return T(()=>{if(d(t)){const s=It(e.refresh.bind(e),d(n));r=Vt(()=>{s()})}x(()=>{i()})}),J(()=>{x(()=>{i()})}),{}},Qt=(e,{retryInterval:t,retryCount:n})=>{let r;const[i,s]=E(0),[o,u]=E(!1);return n?{onBefore:()=>{o()||s(()=>0),u(()=>!1),r&&clearTimeout(r)},onSuccess:()=>{s(()=>0)},onError:()=>{if(s(l=>l+1),n===-1||i()<=n){const l=t??Math.min(1e3*2**i(),3e4);r=setTimeout(()=>{u(()=>!0),e.refresh()},l)}else s(()=>0)},onCancel:()=>{s(()=>0),r&&clearTimeout(r)}}:{}};var zt=Re,Jt=k,Yt="Expected a function";function Zt(e,t,n){var r=!0,i=!0;if(typeof e!="function")throw new TypeError(Yt);return Jt(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),zt(e,t,{leading:r,maxWait:t,trailing:i})}var kt=Zt;const Kt=(e,{throttleWait:t,throttleLeading:n,throttleTrailing:r})=>{const i=R(()=>{const o={};return d(n)!==void 0&&(o.leading=d(n)),d(r)!==void 0&&(o.trailing=d(r)),o}),s=R(()=>kt(o=>{o()},d(t),i()));return T(()=>{if(d(t)){const o=e.runAsync.bind(e);e.runAsync=(...u)=>new Promise((l,c)=>{s()?.(()=>{o(...u).then(l).catch(c)})}),x(()=>{e.runAsync=o,s()?.cancel()})}}),d(t)?{onCancel:()=>{s()?.cancel()}}:{}};class en{constructor(t,n,r,i={}){this.serviceRef=t,this.options=n,this.setUpdateData=r,this.initState=i,this.state={...this.state,loading:!n.manual,...i}}pluginImpls;count=0;servicePreset;state={loading:!1,params:void 0,data:void 0,error:void 0};setState(t={}){this.state={...this.state,...t},this.setUpdateData(this.state)}setData(t,n){n instanceof Array?n.forEach(r=>{this.state[r]=t,this.setUpdateData(t,r)}):(this.state[n]=t,this.setUpdateData(t,n))}runPluginHandler(t,...n){const r=(this.pluginImpls?.map(i=>i[t]?.(...n))??[])?.filter(Boolean);return Object.assign({},...r)}setServicePreset(t){t?this.servicePreset=t:this.servicePreset=null}async runAsync(...t){this.count+=1;const n=this.count,{stopNow:r=!1,returnNow:i=!1,...s}=this.runPluginHandler("onBefore",t);if(r)return new Promise(()=>{});if(this.setState({loading:!0,params:t,...s}),i)return Promise.resolve(s.data);this.options.onBefore?.(t);try{let{servicePromise:o}=this.runPluginHandler("onRequest",this.serviceRef,t);const u=c=>{if(n!==this.count)return new Promise(()=>{});const a=this.options.formatResult?this.options.formatResult(c):c;return this.setState({data:a,error:void 0,loading:!1}),this.options.onSuccess?.(a,t),this.runPluginHandler("onSuccess",a,t),this.options.onFinally?.(t,a,void 0),n===this.count&&this.runPluginHandler("onFinally",t,a,void 0),this.setServicePreset(null),a};o||(o=this.servicePreset??this.serviceRef(...t));const l=await o;return u(l)}catch(o){if(n!==this.count)return new Promise(()=>{});throw this.setState({error:o,loading:!1}),this.options.onError?.(o,t),this.runPluginHandler("onError",o,t),this.options.onFinally?.(t,void 0,o),n===this.count&&this.runPluginHandler("onFinally",t,void 0,o),o}}run(...t){this.runAsync(...t).catch(n=>{this.options.onError||console.error(n)})}cancel(){this.count+=1,this.setState({loading:!1}),this.runPluginHandler("onCancel")}refresh(){this.run(...this.state.params||[])}refreshAsync(){return this.runAsync(...this.state.params||[])}mutate(t){let n;typeof t=="function"?n=t?.(this.state.data):n=t,this.runPluginHandler("onMutate",n),this.setState({data:n})}}function tn(e,t={},n=[]){const{initialData:r=void 0,manual:i=!1,ready:s=!0,...o}={...t??{}},u={manual:i,ready:s,...o},l=e,[c,a]=E({data:r,loading:!1,params:void 0,error:void 0}),f=(S,Q)=>{a(Q?re=>({...re,[Q]:S}):S)},p=R(()=>c().data),F=R(()=>c().loading),te=R(()=>c().params),ne=R(()=>c().error),X=n.map(S=>S?.onInit?.(u)).filter(Boolean),g=new en(l,u,f,Object.assign({},...X,c));return g.options=u,g.pluginImpls=n.map(S=>S(g,u)),J(()=>{if(!i){const S=g.state.params||t.defaultParams||[];d(s)&&g.run(...S)}}),{data:p,error:ne,loading:F,params:te,cancel:g.cancel.bind(g),refresh:g.refresh.bind(g),refreshAsync:g.refreshAsync.bind(g),run:g.run.bind(g),runAsync:g.runAsync.bind(g),mutate:g.mutate.bind(g)}}function Ae(e,t,n){return tn(e,t,[...n||[],Mt,Ht,Gt,Xt,Kt,be,He,Qt])}function nn(e,t,n){return Ae(e,t,n)}return $.clearUseRequestCache=Le,$.createUseRequest=nn,$.default=Ae,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),$}({});