@sirajju/use-sync
Version:
A package for keep updating the states
1 lines • 26 kB
JavaScript
(()=>{"use strict";var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{clearCache:()=>T,clearIndexedDBCache:()=>y,deleteFromIndexedDB:()=>v,getFromIndexedDB:()=>p,getHistory:()=>W,storeInIndexedDB:()=>h,syncIndividual:()=>M,useSync:()=>_});const n=require("react"),r=require("react-redux");var o;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(o||(o={}));var a,c,i={DEBUG:"color: #5bc0de",INFO:"color: #28a745",WARN:"color: #ffc107",ERROR:"color: #dc3545",DEFAULT:""},s=function(e,t,n,r){return new(n||(n=Promise))((function(o,a){function c(e){try{s(r.next(e))}catch(e){a(e)}}function i(e){try{s(r.throw(e))}catch(e){a(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(c,i)}s((r=r.apply(e,t||[])).next())}))},u=function(e,t){var n,r,o,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},c=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return c.next=i(0),c.throw=i(1),c.return=i(2),"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function i(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;c&&(c=0,i[0]&&(a=0)),a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}},l="apiResponses",d=null,f=function(){return d||(d=new Promise((function(e,t){var n=indexedDB.open("useSyncCache",1);n.onerror=function(e){t("IndexedDB error: ".concat(e.target.error))},n.onsuccess=function(t){e(t.target.result)},n.onupgradeneeded=function(e){var t=e.target.result;t.objectStoreNames.contains(l)||t.createObjectStore(l,{keyPath:"key"})}})))},h=function(e,t,n){return s(void 0,void 0,void 0,(function(){var r,o,a,c,i;return u(this,(function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,f()];case 1:return r=s.sent(),o=r.transaction([l],"readwrite"),a=o.objectStore(l),c={key:e,data:t,timestamp:Date.now(),expiresAt:n},[2,new Promise((function(e,t){var n=a.put(c);n.onsuccess=function(){return e()},n.onerror=function(e){return t("Error storing data: ".concat(e.target.error))},o.oncomplete=function(){return e()},o.onerror=function(e){return t("Transaction error: ".concat(o.error))}}))];case 2:throw i=s.sent(),console.error("IndexedDB store error:",i),i;case 3:return[2]}}))}))},p=function(e){return s(void 0,void 0,void 0,(function(){var t,n,r,o;return u(this,(function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,f()];case 1:return t=a.sent(),n=t.transaction([l],"readonly"),r=n.objectStore(l),[2,new Promise((function(t,n){var o=r.get(e);o.onsuccess=function(n){var r=n.target.result;r?Date.now()>r.expiresAt?(v(e).catch(console.error),t(null)):t(r):t(null)},o.onerror=function(e){return n("Error retrieving data: ".concat(e.target.error))}}))];case 2:return o=a.sent(),console.error("IndexedDB get error:",o),[2,null];case 3:return[2]}}))}))},v=function(e){return s(void 0,void 0,void 0,(function(){var t,n,r,o;return u(this,(function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,f()];case 1:return t=a.sent(),n=t.transaction([l],"readwrite"),r=n.objectStore(l),[2,new Promise((function(t,n){var o=r.delete(e);o.onsuccess=function(){return t()},o.onerror=function(e){return n("Error deleting data: ".concat(e.target.error))}}))];case 2:throw o=a.sent(),console.error("IndexedDB delete error:",o),o;case 3:return[2]}}))}))},y=function(){return s(void 0,void 0,void 0,(function(){var e,t,n,r;return u(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,f()];case 1:return e=o.sent(),t=e.transaction([l],"readwrite"),n=t.objectStore(l),[2,new Promise((function(e,t){var r=n.clear();r.onsuccess=function(){return e()},r.onerror=function(e){return t("Error clearing cache: ".concat(e.target.error))}}))];case 2:throw r=o.sent(),console.error("IndexedDB clear cache error:",r),r;case 3:return[2]}}))}))},m=function(){return m=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},m.apply(this,arguments)},g=function(e,t,n,r){return new(n||(n=Promise))((function(o,a){function c(e){try{s(r.next(e))}catch(e){a(e)}}function i(e){try{s(r.throw(e))}catch(e){a(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(c,i)}s((r=r.apply(e,t||[])).next())}))},w=function(e,t){var n,r,o,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},c=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return c.next=i(0),c.throw=i(1),c.return=i(2),"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function i(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;c&&(c=0,i[0]&&(a=0)),a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}},b=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n},D=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},E=function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,a=n.call(e),c=[];try{for(;(void 0===t||t-- >0)&&!(r=a.next()).done;)c.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=a.return)&&n.call(a)}finally{if(o)throw o.error}}return c},x=function(e,t,n){if(n||2===arguments.length)for(var r,o=0,a=t.length;o<a;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},R=[],B=new Map,k=!1,O=[],S=5e3,I=864e5,C="useSyncLastCleanup",U=new Map,P=new Map,G=new Map,A=[],j=function(e){if(null==a?void 0:a.throwError)throw new Error(e);console.error(e)},F=function(e,t,n){if(void 0===t&&(t="INFO"),(null==a?void 0:a.log)&&function(e){if(!(null==a?void 0:a.logLevel))return!0;var t=o[a.logLevel];return o[e]>=t}(t)){var r=(new Date).toISOString(),c="[".concat(r,"] %c").concat(t.toUpperCase(),"%c: ").concat(e);if(a.logger)return a.logger(t,e,n);n?console[t.toLowerCase()](c,i[t],i.DEFAULT,n):console[t.toLowerCase()](c,i[t],i.DEFAULT)}},N=function(e,t){var n,r;if(!t||0===Object.keys(t).length)return e;var o=new URLSearchParams;try{for(var a=D(Object.entries(t)),c=a.next();!c.done;c=a.next()){var i=E(c.value,2),s=i[0],u=i[1];null!=u&&o.append(s,String(u))}}catch(e){n={error:e}}finally{try{c&&!c.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}var l=o.toString();return l?"".concat(e).concat(e.includes("?")?"&":"?").concat(l):e},L=function(e,t){var n=A.findIndex((function(t){return t.url===e.url&&t.timestamp===e.timestamp}));-1!==n&&(A[n]=m(m({},A[n]),{recieveTime:Date.now(),response:t}))},T=function(e){return g(void 0,void 0,void 0,(function(){return w(this,(function(t){switch(t.label){case 0:return e?(U.delete(e),[4,v(e)]):[3,2];case 1:return t.sent(),[3,4];case 2:return U.clear(),[4,y()];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))},K=function(){return g(void 0,void 0,void 0,(function(){var e,t,n;return w(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),F("Starting cache cleanup process","DEBUG"),e=function(){var e,t,n=Date.now(),r=0;try{for(var o=D(U.entries()),a=o.next();!a.done;a=o.next()){var c=E(a.value,2),i=c[0],s=c[1];s.expiresAt&&n>s.expiresAt&&(U.delete(i),r++)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}return r>0&&F("Cleaned ".concat(r," expired items from memory cache"),"DEBUG"),r}(),[4,s(void 0,void 0,void 0,(function(){var e,t,n,r,o,a;return u(this,(function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),[4,f()];case 1:return e=c.sent(),t=e.transaction([l],"readwrite"),n=t.objectStore(l),r=0,o=Date.now(),[2,new Promise((function(e,a){var c=n.openCursor();c.onsuccess=function(t){var n=t.target.result;if(n){var a=n.value;a.expiresAt&&o>a.expiresAt&&(n.delete().onsuccess=function(){r++}),n.continue()}else console.log("Cleaned up ".concat(r," expired entries from IndexedDB")),e({removed:r})},c.onerror=function(e){console.error("Error in cleanExpiredIndexedDBCache:",e.target.error),a("Error cleaning expired entries: ".concat(e.target.error))},t.oncomplete=function(){e({removed:r})},t.onerror=function(e){a("Transaction error: ".concat(t.error))}}))];case 2:return a=c.sent(),console.error("Error cleaning IndexedDB cache:",a),[2,{removed:0}];case 3:return[2]}}))}))];case 1:return t=r.sent().removed,function(){try{localStorage.setItem(C,Date.now().toString())}catch(e){F("Error updating last cleanup time: ".concat(e),"ERROR")}}(),F("Cache cleanup complete. Removed ".concat(e," memory items and ").concat(t," IndexedDB items"),"INFO"),[2,{memory:e,indexedDB:t}];case 2:return n=r.sent(),F("Error during cache cleanup: ".concat(n),"ERROR"),[2,{memory:0,indexedDB:0}];case 3:return[2]}}))}))},W=function(e){return void 0===e&&(e=!0),e&&function(e){void 0===e&&(e=3e5);var t=Date.now();A=A.filter((function(n){return t-n.timestamp<e}))}(),A},M=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return g(void 0,x([e],E(t),!1),void 0,(function(e,t,n,r,o){var i,s,u,l,d,f,v,y,b,D,E,x,S,C,P,G,T,K,W;return void 0===t&&(t={}),void 0===r&&(r=c),w(this,(function(c){switch(c.label){case 0:return k||!a.waiting?[3,2]:(F("".concat(e," Waiting for initial sync to complete"),"DEBUG"),[4,g(void 0,void 0,void 0,(function(){return w(this,(function(e){return[2,new Promise((function(e){var t=setInterval((function(){k&&(clearInterval(t),e(!0))}),100)}))]}))}))]);case 1:c.sent(),c.label=2;case 2:if(i=R.find((function(t){return t.key===e})),!(s=B.get(e))||!i)return F("Configuration not found for ".concat(e),"ERROR"),[2,j("no url found for item ".concat(e))];if(!i.allowDuplicates){if(O.includes("".concat(e,"_").concat(t.path)))return F("Skipping duplicate fetch for ".concat(e),"DEBUG"),[2];F("Starting individual sync for ".concat(e),"INFO"),O.push("".concat(e,"_").concat(t.path))}c.label=3;case 3:if(c.trys.push([3,18,19,20]),u=m(m({},i.options),t),l=(null===(K=null==t?void 0:t.method)||void 0===K?void 0:K.toUpperCase())||"GET",d=("boolean"==typeof o?o:"boolean"==typeof u.useIndexDB?u.useIndexDB:"boolean"==typeof u.indexDbCache?u.indexDbCache:i.indexDbCache)&&"GET"==l,f=u.path?"".concat(s).concat(u.path):s,v=u.params?N(f,u.params):f,y={url:v,timestamp:Date.now(),params:u.params||{},headers:u.headers||{},options:u,path:u.path||"",response:void 0,recieveTime:void 0},A.push(y),F("IndexedDB cache enabled: ".concat(d),"DEBUG"),!d)return[3,7];c.label=4;case 4:return c.trys.push([4,6,,7]),b=a.generateCacheKey?a.generateCacheKey(e,v,u.params):"".concat(e,"-").concat(v),F("Using cache key: ".concat(b),"DEBUG"),[4,p(b)];case 5:return(D=c.sent())&&Date.now()<D.expiresAt?(F("Using IndexedDB cached data for ".concat(e),"DEBUG"),U.set(b,{data:D.data,timestamp:D.timestamp,expiresAt:D.expiresAt}),L(y,D.data),u.updateIndexDbData&&(F("Background updating IndexedDB data for ".concat(e),"DEBUG"),g(void 0,void 0,void 0,(function(){var t,n,r,o,c;return w(this,(function(s){switch(s.label){case 0:return s.trys.push([0,8,,9]),[4,fetch(v,u)];case 1:return(t=s.sent()).ok?(n=null,i.transformResponse?[3,3]:[4,t.json()]):[3,7];case 2:return n=s.sent(),[3,5];case 3:return[4,i.transformResponse(t)];case 4:n=s.sent(),s.label=5;case 5:return r=a.generateCacheKey?a.generateCacheKey(e,v,u.params):b,o=Date.now()+(u.indexDbCacheDuration||a.indexDbCacheDuration||a.cacheDuration||I),[4,h(r,n,o)];case 6:s.sent(),F("Updated IndexedDB data for ".concat(e," in background"),"DEBUG"),s.label=7;case 7:return[3,9];case 8:return c=s.sent(),F("Background update failed for ".concat(e,": ").concat(c),"ERROR"),[3,9];case 9:return[2]}}))}))),!1!==n&&r("function"==typeof n?n(D.data):i.action(D.data)),[2,D.data]):[3,7];case 6:return E=c.sent(),F("IndexedDB cache retrieval error for ".concat(e,": ").concat(E),"ERROR"),[3,7];case 7:return[4,fetch(v,u)];case 8:if((x=c.sent()).ok)return[3,13];if(!(null===(W=x.headers.get("content-type"))||void 0===W?void 0:W.includes("application/json")))return[3,12];c.label=9;case 9:return c.trys.push([9,11,,12]),[4,x.json()];case 10:throw S=c.sent(),F("Sync failed for ".concat(e),"ERROR",{status:x.status,statusText:x.statusText,errorData:S}),new Error("Failed to fetch ".concat(e," ").concat(x.statusText," - ").concat(S.message));case 11:return c.sent(),[3,12];case 12:throw F("Sync failed for ".concat(e),"ERROR",{status:x.status,statusText:x.statusText}),new Error("Failed to fetch ".concat(e," ").concat(x.statusText));case 13:return C=null,i.transformResponse?[3,15]:[4,x.json()];case 14:return C=c.sent(),[3,17];case 15:return[4,i.transformResponse(x)];case 16:C=c.sent(),c.label=17;case 17:return L(y,C),F("Individual sync successful for ".concat(e),"INFO",{dataSize:JSON.stringify(C).length}),d&&(P=a.generateCacheKey?a.generateCacheKey(e,v,u.params):"".concat(e,"-").concat(v),G=Date.now()+(u.indexDbCacheDuration||a.indexDbCacheDuration||a.cacheDuration||I),h(P,C,G).catch((function(e){F("Failed to store in IndexedDB: ".concat(e),"ERROR")}))),!1!==n&&r("function"==typeof n?n(C):i.action(C)),[2,C];case 18:return T=c.sent(),F("Sync error : ".concat(T),"ERROR"),[3,20];case 19:return O=O.filter((function(n){return n!=="".concat(e,"_").concat(t.path)})),F("Completed individual sync for ".concat(e),"DEBUG"),[7];case 20:return[2]}}))}))},_=function(e){var t=e.fetchOrder,o=e.fetchItems,i=e.throwError,s=void 0===i||i,u=e.cacheDuration,l=e.memoryCacheDuration,d=e.indexDbCacheDuration,f=e.logLevel,v=void 0===f?"DEBUG":f,y=b(e,["fetchOrder","fetchItems","throwError","cacheDuration","memoryCacheDuration","indexDbCacheDuration","logLevel"]);t=t.sort((function(e,t){return t.priority-e.priority}));var O=(0,n.useRef)(!1),W=(0,n.useRef)(m({fetchOrder:t,fetchItems:o,throwError:s,logLevel:v,cacheDuration:u,memoryCacheDuration:l,indexDbCacheDuration:d},y));S=l||u||S,I=d||u||I,a=W.current,B=W.current.fetchItems,R=W.current.fetchOrder;var _=E((0,n.useState)({isPending:!0,haveError:!1}),2),q=_[0],z=_[1],J=E((0,n.useState)(new Set),2),H=J[0],Q=J[1];(0,n.useEffect)((function(){z((function(e){return m(m({},e),{isPending:H.size>0})})),k=0==H.size}),[H]);var V=(0,n.useRef)([]),X=(0,r.useDispatch)();c=X;var Y=(0,n.useCallback)((function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return g(void 0,x([e],E(t),!1),void 0,(function(e,t){return void 0===t&&(t={}),w(this,(function(n){switch(n.label){case 0:return[4,M(e,t,null,X,t.useIndexDB)];case 1:return n.sent(),[2]}}))}))}),[X]),Z=(0,n.useCallback)((function(e,t){return g(void 0,void 0,void 0,(function(){var n,r,o,c,i,s,u,l,d,f,v,y,m;return w(this,(function(b){switch(b.label){case 0:Q((function(t){return new Set(x(x([],E(Array.from(t)),!1),[e.key],!1))})),b.label=1;case 1:if(b.trys.push([1,,6,7]),n=Date.now(),r="boolean"==typeof(null===(f=e.options)||void 0===f?void 0:f.useIndexDB)?e.options.useIndexDB:e.indexDbCache||(null===(v=e.options)||void 0===v?void 0:v.indexDbCache),o=null===(y=e.options)||void 0===y?void 0:y.params,F("Config: ".concat(JSON.stringify(e)),"DEBUG"),F("URL: ".concat(t),"DEBUG"),F("Using cache duration: ".concat(S),"DEBUG"),F("Using IndexedDB cache: ".concat(r),"DEBUG"),c=a.generateCacheKey?a.generateCacheKey(e.key,t,o):"".concat(e.key,"-").concat(t),F("Using cache key in fetchWithCache: ".concat(c),"DEBUG"),(i=U.get(c))&&n<i.expiresAt)return F("Using in-memory cached data for ".concat(e.key),"DEBUG"),[2,i.data];if(!r)return[3,5];b.label=2;case 2:return b.trys.push([2,4,,5]),[4,p(c)];case 3:return(s=b.sent())&&n<s.expiresAt?(F("Using IndexedDB cached data for ".concat(e.key),"DEBUG"),U.set(c,{data:s.data,timestamp:s.timestamp,expiresAt:s.expiresAt}),(null===(m=e.options)||void 0===m?void 0:m.updateIndexDbData)&&(F("Background updating IndexedDB data for ".concat(e.key),"DEBUG"),g(void 0,void 0,void 0,(function(){var r,o,i,s,u,l,d,f,p,v,y,m,g,b,D;return w(this,(function(w){switch(w.label){case 0:return w.trys.push([0,11,,12]),r=null===(y=e.options)||void 0===y?void 0:y.params,o=(null===(m=e.options)||void 0===m?void 0:m.path)?"".concat(t).concat(null===(g=e.options)||void 0===g?void 0:g.path):t,i=r?N(o,r):o,s=a.generateCacheKey?a.generateCacheKey(e.key,i,r):c,a.customFetch?[4,a.customFetch(i,e.options||{})]:[3,2];case 1:return l=w.sent(),[3,4];case 2:return[4,fetch(i,e.options||{})];case 3:l=w.sent(),w.label=4;case 4:return(u=l).ok?(d=null,e.transformResponse?[3,6]:[4,u.json()]):[3,10];case 5:return d=w.sent(),[3,8];case 6:return[4,e.transformResponse(u)];case 7:d=w.sent(),w.label=8;case 8:return f=n+((null===(b=e.options)||void 0===b?void 0:b.indexDbCacheDuration)||a.indexDbCacheDuration||a.cacheDuration||I),[4,h(s,d,f)];case 9:w.sent(),p=n+((null===(D=e.options)||void 0===D?void 0:D.memoryCacheDuration)||a.memoryCacheDuration||a.cacheDuration||S),U.set(s,{data:d,timestamp:n,expiresAt:p}),F("Updated IndexedDB data for ".concat(e.key," in background"),"DEBUG"),w.label=10;case 10:return[3,12];case 11:return v=w.sent(),F("Background update failed for ".concat(e.key,": ").concat(v),"ERROR"),[3,12];case 12:return[2]}}))}))),[2,s.data]):[3,5];case 4:return u=b.sent(),F("IndexedDB error for ".concat(e.key,": ").concat(u),"ERROR"),[3,5];case 5:return(l=P.get(c))&&n-l.timestamp<5e3?(F("Reusing pending request for ".concat(e.key),"DEBUG"),[2,l.promise]):(d=g(void 0,void 0,void 0,(function(){var o,i,s,u,l,d,f,p,v,y,m,g,b,D,E,x;return w(this,(function(w){switch(w.label){case 0:return w.trys.push([0,,9,10]),F("Making fresh request for ".concat(e.key),"DEBUG"),o=null===(y=e.options)||void 0===y?void 0:y.params,i=(null===(m=e.options)||void 0===m?void 0:m.path)?"".concat(t).concat(null===(g=e.options)||void 0===g?void 0:g.path):t,s=o?N(i,o):i,u={url:s||t,timestamp:Date.now(),params:o||{},headers:(null===(b=e.options)||void 0===b?void 0:b.headers)||{},options:e.options||{},path:(null===(D=e.options)||void 0===D?void 0:D.path)||"",response:void 0,recieveTime:void 0},A.push(u),a.customFetch?[4,a.customFetch(s,e.options||{})]:[3,2];case 1:return d=w.sent(),[3,4];case 2:return[4,fetch(s,e.options||{})];case 3:d=w.sent(),w.label=4;case 4:return l=d,f=null,e.transformResponse?[3,6]:[4,l.json()];case 5:return f=w.sent(),[3,8];case 6:return[4,e.transformResponse(l)];case 7:f=w.sent(),w.label=8;case 8:if(L(u,f),!l.ok)try{F(f.message||"Request failed for ".concat(e.key),"ERROR",{status:l.status,statusText:l.statusText}),L(u,f),j(f.message||l)}catch(e){j(f.message||l)}return p=n+((null===(E=e.options)||void 0===E?void 0:E.memoryCacheDuration)||a.memoryCacheDuration||a.cacheDuration||S),U.set(c,{data:f,timestamp:n,expiresAt:p}),r&&(v=n+((null===(x=e.options)||void 0===x?void 0:x.indexDbCacheDuration)||a.indexDbCacheDuration||a.cacheDuration||I),h(c,f,v).catch((function(e){F("Failed to store in IndexedDB: ".concat(e),"ERROR")}))),F("Cached new data for ".concat(e.key),"DEBUG",{memoryCacheExpiry:new Date(p),indexDbCache:r?"enabled":"disabled"}),[2,f];case 9:return P.delete(c),[7];case 10:return[2]}}))})),P.set(c,{timestamp:n,promise:d}),[2,d]);case 6:return[7];case 7:return[2]}}))}))}),[]),$=(0,n.useCallback)((function(){return g(void 0,void 0,void 0,(function(){var e,t,n,r,o,c,i,s,u,l,d,f,h,p,v,y,b;return w(this,(function(R){switch(R.label){case 0:if(k=!1,!O.current)return[2];R.label=1;case 1:return R.trys.push([1,3,4,5]),z({isPending:!0,haveError:!1}),F("Starting sync process","INFO"),e=[],t=[],n=[],r=W.current.fetchOrder,o=W.current.fetchItems,r.forEach((function(r){r.refetchOnline&&e.push(r.key),r.refetchOnFocus&&t.push(r.key),r.triggerEvents&&n.push({events:"string"==typeof r.triggerEvents?[r.triggerEvents]:r.triggerEvents,key:r.key})})),c=function(){F("Online event triggered","DEBUG"),e.forEach((function(e){return Y(e)}))},i=function(){F("Focus event triggered","DEBUG"),t.forEach((function(e){return Y(e)}))},window.addEventListener("online",c),window.addEventListener("focus",i),s=new Map,n.forEach((function(e){var t=e.key;e.events.forEach((function(e){var n=function(){F('Window event "'.concat(e,'" triggered for ').concat(t),"DEBUG"),Y(t)};s.set("".concat(t,"-").concat(e),n),"undefined"!=typeof window&&window.addEventListener(e,n)}))})),u=r.map((function(e){return g(void 0,void 0,void 0,(function(){var t,n,r,c,i,s;return w(this,(function(u){switch(u.label){case 0:if(t=o.get(e.key),"object"==typeof e.includedPaths&&Array.isArray(e.includedPaths)&&(n=a.getPathName?a.getPathName(t):window.location.pathname,!e.includedPaths.includes(n)))return F("Skipping ".concat(e.key," - not in included paths"),"WARN"),[2];if("object"==typeof e.excludedPaths&&Array.isArray(e.excludedPaths)&&(n=a.getPathName?a.getPathName(t):window.location.pathname,e.excludedPaths.includes(n)))return F("Skipping ".concat(e.key," - in excluded paths"),"WARN"),[2];if("boolean"==typeof e.initialSync&&!e.initialSync)return[2];if("boolean"==typeof e.backgroundSync&&e.backgroundSync)return Q((function(t){var n=new Set(t);return n.delete(e.key),n})),[2,G.set(e.key,(function(){return Y(e.key)}))];if(V.current.includes("".concat(e.key,"_").concat(null===(i=e.options)||void 0===i?void 0:i.path)))return F("Skipping ".concat(e.key," - already pending"),"WARN"),[2];if(!t)return F("URL not found for ".concat(e.key),"ERROR"),[2,j("url not found for ".concat(e.key))];V.current=x(x([],E(V.current),!1),["".concat(e.key,"_").concat(null===(s=e.options)||void 0===s?void 0:s.path)],!1),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,Z(e,t)];case 2:return r=u.sent(),Q((function(t){var n=new Set(t);return n.delete(e.key),n})),O.current&&X(e.action(r)),[3,5];case 3:return c=u.sent(),F("Sync error : ".concat(c),"ERROR"),[3,5];case 4:return O.current&&(V.current=V.current.filter((function(t){var n;return t!=="".concat(e.key,"_").concat(null===(n=e.options)||void 0===n?void 0:n.path)}))),[7];case 5:return[2]}}))}))})).filter(Boolean),[4,Promise.all(u)];case 2:if(R.sent(),O.current){z({isPending:!1,haveError:!1}),l=Array.from(G.entries());try{for(d=D(l),f=d.next();!f.done;f=d.next())h=E(f.value,2),p=h[0],(0,h[1])(),G.delete(p)}catch(e){y={error:e}}finally{try{f&&!f.done&&(b=d.return)&&b.call(d)}finally{if(y)throw y.error}}}return[2,function(){F("Cleaning up event listeners","DEBUG"),window.removeEventListener("online",c),window.removeEventListener("focus",i),n.forEach((function(e){var t=e.key;e.events.forEach((function(e){var n=s.get("".concat(t,"-").concat(e));n&&"undefined"!=typeof window&&window.removeEventListener(e,n)}))})),s.clear()}];case 3:return v=R.sent(),z((function(e){return m(m({},e),{haveError:!0})})),k=!0,F("Sync process failed","ERROR",{error:v}),W.current.onError&&W.current.onError(v),[3,5];case 4:return[7];case 5:return[2]}}))}))}),[X,Z,Y]),ee=E((0,n.useState)(window.location.pathname),2),te=ee[0],ne=ee[1];return(0,n.useEffect)((function(){if(W.current.reSyncOnPathChange){var e=function(){var e=window.location.pathname;e!==te&&(ne(e),F("Location changed, triggering re-sync","INFO"),$())};window.addEventListener("popstate",e);var t=window.history.pushState,n=window.history.replaceState;return window.history.pushState=function(){t.apply(this,x([],E(arguments),!1)),e()},window.history.replaceState=function(){n.apply(this,x([],E(arguments),!1)),e()},function(){window.removeEventListener("popstate",e),window.history.pushState=t,window.history.replaceState=n}}}),[te,$]),(0,n.useEffect)((function(){O.current=!0,function(){try{var e=localStorage.getItem(C);if(!e)return!0;var t=parseInt(e,10);return Date.now()-t>864e5}catch(e){return F("Error checking cache cleanup time: ".concat(e),"ERROR"),!0}}()&&(F("Running scheduled cache cleanup","INFO"),K().then((function(e){var t=e.memory,n=e.indexedDB;F("Scheduled cleanup completed. Removed ".concat(t," memory items and ").concat(n," IndexedDB items"),"INFO")})).catch((function(e){F("Error during scheduled cache cleanup: ".concat(e),"ERROR")})));var e=$();return function(){O.current=!1,e.then((function(e){return e&&e()}))}}),[$]),{isPending:q.isPending||H.size>0,haveError:q.haveError,clearCache:T,refresh:$,loadingItems:Array.from(H)}};module.exports=t})();