tsdf 8.0.0-beta.2 → 8.0.0-beta.4

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,1761 @@
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" ? 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/utils/serializableClone.ts
604
+ function serializableClone(input) {
605
+ return JSON.parse(JSON.stringify(input));
606
+ }
607
+
608
+ // src/collectionStore.ts
609
+ function newTSDFCollectionStore({
610
+ debugName,
611
+ fetchFn,
612
+ disableRefetchOnWindowFocus,
613
+ lowPriorityThrottleMs,
614
+ errorNormalizer,
615
+ mediumPriorityThrottleMs,
616
+ disableRefetchOnMount: globalDisableRefetchOnMount,
617
+ dynamicRealtimeThrottleMs,
618
+ getCollectionItemKey: filterCollectionItemObjKey
619
+ }) {
620
+ const store = new import_t_state3.Store({
621
+ debugName,
622
+ state: {}
623
+ });
624
+ function getItemKey(params) {
625
+ return getCacheId(
626
+ filterCollectionItemObjKey ? filterCollectionItemObjKey(params) : params
627
+ );
628
+ }
629
+ async function fetch(fetchCtx, itemPayload) {
630
+ const itemId = getItemKey(itemPayload);
631
+ const payload = serializableClone(itemPayload);
632
+ const itemState = store.state[itemId];
633
+ store.produceState(
634
+ (draft) => {
635
+ const item = draft[itemId];
636
+ if (!item) {
637
+ draft[itemId] = {
638
+ data: null,
639
+ error: null,
640
+ status: "loading",
641
+ payload,
642
+ refetchOnMount: false,
643
+ wasLoaded: false
644
+ };
645
+ return;
646
+ }
647
+ item.status = item.data !== null ? "refetching" : "loading";
648
+ item.payload = payload;
649
+ item.error = null;
650
+ item.refetchOnMount = false;
651
+ },
652
+ {
653
+ equalityCheck: import_t_state3.deepEqual,
654
+ action: {
655
+ type: !itemState?.data ? "fetch-start-loading" : "fetch-start-refetching",
656
+ payload
657
+ }
658
+ }
659
+ );
660
+ try {
661
+ const data = await fetchFn(payload);
662
+ if (fetchCtx.shouldAbort())
663
+ return false;
664
+ store.produceState(
665
+ (draft) => {
666
+ const item = draft[itemId];
667
+ if (!item)
668
+ return;
669
+ item.data = data;
670
+ item.status = "success";
671
+ item.wasLoaded = true;
672
+ },
673
+ { action: { type: "fetch-success", payload } }
674
+ );
675
+ return true;
676
+ } catch (exception) {
677
+ if (fetchCtx.shouldAbort())
678
+ return false;
679
+ const error = errorNormalizer(exception);
680
+ store.produceState(
681
+ (draft) => {
682
+ const item = draft[itemId];
683
+ if (!item)
684
+ return;
685
+ item.error = error;
686
+ item.status = "error";
687
+ },
688
+ { action: { type: "fetch-error", payload, error } }
689
+ );
690
+ return false;
691
+ }
692
+ }
693
+ const fetchOrquestrator = createCollectionFetchOrquestrator({
694
+ fetchFn: fetch,
695
+ lowPriorityThrottleMs,
696
+ dynamicRealtimeThrottleMs,
697
+ mediumPriorityThrottleMs
698
+ });
699
+ function scheduleFetch(fetchType, payload) {
700
+ const multiplePayloads = Array.isArray(payload);
701
+ const payloads = multiplePayloads ? payload : [payload];
702
+ const results = [];
703
+ for (const param of payloads) {
704
+ const itemKey = getItemKey(param);
705
+ results.push(
706
+ fetchOrquestrator.get(itemKey).scheduleFetch(fetchType, param)
707
+ );
708
+ }
709
+ return multiplePayloads ? results : results[0];
710
+ }
711
+ async function awaitFetch(params) {
712
+ const itemId = getItemKey(params);
713
+ const wasAborted = await fetchOrquestrator.get(itemId).awaitFetch(params);
714
+ if (wasAborted) {
715
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
716
+ }
717
+ const item = store.state[itemId];
718
+ if (!item?.data) {
719
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
720
+ }
721
+ return item.error ? { data: null, error: item.error } : { data: item.data, error: null };
722
+ }
723
+ function getItemsKeyArray(params) {
724
+ const items = store.state;
725
+ if (Array.isArray(params)) {
726
+ return params.map(getItemKey);
727
+ } else if (typeof params === "function") {
728
+ return filterAndMap(Object.entries(items), ([itemKey, item], ignore2) => {
729
+ return item && params(item.payload, item.data) ? itemKey : ignore2;
730
+ });
731
+ } else {
732
+ return [getItemKey(params)];
733
+ }
734
+ }
735
+ const storeEvents = (0, import_mitt3.default)();
736
+ const invalidationWasTriggered = /* @__PURE__ */ new Set();
737
+ function invalidateItem(itemPayload, priority = "highPriority") {
738
+ const itemsKey = getItemsKeyArray(itemPayload);
739
+ for (const itemKey of itemsKey) {
740
+ store.produceState(
741
+ (draft) => {
742
+ const item = draft[itemKey];
743
+ if (!item)
744
+ return;
745
+ item.refetchOnMount = priority;
746
+ },
747
+ { action: { type: "invalidate-data", itemKey } }
748
+ );
749
+ invalidationWasTriggered.delete(itemKey);
750
+ storeEvents.emit("invalidateData", { priority, itemKey });
751
+ }
752
+ }
753
+ function getItemState(params) {
754
+ if (typeof params === "function" || Array.isArray(params)) {
755
+ const itemsId = getItemsKeyArray(params);
756
+ return filterAndMap(itemsId, (itemId, ignore2) => {
757
+ return store.state[itemId] || ignore2;
758
+ });
759
+ }
760
+ return store.state[getItemKey(params)];
761
+ }
762
+ function useMultipleItems(queries, {
763
+ selector,
764
+ omitPayload,
765
+ returnIdleStatus,
766
+ returnRefetchingStatus,
767
+ disableRefetchOnMount = globalDisableRefetchOnMount
768
+ } = {}) {
769
+ const queriesWithId = useDeepMemo(() => {
770
+ return queries.map((payload) => {
771
+ return { itemKey: getItemKey(payload), payload };
772
+ });
773
+ }, [queries]);
774
+ const dataSelector = (0, import_react4.useCallback)((itemState) => {
775
+ if (selector)
776
+ return selector(itemState);
777
+ return itemState;
778
+ }, []);
779
+ const resultSelector = (0, import_react4.useCallback)(
780
+ (state) => {
781
+ return queriesWithId.map(
782
+ ({
783
+ itemKey,
784
+ payload
785
+ }) => {
786
+ const item = state[itemKey];
787
+ if (item === null) {
788
+ return {
789
+ itemStateKey: itemKey,
790
+ status: "deleted",
791
+ data: dataSelector(null),
792
+ error: null,
793
+ payload: omitPayload ? void 0 : payload,
794
+ isLoading: false
795
+ };
796
+ }
797
+ if (!item) {
798
+ return {
799
+ itemStateKey: itemKey,
800
+ status: returnIdleStatus ? "idle" : "loading",
801
+ data: dataSelector(null),
802
+ error: null,
803
+ payload: omitPayload ? void 0 : payload,
804
+ isLoading: returnIdleStatus ? false : true
805
+ };
806
+ }
807
+ let status = item.status;
808
+ if (!returnRefetchingStatus && item.status === "refetching") {
809
+ status = "success";
810
+ }
811
+ return {
812
+ itemStateKey: itemKey,
813
+ status,
814
+ data: dataSelector(item.data),
815
+ error: item.error,
816
+ isLoading: status === "loading",
817
+ payload: omitPayload ? void 0 : item.payload
818
+ };
819
+ }
820
+ );
821
+ },
822
+ [
823
+ dataSelector,
824
+ omitPayload,
825
+ queriesWithId,
826
+ returnIdleStatus,
827
+ returnRefetchingStatus
828
+ ]
829
+ );
830
+ const storeState = store.useSelector(resultSelector, {
831
+ equalityFn: import_t_state3.deepEqual,
832
+ useExternalDeps: true
833
+ });
834
+ useOnMittEvent(storeEvents, "invalidateData", (event) => {
835
+ for (const { itemKey, payload } of queriesWithId) {
836
+ if (itemKey !== event.itemKey)
837
+ continue;
838
+ if (!invalidationWasTriggered.has(itemKey)) {
839
+ scheduleFetch(event.priority, payload);
840
+ invalidationWasTriggered.add(itemKey);
841
+ }
842
+ }
843
+ });
844
+ (0, import_react4.useEffect)(() => {
845
+ for (const { itemKey: itemId, payload } of queriesWithId) {
846
+ if (itemId) {
847
+ if (disableRefetchOnMount) {
848
+ const itemState = getItemState(payload);
849
+ const shouldFetch = !itemState?.wasLoaded || itemState.refetchOnMount;
850
+ if (shouldFetch) {
851
+ scheduleFetch(
852
+ itemState?.refetchOnMount || "lowPriority",
853
+ payload
854
+ );
855
+ return;
856
+ }
857
+ } else {
858
+ scheduleFetch("lowPriority", payload);
859
+ }
860
+ }
861
+ }
862
+ }, [disableRefetchOnMount, queriesWithId]);
863
+ return storeState;
864
+ }
865
+ function useItem(payload, options = {}) {
866
+ const { selector, ensureIsLoaded } = options;
867
+ const query = (0, import_react4.useMemo)(
868
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
869
+ [payload]
870
+ );
871
+ const item = useMultipleItems(query, options);
872
+ const result = (0, import_react4.useMemo)(
873
+ () => item[0] ?? {
874
+ payload: void 0,
875
+ data: selector ? selector(null) : null,
876
+ error: null,
877
+ status: "idle",
878
+ itemStateKey: "",
879
+ isLoading: false
880
+ },
881
+ [item]
882
+ );
883
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
884
+ ensureIsLoaded,
885
+ !!payload,
886
+ () => {
887
+ if (payload) {
888
+ scheduleFetch("highPriority", payload);
889
+ }
890
+ }
891
+ );
892
+ (0, import_t_state3.useSubscribeToStore)(store, ({ observe }) => {
893
+ if (!ensureIsLoaded)
894
+ return;
895
+ observe.ifSelector((state) => state[result.itemStateKey]?.status).change.then(({ current }) => {
896
+ if (current === "success" || current === "error") {
897
+ emitIsLoadedEvt("isLoaded", true);
898
+ }
899
+ });
900
+ });
901
+ return useModifyResult(result);
902
+ }
903
+ function startMutation(fetchParams) {
904
+ const itemKeys = getItemsKeyArray(fetchParams);
905
+ const endMutations = [];
906
+ for (const itemKey of itemKeys) {
907
+ endMutations.push(fetchOrquestrator.get(itemKey).startMutation());
908
+ }
909
+ return () => {
910
+ for (const endMutation of endMutations) {
911
+ endMutation();
912
+ }
913
+ };
914
+ }
915
+ function addItemToState(fetchParams, data) {
916
+ const itemKey = getItemKey(fetchParams);
917
+ store.produceState(
918
+ (draftState) => {
919
+ draftState[itemKey] = {
920
+ data,
921
+ status: "success",
922
+ wasLoaded: true,
923
+ refetchOnMount: false,
924
+ error: null,
925
+ payload: serializableClone(fetchParams)
926
+ };
927
+ },
928
+ { action: { type: "create-item-state", payload: fetchParams } }
929
+ );
930
+ }
931
+ function deleteItemState(fetchParams) {
932
+ const itemKeys = getItemsKeyArray(fetchParams);
933
+ store.produceState(
934
+ (draftState) => {
935
+ for (const itemKey of itemKeys) {
936
+ draftState[itemKey] = null;
937
+ }
938
+ },
939
+ { action: { type: "delete-item-state", payload: fetchParams } }
940
+ );
941
+ }
942
+ function updateItemState(fetchParams, produceNewData, ifNothingWasUpdated) {
943
+ const itemKeys = getItemsKeyArray(fetchParams);
944
+ let someItemWasUpdated = false;
945
+ store.batch(
946
+ () => {
947
+ store.produceState((draftState) => {
948
+ for (const itemKey of itemKeys) {
949
+ const item = draftState[itemKey];
950
+ if (!item)
951
+ continue;
952
+ if (item.data) {
953
+ someItemWasUpdated = true;
954
+ const newData = produceNewData(item.data, item);
955
+ if (newData) {
956
+ item.data = newData;
957
+ }
958
+ }
959
+ }
960
+ });
961
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
962
+ ifNothingWasUpdated();
963
+ }
964
+ },
965
+ { type: "update-item-state", item: itemKeys }
966
+ );
967
+ return someItemWasUpdated;
968
+ }
969
+ if (!disableRefetchOnWindowFocus) {
970
+ let handleFocus2 = function() {
971
+ invalidateItem(() => true, "lowPriority");
972
+ };
973
+ var handleFocus = handleFocus2;
974
+ window.addEventListener("focus", handleFocus2);
975
+ window.addEventListener("visibilitychange", handleFocus2);
976
+ }
977
+ return {
978
+ store,
979
+ scheduleFetch,
980
+ awaitFetch,
981
+ useMultipleItems,
982
+ useItem,
983
+ getItemKey,
984
+ getItemState,
985
+ startMutation,
986
+ invalidateItem,
987
+ updateItemState,
988
+ addItemToState,
989
+ deleteItemState
990
+ };
991
+ }
992
+
993
+ // src/listQueryStore.ts
994
+ var import_mitt4 = __toESM(require("mitt"), 1);
995
+ var import_react5 = require("react");
996
+ var import_t_state4 = require("t-state");
997
+ var noFetchFnError = "No fetchItemFn was provided";
998
+ function newTSDFListQueryStore({
999
+ debugName,
1000
+ fetchListFn,
1001
+ fetchItemFn,
1002
+ errorNormalizer,
1003
+ defaultQuerySize = 50,
1004
+ disableRefetchOnWindowFocus,
1005
+ disableRefetchOnMount: globalDisableRefetchOnMount,
1006
+ lowPriorityThrottleMs,
1007
+ mediumPriorityThrottleMs,
1008
+ dynamicRealtimeThrottleMs,
1009
+ syncMutationsAndInvalidations
1010
+ }) {
1011
+ const store = new import_t_state4.Store({
1012
+ debugName,
1013
+ state: { items: {}, queries: {}, itemQueries: {} }
1014
+ });
1015
+ function getQueryKey(params) {
1016
+ return getCacheId(params);
1017
+ }
1018
+ async function fetchQuery(fetchCtx, [fetchType, queryPayload, size = defaultQuerySize]) {
1019
+ const payload = serializableClone(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, id } of items) {
1073
+ draft.items[id] = data;
1074
+ query.items.push(String(id));
1075
+ const itemQuery = draft.itemQueries[id];
1076
+ if (!itemQuery || itemQuery.status !== "loading" && itemQuery.status !== "refetching") {
1077
+ draft.itemQueries[id] = {
1078
+ error: null,
1079
+ refetchOnMount: false,
1080
+ status: "success",
1081
+ wasLoaded: true
1082
+ };
1083
+ }
1084
+ }
1085
+ },
1086
+ {
1087
+ action: { type: "fetch-query-success", payload }
1088
+ }
1089
+ );
1090
+ for (const { id } of items) {
1091
+ const itemFetchOrquestrator = fetchItemOrquestrator?.get(String(id));
1092
+ if (itemFetchOrquestrator) {
1093
+ itemFetchOrquestrator.setLastFetchStartTime(fetchCtx.getStartTime());
1094
+ }
1095
+ }
1096
+ return true;
1097
+ } catch (exception) {
1098
+ if (fetchCtx.shouldAbort())
1099
+ return false;
1100
+ const error = errorNormalizer(exception);
1101
+ store.produceState(
1102
+ (draft) => {
1103
+ const query = draft.queries[queryKey];
1104
+ if (!query)
1105
+ return;
1106
+ query.status = "error";
1107
+ query.error = error;
1108
+ },
1109
+ {
1110
+ action: { type: "fetch-query-error", payload, error }
1111
+ }
1112
+ );
1113
+ return false;
1114
+ }
1115
+ }
1116
+ function getQueryState(params) {
1117
+ return store.state.queries[getQueryKey(params)];
1118
+ }
1119
+ function getItemState(id) {
1120
+ if (typeof id === "string") {
1121
+ return store.state.items[id];
1122
+ }
1123
+ const itemsId = getItemsIdArray(id);
1124
+ return filterAndMap(itemsId, (itemId, ignore2) => {
1125
+ const item = store.state.items[itemId];
1126
+ return !item ? ignore2 : { id: itemId, data: item };
1127
+ });
1128
+ }
1129
+ const fetchQueryOrquestrator = createCollectionFetchOrquestrator({
1130
+ fetchFn: fetchQuery,
1131
+ lowPriorityThrottleMs,
1132
+ dynamicRealtimeThrottleMs,
1133
+ mediumPriorityThrottleMs
1134
+ });
1135
+ function scheduleListQueryFetch(fetchType, payload, size) {
1136
+ const multiplePayloads = Array.isArray(payload);
1137
+ const payloads = multiplePayloads ? payload : [payload];
1138
+ const results = payloads.map((param) => {
1139
+ return fetchQueryOrquestrator.get(getQueryKey(param)).scheduleFetch(fetchType, ["load", param, size]);
1140
+ });
1141
+ return multiplePayloads ? results : results[0];
1142
+ }
1143
+ function loadMore(params, size) {
1144
+ const queryState = getQueryState(params);
1145
+ if (!queryState || !queryState.hasMore)
1146
+ return "skipped";
1147
+ return fetchQueryOrquestrator.get(getQueryKey(params)).scheduleFetch("highPriority", ["loadMore", params, size]);
1148
+ }
1149
+ function getQueryItems(query, itemDataSelector) {
1150
+ return filterAndMap(query.items, (itemId, ignore2) => {
1151
+ const data = store.state.items[itemId];
1152
+ return data ? itemDataSelector(data, itemId) : ignore2;
1153
+ });
1154
+ }
1155
+ async function awaitListQueryFetch(params, size = defaultQuerySize) {
1156
+ const queryKey = getQueryKey(params);
1157
+ const wasAborted = await fetchQueryOrquestrator.get(queryKey).awaitFetch(["load", params, size]);
1158
+ if (wasAborted) {
1159
+ return {
1160
+ items: [],
1161
+ error: errorNormalizer(new Error("Aborted")),
1162
+ hasMore: false
1163
+ };
1164
+ }
1165
+ const query = store.state.queries[queryKey];
1166
+ if (!query) {
1167
+ return {
1168
+ items: [],
1169
+ error: errorNormalizer(new Error("Not found")),
1170
+ hasMore: false
1171
+ };
1172
+ }
1173
+ return query.error ? { items: [], error: query.error, hasMore: query.hasMore } : {
1174
+ items: getQueryItems(query, (data, id) => ({ data, id })),
1175
+ error: null,
1176
+ hasMore: query.hasMore
1177
+ };
1178
+ }
1179
+ async function awaitItemFetch(itemId) {
1180
+ if (!fetchItemOrquestrator)
1181
+ throw new Error(noFetchFnError);
1182
+ const wasAborted = await fetchItemOrquestrator.get(itemId).awaitFetch(itemId);
1183
+ if (wasAborted) {
1184
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
1185
+ }
1186
+ const itemData = store.state.items[itemId];
1187
+ const itemQuery = store.state.itemQueries[itemId];
1188
+ if (!itemQuery || !itemData) {
1189
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
1190
+ }
1191
+ return itemQuery.error ? { data: null, error: itemQuery.error } : { data: itemData, error: null };
1192
+ }
1193
+ function getQueriesKeyArray(payloads) {
1194
+ if (Array.isArray(payloads)) {
1195
+ return payloads.map((payload) => ({
1196
+ key: getQueryKey(payload),
1197
+ payload
1198
+ }));
1199
+ } else if (typeof payloads === "function") {
1200
+ return filterAndMap(
1201
+ Object.entries(store.state.queries),
1202
+ ([queryKey, query], ignore2) => {
1203
+ return payloads(query.payload, query, queryKey) ? {
1204
+ key: queryKey,
1205
+ payload: query.payload
1206
+ } : ignore2;
1207
+ }
1208
+ );
1209
+ } else {
1210
+ return [{ key: getQueryKey(payloads), payload: payloads }];
1211
+ }
1212
+ }
1213
+ const storeEvents = (0, import_mitt4.default)();
1214
+ const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
1215
+ function invalidateQuery(queryPayload, priority = "highPriority", ignoreInvalidationSync = false) {
1216
+ const queriesKey = getQueriesKeyArray(queryPayload);
1217
+ for (const { key } of queriesKey) {
1218
+ store.produceState(
1219
+ (draft) => {
1220
+ const query = draft.queries[key];
1221
+ if (!query)
1222
+ return;
1223
+ query.refetchOnMount = priority;
1224
+ },
1225
+ { action: { type: "invalidate-data", key } }
1226
+ );
1227
+ queryInvalidationWasTriggered.delete(key);
1228
+ storeEvents.emit("invalidateQuery", { priority, queryKey: key });
1229
+ }
1230
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1231
+ invalidateItem(
1232
+ (_, itemId) => queriesKey.some(({ payload }) => {
1233
+ return syncMutationsAndInvalidations.syncItemAndQuery(
1234
+ itemId,
1235
+ payload
1236
+ );
1237
+ }),
1238
+ priority,
1239
+ true
1240
+ );
1241
+ invalidateQuery(
1242
+ (queryToInvalidatePayload, _, queryToInvalidateKey) => queriesKey.some((alreadyInvalidatedQueryPayload) => {
1243
+ return queryToInvalidateKey !== alreadyInvalidatedQueryPayload.key && syncMutationsAndInvalidations.syncQueries(
1244
+ alreadyInvalidatedQueryPayload.payload,
1245
+ queryToInvalidatePayload
1246
+ );
1247
+ }),
1248
+ priority,
1249
+ true
1250
+ );
1251
+ }
1252
+ }
1253
+ function defaultItemSelector(data, id) {
1254
+ return { id, data };
1255
+ }
1256
+ function useMultipleListQueries(queries, {
1257
+ itemSelector = defaultItemSelector,
1258
+ omitPayload,
1259
+ returnIdleStatus,
1260
+ returnRefetchingStatus,
1261
+ loadSize,
1262
+ disableRefetchOnMount = globalDisableRefetchOnMount
1263
+ } = {}) {
1264
+ const queriesWithId = useDeepMemo(() => {
1265
+ return queries.map((payload) => {
1266
+ return {
1267
+ key: getQueryKey(payload),
1268
+ payload
1269
+ };
1270
+ });
1271
+ }, [queries]);
1272
+ const dataSelector = (0, import_react5.useCallback)(itemSelector, []);
1273
+ const resultSelector = (0, import_react5.useCallback)(
1274
+ (state) => {
1275
+ return queriesWithId.map(
1276
+ ({
1277
+ key: queryKey,
1278
+ payload
1279
+ }) => {
1280
+ const query = state.queries[queryKey];
1281
+ if (!query) {
1282
+ return {
1283
+ queryKey,
1284
+ status: returnIdleStatus ? "idle" : "loading",
1285
+ items: [],
1286
+ error: null,
1287
+ hasMore: false,
1288
+ payload: omitPayload ? void 0 : payload,
1289
+ isLoading: returnIdleStatus ? false : true
1290
+ };
1291
+ }
1292
+ let status = query.status;
1293
+ if (!returnRefetchingStatus && query.status === "refetching") {
1294
+ status = "success";
1295
+ }
1296
+ return {
1297
+ queryKey,
1298
+ status,
1299
+ items: getQueryItems(query, dataSelector),
1300
+ error: query.error,
1301
+ hasMore: query.hasMore,
1302
+ isLoading: status === "loading",
1303
+ payload: omitPayload ? void 0 : query.payload
1304
+ };
1305
+ }
1306
+ );
1307
+ },
1308
+ [
1309
+ dataSelector,
1310
+ omitPayload,
1311
+ queriesWithId,
1312
+ returnIdleStatus,
1313
+ returnRefetchingStatus
1314
+ ]
1315
+ );
1316
+ const storeState = store.useSelector(resultSelector, {
1317
+ equalityFn: import_t_state4.deepEqual,
1318
+ useExternalDeps: true
1319
+ });
1320
+ useOnMittEvent(storeEvents, "invalidateQuery", (event) => {
1321
+ for (const { key, payload } of queriesWithId) {
1322
+ if (key !== event.queryKey)
1323
+ continue;
1324
+ if (!queryInvalidationWasTriggered.has(key)) {
1325
+ scheduleListQueryFetch(event.priority, payload);
1326
+ queryInvalidationWasTriggered.add(key);
1327
+ }
1328
+ }
1329
+ });
1330
+ const loadSizeConst = useConst(() => loadSize);
1331
+ (0, import_react5.useEffect)(() => {
1332
+ for (const { key: itemId, payload: fetchParams } of queriesWithId) {
1333
+ if (itemId) {
1334
+ if (disableRefetchOnMount) {
1335
+ const itemState = getQueryState(fetchParams);
1336
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1337
+ if (shouldFetch) {
1338
+ scheduleListQueryFetch(
1339
+ itemState?.refetchOnMount || "lowPriority",
1340
+ fetchParams,
1341
+ loadSizeConst
1342
+ );
1343
+ return;
1344
+ }
1345
+ } else {
1346
+ scheduleListQueryFetch("lowPriority", fetchParams, loadSizeConst);
1347
+ }
1348
+ }
1349
+ }
1350
+ }, [disableRefetchOnMount, loadSizeConst, queriesWithId]);
1351
+ return storeState;
1352
+ }
1353
+ function useListQuery(payload, options = {}) {
1354
+ const { ensureIsLoaded } = options;
1355
+ const query = (0, import_react5.useMemo)(
1356
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
1357
+ [payload]
1358
+ );
1359
+ const queryResult = useMultipleListQueries(query, options);
1360
+ const result = (0, import_react5.useMemo)(
1361
+ () => queryResult[0] ?? {
1362
+ payload: void 0,
1363
+ error: null,
1364
+ hasMore: false,
1365
+ isLoading: false,
1366
+ status: "idle",
1367
+ queryKey: "",
1368
+ items: []
1369
+ },
1370
+ [queryResult]
1371
+ );
1372
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1373
+ ensureIsLoaded,
1374
+ !!payload,
1375
+ () => {
1376
+ if (payload) {
1377
+ scheduleListQueryFetch("highPriority", payload);
1378
+ }
1379
+ }
1380
+ );
1381
+ (0, import_t_state4.useSubscribeToStore)(store, ({ observe }) => {
1382
+ if (!ensureIsLoaded)
1383
+ return;
1384
+ observe.ifSelector((state) => state.queries[result.queryKey]?.status).change.then(({ current }) => {
1385
+ if (current === "success" || current === "error") {
1386
+ emitIsLoadedEvt("isLoaded", true);
1387
+ }
1388
+ });
1389
+ });
1390
+ return useModifyResult(result);
1391
+ }
1392
+ async function fetchItem(fetchCtx, itemId) {
1393
+ if (!fetchItemOrquestrator) {
1394
+ throw new Error(noFetchFnError);
1395
+ }
1396
+ const isLoaded = !store.state.itemQueries[itemId]?.wasLoaded;
1397
+ store.produceState(
1398
+ (draft) => {
1399
+ const itemQuery = draft.itemQueries[itemId];
1400
+ if (!itemQuery) {
1401
+ draft.itemQueries[itemId] = {
1402
+ status: "loading",
1403
+ error: null,
1404
+ wasLoaded: false,
1405
+ refetchOnMount: false
1406
+ };
1407
+ return;
1408
+ }
1409
+ itemQuery.status = itemQuery.wasLoaded ? "refetching" : "loading";
1410
+ itemQuery.error = null;
1411
+ itemQuery.refetchOnMount = false;
1412
+ },
1413
+ {
1414
+ action: {
1415
+ type: isLoaded ? "fetch-item-start" : "fetch-item-refetch-start",
1416
+ itemId
1417
+ }
1418
+ }
1419
+ );
1420
+ try {
1421
+ const item = await fetchItemFn(itemId);
1422
+ if (fetchCtx.shouldAbort())
1423
+ return false;
1424
+ store.produceState(
1425
+ (draft) => {
1426
+ const itemQuery = draft.itemQueries[itemId];
1427
+ if (!itemQuery)
1428
+ return;
1429
+ itemQuery.status = "success";
1430
+ itemQuery.wasLoaded = true;
1431
+ draft.items[itemId] = item;
1432
+ },
1433
+ {
1434
+ action: { type: "fetch-item-success", itemId }
1435
+ }
1436
+ );
1437
+ return true;
1438
+ } catch (exception) {
1439
+ if (fetchCtx.shouldAbort())
1440
+ return false;
1441
+ const error = errorNormalizer(exception);
1442
+ store.produceState(
1443
+ (draft) => {
1444
+ const itemQuery = draft.itemQueries[itemId];
1445
+ if (!itemQuery)
1446
+ return;
1447
+ itemQuery.status = "error";
1448
+ itemQuery.error = error;
1449
+ },
1450
+ {
1451
+ action: { type: "fetch-item-error", itemId }
1452
+ }
1453
+ );
1454
+ return false;
1455
+ }
1456
+ }
1457
+ const fetchItemOrquestrator = fetchItemFn && createCollectionFetchOrquestrator({
1458
+ fetchFn: fetchItem,
1459
+ lowPriorityThrottleMs,
1460
+ dynamicRealtimeThrottleMs,
1461
+ mediumPriorityThrottleMs
1462
+ });
1463
+ function scheduleItemFetch(fetchType, itemId) {
1464
+ if (!fetchItemOrquestrator) {
1465
+ throw new Error(noFetchFnError);
1466
+ }
1467
+ const fetchMultiple = Array.isArray(itemId);
1468
+ const itemsId = fetchMultiple ? itemId : [itemId];
1469
+ const results = itemsId.map((id) => {
1470
+ return fetchItemOrquestrator.get(id).scheduleFetch(fetchType, id);
1471
+ });
1472
+ return fetchMultiple ? results : results[0];
1473
+ }
1474
+ function getItemsIdArray(itemId) {
1475
+ if (Array.isArray(itemId)) {
1476
+ return itemId;
1477
+ }
1478
+ if (typeof itemId === "function") {
1479
+ return filterAndMap(
1480
+ Object.entries(store.state.items),
1481
+ ([id, item], ignore2) => {
1482
+ if (item === null)
1483
+ return ignore2;
1484
+ return itemId(item, id) ? id : ignore2;
1485
+ }
1486
+ );
1487
+ }
1488
+ return [itemId];
1489
+ }
1490
+ const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
1491
+ function invalidateItem(itemId, priority = "highPriority", ignoreInvalidationSync = false) {
1492
+ if (!fetchItemOrquestrator) {
1493
+ throw new Error(noFetchFnError);
1494
+ }
1495
+ const itemsId = getItemsIdArray(itemId);
1496
+ for (const id of itemsId) {
1497
+ store.produceState(
1498
+ (draft) => {
1499
+ const query = draft.itemQueries[id];
1500
+ if (!query)
1501
+ return;
1502
+ query.refetchOnMount = priority;
1503
+ },
1504
+ { action: { type: "invalidate-item", queryKey: id } }
1505
+ );
1506
+ itemInvalidationWasTriggered.delete(id);
1507
+ storeEvents.emit("invalidateItem", { priority, itemId: id });
1508
+ }
1509
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1510
+ invalidateQuery(
1511
+ (query) => itemsId.some(
1512
+ (id) => syncMutationsAndInvalidations.syncItemAndQuery(id, query)
1513
+ ),
1514
+ priority,
1515
+ true
1516
+ );
1517
+ }
1518
+ }
1519
+ function startItemMutation(itemId) {
1520
+ if (!fetchItemOrquestrator)
1521
+ throw new Error(noFetchFnError);
1522
+ const itemsId = getItemsIdArray(itemId);
1523
+ const endMutations = [];
1524
+ for (const id of itemsId) {
1525
+ endMutations.push(fetchItemOrquestrator.get(id).startMutation());
1526
+ if (syncMutationsAndInvalidations) {
1527
+ for (const [queryKey, query] of Object.entries(store.state.queries)) {
1528
+ if (syncMutationsAndInvalidations.syncItemAndQuery(id, query.payload)) {
1529
+ endMutations.push(
1530
+ fetchQueryOrquestrator.get(queryKey).startMutation()
1531
+ );
1532
+ }
1533
+ }
1534
+ }
1535
+ }
1536
+ return () => {
1537
+ for (const endMutation of endMutations) {
1538
+ endMutation();
1539
+ }
1540
+ };
1541
+ }
1542
+ function defaultItemDataSelector(data) {
1543
+ return data;
1544
+ }
1545
+ function useMultipleItems(itemIds, {
1546
+ selector = defaultItemDataSelector,
1547
+ returnIdleStatus,
1548
+ returnRefetchingStatus,
1549
+ disableRefetchOnMount
1550
+ } = {}) {
1551
+ const dataSelector = (0, import_react5.useCallback)(selector, []);
1552
+ const memoizedItemIds = useDeepMemo(() => itemIds, [itemIds]);
1553
+ const resultSelector = (0, import_react5.useCallback)(
1554
+ (state) => {
1555
+ return memoizedItemIds.map(
1556
+ (itemId) => {
1557
+ const itemQuery = state.itemQueries[itemId];
1558
+ const itemState = state.items[itemId];
1559
+ if (itemQuery === null) {
1560
+ return {
1561
+ status: "deleted",
1562
+ error: null,
1563
+ isLoading: false,
1564
+ itemId,
1565
+ data: dataSelector(null, itemId)
1566
+ };
1567
+ }
1568
+ if (!itemQuery) {
1569
+ return {
1570
+ status: returnIdleStatus ? "idle" : "loading",
1571
+ error: null,
1572
+ isLoading: returnIdleStatus ? false : true,
1573
+ itemId,
1574
+ data: dataSelector(null, itemId)
1575
+ };
1576
+ }
1577
+ let status = itemQuery.status;
1578
+ if (!returnRefetchingStatus && itemQuery.status === "refetching") {
1579
+ status = "success";
1580
+ }
1581
+ return {
1582
+ status,
1583
+ error: itemQuery.error,
1584
+ isLoading: status === "loading",
1585
+ data: dataSelector(itemState ?? null, itemId),
1586
+ itemId
1587
+ };
1588
+ }
1589
+ );
1590
+ },
1591
+ [dataSelector, memoizedItemIds, returnIdleStatus, returnRefetchingStatus]
1592
+ );
1593
+ const storeState = store.useSelector(resultSelector, {
1594
+ equalityFn: import_t_state4.deepEqual,
1595
+ useExternalDeps: true
1596
+ });
1597
+ useOnMittEvent(storeEvents, "invalidateItem", (event) => {
1598
+ for (const itemId of memoizedItemIds) {
1599
+ if (itemId !== event.itemId)
1600
+ continue;
1601
+ if (!itemInvalidationWasTriggered.has(itemId)) {
1602
+ scheduleItemFetch(event.priority, itemId);
1603
+ itemInvalidationWasTriggered.add(itemId);
1604
+ }
1605
+ }
1606
+ });
1607
+ (0, import_react5.useEffect)(() => {
1608
+ for (const itemId of memoizedItemIds) {
1609
+ if (itemId) {
1610
+ if (disableRefetchOnMount) {
1611
+ const itemState = store.state.itemQueries[itemId];
1612
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1613
+ if (shouldFetch) {
1614
+ scheduleItemFetch(
1615
+ itemState?.refetchOnMount || "lowPriority",
1616
+ itemId
1617
+ );
1618
+ return;
1619
+ }
1620
+ } else {
1621
+ scheduleItemFetch("lowPriority", itemId);
1622
+ }
1623
+ }
1624
+ }
1625
+ }, [disableRefetchOnMount, memoizedItemIds]);
1626
+ return storeState;
1627
+ }
1628
+ function useItem(itemId, options = {}) {
1629
+ const { ensureIsLoaded } = options;
1630
+ const query = (0, import_react5.useMemo)(
1631
+ () => itemId === false || itemId === null || itemId === void 0 ? [] : [itemId],
1632
+ [itemId]
1633
+ );
1634
+ const queryResult = useMultipleItems(query, options);
1635
+ const memoizedSelector = (0, import_react5.useCallback)(
1636
+ options.selector ?? defaultItemDataSelector,
1637
+ []
1638
+ );
1639
+ const result = (0, import_react5.useMemo)(
1640
+ () => queryResult[0] ?? {
1641
+ error: null,
1642
+ isLoading: false,
1643
+ status: "idle",
1644
+ data: memoizedSelector(null, itemId || ""),
1645
+ itemId: itemId || ""
1646
+ },
1647
+ [itemId, memoizedSelector, queryResult]
1648
+ );
1649
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1650
+ ensureIsLoaded,
1651
+ !!itemId,
1652
+ () => {
1653
+ if (itemId) {
1654
+ scheduleItemFetch("highPriority", itemId);
1655
+ }
1656
+ }
1657
+ );
1658
+ (0, import_t_state4.useSubscribeToStore)(store, ({ observe }) => {
1659
+ if (!ensureIsLoaded || !itemId)
1660
+ return;
1661
+ observe.ifSelector((state) => state.itemQueries[itemId]?.status).change.then(({ current }) => {
1662
+ if (current === "success" || current === "error") {
1663
+ emitIsLoadedEvt("isLoaded", true);
1664
+ }
1665
+ });
1666
+ });
1667
+ return useModifyResult(result);
1668
+ }
1669
+ function updateItemState(itemIds, produceNewData, ifNothingWasUpdated) {
1670
+ const itemKeys = getItemsIdArray(itemIds);
1671
+ let someItemWasUpdated = false;
1672
+ store.batch(
1673
+ () => {
1674
+ store.produceState((draftState) => {
1675
+ for (const itemId of itemKeys) {
1676
+ const item = draftState.items[itemId];
1677
+ if (!item)
1678
+ continue;
1679
+ someItemWasUpdated = true;
1680
+ const newData = produceNewData(item, itemId);
1681
+ if (newData) {
1682
+ draftState.items[itemId] = newData;
1683
+ }
1684
+ }
1685
+ });
1686
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
1687
+ ifNothingWasUpdated();
1688
+ }
1689
+ },
1690
+ { type: "update-item-state", item: itemKeys }
1691
+ );
1692
+ return someItemWasUpdated;
1693
+ }
1694
+ function addItemToState(itemId, data) {
1695
+ store.produceState(
1696
+ (draftState) => {
1697
+ draftState.items[itemId] = data;
1698
+ draftState.itemQueries[itemId] = {
1699
+ status: "success",
1700
+ wasLoaded: true,
1701
+ refetchOnMount: false,
1702
+ error: null
1703
+ };
1704
+ },
1705
+ { action: { type: "create-item-state", itemId } }
1706
+ );
1707
+ }
1708
+ function deleteItemState(itemId) {
1709
+ const itemsId = getItemsIdArray(itemId);
1710
+ store.produceState(
1711
+ (draftState) => {
1712
+ for (const itemKey of itemsId) {
1713
+ draftState.items[itemKey] = null;
1714
+ draftState.itemQueries[itemKey] = null;
1715
+ for (const query of Object.values(draftState.queries)) {
1716
+ if (query.items.includes(itemKey)) {
1717
+ query.items = query.items.filter((i) => i !== itemKey);
1718
+ }
1719
+ }
1720
+ }
1721
+ },
1722
+ { action: { type: "delete-item-state", itemId } }
1723
+ );
1724
+ }
1725
+ if (!disableRefetchOnWindowFocus) {
1726
+ let handleFocus2 = function() {
1727
+ invalidateQuery(() => true, "lowPriority");
1728
+ invalidateItem(() => true, "lowPriority");
1729
+ };
1730
+ var handleFocus = handleFocus2;
1731
+ window.addEventListener("focus", handleFocus2);
1732
+ window.addEventListener("visibilitychange", handleFocus2);
1733
+ }
1734
+ return {
1735
+ store,
1736
+ scheduleListQueryFetch,
1737
+ getQueryState,
1738
+ getQueryKey,
1739
+ deleteItemState,
1740
+ getItemState,
1741
+ loadMore,
1742
+ invalidateQuery,
1743
+ invalidateItem,
1744
+ scheduleItemFetch,
1745
+ awaitItemFetch,
1746
+ awaitListQueryFetch,
1747
+ useMultipleListQueries,
1748
+ useListQuery,
1749
+ useItem,
1750
+ useMultipleItems,
1751
+ addItemToState,
1752
+ updateItemState,
1753
+ startItemMutation
1754
+ };
1755
+ }
1756
+ // Annotate the CommonJS export names for ESM import in node:
1757
+ 0 && (module.exports = {
1758
+ newTSDFCollectionStore,
1759
+ newTSDFDocumentStore,
1760
+ newTSDFListQueryStore
1761
+ });