tsdf 8.0.0-beta.3 → 8.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.cjs CHANGED
@@ -1 +1,1794 @@
1
- "use strict";var Ve=Object.create;var Fe=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var ze=(r,c)=>{for(var S in c)Fe(r,S,{get:c[S],enumerable:!0})},Me=(r,c,S,g)=>{if(c&&typeof c=="object"||typeof c=="function")for(let T of Ue(c))!je.call(r,T)&&T!==S&&Fe(r,T,{get:()=>c[T],enumerable:!(g=ke(c,T))||g.enumerable});return r};var me=(r,c,S)=>(S=r!=null?Ve(We(r)):{},Me(c||!r||!r.__esModule?Fe(S,"default",{value:r,enumerable:!0}):S,r)),_e=r=>Me(Fe({},"__esModule",{value:!0}),r);var Ye={};ze(Ye,{newTSDFCollectionStore:()=>Ne,newTSDFDocumentStore:()=>xe,newTSDFListQueryStore:()=>Ke});module.exports=_e(Ye);var Oe=me(require("immer"),1),qe=me(require("mitt"),1),Pe=require("react"),we=require("t-state");function ge({fetchFn:r,on:c,mediumPriorityThrottleMs:S=10,lowPriorityThrottleMs:g=200,dynamicRealtimeThrottleMs:T}){let m={e:null,r:null,t:null},U=0,C=0,O=!1,f=0,M=0,y=[],Q=!1,J=0;function Y(a){M=a}function W(a){f=a}function j(){if(m.r){c?.("scheduled-fetch-started");let a=m.r.params;m.r=null,E(a,Date.now())}}function z(){O=!0,J=C,m.e=null;let a=Qe();return U=a,()=>ae(a)}function ae(a){return a===U?(O=!1,y.length>0&&(y.forEach(s=>s()),y=[]),j(),!0):!1}function ue(){return m}async function E(a,s){if(m.e)throw new Error("[tsdf] Fetch already in progress");let t=Qe();C=t,Q=!1,m.e={startTime:s,onEnd:[]};let F=f;f=s;function b(){let X=t!==C||O||t<=J;return Q=X,X}let p=await r({shouldAbort:b,getStartTime:()=>s},a),P=ue();if(!P.e)return f=F,!1;p&&(M=Date.now()-s),P.t&&(clearTimeout(P.t.timeoutId),m.t=null);let N=P.e.onEnd;return P.e=null,N.length>0&&N.forEach(X=>X()),j(),!0}function v(a,s){let t=Date.now();return T&&a==="realtimeUpdate"&&Z(t,s)?"rt-scheduled":B(a,t)?"skipped":H(a,s)?"scheduled":(E(s,t),"started")}function B(a,s){return!!(a==="highPriority"&&m.e&&s-m.e.startTime<S||a==="lowPriority"&&(m.e||m.r||O||f&&s-f<g))}function H(a,s){let t=(()=>a==="lowPriority"?!1:!!m.e||!!O)();return t&&(m.r={params:s}),t}function G(a,s){if(!T)return!1;let t=a-(f+M),F=T(M);if(t>=F)return!1;let b=F-t;return m.t={timeoutId:window.setTimeout(()=>{m.t=null,c?.("scheduled-rt-fetch-started"),E(s,Date.now())},b)},!0}function Z(a,s){return!M||!f||!T?!1:m.t?!0:m.e?(m.e.onEnd.push(()=>{G(Date.now(),s)}),!0):O?(y.push(()=>{G(Date.now(),s)||(c?.("scheduled-rt-fetch-started"),v("highPriority",s))}),!0):!!G(a,s)}function de(a){m.e&&m.e.onEnd.push(a)}async function l(a){return v("highPriority",a),m.e&&await new Promise(s=>{de(()=>s(!0))}),Q}return{scheduleFetch:v,awaitFetch:l,startMutation:z,get hasPendingFetch(){return!!m.e||!!m.r||!!m.t},get fetchIsInProgress(){return!!m.e},get mutationIsInProgress(){return O},setLastFetchDurantion:Y,setLastFetchStartTime:W}}var Je=0;function Qe(){return++Je}var Le=me(require("mitt"),1),Te=require("react");var A=require("react"),Ie=require("t-state");function Be(r,c=Ie.deepEqual){let S=(0,A.useRef)(),g=(0,A.useRef)(0);return c(r,S.current)||(S.current=r,g.current+=1),[g.current]}function ye(r,c){return(0,A.useMemo)(r,Be(c))}function Ge(r){let c=(0,A.useRef)({insideEffect:r,insideMemo:r});return c.current.insideMemo=r,(0,A.useLayoutEffect)(()=>{c.current.insideEffect=r}),c.current}function oe(r,c,S){let g=Ge(S);(0,A.useLayoutEffect)(()=>{let T=m=>{g.insideEffect(m)};return r.on(c,T),()=>{r.off(c,T)}},[r,c,g])}function He(r,c){let S=(0,A.useRef)(c);return(0,A.useEffect)(()=>{S.current=r}),S.current}function De(r,c,{equalityFn:S=Ie.shallowEqual,callOnMount:g,layoutEffect:T}={}){let m=T?A.useLayoutEffect:A.useEffect,U=He(r,g?void 0:r);m(()=>{if(!S(r,U))return c({prev:U,current:r})})}function be(r){let c=(0,A.useRef)();return c.current===void 0&&(c.current=r()),c.current}function le(r,c,S){let g=be(()=>(0,Le.default)()),[T,m]=(0,Te.useState)(!0);De(r&&T&&c,({current:C})=>{C&&S()},{callOnMount:!0}),oe(g,"isLoaded",C=>{r&&c&&C&&m(!1)});function U(C){return(0,Te.useMemo)(()=>{if(r){let O=c&&T?"loading":C.status;return{...C,isLoading:O==="loading",status:O}}return C},[r,T,C])}return[U,g.emit]}function xe({debugName:r,fetchFn:c,initialData:S,disableRefetchOnWindowFocus:g,disableRefetchOnMount:T,lowPriorityThrottleMs:m,mediumPriorityThrottleMs:U,dynamicRealtimeThrottleMs:C,errorNormalizer:O}){let f=new we.Store({debugName:r,state:{data:S??null,error:null,status:S?"success":"idle",refetchOnMount:!1}});async function M(E,v){f.setPartialState({status:f.state.status==="success"?"refetching":"loading",error:null,refetchOnMount:!1},{action:f.state.status==="success"?"fetch-start-refetching":"fetch-start-loading"});try{let B=await c();return E.shouldAbort()?!1:(f.setPartialState({data:B,status:"success"},{action:"fetch-success"}),!0)}catch(B){return E.shouldAbort()||f.setPartialState({error:O(B),status:"error"},{action:"fetch-error"}),!1}}let y=ge({fetchFn:M,lowPriorityThrottleMs:m,dynamicRealtimeThrottleMs:C,mediumPriorityThrottleMs:U});function Q(E){return y.scheduleFetch(E,null)}async function J(){return await y.awaitFetch(null)?{data:null,error:O(new Error("Aborted"))}:f.state.data?f.state.error?{data:null,error:f.state.error}:{data:f.state.data,error:null}:{data:null,error:O(new Error("No data"))}}let Y=(0,qe.default)(),W=!1;function j(E="highPriority"){f.setKey("refetchOnMount",E,{action:"invalidate-data"}),W=!1,Y.emit("invalidateData",E)}function z({selector:E,disabled:v,returnRefetchingStatus:B,disableRefetchOnMount:H=T,returnIdleStatus:G=!!v,ensureIsLoaded:Z}={}){let de=(0,Pe.useCallback)(t=>{let{error:F}=t,b=E?E(t.data):t.data,p=t.status;return!G&&p==="idle"&&(p="loading"),!B&&p==="refetching"&&(p="success"),{data:b,error:F,status:p,isLoading:p==="loading"}},[B,G,E]),l=f.useSelector(de,{useExternalDeps:!0});oe(Y,"invalidateData",t=>{W||(Q(t),W=!0)}),(0,Pe.useEffect)(()=>{v||(H?(f.state.refetchOnMount||f.state.status==="idle")&&Q(f.state.refetchOnMount||"lowPriority"):Q("lowPriority"))},[H,v]);let[a,s]=le(Z,!v,()=>{Q("highPriority")});return(0,we.useSubscribeToStore)(f,({observe:t})=>{t.ifSelector(F=>F.status).change.then(({current:F})=>{(F==="success"||F==="error")&&s("isLoaded",!0)})}),a(l)}function ae(E){f.setKey("data",v=>v&&(0,Oe.default)(v,E),{action:"update-state"})}if(!g){let E=function(){j("lowPriority")};var ue=E;window.addEventListener("focus",E),window.addEventListener("visibilitychange",E)}return{store:f,awaitFetch:J,scheduleFetch:Q,invalidateData:j,useDocument:z,updateState:ae,startMutation:y.startMutation}}var ve=me(require("mitt"),1),se=require("react"),ce=require("t-state");function he(r){let c=new Map;function S(g){return c.has(g)||c.set(g,ge(r)),c.get(g)}return{get:S}}var Re=Symbol();function re(r,c){let S=[],g=0;for(let T of r){let m=c(T,Re,g);m!==Re&&S.push(m),g++}return S}function Ce(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ee(r){return typeof r=="string"?r:JSON.stringify(r&&Ce(r)?Xe(r):r)}function Xe(r){return re(Object.keys(r).sort(),(c,S)=>r[c]===void 0?S:{[c]:r[c]})}function Se(r){return JSON.parse(JSON.stringify(r))}function Ne({debugName:r,fetchFn:c,disableRefetchOnWindowFocus:S,lowPriorityThrottleMs:g,errorNormalizer:T,mediumPriorityThrottleMs:m,disableRefetchOnMount:U,dynamicRealtimeThrottleMs:C,getCollectionItemKey:O}){let f=new ce.Store({debugName:r,state:{}});function M(l){return Ee(O?O(l):l)}async function y(l,a){let s=M(a),t=Se(a),F=f.state[s];f.produceState(b=>{let p=b[s];if(!p){b[s]={data:null,error:null,status:"loading",payload:t,refetchOnMount:!1,wasLoaded:!1};return}p.status=p.data!==null?"refetching":"loading",p.payload=t,p.error=null,p.refetchOnMount=!1},{equalityCheck:ce.deepEqual,action:{type:F?.data?"fetch-start-refetching":"fetch-start-loading",payload:t}});try{let b=await c(t);return l.shouldAbort()?!1:(f.produceState(p=>{let P=p[s];!P||(P.data=b,P.status="success",P.wasLoaded=!0)},{action:{type:"fetch-success",payload:t}}),!0)}catch(b){if(l.shouldAbort())return!1;let p=T(b);return f.produceState(P=>{let N=P[s];!N||(N.error=p,N.status="error")},{action:{type:"fetch-error",payload:t,error:p}}),!1}}let Q=he({fetchFn:y,lowPriorityThrottleMs:g,dynamicRealtimeThrottleMs:C,mediumPriorityThrottleMs:m});function J(l,a){let s=Array.isArray(a),t=s?a:[a],F=[];for(let b of t){let p=M(b);F.push(Q.get(p).scheduleFetch(l,b))}return s?F:F[0]}async function Y(l){let a=M(l);if(await Q.get(a).awaitFetch(l))return{data:null,error:T(new Error("Aborted"))};let t=f.state[a];return t?.data?t.error?{data:null,error:t.error}:{data:t.data,error:null}:{data:null,error:T(new Error("Not found"))}}function W(l){let a=f.state;return Array.isArray(l)?l.map(M):typeof l=="function"?re(Object.entries(a),([s,t],F)=>t&&l(t.payload,t.data)?s:F):[M(l)]}let j=(0,ve.default)(),z=new Set;function ae(l,a="highPriority"){let s=W(l);for(let t of s)f.produceState(F=>{let b=F[t];!b||(b.refetchOnMount=a)},{action:{type:"invalidate-data",itemKey:t}}),z.delete(t),j.emit("invalidateData",{priority:a,itemKey:t})}function ue(l){if(typeof l=="function"||Array.isArray(l)){let a=W(l);return re(a,(s,t)=>f.state[s]||t)}return f.state[M(l)]}function E(l,{selector:a,omitPayload:s,returnIdleStatus:t,returnRefetchingStatus:F,disableRefetchOnMount:b=U}={}){let p=ye(()=>l.map(q=>({itemKey:M(q),payload:q})),[l]),P=(0,se.useCallback)(q=>a?a(q):q,[]),N=(0,se.useCallback)(q=>p.map(({itemKey:K,payload:$})=>{let ee=q[K];if(ee===null)return{itemStateKey:K,status:"deleted",data:P(null),error:null,payload:s?void 0:$,isLoading:!1};if(!ee)return{itemStateKey:K,status:t?"idle":"loading",data:P(null),error:null,payload:s?void 0:$,isLoading:!t};let fe=ee.status;return!F&&ee.status==="refetching"&&(fe="success"),{itemStateKey:K,status:fe,data:P(ee.data),error:ee.error,isLoading:fe==="loading",payload:s?void 0:ee.payload}}),[P,s,p,t,F]),X=f.useSelector(N,{equalityFn:ce.deepEqual,useExternalDeps:!0});return oe(j,"invalidateData",q=>{for(let{itemKey:K,payload:$}of p)K===q.itemKey&&(z.has(K)||(J(q.priority,$),z.add(K)))}),(0,se.useEffect)(()=>{for(let{itemKey:q,payload:K}of p)if(q)if(b){let $=ue(K);if(!$?.wasLoaded||$.refetchOnMount){J($?.refetchOnMount||"lowPriority",K);return}}else J("lowPriority",K)},[b,p]),X}function v(l,a={}){let{selector:s,ensureIsLoaded:t}=a,F=(0,se.useMemo)(()=>l===!1||l===null||l===void 0?[]:[l],[l]),b=E(F,a),p=(0,se.useMemo)(()=>b[0]??{payload:void 0,data:s?s(null):null,error:null,status:"idle",itemStateKey:"",isLoading:!1},[b]),[P,N]=le(t,!!l,()=>{l&&J("highPriority",l)});return(0,ce.useSubscribeToStore)(f,({observe:X})=>{!t||X.ifSelector(q=>q[p.itemStateKey]?.status).change.then(({current:q})=>{(q==="success"||q==="error")&&N("isLoaded",!0)})}),P(p)}function B(l){let a=W(l),s=[];for(let t of a)s.push(Q.get(t).startMutation());return()=>{for(let t of s)t()}}function H(l,a){let s=M(l);f.produceState(t=>{t[s]={data:a,status:"success",wasLoaded:!0,refetchOnMount:!1,error:null,payload:Se(l)}},{action:{type:"create-item-state",payload:l}})}function G(l){let a=W(l);f.produceState(s=>{for(let t of a)s[t]=null},{action:{type:"delete-item-state",payload:l}})}function Z(l,a,s){let t=W(l),F=!1;return f.batch(()=>{f.produceState(b=>{for(let p of t){let P=b[p];if(!!P&&P.data){F=!0;let N=a(P.data,P);N&&(P.data=N)}}}),s&&!F&&s()},{type:"update-item-state",item:t}),F}if(!S){let l=function(){ae(()=>!0,"lowPriority")};var de=l;window.addEventListener("focus",l),window.addEventListener("visibilitychange",l)}return{store:f,scheduleFetch:J,awaitFetch:Y,useMultipleItems:E,useItem:v,getItemKey:M,getItemState:ue,startMutation:B,invalidateItem:ae,updateItemState:Z,addItemToState:H,deleteItemState:G}}var Ae=me(require("mitt"),1),k=require("react"),ne=require("t-state");var pe="No fetchItemFn was provided";function Ke({debugName:r,fetchListFn:c,fetchItemFn:S,errorNormalizer:g,defaultQuerySize:T=50,disableRefetchOnWindowFocus:m,disableRefetchOnMount:U,lowPriorityThrottleMs:C,mediumPriorityThrottleMs:O,dynamicRealtimeThrottleMs:f,syncMutationsAndInvalidations:M}){let y=new ne.Store({debugName:r,state:{items:{},queries:{},itemQueries:{}}});function Q(e){return Ee(e)}async function J(e,[n,u,i=T]){let o=Se(u),d=Q(o),h=y.state.queries[d],x=!h?.wasLoaded;y.produceState(I=>{let L=I.queries[d];if(!L){I.queries[d]={error:null,status:"loading",wasLoaded:!1,payload:o,refetchOnMount:!1,hasMore:!1,items:[]};return}L.status=L.wasLoaded?n==="loadMore"?"loadingMore":"refetching":"loading",L.error=null,L.refetchOnMount=!1},{equalityCheck:ne.deepEqual,action:{type:x?"fetch-query-start-loading":n==="loadMore"?"fetch-query-loading-more":"refetching-query-start",payload:o}});let V=h?.items.length??0,D=(()=>n==="loadMore"?V+i:x?i:Math.max(V,i))();try{let{items:I,hasMore:L}=await c(o,D);if(e.shouldAbort())return!1;y.produceState(R=>{let w=R.queries[d];if(!!w){w.status="success",w.wasLoaded=!0,w.hasMore=L,w.items=[];for(let{data:te,id:_}of I){R.items[_]=te,w.items.push(String(_));let ie=R.itemQueries[_];(!ie||ie.status!=="loading"&&ie.status!=="refetching")&&(R.itemQueries[_]={error:null,refetchOnMount:!1,status:"success",wasLoaded:!0})}}},{action:{type:"fetch-query-success",payload:o}});for(let{id:R}of I){let w=t?.get(String(R));w&&w.setLastFetchStartTime(e.getStartTime())}return!0}catch(I){if(e.shouldAbort())return!1;let L=g(I);return y.produceState(R=>{let w=R.queries[d];!w||(w.status="error",w.error=L)},{action:{type:"fetch-query-error",payload:o,error:L}}),!1}}function Y(e){return y.state.queries[Q(e)]}function W(e){if(typeof e=="string")return y.state.items[e];let n=b(e);return re(n,(u,i)=>{let o=y.state.items[u];return o?{id:u,data:o}:i})}let j=he({fetchFn:J,lowPriorityThrottleMs:C,dynamicRealtimeThrottleMs:f,mediumPriorityThrottleMs:O});function z(e,n,u){let i=Array.isArray(n),d=(i?n:[n]).map(h=>j.get(Q(h)).scheduleFetch(e,["load",h,u]));return i?d:d[0]}function ae(e,n){let u=Y(e);return!u||!u.hasMore?"skipped":j.get(Q(e)).scheduleFetch("highPriority",["loadMore",e,n])}function ue(e,n){return re(e.items,(u,i)=>{let o=y.state.items[u];return o?n(o,u):i})}async function E(e,n=T){let u=Q(e);if(await j.get(u).awaitFetch(["load",e,n]))return{items:[],error:g(new Error("Aborted")),hasMore:!1};let o=y.state.queries[u];return o?o.error?{items:[],error:o.error,hasMore:o.hasMore}:{items:ue(o,(d,h)=>({data:d,id:h})),error:null,hasMore:o.hasMore}:{items:[],error:g(new Error("Not found")),hasMore:!1}}async function v(e){if(!t)throw new Error(pe);if(await t.get(e).awaitFetch(e))return{data:null,error:g(new Error("Aborted"))};let u=y.state.items[e],i=y.state.itemQueries[e];return!i||!u?{data:null,error:g(new Error("Not found"))}:i.error?{data:null,error:i.error}:{data:u,error:null}}function B(e){return Array.isArray(e)?e.map(n=>({key:Q(n),payload:n})):typeof e=="function"?re(Object.entries(y.state.queries),([n,u],i)=>e(u.payload,u,n)?{key:n,payload:u.payload}:i):[{key:Q(e),payload:e}]}let H=(0,Ae.default)(),G=new Set;function Z(e,n="highPriority",u=!1){let i=B(e);for(let{key:o}of i)y.produceState(d=>{let h=d.queries[o];!h||(h.refetchOnMount=n)},{action:{type:"invalidate-data",key:o}}),G.delete(o),H.emit("invalidateQuery",{priority:n,queryKey:o});M&&!u&&(P((o,d)=>i.some(({payload:h})=>M.syncItemAndQuery(d,h)),n,!0),Z((o,d,h)=>i.some(x=>h!==x.key&&M.syncQueries(x.payload,o)),n,!0))}function de(e,n){return{id:n,data:e}}function l(e,{itemSelector:n=de,omitPayload:u,returnIdleStatus:i,returnRefetchingStatus:o,loadSize:d,disableRefetchOnMount:h=U}={}){let x=ye(()=>e.map(R=>({key:Q(R),payload:R})),[e]),V=(0,k.useCallback)(n,[]),D=(0,k.useCallback)(R=>x.map(({key:w,payload:te})=>{let _=R.queries[w];if(!_)return{queryKey:w,status:i?"idle":"loading",items:[],error:null,hasMore:!1,payload:u?void 0:te,isLoading:!i};let ie=_.status;return!o&&_.status==="refetching"&&(ie="success"),{queryKey:w,status:ie,items:ue(_,V),error:_.error,hasMore:_.hasMore,isLoading:ie==="loading",payload:u?void 0:_.payload}}),[V,u,x,i,o]),I=y.useSelector(D,{equalityFn:ne.deepEqual,useExternalDeps:!0});oe(H,"invalidateQuery",R=>{for(let{key:w,payload:te}of x)w===R.queryKey&&(G.has(w)||(z(R.priority,te),G.add(w)))});let L=be(()=>d);return(0,k.useEffect)(()=>{for(let{key:R,payload:w}of x)if(R)if(h){let te=Y(w);if(!te||!te.wasLoaded||te.refetchOnMount){z(te?.refetchOnMount||"lowPriority",w,L);return}}else z("lowPriority",w,L)},[h,L,x]),I}function a(e,n={}){let{ensureIsLoaded:u}=n,i=(0,k.useMemo)(()=>e===!1||e===null||e===void 0?[]:[e],[e]),o=l(i,n),d=(0,k.useMemo)(()=>o[0]??{payload:void 0,error:null,hasMore:!1,isLoading:!1,status:"idle",queryKey:"",items:[]},[o]),[h,x]=le(u,!!e,()=>{e&&z("highPriority",e)});return(0,ne.useSubscribeToStore)(y,({observe:V})=>{!u||V.ifSelector(D=>D.queries[d.queryKey]?.status).change.then(({current:D})=>{(D==="success"||D==="error")&&x("isLoaded",!0)})}),h(d)}async function s(e,n){if(!t)throw new Error(pe);let u=!y.state.itemQueries[n]?.wasLoaded;y.produceState(i=>{let o=i.itemQueries[n];if(!o){i.itemQueries[n]={status:"loading",error:null,wasLoaded:!1,refetchOnMount:!1};return}o.status=o.wasLoaded?"refetching":"loading",o.error=null,o.refetchOnMount=!1},{action:{type:u?"fetch-item-start":"fetch-item-refetch-start",itemId:n}});try{let i=await S(n);return e.shouldAbort()?!1:(y.produceState(o=>{let d=o.itemQueries[n];!d||(d.status="success",d.wasLoaded=!0,o.items[n]=i)},{action:{type:"fetch-item-success",itemId:n}}),!0)}catch(i){if(e.shouldAbort())return!1;let o=g(i);return y.produceState(d=>{let h=d.itemQueries[n];!h||(h.status="error",h.error=o)},{action:{type:"fetch-item-error",itemId:n}}),!1}}let t=S&&he({fetchFn:s,lowPriorityThrottleMs:C,dynamicRealtimeThrottleMs:f,mediumPriorityThrottleMs:O});function F(e,n){if(!t)throw new Error(pe);let u=Array.isArray(n),o=(u?n:[n]).map(d=>t.get(d).scheduleFetch(e,d));return u?o:o[0]}function b(e){return Array.isArray(e)?e:typeof e=="function"?re(Object.entries(y.state.items),([n,u],i)=>u===null?i:e(u,n)?n:i):[e]}let p=new Set;function P(e,n="highPriority",u=!1){if(!t)throw new Error(pe);let i=b(e);for(let o of i)y.produceState(d=>{let h=d.itemQueries[o];!h||(h.refetchOnMount=n)},{action:{type:"invalidate-item",queryKey:o}}),p.delete(o),H.emit("invalidateItem",{priority:n,itemId:o});M&&!u&&Z(o=>i.some(d=>M.syncItemAndQuery(d,o)),n,!0)}function N(e){if(!t)throw new Error(pe);let n=b(e),u=[];for(let i of n)if(u.push(t.get(i).startMutation()),M)for(let[o,d]of Object.entries(y.state.queries))M.syncItemAndQuery(i,d.payload)&&u.push(j.get(o).startMutation());return()=>{for(let i of u)i()}}function X(e){return e}function q(e,{selector:n=X,returnIdleStatus:u,returnRefetchingStatus:i,disableRefetchOnMount:o}={}){let d=(0,k.useCallback)(n,[]),h=ye(()=>e,[e]),x=(0,k.useCallback)(D=>h.map(I=>{let L=D.itemQueries[I],R=D.items[I];if(L===null)return{status:"deleted",error:null,isLoading:!1,itemId:I,data:d(null,I)};if(!L)return{status:u?"idle":"loading",error:null,isLoading:!u,itemId:I,data:d(null,I)};let w=L.status;return!i&&L.status==="refetching"&&(w="success"),{status:w,error:L.error,isLoading:w==="loading",data:d(R??null,I),itemId:I}}),[d,h,u,i]),V=y.useSelector(x,{equalityFn:ne.deepEqual,useExternalDeps:!0});return oe(H,"invalidateItem",D=>{for(let I of h)I===D.itemId&&(p.has(I)||(F(D.priority,I),p.add(I)))}),(0,k.useEffect)(()=>{for(let D of h)if(D)if(o){let I=y.state.itemQueries[D];if(!I||!I.wasLoaded||I.refetchOnMount){F(I?.refetchOnMount||"lowPriority",D);return}}else F("lowPriority",D)},[o,h]),V}function K(e,n={}){let{ensureIsLoaded:u}=n,i=(0,k.useMemo)(()=>e===!1||e===null||e===void 0?[]:[e],[e]),o=q(i,n),d=(0,k.useCallback)(n.selector??X,[]),h=(0,k.useMemo)(()=>o[0]??{error:null,isLoading:!1,status:"idle",data:d(null,e||""),itemId:e||""},[e,d,o]),[x,V]=le(u,!!e,()=>{e&&F("highPriority",e)});return(0,ne.useSubscribeToStore)(y,({observe:D})=>{!u||!e||D.ifSelector(I=>I.itemQueries[e]?.status).change.then(({current:I})=>{(I==="success"||I==="error")&&V("isLoaded",!0)})}),x(h)}function $(e,n,u){let i=b(e),o=!1;return y.batch(()=>{y.produceState(d=>{for(let h of i){let x=d.items[h];if(!x)continue;o=!0;let V=n(x,h);V&&(d.items[h]=V)}}),u&&!o&&u()},{type:"update-item-state",item:i}),o}function ee(e,n){y.produceState(u=>{u.items[e]=n,u.itemQueries[e]={status:"success",wasLoaded:!0,refetchOnMount:!1,error:null}},{action:{type:"create-item-state",itemId:e}})}function fe(e){let n=b(e);y.produceState(u=>{for(let i of n){u.items[i]=null,u.itemQueries[i]=null;for(let o of Object.values(u.queries))o.items.includes(i)&&(o.items=o.items.filter(d=>d!==i))}},{action:{type:"delete-item-state",itemId:e}})}if(!m){let e=function(){Z(()=>!0,"lowPriority"),P(()=>!0,"lowPriority")};var Xt=e;window.addEventListener("focus",e),window.addEventListener("visibilitychange",e)}return{store:y,scheduleListQueryFetch:z,getQueryState:Y,getQueryKey:Q,deleteItemState:fe,getItemState:W,loadMore:ae,invalidateQuery:Z,invalidateItem:P,scheduleItemFetch:F,awaitItemFetch:v,awaitListQueryFetch:E,useMultipleListQueries:l,useListQuery:a,useItem:K,useMultipleItems:q,addItemToState:ee,updateItemState:$,startItemMutation:N}}0&&(module.exports={newTSDFCollectionStore,newTSDFDocumentStore,newTSDFListQueryStore});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/main.ts
27
+ var main_exports = {};
28
+ __export(main_exports, {
29
+ newTSDFCollectionStore: () => newTSDFCollectionStore,
30
+ newTSDFDocumentStore: () => newTSDFDocumentStore,
31
+ newTSDFListQueryStore: () => newTSDFListQueryStore
32
+ });
33
+ module.exports = __toCommonJS(main_exports);
34
+
35
+ // src/documentStore.ts
36
+ var import_immer = __toESM(require("immer"), 1);
37
+ var import_mitt2 = __toESM(require("mitt"), 1);
38
+ var import_react3 = require("react");
39
+ var import_t_state2 = require("t-state");
40
+
41
+ // src/fetchOrquestrator.ts
42
+ function createFetchOrquestrator({
43
+ fetchFn,
44
+ on,
45
+ mediumPriorityThrottleMs = 10,
46
+ lowPriorityThrottleMs = 200,
47
+ dynamicRealtimeThrottleMs
48
+ }) {
49
+ const fetchs = {
50
+ a: null,
51
+ c: null,
52
+ b: null
53
+ };
54
+ let lastMutationIdStarted = 0;
55
+ let lastFetchIdStarted = 0;
56
+ let mutationIsInProgress = false;
57
+ let lastFetchStartTime = 0;
58
+ let lastFetchDuration = 0;
59
+ let onMutationEnd = [];
60
+ let lastFetchWasAborted = false;
61
+ let abortFetchsBeforeOrEqual = 0;
62
+ function setLastFetchDurantion(duration) {
63
+ lastFetchDuration = duration;
64
+ }
65
+ function setLastFetchStartTime(startTime) {
66
+ lastFetchStartTime = startTime;
67
+ }
68
+ function flushScheduledFetch() {
69
+ if (fetchs.c) {
70
+ on?.("scheduled-fetch-started");
71
+ const params = fetchs.c.params;
72
+ fetchs.c = null;
73
+ startFetch(params, Date.now());
74
+ }
75
+ }
76
+ function startMutation() {
77
+ mutationIsInProgress = true;
78
+ abortFetchsBeforeOrEqual = lastFetchIdStarted;
79
+ fetchs.a = null;
80
+ const id = getAutoIncrementId();
81
+ lastMutationIdStarted = id;
82
+ return () => endMutation(id);
83
+ }
84
+ function endMutation(id) {
85
+ if (id === lastMutationIdStarted) {
86
+ mutationIsInProgress = false;
87
+ if (onMutationEnd.length > 0) {
88
+ onMutationEnd.forEach((cb) => cb());
89
+ onMutationEnd = [];
90
+ }
91
+ flushScheduledFetch();
92
+ return true;
93
+ }
94
+ return false;
95
+ }
96
+ function getFetchs() {
97
+ return fetchs;
98
+ }
99
+ async function startFetch(params, startTime) {
100
+ if (fetchs.a) {
101
+ throw new Error("[tsdf] Fetch already in progress");
102
+ }
103
+ const id = getAutoIncrementId();
104
+ lastFetchIdStarted = id;
105
+ lastFetchWasAborted = false;
106
+ fetchs.a = { startTime, onEnd: [] };
107
+ const prevFetchStartTime = lastFetchStartTime;
108
+ lastFetchStartTime = startTime;
109
+ function shouldAbort() {
110
+ const abort = id !== lastFetchIdStarted || mutationIsInProgress || id <= abortFetchsBeforeOrEqual;
111
+ lastFetchWasAborted = abort;
112
+ return abort;
113
+ }
114
+ const success = await fetchFn(
115
+ {
116
+ shouldAbort,
117
+ getStartTime: () => startTime
118
+ },
119
+ params
120
+ );
121
+ const currentFetchs = getFetchs();
122
+ if (!currentFetchs.a) {
123
+ lastFetchStartTime = prevFetchStartTime;
124
+ return false;
125
+ }
126
+ if (success) {
127
+ lastFetchDuration = Date.now() - startTime;
128
+ }
129
+ if (currentFetchs.b) {
130
+ clearTimeout(currentFetchs.b.timeoutId);
131
+ fetchs.b = null;
132
+ }
133
+ const onEnd = currentFetchs.a.onEnd;
134
+ currentFetchs.a = null;
135
+ if (onEnd.length > 0) {
136
+ onEnd.forEach((cb) => cb());
137
+ }
138
+ flushScheduledFetch();
139
+ return true;
140
+ }
141
+ function scheduleFetch(fetchType, params) {
142
+ const startTime = Date.now();
143
+ if (dynamicRealtimeThrottleMs && fetchType === "realtimeUpdate") {
144
+ if (scheduleRTU(startTime, params)) {
145
+ return "rt-scheduled";
146
+ }
147
+ }
148
+ if (shouldSkipFetch(fetchType, startTime)) {
149
+ return "skipped";
150
+ }
151
+ if (shouldScheduleFetch(fetchType, params)) {
152
+ return "scheduled";
153
+ }
154
+ startFetch(params, startTime);
155
+ return "started";
156
+ }
157
+ function shouldSkipFetch(fetchType, startTime) {
158
+ if (fetchType === "highPriority") {
159
+ if (fetchs.a) {
160
+ const timeSinceLastFetch = startTime - fetchs.a.startTime;
161
+ if (timeSinceLastFetch < mediumPriorityThrottleMs) {
162
+ return true;
163
+ }
164
+ }
165
+ }
166
+ if (fetchType === "lowPriority") {
167
+ if (fetchs.a || fetchs.c || mutationIsInProgress) {
168
+ return true;
169
+ }
170
+ if (lastFetchStartTime) {
171
+ const timeSinceLastFetch = startTime - lastFetchStartTime;
172
+ if (timeSinceLastFetch < lowPriorityThrottleMs) {
173
+ return true;
174
+ }
175
+ }
176
+ }
177
+ return false;
178
+ }
179
+ function shouldScheduleFetch(priority, params) {
180
+ const shouldSchedule = (() => {
181
+ if (priority === "lowPriority") {
182
+ return false;
183
+ }
184
+ return !!fetchs.a || !!mutationIsInProgress;
185
+ })();
186
+ if (shouldSchedule) {
187
+ fetchs.c = { params };
188
+ }
189
+ return shouldSchedule;
190
+ }
191
+ function addDelayedRTU(startTime, params) {
192
+ if (!dynamicRealtimeThrottleMs)
193
+ return false;
194
+ const timeSinceLastFetch = startTime - (lastFetchStartTime + lastFetchDuration);
195
+ const minimumRealtimeInterval = dynamicRealtimeThrottleMs(lastFetchDuration);
196
+ if (timeSinceLastFetch >= minimumRealtimeInterval)
197
+ return false;
198
+ const delay = minimumRealtimeInterval - timeSinceLastFetch;
199
+ fetchs.b = {
200
+ timeoutId: window.setTimeout(() => {
201
+ fetchs.b = null;
202
+ on?.("scheduled-rt-fetch-started");
203
+ startFetch(params, Date.now());
204
+ }, delay)
205
+ };
206
+ return true;
207
+ }
208
+ function scheduleRTU(startTime, params) {
209
+ if (!lastFetchDuration || !lastFetchStartTime || !dynamicRealtimeThrottleMs) {
210
+ return false;
211
+ }
212
+ if (fetchs.b) {
213
+ return true;
214
+ }
215
+ if (fetchs.a) {
216
+ fetchs.a.onEnd.push(() => {
217
+ addDelayedRTU(Date.now(), params);
218
+ });
219
+ return true;
220
+ } else if (mutationIsInProgress) {
221
+ onMutationEnd.push(() => {
222
+ const added = addDelayedRTU(Date.now(), params);
223
+ if (!added) {
224
+ on?.("scheduled-rt-fetch-started");
225
+ scheduleFetch("highPriority", params);
226
+ }
227
+ });
228
+ return true;
229
+ } else {
230
+ if (!addDelayedRTU(startTime, params)) {
231
+ return false;
232
+ }
233
+ }
234
+ return true;
235
+ }
236
+ function addOnFetchEnd(cb) {
237
+ if (fetchs.a) {
238
+ fetchs.a.onEnd.push(cb);
239
+ }
240
+ }
241
+ async function awaitFetch(params) {
242
+ scheduleFetch("highPriority", params);
243
+ if (fetchs.a) {
244
+ await new Promise((resolve) => {
245
+ addOnFetchEnd(() => resolve(true));
246
+ });
247
+ }
248
+ return lastFetchWasAborted;
249
+ }
250
+ return {
251
+ scheduleFetch,
252
+ awaitFetch,
253
+ startMutation,
254
+ get hasPendingFetch() {
255
+ return !!fetchs.a || !!fetchs.c || !!fetchs.b;
256
+ },
257
+ get fetchIsInProgress() {
258
+ return !!fetchs.a;
259
+ },
260
+ get mutationIsInProgress() {
261
+ return mutationIsInProgress;
262
+ },
263
+ setLastFetchDurantion,
264
+ setLastFetchStartTime
265
+ };
266
+ }
267
+ var autoIncrementId = 0;
268
+ function getAutoIncrementId() {
269
+ return ++autoIncrementId;
270
+ }
271
+
272
+ // src/useEnsureIsLoaded.ts
273
+ var import_mitt = __toESM(require("mitt"), 1);
274
+ var import_react2 = require("react");
275
+
276
+ // src/utils/hooks.ts
277
+ var import_react = require("react");
278
+ var import_t_state = require("t-state");
279
+ function useDeepCompareMemoize(value, equalityFn = import_t_state.deepEqual) {
280
+ const ref = (0, import_react.useRef)();
281
+ const signalRef = (0, import_react.useRef)(0);
282
+ if (!equalityFn(value, ref.current)) {
283
+ ref.current = value;
284
+ signalRef.current += 1;
285
+ }
286
+ return [signalRef.current];
287
+ }
288
+ function useDeepMemo(callback, deeps) {
289
+ return (0, import_react.useMemo)(callback, useDeepCompareMemoize(deeps));
290
+ }
291
+ function useLatestValue(value) {
292
+ const ref = (0, import_react.useRef)({ insideEffect: value, insideMemo: value });
293
+ ref.current.insideMemo = value;
294
+ (0, import_react.useLayoutEffect)(() => {
295
+ ref.current.insideEffect = value;
296
+ });
297
+ return ref.current;
298
+ }
299
+ function useOnMittEvent(mitt5, event, callback) {
300
+ const latestCallback = useLatestValue(callback);
301
+ (0, import_react.useLayoutEffect)(() => {
302
+ const cb = (payload) => {
303
+ latestCallback.insideEffect(payload);
304
+ };
305
+ mitt5.on(event, cb);
306
+ return () => {
307
+ mitt5.off(event, cb);
308
+ };
309
+ }, [mitt5, event, latestCallback]);
310
+ }
311
+ function usePrevious(value, initial) {
312
+ const ref = (0, import_react.useRef)(initial);
313
+ (0, import_react.useEffect)(() => {
314
+ ref.current = value;
315
+ });
316
+ return ref.current;
317
+ }
318
+ function useOnChange(value, callBack, {
319
+ equalityFn: areEqual = import_t_state.shallowEqual,
320
+ callOnMount,
321
+ layoutEffect
322
+ } = {}) {
323
+ const useEffectFn = layoutEffect ? import_react.useLayoutEffect : import_react.useEffect;
324
+ const prev = usePrevious(value, !callOnMount ? value : void 0);
325
+ useEffectFn(() => {
326
+ if (!areEqual(value, prev)) {
327
+ return callBack({ prev, current: value });
328
+ }
329
+ });
330
+ }
331
+ function useConst(getValue) {
332
+ const store = (0, import_react.useRef)();
333
+ if (store.current === void 0) {
334
+ store.current = getValue();
335
+ }
336
+ return store.current;
337
+ }
338
+
339
+ // src/useEnsureIsLoaded.ts
340
+ function useEnsureIsLoaded(ensureIsLoaded, enabled, forceFetch) {
341
+ const isLoadedEvtEmitter = useConst(() => (0, import_mitt.default)());
342
+ const [isForceLoading, setIsForceLoading] = (0, import_react2.useState)(true);
343
+ useOnChange(
344
+ ensureIsLoaded && isForceLoading && enabled,
345
+ ({ current }) => {
346
+ if (current) {
347
+ forceFetch();
348
+ }
349
+ },
350
+ { callOnMount: true }
351
+ );
352
+ useOnMittEvent(isLoadedEvtEmitter, "isLoaded", (isLoaded) => {
353
+ if (ensureIsLoaded && enabled && isLoaded) {
354
+ setIsForceLoading(false);
355
+ }
356
+ });
357
+ function useModifyResult(result) {
358
+ return (0, import_react2.useMemo)(() => {
359
+ if (ensureIsLoaded) {
360
+ const newStatus = enabled && isForceLoading ? "loading" : result.status;
361
+ return {
362
+ ...result,
363
+ isLoading: newStatus === "loading",
364
+ status: newStatus
365
+ };
366
+ }
367
+ return result;
368
+ }, [ensureIsLoaded, isForceLoading, result]);
369
+ }
370
+ return [useModifyResult, isLoadedEvtEmitter.emit];
371
+ }
372
+
373
+ // src/documentStore.ts
374
+ function newTSDFDocumentStore({
375
+ debugName,
376
+ fetchFn,
377
+ initialData,
378
+ disableRefetchOnWindowFocus,
379
+ disableRefetchOnMount: globalDisableRefetchOnMount,
380
+ lowPriorityThrottleMs,
381
+ mediumPriorityThrottleMs,
382
+ dynamicRealtimeThrottleMs,
383
+ errorNormalizer
384
+ }) {
385
+ const store = new import_t_state2.Store({
386
+ debugName,
387
+ state: {
388
+ data: initialData ?? null,
389
+ error: null,
390
+ status: initialData ? "success" : "idle",
391
+ refetchOnMount: false
392
+ }
393
+ });
394
+ async function fetch(fetchCtx, _) {
395
+ store.setPartialState(
396
+ {
397
+ status: store.state.status === "success" ? "refetching" : "loading",
398
+ error: null,
399
+ refetchOnMount: false
400
+ },
401
+ {
402
+ action: store.state.status === "success" ? "fetch-start-refetching" : "fetch-start-loading"
403
+ }
404
+ );
405
+ try {
406
+ const data = await fetchFn();
407
+ if (fetchCtx.shouldAbort())
408
+ return false;
409
+ store.setPartialState(
410
+ {
411
+ data,
412
+ status: "success"
413
+ },
414
+ { action: "fetch-success" }
415
+ );
416
+ return true;
417
+ } catch (exception) {
418
+ if (fetchCtx.shouldAbort())
419
+ return false;
420
+ store.setPartialState(
421
+ {
422
+ error: errorNormalizer(exception),
423
+ status: "error"
424
+ },
425
+ { action: "fetch-error" }
426
+ );
427
+ return false;
428
+ }
429
+ }
430
+ const fetchOrquestrator = createFetchOrquestrator({
431
+ fetchFn: fetch,
432
+ lowPriorityThrottleMs,
433
+ dynamicRealtimeThrottleMs,
434
+ mediumPriorityThrottleMs
435
+ });
436
+ function scheduleFetch(fetchType) {
437
+ return fetchOrquestrator.scheduleFetch(fetchType, null);
438
+ }
439
+ async function awaitFetch() {
440
+ const wasAborted = await fetchOrquestrator.awaitFetch(null);
441
+ if (wasAborted) {
442
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
443
+ }
444
+ if (!store.state.data) {
445
+ return { data: null, error: errorNormalizer(new Error("No data")) };
446
+ }
447
+ return store.state.error ? { data: null, error: store.state.error } : { data: store.state.data, error: null };
448
+ }
449
+ const storeEvents = (0, import_mitt2.default)();
450
+ let invalidationWasTriggered = false;
451
+ function invalidateData(priority = "highPriority") {
452
+ store.setKey("refetchOnMount", priority, { action: "invalidate-data" });
453
+ invalidationWasTriggered = false;
454
+ storeEvents.emit("invalidateData", priority);
455
+ }
456
+ function useDocument({
457
+ selector,
458
+ disabled,
459
+ returnRefetchingStatus,
460
+ disableRefetchOnMount = globalDisableRefetchOnMount,
461
+ returnIdleStatus = !!disabled,
462
+ ensureIsLoaded
463
+ } = {}) {
464
+ const storeStateSelector = (0, import_react3.useCallback)(
465
+ (state) => {
466
+ const { error } = state;
467
+ const data = selector ? selector(state.data) : state.data;
468
+ let status = state.status;
469
+ if (!returnIdleStatus && status === "idle") {
470
+ status = "loading";
471
+ }
472
+ if (!returnRefetchingStatus && status === "refetching") {
473
+ status = "success";
474
+ }
475
+ return {
476
+ data,
477
+ error,
478
+ status,
479
+ isLoading: status === "loading"
480
+ };
481
+ },
482
+ [returnRefetchingStatus, returnIdleStatus, selector]
483
+ );
484
+ const storeState = store.useSelector(storeStateSelector, {
485
+ useExternalDeps: true
486
+ });
487
+ useOnMittEvent(storeEvents, "invalidateData", (priority) => {
488
+ if (!invalidationWasTriggered) {
489
+ scheduleFetch(priority);
490
+ invalidationWasTriggered = true;
491
+ }
492
+ });
493
+ (0, import_react3.useEffect)(() => {
494
+ if (disabled)
495
+ return;
496
+ if (disableRefetchOnMount) {
497
+ const shouldFetch = store.state.refetchOnMount || store.state.status === "idle";
498
+ if (shouldFetch) {
499
+ scheduleFetch(store.state.refetchOnMount || "lowPriority");
500
+ }
501
+ } else {
502
+ scheduleFetch("lowPriority");
503
+ }
504
+ }, [disableRefetchOnMount, disabled]);
505
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
506
+ ensureIsLoaded,
507
+ !disabled,
508
+ () => {
509
+ scheduleFetch("highPriority");
510
+ }
511
+ );
512
+ (0, import_t_state2.useSubscribeToStore)(store, ({ observe }) => {
513
+ observe.ifSelector((state) => state.status).change.then(({ current }) => {
514
+ if (current === "success" || current === "error") {
515
+ emitIsLoadedEvt("isLoaded", true);
516
+ }
517
+ });
518
+ });
519
+ return useModifyResult(storeState);
520
+ }
521
+ function updateState(produceNewData) {
522
+ store.setKey(
523
+ "data",
524
+ (current) => {
525
+ if (!current)
526
+ return current;
527
+ return (0, import_immer.default)(current, produceNewData);
528
+ },
529
+ { action: "update-state" }
530
+ );
531
+ }
532
+ if (!disableRefetchOnWindowFocus) {
533
+ let handleFocus2 = function() {
534
+ invalidateData("lowPriority");
535
+ };
536
+ var handleFocus = handleFocus2;
537
+ window.addEventListener("focus", handleFocus2);
538
+ window.addEventListener("visibilitychange", handleFocus2);
539
+ }
540
+ return {
541
+ store,
542
+ awaitFetch,
543
+ scheduleFetch,
544
+ invalidateData,
545
+ useDocument,
546
+ updateState,
547
+ startMutation: fetchOrquestrator.startMutation
548
+ };
549
+ }
550
+
551
+ // src/collectionStore.ts
552
+ var import_mitt3 = __toESM(require("mitt"), 1);
553
+ var import_react4 = require("react");
554
+ var import_t_state3 = require("t-state");
555
+
556
+ // src/collectionFetchOrquestrator.ts
557
+ function createCollectionFetchOrquestrator(props) {
558
+ const fetchOrquestrators = /* @__PURE__ */ new Map();
559
+ function getFetchOrquestrator(key) {
560
+ if (!fetchOrquestrators.has(key)) {
561
+ fetchOrquestrators.set(key, createFetchOrquestrator(props));
562
+ }
563
+ return fetchOrquestrators.get(key);
564
+ }
565
+ return {
566
+ get: getFetchOrquestrator
567
+ };
568
+ }
569
+
570
+ // src/utils/filterAndMap.ts
571
+ var ignore = Symbol();
572
+ function filterAndMap(arr, fn) {
573
+ const result = [];
574
+ let i = 0;
575
+ for (const item of arr) {
576
+ const mappedItem = fn(item, ignore, i);
577
+ if (mappedItem !== ignore) {
578
+ result.push(mappedItem);
579
+ }
580
+ i++;
581
+ }
582
+ return result;
583
+ }
584
+
585
+ // src/utils/isObject.ts
586
+ function isObject(value) {
587
+ return typeof value === "object" && value !== null && !Array.isArray(value);
588
+ }
589
+
590
+ // src/utils/getCacheId.ts
591
+ function getCacheId(input) {
592
+ return typeof input === "string" || typeof input === "number" ? String(input) : JSON.stringify(input && isObject(input) ? orderedProps(input) : input);
593
+ }
594
+ function orderedProps(obj) {
595
+ return filterAndMap(Object.keys(obj).sort(), (k, ignore2) => {
596
+ const value = obj[k];
597
+ if (value === void 0)
598
+ return ignore2;
599
+ return { [k]: obj[k] };
600
+ });
601
+ }
602
+
603
+ // src/collectionStore.ts
604
+ var import_json = require("klona/json");
605
+ function newTSDFCollectionStore({
606
+ debugName,
607
+ fetchFn,
608
+ disableRefetchOnWindowFocus,
609
+ lowPriorityThrottleMs,
610
+ errorNormalizer,
611
+ mediumPriorityThrottleMs,
612
+ disableRefetchOnMount: globalDisableRefetchOnMount,
613
+ dynamicRealtimeThrottleMs,
614
+ getCollectionItemKey: filterCollectionItemObjKey
615
+ }) {
616
+ const store = new import_t_state3.Store({
617
+ debugName,
618
+ state: {}
619
+ });
620
+ function getItemKey(params) {
621
+ return getCacheId(
622
+ filterCollectionItemObjKey ? filterCollectionItemObjKey(params) : params
623
+ );
624
+ }
625
+ async function fetch(fetchCtx, itemPayload) {
626
+ const itemId = getItemKey(itemPayload);
627
+ const payload = (0, import_json.klona)(itemPayload);
628
+ const itemState = store.state[itemId];
629
+ store.produceState(
630
+ (draft) => {
631
+ const item = draft[itemId];
632
+ if (!item) {
633
+ draft[itemId] = {
634
+ data: null,
635
+ error: null,
636
+ status: "loading",
637
+ payload,
638
+ refetchOnMount: false,
639
+ wasLoaded: false
640
+ };
641
+ return;
642
+ }
643
+ item.status = item.data !== null ? "refetching" : "loading";
644
+ item.payload = payload;
645
+ item.error = null;
646
+ item.refetchOnMount = false;
647
+ },
648
+ {
649
+ equalityCheck: import_t_state3.deepEqual,
650
+ action: {
651
+ type: !itemState?.data ? "fetch-start-loading" : "fetch-start-refetching",
652
+ payload
653
+ }
654
+ }
655
+ );
656
+ try {
657
+ const data = await fetchFn(payload);
658
+ if (fetchCtx.shouldAbort())
659
+ return false;
660
+ store.produceState(
661
+ (draft) => {
662
+ const item = draft[itemId];
663
+ if (!item)
664
+ return;
665
+ item.data = data;
666
+ item.status = "success";
667
+ item.wasLoaded = true;
668
+ },
669
+ { action: { type: "fetch-success", payload } }
670
+ );
671
+ return true;
672
+ } catch (exception) {
673
+ if (fetchCtx.shouldAbort())
674
+ return false;
675
+ const error = errorNormalizer(exception);
676
+ store.produceState(
677
+ (draft) => {
678
+ const item = draft[itemId];
679
+ if (!item)
680
+ return;
681
+ item.error = error;
682
+ item.status = "error";
683
+ },
684
+ { action: { type: "fetch-error", payload, error } }
685
+ );
686
+ return false;
687
+ }
688
+ }
689
+ const fetchOrquestrator = createCollectionFetchOrquestrator({
690
+ fetchFn: fetch,
691
+ lowPriorityThrottleMs,
692
+ dynamicRealtimeThrottleMs,
693
+ mediumPriorityThrottleMs
694
+ });
695
+ function scheduleFetch(fetchType, payload) {
696
+ const multiplePayloads = Array.isArray(payload);
697
+ const payloads = multiplePayloads ? payload : [payload];
698
+ const results = [];
699
+ for (const param of payloads) {
700
+ const itemKey = getItemKey(param);
701
+ results.push(
702
+ fetchOrquestrator.get(itemKey).scheduleFetch(fetchType, param)
703
+ );
704
+ }
705
+ return multiplePayloads ? results : results[0];
706
+ }
707
+ async function awaitFetch(params) {
708
+ const itemId = getItemKey(params);
709
+ const wasAborted = await fetchOrquestrator.get(itemId).awaitFetch(params);
710
+ if (wasAborted) {
711
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
712
+ }
713
+ const item = store.state[itemId];
714
+ if (!item?.data) {
715
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
716
+ }
717
+ return item.error ? { data: null, error: item.error } : { data: item.data, error: null };
718
+ }
719
+ function getItemsKeyArray(params) {
720
+ const items = store.state;
721
+ if (Array.isArray(params)) {
722
+ return params.map(getItemKey);
723
+ } else if (typeof params === "function") {
724
+ return filterAndMap(Object.entries(items), ([itemKey, item], ignore2) => {
725
+ return item && params(item.payload, item.data) ? itemKey : ignore2;
726
+ });
727
+ } else {
728
+ return [getItemKey(params)];
729
+ }
730
+ }
731
+ const storeEvents = (0, import_mitt3.default)();
732
+ const invalidationWasTriggered = /* @__PURE__ */ new Set();
733
+ function invalidateItem(itemPayload, priority = "highPriority") {
734
+ const itemsKey = getItemsKeyArray(itemPayload);
735
+ for (const itemKey of itemsKey) {
736
+ store.produceState(
737
+ (draft) => {
738
+ const item = draft[itemKey];
739
+ if (!item)
740
+ return;
741
+ item.refetchOnMount = priority;
742
+ },
743
+ { action: { type: "invalidate-data", itemKey } }
744
+ );
745
+ invalidationWasTriggered.delete(itemKey);
746
+ storeEvents.emit("invalidateData", { priority, itemKey });
747
+ }
748
+ }
749
+ function getItemState(params) {
750
+ if (typeof params === "function" || Array.isArray(params)) {
751
+ const itemsId = getItemsKeyArray(params);
752
+ return filterAndMap(itemsId, (itemId, ignore2) => {
753
+ return store.state[itemId] || ignore2;
754
+ });
755
+ }
756
+ return store.state[getItemKey(params)];
757
+ }
758
+ function useMultipleItems(queries, {
759
+ selector,
760
+ omitPayload,
761
+ returnIdleStatus,
762
+ returnRefetchingStatus,
763
+ disableRefetchOnMount = globalDisableRefetchOnMount
764
+ } = {}) {
765
+ const queriesWithId = useDeepMemo(() => {
766
+ return queries.map((payload) => {
767
+ return { itemKey: getItemKey(payload), payload };
768
+ });
769
+ }, [queries]);
770
+ const dataSelector = (0, import_react4.useCallback)((itemState) => {
771
+ if (selector)
772
+ return selector(itemState);
773
+ return itemState;
774
+ }, []);
775
+ const resultSelector = (0, import_react4.useCallback)(
776
+ (state) => {
777
+ return queriesWithId.map(
778
+ ({
779
+ itemKey,
780
+ payload
781
+ }) => {
782
+ const item = state[itemKey];
783
+ if (item === null) {
784
+ return {
785
+ itemStateKey: itemKey,
786
+ status: "deleted",
787
+ data: dataSelector(null),
788
+ error: null,
789
+ payload: omitPayload ? void 0 : payload,
790
+ isLoading: false
791
+ };
792
+ }
793
+ if (!item) {
794
+ return {
795
+ itemStateKey: itemKey,
796
+ status: returnIdleStatus ? "idle" : "loading",
797
+ data: dataSelector(null),
798
+ error: null,
799
+ payload: omitPayload ? void 0 : payload,
800
+ isLoading: returnIdleStatus ? false : true
801
+ };
802
+ }
803
+ let status = item.status;
804
+ if (!returnRefetchingStatus && item.status === "refetching") {
805
+ status = "success";
806
+ }
807
+ return {
808
+ itemStateKey: itemKey,
809
+ status,
810
+ data: dataSelector(item.data),
811
+ error: item.error,
812
+ isLoading: status === "loading",
813
+ payload: omitPayload ? void 0 : item.payload
814
+ };
815
+ }
816
+ );
817
+ },
818
+ [
819
+ dataSelector,
820
+ omitPayload,
821
+ queriesWithId,
822
+ returnIdleStatus,
823
+ returnRefetchingStatus
824
+ ]
825
+ );
826
+ const storeState = store.useSelector(resultSelector, {
827
+ equalityFn: import_t_state3.deepEqual,
828
+ useExternalDeps: true
829
+ });
830
+ useOnMittEvent(storeEvents, "invalidateData", (event) => {
831
+ for (const { itemKey, payload } of queriesWithId) {
832
+ if (itemKey !== event.itemKey)
833
+ continue;
834
+ if (!invalidationWasTriggered.has(itemKey)) {
835
+ scheduleFetch(event.priority, payload);
836
+ invalidationWasTriggered.add(itemKey);
837
+ }
838
+ }
839
+ });
840
+ (0, import_react4.useEffect)(() => {
841
+ for (const { itemKey: itemId, payload } of queriesWithId) {
842
+ if (itemId) {
843
+ if (disableRefetchOnMount) {
844
+ const itemState = getItemState(payload);
845
+ const shouldFetch = !itemState?.wasLoaded || itemState.refetchOnMount;
846
+ if (shouldFetch) {
847
+ scheduleFetch(
848
+ itemState?.refetchOnMount || "lowPriority",
849
+ payload
850
+ );
851
+ return;
852
+ }
853
+ } else {
854
+ scheduleFetch("lowPriority", payload);
855
+ }
856
+ }
857
+ }
858
+ }, [disableRefetchOnMount, queriesWithId]);
859
+ return storeState;
860
+ }
861
+ function useItem(payload, options = {}) {
862
+ const { selector, ensureIsLoaded } = options;
863
+ const query = (0, import_react4.useMemo)(
864
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
865
+ [payload]
866
+ );
867
+ const item = useMultipleItems(query, options);
868
+ const result = (0, import_react4.useMemo)(
869
+ () => item[0] ?? {
870
+ payload: void 0,
871
+ data: selector ? selector(null) : null,
872
+ error: null,
873
+ status: "idle",
874
+ itemStateKey: "",
875
+ isLoading: false
876
+ },
877
+ [item]
878
+ );
879
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
880
+ ensureIsLoaded,
881
+ !!payload,
882
+ () => {
883
+ if (payload) {
884
+ scheduleFetch("highPriority", payload);
885
+ }
886
+ }
887
+ );
888
+ (0, import_t_state3.useSubscribeToStore)(store, ({ observe }) => {
889
+ if (!ensureIsLoaded)
890
+ return;
891
+ observe.ifSelector((state) => state[result.itemStateKey]?.status).change.then(({ current }) => {
892
+ if (current === "success" || current === "error") {
893
+ emitIsLoadedEvt("isLoaded", true);
894
+ }
895
+ });
896
+ });
897
+ return useModifyResult(result);
898
+ }
899
+ function startMutation(fetchParams) {
900
+ const itemKeys = getItemsKeyArray(fetchParams);
901
+ const endMutations = [];
902
+ for (const itemKey of itemKeys) {
903
+ endMutations.push(fetchOrquestrator.get(itemKey).startMutation());
904
+ }
905
+ return () => {
906
+ for (const endMutation of endMutations) {
907
+ endMutation();
908
+ }
909
+ };
910
+ }
911
+ function addItemToState(fetchParams, data) {
912
+ const itemKey = getItemKey(fetchParams);
913
+ store.produceState(
914
+ (draftState) => {
915
+ draftState[itemKey] = {
916
+ data,
917
+ status: "success",
918
+ wasLoaded: true,
919
+ refetchOnMount: false,
920
+ error: null,
921
+ payload: (0, import_json.klona)(fetchParams)
922
+ };
923
+ },
924
+ { action: { type: "create-item-state", payload: fetchParams } }
925
+ );
926
+ }
927
+ function deleteItemState(fetchParams) {
928
+ const itemKeys = getItemsKeyArray(fetchParams);
929
+ store.produceState(
930
+ (draftState) => {
931
+ for (const itemKey of itemKeys) {
932
+ draftState[itemKey] = null;
933
+ }
934
+ },
935
+ { action: { type: "delete-item-state", payload: fetchParams } }
936
+ );
937
+ }
938
+ function updateItemState(fetchParams, produceNewData, ifNothingWasUpdated) {
939
+ const itemKeys = getItemsKeyArray(fetchParams);
940
+ let someItemWasUpdated = false;
941
+ store.batch(
942
+ () => {
943
+ store.produceState((draftState) => {
944
+ for (const itemKey of itemKeys) {
945
+ const item = draftState[itemKey];
946
+ if (!item)
947
+ continue;
948
+ if (item.data) {
949
+ someItemWasUpdated = true;
950
+ const newData = produceNewData(item.data, item);
951
+ if (newData) {
952
+ item.data = newData;
953
+ }
954
+ }
955
+ }
956
+ });
957
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
958
+ ifNothingWasUpdated();
959
+ }
960
+ },
961
+ { type: "update-item-state", item: itemKeys }
962
+ );
963
+ return someItemWasUpdated;
964
+ }
965
+ if (!disableRefetchOnWindowFocus) {
966
+ let handleFocus2 = function() {
967
+ invalidateItem(() => true, "lowPriority");
968
+ };
969
+ var handleFocus = handleFocus2;
970
+ window.addEventListener("focus", handleFocus2);
971
+ window.addEventListener("visibilitychange", handleFocus2);
972
+ }
973
+ return {
974
+ store,
975
+ scheduleFetch,
976
+ awaitFetch,
977
+ useMultipleItems,
978
+ useItem,
979
+ getItemKey,
980
+ getItemState,
981
+ startMutation,
982
+ invalidateItem,
983
+ updateItemState,
984
+ addItemToState,
985
+ deleteItemState
986
+ };
987
+ }
988
+
989
+ // src/listQueryStore.ts
990
+ var import_mitt4 = __toESM(require("mitt"), 1);
991
+ var import_react5 = require("react");
992
+ var import_t_state4 = require("t-state");
993
+ var import_json2 = require("klona/json");
994
+ var noFetchFnError = "No fetchItemFn was provided";
995
+ function newTSDFListQueryStore({
996
+ debugName,
997
+ fetchListFn,
998
+ fetchItemFn,
999
+ errorNormalizer,
1000
+ defaultQuerySize = 50,
1001
+ disableRefetchOnWindowFocus,
1002
+ disableRefetchOnMount: globalDisableRefetchOnMount,
1003
+ lowPriorityThrottleMs,
1004
+ mediumPriorityThrottleMs,
1005
+ dynamicRealtimeThrottleMs,
1006
+ syncMutationsAndInvalidations
1007
+ }) {
1008
+ const store = new import_t_state4.Store({
1009
+ debugName,
1010
+ state: { items: {}, queries: {}, itemQueries: {} }
1011
+ });
1012
+ function getQueryKey(params) {
1013
+ return getCacheId(params);
1014
+ }
1015
+ function getItemKey(params) {
1016
+ return getCacheId(params);
1017
+ }
1018
+ async function fetchQuery(fetchCtx, [fetchType, queryPayload, size = defaultQuerySize]) {
1019
+ const payload = (0, import_json2.klona)(queryPayload);
1020
+ const queryKey = getQueryKey(payload);
1021
+ const queryState = store.state.queries[queryKey];
1022
+ const isLoading = !queryState?.wasLoaded;
1023
+ store.produceState(
1024
+ (draft) => {
1025
+ const query = draft.queries[queryKey];
1026
+ if (!query) {
1027
+ draft.queries[queryKey] = {
1028
+ error: null,
1029
+ status: "loading",
1030
+ wasLoaded: false,
1031
+ payload,
1032
+ refetchOnMount: false,
1033
+ hasMore: false,
1034
+ items: []
1035
+ };
1036
+ return;
1037
+ }
1038
+ query.status = query.wasLoaded ? fetchType === "loadMore" ? "loadingMore" : "refetching" : "loading";
1039
+ query.error = null;
1040
+ query.refetchOnMount = false;
1041
+ },
1042
+ {
1043
+ equalityCheck: import_t_state4.deepEqual,
1044
+ action: {
1045
+ type: isLoading ? "fetch-query-start-loading" : fetchType === "loadMore" ? "fetch-query-loading-more" : "refetching-query-start",
1046
+ payload
1047
+ }
1048
+ }
1049
+ );
1050
+ const currentQuerySize = queryState?.items.length ?? 0;
1051
+ const querySize = (() => {
1052
+ if (fetchType === "loadMore") {
1053
+ return currentQuerySize + size;
1054
+ }
1055
+ if (isLoading)
1056
+ return size;
1057
+ return Math.max(currentQuerySize, size);
1058
+ })();
1059
+ try {
1060
+ const { items, hasMore } = await fetchListFn(payload, querySize);
1061
+ if (fetchCtx.shouldAbort())
1062
+ return false;
1063
+ store.produceState(
1064
+ (draft) => {
1065
+ const query = draft.queries[queryKey];
1066
+ if (!query)
1067
+ return;
1068
+ query.status = "success";
1069
+ query.wasLoaded = true;
1070
+ query.hasMore = hasMore;
1071
+ query.items = [];
1072
+ for (const { data, itemPayload } of items) {
1073
+ const itemKey = getItemKey(itemPayload);
1074
+ draft.items[itemKey] = data;
1075
+ query.items.push(String(itemKey));
1076
+ const itemQuery = draft.itemQueries[itemKey];
1077
+ if (!itemQuery || itemQuery.status !== "loading" && itemQuery.status !== "refetching") {
1078
+ draft.itemQueries[itemKey] = {
1079
+ error: null,
1080
+ refetchOnMount: false,
1081
+ status: "success",
1082
+ wasLoaded: true,
1083
+ payload: itemPayload
1084
+ };
1085
+ }
1086
+ }
1087
+ },
1088
+ {
1089
+ action: { type: "fetch-query-success", payload }
1090
+ }
1091
+ );
1092
+ for (const { itemPayload: id } of items) {
1093
+ const itemFetchOrquestrator = fetchItemOrquestrator?.get(String(id));
1094
+ if (itemFetchOrquestrator) {
1095
+ itemFetchOrquestrator.setLastFetchStartTime(fetchCtx.getStartTime());
1096
+ }
1097
+ }
1098
+ return true;
1099
+ } catch (exception) {
1100
+ if (fetchCtx.shouldAbort())
1101
+ return false;
1102
+ const error = errorNormalizer(exception);
1103
+ store.produceState(
1104
+ (draft) => {
1105
+ const query = draft.queries[queryKey];
1106
+ if (!query)
1107
+ return;
1108
+ query.status = "error";
1109
+ query.error = error;
1110
+ },
1111
+ {
1112
+ action: { type: "fetch-query-error", payload, error }
1113
+ }
1114
+ );
1115
+ return false;
1116
+ }
1117
+ }
1118
+ function getQueryState(params) {
1119
+ return store.state.queries[getQueryKey(params)];
1120
+ }
1121
+ function getItemState(itemPayload) {
1122
+ if (typeof itemPayload === "function" || Array.isArray(itemPayload)) {
1123
+ const itemsId = getItemsKeyArray(itemPayload);
1124
+ return filterAndMap(itemsId, ({ itemKey }, ignore2) => {
1125
+ const item = store.state.items[itemKey];
1126
+ const payload = store.state.itemQueries[itemKey]?.payload;
1127
+ return !item || !payload ? ignore2 : { payload, data: item };
1128
+ });
1129
+ }
1130
+ return store.state.items[getItemKey(itemPayload)];
1131
+ }
1132
+ const fetchQueryOrquestrator = createCollectionFetchOrquestrator({
1133
+ fetchFn: fetchQuery,
1134
+ lowPriorityThrottleMs,
1135
+ dynamicRealtimeThrottleMs,
1136
+ mediumPriorityThrottleMs
1137
+ });
1138
+ function scheduleListQueryFetch(fetchType, payload, size) {
1139
+ const multiplePayloads = Array.isArray(payload);
1140
+ const payloads = multiplePayloads ? payload : [payload];
1141
+ const results = payloads.map((param) => {
1142
+ return fetchQueryOrquestrator.get(getQueryKey(param)).scheduleFetch(fetchType, ["load", param, size]);
1143
+ });
1144
+ return multiplePayloads ? results : results[0];
1145
+ }
1146
+ function loadMore(params, size) {
1147
+ const queryState = getQueryState(params);
1148
+ if (!queryState || !queryState.hasMore)
1149
+ return "skipped";
1150
+ return fetchQueryOrquestrator.get(getQueryKey(params)).scheduleFetch("highPriority", ["loadMore", params, size]);
1151
+ }
1152
+ function getQueryItems(query, itemDataSelector) {
1153
+ return filterAndMap(query.items, (itemKey, ignore2) => {
1154
+ const item = store.state.items[itemKey];
1155
+ return item ? itemDataSelector(item, itemKey) : ignore2;
1156
+ });
1157
+ }
1158
+ async function awaitListQueryFetch(params, size = defaultQuerySize) {
1159
+ const queryKey = getQueryKey(params);
1160
+ const wasAborted = await fetchQueryOrquestrator.get(queryKey).awaitFetch(["load", params, size]);
1161
+ if (wasAborted) {
1162
+ return {
1163
+ items: [],
1164
+ error: errorNormalizer(new Error("Aborted")),
1165
+ hasMore: false
1166
+ };
1167
+ }
1168
+ const query = store.state.queries[queryKey];
1169
+ if (!query) {
1170
+ return {
1171
+ items: [],
1172
+ error: errorNormalizer(new Error("Not found")),
1173
+ hasMore: false
1174
+ };
1175
+ }
1176
+ return query.error ? { items: [], error: query.error, hasMore: query.hasMore } : {
1177
+ items: getQueryItems(query, (data, itemKey) => ({ data, itemKey })),
1178
+ error: null,
1179
+ hasMore: query.hasMore
1180
+ };
1181
+ }
1182
+ async function awaitItemFetch(itemPayload) {
1183
+ if (!fetchItemOrquestrator)
1184
+ throw new Error(noFetchFnError);
1185
+ const itemKey = getItemKey(itemPayload);
1186
+ const wasAborted = await fetchItemOrquestrator.get(itemKey).awaitFetch(itemPayload);
1187
+ if (wasAborted) {
1188
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
1189
+ }
1190
+ const item = store.state.items[itemKey];
1191
+ const itemQuery = store.state.itemQueries[itemKey];
1192
+ if (!itemQuery || !item) {
1193
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
1194
+ }
1195
+ return itemQuery.error ? { data: null, error: itemQuery.error } : { data: item, error: null };
1196
+ }
1197
+ function getQueriesKeyArray(payloads) {
1198
+ if (Array.isArray(payloads)) {
1199
+ return payloads.map((payload) => ({
1200
+ key: getQueryKey(payload),
1201
+ payload
1202
+ }));
1203
+ } else if (typeof payloads === "function") {
1204
+ return filterAndMap(
1205
+ Object.entries(store.state.queries),
1206
+ ([queryKey, query], ignore2) => {
1207
+ return payloads(query.payload, query, queryKey) ? {
1208
+ key: queryKey,
1209
+ payload: query.payload
1210
+ } : ignore2;
1211
+ }
1212
+ );
1213
+ } else {
1214
+ return [{ key: getQueryKey(payloads), payload: payloads }];
1215
+ }
1216
+ }
1217
+ const storeEvents = (0, import_mitt4.default)();
1218
+ const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
1219
+ function invalidateQuery(queryPayload, priority = "highPriority", ignoreInvalidationSync = false) {
1220
+ const queriesKey = getQueriesKeyArray(queryPayload);
1221
+ for (const { key } of queriesKey) {
1222
+ store.produceState(
1223
+ (draft) => {
1224
+ const query = draft.queries[key];
1225
+ if (!query)
1226
+ return;
1227
+ query.refetchOnMount = priority;
1228
+ },
1229
+ { action: { type: "invalidate-data", key } }
1230
+ );
1231
+ queryInvalidationWasTriggered.delete(key);
1232
+ storeEvents.emit("invalidateQuery", { priority, queryKey: key });
1233
+ }
1234
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1235
+ invalidateItem(
1236
+ (itemPayload) => queriesKey.some(({ payload }) => {
1237
+ return syncMutationsAndInvalidations.syncItemAndQuery(
1238
+ itemPayload,
1239
+ payload
1240
+ );
1241
+ }),
1242
+ priority,
1243
+ true
1244
+ );
1245
+ invalidateQuery(
1246
+ (queryToInvalidatePayload, _, queryToInvalidateKey) => queriesKey.some((alreadyInvalidatedQueryPayload) => {
1247
+ return queryToInvalidateKey !== alreadyInvalidatedQueryPayload.key && syncMutationsAndInvalidations.syncQueries(
1248
+ alreadyInvalidatedQueryPayload.payload,
1249
+ queryToInvalidatePayload
1250
+ );
1251
+ }),
1252
+ priority,
1253
+ true
1254
+ );
1255
+ }
1256
+ }
1257
+ function defaultItemSelector(data, id) {
1258
+ return { id, data };
1259
+ }
1260
+ function useMultipleListQueries(queries, {
1261
+ itemSelector = defaultItemSelector,
1262
+ omitPayload,
1263
+ returnIdleStatus,
1264
+ returnRefetchingStatus,
1265
+ loadSize,
1266
+ disableRefetchOnMount = globalDisableRefetchOnMount
1267
+ } = {}) {
1268
+ const queriesWithId = useDeepMemo(() => {
1269
+ return queries.map((payload) => {
1270
+ return {
1271
+ key: getQueryKey(payload),
1272
+ payload
1273
+ };
1274
+ });
1275
+ }, [queries]);
1276
+ const dataSelector = (0, import_react5.useCallback)(itemSelector, []);
1277
+ const resultSelector = (0, import_react5.useCallback)(
1278
+ (state) => {
1279
+ return queriesWithId.map(
1280
+ ({
1281
+ key: queryKey,
1282
+ payload
1283
+ }) => {
1284
+ const query = state.queries[queryKey];
1285
+ if (!query) {
1286
+ return {
1287
+ queryKey,
1288
+ status: returnIdleStatus ? "idle" : "loading",
1289
+ items: [],
1290
+ error: null,
1291
+ hasMore: false,
1292
+ payload: omitPayload ? void 0 : payload,
1293
+ isLoading: returnIdleStatus ? false : true
1294
+ };
1295
+ }
1296
+ let status = query.status;
1297
+ if (!returnRefetchingStatus && query.status === "refetching") {
1298
+ status = "success";
1299
+ }
1300
+ return {
1301
+ queryKey,
1302
+ status,
1303
+ items: getQueryItems(query, dataSelector),
1304
+ error: query.error,
1305
+ hasMore: query.hasMore,
1306
+ isLoading: status === "loading",
1307
+ payload: omitPayload ? void 0 : query.payload
1308
+ };
1309
+ }
1310
+ );
1311
+ },
1312
+ [
1313
+ dataSelector,
1314
+ omitPayload,
1315
+ queriesWithId,
1316
+ returnIdleStatus,
1317
+ returnRefetchingStatus
1318
+ ]
1319
+ );
1320
+ const storeState = store.useSelector(resultSelector, {
1321
+ equalityFn: import_t_state4.deepEqual,
1322
+ useExternalDeps: true
1323
+ });
1324
+ useOnMittEvent(storeEvents, "invalidateQuery", (event) => {
1325
+ for (const { key, payload } of queriesWithId) {
1326
+ if (key !== event.queryKey)
1327
+ continue;
1328
+ if (!queryInvalidationWasTriggered.has(key)) {
1329
+ scheduleListQueryFetch(event.priority, payload);
1330
+ queryInvalidationWasTriggered.add(key);
1331
+ }
1332
+ }
1333
+ });
1334
+ const loadSizeConst = useConst(() => loadSize);
1335
+ (0, import_react5.useEffect)(() => {
1336
+ for (const { key: itemId, payload: fetchParams } of queriesWithId) {
1337
+ if (itemId) {
1338
+ if (disableRefetchOnMount) {
1339
+ const itemState = getQueryState(fetchParams);
1340
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1341
+ if (shouldFetch) {
1342
+ scheduleListQueryFetch(
1343
+ itemState?.refetchOnMount || "lowPriority",
1344
+ fetchParams,
1345
+ loadSizeConst
1346
+ );
1347
+ return;
1348
+ }
1349
+ } else {
1350
+ scheduleListQueryFetch("lowPriority", fetchParams, loadSizeConst);
1351
+ }
1352
+ }
1353
+ }
1354
+ }, [disableRefetchOnMount, loadSizeConst, queriesWithId]);
1355
+ return storeState;
1356
+ }
1357
+ function useListQuery(payload, options = {}) {
1358
+ const { ensureIsLoaded } = options;
1359
+ const query = (0, import_react5.useMemo)(
1360
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
1361
+ [payload]
1362
+ );
1363
+ const queryResult = useMultipleListQueries(query, options);
1364
+ const result = (0, import_react5.useMemo)(
1365
+ () => queryResult[0] ?? {
1366
+ payload: void 0,
1367
+ error: null,
1368
+ hasMore: false,
1369
+ isLoading: false,
1370
+ status: "idle",
1371
+ queryKey: "",
1372
+ items: []
1373
+ },
1374
+ [queryResult]
1375
+ );
1376
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1377
+ ensureIsLoaded,
1378
+ !!payload,
1379
+ () => {
1380
+ if (payload) {
1381
+ scheduleListQueryFetch("highPriority", payload);
1382
+ }
1383
+ }
1384
+ );
1385
+ (0, import_t_state4.useSubscribeToStore)(store, ({ observe }) => {
1386
+ if (!ensureIsLoaded)
1387
+ return;
1388
+ observe.ifSelector((state) => state.queries[result.queryKey]?.status).change.then(({ current }) => {
1389
+ if (current === "success" || current === "error") {
1390
+ emitIsLoadedEvt("isLoaded", true);
1391
+ }
1392
+ });
1393
+ });
1394
+ return useModifyResult(result);
1395
+ }
1396
+ async function fetchItem(fetchCtx, itemPayload) {
1397
+ if (!fetchItemOrquestrator) {
1398
+ throw new Error(noFetchFnError);
1399
+ }
1400
+ const itemKey = getCacheId(itemPayload);
1401
+ const isLoaded = !store.state.itemQueries[itemKey]?.wasLoaded;
1402
+ store.produceState(
1403
+ (draft) => {
1404
+ const itemQuery = draft.itemQueries[itemKey];
1405
+ if (!itemQuery) {
1406
+ draft.itemQueries[itemKey] = {
1407
+ status: "loading",
1408
+ error: null,
1409
+ wasLoaded: false,
1410
+ refetchOnMount: false,
1411
+ payload: (0, import_json2.klona)(itemPayload)
1412
+ };
1413
+ return;
1414
+ }
1415
+ itemQuery.status = itemQuery.wasLoaded ? "refetching" : "loading";
1416
+ itemQuery.error = null;
1417
+ itemQuery.refetchOnMount = false;
1418
+ },
1419
+ {
1420
+ action: {
1421
+ type: isLoaded ? "fetch-item-start" : "fetch-item-refetch-start",
1422
+ itemPayload
1423
+ }
1424
+ }
1425
+ );
1426
+ try {
1427
+ const item = await fetchItemFn(itemPayload);
1428
+ if (fetchCtx.shouldAbort())
1429
+ return false;
1430
+ store.produceState(
1431
+ (draft) => {
1432
+ const itemQuery = draft.itemQueries[itemKey];
1433
+ if (!itemQuery)
1434
+ return;
1435
+ itemQuery.status = "success";
1436
+ itemQuery.wasLoaded = true;
1437
+ draft.items[itemKey] = item;
1438
+ },
1439
+ {
1440
+ action: { type: "fetch-item-success", itemPayload }
1441
+ }
1442
+ );
1443
+ return true;
1444
+ } catch (exception) {
1445
+ if (fetchCtx.shouldAbort())
1446
+ return false;
1447
+ const error = errorNormalizer(exception);
1448
+ store.produceState(
1449
+ (draft) => {
1450
+ const itemQuery = draft.itemQueries[itemKey];
1451
+ if (!itemQuery)
1452
+ return;
1453
+ itemQuery.status = "error";
1454
+ itemQuery.error = error;
1455
+ },
1456
+ {
1457
+ action: { type: "fetch-item-error", itemPayload }
1458
+ }
1459
+ );
1460
+ return false;
1461
+ }
1462
+ }
1463
+ const fetchItemOrquestrator = fetchItemFn && createCollectionFetchOrquestrator({
1464
+ fetchFn: fetchItem,
1465
+ lowPriorityThrottleMs,
1466
+ dynamicRealtimeThrottleMs,
1467
+ mediumPriorityThrottleMs
1468
+ });
1469
+ function scheduleItemFetch(fetchType, itemPayload) {
1470
+ if (!fetchItemOrquestrator) {
1471
+ throw new Error(noFetchFnError);
1472
+ }
1473
+ const fetchMultiple = Array.isArray(itemPayload);
1474
+ const itemsId = fetchMultiple ? itemPayload : [itemPayload];
1475
+ const results = itemsId.map((payload) => {
1476
+ const itemKey = getCacheId(payload);
1477
+ return fetchItemOrquestrator.get(itemKey).scheduleFetch(fetchType, payload);
1478
+ });
1479
+ return fetchMultiple ? results : results[0];
1480
+ }
1481
+ function getItemsKeyArray(itemsPayload) {
1482
+ if (Array.isArray(itemsPayload)) {
1483
+ return itemsPayload.map((payload) => ({
1484
+ itemKey: getItemKey(payload),
1485
+ payload
1486
+ }));
1487
+ }
1488
+ if (typeof itemsPayload === "function") {
1489
+ return filterAndMap(
1490
+ Object.entries(store.state.items),
1491
+ ([itemKey, item], ignore2) => {
1492
+ const payload = store.state.itemQueries[itemKey]?.payload;
1493
+ if (item === null || !payload)
1494
+ return ignore2;
1495
+ return itemsPayload(payload, item) ? { itemKey, payload } : ignore2;
1496
+ }
1497
+ );
1498
+ }
1499
+ return [{ payload: itemsPayload, itemKey: getItemKey(itemsPayload) }];
1500
+ }
1501
+ const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
1502
+ function invalidateItem(itemId, priority = "highPriority", ignoreInvalidationSync = false) {
1503
+ if (!fetchItemOrquestrator) {
1504
+ throw new Error(noFetchFnError);
1505
+ }
1506
+ const itemsKey = getItemsKeyArray(itemId);
1507
+ for (const { itemKey } of itemsKey) {
1508
+ store.produceState(
1509
+ (draft) => {
1510
+ const query = draft.itemQueries[itemKey];
1511
+ if (!query)
1512
+ return;
1513
+ query.refetchOnMount = priority;
1514
+ },
1515
+ { action: { type: "invalidate-item", queryKey: itemKey } }
1516
+ );
1517
+ itemInvalidationWasTriggered.delete(itemKey);
1518
+ storeEvents.emit("invalidateItem", { priority, itemKey });
1519
+ }
1520
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1521
+ invalidateQuery(
1522
+ (query) => itemsKey.some(
1523
+ ({ payload }) => syncMutationsAndInvalidations.syncItemAndQuery(payload, query)
1524
+ ),
1525
+ priority,
1526
+ true
1527
+ );
1528
+ }
1529
+ }
1530
+ function startItemMutation(itemId) {
1531
+ if (!fetchItemOrquestrator)
1532
+ throw new Error(noFetchFnError);
1533
+ const itemsKey = getItemsKeyArray(itemId);
1534
+ const endMutations = [];
1535
+ for (const { itemKey, payload } of itemsKey) {
1536
+ endMutations.push(fetchItemOrquestrator.get(itemKey).startMutation());
1537
+ if (syncMutationsAndInvalidations) {
1538
+ for (const [queryKey, query] of Object.entries(store.state.queries)) {
1539
+ if (syncMutationsAndInvalidations.syncItemAndQuery(
1540
+ payload,
1541
+ query.payload
1542
+ )) {
1543
+ endMutations.push(
1544
+ fetchQueryOrquestrator.get(queryKey).startMutation()
1545
+ );
1546
+ }
1547
+ }
1548
+ }
1549
+ }
1550
+ return () => {
1551
+ for (const endMutation of endMutations) {
1552
+ endMutation();
1553
+ }
1554
+ };
1555
+ }
1556
+ function defaultItemDataSelector(data) {
1557
+ return data;
1558
+ }
1559
+ function useMultipleItems(itemsPayload_, {
1560
+ selector = defaultItemDataSelector,
1561
+ returnIdleStatus,
1562
+ returnRefetchingStatus,
1563
+ disableRefetchOnMount
1564
+ } = {}) {
1565
+ const dataSelector = (0, import_react5.useCallback)(selector, []);
1566
+ const memoizedItemKeys = useDeepMemo(
1567
+ () => itemsPayload_.map(
1568
+ (itemPayload) => ({
1569
+ payload: itemPayload,
1570
+ itemKey: getItemKey(itemPayload)
1571
+ })
1572
+ ),
1573
+ [itemsPayload_]
1574
+ );
1575
+ const resultSelector = (0, import_react5.useCallback)(
1576
+ (state) => {
1577
+ return memoizedItemKeys.map(
1578
+ ({
1579
+ itemKey,
1580
+ payload
1581
+ }) => {
1582
+ const itemQuery = state.itemQueries[itemKey];
1583
+ const itemState = state.items[itemKey];
1584
+ if (itemQuery === null) {
1585
+ return {
1586
+ status: "deleted",
1587
+ error: null,
1588
+ isLoading: false,
1589
+ payload,
1590
+ data: dataSelector(null, itemKey)
1591
+ };
1592
+ }
1593
+ if (!itemQuery) {
1594
+ return {
1595
+ status: returnIdleStatus ? "idle" : "loading",
1596
+ error: null,
1597
+ isLoading: returnIdleStatus ? false : true,
1598
+ payload,
1599
+ data: dataSelector(null, itemKey)
1600
+ };
1601
+ }
1602
+ let status = itemQuery.status;
1603
+ if (!returnRefetchingStatus && itemQuery.status === "refetching") {
1604
+ status = "success";
1605
+ }
1606
+ return {
1607
+ status,
1608
+ error: itemQuery.error,
1609
+ isLoading: status === "loading",
1610
+ data: dataSelector(itemState ?? null, itemKey),
1611
+ payload
1612
+ };
1613
+ }
1614
+ );
1615
+ },
1616
+ [
1617
+ dataSelector,
1618
+ memoizedItemKeys,
1619
+ returnIdleStatus,
1620
+ returnRefetchingStatus
1621
+ ]
1622
+ );
1623
+ const storeState = store.useSelector(resultSelector, {
1624
+ equalityFn: import_t_state4.deepEqual,
1625
+ useExternalDeps: true
1626
+ });
1627
+ useOnMittEvent(storeEvents, "invalidateItem", (event) => {
1628
+ for (const { payload, itemKey } of memoizedItemKeys) {
1629
+ if (itemKey !== event.itemKey)
1630
+ continue;
1631
+ if (!itemInvalidationWasTriggered.has(itemKey)) {
1632
+ scheduleItemFetch(event.priority, payload);
1633
+ itemInvalidationWasTriggered.add(itemKey);
1634
+ }
1635
+ }
1636
+ });
1637
+ (0, import_react5.useEffect)(() => {
1638
+ for (const { payload, itemKey } of memoizedItemKeys) {
1639
+ if (itemKey) {
1640
+ if (disableRefetchOnMount) {
1641
+ const itemState = store.state.itemQueries[itemKey];
1642
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1643
+ if (shouldFetch) {
1644
+ scheduleItemFetch(
1645
+ itemState?.refetchOnMount || "lowPriority",
1646
+ payload
1647
+ );
1648
+ return;
1649
+ }
1650
+ } else {
1651
+ scheduleItemFetch("lowPriority", payload);
1652
+ }
1653
+ }
1654
+ }
1655
+ }, [disableRefetchOnMount, memoizedItemKeys]);
1656
+ return storeState;
1657
+ }
1658
+ function useItem(itemPayload, options = {}) {
1659
+ const { ensureIsLoaded } = options;
1660
+ const query = (0, import_react5.useMemo)(
1661
+ () => itemPayload === false || itemPayload === null || itemPayload === void 0 ? [] : [itemPayload],
1662
+ [itemPayload]
1663
+ );
1664
+ const queryResult = useMultipleItems(query, options);
1665
+ const memoizedSelector = (0, import_react5.useCallback)(
1666
+ options.selector ?? defaultItemDataSelector,
1667
+ []
1668
+ );
1669
+ const result = (0, import_react5.useMemo)(
1670
+ () => queryResult[0] ?? {
1671
+ error: null,
1672
+ isLoading: false,
1673
+ status: "idle",
1674
+ data: memoizedSelector(null, ""),
1675
+ payload: itemPayload || null
1676
+ },
1677
+ [itemPayload, memoizedSelector, queryResult]
1678
+ );
1679
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1680
+ ensureIsLoaded,
1681
+ !!itemPayload,
1682
+ () => {
1683
+ if (itemPayload) {
1684
+ scheduleItemFetch("highPriority", itemPayload);
1685
+ }
1686
+ }
1687
+ );
1688
+ (0, import_t_state4.useSubscribeToStore)(store, ({ observe }) => {
1689
+ if (!ensureIsLoaded || !itemPayload)
1690
+ return;
1691
+ observe.ifSelector((state) => state.itemQueries[itemPayload]?.status).change.then(({ current }) => {
1692
+ if (current === "success" || current === "error") {
1693
+ emitIsLoadedEvt("isLoaded", true);
1694
+ }
1695
+ });
1696
+ });
1697
+ return useModifyResult(result);
1698
+ }
1699
+ function updateItemState(itemIds, produceNewData, ifNothingWasUpdated) {
1700
+ const itemKeys = getItemsKeyArray(itemIds);
1701
+ let someItemWasUpdated = false;
1702
+ store.batch(
1703
+ () => {
1704
+ store.produceState((draftState) => {
1705
+ for (const { itemKey, payload } of itemKeys) {
1706
+ const item = draftState.items[itemKey];
1707
+ if (!item)
1708
+ continue;
1709
+ someItemWasUpdated = true;
1710
+ const newData = produceNewData(item, payload);
1711
+ if (newData) {
1712
+ draftState.items[itemKey] = newData;
1713
+ }
1714
+ }
1715
+ });
1716
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
1717
+ ifNothingWasUpdated();
1718
+ }
1719
+ },
1720
+ { type: "update-item-state", item: itemKeys }
1721
+ );
1722
+ return someItemWasUpdated;
1723
+ }
1724
+ function addItemToState(itemPayload, data) {
1725
+ const itemKey = getItemKey(itemPayload);
1726
+ store.produceState(
1727
+ (draftState) => {
1728
+ draftState.items[itemKey] = data;
1729
+ draftState.itemQueries[itemKey] = {
1730
+ status: "success",
1731
+ wasLoaded: true,
1732
+ refetchOnMount: false,
1733
+ error: null,
1734
+ payload: (0, import_json2.klona)(itemPayload)
1735
+ };
1736
+ },
1737
+ { action: { type: "create-item-state", itemPayload } }
1738
+ );
1739
+ }
1740
+ function deleteItemState(itemId) {
1741
+ const itemsId = getItemsKeyArray(itemId);
1742
+ store.produceState(
1743
+ (draftState) => {
1744
+ for (const { itemKey } of itemsId) {
1745
+ draftState.items[itemKey] = null;
1746
+ draftState.itemQueries[itemKey] = null;
1747
+ for (const query of Object.values(draftState.queries)) {
1748
+ if (query.items.includes(itemKey)) {
1749
+ query.items = query.items.filter((i) => i !== itemKey);
1750
+ }
1751
+ }
1752
+ }
1753
+ },
1754
+ { action: { type: "delete-item-state", itemId } }
1755
+ );
1756
+ }
1757
+ if (!disableRefetchOnWindowFocus) {
1758
+ let handleFocus2 = function() {
1759
+ invalidateQuery(() => true, "lowPriority");
1760
+ invalidateItem(() => true, "lowPriority");
1761
+ };
1762
+ var handleFocus = handleFocus2;
1763
+ window.addEventListener("focus", handleFocus2);
1764
+ window.addEventListener("visibilitychange", handleFocus2);
1765
+ }
1766
+ return {
1767
+ store,
1768
+ scheduleListQueryFetch,
1769
+ getQueryState,
1770
+ getQueryKey,
1771
+ deleteItemState,
1772
+ getItemState,
1773
+ loadMore,
1774
+ invalidateQuery,
1775
+ invalidateItem,
1776
+ scheduleItemFetch,
1777
+ awaitItemFetch,
1778
+ awaitListQueryFetch,
1779
+ useMultipleListQueries,
1780
+ useListQuery,
1781
+ getItemKey,
1782
+ useItem,
1783
+ useMultipleItems,
1784
+ addItemToState,
1785
+ updateItemState,
1786
+ startItemMutation
1787
+ };
1788
+ }
1789
+ // Annotate the CommonJS export names for ESM import in node:
1790
+ 0 && (module.exports = {
1791
+ newTSDFCollectionStore,
1792
+ newTSDFDocumentStore,
1793
+ newTSDFListQueryStore
1794
+ });