@better-typed/react-hyper-fetch
Advanced tools
Comparing version 1.3.1 to 1.4.0
export * from "./use-command-events"; | ||
export * from "./use-debounce"; | ||
export * from "./use-tracked-state"; |
@@ -1,2 +0,2 @@ | ||
var Ne=Object.create;var ue=Object.defineProperty,We=Object.defineProperties,Ge=Object.getOwnPropertyDescriptor,Je=Object.getOwnPropertyDescriptors,$e=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,ze=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty,He=Object.prototype.propertyIsEnumerable;var Ue=(e,t,n)=>t in e?ue(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y=(e,t)=>{for(var n in t||(t={}))ke.call(t,n)&&Ue(e,n,t[n]);if(Oe)for(var n of Oe(t))He.call(t,n)&&Ue(e,n,t[n]);return e},B=(e,t)=>We(e,Je(t));var Xe=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},qe=(e,t,n,g)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of $e(t))!ke.call(e,d)&&d!==n&&ue(e,d,{get:()=>t[d],enumerable:!(g=Ge(t,d))||g.enumerable});return e};var Ye=(e,t,n)=>(n=e!=null?Ne(ze(e)):{},qe(t||!e||!e.__esModule?ue(n,"default",{value:e,enumerable:!0}):n,e)),Ze=e=>qe(ue({},"__esModule",{value:!0}),e);var ce=(e,t,n)=>new Promise((g,d)=>{var l=o=>{try{c(n.next(o))}catch(T){d(T)}},f=o=>{try{c(n.throw(o))}catch(T){d(T)}},c=o=>o.done?g(o.value):Promise.resolve(o.value).then(l,f);c((n=n.apply(e,t)).next())});var ot={};Xe(ot,{getDetailsState:()=>$,getInitialState:()=>fe,getRefreshTime:()=>Se,getTimestamp:()=>Me,getValidCacheData:()=>we,initialState:()=>J,isEmpty:()=>Re,isEqual:()=>ie,isStaleCacheData:()=>de,useAppManager:()=>rt,useCache:()=>nt,useCacheDefaultOptions:()=>Ce,useCommandEvents:()=>H,useDebounce:()=>te,useFetch:()=>Ve,useFetchDefaultOptions:()=>F,useQueue:()=>tt,useQueueDefaultOptions:()=>ge,useSubmit:()=>et,useSubmitDefaultOptions:()=>Te,useTrackedState:()=>X});module.exports=Ze(ot);var Le=require("react"),re=require("@better-typed/react-lifecycle-hooks"),le=require("@better-typed/hyper-fetch");var Q=require("react"),Pe=require("@better-typed/react-lifecycle-hooks"),H=({command:e,dispatcher:t,logger:n,actions:g,setCacheData:d})=>{let{cache:l,commandManager:f}=e.builder,c=(0,Q.useRef)(null),o=(0,Q.useRef)(null),T=(0,Q.useRef)(null),b=(0,Q.useRef)(null),x=(0,Q.useRef)(null),D=(0,Q.useRef)(null),a=(0,Q.useRef)(null),R=(0,Q.useRef)(null),U=(0,Q.useRef)(null),C=(0,Q.useRef)(new Map),k=(0,Q.useRef)(null),S=r=>{let s=C.current.get(r);s==null||s.unmount(),C.current.delete(r)},v=()=>{let r=C.current;Array.from(r.values()).forEach(i=>{i.unmount()}),r.clear()},h=(r,s,i)=>{var _,w,L,A,V;let{isOffline:W,isFailed:Z,isCanceled:se}=i;e.offline&&W&&Z?(n.debug("Performing offline error callback",{data:s,details:i}),(_=b.current)==null||_.call(b,{response:s[1],command:r,details:i})):se?(n.debug("Performing abort callback",{data:s,details:i}),(w=T.current)==null||w.call(T,{response:s[1],command:r,details:i})):Z?(n.debug("Performing error callback",{data:s,details:i}),(A=o.current)==null||A.call(o,{response:s[1],command:r,details:i})):(n.debug("Performing success callback",{data:s,details:i}),(L=c.current)==null||L.call(c,{response:s[0],command:r,details:i})),(V=x.current)==null||V.call(x,{response:s,command:r,details:i})},u=r=>({isLoading:s})=>{let i=!s&&!t.hasRunningRequests(r);(s||i)&&g.setLoading(s,!1)},p=(r,s)=>{var i;(i=R.current)==null||i.call(R,r,s)},m=(r,s)=>{var i;(i=U.current)==null||i.call(U,r,s)},q=r=>s=>{var i;(i=D.current)==null||i.call(D,{command:r,details:s})},P=r=>s=>{var i;(i=a.current)==null||i.call(a,{command:r,details:s})},M=r=>(s,i)=>{h(r,s,i)},O=({requestId:r})=>{S(r)},E=()=>{var r;(r=k.current)==null||r.unmount(),k.current=null},N=r=>{let s=f.events.onLoading(r.queueKey,u(r.queueKey)),i=l.events.onData(r.cacheKey,d),W=()=>{s(),i()};return E(),k.current={unmount:W},W},K=(r,s)=>{if(!s){let{queueKey:A,cacheKey:V}=r,be=f.events.onRequestStart(A,q(r)),ve=f.events.onResponseStart(A,P(r)),I=f.events.onUploadProgress(A,m),G=f.events.onDownloadProgress(A,p),ae=f.events.onResponse(V,M(r)),ee=()=>{G(),I(),be(),ve(),ae()};return C.current.set(A,{unmount:ee}),ee}let i=f.events.onRemoveById(s,O),W=f.events.onRequestStartById(s,q(r)),Z=f.events.onResponseStartById(s,P(r)),se=f.events.onResponseById(s,M(r)),_=f.events.onUploadProgressById(s,m),w=f.events.onDownloadProgressById(s,p),L=()=>{i(),w(),_(),W(),Z(),se()};return C.current.set(s,{unmount:L}),L},j=()=>{let{abortKey:r}=e;t.getAllRunningRequest().forEach(i=>{i.command.abortKey===r&&t.delete(i.command.queueKey,i.requestId,r)})};return(0,Pe.useWillUnmount)(()=>{v(),E()}),[{abort:j,onSuccess:r=>{c.current=r},onError:r=>{o.current=r},onAbort:r=>{T.current=r},onOfflineError:r=>{b.current=r},onFinished:r=>{x.current=r},onRequestStart:r=>{D.current=r},onResponseStart:r=>{a.current=r},onDownloadProgress:r=>{R.current=r},onUploadProgress:r=>{U.current=r}},{addDataListener:N,clearDataListener:E,addLifecycleListeners:K,removeLifecycleListener:S,clearLifecycleListeners:v}]};var Fe=require("react"),Ie=require("@better-typed/react-lifecycle-hooks"),te=(e=600)=>{let t=(0,Fe.useRef)(null),n=()=>{t.current!==null&&clearTimeout(t.current),t.current=null},g=(d,l)=>{n(),t.current=setTimeout(()=>{d()},l||e)};return(0,Ie.useWillUnmount)(n),{debounce:g,resetDebounce:n,active:!!t.current}};var J={data:null,error:null,loading:!1,status:null,retries:0,timestamp:null};var xe=require("react"),pe=require("@better-typed/react-lifecycle-hooks");var Re=e=>{let t=Object.prototype.toString.call(e);return Array.isArray(e)?!e.length:typeof e=="object"&&e!==null&&t==="[object Object]"?!Object.keys(e).length:!1},ie=(e,t)=>{let n=Object.prototype.toString.call(e),g=Object.prototype.toString.call(t),d=typeof e,l=typeof t,f=o=>d===o&&l===o,c=o=>n===o&&g===o;return n!==g?!1:e===null&&t===null||f("number")&&Number.isNaN(e)&&Number.isNaN(t)||Re(e)&&Re(t)?!0:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:!e.some((o,T)=>!ie(o,t[T])):f("object")&&c("[object Object]")?Object.keys(e).length!==Object.keys(t).length?!1:!Object.entries(e).some(([o,T])=>!ie(T,t[o])):e instanceof Date&&t instanceof Date?+e==+t:e===t};var $=(e,t)=>y({retries:(e==null?void 0:e.retries)||0,timestamp:+new Date,isFailed:!1,isCanceled:!1,isOffline:!1},t),de=(e,t)=>t?+new Date>+t+e:!0,we=(e,t,n)=>!de(e.cacheTime,n==null?void 0:n.details.timestamp)&&n?n:t?{data:t,details:$(),cacheTime:1e3,clearKey:e.builder.cache.clearKey}:null,Me=e=>e?new Date(e):null,fe=(e,t,n)=>{var T,b,x;let{builder:g,cacheKey:d}=n,{cache:l}=g,f=l.get(d),c=we(n,e,f),o=t.hasRunningRequests(n.queueKey);return B(y({},J),{data:((T=c==null?void 0:c.data)==null?void 0:T[0])||J.data,error:((b=c==null?void 0:c.data)==null?void 0:b[1])||J.error,status:((x=c==null?void 0:c.data)==null?void 0:x[2])||J.status,retries:(c==null?void 0:c.details.retries)||J.retries,timestamp:Me((c==null?void 0:c.details.timestamp)||J.timestamp),loading:o})};var X=({command:e,dispatcher:t,initialData:n,deepCompare:g,dependencyTracking:d,defaultCacheEmitting:l=!0})=>{let{builder:f,cacheKey:c,queueKey:o,cacheTime:T}=e,{cache:b,commandManager:x}=f,D=(0,pe.useForceUpdate)(),a=(0,xe.useRef)(fe(n,t,e)),R=(0,xe.useRef)([]),U=()=>{let u=b.get(c);return de(T,(u==null?void 0:u.details.timestamp)||a.current.timestamp)},C=u=>{R.current.some(m=>u.includes(m))&&D()},k=u=>{R.current.includes(u)||R.current.push(u)};(0,pe.useDidUpdate)(()=>{a.current.loading=t.hasRunningRequests(o);let u=fe(n,t,e),p=(n==null?void 0:n[0])===a.current.data,m=!!(a.current.data||a.current.error)&&!p,q=!m&&a.current.data,P=m&&!a.current.data;(q||P)&&(a.current=u)},[c,o],!0),(0,pe.useDidUpdate)(()=>{(()=>{d||Object.keys(a.current).forEach(p=>k(p))})()},[d],!0);let S=(u,p)=>typeof g=="function"?g(u,p):g?ie(u,p):!1,v=u=>ce(void 0,null,function*(){let p={data:u.data[0],error:u.data[1],status:u.data[2],retries:u.details.retries,timestamp:new Date(u.details.timestamp),loading:a.current.loading},m=Object.keys(p).filter(q=>{let P=q,M=a.current[P],O=p[P];return!S(M,O)});a.current=y(y({},a.current),p),C(m)}),h={setData:(u,p=l)=>{if(p){let m=a.current;b.set(e,[u,m.error,m.status],$(a.current))}else a.current.data=u,C(["data"])},setError:(u,p=l)=>{if(p){let m=a.current;b.set(e,[m.data,u,m.status],$(a.current,{isFailed:!!u}))}else a.current.error=u,C(["error"])},setLoading:(u,p=!0)=>{p?x.events.emitLoading(o,"",{queueKey:o,requestId:"",isLoading:u,isRetry:!1,isOffline:!1}):(a.current.loading=u,C(["loading"]))},setStatus:(u,p=l)=>{if(p){let m=a.current;b.set(e,[m.data,m.error,u],$(a.current))}else a.current.status=u,C(["status"])},setRetries:(u,p=l)=>{if(p){let m=a.current;b.set(e,[m.data,m.error,m.status],$(a.current,{retries:u}))}else a.current.retries=u,C(["retries"])},setTimestamp:(u,p=l)=>{if(p){let m=a.current;b.set(e,[m.data,m.error,m.status],$(a.current,{timestamp:+u}))}else a.current.timestamp=u,C(["timestamp"])}};return[a.current,h,{setRenderKey:k,setCacheData:v,getStaleStatus:U}]};var ne=Ye(require("react")),_e=ne.default.createContext([{},()=>null]);var z=()=>(0,ne.useContext)(_e);var Ve=(e,t=F)=>{let[n]=z(),{dependencies:g=F.dependencies,disabled:d=F.disabled,dependencyTracking:l=F.dependencyTracking,revalidateOnMount:f=F.revalidateOnMount,initialData:c=F.initialData,refresh:o=F.refresh,refreshTime:T=F.refreshTime,refreshBlurred:b=F.refreshBlurred,refreshOnBlur:x=F.refreshOnBlur,refreshOnFocus:D=F.refreshOnFocus,refreshOnReconnect:a=F.refreshOnReconnect,debounce:R=F.debounce,debounceTime:U=F.debounceTime,deepCompare:C=F.deepCompare}=y(y(y({},F),n.useFetchConfig),t),k=JSON.stringify(e.dump()),S=te(U),v=te(T),{cacheKey:h,queueKey:u,builder:p}=e,{cache:m,fetchDispatcher:q,appManager:P,loggerManager:M}=p,O=(0,Le.useRef)(M.init("useFetch")).current,[E,N,{setRenderKey:K,setCacheData:j,getStaleStatus:r}]=X({logger:O,command:e,dispatcher:q,initialData:c,deepCompare:C,dependencyTracking:l}),[s,i]=H({logger:O,actions:N,command:e,dispatcher:q,setCacheData:j}),{addDataListener:W,addLifecycleListeners:Z,clearDataListener:se,clearLifecycleListeners:_}=i,w=()=>{d?O.debug("Cannot add to fetch queue",{disabled:d}):(O.debug("Fetching data"),q.add(e))};function L(){if(!o)return;let I=Se(T,E.timestamp);O.debug(`Starting refresh counter, request will be send in ${I}ms`),v.debounce(()=>{let G=!P.isFocused,ae=q.hasRunningRequests(e.queueKey),ee=q.getIsActiveQueue(e.queueKey),he=ae||ee;(G&&b&&!he||!G&&!he)&&(w(),O.debug("Performing refresh request")),L()},I)}let A=I=>{I&&I instanceof le.Command?m.revalidate((0,le.getCommandKey)(I)):I&&!(I instanceof le.Command)?m.revalidate(I):(w(),L())},V=()=>{let I=r(),G=q.getIsActiveQueue(u);(f||I&&!G)&&w()},be=()=>{R?(O.debug("Debouncing request",{queueKey:u,command:e}),S.debounce(()=>w())):w()};return(0,re.useDidUpdate)(()=>{W(e),Z(e);let I=P.events.onFocus(()=>{D&&(w(),L())}),G=P.events.onBlur(()=>{x&&(w(),L())}),ae=P.events.onOnline(()=>{a&&(w(),L())}),ee=m.events.onRevalidate(h,w);return()=>{se(),_(),I(),G(),ae(),ee()}},[k],!0),(0,re.useDidMount)(V),(0,re.useDidUpdate)(be,[k,...g]),(0,re.useDidUpdate)(L,[k,...g,d,o,T],!0),B(y(y({get data(){return K("data"),E.data},get error(){return K("error"),E.error},get loading(){return K("loading"),E.loading},get status(){return K("status"),E.status},get retries(){return K("retries"),E.retries},get timestamp(){return K("timestamp"),E.timestamp}},N),s),{isDebouncing:S.active,revalidate:A})};var Se=(e,t)=>{if(t){let n=Date.now()-+t;return n<e?e-n:e}return e};var Qe=require("@better-typed/hyper-fetch"),F={dependencies:[],disabled:!1,dependencyTracking:!0,revalidateOnMount:!0,initialData:null,refresh:!1,refreshTime:Qe.DateInterval.hour,refreshBlurred:!0,refreshOnBlur:!1,refreshOnFocus:!1,refreshOnReconnect:!1,debounce:!1,debounceTime:400,deepCompare:!0};var Ee=require("react"),Y=require("@better-typed/hyper-fetch"),Ke=require("@better-typed/react-lifecycle-hooks");var et=(e,t=Te)=>{let[n]=z(),{disabled:g,dependencyTracking:d,initialData:l,debounce:f,debounceTime:c,deepCompare:o}=y(y(y({},Te),n.useSubmitConfig),t),{builder:T}=e,{cache:b,submitDispatcher:x,loggerManager:D}=T,a=(0,Ee.useRef)(D.init("useSubmit")).current,R=te(c),U=(0,Ee.useRef)(()=>null),[C,k,{setRenderKey:S,setCacheData:v}]=X({logger:a,command:e,dispatcher:x,initialData:l,deepCompare:o,dependencyTracking:d}),[h,u]=H({logger:a,actions:k,command:e,dispatcher:x,setCacheData:v}),{addDataListener:p,addLifecycleListeners:m}=u,q=(...O)=>{let E=O[0],N=e.clone(E);if(g)throw a.warning("Cannot submit request",{disabled:g,submitOptions:E}),new Error("Cannot submit request. Option 'disabled' is enabled");let K=()=>(p(N),(0,Y.commandSendRequest)(N,B(y({dispatcherType:"submit"},E),{onSettle:(j,r)=>{var s;m(N,j),(s=E==null?void 0:E.onSettle)==null||s.call(E,j,r)}})));return new Promise(j=>{(()=>ce(void 0,null,function*(){if(a.debug("Submitting request",{disabled:g,submitOptions:E}),f)U.current=s=>{U.current(s),j(s)},R.debounce(()=>ce(void 0,null,function*(){let s=U.current;U.current=()=>null;let i=yield K();s(i)}));else{let s=yield K();j(s)}}))()})},P=O=>{!O||(O&&O instanceof Y.Command?b.revalidate((0,Y.getCommandKey)(O)):O instanceof Y.Command||b.revalidate(O))},M={onSubmitSuccess:h.onSuccess,onSubmitError:h.onError,onSubmitFinished:h.onFinished,onSubmitRequestStart:h.onRequestStart,onSubmitResponseStart:h.onResponseStart,onSubmitDownloadProgress:h.onDownloadProgress,onSubmitUploadProgress:h.onUploadProgress,onSubmitOfflineError:h.onOfflineError,onSubmitAbort:h.onAbort};return(0,Ke.useDidMount)(()=>{p(e)}),B(y(y({submit:q,get data(){return S("data"),C.data},get error(){return S("error"),C.error},get submitting(){return S("loading"),C.loading},get status(){return S("status"),C.status},get retries(){return S("retries"),C.retries},get timestamp(){return S("timestamp"),C.timestamp},abort:h.abort},k),M),{isDebouncing:R.active,revalidate:P})};var Te={disabled:!1,dependencyTracking:!0,cacheOnMount:!0,initialData:null,debounce:!1,debounceTime:400,suspense:!1,shouldThrow:!1,invalidate:[],deepCompare:!0};var me=require("react"),Be=require("@better-typed/hyper-fetch"),ye=require("@better-typed/react-lifecycle-hooks");var tt=(e,t=ge)=>{let[n]=z(),{queueType:g="auto"}=y(y(y({},ge),n.useQueueConfig),t),{abortKey:d,queueKey:l,builder:f}=e,{commandManager:c}=f,[o]=(0,Be.getCommandDispatcher)(e,g),T=(0,me.useRef)(null),[b,x]=(0,me.useState)(!1),[D,a]=(0,me.useState)([]),R=v=>v.map(h=>B(y({},h),{stopRequest:()=>o.stopRequest(l,h.requestId),startRequest:()=>o.startRequest(l,h.requestId),deleteRequest:()=>o.delete(l,h.requestId,d)})),U=(v,h)=>{a(u=>u.map(p=>p.requestId===v?y(y({},p),h):p))},C=()=>{let v=o.getQueue(l);x(v.stopped),a(R(v.requests))},k=v=>{x(v.stopped),a(R(v.requests))},S=()=>{var q;let v=o.events.onQueueChange(l,k),h=o.events.onQueueStatus(l,k),u=c.events.onDownloadProgress(l,(P,{requestId:M})=>{U(M,{downloading:P})}),p=c.events.onUploadProgress(l,(P,{requestId:M})=>{U(M,{uploading:P})}),m=()=>{h(),v(),u(),p()};return(q=T.current)==null||q.call(T),T.current=m,m};return(0,ye.useDidMount)(C),(0,ye.useDidUpdate)(S,[b,D,a,x],!0),{stopped:b,requests:D,stop:()=>o.stop(l),pause:()=>o.pause(l),start:()=>o.start(l)}};var ge={queueType:"auto"};var Ae=require("react"),oe=require("@better-typed/hyper-fetch");var nt=(e,t=Ce)=>{let{cacheKey:n,builder:g}=e,{cache:d,loggerManager:l}=g,f=(0,Ae.useRef)(l.init("useCache")).current,[c]=(0,oe.getCommandDispatcher)(e),[o]=z(),{dependencyTracking:T,initialData:b,deepCompare:x}=y(y(y({},Ce),o.useCacheConfig),t),[D,a,{setRenderKey:R,setCacheData:U}]=X({logger:f,command:e,dispatcher:c,initialData:b,deepCompare:x,dependencyTracking:T}),[C]=H({logger:f,actions:a,command:e,dispatcher:c,setCacheData:U}),k=S=>{S instanceof oe.Command?d.revalidate((0,oe.getCommandKey)(S,!0)):S?d.revalidate(S):d.revalidate(n)};return B(y({get data(){return R("data"),D.data},get error(){return R("error"),D.error},get loading(){return R("loading"),D.loading},get status(){return R("status"),D.status},get retries(){return R("retries"),D.retries},get timestamp(){return R("timestamp"),D.timestamp},onCacheError:C.onError,onCacheSuccess:C.onSuccess,onCacheChange:C.onFinished},a),{revalidate:k})};var Ce={dependencyTracking:!0,initialData:null,deepCompare:!0};var De=require("react"),je=require("@better-typed/react-lifecycle-hooks"),rt=e=>{let[t,n]=(0,De.useState)(e.appManager.isOnline),[g,d]=(0,De.useState)(e.appManager.isFocused),l=()=>{let o=e.appManager.events.onOnline(()=>n(!0)),T=e.appManager.events.onOffline(()=>n(!1)),b=e.appManager.events.onFocus(()=>d(!0)),x=e.appManager.events.onBlur(()=>d(!1));return()=>{o(),T(),b(),x()}},f=o=>{e.appManager.setOnline(o)},c=o=>{e.appManager.setFocused(o)};return(0,je.useDidMount)(l),{isOnline:t,isFocused:g,setOnline:f,setFocused:c}}; | ||
var We=Object.create;var ae=Object.defineProperty,ze=Object.defineProperties,He=Object.getOwnPropertyDescriptor,Xe=Object.getOwnPropertyDescriptors,Ye=Object.getOwnPropertyNames,Ie=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty,_e=Object.prototype.propertyIsEnumerable;var we=(e,n,r)=>n in e?ae(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r,d=(e,n)=>{for(var r in n||(n={}))Me.call(n,r)&&we(e,r,n[r]);if(Ie)for(var r of Ie(n))_e.call(n,r)&&we(e,r,n[r]);return e},w=(e,n)=>ze(e,Xe(n));var Ve=(e,n)=>{for(var r in n)ae(e,r,{get:n[r],enumerable:!0})},Le=(e,n,r,y)=>{if(n&&typeof n=="object"||typeof n=="function")for(let f of Ye(n))!Me.call(e,f)&&f!==r&&ae(e,f,{get:()=>n[f],enumerable:!(y=He(n,f))||y.enumerable});return e};var et=(e,n,r)=>(r=e!=null?We(Ze(e)):{},Le(n||!e||!e.__esModule?ae(r,"default",{value:e,enumerable:!0}):r,e)),tt=e=>Le(ae({},"__esModule",{value:!0}),e);var ue=(e,n,r)=>new Promise((y,f)=>{var m=o=>{try{i(r.next(o))}catch(g){f(g)}},T=o=>{try{i(r.throw(o))}catch(g){f(g)}},i=o=>o.done?y(o.value):Promise.resolve(o.value).then(m,T);i((r=r.apply(e,n)).next())});var ct={};Ve(ct,{getDetailsState:()=>z,getInitialState:()=>Te,getRefreshTime:()=>qe,getTimestamp:()=>Qe,getValidCacheData:()=>Ke,initialState:()=>W,isEmpty:()=>Ue,isEqual:()=>ce,isStaleCacheData:()=>fe,useAppManager:()=>ut,useCache:()=>at,useCacheDefaultOptions:()=>he,useCommandEvents:()=>Z,useFetch:()=>rt,useFetchDefaultOptions:()=>D,useQueue:()=>st,useQueueDefaultOptions:()=>Ce,useSubmit:()=>ot,useSubmitDefaultOptions:()=>ge,useTrackedState:()=>_});module.exports=tt(ct);var Ae=require("react"),re=require("@better-typed/react-lifecycle-hooks"),pe=require("@better-typed/react-performance-hooks"),le=require("@better-typed/hyper-fetch");var B=require("react"),Be=require("@better-typed/react-lifecycle-hooks"),Z=({command:e,dispatcher:n,logger:r,actions:y,setCacheData:f})=>{let{cache:m,commandManager:T}=e.builder,i=(0,B.useRef)(null),o=(0,B.useRef)(null),g=(0,B.useRef)(null),C=(0,B.useRef)(null),R=(0,B.useRef)(null),E=(0,B.useRef)(null),a=(0,B.useRef)(null),b=(0,B.useRef)(null),v=(0,B.useRef)(null),h=(0,B.useRef)(new Map),U=(0,B.useRef)(null),q=t=>{let u=h.current.get(t);u==null||u.unmount(),h.current.delete(t)},O=()=>{let t=h.current;Array.from(t.values()).forEach(c=>{c.unmount()}),t.clear()},x=(t,u,c)=>{var Q,G,Y,N,ee;let{isOffline:F,isFailed:$,isCanceled:L}=c;e.offline&&F&&$?(r.debug("Performing offline error callback",{data:u,details:c}),(Q=C.current)==null||Q.call(C,{response:u[1],command:t,details:c})):L?(r.debug("Performing abort callback",{data:u,details:c}),(G=g.current)==null||G.call(g,{response:u[1],command:t,details:c})):$?(r.debug("Performing error callback",{data:u,details:c}),(N=o.current)==null||N.call(o,{response:u[1],command:t,details:c})):(r.debug("Performing success callback",{data:u,details:c}),(Y=i.current)==null||Y.call(i,{response:u[0],command:t,details:c})),(ee=R.current)==null||ee.call(R,{response:u,command:t,details:c})},s=t=>({isLoading:u})=>{let c=!u&&!n.hasRunningRequests(t);(u||c)&&y.setLoading(u,!1)},p=(t,u)=>{var c;(c=b.current)==null||c.call(b,t,u)},l=(t,u)=>{var c;(c=v.current)==null||c.call(v,t,u)},S=t=>u=>{var c;(c=E.current)==null||c.call(E,{command:t,details:u})},P=t=>u=>{var c;(c=a.current)==null||c.call(a,{command:t,details:u})},k=t=>(u,c)=>{x(t,u,c)},j=({requestId:t})=>{q(t)},X=()=>{var t;(t=U.current)==null||t.unmount(),U.current=null},K=t=>{let u=T.events.onLoading(t.queueKey,s(t.queueKey)),c=m.events.onData(t.cacheKey,f),F=()=>{u(),c()};return X(),U.current={unmount:F},F},se=(t,u)=>{if(!u){let{queueKey:N,cacheKey:ee}=t,A=T.events.onRequestStart(N,S(t)),J=T.events.onResponseStart(N,P(t)),Re=T.events.onUploadProgress(N,l),xe=T.events.onDownloadProgress(N,p),Se=T.events.onResponse(ee,k(t)),Ee=()=>{xe(),Re(),A(),J(),Se()};return h.current.set(N,{unmount:Ee}),Ee}let c=T.events.onRemoveById(u,j),F=T.events.onRequestStartById(u,S(t)),$=T.events.onResponseStartById(u,P(t)),L=T.events.onResponseById(u,k(t)),Q=T.events.onUploadProgressById(u,l),G=T.events.onDownloadProgressById(u,p),Y=()=>{c(),G(),Q(),F(),$(),L()};return h.current.set(u,{unmount:Y}),Y},M=()=>{let{abortKey:t}=e;n.getAllRunningRequest().forEach(c=>{c.command.abortKey===t&&n.delete(c.command.queueKey,c.requestId,t)})};return(0,Be.useWillUnmount)(()=>{O(),X()}),[{abort:M,onSuccess:t=>{i.current=t},onError:t=>{o.current=t},onAbort:t=>{g.current=t},onOfflineError:t=>{C.current=t},onFinished:t=>{R.current=t},onRequestStart:t=>{E.current=t},onResponseStart:t=>{a.current=t},onDownloadProgress:t=>{b.current=t},onUploadProgress:t=>{v.current=t}},{addDataListener:K,clearDataListener:X,addLifecycleListeners:se,removeLifecycleListener:q,clearLifecycleListeners:O}]};var W={data:null,error:null,loading:!1,status:null,retries:0,timestamp:null};var ke=require("react"),ie=require("@better-typed/react-lifecycle-hooks");var Ue=e=>{let n=Object.prototype.toString.call(e);return Array.isArray(e)?!e.length:typeof e=="object"&&e!==null&&n==="[object Object]"?!Object.keys(e).length:!1},ce=(e,n)=>{let r=Object.prototype.toString.call(e),y=Object.prototype.toString.call(n),f=typeof e,m=typeof n,T=o=>f===o&&m===o,i=o=>r===o&&y===o;return r!==y?!1:e===null&&n===null||T("number")&&Number.isNaN(e)&&Number.isNaN(n)||Ue(e)&&Ue(n)?!0:Array.isArray(e)&&Array.isArray(n)?e.length!==n.length?!1:!e.some((o,g)=>!ce(o,n[g])):T("object")&&i("[object Object]")?Object.keys(e).length!==Object.keys(n).length?!1:!Object.entries(e).some(([o,g])=>!ce(g,n[o])):e instanceof Date&&n instanceof Date?+e==+n:e===n};var de=e=>w(d({},e),{throttle:void 0,debounce:void 0});var z=(e,n)=>d({retries:(e==null?void 0:e.retries)||0,timestamp:+new Date,isFailed:!1,isCanceled:!1,isOffline:!1},n),fe=(e,n)=>n?+new Date>+n+e:!0,Ke=(e,n,r)=>!fe(e.cacheTime,r==null?void 0:r.details.timestamp)&&r?r:n?{data:n,details:z(),cacheTime:1e3,clearKey:e.builder.cache.clearKey}:null,Qe=e=>e?new Date(e):null,Te=(e,n,r)=>{var g,C,R;let{builder:y,cacheKey:f}=r,{cache:m}=y,T=m.get(f),i=Ke(r,e,T),o=n.hasRunningRequests(r.queueKey);return w(d({},W),{data:((g=i==null?void 0:i.data)==null?void 0:g[0])||W.data,error:((C=i==null?void 0:i.data)==null?void 0:C[1])||W.error,status:((R=i==null?void 0:i.data)==null?void 0:R[2])||W.status,retries:(i==null?void 0:i.details.retries)||W.retries,timestamp:Qe((i==null?void 0:i.details.timestamp)||W.timestamp),loading:o})};var _=({command:e,dispatcher:n,initialData:r,deepCompare:y,dependencyTracking:f,defaultCacheEmitting:m=!0})=>{let{builder:T,cacheKey:i,queueKey:o,cacheTime:g}=e,{cache:C,commandManager:R}=T,E=(0,ie.useForceUpdate)(),a=(0,ke.useRef)(Te(r,n,e)),b=(0,ke.useRef)([]),v=()=>{let s=C.get(i);return fe(g,(s==null?void 0:s.details.timestamp)||a.current.timestamp)},h=s=>{b.current.some(l=>s.includes(l))&&E()},U=s=>{b.current.includes(s)||b.current.push(s)};(0,ie.useDidUpdate)(()=>{a.current.loading=n.hasRunningRequests(o);let s=Te(r,n,e),p=(r==null?void 0:r[0])===a.current.data,l=!!(a.current.data||a.current.error)&&!p,S=!l&&a.current.data,P=l&&!a.current.data;(S||P)&&(a.current=s)},[i,o],!0),(0,ie.useDidUpdate)(()=>{(()=>{f||Object.keys(a.current).forEach(p=>U(p))})()},[f],!0);let q=(s,p)=>typeof y=="function"?y(s,p):y?ce(s,p):!1,O=s=>ue(void 0,null,function*(){let p={data:s.data[0],error:s.data[1],status:s.data[2],retries:s.details.retries,timestamp:new Date(s.details.timestamp),loading:a.current.loading},l=Object.keys(p).filter(S=>{let P=S,k=a.current[P],j=p[P];return!q(k,j)});a.current=d(d({},a.current),p),h(l)}),x={setData:(s,p=m)=>{if(p){let l=a.current;C.set(e,[s,l.error,l.status],z(a.current))}else a.current.data=s,h(["data"])},setError:(s,p=m)=>{if(p){let l=a.current;C.set(e,[l.data,s,l.status],z(a.current,{isFailed:!!s}))}else a.current.error=s,h(["error"])},setLoading:(s,p=!0)=>{p?R.events.emitLoading(o,"",{queueKey:o,requestId:"",isLoading:s,isRetry:!1,isOffline:!1}):(a.current.loading=s,h(["loading"]))},setStatus:(s,p=m)=>{if(p){let l=a.current;C.set(e,[l.data,l.error,s],z(a.current))}else a.current.status=s,h(["status"])},setRetries:(s,p=m)=>{if(p){let l=a.current;C.set(e,[l.data,l.error,l.status],z(a.current,{retries:s}))}else a.current.retries=s,h(["retries"])},setTimestamp:(s,p=m)=>{if(p){let l=a.current;C.set(e,[l.data,l.error,l.status],z(a.current,{timestamp:+s}))}else a.current.timestamp=s,h(["timestamp"])}};return[a.current,x,{setRenderKey:U,setCacheData:O,getStaleStatus:v}]};var ne=et(require("react")),nt=ne.default.createContext([{},()=>null]);var H=()=>(0,ne.useContext)(nt);var rt=(e,n=D)=>{let[r]=H(),{dependencies:y=D.dependencies,disabled:f=D.disabled,dependencyTracking:m=D.dependencyTracking,revalidateOnMount:T=D.revalidateOnMount,initialData:i=D.initialData,refresh:o=D.refresh,refreshTime:g=D.refreshTime,refreshBlurred:C=D.refreshBlurred,refreshOnBlur:R=D.refreshOnBlur,refreshOnFocus:E=D.refreshOnFocus,refreshOnReconnect:a=D.refreshOnReconnect,bounce:b=D.bounce,bounceType:v=D.bounceType,bounceTime:h=D.bounceTime,deepCompare:U=D.deepCompare}=d(d(d({},D),r.useFetchConfig),n),q=JSON.stringify(e.dump()),O=(0,pe.useDebounce)(h),x=(0,pe.useThrottle)(h),s=(0,pe.useDebounce)(g),{cacheKey:p,queueKey:l,builder:S}=e,{cache:P,fetchDispatcher:k,appManager:j,loggerManager:X}=S,K=(0,Ae.useRef)(X.init("useFetch")).current,se=v==="throttle"?x:O,M=v==="throttle"?x.throttle:O.debounce,[t,u,{setRenderKey:c,setCacheData:F,getStaleStatus:$}]=_({logger:K,command:e,dispatcher:k,initialData:i,deepCompare:U,dependencyTracking:m}),[L,Q]=Z({logger:K,actions:u,command:e,dispatcher:k,setCacheData:F}),{addDataListener:G,addLifecycleListeners:Y,clearDataListener:N,clearLifecycleListeners:ee}=Q,A=()=>{f?K.debug("Cannot add to fetch queue",{disabled:f}):(K.debug("Fetching data"),k.add(e))};function J(){if(!o)return;let I=qe(g,t.timestamp);K.debug(`Starting refresh counter, request will be send in ${I}ms`),s.debounce(()=>{let te=!j.isFocused,Oe=k.hasRunningRequests(e.queueKey),De=k.getIsActiveQueue(e.queueKey),ve=Oe||De;(te&&C&&!ve||!te&&!ve)&&(A(),K.debug("Performing refresh request")),J()},I)}let Re=I=>{I&&I instanceof le.Command?P.revalidate((0,le.getCommandKey)(I)):I&&!(I instanceof le.Command)?P.revalidate(I):(A(),J())},xe=()=>{let I=$(),te=k.getIsActiveQueue(l);(T||I&&!te)&&A()},Se=()=>{b?(K.debug(`Bounce request with ${v}`,{queueKey:l,command:e}),M(()=>A())):A()};return(0,re.useDidUpdate)(()=>{G(e),Y(e);let I=j.events.onFocus(()=>{E&&(A(),J())}),te=j.events.onBlur(()=>{R&&(A(),J())}),Oe=j.events.onOnline(()=>{a&&(A(),J())}),De=P.events.onRevalidate(p,A);return()=>{N(),ee(),I(),te(),Oe(),De()}},[q],!0),(0,re.useDidMount)(xe),(0,re.useDidUpdate)(Se,[q,...y]),(0,re.useDidUpdate)(J,[q,...y,f,o,g],!0),w(d(d({get data(){return c("data"),t.data},get error(){return c("error"),t.error},get loading(){return c("loading"),t.loading},get status(){return c("status"),t.status},get retries(){return c("retries"),t.retries},get timestamp(){return c("timestamp"),t.timestamp},bounce:de(se)},u),L),{revalidate:Re})};var qe=(e,n)=>{if(n){let r=Date.now()-+n;return r<e?e-r:e}return e};var je=require("@better-typed/hyper-fetch"),D={dependencies:[],disabled:!1,dependencyTracking:!0,revalidateOnMount:!0,initialData:null,refresh:!1,refreshTime:je.DateInterval.hour,refreshBlurred:!0,refreshOnBlur:!1,refreshOnFocus:!1,refreshOnReconnect:!1,bounce:!1,bounceType:"debounce",bounceTime:400,deepCompare:!0};var Pe=require("react"),V=require("@better-typed/hyper-fetch"),Ne=require("@better-typed/react-lifecycle-hooks"),ye=require("@better-typed/react-performance-hooks");var ot=(e,n=ge)=>{let[r]=H(),{disabled:y,dependencyTracking:f,initialData:m,bounce:T,bounceType:i,bounceTime:o,deepCompare:g}=d(d(d({},ge),r.useSubmitConfig),n),{builder:C}=e,{cache:R,submitDispatcher:E,loggerManager:a}=C,b=(0,Pe.useRef)(a.init("useSubmit")).current,v=(0,ye.useDebounce)(o),h=(0,ye.useThrottle)(o),U=(0,Pe.useRef)(()=>null),q=i==="throttle"?h:v,O=i==="throttle"?h.throttle:v.debounce,[x,s,{setRenderKey:p,setCacheData:l}]=_({logger:b,command:e,dispatcher:E,initialData:m,deepCompare:g,dependencyTracking:f}),[S,P]=Z({logger:b,actions:s,command:e,dispatcher:E,setCacheData:l}),{addDataListener:k,addLifecycleListeners:j}=P,X=(...M)=>{let t=M[0],u=e.clone(t);if(y)throw b.warning("Cannot submit request",{disabled:y,submitOptions:t}),new Error("Cannot submit request. Option 'disabled' is enabled");let c=()=>(k(u),(0,V.commandSendRequest)(u,w(d({dispatcherType:"submit"},t),{onSettle:(F,$)=>{var L;j(u,F),(L=t==null?void 0:t.onSettle)==null||L.call(t,F,$)}})));return new Promise(F=>{(()=>ue(void 0,null,function*(){if(b.debug("Submitting request",{disabled:y,submitOptions:t}),T){let L=U.current;U.current=Q=>{L(Q),F(Q)},O(()=>ue(void 0,null,function*(){let Q=U.current;U.current=()=>null;let G=yield c();Q(G)}))}else{let L=yield c();F(L)}}))()})},K=M=>{!M||(M&&M instanceof V.Command?R.revalidate((0,V.getCommandKey)(M)):M instanceof V.Command||R.revalidate(M))},se={onSubmitSuccess:S.onSuccess,onSubmitError:S.onError,onSubmitFinished:S.onFinished,onSubmitRequestStart:S.onRequestStart,onSubmitResponseStart:S.onResponseStart,onSubmitDownloadProgress:S.onDownloadProgress,onSubmitUploadProgress:S.onUploadProgress,onSubmitOfflineError:S.onOfflineError,onSubmitAbort:S.onAbort};return(0,Ne.useDidMount)(()=>{k(e)}),w(d(d({submit:X,get data(){return p("data"),x.data},get error(){return p("error"),x.error},get submitting(){return p("loading"),x.loading},get status(){return p("status"),x.status},get retries(){return p("retries"),x.retries},get timestamp(){return p("timestamp"),x.timestamp},abort:S.abort},s),se),{bounce:de(q),revalidate:K})};var ge={disabled:!1,dependencyTracking:!0,initialData:null,bounce:!1,bounceType:"debounce",bounceTime:400,deepCompare:!0};var me=require("react"),$e=require("@better-typed/hyper-fetch"),be=require("@better-typed/react-lifecycle-hooks");var st=(e,n=Ce)=>{let[r]=H(),{queueType:y="auto"}=d(d(d({},Ce),r.useQueueConfig),n),{abortKey:f,queueKey:m,builder:T}=e,{commandManager:i}=T,[o]=(0,$e.getCommandDispatcher)(e,y),g=(0,me.useRef)(null),[C,R]=(0,me.useState)(!1),[E,a]=(0,me.useState)([]),b=O=>O.map(x=>w(d({},x),{stopRequest:()=>o.stopRequest(m,x.requestId),startRequest:()=>o.startRequest(m,x.requestId),deleteRequest:()=>o.delete(m,x.requestId,f)})),v=(O,x)=>{a(s=>s.map(p=>p.requestId===O?d(d({},p),x):p))},h=()=>{let O=o.getQueue(m);R(O.stopped),a(b(O.requests))},U=O=>{R(O.stopped),a(b(O.requests))},q=()=>{var S;let O=o.events.onQueueChange(m,U),x=o.events.onQueueStatus(m,U),s=i.events.onDownloadProgress(m,(P,{requestId:k})=>{v(k,{downloading:P})}),p=i.events.onUploadProgress(m,(P,{requestId:k})=>{v(k,{uploading:P})}),l=()=>{x(),O(),s(),p()};return(S=g.current)==null||S.call(g),g.current=l,l};return(0,be.useDidMount)(h),(0,be.useDidUpdate)(q,[C,E,a,R],!0),{stopped:C,requests:E,stop:()=>o.stop(m),pause:()=>o.pause(m),start:()=>o.start(m)}};var Ce={queueType:"auto"};var Ge=require("react"),oe=require("@better-typed/hyper-fetch");var at=(e,n=he)=>{let{cacheKey:r,builder:y}=e,{cache:f,loggerManager:m}=y,T=(0,Ge.useRef)(m.init("useCache")).current,[i]=(0,oe.getCommandDispatcher)(e),[o]=H(),{dependencyTracking:g,initialData:C,deepCompare:R}=d(d(d({},he),o.useCacheConfig),n),[E,a,{setRenderKey:b,setCacheData:v}]=_({logger:T,command:e,dispatcher:i,initialData:C,deepCompare:R,dependencyTracking:g}),[h]=Z({logger:T,actions:a,command:e,dispatcher:i,setCacheData:v}),U=q=>{q instanceof oe.Command?f.revalidate((0,oe.getCommandKey)(q,!0)):q?f.revalidate(q):f.revalidate(r)};return w(d({get data(){return b("data"),E.data},get error(){return b("error"),E.error},get loading(){return b("loading"),E.loading},get status(){return b("status"),E.status},get retries(){return b("retries"),E.retries},get timestamp(){return b("timestamp"),E.timestamp},onCacheError:h.onError,onCacheSuccess:h.onSuccess,onCacheChange:h.onFinished},a),{revalidate:U})};var he={dependencyTracking:!0,initialData:null,deepCompare:!0};var Fe=require("react"),Je=require("@better-typed/react-lifecycle-hooks"),ut=e=>{let[n,r]=(0,Fe.useState)(e.appManager.isOnline),[y,f]=(0,Fe.useState)(e.appManager.isFocused),m=()=>{let o=e.appManager.events.onOnline(()=>r(!0)),g=e.appManager.events.onOffline(()=>r(!1)),C=e.appManager.events.onFocus(()=>f(!0)),R=e.appManager.events.onBlur(()=>f(!1));return()=>{o(),g(),C(),R()}},T=o=>{e.appManager.setOnline(o)},i=o=>{e.appManager.setFocused(o)};return(0,Je.useDidMount)(m),{isOnline:n,isFocused:y,setOnline:T,setFocused:i}}; | ||
//# sourceMappingURL=index.cjs.js.map |
@@ -1,2 +0,2 @@ | ||
var De=Object.defineProperty,ve=Object.defineProperties;var Oe=Object.getOwnPropertyDescriptors;var fe=Object.getOwnPropertySymbols;var Ue=Object.prototype.hasOwnProperty,ke=Object.prototype.propertyIsEnumerable;var Te=(e,t,r)=>t in e?De(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,T=(e,t)=>{for(var r in t||(t={}))Ue.call(t,r)&&Te(e,r,t[r]);if(fe)for(var r of fe(t))ke.call(t,r)&&Te(e,r,t[r]);return e},K=(e,t)=>ve(e,Oe(t));var ne=(e,t,r)=>new Promise((g,y)=>{var l=o=>{try{c(r.next(o))}catch(f){y(f)}},d=o=>{try{c(r.throw(o))}catch(f){y(f)}},c=o=>o.done?g(o.value):Promise.resolve(o.value).then(l,d);c((r=r.apply(e,t)).next())});import{useRef as Be}from"react";import{useDidUpdate as ie,useDidMount as Ae}from"@better-typed/react-lifecycle-hooks";import{Command as be,getCommandKey as je}from"@better-typed/hyper-fetch";import{useRef as B}from"react";import{useWillUnmount as qe}from"@better-typed/react-lifecycle-hooks";var _=({command:e,dispatcher:t,logger:r,actions:g,setCacheData:y})=>{let{cache:l,commandManager:d}=e.builder,c=B(null),o=B(null),f=B(null),b=B(null),x=B(null),D=B(null),a=B(null),R=B(null),U=B(null),C=B(new Map),k=B(null),S=n=>{let s=C.current.get(n);s==null||s.unmount(),C.current.delete(n)},v=()=>{let n=C.current;Array.from(n.values()).forEach(i=>{i.unmount()}),n.clear()},h=(n,s,i)=>{var X,w,L,A,Y;let{isOffline:W,isFailed:H,isCanceled:ee}=i;e.offline&&W&&H?(r.debug("Performing offline error callback",{data:s,details:i}),(X=b.current)==null||X.call(b,{response:s[1],command:n,details:i})):ee?(r.debug("Performing abort callback",{data:s,details:i}),(w=f.current)==null||w.call(f,{response:s[1],command:n,details:i})):H?(r.debug("Performing error callback",{data:s,details:i}),(A=o.current)==null||A.call(o,{response:s[1],command:n,details:i})):(r.debug("Performing success callback",{data:s,details:i}),(L=c.current)==null||L.call(c,{response:s[0],command:n,details:i})),(Y=x.current)==null||Y.call(x,{response:s,command:n,details:i})},u=n=>({isLoading:s})=>{let i=!s&&!t.hasRunningRequests(n);(s||i)&&g.setLoading(s,!1)},p=(n,s)=>{var i;(i=R.current)==null||i.call(R,n,s)},m=(n,s)=>{var i;(i=U.current)==null||i.call(U,n,s)},q=n=>s=>{var i;(i=D.current)==null||i.call(D,{command:n,details:s})},P=n=>s=>{var i;(i=a.current)==null||i.call(a,{command:n,details:s})},M=n=>(s,i)=>{h(n,s,i)},O=({requestId:n})=>{S(n)},E=()=>{var n;(n=k.current)==null||n.unmount(),k.current=null},N=n=>{let s=d.events.onLoading(n.queueKey,u(n.queueKey)),i=l.events.onData(n.cacheKey,y),W=()=>{s(),i()};return E(),k.current={unmount:W},W},Q=(n,s)=>{if(!s){let{queueKey:A,cacheKey:Y}=n,se=d.events.onRequestStart(A,q(n)),de=d.events.onResponseStart(A,P(n)),I=d.events.onUploadProgress(A,m),G=d.events.onDownloadProgress(A,p),te=d.events.onResponse(Y,M(n)),Z=()=>{G(),I(),se(),de(),te()};return C.current.set(A,{unmount:Z}),Z}let i=d.events.onRemoveById(s,O),W=d.events.onRequestStartById(s,q(n)),H=d.events.onResponseStartById(s,P(n)),ee=d.events.onResponseById(s,M(n)),X=d.events.onUploadProgressById(s,m),w=d.events.onDownloadProgressById(s,p),L=()=>{i(),w(),X(),W(),H(),ee()};return C.current.set(s,{unmount:L}),L},j=()=>{let{abortKey:n}=e;t.getAllRunningRequest().forEach(i=>{i.command.abortKey===n&&t.delete(i.command.queueKey,i.requestId,n)})};return qe(()=>{v(),E()}),[{abort:j,onSuccess:n=>{c.current=n},onError:n=>{o.current=n},onAbort:n=>{f.current=n},onOfflineError:n=>{b.current=n},onFinished:n=>{x.current=n},onRequestStart:n=>{D.current=n},onResponseStart:n=>{a.current=n},onDownloadProgress:n=>{R.current=n},onUploadProgress:n=>{U.current=n}},{addDataListener:N,clearDataListener:E,addLifecycleListeners:Q,removeLifecycleListener:S,clearLifecycleListeners:v}]};import{useRef as Pe}from"react";import{useWillUnmount as Fe}from"@better-typed/react-lifecycle-hooks";var re=(e=600)=>{let t=Pe(null),r=()=>{t.current!==null&&clearTimeout(t.current),t.current=null},g=(y,l)=>{r(),t.current=setTimeout(()=>{y()},l||e)};return Fe(r),{debounce:g,resetDebounce:r,active:!!t.current}};var $={data:null,error:null,loading:!1,status:null,retries:0,timestamp:null};import{useRef as ye}from"react";import{useDidUpdate as Ce,useForceUpdate as Me}from"@better-typed/react-lifecycle-hooks";var ge=e=>{let t=Object.prototype.toString.call(e);return Array.isArray(e)?!e.length:typeof e=="object"&&e!==null&&t==="[object Object]"?!Object.keys(e).length:!1},oe=(e,t)=>{let r=Object.prototype.toString.call(e),g=Object.prototype.toString.call(t),y=typeof e,l=typeof t,d=o=>y===o&&l===o,c=o=>r===o&&g===o;return r!==g?!1:e===null&&t===null||d("number")&&Number.isNaN(e)&&Number.isNaN(t)||ge(e)&&ge(t)?!0:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:!e.some((o,f)=>!oe(o,t[f])):d("object")&&c("[object Object]")?Object.keys(e).length!==Object.keys(t).length?!1:!Object.entries(e).some(([o,f])=>!oe(f,t[o])):e instanceof Date&&t instanceof Date?+e==+t:e===t};var z=(e,t)=>T({retries:(e==null?void 0:e.retries)||0,timestamp:+new Date,isFailed:!1,isCanceled:!1,isOffline:!1},t),ue=(e,t)=>t?+new Date>+t+e:!0,Ie=(e,t,r)=>!ue(e.cacheTime,r==null?void 0:r.details.timestamp)&&r?r:t?{data:t,details:z(),cacheTime:1e3,clearKey:e.builder.cache.clearKey}:null,we=e=>e?new Date(e):null,ce=(e,t,r)=>{var f,b,x;let{builder:g,cacheKey:y}=r,{cache:l}=g,d=l.get(y),c=Ie(r,e,d),o=t.hasRunningRequests(r.queueKey);return K(T({},$),{data:((f=c==null?void 0:c.data)==null?void 0:f[0])||$.data,error:((b=c==null?void 0:c.data)==null?void 0:b[1])||$.error,status:((x=c==null?void 0:c.data)==null?void 0:x[2])||$.status,retries:(c==null?void 0:c.details.retries)||$.retries,timestamp:we((c==null?void 0:c.details.timestamp)||$.timestamp),loading:o})};var V=({command:e,dispatcher:t,initialData:r,deepCompare:g,dependencyTracking:y,defaultCacheEmitting:l=!0})=>{let{builder:d,cacheKey:c,queueKey:o,cacheTime:f}=e,{cache:b,commandManager:x}=d,D=Me(),a=ye(ce(r,t,e)),R=ye([]),U=()=>{let u=b.get(c);return ue(f,(u==null?void 0:u.details.timestamp)||a.current.timestamp)},C=u=>{R.current.some(m=>u.includes(m))&&D()},k=u=>{R.current.includes(u)||R.current.push(u)};Ce(()=>{a.current.loading=t.hasRunningRequests(o);let u=ce(r,t,e),p=(r==null?void 0:r[0])===a.current.data,m=!!(a.current.data||a.current.error)&&!p,q=!m&&a.current.data,P=m&&!a.current.data;(q||P)&&(a.current=u)},[c,o],!0),Ce(()=>{(()=>{y||Object.keys(a.current).forEach(p=>k(p))})()},[y],!0);let S=(u,p)=>typeof g=="function"?g(u,p):g?oe(u,p):!1,v=u=>ne(void 0,null,function*(){let p={data:u.data[0],error:u.data[1],status:u.data[2],retries:u.details.retries,timestamp:new Date(u.details.timestamp),loading:a.current.loading},m=Object.keys(p).filter(q=>{let P=q,M=a.current[P],O=p[P];return!S(M,O)});a.current=T(T({},a.current),p),C(m)}),h={setData:(u,p=l)=>{if(p){let m=a.current;b.set(e,[u,m.error,m.status],z(a.current))}else a.current.data=u,C(["data"])},setError:(u,p=l)=>{if(p){let m=a.current;b.set(e,[m.data,u,m.status],z(a.current,{isFailed:!!u}))}else a.current.error=u,C(["error"])},setLoading:(u,p=!0)=>{p?x.events.emitLoading(o,"",{queueKey:o,requestId:"",isLoading:u,isRetry:!1,isOffline:!1}):(a.current.loading=u,C(["loading"]))},setStatus:(u,p=l)=>{if(p){let m=a.current;b.set(e,[m.data,m.error,u],z(a.current))}else a.current.status=u,C(["status"])},setRetries:(u,p=l)=>{if(p){let m=a.current;b.set(e,[m.data,m.error,m.status],z(a.current,{retries:u}))}else a.current.retries=u,C(["retries"])},setTimestamp:(u,p=l)=>{if(p){let m=a.current;b.set(e,[m.data,m.error,m.status],z(a.current,{timestamp:+u}))}else a.current.timestamp=u,C(["timestamp"])}};return[a.current,h,{setRenderKey:k,setCacheData:v,getStaleStatus:U}]};import Le,{useContext as Qe,useMemo as Qt,useState as Kt}from"react";var Ke=Le.createContext([{},()=>null]);var J=()=>Qe(Ke);var _t=(e,t=F)=>{let[r]=J(),{dependencies:g=F.dependencies,disabled:y=F.disabled,dependencyTracking:l=F.dependencyTracking,revalidateOnMount:d=F.revalidateOnMount,initialData:c=F.initialData,refresh:o=F.refresh,refreshTime:f=F.refreshTime,refreshBlurred:b=F.refreshBlurred,refreshOnBlur:x=F.refreshOnBlur,refreshOnFocus:D=F.refreshOnFocus,refreshOnReconnect:a=F.refreshOnReconnect,debounce:R=F.debounce,debounceTime:U=F.debounceTime,deepCompare:C=F.deepCompare}=T(T(T({},F),r.useFetchConfig),t),k=JSON.stringify(e.dump()),S=re(U),v=re(f),{cacheKey:h,queueKey:u,builder:p}=e,{cache:m,fetchDispatcher:q,appManager:P,loggerManager:M}=p,O=Be(M.init("useFetch")).current,[E,N,{setRenderKey:Q,setCacheData:j,getStaleStatus:n}]=V({logger:O,command:e,dispatcher:q,initialData:c,deepCompare:C,dependencyTracking:l}),[s,i]=_({logger:O,actions:N,command:e,dispatcher:q,setCacheData:j}),{addDataListener:W,addLifecycleListeners:H,clearDataListener:ee,clearLifecycleListeners:X}=i,w=()=>{y?O.debug("Cannot add to fetch queue",{disabled:y}):(O.debug("Fetching data"),q.add(e))};function L(){if(!o)return;let I=he(f,E.timestamp);O.debug(`Starting refresh counter, request will be send in ${I}ms`),v.debounce(()=>{let G=!P.isFocused,te=q.hasRunningRequests(e.queueKey),Z=q.getIsActiveQueue(e.queueKey),ae=te||Z;(G&&b&&!ae||!G&&!ae)&&(w(),O.debug("Performing refresh request")),L()},I)}let A=I=>{I&&I instanceof be?m.revalidate(je(I)):I&&!(I instanceof be)?m.revalidate(I):(w(),L())},Y=()=>{let I=n(),G=q.getIsActiveQueue(u);(d||I&&!G)&&w()},se=()=>{R?(O.debug("Debouncing request",{queueKey:u,command:e}),S.debounce(()=>w())):w()};return ie(()=>{W(e),H(e);let I=P.events.onFocus(()=>{D&&(w(),L())}),G=P.events.onBlur(()=>{x&&(w(),L())}),te=P.events.onOnline(()=>{a&&(w(),L())}),Z=m.events.onRevalidate(h,w);return()=>{ee(),X(),I(),G(),te(),Z()}},[k],!0),Ae(Y),ie(se,[k,...g]),ie(L,[k,...g,y,o,f],!0),K(T(T({get data(){return Q("data"),E.data},get error(){return Q("error"),E.error},get loading(){return Q("loading"),E.loading},get status(){return Q("status"),E.status},get retries(){return Q("retries"),E.retries},get timestamp(){return Q("timestamp"),E.timestamp}},N),s),{isDebouncing:S.active,revalidate:A})};var he=(e,t)=>{if(t){let r=Date.now()-+t;return r<e?e-r:e}return e};import{DateInterval as Ne}from"@better-typed/hyper-fetch";var F={dependencies:[],disabled:!1,dependencyTracking:!0,revalidateOnMount:!0,initialData:null,refresh:!1,refreshTime:Ne.hour,refreshBlurred:!0,refreshOnBlur:!1,refreshOnFocus:!1,refreshOnReconnect:!1,debounce:!1,debounceTime:400,deepCompare:!0};import{useRef as Re}from"react";import{Command as xe,getCommandKey as We,commandSendRequest as Ge}from"@better-typed/hyper-fetch";import{useDidMount as Je}from"@better-typed/react-lifecycle-hooks";var Dn=(e,t=pe)=>{let[r]=J(),{disabled:g,dependencyTracking:y,initialData:l,debounce:d,debounceTime:c,deepCompare:o}=T(T(T({},pe),r.useSubmitConfig),t),{builder:f}=e,{cache:b,submitDispatcher:x,loggerManager:D}=f,a=Re(D.init("useSubmit")).current,R=re(c),U=Re(()=>null),[C,k,{setRenderKey:S,setCacheData:v}]=V({logger:a,command:e,dispatcher:x,initialData:l,deepCompare:o,dependencyTracking:y}),[h,u]=_({logger:a,actions:k,command:e,dispatcher:x,setCacheData:v}),{addDataListener:p,addLifecycleListeners:m}=u,q=(...O)=>{let E=O[0],N=e.clone(E);if(g)throw a.warning("Cannot submit request",{disabled:g,submitOptions:E}),new Error("Cannot submit request. Option 'disabled' is enabled");let Q=()=>(p(N),Ge(N,K(T({dispatcherType:"submit"},E),{onSettle:(j,n)=>{var s;m(N,j),(s=E==null?void 0:E.onSettle)==null||s.call(E,j,n)}})));return new Promise(j=>{(()=>ne(void 0,null,function*(){if(a.debug("Submitting request",{disabled:g,submitOptions:E}),d)U.current=s=>{U.current(s),j(s)},R.debounce(()=>ne(void 0,null,function*(){let s=U.current;U.current=()=>null;let i=yield Q();s(i)}));else{let s=yield Q();j(s)}}))()})},P=O=>{!O||(O&&O instanceof xe?b.revalidate(We(O)):O instanceof xe||b.revalidate(O))},M={onSubmitSuccess:h.onSuccess,onSubmitError:h.onError,onSubmitFinished:h.onFinished,onSubmitRequestStart:h.onRequestStart,onSubmitResponseStart:h.onResponseStart,onSubmitDownloadProgress:h.onDownloadProgress,onSubmitUploadProgress:h.onUploadProgress,onSubmitOfflineError:h.onOfflineError,onSubmitAbort:h.onAbort};return Je(()=>{p(e)}),K(T(T({submit:q,get data(){return S("data"),C.data},get error(){return S("error"),C.error},get submitting(){return S("loading"),C.loading},get status(){return S("status"),C.status},get retries(){return S("retries"),C.retries},get timestamp(){return S("timestamp"),C.timestamp},abort:h.abort},k),M),{isDebouncing:R.active,revalidate:P})};var pe={disabled:!1,dependencyTracking:!0,cacheOnMount:!0,initialData:null,debounce:!1,debounceTime:400,suspense:!1,shouldThrow:!1,invalidate:[],deepCompare:!0};import{useState as Se,useRef as $e}from"react";import{getCommandDispatcher as ze}from"@better-typed/hyper-fetch";import{useDidMount as He,useDidUpdate as Xe}from"@better-typed/react-lifecycle-hooks";var Nn=(e,t=le)=>{let[r]=J(),{queueType:g="auto"}=T(T(T({},le),r.useQueueConfig),t),{abortKey:y,queueKey:l,builder:d}=e,{commandManager:c}=d,[o]=ze(e,g),f=$e(null),[b,x]=Se(!1),[D,a]=Se([]),R=v=>v.map(h=>K(T({},h),{stopRequest:()=>o.stopRequest(l,h.requestId),startRequest:()=>o.startRequest(l,h.requestId),deleteRequest:()=>o.delete(l,h.requestId,y)})),U=(v,h)=>{a(u=>u.map(p=>p.requestId===v?T(T({},p),h):p))},C=()=>{let v=o.getQueue(l);x(v.stopped),a(R(v.requests))},k=v=>{x(v.stopped),a(R(v.requests))},S=()=>{var q;let v=o.events.onQueueChange(l,k),h=o.events.onQueueStatus(l,k),u=c.events.onDownloadProgress(l,(P,{requestId:M})=>{U(M,{downloading:P})}),p=c.events.onUploadProgress(l,(P,{requestId:M})=>{U(M,{uploading:P})}),m=()=>{h(),v(),u(),p()};return(q=f.current)==null||q.call(f),f.current=m,m};return He(C),Xe(S,[b,D,a,x],!0),{stopped:b,requests:D,stop:()=>o.stop(l),pause:()=>o.pause(l),start:()=>o.start(l)}};var le={queueType:"auto"};import{useRef as Ye}from"react";import{getCommandDispatcher as Ze,Command as _e,getCommandKey as Ve}from"@better-typed/hyper-fetch";var rr=(e,t=me)=>{let{cacheKey:r,builder:g}=e,{cache:y,loggerManager:l}=g,d=Ye(l.init("useCache")).current,[c]=Ze(e),[o]=J(),{dependencyTracking:f,initialData:b,deepCompare:x}=T(T(T({},me),o.useCacheConfig),t),[D,a,{setRenderKey:R,setCacheData:U}]=V({logger:d,command:e,dispatcher:c,initialData:b,deepCompare:x,dependencyTracking:f}),[C]=_({logger:d,actions:a,command:e,dispatcher:c,setCacheData:U}),k=S=>{S instanceof _e?y.revalidate(Ve(S,!0)):S?y.revalidate(S):y.revalidate(r)};return K(T({get data(){return R("data"),D.data},get error(){return R("error"),D.error},get loading(){return R("loading"),D.loading},get status(){return R("status"),D.status},get retries(){return R("retries"),D.retries},get timestamp(){return R("timestamp"),D.timestamp},onCacheError:C.onError,onCacheSuccess:C.onSuccess,onCacheChange:C.onFinished},a),{revalidate:k})};var me={dependencyTracking:!0,initialData:null,deepCompare:!0};import{useState as Ee}from"react";import{useDidMount as et}from"@better-typed/react-lifecycle-hooks";var mr=e=>{let[t,r]=Ee(e.appManager.isOnline),[g,y]=Ee(e.appManager.isFocused),l=()=>{let o=e.appManager.events.onOnline(()=>r(!0)),f=e.appManager.events.onOffline(()=>r(!1)),b=e.appManager.events.onFocus(()=>y(!0)),x=e.appManager.events.onBlur(()=>y(!1));return()=>{o(),f(),b(),x()}},d=o=>{e.appManager.setOnline(o)},c=o=>{e.appManager.setFocused(o)};return et(l),{isOnline:t,isFocused:g,setOnline:d,setFocused:c}};export{z as getDetailsState,ce as getInitialState,he as getRefreshTime,we as getTimestamp,Ie as getValidCacheData,$ as initialState,ge as isEmpty,oe as isEqual,ue as isStaleCacheData,mr as useAppManager,rr as useCache,me as useCacheDefaultOptions,_ as useCommandEvents,re as useDebounce,_t as useFetch,F as useFetchDefaultOptions,Nn as useQueue,le as useQueueDefaultOptions,Dn as useSubmit,pe as useSubmitDefaultOptions,V as useTrackedState}; | ||
var qe=Object.defineProperty,Pe=Object.defineProperties;var Fe=Object.getOwnPropertyDescriptors;var Ce=Object.getOwnPropertySymbols;var Ie=Object.prototype.hasOwnProperty,we=Object.prototype.propertyIsEnumerable;var be=(e,n,r)=>n in e?qe(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r,d=(e,n)=>{for(var r in n||(n={}))Ie.call(n,r)&&be(e,r,n[r]);if(Ce)for(var r of Ce(n))we.call(n,r)&&be(e,r,n[r]);return e},w=(e,n)=>Pe(e,Fe(n));var ne=(e,n,r)=>new Promise((g,y)=>{var m=o=>{try{i(r.next(o))}catch(T){y(T)}},f=o=>{try{i(r.throw(o))}catch(T){y(T)}},i=o=>o.done?g(o.value):Promise.resolve(o.value).then(m,f);i((r=r.apply(e,n)).next())});import{useRef as Ne}from"react";import{useDidUpdate as fe,useDidMount as $e}from"@better-typed/react-lifecycle-hooks";import{useDebounce as Se,useThrottle as Ge}from"@better-typed/react-performance-hooks";import{Command as Ee,getCommandKey as Je}from"@better-typed/hyper-fetch";import{useRef as A}from"react";import{useWillUnmount as Me}from"@better-typed/react-lifecycle-hooks";var V=({command:e,dispatcher:n,logger:r,actions:g,setCacheData:y})=>{let{cache:m,commandManager:f}=e.builder,i=A(null),o=A(null),T=A(null),C=A(null),R=A(null),E=A(null),a=A(null),b=A(null),D=A(null),h=A(new Map),v=A(null),q=t=>{let u=h.current.get(t);u==null||u.unmount(),h.current.delete(t)},O=()=>{let t=h.current;Array.from(t.values()).forEach(c=>{c.unmount()}),t.clear()},x=(t,u,c)=>{var K,G,H,N,Z;let{isOffline:F,isFailed:$,isCanceled:L}=c;e.offline&&F&&$?(r.debug("Performing offline error callback",{data:u,details:c}),(K=C.current)==null||K.call(C,{response:u[1],command:t,details:c})):L?(r.debug("Performing abort callback",{data:u,details:c}),(G=T.current)==null||G.call(T,{response:u[1],command:t,details:c})):$?(r.debug("Performing error callback",{data:u,details:c}),(N=o.current)==null||N.call(o,{response:u[1],command:t,details:c})):(r.debug("Performing success callback",{data:u,details:c}),(H=i.current)==null||H.call(i,{response:u[0],command:t,details:c})),(Z=R.current)==null||Z.call(R,{response:u,command:t,details:c})},s=t=>({isLoading:u})=>{let c=!u&&!n.hasRunningRequests(t);(u||c)&&g.setLoading(u,!1)},p=(t,u)=>{var c;(c=b.current)==null||c.call(b,t,u)},l=(t,u)=>{var c;(c=D.current)==null||c.call(D,t,u)},S=t=>u=>{var c;(c=E.current)==null||c.call(E,{command:t,details:u})},P=t=>u=>{var c;(c=a.current)==null||c.call(a,{command:t,details:u})},U=t=>(u,c)=>{x(t,u,c)},j=({requestId:t})=>{q(t)},z=()=>{var t;(t=v.current)==null||t.unmount(),v.current=null},B=t=>{let u=f.events.onLoading(t.queueKey,s(t.queueKey)),c=m.events.onData(t.cacheKey,y),F=()=>{u(),c()};return z(),v.current={unmount:F},F},te=(t,u)=>{if(!u){let{queueKey:N,cacheKey:Z}=t,Q=f.events.onRequestStart(N,S(t)),J=f.events.onResponseStart(N,P(t)),se=f.events.onUploadProgress(N,l),ae=f.events.onDownloadProgress(N,p),ue=f.events.onResponse(Z,U(t)),ce=()=>{ae(),se(),Q(),J(),ue()};return h.current.set(N,{unmount:ce}),ce}let c=f.events.onRemoveById(u,j),F=f.events.onRequestStartById(u,S(t)),$=f.events.onResponseStartById(u,P(t)),L=f.events.onResponseById(u,U(t)),K=f.events.onUploadProgressById(u,l),G=f.events.onDownloadProgressById(u,p),H=()=>{c(),G(),K(),F(),$(),L()};return h.current.set(u,{unmount:H}),H},M=()=>{let{abortKey:t}=e;n.getAllRunningRequest().forEach(c=>{c.command.abortKey===t&&n.delete(c.command.queueKey,c.requestId,t)})};return Me(()=>{O(),z()}),[{abort:M,onSuccess:t=>{i.current=t},onError:t=>{o.current=t},onAbort:t=>{T.current=t},onOfflineError:t=>{C.current=t},onFinished:t=>{R.current=t},onRequestStart:t=>{E.current=t},onResponseStart:t=>{a.current=t},onDownloadProgress:t=>{b.current=t},onUploadProgress:t=>{D.current=t}},{addDataListener:B,clearDataListener:z,addLifecycleListeners:te,removeLifecycleListener:q,clearLifecycleListeners:O}]};var X={data:null,error:null,loading:!1,status:null,retries:0,timestamp:null};import{useRef as Re}from"react";import{useDidUpdate as xe,useForceUpdate as Ke}from"@better-typed/react-lifecycle-hooks";var he=e=>{let n=Object.prototype.toString.call(e);return Array.isArray(e)?!e.length:typeof e=="object"&&e!==null&&n==="[object Object]"?!Object.keys(e).length:!1},re=(e,n)=>{let r=Object.prototype.toString.call(e),g=Object.prototype.toString.call(n),y=typeof e,m=typeof n,f=o=>y===o&&m===o,i=o=>r===o&&g===o;return r!==g?!1:e===null&&n===null||f("number")&&Number.isNaN(e)&&Number.isNaN(n)||he(e)&&he(n)?!0:Array.isArray(e)&&Array.isArray(n)?e.length!==n.length?!1:!e.some((o,T)=>!re(o,n[T])):f("object")&&i("[object Object]")?Object.keys(e).length!==Object.keys(n).length?!1:!Object.entries(e).some(([o,T])=>!re(T,n[o])):e instanceof Date&&n instanceof Date?+e==+n:e===n};var oe=e=>w(d({},e),{throttle:void 0,debounce:void 0});var Y=(e,n)=>d({retries:(e==null?void 0:e.retries)||0,timestamp:+new Date,isFailed:!1,isCanceled:!1,isOffline:!1},n),me=(e,n)=>n?+new Date>+n+e:!0,Le=(e,n,r)=>!me(e.cacheTime,r==null?void 0:r.details.timestamp)&&r?r:n?{data:n,details:Y(),cacheTime:1e3,clearKey:e.builder.cache.clearKey}:null,Be=e=>e?new Date(e):null,de=(e,n,r)=>{var T,C,R;let{builder:g,cacheKey:y}=r,{cache:m}=g,f=m.get(y),i=Le(r,e,f),o=n.hasRunningRequests(r.queueKey);return w(d({},X),{data:((T=i==null?void 0:i.data)==null?void 0:T[0])||X.data,error:((C=i==null?void 0:i.data)==null?void 0:C[1])||X.error,status:((R=i==null?void 0:i.data)==null?void 0:R[2])||X.status,retries:(i==null?void 0:i.details.retries)||X.retries,timestamp:Be((i==null?void 0:i.details.timestamp)||X.timestamp),loading:o})};var ee=({command:e,dispatcher:n,initialData:r,deepCompare:g,dependencyTracking:y,defaultCacheEmitting:m=!0})=>{let{builder:f,cacheKey:i,queueKey:o,cacheTime:T}=e,{cache:C,commandManager:R}=f,E=Ke(),a=Re(de(r,n,e)),b=Re([]),D=()=>{let s=C.get(i);return me(T,(s==null?void 0:s.details.timestamp)||a.current.timestamp)},h=s=>{b.current.some(l=>s.includes(l))&&E()},v=s=>{b.current.includes(s)||b.current.push(s)};xe(()=>{a.current.loading=n.hasRunningRequests(o);let s=de(r,n,e),p=(r==null?void 0:r[0])===a.current.data,l=!!(a.current.data||a.current.error)&&!p,S=!l&&a.current.data,P=l&&!a.current.data;(S||P)&&(a.current=s)},[i,o],!0),xe(()=>{(()=>{y||Object.keys(a.current).forEach(p=>v(p))})()},[y],!0);let q=(s,p)=>typeof g=="function"?g(s,p):g?re(s,p):!1,O=s=>ne(void 0,null,function*(){let p={data:s.data[0],error:s.data[1],status:s.data[2],retries:s.details.retries,timestamp:new Date(s.details.timestamp),loading:a.current.loading},l=Object.keys(p).filter(S=>{let P=S,U=a.current[P],j=p[P];return!q(U,j)});a.current=d(d({},a.current),p),h(l)}),x={setData:(s,p=m)=>{if(p){let l=a.current;C.set(e,[s,l.error,l.status],Y(a.current))}else a.current.data=s,h(["data"])},setError:(s,p=m)=>{if(p){let l=a.current;C.set(e,[l.data,s,l.status],Y(a.current,{isFailed:!!s}))}else a.current.error=s,h(["error"])},setLoading:(s,p=!0)=>{p?R.events.emitLoading(o,"",{queueKey:o,requestId:"",isLoading:s,isRetry:!1,isOffline:!1}):(a.current.loading=s,h(["loading"]))},setStatus:(s,p=m)=>{if(p){let l=a.current;C.set(e,[l.data,l.error,s],Y(a.current))}else a.current.status=s,h(["status"])},setRetries:(s,p=m)=>{if(p){let l=a.current;C.set(e,[l.data,l.error,l.status],Y(a.current,{retries:s}))}else a.current.retries=s,h(["retries"])},setTimestamp:(s,p=m)=>{if(p){let l=a.current;C.set(e,[l.data,l.error,l.status],Y(a.current,{timestamp:+s}))}else a.current.timestamp=s,h(["timestamp"])}};return[a.current,x,{setRenderKey:v,setCacheData:O,getStaleStatus:D}]};import Qe,{useContext as Ae,useMemo as Qt,useState as At}from"react";var je=Qe.createContext([{},()=>null]);var W=()=>Ae(je);var nn=(e,n=k)=>{let[r]=W(),{dependencies:g=k.dependencies,disabled:y=k.disabled,dependencyTracking:m=k.dependencyTracking,revalidateOnMount:f=k.revalidateOnMount,initialData:i=k.initialData,refresh:o=k.refresh,refreshTime:T=k.refreshTime,refreshBlurred:C=k.refreshBlurred,refreshOnBlur:R=k.refreshOnBlur,refreshOnFocus:E=k.refreshOnFocus,refreshOnReconnect:a=k.refreshOnReconnect,bounce:b=k.bounce,bounceType:D=k.bounceType,bounceTime:h=k.bounceTime,deepCompare:v=k.deepCompare}=d(d(d({},k),r.useFetchConfig),n),q=JSON.stringify(e.dump()),O=Se(h),x=Ge(h),s=Se(T),{cacheKey:p,queueKey:l,builder:S}=e,{cache:P,fetchDispatcher:U,appManager:j,loggerManager:z}=S,B=Ne(z.init("useFetch")).current,te=D==="throttle"?x:O,M=D==="throttle"?x.throttle:O.debounce,[t,u,{setRenderKey:c,setCacheData:F,getStaleStatus:$}]=ee({logger:B,command:e,dispatcher:U,initialData:i,deepCompare:v,dependencyTracking:m}),[L,K]=V({logger:B,actions:u,command:e,dispatcher:U,setCacheData:F}),{addDataListener:G,addLifecycleListeners:H,clearDataListener:N,clearLifecycleListeners:Z}=K,Q=()=>{y?B.debug("Cannot add to fetch queue",{disabled:y}):(B.debug("Fetching data"),U.add(e))};function J(){if(!o)return;let I=Oe(T,t.timestamp);B.debug(`Starting refresh counter, request will be send in ${I}ms`),s.debounce(()=>{let _=!j.isFocused,ie=U.hasRunningRequests(e.queueKey),pe=U.getIsActiveQueue(e.queueKey),le=ie||pe;(_&&C&&!le||!_&&!le)&&(Q(),B.debug("Performing refresh request")),J()},I)}let se=I=>{I&&I instanceof Ee?P.revalidate(Je(I)):I&&!(I instanceof Ee)?P.revalidate(I):(Q(),J())},ae=()=>{let I=$(),_=U.getIsActiveQueue(l);(f||I&&!_)&&Q()},ue=()=>{b?(B.debug(`Bounce request with ${D}`,{queueKey:l,command:e}),M(()=>Q())):Q()};return fe(()=>{G(e),H(e);let I=j.events.onFocus(()=>{E&&(Q(),J())}),_=j.events.onBlur(()=>{R&&(Q(),J())}),ie=j.events.onOnline(()=>{a&&(Q(),J())}),pe=P.events.onRevalidate(p,Q);return()=>{N(),Z(),I(),_(),ie(),pe()}},[q],!0),$e(ae),fe(ue,[q,...g]),fe(J,[q,...g,y,o,T],!0),w(d(d({get data(){return c("data"),t.data},get error(){return c("error"),t.error},get loading(){return c("loading"),t.loading},get status(){return c("status"),t.status},get retries(){return c("retries"),t.retries},get timestamp(){return c("timestamp"),t.timestamp},bounce:oe(te)},u),L),{revalidate:se})};var Oe=(e,n)=>{if(n){let r=Date.now()-+n;return r<e?e-r:e}return e};import{DateInterval as We}from"@better-typed/hyper-fetch";var k={dependencies:[],disabled:!1,dependencyTracking:!0,revalidateOnMount:!0,initialData:null,refresh:!1,refreshTime:We.hour,refreshBlurred:!0,refreshOnBlur:!1,refreshOnFocus:!1,refreshOnReconnect:!1,bounce:!1,bounceType:"debounce",bounceTime:400,deepCompare:!0};import{useRef as De}from"react";import{Command as ve,getCommandKey as ze,commandSendRequest as He}from"@better-typed/hyper-fetch";import{useDidMount as Xe}from"@better-typed/react-lifecycle-hooks";import{useDebounce as Ye,useThrottle as Ze}from"@better-typed/react-performance-hooks";var Pn=(e,n=Te)=>{let[r]=W(),{disabled:g,dependencyTracking:y,initialData:m,bounce:f,bounceType:i,bounceTime:o,deepCompare:T}=d(d(d({},Te),r.useSubmitConfig),n),{builder:C}=e,{cache:R,submitDispatcher:E,loggerManager:a}=C,b=De(a.init("useSubmit")).current,D=Ye(o),h=Ze(o),v=De(()=>null),q=i==="throttle"?h:D,O=i==="throttle"?h.throttle:D.debounce,[x,s,{setRenderKey:p,setCacheData:l}]=ee({logger:b,command:e,dispatcher:E,initialData:m,deepCompare:T,dependencyTracking:y}),[S,P]=V({logger:b,actions:s,command:e,dispatcher:E,setCacheData:l}),{addDataListener:U,addLifecycleListeners:j}=P,z=(...M)=>{let t=M[0],u=e.clone(t);if(g)throw b.warning("Cannot submit request",{disabled:g,submitOptions:t}),new Error("Cannot submit request. Option 'disabled' is enabled");let c=()=>(U(u),He(u,w(d({dispatcherType:"submit"},t),{onSettle:(F,$)=>{var L;j(u,F),(L=t==null?void 0:t.onSettle)==null||L.call(t,F,$)}})));return new Promise(F=>{(()=>ne(void 0,null,function*(){if(b.debug("Submitting request",{disabled:g,submitOptions:t}),f){let L=v.current;v.current=K=>{L(K),F(K)},O(()=>ne(void 0,null,function*(){let K=v.current;v.current=()=>null;let G=yield c();K(G)}))}else{let L=yield c();F(L)}}))()})},B=M=>{!M||(M&&M instanceof ve?R.revalidate(ze(M)):M instanceof ve||R.revalidate(M))},te={onSubmitSuccess:S.onSuccess,onSubmitError:S.onError,onSubmitFinished:S.onFinished,onSubmitRequestStart:S.onRequestStart,onSubmitResponseStart:S.onResponseStart,onSubmitDownloadProgress:S.onDownloadProgress,onSubmitUploadProgress:S.onUploadProgress,onSubmitOfflineError:S.onOfflineError,onSubmitAbort:S.onAbort};return Xe(()=>{U(e)}),w(d(d({submit:z,get data(){return p("data"),x.data},get error(){return p("error"),x.error},get submitting(){return p("loading"),x.loading},get status(){return p("status"),x.status},get retries(){return p("retries"),x.retries},get timestamp(){return p("timestamp"),x.timestamp},abort:S.abort},s),te),{bounce:oe(q),revalidate:B})};var Te={disabled:!1,dependencyTracking:!0,initialData:null,bounce:!1,bounceType:"debounce",bounceTime:400,deepCompare:!0};import{useState as Ue,useRef as _e}from"react";import{getCommandDispatcher as Ve}from"@better-typed/hyper-fetch";import{useDidMount as et,useDidUpdate as tt}from"@better-typed/react-lifecycle-hooks";var Hn=(e,n=ge)=>{let[r]=W(),{queueType:g="auto"}=d(d(d({},ge),r.useQueueConfig),n),{abortKey:y,queueKey:m,builder:f}=e,{commandManager:i}=f,[o]=Ve(e,g),T=_e(null),[C,R]=Ue(!1),[E,a]=Ue([]),b=O=>O.map(x=>w(d({},x),{stopRequest:()=>o.stopRequest(m,x.requestId),startRequest:()=>o.startRequest(m,x.requestId),deleteRequest:()=>o.delete(m,x.requestId,y)})),D=(O,x)=>{a(s=>s.map(p=>p.requestId===O?d(d({},p),x):p))},h=()=>{let O=o.getQueue(m);R(O.stopped),a(b(O.requests))},v=O=>{R(O.stopped),a(b(O.requests))},q=()=>{var S;let O=o.events.onQueueChange(m,v),x=o.events.onQueueStatus(m,v),s=i.events.onDownloadProgress(m,(P,{requestId:U})=>{D(U,{downloading:P})}),p=i.events.onUploadProgress(m,(P,{requestId:U})=>{D(U,{uploading:P})}),l=()=>{x(),O(),s(),p()};return(S=T.current)==null||S.call(T),T.current=l,l};return et(h),tt(q,[C,E,a,R],!0),{stopped:C,requests:E,stop:()=>o.stop(m),pause:()=>o.pause(m),start:()=>o.start(m)}};var ge={queueType:"auto"};import{useRef as nt}from"react";import{getCommandDispatcher as rt,Command as ot,getCommandKey as st}from"@better-typed/hyper-fetch";var ir=(e,n=ye)=>{let{cacheKey:r,builder:g}=e,{cache:y,loggerManager:m}=g,f=nt(m.init("useCache")).current,[i]=rt(e),[o]=W(),{dependencyTracking:T,initialData:C,deepCompare:R}=d(d(d({},ye),o.useCacheConfig),n),[E,a,{setRenderKey:b,setCacheData:D}]=ee({logger:f,command:e,dispatcher:i,initialData:C,deepCompare:R,dependencyTracking:T}),[h]=V({logger:f,actions:a,command:e,dispatcher:i,setCacheData:D}),v=q=>{q instanceof ot?y.revalidate(st(q,!0)):q?y.revalidate(q):y.revalidate(r)};return w(d({get data(){return b("data"),E.data},get error(){return b("error"),E.error},get loading(){return b("loading"),E.loading},get status(){return b("status"),E.status},get retries(){return b("retries"),E.retries},get timestamp(){return b("timestamp"),E.timestamp},onCacheError:h.onError,onCacheSuccess:h.onSuccess,onCacheChange:h.onFinished},a),{revalidate:v})};var ye={dependencyTracking:!0,initialData:null,deepCompare:!0};import{useState as ke}from"react";import{useDidMount as at}from"@better-typed/react-lifecycle-hooks";var Cr=e=>{let[n,r]=ke(e.appManager.isOnline),[g,y]=ke(e.appManager.isFocused),m=()=>{let o=e.appManager.events.onOnline(()=>r(!0)),T=e.appManager.events.onOffline(()=>r(!1)),C=e.appManager.events.onFocus(()=>y(!0)),R=e.appManager.events.onBlur(()=>y(!1));return()=>{o(),T(),C(),R()}},f=o=>{e.appManager.setOnline(o)},i=o=>{e.appManager.setFocused(o)};return at(m),{isOnline:n,isFocused:g,setOnline:f,setFocused:i}};export{Y as getDetailsState,de as getInitialState,Oe as getRefreshTime,Be as getTimestamp,Le as getValidCacheData,X as initialState,he as isEmpty,re as isEqual,me as isStaleCacheData,Cr as useAppManager,ir as useCache,ye as useCacheDefaultOptions,V as useCommandEvents,nn as useFetch,k as useFetchDefaultOptions,Hn as useQueue,ge as useQueueDefaultOptions,Pn as useSubmit,Te as useSubmitDefaultOptions,ee as useTrackedState}; | ||
//# sourceMappingURL=index.esm.js.map |
@@ -52,8 +52,12 @@ import { CommandInstance, ExtractResponse, ExtractError, CacheValueType } from "@better-typed/hyper-fetch"; | ||
*/ | ||
debounce?: boolean; | ||
bounce?: boolean; | ||
/** | ||
* How long it should debounce requests. | ||
* Possibility to choose between debounce and throttle approaches | ||
*/ | ||
debounceTime?: number; | ||
bounceType?: "debounce" | "throttle"; | ||
/** | ||
* How long it should bounce requests. | ||
*/ | ||
bounceTime?: number; | ||
/** | ||
* Deep comparison function for hook to check for equality in incoming data, to limit rerenders. | ||
@@ -65,5 +69,14 @@ */ | ||
/** | ||
* Is debounce active at given moment | ||
* Data related to current state of the bounce usage | ||
*/ | ||
isDebouncing: boolean; | ||
bounce: { | ||
/** | ||
* Active state of the bounce method | ||
*/ | ||
active: boolean; | ||
/** | ||
* Method to stop the active bounce method execution | ||
*/ | ||
reset: () => void; | ||
}; | ||
/** | ||
@@ -70,0 +83,0 @@ * Revalidate current command resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey). |
@@ -1,12 +0,7 @@ | ||
export declare const useSubmitDefaultOptions: { | ||
disabled: boolean; | ||
dependencyTracking: boolean; | ||
cacheOnMount: boolean; | ||
initialData: any; | ||
debounce: boolean; | ||
debounceTime: number; | ||
suspense: boolean; | ||
shouldThrow: boolean; | ||
invalidate: any[]; | ||
deepCompare: boolean; | ||
import { CommandInstance, RequiredKeys } from "@better-typed/hyper-fetch"; | ||
import { UseSubmitOptionsType } from "./use-submit.types"; | ||
declare type DefaultOptionsType = RequiredKeys<Omit<UseSubmitOptionsType<CommandInstance>, "initialData">> & { | ||
initialData: null; | ||
}; | ||
export declare const useSubmitDefaultOptions: DefaultOptionsType; | ||
export {}; |
@@ -16,8 +16,12 @@ import { CacheValueType, ExtractError, ExtractResponse, CommandInstance, ExtractClientReturnType } from "@better-typed/hyper-fetch"; | ||
*/ | ||
debounce?: boolean; | ||
bounce?: boolean; | ||
/** | ||
* How long it should debounce requests. | ||
* Possibility to choose between debounce and throttle approaches | ||
*/ | ||
debounceTime?: number; | ||
bounceType?: "debounce" | "throttle"; | ||
/** | ||
* How long it should bounce requests. | ||
*/ | ||
bounceTime?: number; | ||
/** | ||
* If `true` it will rerender only when values used by our component gets changed. Otherwise it will rerender on any change. | ||
@@ -81,5 +85,14 @@ */ | ||
/** | ||
* Is debounce active at given moment | ||
* Data related to current state of the bounce usage | ||
*/ | ||
isDebouncing: boolean; | ||
bounce: { | ||
/** | ||
* Active state of the bounce method | ||
*/ | ||
active: boolean; | ||
/** | ||
* Method to stop the active bounce method execution | ||
*/ | ||
reset: () => void; | ||
}; | ||
/** | ||
@@ -86,0 +99,0 @@ * Revalidate current command resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey). |
export * from "./deep-equal.utils"; | ||
export * from "./bounce.utils"; |
{ | ||
"name": "@better-typed/react-hyper-fetch", | ||
"version": "1.3.1", | ||
"version": "1.4.0", | ||
"private": false, | ||
@@ -31,3 +31,4 @@ "description": "React hooks and utils for the hyper-fetch", | ||
"dependencies": { | ||
"@better-typed/react-lifecycle-hooks": "^1.0.5" | ||
"@better-typed/react-lifecycle-hooks": "^1.0.5", | ||
"@better-typed/react-performance-hooks": "^0.8.0" | ||
}, | ||
@@ -34,0 +35,0 @@ "lint-staged": { |
export * from "./use-command-events"; | ||
export * from "./use-debounce"; | ||
export * from "./use-tracked-state"; |
@@ -21,5 +21,6 @@ import { DateInterval, CommandInstance, RequiredKeys } from "@better-typed/hyper-fetch"; | ||
refreshOnReconnect: false, | ||
debounce: false, | ||
debounceTime: 400, | ||
bounce: false, | ||
bounceType: "debounce", | ||
bounceTime: 400, | ||
deepCompare: true, | ||
}; |
import { useRef } from "react"; | ||
import { useDidUpdate, useDidMount } from "@better-typed/react-lifecycle-hooks"; | ||
import { useDebounce, useThrottle } from "@better-typed/react-performance-hooks"; | ||
import { CommandInstance, Command, getCommandKey } from "@better-typed/hyper-fetch"; | ||
import { useDebounce, useCommandEvents, useTrackedState } from "helpers"; | ||
import { useCommandEvents, useTrackedState } from "helpers"; | ||
import { UseFetchOptionsType, useFetchDefaultOptions, UseFetchReturnType, getRefreshTime } from "use-fetch"; | ||
import { useConfigProvider } from "config-provider"; | ||
import { getBounceData } from "utils"; | ||
@@ -33,4 +35,5 @@ /** | ||
refreshOnReconnect = useFetchDefaultOptions.refreshOnReconnect, | ||
debounce = useFetchDefaultOptions.debounce, | ||
debounceTime = useFetchDefaultOptions.debounceTime, | ||
bounce = useFetchDefaultOptions.bounce, | ||
bounceType = useFetchDefaultOptions.bounceType, | ||
bounceTime = useFetchDefaultOptions.bounceTime, | ||
deepCompare = useFetchDefaultOptions.deepCompare, | ||
@@ -44,3 +47,4 @@ } = { | ||
const updateKey = JSON.stringify(command.dump()); | ||
const requestDebounce = useDebounce(debounceTime); | ||
const requestDebounce = useDebounce(bounceTime); | ||
const requestThrottle = useThrottle(bounceTime); | ||
const refreshDebounce = useDebounce(refreshTime); | ||
@@ -52,2 +56,4 @@ | ||
const logger = useRef(loggerManager.init("useFetch")).current; | ||
const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce; | ||
const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce; | ||
@@ -149,5 +155,5 @@ /** | ||
*/ | ||
if (debounce) { | ||
logger.debug("Debouncing request", { queueKey, command }); | ||
requestDebounce.debounce(() => handleFetch()); | ||
if (bounce) { | ||
logger.debug(`Bounce request with ${bounceType}`, { queueKey, command }); | ||
bounceFunction(() => handleFetch()); | ||
} else { | ||
@@ -249,7 +255,7 @@ handleFetch(); | ||
}, | ||
bounce: getBounceData(bounceData), | ||
...actions, | ||
...callbacks, | ||
isDebouncing: requestDebounce.active, | ||
revalidate, | ||
}; | ||
}; |
@@ -54,8 +54,12 @@ import { CommandInstance, ExtractResponse, ExtractError, CacheValueType } from "@better-typed/hyper-fetch"; | ||
*/ | ||
debounce?: boolean; | ||
bounce?: boolean; | ||
/** | ||
* How long it should debounce requests. | ||
* Possibility to choose between debounce and throttle approaches | ||
*/ | ||
debounceTime?: number; | ||
bounceType?: "debounce" | "throttle"; | ||
/** | ||
* How long it should bounce requests. | ||
*/ | ||
bounceTime?: number; | ||
/** | ||
* Deep comparison function for hook to check for equality in incoming data, to limit rerenders. | ||
@@ -70,5 +74,14 @@ */ | ||
/** | ||
* Is debounce active at given moment | ||
* Data related to current state of the bounce usage | ||
*/ | ||
isDebouncing: boolean; | ||
bounce: { | ||
/** | ||
* Active state of the bounce method | ||
*/ | ||
active: boolean; | ||
/** | ||
* Method to stop the active bounce method execution | ||
*/ | ||
reset: () => void; | ||
}; | ||
/** | ||
@@ -75,0 +88,0 @@ * Revalidate current command resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey). |
@@ -1,12 +0,17 @@ | ||
export const useSubmitDefaultOptions = { | ||
disabled: false, // disables submitting possibility | ||
dependencyTracking: true, // if true -> accessors rerender only when used. If false -> rerenders on every change | ||
cacheOnMount: true, // should use data from cache (?) on initialization - to be checked whether is useful | ||
import { CommandInstance, RequiredKeys } from "@better-typed/hyper-fetch"; | ||
import { UseSubmitOptionsType } from "./use-submit.types"; | ||
type DefaultOptionsType = RequiredKeys<Omit<UseSubmitOptionsType<CommandInstance>, "initialData">> & { | ||
initialData: null; | ||
}; | ||
export const useSubmitDefaultOptions: DefaultOptionsType = { | ||
disabled: false, | ||
dependencyTracking: true, | ||
initialData: null, | ||
debounce: false, | ||
debounceTime: 400, // milliseconds | ||
suspense: false, // TBD | ||
shouldThrow: false, // TBD | ||
invalidate: [], | ||
bounce: false, | ||
bounceType: "debounce", | ||
bounceTime: 400, | ||
deepCompare: true, | ||
}; |
@@ -14,6 +14,8 @@ import { useRef } from "react"; | ||
import { useDidMount } from "@better-typed/react-lifecycle-hooks"; | ||
import { useDebounce, useThrottle } from "@better-typed/react-performance-hooks"; | ||
import { useDebounce, useTrackedState, useCommandEvents } from "helpers"; | ||
import { useTrackedState, useCommandEvents } from "helpers"; | ||
import { UseSubmitOptionsType, useSubmitDefaultOptions, UseSubmitReturnType } from "use-submit"; | ||
import { useConfigProvider } from "config-provider"; | ||
import { getBounceData } from "utils"; | ||
@@ -32,3 +34,3 @@ /** | ||
const [globalConfig] = useConfigProvider(); | ||
const { disabled, dependencyTracking, initialData, debounce, debounceTime, deepCompare } = { | ||
const { disabled, dependencyTracking, initialData, bounce, bounceType, bounceTime, deepCompare } = { | ||
...useSubmitDefaultOptions, | ||
@@ -47,7 +49,11 @@ ...globalConfig.useSubmitConfig, | ||
const logger = useRef(loggerManager.init("useSubmit")).current; | ||
const requestDebounce = useDebounce(debounceTime); | ||
const debounceResolve = useRef<(value: ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>) => void>( | ||
const requestDebounce = useDebounce(bounceTime); | ||
const requestThrottle = useThrottle(bounceTime); | ||
const bounceResolver = useRef<(value: ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>) => void>( | ||
() => null, | ||
); | ||
const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce; | ||
const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce; | ||
/** | ||
@@ -106,14 +112,20 @@ * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues | ||
logger.debug(`Submitting request`, { disabled, submitOptions }); | ||
if (debounce) { | ||
// We need to keep the resolve of debounced requests to prevent memory leaks | ||
debounceResolve.current = (value: ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>) => { | ||
debounceResolve.current(value); | ||
if (bounce) { | ||
const bouncedResolve = bounceResolver.current; | ||
// We need to keep the resolve of debounced requests to prevent memory leaks - we need to always resolve promise. | ||
// By default bounce method will prevent function to be triggered, but returned promise will still await to be resolved. | ||
// This way we can close previous promise, making sure our logic will not stuck in memory. | ||
bounceResolver.current = (value: ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>) => { | ||
// Trigger previous awaiting calls to resolve together in bounced batches | ||
bouncedResolve(value); | ||
resolve(value); | ||
}; | ||
// Start debouncing | ||
requestDebounce.debounce(async () => { | ||
// Cleanup debounce resolve | ||
const callback = debounceResolve.current; | ||
debounceResolve.current = () => null; | ||
// Start bounce | ||
bounceFunction(async () => { | ||
// We will always resolve previous calls as we stack the callbacks together until bounce function trigger | ||
const callback = bounceResolver.current; | ||
// Clean bounce resolvers to start the new stack | ||
bounceResolver.current = () => null; | ||
const value = await triggerRequest(); | ||
@@ -199,5 +211,5 @@ callback(value); | ||
...handlers, | ||
isDebouncing: requestDebounce.active, | ||
bounce: getBounceData(bounceData), | ||
revalidate, | ||
}; | ||
}; |
@@ -32,8 +32,12 @@ import { | ||
*/ | ||
debounce?: boolean; | ||
bounce?: boolean; | ||
/** | ||
* How long it should debounce requests. | ||
* Possibility to choose between debounce and throttle approaches | ||
*/ | ||
debounceTime?: number; | ||
bounceType?: "debounce" | "throttle"; | ||
/** | ||
* How long it should bounce requests. | ||
*/ | ||
bounceTime?: number; | ||
/** | ||
* If `true` it will rerender only when values used by our component gets changed. Otherwise it will rerender on any change. | ||
@@ -99,5 +103,14 @@ */ | ||
/** | ||
* Is debounce active at given moment | ||
* Data related to current state of the bounce usage | ||
*/ | ||
isDebouncing: boolean; | ||
bounce: { | ||
/** | ||
* Active state of the bounce method | ||
*/ | ||
active: boolean; | ||
/** | ||
* Method to stop the active bounce method execution | ||
*/ | ||
reset: () => void; | ||
}; | ||
/** | ||
@@ -104,0 +117,0 @@ * Revalidate current command resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey). |
export * from "./deep-equal.utils"; | ||
export * from "./bounce.utils"; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
256786
2584
4
82
+ Added@better-typed/react-performance-hooks@0.8.0(transitive)