synapse-storage 3.0.11 → 3.0.13

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/utils.js CHANGED
@@ -1 +1 @@
1
- var l=!1,h=new Map;function w(n){let e=0;if(n.length===0)return e.toString(36);for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function g(n,e){if(n===e)return!0;if(n==null||e==null)return!1;if(typeof n!="object"&&typeof n!="function"&&typeof e!="object"&&typeof e!="function")return n===e;if(typeof n!=typeof e)return!1;if(n instanceof Date&&e instanceof Date)return n.getTime()===e.getTime();if(Array.isArray(n)&&Array.isArray(e)){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!g(n[t],e[t]))return!1;return!0}if(typeof n=="object"&&typeof e=="object"){let t=Object.keys(n),r=Object.keys(e);return t.length!==r.length?!1:t.every(s=>Object.prototype.hasOwnProperty.call(e,s)?g(n[s],e[s]):!1)}return!1}function v(n,e=g){let t,r,s=!1;return function(o){if(!s||t!==o){let i=n(o);(!s||!e(i,r))&&(r=i),t=o,s=!0}return r}}var y=class{constructor(e,t,r=g,s){this.name=e;this.equals=r;this.logger=s;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t),l&&console.log(`[${this.id}] \u0421\u043E\u0437\u0434\u0430\u043D new SelectorSubscription`)}id;subscribers=new Set;lastValue;memoizedGetState;createMemoizedGetState(e){let t=null,r=!1;return async()=>{if(r&&t)return t;r=!0;try{return t=e(),await t}finally{r=!1}}}async notify(){try{let e=await this.memoizedGetState();if(this.lastValue===void 0||!this.equals(e,this.lastValue)){l&&console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C, notify()`,{old:this.lastValue,new:e}),this.lastValue=e;let t=Array.from(this.subscribers).map(async r=>{try{await r.notify(e)}catch(s){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430`,{error:s})}});await Promise.all(t)}else l&&console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043D\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C in notify(), \u043F\u0440\u043E\u043F\u0443\u0441\u043A \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F`)}catch(e){throw this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 notify()`,{error:e}),e}}subscribe(e){return l&&console.log(`[${this.id}] \u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E \u043D\u043E\u0432\u044B\u0439 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A, \u0432\u0441\u0435\u0433\u043E: ${this.subscribers.size+1}`),this.subscribers.add(e),this.lastValue!==void 0?Promise.resolve().then(()=>{try{e.notify(this.lastValue)}catch(t){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}}):this.notify().catch(t=>{this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}),()=>{l&&console.log(`[${this.id}] \u041F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A \u0443\u0434\u0430\u043B\u0435\u043D, \u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C: ${this.subscribers.size-1}`),this.subscribers.delete(e)}}cleanup(){l&&console.log(`[${this.id}] \u041E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0438, \u0431\u044B\u043B\u043E ${this.subscribers.size} \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u043E\u0432`),this.subscribers.clear(),this.lastValue=void 0}getId(){return this.id}},f=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,l&&console.log(`\u0421\u043E\u0437\u0434\u0430\u043D SelectorModule \u0434\u043B\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${this.storageName}`),this.source.getState().then(r=>{this.cachedState=r,l&&console.log(`\u041A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0434\u043B\u044F ${this.storageName}`)})}storageName;subscriptions=new Map;cachedState;localSelectorCache=new Map;batchUpdateInProgress=!1;pendingUpdates=new Set;generateName(e,t,r){let s=e?"simple":"combined",a="";if(e){let o=t.toString();a=w(o)}else{let o=t.map(c=>c.getId()).join("_"),i=r.toString();a=w(o+i)}return`${this.storageName}_${s}_${a}`}processPendingUpdates(){this.pendingUpdates.size===0||this.batchUpdateInProgress||(this.batchUpdateInProgress=!0,setTimeout(async()=>{try{let e=Array.from(this.pendingUpdates);this.pendingUpdates.clear(),this.cachedState=await this.source.getState();let t=e.map(async r=>{let s=this.subscriptions.get(r);if(s)try{return await s.notify()}catch(a){this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430 ${r}`,{error:a})}return Promise.resolve()});await Promise.all(t)}catch(e){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0439",{error:e})}finally{this.batchUpdateInProgress=!1,this.pendingUpdates.size>0&&this.processPendingUpdates()}},0))}createSelector(e,t,r){let s=!Array.isArray(e),a=s?t||{}:r||{},o=a.name||this.generateName(s,e,s?void 0:t);if(this.localSelectorCache.has(o))return l&&console.log(`[${this.storageName}] Reusing cached selector: ${o}`),this.localSelectorCache.get(o).api;if(h.has(o)){let u=h.get(o);return u.refCount++,l&&console.log(`[${this.storageName}] \u041F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0433\u043E \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440\u0430: ${o}, refCount: ${u.refCount}`),u.api}let i,c,p=[];if(s){let u=v(e,a.equals||g),d=this.createSimpleSelector(u,{...a,name:o,equals:a.equals||g});i=d.api,p=d.unsubscribeFunctions}else{c=e;let u=this.createCombinedSelector(c,t,{...a,name:o,equals:a.equals||g});i=u.api,p=u.unsubscribeFunctions}return this.localSelectorCache.set(o,{api:i,dependencies:c,unsubscribeFunctions:p}),h.set(o,{api:i,refCount:1,unsubscribeFunctions:p}),l&&console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043D\u043E\u0432\u044B\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${o}`),i}createSimpleSelector(e,t){l&&console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043F\u0440\u043E\u0441\u0442\u043E\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${t.name}`);let r=async()=>{if(this.cachedState)return e(this.cachedState);let c=await this.source.getState();return this.cachedState=c,e(c)},s=new y(t.name,r,t.equals||g,this.logger),a=s.getId();this.subscriptions.set(a,s);let i=[this.source.subscribeToAll(async c=>{c?.type==="storage:update"&&(l&&console.log(`[${a}] \u041F\u043E\u043B\u0443\u0447\u0435\u043D\u043E \u0441\u043E\u0431\u044B\u0442\u0438\u0435 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430`),this.pendingUpdates.add(a),this.processPendingUpdates())})];return{api:{select:()=>r(),subscribe:c=>s.subscribe(c),getId:()=>a},unsubscribeFunctions:i}}createCombinedSelector(e,t,r){let s=v(d=>t(...d),r.equals||g),a=async()=>{let d=await Promise.all(e.map(m=>m.select()));return s(d)},o=new y(r.name,a,r.equals||g,this.logger),i=o.getId();this.subscriptions.set(i,o);let c=null,p=()=>{c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,o.notify().catch(d=>this.logger?.error(`[${i}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438:`,{error:d}))},10)},u=e.map(d=>d.subscribe({notify:()=>{p()}}));return{api:{select:()=>a(),subscribe:d=>o.subscribe(d),getId:()=>i},unsubscribeFunctions:u}}destroy(){l&&console.log(`[${this.storageName}] \u041D\u0430\u0447\u0430\u043B\u043E\u0441\u044C \u0443\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D\u0438\u0435 SelectorModule`),this.subscriptions.forEach(t=>t.cleanup()),this.subscriptions.clear(),this.cachedState=void 0,this.pendingUpdates.clear(),this.localSelectorCache.forEach(t=>{t.unsubscribeFunctions.forEach(r=>r())});let e=new Set;this.localSelectorCache.forEach((t,r)=>{e.add(r)}),this.localSelectorCache.clear(),e.forEach(t=>{let r=h.get(t);r&&(r.refCount--,r.refCount<=0&&(r.unsubscribeFunctions.forEach(s=>s()),h.delete(t),l&&console.log(`[${this.storageName}] \u0423\u0434\u0430\u043B\u0435\u043D \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440 \u0438\u0437 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0430: ${t}`)))}),l&&console.log(`[${this.storageName}] \u0423\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D`)}};import{Subject as Le}from"rxjs";import{combineLatest as Ot,merge as Bt,Observable as I,of as M,pipe as Nt,Subject as C}from"rxjs";import{catchError as O,filter as Ft,map as Vt,share as B,switchMap as Ut,take as jt}from"rxjs/operators";import{of as dt}from"rxjs";import{concatAll as gt,delay as pt,mergeMap as ht,toArray as yt}from"rxjs/operators";import{forkJoin as Tt,timer as wt}from"rxjs";import{mergeMap as xt}from"rxjs/operators";var S=class{constructor(e,t={},r,s={},a={}){this.storage=e;this.externalStates=t;this.dispatchers=r;this.services=s;this.config=a;this.subscribeToDispatchers(),this.state$=new I(o=>{this.storage.getState().then(c=>o.next(c));let i=this.storage.subscribeToAll(()=>{this.storage.getState().then(c=>o.next(c))});return()=>i()}).pipe(B())}effects=[];subscriptions=[];running=!1;action$=new C;state$;subscribeToDispatchers(){for(let[e,t]of Object.entries(this.dispatchers)){let r=t.actions.subscribe(s=>{this.action$.next(s)});this.subscriptions.push(r)}}add(e){return this.effects.push(e),this.running&&this.subscribeToEffect(e),this}addEffects(e){return e.forEach(t=>this.add(t)),this}start(){return this.running?this:(this.effects.forEach(e=>this.subscribeToEffect(e)),this.running=!0,this)}stop(){return this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.running=!1,this}subscribeToEffect(e){try{let r=e(this.action$.asObservable(),this.state$,this.externalStates,this.dispatchers,this.services,this.config).pipe(O(s=>(console.error("Error in effect:",s),M(null)))).subscribe(s=>{if(s!=null&&typeof s=="function")try{s()}catch(a){console.error("Error calling effect result function:",a)}});this.subscriptions.push(r)}catch(t){console.error("Error setting up effect:",t)}}};async function K(n){let e=n.createStorageFn?await n.createStorageFn():n.storage,t=[],r={storage:e,selectors:{},destroy:async()=>{for(let i of t)await i()}};t.push(()=>e.destroy());let s,a,o;if(n.createSelectorsFn)try{a=new f(e);let i=n.externalSelectors||{};r.selectors=n.createSelectorsFn(a,i),typeof a.destroy=="function"&&t.push(()=>a.destroy())}catch(i){console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F selectors:",i)}if(n.createDispatcherFn&&(s=n.createDispatcherFn(e),r.dispatcher=s,s&&"dispatch"in s&&(r.actions=s.dispatch,typeof s.destroy=="function"&&t.push(()=>s.destroy()))),n.createEffectConfig&&s)try{let{dispatchers:i,api:c,config:p,externalStates:u}=n.createEffectConfig(s),d=u||{};o=new S(e,d,i,c,p),Array.isArray(n.effects)&&n.effects.forEach(m=>{o&&o.add(m)}),o.start(),r.state$=o.state$,t.push(()=>{o&&o.stop()})}catch(i){console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u043C\u043E\u0434\u0443\u043B\u044F \u044D\u0444\u0444\u0435\u043A\u0442\u043E\u0432:",i)}return r}export{K as createSynapse};
1
+ var y=!1,A=new Map;function N(a){let e=0;if(a.length===0)return e.toString(36);for(let t=0;t<a.length;t++){let s=a.charCodeAt(t);e=(e<<5)-e+s,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function T(a,e){if(a===e)return!0;if(a==null||e==null)return!1;if(typeof a!="object"&&typeof a!="function"&&typeof e!="object"&&typeof e!="function")return a===e;if(typeof a!=typeof e)return!1;if(a instanceof Date&&e instanceof Date)return a.getTime()===e.getTime();if(Array.isArray(a)&&Array.isArray(e)){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!T(a[t],e[t]))return!1;return!0}if(typeof a=="object"&&typeof e=="object"){let t=Object.keys(a),s=Object.keys(e);return t.length!==s.length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)?T(a[r],e[r]):!1)}return!1}function K(a,e=T){let t,s,r=!1;return function(o){if(!r||t!==o){let i=a(o);(!r||!e(i,s))&&(s=i),t=o,r=!0}return s}}var I=class{constructor(e,t,s=T,r){this.name=e;this.equals=s;this.logger=r;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t)}id;subscribers=new Set;lastValue;memoizedGetState;createMemoizedGetState(e){let t=null,s=!1;return async()=>{if(s&&t)return t;s=!0;try{return t=e(),await t}finally{s=!1}}}async notify(){try{let e=await this.memoizedGetState();if(this.lastValue===void 0||!this.equals(e,this.lastValue)){this.lastValue=e;let t=Array.from(this.subscribers).map(async s=>{try{await s.notify(e)}catch(r){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430`,{error:r})}});await Promise.all(t)}}catch(e){throw this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 notify()`,{error:e}),e}}subscribe(e){return this.subscribers.add(e),this.lastValue!==void 0?Promise.resolve().then(()=>{try{e.notify(this.lastValue)}catch(t){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}}):this.notify().catch(t=>{this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}),()=>{this.subscribers.delete(e)}}cleanup(){this.subscribers.clear(),this.lastValue=void 0}getId(){return this.id}},C=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,this.source.getState().then(s=>{this.cachedState=s})}storageName;subscriptions=new Map;cachedState;localSelectorCache=new Map;batchUpdateInProgress=!1;pendingUpdates=new Set;generateName(e,t,s){let r=e?"simple":"combined",n="";if(e){let o=t.toString();n=N(o)}else{let o=t.map(c=>c.getId()).join("_"),i=s.toString();n=N(o+i)}return`${this.storageName}_${r}_${n}`}processPendingUpdates(){this.pendingUpdates.size===0||this.batchUpdateInProgress||(this.batchUpdateInProgress=!0,setTimeout(async()=>{try{let e=Array.from(this.pendingUpdates);this.pendingUpdates.clear(),this.cachedState=await this.source.getState();let t=e.map(async s=>{let r=this.subscriptions.get(s);if(r)try{return await r.notify()}catch(n){this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430 ${s}`,{error:n})}return Promise.resolve()});await Promise.all(t)}catch(e){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0439",{error:e})}finally{this.batchUpdateInProgress=!1,this.pendingUpdates.size>0&&this.processPendingUpdates()}},0))}createSelector(e,t,s){let r=!Array.isArray(e),n=r?t||{}:s||{},o=n.name||this.generateName(r,e,r?void 0:t);if(this.localSelectorCache.has(o))return this.localSelectorCache.get(o).api;if(A.has(o)){let u=A.get(o);return u.refCount++,u.api}let i,c,d=[];if(r){let u=K(e,n.equals||T),p=this.createSimpleSelector(u,{...n,name:o,equals:n.equals||T});i=p.api,d=p.unsubscribeFunctions}else{c=e;let u=this.createCombinedSelector(c,t,{...n,name:o,equals:n.equals||T});i=u.api,d=u.unsubscribeFunctions}return this.localSelectorCache.set(o,{api:i,dependencies:c,unsubscribeFunctions:d}),A.set(o,{api:i,refCount:1,unsubscribeFunctions:d}),i}createSimpleSelector(e,t){let s=async()=>{if(this.cachedState)return e(this.cachedState);let c=await this.source.getState();return this.cachedState=c,e(c)},r=new I(t.name,s,t.equals||T,this.logger),n=r.getId();this.subscriptions.set(n,r);let i=[this.source.subscribeToAll(async c=>{c?.type==="storage:update"&&(this.pendingUpdates.add(n),this.processPendingUpdates())})];return{api:{select:()=>s(),subscribe:c=>r.subscribe(c),getId:()=>n},unsubscribeFunctions:i}}createCombinedSelector(e,t,s){let r=K(p=>t(...p),s.equals||T),n=async()=>{let p=await Promise.all(e.map(l=>l.select()));return r(p)},o=new I(s.name,n,s.equals||T,this.logger),i=o.getId();this.subscriptions.set(i,o);let c=null,d=()=>{c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,o.notify().catch(p=>this.logger?.error(`[${i}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438:`,{error:p}))},10)},u=e.map(p=>p.subscribe({notify:()=>{d()}}));return{api:{select:()=>n(),subscribe:p=>o.subscribe(p),getId:()=>i},unsubscribeFunctions:u}}destroy(){this.subscriptions.forEach(t=>t.cleanup()),this.subscriptions.clear(),this.cachedState=void 0,this.pendingUpdates.clear(),this.localSelectorCache.forEach(t=>{t.unsubscribeFunctions.forEach(s=>s())});let e=new Set;this.localSelectorCache.forEach((t,s)=>{e.add(s)}),this.localSelectorCache.clear(),e.forEach(t=>{let s=A.get(t);s&&(s.refCount--,s.refCount<=0&&(s.unsubscribeFunctions.forEach(r=>r()),A.delete(t)))})}};var b=class{constructor(e,t=!1){this.value=e;this.isRawKey=t}toString(){return this.value}toJSON(){return this.value}valueOf(){return this.value}isUnparseable(){return this.isRawKey}};var V=(a={})=>{let e=a.batchSize??10,t=a.batchDelay??10,s=new Map,r=new Map,n=l=>l.type==="set"||l.type==="update",o=l=>`${l.type}_${l.key?.toString()||"default"}`,i=l=>{let g=new Map;for(let h of l){let S=`${h.type}_${h.key?.toString()||"default"}`;g.set(S,h)}return Array.from(g.values())},c=l=>{let g=r.get(l);g&&(globalThis.clearTimeout(g),r.delete(l))},d=(l,g)=>{let h=globalThis.setTimeout(g,t);r.set(l,h)},u=async(l,g,h)=>{let S=s.get(l);if(!(!S||S.length===0)){s.delete(l),c(l);try{let E=S.map(f=>f.action),m=i(E);for(let f of m)try{let B=await h(f);S.filter(w=>w.action.type===f.type&&w.action.key?.toString()===f.key?.toString()).forEach(w=>w.resolve(B))}catch(B){S.filter(w=>w.action.type===f.type&&w.action.key?.toString()===f.key?.toString()).forEach(w=>w.reject(B))}}catch(E){S.forEach(m=>m.reject(E))}}},p=async(l,g,h)=>new Promise((S,E)=>{let m=o(l),f=s.get(m);f||(f=[],s.set(m,f)),f.push({action:l,resolve:S,reject:E,timestamp:Date.now()}),c(m),f.length>=e?setImmediate(()=>u(m,g,h)):d(m,()=>u(m,g,h))});return{name:"batching",setup:()=>{},cleanup:async()=>{r.forEach(l=>globalThis.clearTimeout(l)),r.clear(),s.clear()},reducer:l=>g=>async h=>n(h)?p(h,l,g):g(h)}};var j=(a={})=>{let{comparator:e=(r,n)=>{if(r===n)return!0;if(typeof r!="object"||typeof n!="object"||r===null||n===null)return r===n;let o=Object.keys(r),i=Object.keys(n);return o.length!==i.length?!1:o.every(c=>Object.prototype.hasOwnProperty.call(n,c)&&r[c]===n[c])},segments:t=[]}=a,s=new Map;return{name:"shallow-compare",setup:r=>{},reducer:r=>n=>async o=>{if(o.type!=="set"||t.length&&!t.includes(o.metadata?.segment??"default"))return n(o);let i=o.key,c=s.get(i),d=o.value;if(c!==void 0&&e(c,d))return{...c,t:{valueNotChanged:!0,originalValue:c}};let u=await n(o);return s.set(i,d),u}}};var M=class{middlewares=[];api;initialized=!1;dispatchFn;constructor(e){this.api={dispatch:async t=>this.dispatch(t),getState:()=>e.getState(),storage:{doGet:e.doGet.bind(e),doSet:e.doSet.bind(e),doUpdate:e.doUpdate.bind(e),doDelete:e.doDelete.bind(e),doClear:e.doClear.bind(e),doKeys:e.doKeys.bind(e),notifySubscribers:e.notifySubscribers.bind(e)}}}async baseOperation(e){let{processed:t,...s}=e.metadata||{},r={...e,metadata:s};switch(r.type){case"get":return this.api.storage.doGet(r.key);case"set":return await this.api.storage.doSet(r.key,r.value),this.api.storage.doGet(r.key);case"update":return Array.isArray(r.value)?(await this.api.storage.doUpdate(r.value),this.api.storage.doGet("")):r.value;case"delete":return this.api.storage.doDelete(r.key);case"clear":return this.api.storage.doClear();case"init":{let n=await this.api.storage.doGet("");return Object.keys(n||{}).length>0?n:r.value?(await this.api.storage.doSet("",r.value),this.api.storage.doGet("")):n}case"keys":return this.api.storage.doKeys();default:throw new Error(`Unknown action type: ${r.type}`)}}initializeMiddlewares(){if(this.initialized)return;let e=this.baseOperation.bind(this);for(let t of[...this.middlewares].reverse()){let s=e;e=async r=>{if(r.metadata?.processed)return s(r);let n={...r,metadata:{...r.metadata,processed:!0,timestamp:r.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(s)(n)}}this.dispatchFn=e,this.initialized=!0}use(e){e.setup&&e.setup(this.api),this.middlewares.push(e),this.initialized=!1}async dispatch(e){this.initialized||this.initializeMiddlewares();try{return this.dispatchFn(e)}catch(t){throw t}}};function x(a){return a instanceof b&&a.isUnparseable()?[a.toString()]:a.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function v(a,e){return x(e).reduce((s,r)=>s===void 0?void 0:s[r],a)}function P(a,e,t){if(e==="")return t;let s=x(e);if(e instanceof b&&e.isUnparseable())return a[e.toString()]=t,a;let r=s.pop(),n=s.reduce((o,i)=>{let c=s[s.indexOf(i)+1],d=!Number.isNaN(Number(c));return i in o||(o[i]=d?[]:{}),o[i]},a);return n[r]=t,a}var R=class a{constructor(e,t,s,r){this.config=e;this.pluginExecutor=t;this.eventEmitter=s;this.logger=r;this.name=e.name,this.middlewareModule=new M({getState:this.getState.bind(this),doGet:this.doGet.bind(this),doSet:this.doSet.bind(this),doUpdate:this.doUpdate.bind(this),doDelete:this.doDelete.bind(this),doClear:this.doClear.bind(this),doKeys:this.doKeys.bind(this),notifySubscribers:this.notifySubscribers.bind(this),pluginExecutor:this.pluginExecutor,eventEmitter:this.eventEmitter,logger:this.logger}),this.initializeMiddlewares()}static GLOBAL_SUBSCRIPTION_KEY="*";name;e={status:"idle"};statusSubscribers=new Set;selectorPathCache=new WeakMap;middlewareModule;initializedMiddlewares=null;subscribers=new Map;get initStatus(){return{...this.e}}async waitForReady(){if(this.e.status==="ready")return this;if(this.e.status==="error")throw this.e.error||new Error("Storage initialization failed");return new Promise((e,t)=>{let s=this.onStatusChange(r=>{r.status==="ready"?(s(),e(this)):r.status==="error"&&(s(),t(r.error||new Error("Storage initialization failed")))})})}onStatusChange(e){return this.statusSubscribers.add(e),e(this.initStatus),()=>{this.statusSubscribers.delete(e)}}updateInitStatus(e){let t=this.e.status;this.e={...this.e,...e},t!==this.e.status&&this.logger?.debug(`Storage "${this.name}" status changed: ${t} -> ${this.e.status}`);let s=this.initStatus;this.statusSubscribers.forEach(r=>{try{r(s)}catch(n){this.logger?.error("Error in status change callback",{error:n})}})}async initialize(){if(this.e.status==="ready")return this;if(this.e.status==="loading")return this.waitForReady();this.updateInitStatus({status:"loading",error:void 0});try{let e=await this.doInitialize();return this.updateInitStatus({status:"ready",error:void 0}),e}catch(e){throw this.updateInitStatus({status:"error",error:e instanceof Error?e:new Error(String(e))}),e}}ensureReady(){if(this.e.status!=="ready")throw new Error(`Storage "${this.name}" is not ready. Current status: ${this.e.status}`)}initializeMiddlewares(){this.config.middlewares&&!this.initializedMiddlewares&&(this.initializedMiddlewares=this.config.middlewares(()=>this.getDefaultMiddleware()),this.initializedMiddlewares.forEach(e=>this.middlewareModule.use(e)))}getDefaultMiddleware(){return{batching:(e={})=>V(e),shallowCompare:(e={})=>j(e)}}async initializeWithMiddlewares(){try{let e=await this.getState();!(Object.keys(e).length>0)&&this.config.initialState&&await this.middlewareModule.dispatch({type:"init",value:this.config.initialState})}catch(e){throw this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430",{error:e}),e}}async get(e){this.ensureReady();try{let t={operation:"get",timestamp:Date.now(),key:e},s=await this.middlewareModule.dispatch({type:"get",key:e,metadata:t}),r=await this.pluginExecutor?.executeAfterGet(e,s,t)??s;return await this.emitEvent({type:"storage:select",payload:{key:e,value:r}}),r}catch(t){throw this.logger?.error("Error getting value",{key:e,error:t}),t}}async set(e,t){this.ensureReady();try{let s={operation:"set",timestamp:Date.now(),key:e},r=await this.pluginExecutor?.executeBeforeSet(t,s)??t,n=await this.middlewareModule.dispatch({type:"set",key:e,value:r,metadata:s}),o=n?.t?.valueNotChanged===!0,i;if(o&&n?.t?.originalValue!==void 0?i=n.t.originalValue:i=await this.pluginExecutor?.executeAfterSet(e,n,s)??n,!o){let d=[e.toString()];this.notifySubscribers(e,i),this.notifySubscribers(a.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:i,changedPaths:d}),await this.emitEvent({type:"storage:update",payload:{key:e,value:i,changedPaths:d}})}}catch(s){throw this.logger?.error("Error setting value",{key:e,error:s}),s}}async update(e){this.ensureReady();try{let t={operation:"update",timestamp:Date.now()},s=await this.getState(),r=structuredClone(s);e(r);let n=this.findChangedPaths(s,r);if(n.size===0){this.logger?.debug&&this.logger.debug("No changes detected in update");return}this.logger?.debug&&this.logger.debug("Changed paths:",{paths:Array.from(n)});let o=new Set;for(let l of n){let g=l.split(".")[0];o.add(g)}let i=await Promise.all(Array.from(o).map(async l=>{let g={...t,key:l},h=await this.pluginExecutor?.executeBeforeSet(r[l],g)??r[l];return{key:l,value:h}})),c=await this.middlewareModule.dispatch({type:"update",value:i,metadata:{...t,batchUpdate:!0,changedPaths:Array.from(n)}}),d={};Array.isArray(c)?c.forEach(l=>{l&&typeof l=="object"&&"key"in l&&"value"in l&&(d[l.key]=l.value)}):c&&typeof c=="object"&&(d={...c});let u=Object.keys(d).filter(l=>!this.isEqual(s[l],d[l]));if(u.length===0){this.logger?.debug&&this.logger.debug("No actual changes after middleware processing");return}let p={};u.forEach(l=>{p[l]=d[l]}),this.logger?.debug&&this.logger.debug("Notifying subscribers about changes:",{keys:u}),this.notifySubscribers(a.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:u,value:p,changedPaths:Array.from(n)});for(let l of n)try{let g=l.split(".")[0];if(g in p){let h;if(l===g)h=p[g];else{let S=l.substring(g.length+1);h=v(p[g],S)}h!==void 0&&this.notifySubscribers(l,h)}}catch(g){this.logger?.error("Error notifying path subscribers",{path:l,error:g})}await this.emitEvent({type:"storage:update",payload:{state:p,key:u,changedPaths:Array.from(n)}})}catch(t){throw this.logger?.error("Error updating state",{error:t}),t}}async delete(e){this.ensureReady();try{let t={operation:"delete",timestamp:Date.now(),key:e};if(await this.pluginExecutor?.executeBeforeDelete(e,t)){let s=await this.middlewareModule.dispatch({type:"delete",key:e,metadata:t});await this.pluginExecutor?.executeAfterDelete(e,t);let n=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(a.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:s,changedPaths:n}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:s,changedPaths:n}})}}catch(t){throw this.logger?.error("Error deleting value",{key:e,error:t}),t}}async clear(){this.ensureReady();try{this.pluginExecutor?.executeOnClear(),await this.middlewareModule.dispatch({type:"clear"})}catch(e){throw this.logger?.error("Error clearing storage",{error:e}),e}}async keys(){this.ensureReady();try{return await this.middlewareModule.dispatch({type:"keys"})}catch(e){throw this.logger?.error("Error getting keys",{error:e}),e}}async has(e){this.ensureReady();try{return await this.doHas(e)}catch(t){throw this.logger?.error("Error checking value existence",{key:e,error:t}),t}}async getState(){try{return await this.doGet("")||{}}catch(e){throw this.logger?.error("Error getting state",{error:e}),e}}subscribeToAll(e){return this.subscribers.has(a.GLOBAL_SUBSCRIPTION_KEY)||this.subscribers.set(a.GLOBAL_SUBSCRIPTION_KEY,new Set),this.subscribers.get(a.GLOBAL_SUBSCRIPTION_KEY).add(e),()=>{let t=this.subscribers.get(a.GLOBAL_SUBSCRIPTION_KEY);t&&(t.delete(e),t.size===0&&this.subscribers.delete(a.GLOBAL_SUBSCRIPTION_KEY))}}subscribe(e,t){return typeof e=="string"?this.subscribeByKey(e,t):this.subscribeBySelector(e,t)}async destroy(){try{await this.clear(),await this.doDestroy(),this.initializedMiddlewares&&(await Promise.all(this.initializedMiddlewares.map(async e=>{"cleanup"in e&&await e.cleanup?.()})),this.initializedMiddlewares=null),this.statusSubscribers.clear(),this.updateInitStatus({status:"idle"}),await this.emitEvent({type:"storage:destroy"})}catch(e){throw this.logger?.error("Error destroying storage",{error:e}),e}}subscribeByKey(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let s=!1;return this.subscribers.get(e).add(t),this.get(e).then(r=>{try{s||(s=!0,t(r))}catch(n){this.logger?.error("Error in initial callback",{key:e,error:n})}}),()=>{let r=this.subscribers.get(e);r&&(r.delete(t),r.size===0&&this.subscribers.delete(e))}}createDummyState(){let e={get:(t,s)=>(t[s]=t[s]||new Proxy({},e),t[s])};return new Proxy({},e)}isEqual(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;let s=typeof e;if(s!==typeof t)return!1;if(s!=="object")return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!this.isEqual(e[i],t[i]))return!1;return!0}let n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(i=>Object.prototype.hasOwnProperty.call(t,i)&&this.isEqual(e[i],t[i]))}extractPath(e,t){if(this.selectorPathCache.has(e))return this.selectorPathCache.get(e);let s=[],r=(n="")=>({get:(o,i)=>{if(typeof i=="symbol")return Reflect.get(o,i);let c=n?`${n}.${i}`:i;return s.push(c),new Proxy({},r(c))},has:(o,i)=>!0,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0}),apply:(o,i,c)=>new Proxy(()=>{},r(n))});try{e(new Proxy(t,r()))}catch{}return s.length===0?"":(s.sort((n,o)=>o.length-n.length),this.selectorPathCache.set(e,s[0]),s[0])}notifySubscribers(e,t){let s=e.toString(),r=this.subscribers.get(s);r?.size&&new Set(r).forEach(o=>{try{o(t)}catch(i){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0435 \u043D\u0430 \u043A\u043E\u043B\u0431\u044D\u043A",{key:s,error:i})}})}findChangedPaths(e,t,s="",r=new Set,n=new WeakMap){if(e===t)return r;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e!==t&&r.add(s||""),r;if(n.has(e))return r;n.set(e,!0);let o=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let i of o){let c=e[i],d=t[i];if(c===d)continue;let u=s?`${s}.${i}`:i;c&&d&&typeof c=="object"&&typeof d=="object"&&!Array.isArray(c)&&!Array.isArray(d)?this.findChangedPaths(c,d,u,r,n):Array.isArray(c)&&Array.isArray(d)?this.isEqual(c,d)||r.add(u):this.isEqual(c,d)||r.add(u)}return r}subscribeBySelector(e,t){let s=this.createDummyState(),r=this.extractPath(e,s);this.logger?.debug&&this.logger.debug("Subscribing to path:",{path:r});let n=async o=>{try{if(o==null){let d=await this.getState(),u=e(d);t(u);return}if(typeof o!="object"||o===null){t(o);return}let i=await this.getState(),c=e(i);t(c)}catch(i){this.logger?.error("Error in selector callback",{path:r,error:i}),t(o)}};return r?this.subscribeByKey(r,n):this.subscribeToAll(()=>{this.getState().then(o=>{t(e(o))})})}async emitEvent(e){try{await this.eventEmitter?.emit({...e,metadata:{...e.metadata||{},timestamp:Date.now(),storageName:this.name}})}catch(t){this.logger?.error("Error emitting event",{event:e,error:t})}}};var D=class extends R{storage=new Map;constructor(e,t,s,r){super(e,t,s,r)}async doInitialize(){try{return this.logger?.debug(`Initializing MemoryStorage "${this.name}"`),this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this.logger?.debug(`MemoryStorage "${this.name}" initialized successfully`),this}catch(e){throw this.logger?.error("Error initializing MemoryStorage",{error:e}),e}}async doGet(e){let t=this.storage.get(this.name);if(t)return e instanceof b&&e.isUnparseable()?t[e.valueOf()]:v(t,e)}async doSet(e,t){let s=this.storage.get(this.name)||{};if(e instanceof b&&e.isUnparseable()){s[e.valueOf()]=t,this.storage.set(this.name,s);return}let r=P({...s},e,t);this.storage.set(this.name,r)}async doDelete(e){let t=this.storage.get(this.name);if(!t)return!1;if(e instanceof b&&e.isUnparseable()){let i=e.valueOf();return i in t?(delete t[i],this.storage.set(this.name,t),!0):!1}let s=x(e),r=s.slice(0,-1).join("."),n=s[s.length-1],o=r?v(t,r):t;return!o||!(n in o)?!1:(delete o[n],this.storage.set(this.name,t),!0)}async doUpdate(e){let s={...this.storage.get(this.name)||{}};for(let{key:r,value:n}of e)r instanceof b&&r.isUnparseable()?s[r.valueOf()]=n:P(s,r,n);this.storage.set(this.name,s)}async doClear(){this.storage.delete(this.name)}async doKeys(){let e=this.storage.get(this.name);return e?this.getAllKeys(e):[]}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){this.storage.delete(this.name)}getAllKeys(e){return Object.keys(e)}};import{Observable as G,Subject as U}from"rxjs";var $=class{constructor(e){this.options=e;this.storage=e.storage,this.middlewareAPI={getState:()=>this.storage.getState(),dispatch:async t=>(this.actions$.next(t),t.payload),storage:this.storage,actions$:this.actions,actions:this.dispatch,watchers:this.watchers,findActionByType:t=>this.findActionByType(t),findWatcherByType:t=>this.findWatcherByType(t)},e.middlewares&&e.middlewares.length>0&&this.use(...e.middlewares)}actions$=new U;actions=this.actions$.asObservable();dispatch={};watchers={};storage;middlewareFunctions=[];middlewareAPI;use(...e){for(let t=0;t<e.length;t++)try{let s=e[t](this.middlewareAPI);this.middlewareFunctions.push(s)}catch{}return this}getActions(){return this.dispatch}getTypedDispatch(){return this.dispatch}getTypedWatchers(){return this.watchers}findActionByType(e){return Object.values(this.dispatch).find(t=>t.actionType.split(`[${this.storage.name}]`)[1]===e)}findWatcherByType(e){return Object.values(this.watchers).find(t=>t.actionType===e)}createAction(e,t){let s=`[${this.storage.name}]${e.type}`,r=null,n=null,o=async i=>{let c=[i];if(t?.memoize&&r&&n&&t.memoize(c,r,n))return n;let d={type:s,meta:e.meta},u;if(this.middlewareFunctions.length>0){let p=async l=>t?.worker?this.executeInWorker(t.worker,s,c,e.action):Promise.resolve(e.action(i));for(let l=this.middlewareFunctions.length-1;l>=0;l--){let g=this.middlewareFunctions[l],h=p;p=async S=>g(async m=>h(m))(S)}u=await p(d)}else t?.worker?u=await this.executeInWorker(t.worker,s,c,e.action):u=await e.action(i);return d.payload=u,r=[...c],n=u,this.actions$.next(d),u};return o.r="dispatch",Object.defineProperty(o,"actionType",{value:s,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(o,"meta",{value:e.meta,writable:!1,enumerable:!0}),o}createWatcher(e){let t=`[${this.storage.name}]${e.type}`,s=new U,r,n=async()=>{let c=await this.storage.getState();return e.selector(c)},o=this.storage.subscribe(e.selector,c=>{if(!e.shouldTrigger||e.shouldTrigger(r,c)){let d={type:t,payload:c,meta:e.meta};this.actions$.next(d),s.next(d),r=c}}),i=()=>{let c=s.asObservable();return e.notifyAfterSubscribe?new G(d=>{let u=!1;n().then(l=>{if(!e.shouldTrigger||e.shouldTrigger(void 0,l)){let g={type:t,payload:l,meta:{...e.meta,isInitial:!0}};d.next(g),r=l,u=!0}}).catch(l=>{d.error(l)});let p=c.subscribe({next:l=>{u&&l.payload===r||d.next(l)},error:l=>d.error(l),complete:()=>d.complete()});return()=>{p.unsubscribe()}}):c};return i.r="watchers",Object.defineProperty(i,"actionType",{value:t,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(i,"meta",{value:e.meta,writable:!1,enumerable:!0}),Object.defineProperty(i,"unsubscribe",{value:o,writable:!1,enumerable:!0}),i}async executeInWorker(e,t,s,r){return new Promise((n,o)=>{let i=`${t}_${Date.now()}_${Math.random()}`,c=d=>{d.data.requestId===i&&(e.removeEventListener("message",c),d.data.error?o(new Error(d.data.error)):n(d.data.result))};e.addEventListener("message",c),e.postMessage({type:t,args:s,requestId:i}),setTimeout(()=>{e.removeEventListener("message",c),o(new Error(`Worker execution timeout for action: ${t}`))},3e4)})}};function k(a,e){let t=new $(a),s=e(a.storage,{createAction:(r,n)=>t.createAction(r,n),createWatcher:r=>t.createWatcher(r)});for(let[r,n]of Object.entries(s))if(typeof n=="function"){let o=n.r;t[o][r]=n}return t}import{combineLatest as Jt,merge as Qt,Observable as W,of as H,pipe as Zt,Subject as Y}from"rxjs";import{catchError as J,filter as tr,map as rr,share as Q,switchMap as sr,take as nr}from"rxjs/operators";import{of as Dt}from"rxjs";import{concatAll as Ct,delay as Mt,mergeMap as Ot,toArray as Bt}from"rxjs/operators";import{forkJoin as Kt,timer as jt}from"rxjs";import{mergeMap as kt}from"rxjs/operators";var O=class{constructor(e,t={},s,r={},n={}){this.storage=e;this.externalStates=t;this.dispatchers=s;this.services=r;this.config=n;this.subscribeToDispatchers(),this.state$=new W(o=>{this.storage.getState().then(c=>o.next(c));let i=this.storage.subscribeToAll(()=>{this.storage.getState().then(c=>o.next(c))});return()=>i()}).pipe(Q())}effects=[];subscriptions=[];running=!1;action$=new Y;state$;subscribeToDispatchers(){for(let[e,t]of Object.entries(this.dispatchers)){let s=t.actions.subscribe(r=>{this.action$.next(r)});this.subscriptions.push(s)}}add(e){return this.effects.push(e),this.running&&this.subscribeToEffect(e),this}addEffects(e){return e.forEach(t=>this.add(t)),this}async start(){return this.running?this:(await this.storage.waitForReady(),this.effects.forEach(e=>this.subscribeToEffect(e)),this.running=!0,this)}stop(){return this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.running=!1,this}subscribeToEffect(e){try{let s=e(this.action$.asObservable(),this.state$,this.externalStates,this.dispatchers,this.services,this.config).pipe(J(r=>H(null))).subscribe(r=>{if(r!=null&&typeof r=="function")try{r()}catch{}});this.subscriptions.push(s)}catch{}}};function X(a){if(!a.storage&&!a.createStorageFn)throw new Error('Synapse config must have either "storage" or "createStorageFn"');if(a.storage&&a.createStorageFn)throw new Error('Synapse config cannot have both "storage" and "createStorageFn". Choose one.');if(a.effects&&!a.createDispatcherFn)throw new Error('Effects require dispatcher. Add "createDispatcherFn" to config.');if(a.createEffectConfig&&!a.createDispatcherFn)throw new Error('Effect config requires dispatcher. Add "createDispatcherFn" to config.');if(a.dependencies){if(!Array.isArray(a.dependencies))throw new Error("Dependencies must be an array");a.dependencies.forEach((e,t)=>{if(!e||typeof e!="object")throw new Error(`Dependency at index ${t} must be an object`);if(!e.storage||typeof e.storage.waitForReady!="function")throw new Error(`Dependency at index ${t} must have a storage with waitForReady method`)})}if(a.createStorageFn&&typeof a.createStorageFn!="function")throw new Error('"createStorageFn" must be a function');if(a.createDispatcherFn&&typeof a.createDispatcherFn!="function")throw new Error('"createDispatcherFn" must be a function');if(a.createSelectorsFn&&typeof a.createSelectorsFn!="function")throw new Error('"createSelectorsFn" must be a function');if(a.createEffectConfig&&typeof a.createEffectConfig!="function")throw new Error('"createEffectConfig" must be a function');if(a.effects){if(!Array.isArray(a.effects))throw new Error("Effects must be an array");a.effects.forEach((e,t)=>{if(typeof e!="function")throw new Error(`Effect at index ${t} must be a function`)})}if(a.externalSelectors&&typeof a.externalSelectors!="object")throw new Error("External selectors must be an object")}async function Z(a=[]){a.length!==0&&await Promise.all(a.map(async(e,t)=>{try{await e.storage.waitForReady()}catch(s){throw new Error(`Dependency ${t} initialization failed: ${s}`)}}))}async function F(a){try{X(a)}catch(i){throw i}await Z(a.dependencies);let e=a.createStorageFn?await a.createStorageFn():a.storage;await e.waitForReady();let t=[],s={storage:e,selectors:{},destroy:async()=>{for(let i of t)await i()}};t.push(()=>e.destroy());let r,n,o;if(a.createSelectorsFn)try{n=new C(e);let i=a.externalSelectors||{};s.selectors=a.createSelectorsFn(n,i),typeof n.destroy=="function"&&t.push(()=>n.destroy())}catch{}if(a.createDispatcherFn&&(r=a.createDispatcherFn(e),s.dispatcher=r,r&&"dispatch"in r&&(s.actions=r.dispatch,typeof r.destroy=="function"&&t.push(()=>r.destroy()))),a.createEffectConfig&&r)try{let{dispatchers:i,api:c,config:d,externalStates:u}=a.createEffectConfig(r),p=u||{};o=new O(e,p,i,c,d),Array.isArray(a.effects)&&a.effects.forEach(l=>{o&&o.add(l)}),await o.start(),s.state$=o.state$,t.push(()=>{o&&o.stop()})}catch{}return s}function ee(a,e){return e==="*"?!0:e.includes("*")?new RegExp("^"+e.replace(/\*/g,".*")+"$").test(a):a===e}async function te(a,e){let t=await a.getState(),s=Object.entries(t.events||{});if(s.length>e){let n=s.sort((o,i)=>i[1].timestamp-o[1].timestamp).slice(0,e);await a.set("events",Object.fromEntries(n))}}var re=(a={})=>F({createStorageFn:async()=>new D({name:a.name||"eventBus",initialState:{events:{},subscriptions:{}}}).initialize(),createDispatcherFn:e=>k({storage:e},(t,{createAction:s})=>({publish:s({type:"PUBLISH_EVENT",meta:{description:"\u041F\u0443\u0431\u043B\u0438\u043A\u0430\u0446\u0438\u044F \u0441\u043E\u0431\u044B\u0442\u0438\u044F \u0432 EventBus"},action:async({event:r,data:n,metadata:o={}})=>{let i=`${r}_${Date.now()}_${Math.random()}`;return await t.set(`events.${i}`,{id:i,event:r,data:n,metadata:{ttl:o.ttl||null,priority:o.priority||"normal",...o},timestamp:Date.now()}),a.autoCleanup&&await te(t,a.maxEvents||1e3),{eventId:i,event:r,data:n}}}),subscribe:s({type:"SUBSCRIBE_TO_EVENT",meta:{description:"\u041F\u043E\u0434\u043F\u0438\u0441\u043A\u0430 \u043D\u0430 \u0441\u043E\u0431\u044B\u0442\u0438\u044F \u0432 EventBus"},action:async({eventPattern:r,handler:n,options:o={}})=>{let i=`sub_${Date.now()}_${Math.random()}`,c=t.subscribe(d=>d.events,d=>{Object.values(d||{}).forEach(u=>{if(ee(u.event,r)){if(o.priority&&u.metadata.priority!==o.priority)return;try{n(u.data,u)}catch{}}})});return await t.set(`subscriptions.${i}`,{id:i,pattern:r,options:o,createdAt:Date.now()}),{subscriptionId:i,unsubscribe:c}}}),getEventHistory:s({type:"GET_EVENT_HISTORY",meta:{description:"\u041F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435 \u0438\u0441\u0442\u043E\u0440\u0438\u0438 \u0441\u043E\u0431\u044B\u0442\u0438\u0439"},action:async({eventType:r,limit:n=100})=>{let o=await t.getState();return Object.values(o.events||{}).filter(i=>i.event===r).sort((i,c)=>c.timestamp-i.timestamp).slice(0,n)}}),clearEvents:s({type:"CLEAR_EVENTS",meta:{description:"\u041E\u0447\u0438\u0441\u0442\u043A\u0430 \u0441\u043E\u0431\u044B\u0442\u0438\u0439"},action:async({olderThan:r}={})=>{if(r){let n=Date.now()-r;await t.update(o=>{Object.keys(o.events||{}).forEach(i=>{o.events[i].timestamp<n&&delete o.events[i]})})}else await t.set("events",{})}}),getActiveSubscriptions:s({type:"GET_SUBSCRIPTIONS",meta:{description:"\u041F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435 \u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0445 \u043F\u043E\u0434\u043F\u0438\u0441\u043E\u043A"},action:async()=>{let r=await t.getState();return Object.values(r.subscriptions||{})}})}))});export{re as createEventBus,F as createSynapse};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "synapse-storage",
3
- "version": "3.0.11",
3
+ "version": "3.0.13",
4
4
  "description": "Набор инструментов для управления состоянием и апи-запросами",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -19,7 +19,8 @@
19
19
  "rxjs",
20
20
  "reactive",
21
21
  "indexeddb",
22
- "localstorage"
22
+ "localstorage",
23
+ "esm-only"
23
24
  ],
24
25
  "author": "Vlad Firsov",
25
26
  "homepage": "https://github.com/Vlad92msk/synapse#readme",
@@ -50,64 +51,28 @@
50
51
  },
51
52
  "exports": {
52
53
  ".": {
53
- "import": {
54
- "types": "./dist/index.d.ts",
55
- "default": "./dist/index.js"
56
- },
57
- "require": {
58
- "types": "./dist/index.d.ts",
59
- "default": "./dist/index.cjs"
60
- }
54
+ "types": "./dist/index.d.ts",
55
+ "import": "./dist/index.js"
61
56
  },
62
57
  "./core": {
63
- "import": {
64
- "types": "./dist/core.d.ts",
65
- "default": "./dist/core.js"
66
- },
67
- "require": {
68
- "types": "./dist/core.d.ts",
69
- "default": "./dist/core.cjs"
70
- }
58
+ "types": "./dist/core.d.ts",
59
+ "import": "./dist/core.js"
71
60
  },
72
61
  "./reactive": {
73
- "import": {
74
- "types": "./dist/reactive.d.ts",
75
- "default": "./dist/reactive.js"
76
- },
77
- "require": {
78
- "types": "./dist/reactive.d.ts",
79
- "default": "./dist/reactive.cjs"
80
- }
62
+ "types": "./dist/reactive.d.ts",
63
+ "import": "./dist/reactive.js"
81
64
  },
82
65
  "./api": {
83
- "import": {
84
- "types": "./dist/api.d.ts",
85
- "default": "./dist/api.js"
86
- },
87
- "require": {
88
- "types": "./dist/api.d.ts",
89
- "default": "./dist/api.cjs"
90
- }
66
+ "types": "./dist/api.d.ts",
67
+ "import": "./dist/api.js"
91
68
  },
92
69
  "./react": {
93
- "import": {
94
- "types": "./dist/react.d.ts",
95
- "default": "./dist/react.js"
96
- },
97
- "require": {
98
- "types": "./dist/react.d.ts",
99
- "default": "./dist/react.cjs"
100
- }
70
+ "types": "./dist/react.d.ts",
71
+ "import": "./dist/react.js"
101
72
  },
102
73
  "./utils": {
103
- "import": {
104
- "types": "./dist/utils.d.ts",
105
- "default": "./dist/utils.js"
106
- },
107
- "require": {
108
- "types": "./dist/utils.d.ts",
109
- "default": "./dist/utils.cjs"
110
- }
74
+ "types": "./dist/utils.d.ts",
75
+ "import": "./dist/utils.js"
111
76
  }
112
77
  },
113
78
  "peerDependencies": {
package/dist/api.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";var H=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var _=(r,e)=>{for(var t in e)H(r,t,{get:e[t],enumerable:!0})},V=(r,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of z(e))!N.call(r,n)&&n!==t&&H(r,n,{get:()=>e[n],enumerable:!(a=J(e,n))||a.enumerable});return r};var W=r=>V(H({},"__esModule",{value:!0}),r);var Y={};_(Y,{ApiClient:()=>K,ResponseFormat:()=>T,apiLogger:()=>k,createUniqueId:()=>O,headersToObject:()=>I});module.exports=W(Y);var k={debug:(r,...e)=>{process.env.NODE_ENV!=="production"&&console.debug(`[API] ${r}`,...e)},log:(r,...e)=>{process.env.NODE_ENV!=="production"&&console.log(`[API] ${r}`,...e)},info:(r,...e)=>{console.info(`[API] ${r}`,...e)},warn:(r,...e)=>{console.warn(`[API] ${r}`,...e)},error:(r,...e)=>{console.error(`[API] ${r}`,...e)}};function O(r){return`${r?`${r}|`:""}${Math.random().toString(36).substring(2,9)+Date.now().toString(36)}`}function I(r){let e={};return r.forEach((t,a)=>{e[a.toLowerCase()]=t}),e}function q(r={},e={}){return{...r,...e,getFromStorage:r.getFromStorage||(t=>{try{let a=localStorage.getItem(t);return a?JSON.parse(a):void 0}catch(a){console.warn(`[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0447\u0442\u0435\u043D\u0438\u044F \u0438\u0437 localStorage: ${a}`);return}}),getCookie:r.getCookie||(t=>{try{let a=document.cookie.match(new RegExp(`(?:^|; )${t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")}=([^;]*)`));return a?decodeURIComponent(a[1]):void 0}catch(a){console.warn(`[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0447\u0442\u0435\u043D\u0438\u044F cookie: ${a}`);return}})}}async function Q(r,e){let t=new Headers,a=e||q({},{});if(r)try{t=await Promise.resolve(r(t,a))}catch(n){console.warn("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043F\u043E\u0434\u0433\u043E\u0442\u043E\u0432\u043A\u0435 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432",n)}return t}function B(r,e){return async(t,a)=>{let n=new Headers(t);if(r)try{n=await Promise.resolve(r(n,a))}catch(i){console.warn("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043F\u043E\u0434\u0433\u043E\u0442\u043E\u0432\u043A\u0435 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u044B\u0445 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432",i)}if(e)try{n=await Promise.resolve(e(n,a))}catch(i){console.warn("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043F\u043E\u0434\u0433\u043E\u0442\u043E\u0432\u043A\u0435 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432 \u044D\u043D\u0434\u043F\u043E\u0438\u043D\u0442\u0430",i)}return n}}var T=(s=>(s.Json="json",s.Blob="blob",s.ArrayBuffer="arrayBuffer",s.Text="text",s.FormData="formData",s.Raw="raw",s))(T||{});function M(r){let e=r.toLowerCase().split(";")[0].trim();if(e.includes("application/json"))return"json";if(e.includes("text/"))return"text";if(e.includes("multipart/form-data"))return"formData";if(e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"))return"blob"}function D(r){let e=r.get("content-type")||"",t=r.get("content-disposition")||"",a=e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"),n=t.includes("attachment")||t.includes("filename=");return a||n}function G(r){let e=r.get("content-disposition");if(!e)return;let t=e.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);if(t&&t[1])return t[1].replace(/['"]/g,"").trim()}function $(r){let e=r.get("content-type")||"",t=r.get("content-disposition")||"",a=r.get("content-length");return D(r)?{filename:G(r),contentType:e,contentDisposition:t,size:a?parseInt(a,10):void 0}:void 0}async function X(r,e){let t=e,a=r.headers.get("content-type")||"";!t&&a&&(D(r.headers)?t="blob":t=M(a)),t||(t="json");try{let n;switch((t==="blob"||t==="arrayBuffer")&&(n=$(r.headers)),t){case"json":try{let s=await r.json();return r.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}catch{let l=await r.text();return r.ok?{data:l,fileMetadata:n}:{error:l,fileMetadata:n}}case"text":{let s=await r.text();return r.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case"blob":{let s=await r.blob();return r.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case"arrayBuffer":{let s=await r.arrayBuffer();return r.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case"formData":{let s=await r.formData();return r.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case"raw":return r.ok?{data:r,fileMetadata:n}:{error:r,fileMetadata:n};default:let i=await r.blob();return r.ok?{data:i,fileMetadata:n}:{error:i,fileMetadata:n}}}catch(n){return console.error(`[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u044F \u0434\u0430\u043D\u043D\u044B\u0445 \u0438\u0437 \u043E\u0442\u0432\u0435\u0442\u0430 (\u0444\u043E\u0440\u043C\u0430\u0442: ${t})`,n),r.ok?{data:void 0}:{error:n}}}function U(r){let{baseUrl:e,timeout:t=3e4,fetchFn:a=fetch,credentials:n="same-origin"}=r;return async(i,s={},l)=>{let{path:h,method:C,body:o,query:u,responseFormat:f}=i,{signal:b,timeout:R=t,responseFormat:p}=s,A=p||f,m=new URL(h.startsWith("http")?h:`${e}${h}`);u&&Object.entries(u).forEach(([d,c])=>{c!=null&&(Array.isArray(c)?c.forEach(w=>m.searchParams.append(d,String(w))):m.searchParams.append(d,String(c)))});let E;if(o!==void 0)if(o instanceof FormData||o instanceof Blob)E=o;else if(typeof o=="object"&&o!==null)try{E=JSON.stringify(o),l.has("Content-Type")||l.set("Content-Type","application/json")}catch(d){console.error("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u0435\u0440\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0442\u0435\u043B\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430",d),E=String(o)}else E=String(o);let P,g=new Promise((d,c)=>{R&&(P=window.setTimeout(()=>{c(new Error(`\u041F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u0437\u0430\u043F\u0440\u043E\u0441\u0430 (${R}\u043C\u0441)`))},R))});try{let d=a(m.toString(),{method:C,headers:l,body:E,signal:b,credentials:n}),c=await Promise.race([d,g]),{data:w,error:F,fileMetadata:L}=await X(c,A);return{data:w,error:F,ok:c.ok,status:c.status,statusText:c.statusText,headers:c.headers,fileDownloadResult:L}}catch(d){let c=d;return console.error("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F \u0437\u0430\u043F\u0440\u043E\u0441\u0430",c),{error:c,ok:!1,status:0,statusText:c.message,headers:new Headers}}finally{P&&window.clearTimeout(P)}}}function j(r,e=[]){let t={};return!r||e.length===0||e.forEach(a=>{r.has(a)&&(t[a]=r.get(a)||"")}),t}var v=class{constructor(e,t,a,n,i,s){this.name=e;this.queryStorage=t;this.configCurrentEndpoint=a;this.cacheableHeaderKeys=n;this.globalCacheConfig=i;this.baseQueryConfig=s;this.prepareHeaders=B(s.prepareHeaders,a.prepareHeaders),this.queryFunction=U({baseUrl:s.baseUrl,fetchFn:s.fetchFn,timeout:s.timeout,credentials:s.credentials}),this.cacheableHeaders=[...n||[],...a.includeCacheableHeaderKeys||[]].filter(l=>!a.excludeCacheableHeaderKeys?.includes(l)),this.meta.name=e,this.meta.tags=a.tags??this.meta.tags,this.meta.invalidatesTags=a.invalidatesTags??this.meta.invalidatesTags,this.meta.cache=this.queryStorage.createCacheConfig(this.configCurrentEndpoint)??this.meta.cache}endpointSubscribers=new Set;fetchCounts=0;meta={cache:!1,invalidatesTags:[],name:"",tags:[]};queryFunction;cacheableHeaders;prepareHeaders;request(e,t){this.fetchCounts++;let a=O(this.name),n=new AbortController,i=new Set,s={status:"idle",requestParams:e,headers:{},error:void 0,data:void 0,fromCache:!1},l=q({requestParams:e},t?.context||{}),h=o=>{Object.assign(s,o),i.forEach(u=>{u({...s})})},C=new Promise(async(o,u)=>{try{let f=await Q(this.prepareHeaders,l),b=j(f,t?.cacheableHeaderKeys?t.cacheableHeaderKeys:this.cacheableHeaders),R=this.queryStorage.shouldCache(this.configCurrentEndpoint,t),[p,A]=this.queryStorage.createCacheKey(this.name,{...e,...b}),m;if(R&&(m=await this.queryStorage.getCachedResult(p)),m)h({fromCache:!0,status:"success",data:m.data,error:void 0,headers:m.headers,requestParams:e}),o({...m,fromCache:!0});else{h({fromCache:!1,status:"loading"});let E=this.configCurrentEndpoint.request(e,t?.context),P={...t,signal:n.signal},g=await this.queryFunction(E,P,f);if(g.ok){let{headers:d,...c}=g;if(R){let w=this.queryStorage.createCacheConfig(this.configCurrentEndpoint);await this.queryStorage.setCachedResult(p,{...c,headers:I(d)},w,A??{},this.configCurrentEndpoint.tags??[],this.configCurrentEndpoint.invalidatesTags??[])}h({fromCache:!1,status:"success",data:g.data,error:void 0,headers:g.headers,requestParams:e}),this.endpointSubscribers.forEach(w=>{let F={status:"success",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};w(F)}),o({...g,fromCache:!1})}else h({fromCache:!1,status:"error",data:void 0,error:g.error,headers:g.headers,requestParams:e}),this.endpointSubscribers.forEach(d=>{let c={status:"error",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:g.error};d(c)}),u(g.error)}}catch(f){h({fromCache:!1,status:"error",data:void 0,error:f,headers:void 0,requestParams:e}),u(f)}});return{id:a,subscribe(o,u={}){let{autoUnsubscribe:f=!0}=u;i.add(o),o(s);let b=()=>i.delete(o);return f&&C.finally(()=>{b()}),b},wait:()=>C,waitWithCallbacks(o={}){let{idle:u,loading:f,success:b,error:R}=o;return this.subscribe(p=>{switch(p.status){case"idle":u?.(p);break;case"loading":f?.(p);break;case"success":b?.(p.data,p);break;case"error":R?.(p.error,p);break}},{autoUnsubscribe:!0}),C},abort:()=>{n&&!n.signal.aborted&&n.abort()},then:(o,u)=>C.then(o,u),catch:o=>C.catch(o),finally:o=>C.finally(o)}}subscribe(e){this.endpointSubscribers.add(e);let t={status:"idle",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};return e(t),()=>this.endpointSubscribers.delete(e)}reset(){return this.fetchCounts=0,Promise.resolve()}destroy(){this.endpointSubscribers.clear()}};var x=class{constructor(e,t=!1){this.value=e;this.isRawKey=t}toString(){return this.value}toJSON(){return this.value}valueOf(){return this.value}isUnparseable(){return this.isRawKey}};var y=class{static createMetadata(e=0,t=[]){let a=Date.now(),n=e>0?a+e:1/0;return{createdAt:a,updatedAt:a,expiresAt:n,tags:t,createdAtDateTime:this.formatDateTime(a),updatedAtDateTime:this.formatDateTime(a),expiresAtDateTime:n===1/0?"never":this.formatDateTime(n)}}static formatDateTime(e){return new Date(e).toISOString()}static isExpired(e){return Date.now()>e.expiresAt}static updateMetadata(e){return{...e,updatedAt:Date.now()}}static createKey(...e){return new x(e.join("_"))}static createApiKey(e,t){if(!t)return[new x(e,!0),t];let a=Object.entries(t).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>`${n}=${i}`).join("&");return[new x(`${e}_${a}`,!0),t]}static hasAnyTag(e,t=[]){return!e.tags||!t.length?!1:t.some(a=>e.tags?.includes(a))}};var S=class{constructor(e,t){this.storageExternal=e;this.globalCacheConfig=t}storage=null;cleanupInterval=null;defaultCacheOptions={ttl:5*60*1e3,cleanup:{enabled:!0,interval:10*60*1e3},invalidateOnError:!0};async initialize(){return await this.createStorage(),this.startCleanupInterval(),this}async createStorage(){try{let e=this.storageExternal;await e.initialize(),this.storage=e}catch(e){throw console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430",e),e}}startCleanupInterval(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);let e=typeof this.globalCacheConfig=="object"?this.globalCacheConfig.cleanup:this.defaultCacheOptions.cleanup;e?.enabled&&e.interval&&(this.cleanupInterval=setInterval(()=>{this.cleanup().catch(t=>console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0447\u0438\u0441\u0442\u043A\u0435 \u043A\u044D\u0448\u0430:",t))},e.interval))}getStorage(){return this.storage}createCacheKey(e,t){return y.createApiKey(e,t)}async getCachedResult(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let t=await this.storage.get(e);if(!t)return;if(y.isExpired(t.metadata)){await this.storage.delete(e);return}let a={...t,metadata:y.updateMetadata(t.metadata)};return await this.storage.set(e,a),t.data}async setCachedResult(e,t,a,n,i,s){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");s?.length&&await this.invalidateCacheByTags(s);let l=y.createMetadata(a.ttl,i),h={data:t,metadata:l,params:n};await this.storage.set(e,h)}shouldCache(e,t){return!(this.globalCacheConfig===!1||e?.cache===!1||typeof e?.cache=="object"&&e?.cache.ttl===0||t?.disableCache===!0||this.globalCacheConfig===void 0&&e?.cache===void 0)}createCacheConfig(e){let t=this.defaultCacheOptions;if(typeof this.globalCacheConfig=="object"&&(t=this.globalCacheConfig),typeof e?.cache=="object"){let a=e.cache;t={...t,...a}}return t}async invalidateCacheByTags(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let t=await this.storage.keys();for(let a of t){let n=await this.storage.get(a);n&&y.hasAnyTag(n.metadata,e)&&await this.storage.delete(a)}}async invalidateCache(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");await this.storage.delete(e)}async cleanup(){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let e=await this.storage.keys();for(let t of e){let a=await this.storage.get(t);a&&y.isExpired(a.metadata)&&await this.storage.delete(t)}}async destroy(){this.cleanupInterval&&(window.clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.storage&&(await this.storage.destroy(),this.storage=null)}};var K=class{queryStorage;cacheableHeaderKeys;globalCacheConfig;baseQueryConfig;storageExternal;createEndpoints;endpoints={};constructor(e){this.cacheableHeaderKeys=e.cacheableHeaderKeys,this.globalCacheConfig=e.cache,this.baseQueryConfig=e.baseQuery,this.storageExternal=e.storage,this.createEndpoints=e.endpoints}async init(){return this.queryStorage=await new S(this.storageExternal,this.globalCacheConfig).initialize(),await this.initializeEndpoints(),this}async initializeEndpoints(){let e=a=>a,t=await this.createEndpoints(e)||{};for(let[a,n]of Object.entries(t)){let i=a;this.endpoints[i]=new v(a,this.queryStorage,n,this.cacheableHeaderKeys,this.globalCacheConfig,this.baseQueryConfig)}}getEndpoints(){return this.endpoints}async request(e,t,a){let i=this.getEndpoints()[e];if(!i)throw new Error(`\u042D\u043D\u0434\u043F\u043E\u0438\u043D\u0442 ${String(e)} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`);try{return await i.request(t,a).wait()}catch(s){throw k.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043A ${String(e)}`,{error:s,params:t}),s}}async destroy(){await Promise.all(Object.values(this.endpoints).map(async e=>(e.destroy(),Promise.resolve()))),this.endpoints={},await this.queryStorage.destroy()}};0&&(module.exports={ApiClient,ResponseFormat,apiLogger,createUniqueId,headersToObject});
package/dist/core.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";var $=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var W=(c,e)=>{for(var t in e)$(c,t,{get:e[t],enumerable:!0})},Q=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Y(e))!J.call(c,s)&&s!==t&&$(c,s,{get:()=>e[s],enumerable:!(r=H(e,s))||r.enumerable});return c};var X=c=>Q($({},"__esModule",{value:!0}),c);var te={};W(te,{IndexedDBStorage:()=>C,LocalStorage:()=>N,MemoryStorage:()=>B,SelectorModule:()=>V,StorageEvents:()=>D,StoragePluginModule:()=>U,broadcastMiddleware:()=>_});module.exports=X(te);var m=!1,I=new Map;function z(c){let e=0;if(c.length===0)return e.toString(36);for(let t=0;t<c.length;t++){let r=c.charCodeAt(t);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function P(c,e){if(c===e)return!0;if(c==null||e==null)return!1;if(typeof c!="object"&&typeof c!="function"&&typeof e!="object"&&typeof e!="function")return c===e;if(typeof c!=typeof e)return!1;if(c instanceof Date&&e instanceof Date)return c.getTime()===e.getTime();if(Array.isArray(c)&&Array.isArray(e)){if(c.length!==e.length)return!1;for(let t=0;t<c.length;t++)if(!P(c[t],e[t]))return!1;return!0}if(typeof c=="object"&&typeof e=="object"){let t=Object.keys(c),r=Object.keys(e);return t.length!==r.length?!1:t.every(s=>Object.prototype.hasOwnProperty.call(e,s)?P(c[s],e[s]):!1)}return!1}function q(c,e=P){let t,r,s=!1;return function(o){if(!s||t!==o){let a=c(o);(!s||!e(a,r))&&(r=a),t=o,s=!0}return r}}var M=class{constructor(e,t,r=P,s){this.name=e;this.equals=r;this.logger=s;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t),m&&console.log(`[${this.id}] \u0421\u043E\u0437\u0434\u0430\u043D new SelectorSubscription`)}id;subscribers=new Set;lastValue;memoizedGetState;createMemoizedGetState(e){let t=null,r=!1;return async()=>{if(r&&t)return t;r=!0;try{return t=e(),await t}finally{r=!1}}}async notify(){try{let e=await this.memoizedGetState();if(this.lastValue===void 0||!this.equals(e,this.lastValue)){m&&console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C, notify()`,{old:this.lastValue,new:e}),this.lastValue=e;let t=Array.from(this.subscribers).map(async r=>{try{await r.notify(e)}catch(s){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430`,{error:s})}});await Promise.all(t)}else m&&console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043D\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C in notify(), \u043F\u0440\u043E\u043F\u0443\u0441\u043A \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F`)}catch(e){throw this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 notify()`,{error:e}),e}}subscribe(e){return m&&console.log(`[${this.id}] \u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E \u043D\u043E\u0432\u044B\u0439 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A, \u0432\u0441\u0435\u0433\u043E: ${this.subscribers.size+1}`),this.subscribers.add(e),this.lastValue!==void 0?Promise.resolve().then(()=>{try{e.notify(this.lastValue)}catch(t){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}}):this.notify().catch(t=>{this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}),()=>{m&&console.log(`[${this.id}] \u041F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A \u0443\u0434\u0430\u043B\u0435\u043D, \u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C: ${this.subscribers.size-1}`),this.subscribers.delete(e)}}cleanup(){m&&console.log(`[${this.id}] \u041E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0438, \u0431\u044B\u043B\u043E ${this.subscribers.size} \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u043E\u0432`),this.subscribers.clear(),this.lastValue=void 0}getId(){return this.id}},V=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,m&&console.log(`\u0421\u043E\u0437\u0434\u0430\u043D SelectorModule \u0434\u043B\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${this.storageName}`),this.source.getState().then(r=>{this.cachedState=r,m&&console.log(`\u041A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0434\u043B\u044F ${this.storageName}`)})}storageName;subscriptions=new Map;cachedState;localSelectorCache=new Map;batchUpdateInProgress=!1;pendingUpdates=new Set;generateName(e,t,r){let s=e?"simple":"combined",i="";if(e){let o=t.toString();i=z(o)}else{let o=t.map(n=>n.getId()).join("_"),a=r.toString();i=z(o+a)}return`${this.storageName}_${s}_${i}`}processPendingUpdates(){this.pendingUpdates.size===0||this.batchUpdateInProgress||(this.batchUpdateInProgress=!0,setTimeout(async()=>{try{let e=Array.from(this.pendingUpdates);this.pendingUpdates.clear(),this.cachedState=await this.source.getState();let t=e.map(async r=>{let s=this.subscriptions.get(r);if(s)try{return await s.notify()}catch(i){this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430 ${r}`,{error:i})}return Promise.resolve()});await Promise.all(t)}catch(e){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0439",{error:e})}finally{this.batchUpdateInProgress=!1,this.pendingUpdates.size>0&&this.processPendingUpdates()}},0))}createSelector(e,t,r){let s=!Array.isArray(e),i=s?t||{}:r||{},o=i.name||this.generateName(s,e,s?void 0:t);if(this.localSelectorCache.has(o))return m&&console.log(`[${this.storageName}] Reusing cached selector: ${o}`),this.localSelectorCache.get(o).api;if(I.has(o)){let u=I.get(o);return u.refCount++,m&&console.log(`[${this.storageName}] \u041F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0433\u043E \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440\u0430: ${o}, refCount: ${u.refCount}`),u.api}let a,n,l=[];if(s){let u=q(e,i.equals||P),g=this.createSimpleSelector(u,{...i,name:o,equals:i.equals||P});a=g.api,l=g.unsubscribeFunctions}else{n=e;let u=this.createCombinedSelector(n,t,{...i,name:o,equals:i.equals||P});a=u.api,l=u.unsubscribeFunctions}return this.localSelectorCache.set(o,{api:a,dependencies:n,unsubscribeFunctions:l}),I.set(o,{api:a,refCount:1,unsubscribeFunctions:l}),m&&console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043D\u043E\u0432\u044B\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${o}`),a}createSimpleSelector(e,t){m&&console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043F\u0440\u043E\u0441\u0442\u043E\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${t.name}`);let r=async()=>{if(this.cachedState)return e(this.cachedState);let n=await this.source.getState();return this.cachedState=n,e(n)},s=new M(t.name,r,t.equals||P,this.logger),i=s.getId();this.subscriptions.set(i,s);let a=[this.source.subscribeToAll(async n=>{n?.type==="storage:update"&&(m&&console.log(`[${i}] \u041F\u043E\u043B\u0443\u0447\u0435\u043D\u043E \u0441\u043E\u0431\u044B\u0442\u0438\u0435 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430`),this.pendingUpdates.add(i),this.processPendingUpdates())})];return{api:{select:()=>r(),subscribe:n=>s.subscribe(n),getId:()=>i},unsubscribeFunctions:a}}createCombinedSelector(e,t,r){let s=q(g=>t(...g),r.equals||P),i=async()=>{let g=await Promise.all(e.map(d=>d.select()));return s(g)},o=new M(r.name,i,r.equals||P,this.logger),a=o.getId();this.subscriptions.set(a,o);let n=null,l=()=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,o.notify().catch(g=>this.logger?.error(`[${a}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438:`,{error:g}))},10)},u=e.map(g=>g.subscribe({notify:()=>{l()}}));return{api:{select:()=>i(),subscribe:g=>o.subscribe(g),getId:()=>a},unsubscribeFunctions:u}}destroy(){m&&console.log(`[${this.storageName}] \u041D\u0430\u0447\u0430\u043B\u043E\u0441\u044C \u0443\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D\u0438\u0435 SelectorModule`),this.subscriptions.forEach(t=>t.cleanup()),this.subscriptions.clear(),this.cachedState=void 0,this.pendingUpdates.clear(),this.localSelectorCache.forEach(t=>{t.unsubscribeFunctions.forEach(r=>r())});let e=new Set;this.localSelectorCache.forEach((t,r)=>{e.add(r)}),this.localSelectorCache.clear(),e.forEach(t=>{let r=I.get(t);r&&(r.refCount--,r.refCount<=0&&(r.unsubscribeFunctions.forEach(s=>s()),I.delete(t),m&&console.log(`[${this.storageName}] \u0423\u0434\u0430\u043B\u0435\u043D \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440 \u0438\u0437 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0430: ${t}`)))}),m&&console.log(`[${this.storageName}] \u0423\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D`)}};var U=class{constructor(e,t,r="default"){this.parentExecutor=e;this.logger=t;this.storageName=r}plugins=new Map;createContext(e){return{storageName:this.storageName,timestamp:Date.now(),metadata:e}}async add(e){if(this.plugins.has(e.name)){this.logger?.warn(`\u041F\u043B\u0430\u0433\u0438\u043D ${e.name} \u0443\u0436\u0435 \u0431\u044B\u043B \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D`);return}try{await e.initialize?.(),this.plugins.set(e.name,e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D",{name:e.name})}catch(t){throw t}}async remove(e){let t=this.plugins.get(e);t&&(await t.destroy?.(),this.plugins.delete(e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0443\u0434\u0430\u043B\u0435\u043D",{name:e}))}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}async initialize(){for(let e of this.plugins.values())await e.initialize?.()}async destroy(){await Promise.all(Array.from(this.plugins.values()).map(e=>e.destroy?.()??Promise.resolve())),this.plugins.clear()}async executeBeforeSet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeSet(r,s));for(let i of this.plugins.values())if(i.onBeforeSet)try{r=await i.onBeforeSet(r,s)}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeSet`,{error:o}),o}return r}async executeAfterSet(e,t,r){let s=t,i=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterSet(e,s,i));for(let o of this.plugins.values())if(o.onAfterSet)try{s=await o.onAfterSet(e,s,i)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onAfterSet`,{key:e,error:a}),a}return s}async executeBeforeGet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeGet(r,s));for(let i of this.plugins.values())if(i.onBeforeGet)try{r=await i.onBeforeGet(r,s)}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeGet`,{key:e,error:o}),o}return r}async executeAfterGet(e,t,r){let s=t,i=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterGet(e,s,i)),console.log("executeAfterGet",e,t,r);for(let o of this.plugins.values())if(o.onAfterGet)try{s=await o.onAfterGet(e,s,i)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onAfterGet`,{key:e,error:a}),a}return s}async executeBeforeDelete(e,t){let r=!0,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeDelete(e,s));for(let i of this.plugins.values())if(i.onBeforeDelete)try{r=await i.onBeforeDelete(e,s)&&r}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeDelete`,{key:e,error:o}),o}return r}async executeAfterDelete(e,t){let r=this.createContext(t);this.parentExecutor&&await this.parentExecutor.executeAfterDelete(e,r);for(let s of this.plugins.values())if(s.onAfterDelete)try{await s.onAfterDelete(e,r)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${s.name} onAfterDelete`,{key:e,error:i}),i}}async executeOnClear(e){let t=this.createContext(e);this.parentExecutor&&await this.parentExecutor.executeOnClear(t);for(let r of this.plugins.values())if(r.onClear)try{await r.onClear(t)}catch(s){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${r.name} onClear`,{error:s}),s}}};var D=(o=>(o.STORAGE_UPDATE="storage:update",o.STORAGE_DELETE="storage:delete",o.STORAGE_PATCH="storage:patch",o.STORAGE_SELECT="storage:select",o.STORAGE_CLEAR="storage:clear",o.STORAGE_DESTROY="storage:destroy",o))(D||{});var R=class{channel;tabId;messageHandlers;syncHandler;debug;syncTimeoutMs=1e3;pendingSyncRequests;constructor(e,t={}){this.channel=new BroadcastChannel(e),this.tabId=crypto.randomUUID(),this.messageHandlers=new Set,this.debug=t.debug??!1,this.pendingSyncRequests=new Map,this.channel.onmessage=this.handleMessage.bind(this),this.channel.onmessageerror=this.handleError.bind(this)}log(...e){this.debug&&console.log(`[SyncBroadcastChannel][${this.tabId}]`,...e)}error(...e){console.error(`[SyncBroadcastChannel][${this.tabId}]`,...e)}async handleMessage(e){let t=e.data;if(t.senderId!==this.tabId){if(t.type==="SYNC_REQUEST"){if(this.syncHandler)try{let r=await this.syncHandler();this.postMessage("SYNC_RESPONSE",r,t.senderId)}catch(r){this.error("Error handling sync request:",r)}return}if(t.type==="SYNC_RESPONSE"){let r=this.pendingSyncRequests.get(this.tabId);r&&(clearTimeout(r.timeout),this.pendingSyncRequests.delete(this.tabId),r.resolve(t.payload));return}for(let r of this.messageHandlers)try{await r(t)}catch(s){this.error("Error in message handler:",s)}}}handleError(e){this.error("Channel error:",e)}postMessage(e,t,r){let s={type:e,payload:t,senderId:this.tabId,timestamp:Date.now()};this.channel.postMessage(s)}subscribe(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}setSyncHandler(e){this.syncHandler=e}broadcast(e,t){this.postMessage(e,t)}async requestSync(){return new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingSyncRequests.delete(this.tabId),e(null)},this.syncTimeoutMs);this.pendingSyncRequests.set(this.tabId,{resolve:e,reject:t,timeout:r}),this.postMessage("SYNC_REQUEST",{type:"sync"})})}close(){for(let[,e]of this.pendingSyncRequests)clearTimeout(e.timeout),e.reject(new Error("Channel closed"));this.pendingSyncRequests.clear(),this.messageHandlers.clear(),this.syncHandler=void 0,this.channel.close()}};async function Z(c,e,t){switch(e){case"set":t?.key!==void 0&&t?.value!==void 0&&(await c.storage.doSet(t.key,t.value),c.storage.notifySubscribers(t.key,t.value));break;case"update":Array.isArray(t?.value)&&(await c.storage.doUpdate(t.value),t.value.forEach(({key:r,value:s})=>{c.storage.notifySubscribers(r,s)}));break;case"delete":t?.key!==void 0&&(await c.storage.doDelete(t.key),c.storage.notifySubscribers(t.key,void 0));break;case"clear":await c.storage.doClear(),c.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}c.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:t?.value,source:"broadcast"})}async function ee(c,e,t){switch(e){case"set":if(t?.key!==void 0){let r=await c.storage.doGet(t.key);c.storage.notifySubscribers(t.key,r)}break;case"update":if(Array.isArray(t?.value)){for(let{key:r}of t.value){let s=await c.storage.doGet(r);c.storage.notifySubscribers(r,s)}c.storage.notifySubscribers("*",{type:"storage:update",key:t.value.map(({key:r})=>r),value:t.value,source:"broadcast"})}break;case"delete":t?.key!==void 0&&c.storage.notifySubscribers(t.key,void 0);break;case"clear":c.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}e!=="update"&&c.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:e==="delete"?void 0:t?.value,source:"broadcast"})}var _=c=>{let{storageName:e,storageType:t}=c,r=`${t}-${e}`,s=new R(r,{debug:!0});return{name:"broadcast",setup:i=>(t==="memory"&&(s.setSyncHandler(async()=>{let o=await i.getState();return{type:"update",key:"*",value:Object.entries(o).map(([l,u])=>({key:l,value:u})),metadata:{batchUpdate:!0,timestamp:Date.now()}}}),s.requestSync().then(async o=>{if(o?.type==="update"&&Array.isArray(o.value))try{if(!o.value.every(n=>n&&typeof n=="object"&&"key"in n&&"value"in n)){console.error("[Sync Response] Invalid updates structure:",o.value);return}await i.storage.doUpdate(o.value),o.value.forEach(({key:n,value:l})=>{i.storage.notifySubscribers(n,l)}),i.storage.notifySubscribers("*",{type:"storage:update",value:o.value,source:"broadcast"})}catch(a){console.error("[Sync Response] Error applying updates:",a)}})),s.subscribe(async o=>{let{type:a,payload:n}=o;t==="memory"?await Z(i,a,n):await ee(i,a,n)})),reducer:i=>o=>async a=>{let n=await o(a);return["set","delete","clear","update"].includes(a.type)&&s.broadcast(a.type,a),n},cleanup:()=>{s.close()}}};var f=class{constructor(e,t=!1){this.value=e;this.isRawKey=t}toString(){return this.value}toJSON(){return this.value}valueOf(){return this.value}isUnparseable(){return this.isRawKey}};var L=(c={})=>{let e=c.batchSize??10,t=c.batchDelay??10,r=new Map,s=new Map,i=d=>d.type==="set"||d.type==="update",o=d=>`${d.type}_${d.key?.toString()||"default"}`,a=d=>{let h=new Map;for(let p of d){let S=`${p.type}_${p.key?.toString()||"default"}`;h.set(S,p)}return Array.from(h.values())},n=d=>{let h=s.get(d);h&&(globalThis.clearTimeout(h),s.delete(d))},l=(d,h)=>{let p=globalThis.setTimeout(h,t);s.set(d,p)},u=async(d,h,p)=>{let S=r.get(d);if(!(!S||S.length===0)){r.delete(d),n(d);try{let x=S.map(y=>y.action),b=a(x);console.log(`\u{1F504} Batching ${d}: ${S.length} actions -> ${b.length} merged`,{original:x.map(y=>({type:y.type,key:y.key?.toString(),value:y.value})),merged:b.map(y=>({type:y.type,key:y.key?.toString(),value:y.value}))});for(let y of b)try{let K=await p(y);S.filter(T=>T.action.type===y.type&&T.action.key?.toString()===y.key?.toString()).forEach(T=>T.resolve(K))}catch(K){S.filter(T=>T.action.type===y.type&&T.action.key?.toString()===y.key?.toString()).forEach(T=>T.reject(K))}}catch(x){S.forEach(b=>b.reject(x))}}},g=async(d,h,p)=>new Promise((S,x)=>{let b=o(d),y=r.get(b);y||(y=[],r.set(b,y)),y.push({action:d,resolve:S,reject:x,timestamp:Date.now()}),n(b),y.length>=e?setImmediate(()=>u(b,h,p)):l(b,()=>u(b,h,p))});return{name:"batching",setup:()=>{},cleanup:async()=>{s.forEach(d=>globalThis.clearTimeout(d)),s.clear(),r.clear()},reducer:d=>h=>async p=>i(p)?g(p,d,h):h(p)}};var F=(c={})=>{let{comparator:e=(s,i)=>{if(s===i)return!0;if(typeof s!="object"||typeof i!="object"||s===null||i===null)return s===i;let o=Object.keys(s),a=Object.keys(i);return o.length!==a.length?!1:o.every(n=>Object.prototype.hasOwnProperty.call(i,n)&&s[n]===i[n])},segments:t=[]}=c,r=new Map;return{name:"shallow-compare",setup:s=>{},reducer:s=>i=>async o=>{if(o.type!=="set"||t.length&&!t.includes(o.metadata?.segment??"default"))return i(o);let a=o.key,n=r.get(a),l=o.value;if(n!==void 0&&e(n,l))return console.log("ShallowCompare: \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0438\u0434\u0435\u043D\u0442\u0438\u0447\u043D\u044B, \u043F\u0440\u043E\u043F\u0443\u0441\u043A\u0430\u0435\u043C \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u044E",{key:a,value:l}),{...n,__metadata:{valueNotChanged:!0,originalValue:n}};let u=await i(o);return r.set(a,l),u}}};var O=class{middlewares=[];api;initialized=!1;dispatchFn;constructor(e){this.api={dispatch:async t=>this.dispatch(t),getState:()=>e.getState(),storage:{doGet:e.doGet.bind(e),doSet:e.doSet.bind(e),doUpdate:e.doUpdate.bind(e),doDelete:e.doDelete.bind(e),doClear:e.doClear.bind(e),doKeys:e.doKeys.bind(e),notifySubscribers:e.notifySubscribers.bind(e)}}}async baseOperation(e){let{processed:t,...r}=e.metadata||{},s={...e,metadata:r};switch(s.type){case"get":return this.api.storage.doGet(s.key);case"set":return await this.api.storage.doSet(s.key,s.value),this.api.storage.doGet(s.key);case"update":return Array.isArray(s.value)?(await this.api.storage.doUpdate(s.value),this.api.storage.doGet("")):s.value;case"delete":return this.api.storage.doDelete(s.key);case"clear":return this.api.storage.doClear();case"init":{let i=await this.api.storage.doGet("");return Object.keys(i||{}).length>0?i:s.value?(await this.api.storage.doSet("",s.value),this.api.storage.doGet("")):i}case"keys":return this.api.storage.doKeys();default:throw new Error(`Unknown action type: ${s.type}`)}}initializeMiddlewares(){if(this.initialized)return;let e=this.baseOperation.bind(this);for(let t of[...this.middlewares].reverse()){let r=e;e=async s=>{if(s.metadata?.processed)return r(s);let i={...s,metadata:{...s.metadata,processed:!0,timestamp:s.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(r)(i)}}this.dispatchFn=e,this.initialized=!0}use(e){e.setup&&e.setup(this.api),this.middlewares.push(e),this.initialized=!1}async dispatch(e){this.initialized||this.initializeMiddlewares();try{return this.dispatchFn(e)}catch(t){throw console.error("Error in middleware chain:",t),t}}};function w(c){return c instanceof f&&c.isUnparseable()?[c.toString()]:c.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function v(c,e){return w(e).reduce((r,s)=>r===void 0?void 0:r[s],c)}function E(c,e,t){if(e==="")return t;let r=w(e);if(e instanceof f&&e.isUnparseable())return c[e.toString()]=t,c;let s=r.pop(),i=r.reduce((o,a)=>{let n=r[r.indexOf(a)+1],l=!Number.isNaN(Number(n));return a in o||(o[a]=l?[]:{}),o[a]},c);return i[s]=t,c}var A=class c{constructor(e,t,r,s){this.config=e;this.pluginExecutor=t;this.eventEmitter=r;this.logger=s;this.name=e.name,this.middlewareModule=new O({getState:this.getState.bind(this),doGet:this.doGet.bind(this),doSet:this.doSet.bind(this),doUpdate:this.doUpdate.bind(this),doDelete:this.doDelete.bind(this),doClear:this.doClear.bind(this),doKeys:this.doKeys.bind(this),notifySubscribers:this.notifySubscribers.bind(this),pluginExecutor:this.pluginExecutor,eventEmitter:this.eventEmitter,logger:this.logger}),this.initializeMiddlewares()}static GLOBAL_SUBSCRIPTION_KEY="*";name;selectorPathCache=new WeakMap;middlewareModule;initializedMiddlewares=null;subscribers=new Map;initializeMiddlewares(){this.config.middlewares&&!this.initializedMiddlewares&&(this.initializedMiddlewares=this.config.middlewares(()=>this.getDefaultMiddleware()),this.initializedMiddlewares.forEach(e=>this.middlewareModule.use(e)))}getDefaultMiddleware(){return{batching:(e={})=>L(e),shallowCompare:(e={})=>F(e)}}async initializeWithMiddlewares(){try{let e=await this.getState();!(Object.keys(e).length>0)&&this.config.initialState&&await this.middlewareModule.dispatch({type:"init",value:this.config.initialState})}catch(e){throw this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430",{error:e}),e}}async get(e){try{let t={operation:"get",timestamp:Date.now(),key:e},r=await this.middlewareModule.dispatch({type:"get",key:e,metadata:t}),s=await this.pluginExecutor?.executeAfterGet(e,r,t)??r;return await this.emitEvent({type:"storage:select",payload:{key:e,value:s}}),s}catch(t){throw this.logger?.error("Error getting value",{key:e,error:t}),t}}async set(e,t){try{let r={operation:"set",timestamp:Date.now(),key:e},s=await this.pluginExecutor?.executeBeforeSet(t,r)??t,i=await this.middlewareModule.dispatch({type:"set",key:e,value:s,metadata:r}),o=i?.__metadata?.valueNotChanged===!0,a;if(o&&i?.__metadata?.originalValue!==void 0?a=i.__metadata.originalValue:a=await this.pluginExecutor?.executeAfterSet(e,i,r)??i,!o){let l=[e.toString()];this.notifySubscribers(e,a),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:a,changedPaths:l}),await this.emitEvent({type:"storage:update",payload:{key:e,value:a,changedPaths:l}})}}catch(r){throw this.logger?.error("Error setting value",{key:e,error:r}),r}}async update(e){try{let t={operation:"update",timestamp:Date.now()},r=await this.getState(),s=structuredClone(r);e(s);let i=this.findChangedPaths(r,s);if(i.size===0){this.logger?.debug&&this.logger.debug("No changes detected in update");return}this.logger?.debug&&this.logger.debug("Changed paths:",{paths:Array.from(i)});let o=new Set;for(let d of i){let h=d.split(".")[0];o.add(h)}let a=await Promise.all(Array.from(o).map(async d=>{let h={...t,key:d},p=await this.pluginExecutor?.executeBeforeSet(s[d],h)??s[d];return{key:d,value:p}})),n=await this.middlewareModule.dispatch({type:"update",value:a,metadata:{...t,batchUpdate:!0,changedPaths:Array.from(i)}}),l={};Array.isArray(n)?n.forEach(d=>{d&&typeof d=="object"&&"key"in d&&"value"in d&&(l[d.key]=d.value)}):n&&typeof n=="object"&&(l={...n});let u=Object.keys(l).filter(d=>!this.isEqual(r[d],l[d]));if(u.length===0){this.logger?.debug&&this.logger.debug("No actual changes after middleware processing");return}let g={};u.forEach(d=>{g[d]=l[d]}),this.logger?.debug&&this.logger.debug("Notifying subscribers about changes:",{keys:u}),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:u,value:g,changedPaths:Array.from(i)});for(let d of i)try{let h=d.split(".")[0];if(h in g){let p;if(d===h)p=g[h];else{let S=d.substring(h.length+1);p=v(g[h],S)}p!==void 0&&this.notifySubscribers(d,p)}}catch(h){this.logger?.error("Error notifying path subscribers",{path:d,error:h})}await this.emitEvent({type:"storage:update",payload:{state:g,key:u,changedPaths:Array.from(i)}})}catch(t){throw this.logger?.error("Error updating state",{error:t}),t}}async delete(e){try{let t={operation:"delete",timestamp:Date.now(),key:e};if(await this.pluginExecutor?.executeBeforeDelete(e,t)){let r=await this.middlewareModule.dispatch({type:"delete",key:e,metadata:t});await this.pluginExecutor?.executeAfterDelete(e,t);let i=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:r,changedPaths:i}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:r,changedPaths:i}})}}catch(t){throw this.logger?.error("Error deleting value",{key:e,error:t}),t}}async clear(){try{this.pluginExecutor?.executeOnClear(),await this.middlewareModule.dispatch({type:"clear"})}catch(e){throw this.logger?.error("Error clearing storage",{error:e}),e}}async keys(){try{return await this.middlewareModule.dispatch({type:"keys"})}catch(e){throw this.logger?.error("Error getting keys",{error:e}),e}}async has(e){try{return await this.doHas(e)}catch(t){throw this.logger?.error("Error checking value existence",{key:e,error:t}),t}}async getState(){try{return await this.doGet("")||{}}catch(e){throw this.logger?.error("Error getting state",{error:e}),e}}subscribeToAll(e){return this.subscribers.has(c.GLOBAL_SUBSCRIPTION_KEY)||this.subscribers.set(c.GLOBAL_SUBSCRIPTION_KEY,new Set),this.subscribers.get(c.GLOBAL_SUBSCRIPTION_KEY).add(e),()=>{let t=this.subscribers.get(c.GLOBAL_SUBSCRIPTION_KEY);t&&(t.delete(e),t.size===0&&this.subscribers.delete(c.GLOBAL_SUBSCRIPTION_KEY))}}subscribe(e,t){return typeof e=="string"?this.subscribeByKey(e,t):this.subscribeBySelector(e,t)}async destroy(){try{await this.clear(),await this.doDestroy(),this.initializedMiddlewares&&(await Promise.all(this.initializedMiddlewares.map(async e=>{"cleanup"in e&&await e.cleanup?.()})),this.initializedMiddlewares=null),await this.emitEvent({type:"storage:destroy"})}catch(e){throw this.logger?.error("Error destroying storage",{error:e}),e}}subscribeByKey(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=!1;return this.subscribers.get(e).add(t),this.get(e).then(s=>{try{r||(r=!0,t(s))}catch(i){this.logger?.error("Error in initial callback",{key:e,error:i})}}),()=>{let s=this.subscribers.get(e);s&&(s.delete(t),s.size===0&&this.subscribers.delete(e))}}createDummyState(){let e={get:(t,r)=>(t[r]=t[r]||new Proxy({},e),t[r])};return new Proxy({},e)}isEqual(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;let r=typeof e;if(r!==typeof t)return!1;if(r!=="object")return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++)if(!this.isEqual(e[a],t[a]))return!1;return!0}let i=Object.keys(e),o=Object.keys(t);return i.length!==o.length?!1:i.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&this.isEqual(e[a],t[a]))}extractPath(e,t){if(this.selectorPathCache.has(e))return this.selectorPathCache.get(e);let r=[],s=(i="")=>({get:(o,a)=>{if(typeof a=="symbol")return Reflect.get(o,a);let n=i?`${i}.${a}`:a;return r.push(n),new Proxy({},s(n))},has:(o,a)=>!0,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0}),apply:(o,a,n)=>new Proxy(()=>{},s(i))});try{e(new Proxy(t,s()))}catch{}return r.length===0?"":(r.sort((i,o)=>o.length-i.length),this.selectorPathCache.set(e,r[0]),r[0])}notifySubscribers(e,t){let r=e.toString(),s=this.subscribers.get(r);s?.size&&new Set(s).forEach(o=>{try{o(t)}catch(a){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0435 \u043D\u0430 \u043A\u043E\u043B\u0431\u044D\u043A",{key:r,error:a})}})}findChangedPaths(e,t,r="",s=new Set,i=new WeakMap){if(e===t)return s;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e!==t&&s.add(r||""),s;if(i.has(e))return s;i.set(e,!0);let o=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let a of o){let n=e[a],l=t[a];if(n===l)continue;let u=r?`${r}.${a}`:a;n&&l&&typeof n=="object"&&typeof l=="object"&&!Array.isArray(n)&&!Array.isArray(l)?this.findChangedPaths(n,l,u,s,i):Array.isArray(n)&&Array.isArray(l)?this.isEqual(n,l)||s.add(u):this.isEqual(n,l)||s.add(u)}return s}subscribeBySelector(e,t){let r=this.createDummyState(),s=this.extractPath(e,r);this.logger?.debug&&this.logger.debug("Subscribing to path:",{path:s});let i=async o=>{try{if(o==null){let l=await this.getState(),u=e(l);t(u);return}if(typeof o!="object"||o===null){t(o);return}let a=await this.getState(),n=e(a);t(n)}catch(a){this.logger?.error("Error in selector callback",{path:s,error:a}),t(o)}};return s?this.subscribeByKey(s,i):this.subscribeToAll(()=>{this.getState().then(o=>{t(e(o))})})}async emitEvent(e){try{await this.eventEmitter?.emit({...e,metadata:{...e.metadata||{},timestamp:Date.now(),storageName:this.name}})}catch(t){this.logger?.error("Error emitting event",{event:e,error:t})}}};var G=class c{constructor(e,t,r){this.dbName=e;this.logger=r;this.dbVersion=t}static instances=new Map;db=null;initPromise=null;storeNames=new Set;dbVersion;static getInstance(e,t=1,r){c.instances.has(e)||c.instances.set(e,new c(e,t,r));let s=c.instances.get(e);return t>s.dbVersion&&(s.dbVersion=t),s}async initialize(){return this.db?this.db:(this.initPromise||(this.initPromise=this.openDatabase()),this.initPromise)}async ensureStoreExists(e){if(await this.initialize(),this.db.objectStoreNames.contains(e))return this.storeNames.add(e),this.db;this.logger?.debug(`Store "${e}" not found, upgrading database`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase([e]);let t=await this.initPromise;return this.storeNames.add(e),t}async openDatabase(e=[]){return new Promise((t,r)=>{this.logger?.debug(`Opening database "${this.dbName}" with version ${this.dbVersion}`);let s=indexedDB.open(this.dbName,this.dbVersion);s.onerror=()=>{this.logger?.error(`Failed to open database "${this.dbName}"`,{error:s.error}),r(s.error)},s.onsuccess=()=>{this.db=s.result;for(let i=0;i<this.db.objectStoreNames.length;i++)this.storeNames.add(this.db.objectStoreNames[i]);this.logger?.debug(`Database "${this.dbName}" opened successfully`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),t(this.db)},s.onupgradeneeded=i=>{let o=i.target.result;this.logger?.debug(`Upgrading database "${this.dbName}" to version ${this.dbVersion}`);for(let a of e)o.objectStoreNames.contains(a)||(this.logger?.debug(`Creating store "${a}"`),o.createObjectStore(a))}})}closeDatabase(){this.db&&(this.db.close(),this.db=null,this.initPromise=null)}async deleteDatabase(){return this.closeDatabase(),new Promise((e,t)=>{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{this.logger?.debug(`Database "${this.dbName}" deleted successfully`),c.instances.delete(this.dbName),this.storeNames.clear(),e()},r.onerror=()=>{this.logger?.error(`Failed to delete database "${this.dbName}"`,{error:r.error}),t(r.error)}})}async ensureStoresExist(e){await this.initialize();let t=e.filter(r=>!this.db.objectStoreNames.contains(r));return t.length===0?this.db:(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u043D\u0435\u0434\u043E\u0441\u0442\u0430\u044E\u0449\u0438\u0445 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449: ${t.join(", ")}`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase(t),this.initPromise)}getCurrentVersion(){return this.dbVersion}},j=class{constructor(e,t=1,r){this.dbName=e;this.logger=r;this.version=t}db=null;version;getCurrentVersion(){return this.version}openDatabase(e,t=[]){return new Promise((r,s)=>{this.logger?.debug(`\u041E\u0442\u043A\u0440\u044B\u0442\u0438\u0435 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0441 \u0432\u0435\u0440\u0441\u0438\u0435\u0439 ${e}`);let i=indexedDB.open(this.dbName,e);i.onerror=()=>{this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u0438\u0438 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}"`,{error:i.error}),s(i.error)},i.onsuccess=()=>{this.db=i.result,this.version=this.db.version,this.logger?.debug(`\u0411\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0442\u043A\u0440\u044B\u0442\u0430`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),r(this.db)},i.onupgradeneeded=o=>{let a=o.target.result;this.logger?.debug(`\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0434\u043E \u0432\u0435\u0440\u0441\u0438\u0438 ${e}`);for(let n of t)a.objectStoreNames.contains(n)||(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 "${n}"`),a.createObjectStore(n))}})}async ensureStoresExist(e){this.db||(this.db=await this.openDatabase(this.version));let t=e.filter(r=>!this.db.objectStoreNames.contains(r));return t.length===0?this.db:(this.logger?.debug(`\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0441\u043E\u0437\u0434\u0430\u0442\u044C \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${t.join(", ")}`,{dbName:this.dbName,currentVersion:this.version}),this.db.close(),this.db=null,this.version++,this.db=await this.openDatabase(this.version,t),this.db)}close(){this.db&&(this.db.close(),this.db=null)}},C=class c extends A{DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,r,s){super(e,t,r,s);let i=e.options;this.DB_NAME=i.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=i.dbVersion||1,this.dbManager=G.getInstance(this.DB_NAME,this.DB_VERSION,s)}async initialize(){try{this.logger?.debug(`Initializing IndexedDB storage "${this.STORE_NAME}"`),await this.dbManager.ensureStoreExists(this.STORE_NAME);try{if(!(await this.dbManager.initialize()).objectStoreNames.contains(this.STORE_NAME))throw new Error(`Store "${this.STORE_NAME}" not found after initialization`)}catch(e){throw this.logger?.error(`Error verifying store "${this.STORE_NAME}" exists:`,{error:e}),e}this.initializeMiddlewares();try{await this.initializeWithMiddlewares(),this.logger?.debug(`IndexedDB storage "${this.STORE_NAME}" initialized successfully`)}catch(e){this.logger?.error(`Failed to initialize middleware for store "${this.STORE_NAME}"`,{error:e})}return this}catch(e){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 IndexedDB "${this.name}"`,{error:e}),e}}static async getCurrentDBVersion(e){return new Promise(t=>{try{let r=indexedDB.open(e);r.onsuccess=()=>{let s=r.result.version;r.result.close(),t(s)},r.onerror=()=>{console.warn(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0438 \u0432\u0435\u0440\u0441\u0438\u0438 \u0411\u0414 ${e}`,r.error),t(0)}}catch(r){console.warn(`\u0418\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u043F\u0440\u0438 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0438 \u0432\u0435\u0440\u0441\u0438\u0438 \u0411\u0414 ${e}`,r),t(0)}})}static async createStorages(e,t,r){let i=await this.getCurrentDBVersion(e)||1,o=new j(e,i,r),a=Object.values(t).map(l=>l.name);await o.ensureStoresExist(a);let n={};for(let[l,u]of Object.entries(t)){let g=new c({...u,options:{dbName:e,dbVersion:o.getCurrentVersion()}},u.pluginExecutor,u.eventEmitter,r);n[l]=await g.initialize()}return n}async getTransaction(e="readonly"){try{let t=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!t.objectStoreNames.contains(this.STORE_NAME)){this.logger?.warn(`Object store "${this.STORE_NAME}" not found, attempting to repair`),t.close(),this.dbManager.closeDatabase();let r=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!r.objectStoreNames.contains(this.STORE_NAME))throw new Error(`Object store "${this.STORE_NAME}" still doesn't exist after repair attempt`);return r.transaction(this.STORE_NAME,e)}return t.transaction(this.STORE_NAME,e)}catch(t){throw this.logger?.error(`Failed to create transaction for store "${this.STORE_NAME}"`,{error:t}),t}}async getObjectStore(e="readonly"){return(await this.getTransaction(e)).objectStore(this.STORE_NAME)}async doGet(e){let t=await this.getObjectStore();if(e==="")return new Promise((s,i)=>{let o=t.getAll();o.onerror=()=>i(o.error),o.onsuccess=()=>{let a=o.result,n=t.getAllKeys();n.onsuccess=()=>{let l=n.result.reduce((u,g,d)=>(g!=="root"&&(u[g]=a[d]),u),{});s(l)},n.onerror=()=>i(n.error)}});if(e instanceof f&&e.isUnparseable())return new Promise((s,i)=>{let o=t.get(e.valueOf());o.onerror=()=>i(o.error),o.onsuccess=()=>s(o.result)});let r=w(e);if(r.length>1){let s=r[0];return new Promise((i,o)=>{let a=t.get(s);a.onerror=()=>o(a.error),a.onsuccess=()=>{let n=a.result;if(!n){i(void 0);return}let l=v(n,r.slice(1).join("."));i(l)}})}return new Promise((s,i)=>{let o=t.get(r[0]);o.onerror=()=>i(o.error),o.onsuccess=()=>s(o.result)})}async doSet(e,t){if(e===""){let i=await this.getObjectStore("readwrite");return new Promise((o,a)=>{let n=i.transaction;n.oncomplete=()=>{o()},n.onerror=()=>{a(n.error)};let l=i.clear();l.onsuccess=()=>{let u=Object.entries(t);for(let[g,d]of u)i.put(d,g)},l.onerror=()=>{a(l.error)}})}let r=await this.getObjectStore("readwrite");if(e instanceof f&&e.isUnparseable()){await this.putValueInStore(r,e.valueOf(),t);return}let s=w(e);if(s.length>1){let i=s[0];return new Promise((o,a)=>{let n=r.get(i);n.onerror=()=>a(n.error),n.onsuccess=()=>{let l=n.result||{},u=E(l,s.slice(1).join("."),t),g=r.put(u,i);g.onerror=()=>a(g.error),g.onsuccess=()=>o()}})}await this.putValueInStore(r,s[0],t)}async putValueInStore(e,t,r){return new Promise((s,i)=>{let o=e.put(r,t.valueOf());o.onerror=()=>i(o.error),o.onsuccess=()=>s()})}async doUpdate(e){let t=new Map,r=[];for(let{key:s,value:i}of e){if(s instanceof f&&s.isUnparseable()){r.push({key:s.valueOf(),value:i});continue}let o=w(s),a=o[0],n=o.slice(1);t.has(a)||t.set(a,[]),t.get(a).push({path:n,value:i})}try{for(let{key:s,value:i}of r){let o=await this.getObjectStore("readwrite");await this.putValueInStore(o,s,i)}for(let[s,i]of t){let a={...await this.doGet(s)||{}};for(let{path:l,value:u}of i)l.length===0?a=u:a=E(a,l.join("."),u);let n=await this.getObjectStore("readwrite");await this.putValueInStore(n,s,a)}}catch(s){throw this.logger?.error("Error during update:",{error:s}),s}}async doDelete(e){let t=await this.getObjectStore("readwrite");if(e instanceof f&&e.isUnparseable())return new Promise((i,o)=>{let a=t.delete(e.valueOf());a.onerror=()=>o(a.error),a.onsuccess=()=>i(!0)});let r=w(e);if(r.length===1)return new Promise((i,o)=>{let a=t.delete(r[0]);a.onerror=()=>o(a.error),a.onsuccess=()=>i(!0)});let s=r[0];return new Promise((i,o)=>{let a=t.get(s);a.onerror=()=>o(a.error),a.onsuccess=()=>{let n=a.result;if(!n){i(!1);return}let l=v(n,r.slice(0,-1).join(".")),u=r[r.length-1];if(!l||!(u in l)){i(!1);return}if(Array.isArray(l)){let d=parseInt(u,10);isNaN(d)?delete l[u]:l.splice(d,1)}else delete l[u];let g=t.put(n,s);g.onerror=()=>o(g.error),g.onsuccess=()=>i(!0)}})}async doClear(){let e=await this.getObjectStore("readwrite");return new Promise((t,r)=>{let s=e.clear();s.onsuccess=()=>t(),s.onerror=()=>r(s.error)})}async doKeys(){let t=(await this.getObjectStore()).getAllKeys();return new Promise((r,s)=>{t.onsuccess=()=>{r(t.result)},t.onerror=()=>s(t.error)})}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){try{await this.doClear()}catch(e){throw this.logger?.error(`Error destroying store "${this.STORE_NAME}"`,{error:e}),e}}};var N=class extends A{constructor(e,t,r,s){super(e,t,r,s)}async initialize(){try{return await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing LocalStorage",{error:e}),e}}async doGet(e){let t=localStorage.getItem(this.name);if(!t)return;let r=JSON.parse(t);return e instanceof f&&e.isUnparseable()?r[e.valueOf()]:v(r,e)}async doSet(e,t){let r=localStorage.getItem(this.name),s=r?JSON.parse(r):{};if(e instanceof f&&e.isUnparseable()){s[e.valueOf()]=t,localStorage.setItem(this.name,JSON.stringify(s));return}let i=E({...s},e,t);localStorage.setItem(this.name,JSON.stringify(i))}async doDelete(e){let t=localStorage.getItem(this.name);if(!t)return!1;let r=JSON.parse(t);if(e instanceof f&&e.isUnparseable()){let n=e.valueOf();return n in r?(delete r[n],localStorage.setItem(this.name,JSON.stringify(r)),!0):!1}let s=w(e),i=s.slice(0,-1).join("."),o=s[s.length-1],a=i?v(r,i):r;return!a||!(o in a)?!1:(delete a[o],localStorage.setItem(this.name,JSON.stringify(r)),!0)}async doUpdate(e){let t=localStorage.getItem(this.name),r=t?JSON.parse(t):{};for(let{key:s,value:i}of e)s instanceof f&&s.isUnparseable()?r[s.valueOf()]=i:E(r,s,i);localStorage.setItem(this.name,JSON.stringify(r))}async doClear(){localStorage.removeItem(this.name)}async doKeys(){let e=localStorage.getItem(this.name);if(!e)return[];let t=JSON.parse(e);return this.getAllKeys(t)}async doHas(e){return await this.doGet(e)!==void 0}getAllKeys(e){return Object.keys(e)}async doDestroy(){await this.doClear()}};var B=class extends A{storage=new Map;constructor(e,t,r,s){super(e,t,r,s)}async initialize(){try{return this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing MemoryStorage",{error:e}),e}}async doGet(e){let t=this.storage.get(this.name);if(t)return e instanceof f&&e.isUnparseable()?t[e.valueOf()]:v(t,e)}async doSet(e,t){let r=this.storage.get(this.name)||{};if(e instanceof f&&e.isUnparseable()){r[e.valueOf()]=t,this.storage.set(this.name,r);return}let s=E({...r},e,t);this.storage.set(this.name,s)}async doDelete(e){let t=this.storage.get(this.name);if(!t)return!1;if(e instanceof f&&e.isUnparseable()){let a=e.valueOf();return a in t?(delete t[a],this.storage.set(this.name,t),!0):!1}let r=w(e),s=r.slice(0,-1).join("."),i=r[r.length-1],o=s?v(t,s):t;return!o||!(i in o)?!1:(delete o[i],this.storage.set(this.name,t),!0)}async doUpdate(e){let r={...this.storage.get(this.name)||{}};for(let{key:s,value:i}of e)s instanceof f&&s.isUnparseable()?r[s.valueOf()]=i:E(r,s,i);this.storage.set(this.name,r)}async doClear(){this.storage.delete(this.name)}async doKeys(){let e=this.storage.get(this.name);return e?this.getAllKeys(e):[]}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){this.storage.delete(this.name)}getAllKeys(e){return Object.keys(e)}};0&&(module.exports={IndexedDBStorage,LocalStorage,MemoryStorage,SelectorModule,StorageEvents,StoragePluginModule,broadcastMiddleware});
package/dist/index.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";var oe=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var Ne=(o,e)=>{for(var t in e)oe(o,t,{get:e[t],enumerable:!0})},ke=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $e(e))!qe.call(o,r)&&r!==t&&oe(o,r,{get:()=>e[r],enumerable:!(s=Ke(e,r))||s.enumerable});return o};var Ue=o=>ke(oe({},"__esModule",{value:!0}),o);var ot={};Ne(ot,{ApiClient:()=>ue,Dispatcher:()=>ne,EffectsModule:()=>H,IndexedDBStorage:()=>X,LocalStorage:()=>Z,MemoryStorage:()=>ee,ResponseFormat:()=>N,SelectorModule:()=>U,StorageEvents:()=>Q,StoragePluginModule:()=>pe,apiLogger:()=>ie,broadcastMiddleware:()=>ge,combineEffects:()=>at,createDispatcher:()=>Qe,createEffect:()=>nt,createEffectBase:()=>st,createSynapse:()=>Be,createSynapseCtx:()=>Ge,createUniqueId:()=>ce,headersToObject:()=>le,loggerDispatcherMiddleware:()=>Je,ofType:()=>Ye,ofTypes:()=>Xe,ofTypesWaitAll:()=>Ze,selectorMap:()=>et,selectorObject:()=>tt,useSelector:()=>ze,useStorageSubscribe:()=>Le,validateMap:()=>rt});module.exports=Ue(ot);var ie={debug:(o,...e)=>{process.env.NODE_ENV!=="production"&&console.debug(`[API] ${o}`,...e)},log:(o,...e)=>{process.env.NODE_ENV!=="production"&&console.log(`[API] ${o}`,...e)},info:(o,...e)=>{console.info(`[API] ${o}`,...e)},warn:(o,...e)=>{console.warn(`[API] ${o}`,...e)},error:(o,...e)=>{console.error(`[API] ${o}`,...e)}};function ce(o){return`${o?`${o}|`:""}${Math.random().toString(36).substring(2,9)+Date.now().toString(36)}`}function le(o){let e={};return o.forEach((t,s)=>{e[s.toLowerCase()]=t}),e}function z(o={},e={}){return{...o,...e,getFromStorage:o.getFromStorage||(t=>{try{let s=localStorage.getItem(t);return s?JSON.parse(s):void 0}catch(s){console.warn(`[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0447\u0442\u0435\u043D\u0438\u044F \u0438\u0437 localStorage: ${s}`);return}}),getCookie:o.getCookie||(t=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){console.warn(`[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0447\u0442\u0435\u043D\u0438\u044F cookie: ${s}`);return}})}}async function be(o,e){let t=new Headers,s=e||z({},{});if(o)try{t=await Promise.resolve(o(t,s))}catch(r){console.warn("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043F\u043E\u0434\u0433\u043E\u0442\u043E\u0432\u043A\u0435 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432",r)}return t}function we(o,e){return async(t,s)=>{let r=new Headers(t);if(o)try{r=await Promise.resolve(o(r,s))}catch(a){console.warn("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043F\u043E\u0434\u0433\u043E\u0442\u043E\u0432\u043A\u0435 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u044B\u0445 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432",a)}if(e)try{r=await Promise.resolve(e(r,s))}catch(a){console.warn("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043F\u043E\u0434\u0433\u043E\u0442\u043E\u0432\u043A\u0435 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432 \u044D\u043D\u0434\u043F\u043E\u0438\u043D\u0442\u0430",a)}return r}}var N=(n=>(n.Json="json",n.Blob="blob",n.ArrayBuffer="arrayBuffer",n.Text="text",n.FormData="formData",n.Raw="raw",n))(N||{});function xe(o){let e=o.toLowerCase().split(";")[0].trim();if(e.includes("application/json"))return"json";if(e.includes("text/"))return"text";if(e.includes("multipart/form-data"))return"formData";if(e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"))return"blob"}function de(o){let e=o.get("content-type")||"",t=o.get("content-disposition")||"",s=e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"),r=t.includes("attachment")||t.includes("filename=");return s||r}function Ve(o){let e=o.get("content-disposition");if(!e)return;let t=e.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);if(t&&t[1])return t[1].replace(/['"]/g,"").trim()}function ve(o){let e=o.get("content-type")||"",t=o.get("content-disposition")||"",s=o.get("content-length");return de(o)?{filename:Ve(o),contentType:e,contentDisposition:t,size:s?parseInt(s,10):void 0}:void 0}async function je(o,e){let t=e,s=o.headers.get("content-type")||"";!t&&s&&(de(o.headers)?t="blob":t=xe(s)),t||(t="json");try{let r;switch((t==="blob"||t==="arrayBuffer")&&(r=ve(o.headers)),t){case"json":try{let n=await o.json();return o.ok?{data:n,fileMetadata:r}:{error:n,fileMetadata:r}}catch{let i=await o.text();return o.ok?{data:i,fileMetadata:r}:{error:i,fileMetadata:r}}case"text":{let n=await o.text();return o.ok?{data:n,fileMetadata:r}:{error:n,fileMetadata:r}}case"blob":{let n=await o.blob();return o.ok?{data:n,fileMetadata:r}:{error:n,fileMetadata:r}}case"arrayBuffer":{let n=await o.arrayBuffer();return o.ok?{data:n,fileMetadata:r}:{error:n,fileMetadata:r}}case"formData":{let n=await o.formData();return o.ok?{data:n,fileMetadata:r}:{error:n,fileMetadata:r}}case"raw":return o.ok?{data:o,fileMetadata:r}:{error:o,fileMetadata:r};default:let a=await o.blob();return o.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}}catch(r){return console.error(`[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u044F \u0434\u0430\u043D\u043D\u044B\u0445 \u0438\u0437 \u043E\u0442\u0432\u0435\u0442\u0430 (\u0444\u043E\u0440\u043C\u0430\u0442: ${t})`,r),o.ok?{data:void 0}:{error:r}}}function Re(o){let{baseUrl:e,timeout:t=3e4,fetchFn:s=fetch,credentials:r="same-origin"}=o;return async(a,n={},i)=>{let{path:c,method:d,body:l,query:p,responseFormat:u}=a,{signal:h,timeout:g=t,responseFormat:y}=n,E=y||u,m=new URL(c.startsWith("http")?c:`${e}${c}`);p&&Object.entries(p).forEach(([S,b])=>{b!=null&&(Array.isArray(b)?b.forEach(O=>m.searchParams.append(S,String(O))):m.searchParams.append(S,String(b)))});let f;if(l!==void 0)if(l instanceof FormData||l instanceof Blob)f=l;else if(typeof l=="object"&&l!==null)try{f=JSON.stringify(l),i.has("Content-Type")||i.set("Content-Type","application/json")}catch(S){console.error("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u0435\u0440\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0442\u0435\u043B\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430",S),f=String(l)}else f=String(l);let A,x=new Promise((S,b)=>{g&&(A=window.setTimeout(()=>{b(new Error(`\u041F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u0437\u0430\u043F\u0440\u043E\u0441\u0430 (${g}\u043C\u0441)`))},g))});try{let S=s(m.toString(),{method:d,headers:i,body:f,signal:h,credentials:r}),b=await Promise.race([S,x]),{data:O,error:q,fileMetadata:Te}=await je(b,E);return{data:O,error:q,ok:b.ok,status:b.status,statusText:b.statusText,headers:b.headers,fileDownloadResult:Te}}catch(S){let b=S;return console.error("[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F \u0437\u0430\u043F\u0440\u043E\u0441\u0430",b),{error:b,ok:!1,status:0,statusText:b.message,headers:new Headers}}finally{A&&window.clearTimeout(A)}}}function Ee(o,e=[]){let t={};return!o||e.length===0||e.forEach(s=>{o.has(s)&&(t[s]=o.get(s)||"")}),t}var L=class{constructor(e,t,s,r,a,n){this.name=e;this.queryStorage=t;this.configCurrentEndpoint=s;this.cacheableHeaderKeys=r;this.globalCacheConfig=a;this.baseQueryConfig=n;this.prepareHeaders=we(n.prepareHeaders,s.prepareHeaders),this.queryFunction=Re({baseUrl:n.baseUrl,fetchFn:n.fetchFn,timeout:n.timeout,credentials:n.credentials}),this.cacheableHeaders=[...r||[],...s.includeCacheableHeaderKeys||[]].filter(i=>!s.excludeCacheableHeaderKeys?.includes(i)),this.meta.name=e,this.meta.tags=s.tags??this.meta.tags,this.meta.invalidatesTags=s.invalidatesTags??this.meta.invalidatesTags,this.meta.cache=this.queryStorage.createCacheConfig(this.configCurrentEndpoint)??this.meta.cache}endpointSubscribers=new Set;fetchCounts=0;meta={cache:!1,invalidatesTags:[],name:"",tags:[]};queryFunction;cacheableHeaders;prepareHeaders;request(e,t){this.fetchCounts++;let s=ce(this.name),r=new AbortController,a=new Set,n={status:"idle",requestParams:e,headers:{},error:void 0,data:void 0,fromCache:!1},i=z({requestParams:e},t?.context||{}),c=l=>{Object.assign(n,l),a.forEach(p=>{p({...n})})},d=new Promise(async(l,p)=>{try{let u=await be(this.prepareHeaders,i),h=Ee(u,t?.cacheableHeaderKeys?t.cacheableHeaderKeys:this.cacheableHeaders),g=this.queryStorage.shouldCache(this.configCurrentEndpoint,t),[y,E]=this.queryStorage.createCacheKey(this.name,{...e,...h}),m;if(g&&(m=await this.queryStorage.getCachedResult(y)),m)c({fromCache:!0,status:"success",data:m.data,error:void 0,headers:m.headers,requestParams:e}),l({...m,fromCache:!0});else{c({fromCache:!1,status:"loading"});let f=this.configCurrentEndpoint.request(e,t?.context),A={...t,signal:r.signal},x=await this.queryFunction(f,A,u);if(x.ok){let{headers:S,...b}=x;if(g){let O=this.queryStorage.createCacheConfig(this.configCurrentEndpoint);await this.queryStorage.setCachedResult(y,{...b,headers:le(S)},O,E??{},this.configCurrentEndpoint.tags??[],this.configCurrentEndpoint.invalidatesTags??[])}c({fromCache:!1,status:"success",data:x.data,error:void 0,headers:x.headers,requestParams:e}),this.endpointSubscribers.forEach(O=>{let q={status:"success",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};O(q)}),l({...x,fromCache:!1})}else c({fromCache:!1,status:"error",data:void 0,error:x.error,headers:x.headers,requestParams:e}),this.endpointSubscribers.forEach(S=>{let b={status:"error",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:x.error};S(b)}),p(x.error)}}catch(u){c({fromCache:!1,status:"error",data:void 0,error:u,headers:void 0,requestParams:e}),p(u)}});return{id:s,subscribe(l,p={}){let{autoUnsubscribe:u=!0}=p;a.add(l),l(n);let h=()=>a.delete(l);return u&&d.finally(()=>{h()}),h},wait:()=>d,waitWithCallbacks(l={}){let{idle:p,loading:u,success:h,error:g}=l;return this.subscribe(y=>{switch(y.status){case"idle":p?.(y);break;case"loading":u?.(y);break;case"success":h?.(y.data,y);break;case"error":g?.(y.error,y);break}},{autoUnsubscribe:!0}),d},abort:()=>{r&&!r.signal.aborted&&r.abort()},then:(l,p)=>d.then(l,p),catch:l=>d.catch(l),finally:l=>d.finally(l)}}subscribe(e){this.endpointSubscribers.add(e);let t={status:"idle",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};return e(t),()=>this.endpointSubscribers.delete(e)}reset(){return this.fetchCounts=0,Promise.resolve()}destroy(){this.endpointSubscribers.clear()}};var T=class{constructor(e,t=!1){this.value=e;this.isRawKey=t}toString(){return this.value}toJSON(){return this.value}valueOf(){return this.value}isUnparseable(){return this.isRawKey}};var M=class{static createMetadata(e=0,t=[]){let s=Date.now(),r=e>0?s+e:1/0;return{createdAt:s,updatedAt:s,expiresAt:r,tags:t,createdAtDateTime:this.formatDateTime(s),updatedAtDateTime:this.formatDateTime(s),expiresAtDateTime:r===1/0?"never":this.formatDateTime(r)}}static formatDateTime(e){return new Date(e).toISOString()}static isExpired(e){return Date.now()>e.expiresAt}static updateMetadata(e){return{...e,updatedAt:Date.now()}}static createKey(...e){return new T(e.join("_"))}static createApiKey(e,t){if(!t)return[new T(e,!0),t];let s=Object.entries(t).sort(([r],[a])=>r.localeCompare(a)).map(([r,a])=>`${r}=${a}`).join("&");return[new T(`${e}_${s}`,!0),t]}static hasAnyTag(e,t=[]){return!e.tags||!t.length?!1:t.some(s=>e.tags?.includes(s))}};var W=class{constructor(e,t){this.storageExternal=e;this.globalCacheConfig=t}storage=null;cleanupInterval=null;defaultCacheOptions={ttl:5*60*1e3,cleanup:{enabled:!0,interval:10*60*1e3},invalidateOnError:!0};async initialize(){return await this.createStorage(),this.startCleanupInterval(),this}async createStorage(){try{let e=this.storageExternal;await e.initialize(),this.storage=e}catch(e){throw console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430",e),e}}startCleanupInterval(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);let e=typeof this.globalCacheConfig=="object"?this.globalCacheConfig.cleanup:this.defaultCacheOptions.cleanup;e?.enabled&&e.interval&&(this.cleanupInterval=setInterval(()=>{this.cleanup().catch(t=>console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0447\u0438\u0441\u0442\u043A\u0435 \u043A\u044D\u0448\u0430:",t))},e.interval))}getStorage(){return this.storage}createCacheKey(e,t){return M.createApiKey(e,t)}async getCachedResult(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let t=await this.storage.get(e);if(!t)return;if(M.isExpired(t.metadata)){await this.storage.delete(e);return}let s={...t,metadata:M.updateMetadata(t.metadata)};return await this.storage.set(e,s),t.data}async setCachedResult(e,t,s,r,a,n){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");n?.length&&await this.invalidateCacheByTags(n);let i=M.createMetadata(s.ttl,a),c={data:t,metadata:i,params:r};await this.storage.set(e,c)}shouldCache(e,t){return!(this.globalCacheConfig===!1||e?.cache===!1||typeof e?.cache=="object"&&e?.cache.ttl===0||t?.disableCache===!0||this.globalCacheConfig===void 0&&e?.cache===void 0)}createCacheConfig(e){let t=this.defaultCacheOptions;if(typeof this.globalCacheConfig=="object"&&(t=this.globalCacheConfig),typeof e?.cache=="object"){let s=e.cache;t={...t,...s}}return t}async invalidateCacheByTags(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let t=await this.storage.keys();for(let s of t){let r=await this.storage.get(s);r&&M.hasAnyTag(r.metadata,e)&&await this.storage.delete(s)}}async invalidateCache(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");await this.storage.delete(e)}async cleanup(){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let e=await this.storage.keys();for(let t of e){let s=await this.storage.get(t);s&&M.isExpired(s.metadata)&&await this.storage.delete(t)}}async destroy(){this.cleanupInterval&&(window.clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.storage&&(await this.storage.destroy(),this.storage=null)}};var ue=class{queryStorage;cacheableHeaderKeys;globalCacheConfig;baseQueryConfig;storageExternal;createEndpoints;endpoints={};constructor(e){this.cacheableHeaderKeys=e.cacheableHeaderKeys,this.globalCacheConfig=e.cache,this.baseQueryConfig=e.baseQuery,this.storageExternal=e.storage,this.createEndpoints=e.endpoints}async init(){return this.queryStorage=await new W(this.storageExternal,this.globalCacheConfig).initialize(),await this.initializeEndpoints(),this}async initializeEndpoints(){let e=s=>s,t=await this.createEndpoints(e)||{};for(let[s,r]of Object.entries(t)){let a=s;this.endpoints[a]=new L(s,this.queryStorage,r,this.cacheableHeaderKeys,this.globalCacheConfig,this.baseQueryConfig)}}getEndpoints(){return this.endpoints}async request(e,t,s){let a=this.getEndpoints()[e];if(!a)throw new Error(`\u042D\u043D\u0434\u043F\u043E\u0438\u043D\u0442 ${String(e)} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`);try{return await a.request(t,s).wait()}catch(n){throw ie.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043A ${String(e)}`,{error:n,params:t}),n}}async destroy(){await Promise.all(Object.values(this.endpoints).map(async e=>(e.destroy(),Promise.resolve()))),this.endpoints={},await this.queryStorage.destroy()}};var v=!1,k=new Map;function Pe(o){let e=0;if(o.length===0)return e.toString(36);for(let t=0;t<o.length;t++){let s=o.charCodeAt(t);e=(e<<5)-e+s,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function I(o,e){if(o===e)return!0;if(o==null||e==null)return!1;if(typeof o!="object"&&typeof o!="function"&&typeof e!="object"&&typeof e!="function")return o===e;if(typeof o!=typeof e)return!1;if(o instanceof Date&&e instanceof Date)return o.getTime()===e.getTime();if(Array.isArray(o)&&Array.isArray(e)){if(o.length!==e.length)return!1;for(let t=0;t<o.length;t++)if(!I(o[t],e[t]))return!1;return!0}if(typeof o=="object"&&typeof e=="object"){let t=Object.keys(o),s=Object.keys(e);return t.length!==s.length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)?I(o[r],e[r]):!1)}return!1}function Ae(o,e=I){let t,s,r=!1;return function(n){if(!r||t!==n){let i=o(n);(!r||!e(i,s))&&(s=i),t=n,r=!0}return s}}var G=class{constructor(e,t,s=I,r){this.name=e;this.equals=s;this.logger=r;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t),v&&console.log(`[${this.id}] \u0421\u043E\u0437\u0434\u0430\u043D new SelectorSubscription`)}id;subscribers=new Set;lastValue;memoizedGetState;createMemoizedGetState(e){let t=null,s=!1;return async()=>{if(s&&t)return t;s=!0;try{return t=e(),await t}finally{s=!1}}}async notify(){try{let e=await this.memoizedGetState();if(this.lastValue===void 0||!this.equals(e,this.lastValue)){v&&console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C, notify()`,{old:this.lastValue,new:e}),this.lastValue=e;let t=Array.from(this.subscribers).map(async s=>{try{await s.notify(e)}catch(r){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430`,{error:r})}});await Promise.all(t)}else v&&console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043D\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C in notify(), \u043F\u0440\u043E\u043F\u0443\u0441\u043A \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F`)}catch(e){throw this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 notify()`,{error:e}),e}}subscribe(e){return v&&console.log(`[${this.id}] \u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E \u043D\u043E\u0432\u044B\u0439 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A, \u0432\u0441\u0435\u0433\u043E: ${this.subscribers.size+1}`),this.subscribers.add(e),this.lastValue!==void 0?Promise.resolve().then(()=>{try{e.notify(this.lastValue)}catch(t){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}}):this.notify().catch(t=>{this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}),()=>{v&&console.log(`[${this.id}] \u041F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A \u0443\u0434\u0430\u043B\u0435\u043D, \u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C: ${this.subscribers.size-1}`),this.subscribers.delete(e)}}cleanup(){v&&console.log(`[${this.id}] \u041E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0438, \u0431\u044B\u043B\u043E ${this.subscribers.size} \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u043E\u0432`),this.subscribers.clear(),this.lastValue=void 0}getId(){return this.id}},U=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,v&&console.log(`\u0421\u043E\u0437\u0434\u0430\u043D SelectorModule \u0434\u043B\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${this.storageName}`),this.source.getState().then(s=>{this.cachedState=s,v&&console.log(`\u041A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0434\u043B\u044F ${this.storageName}`)})}storageName;subscriptions=new Map;cachedState;localSelectorCache=new Map;batchUpdateInProgress=!1;pendingUpdates=new Set;generateName(e,t,s){let r=e?"simple":"combined",a="";if(e){let n=t.toString();a=Pe(n)}else{let n=t.map(c=>c.getId()).join("_"),i=s.toString();a=Pe(n+i)}return`${this.storageName}_${r}_${a}`}processPendingUpdates(){this.pendingUpdates.size===0||this.batchUpdateInProgress||(this.batchUpdateInProgress=!0,setTimeout(async()=>{try{let e=Array.from(this.pendingUpdates);this.pendingUpdates.clear(),this.cachedState=await this.source.getState();let t=e.map(async s=>{let r=this.subscriptions.get(s);if(r)try{return await r.notify()}catch(a){this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430 ${s}`,{error:a})}return Promise.resolve()});await Promise.all(t)}catch(e){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0439",{error:e})}finally{this.batchUpdateInProgress=!1,this.pendingUpdates.size>0&&this.processPendingUpdates()}},0))}createSelector(e,t,s){let r=!Array.isArray(e),a=r?t||{}:s||{},n=a.name||this.generateName(r,e,r?void 0:t);if(this.localSelectorCache.has(n))return v&&console.log(`[${this.storageName}] Reusing cached selector: ${n}`),this.localSelectorCache.get(n).api;if(k.has(n)){let l=k.get(n);return l.refCount++,v&&console.log(`[${this.storageName}] \u041F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0433\u043E \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440\u0430: ${n}, refCount: ${l.refCount}`),l.api}let i,c,d=[];if(r){let l=Ae(e,a.equals||I),p=this.createSimpleSelector(l,{...a,name:n,equals:a.equals||I});i=p.api,d=p.unsubscribeFunctions}else{c=e;let l=this.createCombinedSelector(c,t,{...a,name:n,equals:a.equals||I});i=l.api,d=l.unsubscribeFunctions}return this.localSelectorCache.set(n,{api:i,dependencies:c,unsubscribeFunctions:d}),k.set(n,{api:i,refCount:1,unsubscribeFunctions:d}),v&&console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043D\u043E\u0432\u044B\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${n}`),i}createSimpleSelector(e,t){v&&console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043F\u0440\u043E\u0441\u0442\u043E\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${t.name}`);let s=async()=>{if(this.cachedState)return e(this.cachedState);let c=await this.source.getState();return this.cachedState=c,e(c)},r=new G(t.name,s,t.equals||I,this.logger),a=r.getId();this.subscriptions.set(a,r);let i=[this.source.subscribeToAll(async c=>{c?.type==="storage:update"&&(v&&console.log(`[${a}] \u041F\u043E\u043B\u0443\u0447\u0435\u043D\u043E \u0441\u043E\u0431\u044B\u0442\u0438\u0435 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430`),this.pendingUpdates.add(a),this.processPendingUpdates())})];return{api:{select:()=>s(),subscribe:c=>r.subscribe(c),getId:()=>a},unsubscribeFunctions:i}}createCombinedSelector(e,t,s){let r=Ae(p=>t(...p),s.equals||I),a=async()=>{let p=await Promise.all(e.map(u=>u.select()));return r(p)},n=new G(s.name,a,s.equals||I,this.logger),i=n.getId();this.subscriptions.set(i,n);let c=null,d=()=>{c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,n.notify().catch(p=>this.logger?.error(`[${i}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438:`,{error:p}))},10)},l=e.map(p=>p.subscribe({notify:()=>{d()}}));return{api:{select:()=>a(),subscribe:p=>n.subscribe(p),getId:()=>i},unsubscribeFunctions:l}}destroy(){v&&console.log(`[${this.storageName}] \u041D\u0430\u0447\u0430\u043B\u043E\u0441\u044C \u0443\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D\u0438\u0435 SelectorModule`),this.subscriptions.forEach(t=>t.cleanup()),this.subscriptions.clear(),this.cachedState=void 0,this.pendingUpdates.clear(),this.localSelectorCache.forEach(t=>{t.unsubscribeFunctions.forEach(s=>s())});let e=new Set;this.localSelectorCache.forEach((t,s)=>{e.add(s)}),this.localSelectorCache.clear(),e.forEach(t=>{let s=k.get(t);s&&(s.refCount--,s.refCount<=0&&(s.unsubscribeFunctions.forEach(r=>r()),k.delete(t),v&&console.log(`[${this.storageName}] \u0423\u0434\u0430\u043B\u0435\u043D \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440 \u0438\u0437 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0430: ${t}`)))}),v&&console.log(`[${this.storageName}] \u0423\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D`)}};var pe=class{constructor(e,t,s="default"){this.parentExecutor=e;this.logger=t;this.storageName=s}plugins=new Map;createContext(e){return{storageName:this.storageName,timestamp:Date.now(),metadata:e}}async add(e){if(this.plugins.has(e.name)){this.logger?.warn(`\u041F\u043B\u0430\u0433\u0438\u043D ${e.name} \u0443\u0436\u0435 \u0431\u044B\u043B \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D`);return}try{await e.initialize?.(),this.plugins.set(e.name,e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D",{name:e.name})}catch(t){throw t}}async remove(e){let t=this.plugins.get(e);t&&(await t.destroy?.(),this.plugins.delete(e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0443\u0434\u0430\u043B\u0435\u043D",{name:e}))}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}async initialize(){for(let e of this.plugins.values())await e.initialize?.()}async destroy(){await Promise.all(Array.from(this.plugins.values()).map(e=>e.destroy?.()??Promise.resolve())),this.plugins.clear()}async executeBeforeSet(e,t){let s=e,r=this.createContext(t);this.parentExecutor&&(s=await this.parentExecutor.executeBeforeSet(s,r));for(let a of this.plugins.values())if(a.onBeforeSet)try{s=await a.onBeforeSet(s,r)}catch(n){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onBeforeSet`,{error:n}),n}return s}async executeAfterSet(e,t,s){let r=t,a=this.createContext(s);this.parentExecutor&&(r=await this.parentExecutor.executeAfterSet(e,r,a));for(let n of this.plugins.values())if(n.onAfterSet)try{r=await n.onAfterSet(e,r,a)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${n.name} onAfterSet`,{key:e,error:i}),i}return r}async executeBeforeGet(e,t){let s=e,r=this.createContext(t);this.parentExecutor&&(s=await this.parentExecutor.executeBeforeGet(s,r));for(let a of this.plugins.values())if(a.onBeforeGet)try{s=await a.onBeforeGet(s,r)}catch(n){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onBeforeGet`,{key:e,error:n}),n}return s}async executeAfterGet(e,t,s){let r=t,a=this.createContext(s);this.parentExecutor&&(r=await this.parentExecutor.executeAfterGet(e,r,a)),console.log("executeAfterGet",e,t,s);for(let n of this.plugins.values())if(n.onAfterGet)try{r=await n.onAfterGet(e,r,a)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${n.name} onAfterGet`,{key:e,error:i}),i}return r}async executeBeforeDelete(e,t){let s=!0,r=this.createContext(t);this.parentExecutor&&(s=await this.parentExecutor.executeBeforeDelete(e,r));for(let a of this.plugins.values())if(a.onBeforeDelete)try{s=await a.onBeforeDelete(e,r)&&s}catch(n){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onBeforeDelete`,{key:e,error:n}),n}return s}async executeAfterDelete(e,t){let s=this.createContext(t);this.parentExecutor&&await this.parentExecutor.executeAfterDelete(e,s);for(let r of this.plugins.values())if(r.onAfterDelete)try{await r.onAfterDelete(e,s)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${r.name} onAfterDelete`,{key:e,error:a}),a}}async executeOnClear(e){let t=this.createContext(e);this.parentExecutor&&await this.parentExecutor.executeOnClear(t);for(let s of this.plugins.values())if(s.onClear)try{await s.onClear(t)}catch(r){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${s.name} onClear`,{error:r}),r}}};var Q=(n=>(n.STORAGE_UPDATE="storage:update",n.STORAGE_DELETE="storage:delete",n.STORAGE_PATCH="storage:patch",n.STORAGE_SELECT="storage:select",n.STORAGE_CLEAR="storage:clear",n.STORAGE_DESTROY="storage:destroy",n))(Q||{});var J=class{channel;tabId;messageHandlers;syncHandler;debug;syncTimeoutMs=1e3;pendingSyncRequests;constructor(e,t={}){this.channel=new BroadcastChannel(e),this.tabId=crypto.randomUUID(),this.messageHandlers=new Set,this.debug=t.debug??!1,this.pendingSyncRequests=new Map,this.channel.onmessage=this.handleMessage.bind(this),this.channel.onmessageerror=this.handleError.bind(this)}log(...e){this.debug&&console.log(`[SyncBroadcastChannel][${this.tabId}]`,...e)}error(...e){console.error(`[SyncBroadcastChannel][${this.tabId}]`,...e)}async handleMessage(e){let t=e.data;if(t.senderId!==this.tabId){if(t.type==="SYNC_REQUEST"){if(this.syncHandler)try{let s=await this.syncHandler();this.postMessage("SYNC_RESPONSE",s,t.senderId)}catch(s){this.error("Error handling sync request:",s)}return}if(t.type==="SYNC_RESPONSE"){let s=this.pendingSyncRequests.get(this.tabId);s&&(clearTimeout(s.timeout),this.pendingSyncRequests.delete(this.tabId),s.resolve(t.payload));return}for(let s of this.messageHandlers)try{await s(t)}catch(r){this.error("Error in message handler:",r)}}}handleError(e){this.error("Channel error:",e)}postMessage(e,t,s){let r={type:e,payload:t,senderId:this.tabId,timestamp:Date.now()};this.channel.postMessage(r)}subscribe(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}setSyncHandler(e){this.syncHandler=e}broadcast(e,t){this.postMessage(e,t)}async requestSync(){return new Promise((e,t)=>{let s=setTimeout(()=>{this.pendingSyncRequests.delete(this.tabId),e(null)},this.syncTimeoutMs);this.pendingSyncRequests.set(this.tabId,{resolve:e,reject:t,timeout:s}),this.postMessage("SYNC_REQUEST",{type:"sync"})})}close(){for(let[,e]of this.pendingSyncRequests)clearTimeout(e.timeout),e.reject(new Error("Channel closed"));this.pendingSyncRequests.clear(),this.messageHandlers.clear(),this.syncHandler=void 0,this.channel.close()}};async function He(o,e,t){switch(e){case"set":t?.key!==void 0&&t?.value!==void 0&&(await o.storage.doSet(t.key,t.value),o.storage.notifySubscribers(t.key,t.value));break;case"update":Array.isArray(t?.value)&&(await o.storage.doUpdate(t.value),t.value.forEach(({key:s,value:r})=>{o.storage.notifySubscribers(s,r)}));break;case"delete":t?.key!==void 0&&(await o.storage.doDelete(t.key),o.storage.notifySubscribers(t.key,void 0));break;case"clear":await o.storage.doClear(),o.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}o.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:t?.value,source:"broadcast"})}async function _e(o,e,t){switch(e){case"set":if(t?.key!==void 0){let s=await o.storage.doGet(t.key);o.storage.notifySubscribers(t.key,s)}break;case"update":if(Array.isArray(t?.value)){for(let{key:s}of t.value){let r=await o.storage.doGet(s);o.storage.notifySubscribers(s,r)}o.storage.notifySubscribers("*",{type:"storage:update",key:t.value.map(({key:s})=>s),value:t.value,source:"broadcast"})}break;case"delete":t?.key!==void 0&&o.storage.notifySubscribers(t.key,void 0);break;case"clear":o.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}e!=="update"&&o.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:e==="delete"?void 0:t?.value,source:"broadcast"})}var ge=o=>{let{storageName:e,storageType:t}=o,s=`${t}-${e}`,r=new J(s,{debug:!0});return{name:"broadcast",setup:a=>(t==="memory"&&(r.setSyncHandler(async()=>{let n=await a.getState();return{type:"update",key:"*",value:Object.entries(n).map(([d,l])=>({key:d,value:l})),metadata:{batchUpdate:!0,timestamp:Date.now()}}}),r.requestSync().then(async n=>{if(n?.type==="update"&&Array.isArray(n.value))try{if(!n.value.every(c=>c&&typeof c=="object"&&"key"in c&&"value"in c)){console.error("[Sync Response] Invalid updates structure:",n.value);return}await a.storage.doUpdate(n.value),n.value.forEach(({key:c,value:d})=>{a.storage.notifySubscribers(c,d)}),a.storage.notifySubscribers("*",{type:"storage:update",value:n.value,source:"broadcast"})}catch(i){console.error("[Sync Response] Error applying updates:",i)}})),r.subscribe(async n=>{let{type:i,payload:c}=n;t==="memory"?await He(a,i,c):await _e(a,i,c)})),reducer:a=>n=>async i=>{let c=await n(i);return["set","delete","clear","update"].includes(i.type)&&r.broadcast(i.type,i),c},cleanup:()=>{r.close()}}};var Ce=(o={})=>{let e=o.batchSize??10,t=o.batchDelay??10,s=new Map,r=new Map,a=u=>u.type==="set"||u.type==="update",n=u=>`${u.type}_${u.key?.toString()||"default"}`,i=u=>{let h=new Map;for(let g of u){let y=`${g.type}_${g.key?.toString()||"default"}`;h.set(y,g)}return Array.from(h.values())},c=u=>{let h=r.get(u);h&&(globalThis.clearTimeout(h),r.delete(u))},d=(u,h)=>{let g=globalThis.setTimeout(h,t);r.set(u,g)},l=async(u,h,g)=>{let y=s.get(u);if(!(!y||y.length===0)){s.delete(u),c(u);try{let E=y.map(f=>f.action),m=i(E);console.log(`\u{1F504} Batching ${u}: ${y.length} actions -> ${m.length} merged`,{original:E.map(f=>({type:f.type,key:f.key?.toString(),value:f.value})),merged:m.map(f=>({type:f.type,key:f.key?.toString(),value:f.value}))});for(let f of m)try{let A=await g(f);y.filter(S=>S.action.type===f.type&&S.action.key?.toString()===f.key?.toString()).forEach(S=>S.resolve(A))}catch(A){y.filter(S=>S.action.type===f.type&&S.action.key?.toString()===f.key?.toString()).forEach(S=>S.reject(A))}}catch(E){y.forEach(m=>m.reject(E))}}},p=async(u,h,g)=>new Promise((y,E)=>{let m=n(u),f=s.get(m);f||(f=[],s.set(m,f)),f.push({action:u,resolve:y,reject:E,timestamp:Date.now()}),c(m),f.length>=e?setImmediate(()=>l(m,h,g)):d(m,()=>l(m,h,g))});return{name:"batching",setup:()=>{},cleanup:async()=>{r.forEach(u=>globalThis.clearTimeout(u)),r.clear(),s.clear()},reducer:u=>h=>async g=>a(g)?p(g,u,h):h(g)}};var De=(o={})=>{let{comparator:e=(r,a)=>{if(r===a)return!0;if(typeof r!="object"||typeof a!="object"||r===null||a===null)return r===a;let n=Object.keys(r),i=Object.keys(a);return n.length!==i.length?!1:n.every(c=>Object.prototype.hasOwnProperty.call(a,c)&&r[c]===a[c])},segments:t=[]}=o,s=new Map;return{name:"shallow-compare",setup:r=>{},reducer:r=>a=>async n=>{if(n.type!=="set"||t.length&&!t.includes(n.metadata?.segment??"default"))return a(n);let i=n.key,c=s.get(i),d=n.value;if(c!==void 0&&e(c,d))return console.log("ShallowCompare: \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0438\u0434\u0435\u043D\u0442\u0438\u0447\u043D\u044B, \u043F\u0440\u043E\u043F\u0443\u0441\u043A\u0430\u0435\u043C \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u044E",{key:i,value:d}),{...c,__metadata:{valueNotChanged:!0,originalValue:c}};let l=await a(n);return s.set(i,d),l}}};var Y=class{middlewares=[];api;initialized=!1;dispatchFn;constructor(e){this.api={dispatch:async t=>this.dispatch(t),getState:()=>e.getState(),storage:{doGet:e.doGet.bind(e),doSet:e.doSet.bind(e),doUpdate:e.doUpdate.bind(e),doDelete:e.doDelete.bind(e),doClear:e.doClear.bind(e),doKeys:e.doKeys.bind(e),notifySubscribers:e.notifySubscribers.bind(e)}}}async baseOperation(e){let{processed:t,...s}=e.metadata||{},r={...e,metadata:s};switch(r.type){case"get":return this.api.storage.doGet(r.key);case"set":return await this.api.storage.doSet(r.key,r.value),this.api.storage.doGet(r.key);case"update":return Array.isArray(r.value)?(await this.api.storage.doUpdate(r.value),this.api.storage.doGet("")):r.value;case"delete":return this.api.storage.doDelete(r.key);case"clear":return this.api.storage.doClear();case"init":{let a=await this.api.storage.doGet("");return Object.keys(a||{}).length>0?a:r.value?(await this.api.storage.doSet("",r.value),this.api.storage.doGet("")):a}case"keys":return this.api.storage.doKeys();default:throw new Error(`Unknown action type: ${r.type}`)}}initializeMiddlewares(){if(this.initialized)return;let e=this.baseOperation.bind(this);for(let t of[...this.middlewares].reverse()){let s=e;e=async r=>{if(r.metadata?.processed)return s(r);let a={...r,metadata:{...r.metadata,processed:!0,timestamp:r.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(s)(a)}}this.dispatchFn=e,this.initialized=!0}use(e){e.setup&&e.setup(this.api),this.middlewares.push(e),this.initialized=!1}async dispatch(e){this.initialized||this.initializeMiddlewares();try{return this.dispatchFn(e)}catch(t){throw console.error("Error in middleware chain:",t),t}}};function C(o){return o instanceof T&&o.isUnparseable()?[o.toString()]:o.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function D(o,e){return C(e).reduce((s,r)=>s===void 0?void 0:s[r],o)}function F(o,e,t){if(e==="")return t;let s=C(e);if(e instanceof T&&e.isUnparseable())return o[e.toString()]=t,o;let r=s.pop(),a=s.reduce((n,i)=>{let c=s[s.indexOf(i)+1],d=!Number.isNaN(Number(c));return i in n||(n[i]=d?[]:{}),n[i]},o);return a[r]=t,o}var B=class o{constructor(e,t,s,r){this.config=e;this.pluginExecutor=t;this.eventEmitter=s;this.logger=r;this.name=e.name,this.middlewareModule=new Y({getState:this.getState.bind(this),doGet:this.doGet.bind(this),doSet:this.doSet.bind(this),doUpdate:this.doUpdate.bind(this),doDelete:this.doDelete.bind(this),doClear:this.doClear.bind(this),doKeys:this.doKeys.bind(this),notifySubscribers:this.notifySubscribers.bind(this),pluginExecutor:this.pluginExecutor,eventEmitter:this.eventEmitter,logger:this.logger}),this.initializeMiddlewares()}static GLOBAL_SUBSCRIPTION_KEY="*";name;selectorPathCache=new WeakMap;middlewareModule;initializedMiddlewares=null;subscribers=new Map;initializeMiddlewares(){this.config.middlewares&&!this.initializedMiddlewares&&(this.initializedMiddlewares=this.config.middlewares(()=>this.getDefaultMiddleware()),this.initializedMiddlewares.forEach(e=>this.middlewareModule.use(e)))}getDefaultMiddleware(){return{batching:(e={})=>Ce(e),shallowCompare:(e={})=>De(e)}}async initializeWithMiddlewares(){try{let e=await this.getState();!(Object.keys(e).length>0)&&this.config.initialState&&await this.middlewareModule.dispatch({type:"init",value:this.config.initialState})}catch(e){throw this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430",{error:e}),e}}async get(e){try{let t={operation:"get",timestamp:Date.now(),key:e},s=await this.middlewareModule.dispatch({type:"get",key:e,metadata:t}),r=await this.pluginExecutor?.executeAfterGet(e,s,t)??s;return await this.emitEvent({type:"storage:select",payload:{key:e,value:r}}),r}catch(t){throw this.logger?.error("Error getting value",{key:e,error:t}),t}}async set(e,t){try{let s={operation:"set",timestamp:Date.now(),key:e},r=await this.pluginExecutor?.executeBeforeSet(t,s)??t,a=await this.middlewareModule.dispatch({type:"set",key:e,value:r,metadata:s}),n=a?.__metadata?.valueNotChanged===!0,i;if(n&&a?.__metadata?.originalValue!==void 0?i=a.__metadata.originalValue:i=await this.pluginExecutor?.executeAfterSet(e,a,s)??a,!n){let d=[e.toString()];this.notifySubscribers(e,i),this.notifySubscribers(o.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:i,changedPaths:d}),await this.emitEvent({type:"storage:update",payload:{key:e,value:i,changedPaths:d}})}}catch(s){throw this.logger?.error("Error setting value",{key:e,error:s}),s}}async update(e){try{let t={operation:"update",timestamp:Date.now()},s=await this.getState(),r=structuredClone(s);e(r);let a=this.findChangedPaths(s,r);if(a.size===0){this.logger?.debug&&this.logger.debug("No changes detected in update");return}this.logger?.debug&&this.logger.debug("Changed paths:",{paths:Array.from(a)});let n=new Set;for(let u of a){let h=u.split(".")[0];n.add(h)}let i=await Promise.all(Array.from(n).map(async u=>{let h={...t,key:u},g=await this.pluginExecutor?.executeBeforeSet(r[u],h)??r[u];return{key:u,value:g}})),c=await this.middlewareModule.dispatch({type:"update",value:i,metadata:{...t,batchUpdate:!0,changedPaths:Array.from(a)}}),d={};Array.isArray(c)?c.forEach(u=>{u&&typeof u=="object"&&"key"in u&&"value"in u&&(d[u.key]=u.value)}):c&&typeof c=="object"&&(d={...c});let l=Object.keys(d).filter(u=>!this.isEqual(s[u],d[u]));if(l.length===0){this.logger?.debug&&this.logger.debug("No actual changes after middleware processing");return}let p={};l.forEach(u=>{p[u]=d[u]}),this.logger?.debug&&this.logger.debug("Notifying subscribers about changes:",{keys:l}),this.notifySubscribers(o.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:l,value:p,changedPaths:Array.from(a)});for(let u of a)try{let h=u.split(".")[0];if(h in p){let g;if(u===h)g=p[h];else{let y=u.substring(h.length+1);g=D(p[h],y)}g!==void 0&&this.notifySubscribers(u,g)}}catch(h){this.logger?.error("Error notifying path subscribers",{path:u,error:h})}await this.emitEvent({type:"storage:update",payload:{state:p,key:l,changedPaths:Array.from(a)}})}catch(t){throw this.logger?.error("Error updating state",{error:t}),t}}async delete(e){try{let t={operation:"delete",timestamp:Date.now(),key:e};if(await this.pluginExecutor?.executeBeforeDelete(e,t)){let s=await this.middlewareModule.dispatch({type:"delete",key:e,metadata:t});await this.pluginExecutor?.executeAfterDelete(e,t);let a=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(o.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:s,changedPaths:a}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:s,changedPaths:a}})}}catch(t){throw this.logger?.error("Error deleting value",{key:e,error:t}),t}}async clear(){try{this.pluginExecutor?.executeOnClear(),await this.middlewareModule.dispatch({type:"clear"})}catch(e){throw this.logger?.error("Error clearing storage",{error:e}),e}}async keys(){try{return await this.middlewareModule.dispatch({type:"keys"})}catch(e){throw this.logger?.error("Error getting keys",{error:e}),e}}async has(e){try{return await this.doHas(e)}catch(t){throw this.logger?.error("Error checking value existence",{key:e,error:t}),t}}async getState(){try{return await this.doGet("")||{}}catch(e){throw this.logger?.error("Error getting state",{error:e}),e}}subscribeToAll(e){return this.subscribers.has(o.GLOBAL_SUBSCRIPTION_KEY)||this.subscribers.set(o.GLOBAL_SUBSCRIPTION_KEY,new Set),this.subscribers.get(o.GLOBAL_SUBSCRIPTION_KEY).add(e),()=>{let t=this.subscribers.get(o.GLOBAL_SUBSCRIPTION_KEY);t&&(t.delete(e),t.size===0&&this.subscribers.delete(o.GLOBAL_SUBSCRIPTION_KEY))}}subscribe(e,t){return typeof e=="string"?this.subscribeByKey(e,t):this.subscribeBySelector(e,t)}async destroy(){try{await this.clear(),await this.doDestroy(),this.initializedMiddlewares&&(await Promise.all(this.initializedMiddlewares.map(async e=>{"cleanup"in e&&await e.cleanup?.()})),this.initializedMiddlewares=null),await this.emitEvent({type:"storage:destroy"})}catch(e){throw this.logger?.error("Error destroying storage",{error:e}),e}}subscribeByKey(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let s=!1;return this.subscribers.get(e).add(t),this.get(e).then(r=>{try{s||(s=!0,t(r))}catch(a){this.logger?.error("Error in initial callback",{key:e,error:a})}}),()=>{let r=this.subscribers.get(e);r&&(r.delete(t),r.size===0&&this.subscribers.delete(e))}}createDummyState(){let e={get:(t,s)=>(t[s]=t[s]||new Proxy({},e),t[s])};return new Proxy({},e)}isEqual(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;let s=typeof e;if(s!==typeof t)return!1;if(s!=="object")return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!this.isEqual(e[i],t[i]))return!1;return!0}let a=Object.keys(e),n=Object.keys(t);return a.length!==n.length?!1:a.every(i=>Object.prototype.hasOwnProperty.call(t,i)&&this.isEqual(e[i],t[i]))}extractPath(e,t){if(this.selectorPathCache.has(e))return this.selectorPathCache.get(e);let s=[],r=(a="")=>({get:(n,i)=>{if(typeof i=="symbol")return Reflect.get(n,i);let c=a?`${a}.${i}`:i;return s.push(c),new Proxy({},r(c))},has:(n,i)=>!0,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0}),apply:(n,i,c)=>new Proxy(()=>{},r(a))});try{e(new Proxy(t,r()))}catch{}return s.length===0?"":(s.sort((a,n)=>n.length-a.length),this.selectorPathCache.set(e,s[0]),s[0])}notifySubscribers(e,t){let s=e.toString(),r=this.subscribers.get(s);r?.size&&new Set(r).forEach(n=>{try{n(t)}catch(i){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0435 \u043D\u0430 \u043A\u043E\u043B\u0431\u044D\u043A",{key:s,error:i})}})}findChangedPaths(e,t,s="",r=new Set,a=new WeakMap){if(e===t)return r;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e!==t&&r.add(s||""),r;if(a.has(e))return r;a.set(e,!0);let n=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let i of n){let c=e[i],d=t[i];if(c===d)continue;let l=s?`${s}.${i}`:i;c&&d&&typeof c=="object"&&typeof d=="object"&&!Array.isArray(c)&&!Array.isArray(d)?this.findChangedPaths(c,d,l,r,a):Array.isArray(c)&&Array.isArray(d)?this.isEqual(c,d)||r.add(l):this.isEqual(c,d)||r.add(l)}return r}subscribeBySelector(e,t){let s=this.createDummyState(),r=this.extractPath(e,s);this.logger?.debug&&this.logger.debug("Subscribing to path:",{path:r});let a=async n=>{try{if(n==null){let d=await this.getState(),l=e(d);t(l);return}if(typeof n!="object"||n===null){t(n);return}let i=await this.getState(),c=e(i);t(c)}catch(i){this.logger?.error("Error in selector callback",{path:r,error:i}),t(n)}};return r?this.subscribeByKey(r,a):this.subscribeToAll(()=>{this.getState().then(n=>{t(e(n))})})}async emitEvent(e){try{await this.eventEmitter?.emit({...e,metadata:{...e.metadata||{},timestamp:Date.now(),storageName:this.name}})}catch(t){this.logger?.error("Error emitting event",{event:e,error:t})}}};var he=class o{constructor(e,t,s){this.dbName=e;this.logger=s;this.dbVersion=t}static instances=new Map;db=null;initPromise=null;storeNames=new Set;dbVersion;static getInstance(e,t=1,s){o.instances.has(e)||o.instances.set(e,new o(e,t,s));let r=o.instances.get(e);return t>r.dbVersion&&(r.dbVersion=t),r}async initialize(){return this.db?this.db:(this.initPromise||(this.initPromise=this.openDatabase()),this.initPromise)}async ensureStoreExists(e){if(await this.initialize(),this.db.objectStoreNames.contains(e))return this.storeNames.add(e),this.db;this.logger?.debug(`Store "${e}" not found, upgrading database`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase([e]);let t=await this.initPromise;return this.storeNames.add(e),t}async openDatabase(e=[]){return new Promise((t,s)=>{this.logger?.debug(`Opening database "${this.dbName}" with version ${this.dbVersion}`);let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=()=>{this.logger?.error(`Failed to open database "${this.dbName}"`,{error:r.error}),s(r.error)},r.onsuccess=()=>{this.db=r.result;for(let a=0;a<this.db.objectStoreNames.length;a++)this.storeNames.add(this.db.objectStoreNames[a]);this.logger?.debug(`Database "${this.dbName}" opened successfully`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),t(this.db)},r.onupgradeneeded=a=>{let n=a.target.result;this.logger?.debug(`Upgrading database "${this.dbName}" to version ${this.dbVersion}`);for(let i of e)n.objectStoreNames.contains(i)||(this.logger?.debug(`Creating store "${i}"`),n.createObjectStore(i))}})}closeDatabase(){this.db&&(this.db.close(),this.db=null,this.initPromise=null)}async deleteDatabase(){return this.closeDatabase(),new Promise((e,t)=>{let s=indexedDB.deleteDatabase(this.dbName);s.onsuccess=()=>{this.logger?.debug(`Database "${this.dbName}" deleted successfully`),o.instances.delete(this.dbName),this.storeNames.clear(),e()},s.onerror=()=>{this.logger?.error(`Failed to delete database "${this.dbName}"`,{error:s.error}),t(s.error)}})}async ensureStoresExist(e){await this.initialize();let t=e.filter(s=>!this.db.objectStoreNames.contains(s));return t.length===0?this.db:(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u043D\u0435\u0434\u043E\u0441\u0442\u0430\u044E\u0449\u0438\u0445 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449: ${t.join(", ")}`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase(t),this.initPromise)}getCurrentVersion(){return this.dbVersion}},ye=class{constructor(e,t=1,s){this.dbName=e;this.logger=s;this.version=t}db=null;version;getCurrentVersion(){return this.version}openDatabase(e,t=[]){return new Promise((s,r)=>{this.logger?.debug(`\u041E\u0442\u043A\u0440\u044B\u0442\u0438\u0435 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0441 \u0432\u0435\u0440\u0441\u0438\u0435\u0439 ${e}`);let a=indexedDB.open(this.dbName,e);a.onerror=()=>{this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u0438\u0438 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}"`,{error:a.error}),r(a.error)},a.onsuccess=()=>{this.db=a.result,this.version=this.db.version,this.logger?.debug(`\u0411\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0442\u043A\u0440\u044B\u0442\u0430`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),s(this.db)},a.onupgradeneeded=n=>{let i=n.target.result;this.logger?.debug(`\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0434\u043E \u0432\u0435\u0440\u0441\u0438\u0438 ${e}`);for(let c of t)i.objectStoreNames.contains(c)||(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 "${c}"`),i.createObjectStore(c))}})}async ensureStoresExist(e){this.db||(this.db=await this.openDatabase(this.version));let t=e.filter(s=>!this.db.objectStoreNames.contains(s));return t.length===0?this.db:(this.logger?.debug(`\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0441\u043E\u0437\u0434\u0430\u0442\u044C \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${t.join(", ")}`,{dbName:this.dbName,currentVersion:this.version}),this.db.close(),this.db=null,this.version++,this.db=await this.openDatabase(this.version,t),this.db)}close(){this.db&&(this.db.close(),this.db=null)}},X=class o extends B{DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,s,r){super(e,t,s,r);let a=e.options;this.DB_NAME=a.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=a.dbVersion||1,this.dbManager=he.getInstance(this.DB_NAME,this.DB_VERSION,r)}async initialize(){try{this.logger?.debug(`Initializing IndexedDB storage "${this.STORE_NAME}"`),await this.dbManager.ensureStoreExists(this.STORE_NAME);try{if(!(await this.dbManager.initialize()).objectStoreNames.contains(this.STORE_NAME))throw new Error(`Store "${this.STORE_NAME}" not found after initialization`)}catch(e){throw this.logger?.error(`Error verifying store "${this.STORE_NAME}" exists:`,{error:e}),e}this.initializeMiddlewares();try{await this.initializeWithMiddlewares(),this.logger?.debug(`IndexedDB storage "${this.STORE_NAME}" initialized successfully`)}catch(e){this.logger?.error(`Failed to initialize middleware for store "${this.STORE_NAME}"`,{error:e})}return this}catch(e){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 IndexedDB "${this.name}"`,{error:e}),e}}static async getCurrentDBVersion(e){return new Promise(t=>{try{let s=indexedDB.open(e);s.onsuccess=()=>{let r=s.result.version;s.result.close(),t(r)},s.onerror=()=>{console.warn(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0438 \u0432\u0435\u0440\u0441\u0438\u0438 \u0411\u0414 ${e}`,s.error),t(0)}}catch(s){console.warn(`\u0418\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u043F\u0440\u0438 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0438 \u0432\u0435\u0440\u0441\u0438\u0438 \u0411\u0414 ${e}`,s),t(0)}})}static async createStorages(e,t,s){let a=await this.getCurrentDBVersion(e)||1,n=new ye(e,a,s),i=Object.values(t).map(d=>d.name);await n.ensureStoresExist(i);let c={};for(let[d,l]of Object.entries(t)){let p=new o({...l,options:{dbName:e,dbVersion:n.getCurrentVersion()}},l.pluginExecutor,l.eventEmitter,s);c[d]=await p.initialize()}return c}async getTransaction(e="readonly"){try{let t=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!t.objectStoreNames.contains(this.STORE_NAME)){this.logger?.warn(`Object store "${this.STORE_NAME}" not found, attempting to repair`),t.close(),this.dbManager.closeDatabase();let s=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!s.objectStoreNames.contains(this.STORE_NAME))throw new Error(`Object store "${this.STORE_NAME}" still doesn't exist after repair attempt`);return s.transaction(this.STORE_NAME,e)}return t.transaction(this.STORE_NAME,e)}catch(t){throw this.logger?.error(`Failed to create transaction for store "${this.STORE_NAME}"`,{error:t}),t}}async getObjectStore(e="readonly"){return(await this.getTransaction(e)).objectStore(this.STORE_NAME)}async doGet(e){let t=await this.getObjectStore();if(e==="")return new Promise((r,a)=>{let n=t.getAll();n.onerror=()=>a(n.error),n.onsuccess=()=>{let i=n.result,c=t.getAllKeys();c.onsuccess=()=>{let d=c.result.reduce((l,p,u)=>(p!=="root"&&(l[p]=i[u]),l),{});r(d)},c.onerror=()=>a(c.error)}});if(e instanceof T&&e.isUnparseable())return new Promise((r,a)=>{let n=t.get(e.valueOf());n.onerror=()=>a(n.error),n.onsuccess=()=>r(n.result)});let s=C(e);if(s.length>1){let r=s[0];return new Promise((a,n)=>{let i=t.get(r);i.onerror=()=>n(i.error),i.onsuccess=()=>{let c=i.result;if(!c){a(void 0);return}let d=D(c,s.slice(1).join("."));a(d)}})}return new Promise((r,a)=>{let n=t.get(s[0]);n.onerror=()=>a(n.error),n.onsuccess=()=>r(n.result)})}async doSet(e,t){if(e===""){let a=await this.getObjectStore("readwrite");return new Promise((n,i)=>{let c=a.transaction;c.oncomplete=()=>{n()},c.onerror=()=>{i(c.error)};let d=a.clear();d.onsuccess=()=>{let l=Object.entries(t);for(let[p,u]of l)a.put(u,p)},d.onerror=()=>{i(d.error)}})}let s=await this.getObjectStore("readwrite");if(e instanceof T&&e.isUnparseable()){await this.putValueInStore(s,e.valueOf(),t);return}let r=C(e);if(r.length>1){let a=r[0];return new Promise((n,i)=>{let c=s.get(a);c.onerror=()=>i(c.error),c.onsuccess=()=>{let d=c.result||{},l=F(d,r.slice(1).join("."),t),p=s.put(l,a);p.onerror=()=>i(p.error),p.onsuccess=()=>n()}})}await this.putValueInStore(s,r[0],t)}async putValueInStore(e,t,s){return new Promise((r,a)=>{let n=e.put(s,t.valueOf());n.onerror=()=>a(n.error),n.onsuccess=()=>r()})}async doUpdate(e){let t=new Map,s=[];for(let{key:r,value:a}of e){if(r instanceof T&&r.isUnparseable()){s.push({key:r.valueOf(),value:a});continue}let n=C(r),i=n[0],c=n.slice(1);t.has(i)||t.set(i,[]),t.get(i).push({path:c,value:a})}try{for(let{key:r,value:a}of s){let n=await this.getObjectStore("readwrite");await this.putValueInStore(n,r,a)}for(let[r,a]of t){let i={...await this.doGet(r)||{}};for(let{path:d,value:l}of a)d.length===0?i=l:i=F(i,d.join("."),l);let c=await this.getObjectStore("readwrite");await this.putValueInStore(c,r,i)}}catch(r){throw this.logger?.error("Error during update:",{error:r}),r}}async doDelete(e){let t=await this.getObjectStore("readwrite");if(e instanceof T&&e.isUnparseable())return new Promise((a,n)=>{let i=t.delete(e.valueOf());i.onerror=()=>n(i.error),i.onsuccess=()=>a(!0)});let s=C(e);if(s.length===1)return new Promise((a,n)=>{let i=t.delete(s[0]);i.onerror=()=>n(i.error),i.onsuccess=()=>a(!0)});let r=s[0];return new Promise((a,n)=>{let i=t.get(r);i.onerror=()=>n(i.error),i.onsuccess=()=>{let c=i.result;if(!c){a(!1);return}let d=D(c,s.slice(0,-1).join(".")),l=s[s.length-1];if(!d||!(l in d)){a(!1);return}if(Array.isArray(d)){let u=parseInt(l,10);isNaN(u)?delete d[l]:d.splice(u,1)}else delete d[l];let p=t.put(c,r);p.onerror=()=>n(p.error),p.onsuccess=()=>a(!0)}})}async doClear(){let e=await this.getObjectStore("readwrite");return new Promise((t,s)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>s(r.error)})}async doKeys(){let t=(await this.getObjectStore()).getAllKeys();return new Promise((s,r)=>{t.onsuccess=()=>{s(t.result)},t.onerror=()=>r(t.error)})}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){try{await this.doClear()}catch(e){throw this.logger?.error(`Error destroying store "${this.STORE_NAME}"`,{error:e}),e}}};var Z=class extends B{constructor(e,t,s,r){super(e,t,s,r)}async initialize(){try{return await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing LocalStorage",{error:e}),e}}async doGet(e){let t=localStorage.getItem(this.name);if(!t)return;let s=JSON.parse(t);return e instanceof T&&e.isUnparseable()?s[e.valueOf()]:D(s,e)}async doSet(e,t){let s=localStorage.getItem(this.name),r=s?JSON.parse(s):{};if(e instanceof T&&e.isUnparseable()){r[e.valueOf()]=t,localStorage.setItem(this.name,JSON.stringify(r));return}let a=F({...r},e,t);localStorage.setItem(this.name,JSON.stringify(a))}async doDelete(e){let t=localStorage.getItem(this.name);if(!t)return!1;let s=JSON.parse(t);if(e instanceof T&&e.isUnparseable()){let c=e.valueOf();return c in s?(delete s[c],localStorage.setItem(this.name,JSON.stringify(s)),!0):!1}let r=C(e),a=r.slice(0,-1).join("."),n=r[r.length-1],i=a?D(s,a):s;return!i||!(n in i)?!1:(delete i[n],localStorage.setItem(this.name,JSON.stringify(s)),!0)}async doUpdate(e){let t=localStorage.getItem(this.name),s=t?JSON.parse(t):{};for(let{key:r,value:a}of e)r instanceof T&&r.isUnparseable()?s[r.valueOf()]=a:F(s,r,a);localStorage.setItem(this.name,JSON.stringify(s))}async doClear(){localStorage.removeItem(this.name)}async doKeys(){let e=localStorage.getItem(this.name);if(!e)return[];let t=JSON.parse(e);return this.getAllKeys(t)}async doHas(e){return await this.doGet(e)!==void 0}getAllKeys(e){return Object.keys(e)}async doDestroy(){await this.doClear()}};var ee=class extends B{storage=new Map;constructor(e,t,s,r){super(e,t,s,r)}async initialize(){try{return this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing MemoryStorage",{error:e}),e}}async doGet(e){let t=this.storage.get(this.name);if(t)return e instanceof T&&e.isUnparseable()?t[e.valueOf()]:D(t,e)}async doSet(e,t){let s=this.storage.get(this.name)||{};if(e instanceof T&&e.isUnparseable()){s[e.valueOf()]=t,this.storage.set(this.name,s);return}let r=F({...s},e,t);this.storage.set(this.name,r)}async doDelete(e){let t=this.storage.get(this.name);if(!t)return!1;if(e instanceof T&&e.isUnparseable()){let i=e.valueOf();return i in t?(delete t[i],this.storage.set(this.name,t),!0):!1}let s=C(e),r=s.slice(0,-1).join("."),a=s[s.length-1],n=r?D(t,r):t;return!n||!(a in n)?!1:(delete n[a],this.storage.set(this.name,t),!0)}async doUpdate(e){let s={...this.storage.get(this.name)||{}};for(let{key:r,value:a}of e)r instanceof T&&r.isUnparseable()?s[r.valueOf()]=a:F(s,r,a);this.storage.set(this.name,s)}async doClear(){this.storage.delete(this.name)}async doKeys(){let e=this.storage.get(this.name);return e?this.getAllKeys(e):[]}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){this.storage.delete(this.name)}getAllKeys(e){return Object.keys(e)}};var K=require("react"),V=new Map;function ze(o,e){let[t,s]=(0,K.useState)(e?.initialValue),[r,a]=(0,K.useState)(!!e?.withLoading),n=(0,K.useRef)(e?.initialValue),i=(0,K.useRef)(e?.equals||((l,p)=>l===p)),c=o.getId(),d=l=>{(n.current===void 0||!i.current(l,n.current))&&(n.current=l,s(l))};return(0,K.useEffect)(()=>{V.has(c)||V.set(c,{lastValue:void 0,listeners:new Set,unsubscribe:null});let l=V.get(c);return l.listeners.add(d),l.lastValue!==void 0?(d(l.lastValue),e?.withLoading&&a(!1)):(e?.withLoading&&a(!0),o.select().then(p=>{l.lastValue=p,l.listeners.forEach(u=>u(p)),e?.withLoading&&a(!1)}).catch(p=>{console.error(`useSelector: \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0438 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0434\u043B\u044F ${c}`,p),e?.withLoading&&a(!1)})),l.unsubscribe||(l.unsubscribe=o.subscribe({notify:p=>{l.lastValue=p,l.listeners.forEach(u=>{try{u(p)}catch(h){console.error(`useSelector: \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u0441\u043B\u0443\u0448\u0430\u0442\u0435\u043B\u044F \u0434\u043B\u044F ${c}`,h)}})}})),()=>{let p=V.get(c);p&&(p.listeners.delete(d),p.listeners.size===0&&(p.unsubscribe&&p.unsubscribe(),V.delete(c)))}},[o,c]),e?.withLoading?{data:t,isLoading:r}:t}var te=require("react"),Le=(o,e)=>{let[t,s]=(0,te.useState)(void 0);return(0,te.useEffect)(()=>{let r=!0;(async()=>{try{let i=await o.getState(),c=e(i);r&&s(c)}catch(i){console.error("Failed to initialize storage value:",i)}})();let n;try{n=o.subscribe(e,i=>{r&&s(i)})}catch(i){console.error("Failed to subscribe to storage:",i),n=()=>{}}return()=>{r=!1,n()}},[o,e]),t};var P=require("react");function re(o,e=1){if(e<=0)throw new Error("Size must be greater than 0");if(!o||!o.length)return[];let t=[],s=o.length,r=0;for(;r<s;)t.push(o.slice(r,r+e)),r+=e;return t}var fe=(o,e)=>{for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(typeof e[t]=="object"&&e[t]!==null&&!Array.isArray(e[t])?((!o[t]||typeof o[t]!="object")&&(o[t]={}),fe(o[t],e[t])):o[t]=e[t])};var j=require("react/jsx-runtime"),se="useSynapseActions \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0438 \u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0430 contextSynapse",We="\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430:";function Ge(o,e){let{loadingComponent:t=null,mergeFn:s=fe}=e||{},r=null,a=!1,n=(async()=>{try{r=await(o instanceof Promise?o:Promise.resolve(o)),a=!0}catch(g){console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 Synapse:",g)}})(),i=(0,P.createContext)(null),c=()=>{let g=(0,P.useContext)(i);if(!g)throw new Error(se);return g.storage},d=()=>{let g=(0,P.useContext)(i);if(!g)throw new Error(se);return g.selectors},l=()=>{let g=(0,P.useContext)(i);if(!g)throw new Error(se);if("actions"in g)return g.actions;throw new Error("useSynapseActions: actions \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0442\u0438\u043F\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u043D\u0430 \u0444\u0443\u043D\u043A\u0446\u0438\u044F createDispatcherFn \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430.")},p=()=>{let g=(0,P.useContext)(i);if(!g)throw new Error(se);if("state$"in g)return g.state$;throw new Error("useSynapseState$: state$ \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0442\u0438\u043F\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u043D\u044B \u0444\u0443\u043D\u043A\u0446\u0438\u0438 createDispatcherFn \u0438 createEffectConfig \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430.")};function u(g){function y({contextProps:m,...f}){let[A,x]=(0,P.useState)(!1),[S,b]=(0,P.useState)(a),O=(0,P.useRef)(`synapse-${r?.storage.name||"initializing"}`);return(0,P.useEffect)(()=>{a||n.then(()=>{b(!0)})},[]),(0,P.useEffect)(()=>{if(!S)return;let q=!0;return(async()=>{try{r&&m&&Object.keys(m).length>0&&await r.storage.update(_=>{s(_,m)}),q&&x(!0)}catch(_){console.error(`[${O.current}] ${We}`,_)}})(),()=>{q=!1}},[m,S]),S?A?(0,j.jsx)(i.Provider,{value:r,children:(0,j.jsx)(g,{...f})}):t||(0,j.jsx)("div",{children:"\u0418\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430..."}):t||(0,j.jsx)("div",{children:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430..."})}let E=g.displayName||g.name||"Component";return y.displayName=`SynapseContext(${E})`,y}return{contextSynapse:u,useSynapseStorage:c,useSynapseSelectors:d,useSynapseActions:l,useSynapseState$:p,cleanupSynapse:async()=>(await n,r?.destroy()||Promise.resolve())}}var me=require("rxjs"),ne=class{constructor(e){this.options=e;this.storage=e.storage,this.middlewareAPI={getState:()=>this.storage.getState(),dispatch:async t=>(this.actions$.next(t),t.payload),storage:this.storage,actions$:this.actions,actions:this.dispatch,watchers:this.watchers,findActionByType:t=>this.findActionByType(t),findWatcherByType:t=>this.findWatcherByType(t)},e.middlewares&&e.middlewares.length>0&&this.use(...e.middlewares)}actions$=new me.Subject;actions=this.actions$.asObservable();dispatch={};watchers={};storage;middlewareFunctions=[];middlewareAPI;use(...e){for(let t=0;t<e.length;t++)try{let s=e[t](this.middlewareAPI);this.middlewareFunctions.push(s)}catch(s){console.error(`Error initializing middleware [${t}]:`,s)}return this}getActions(){return this.dispatch}getTypedDispatch(){return this.dispatch}getTypedWatchers(){return this.watchers}findActionByType(e){return Object.values(this.dispatch).find(t=>t.actionType.split(`[${this.storage.name}]`)[1]===e)}findWatcherByType(e){return Object.values(this.watchers).find(t=>t.actionType===e)}createAction(e,t){let s=`[${this.storage.name}]${e.type}`,r=null,a=null,n=async i=>{let c=[i];if(t?.memoize&&r&&a&&t.memoize(c,r,a))return a;let d={type:s,meta:e.meta},l;if(this.middlewareFunctions.length>0){let p=async u=>t?.worker?this.executeInWorker(t.worker,s,c,e.action):Promise.resolve(e.action(i));for(let u=this.middlewareFunctions.length-1;u>=0;u--){let h=this.middlewareFunctions[u],g=p;p=async y=>h(async m=>g(m))(y)}l=await p(d)}else t?.worker?l=await this.executeInWorker(t.worker,s,c,e.action):l=await e.action(i);return d.payload=l,r=[...c],a=l,this.actions$.next(d),l};return n._type="dispatch",Object.defineProperty(n,"actionType",{value:s,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(n,"meta",{value:e.meta,writable:!1,enumerable:!0}),n}createWatcher(e){let t=`[${this.storage.name}]${e.type}`,s=new me.Subject,r,a=this.storage.subscribe(e.selector,i=>{if(!e.shouldTrigger||e.shouldTrigger(r,i)){let c={type:t,payload:i,meta:e.meta};this.actions$.next(c),s.next(c),r=i}}),n=()=>s.asObservable();return n._type="watchers",Object.defineProperty(n,"actionType",{value:t,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(n,"meta",{value:e.meta,writable:!1,enumerable:!0}),Object.defineProperty(n,"unsubscribe",{value:a,writable:!1,enumerable:!0}),n}async executeInWorker(e,t,s,r){return new Promise((a,n)=>{let i=`${t}_${Date.now()}_${Math.random()}`,c=d=>{d.data.requestId===i&&(e.removeEventListener("message",c),d.data.error?n(new Error(d.data.error)):a(d.data.result))};e.addEventListener("message",c),e.postMessage({type:t,args:s,requestId:i}),setTimeout(()=>{e.removeEventListener("message",c),n(new Error(`Worker execution timeout for action: ${t}`))},3e4)})}};function Qe(o,e){let t=new ne(o),s=e(o.storage,{createAction:(r,a)=>t.createAction(r,a),createWatcher:r=>t.createWatcher(r)});for(let[r,a]of Object.entries(s))if(typeof a=="function"){let n=a._type;t[n][r]=a}return t}function Ie(o,e){let t={};return[...new Set([...Object.keys(o),...Object.keys(e)])].forEach(r=>{if(r in o&&r in e)if(typeof o[r]=="object"&&o[r]!==null&&typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(o[r])&&!Array.isArray(e[r])){let a=Ie(o[r],e[r]);Object.keys(a).length>0&&(t[r]=a)}else JSON.stringify(o[r])!==JSON.stringify(e[r])&&(t[r]={PREV:o[r],NEXT:e[r]});else r in o?t[r]={PREV:o[r],NEXT:void 0}:t[r]={PREV:void 0,NEXT:e[r]}}),t}var Je=(o={})=>{let e={action:"\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435",prevState:"\u041F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",nextState:"\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",duration:"\u0414\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",error:"\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0438",diff:"\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F",changesCount:"\u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439",showFullState:"\u041F\u043E\u043B\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435"},t={collapsed:!1,duration:!0,diff:!1,showFullState:!0,translations:e,colors:{title:"#3498db",prevState:"#9E9E9E",fullState:"#008a15",action:"#03A9F4",nextState:"#4CAF50",error:"#F20404",diff:"#9C27B0"}},s={...t,...o,translations:{...e,...o.translations||{}},colors:{...t.colors,...o.colors||{}}},{collapsed:r,duration:a,colors:n,translations:i}=s;return c=>d=>async l=>{let p=Date.now(),u=await c.getState();try{let h=await d(l),g=await c.getState(),E=Date.now()-p,m=`${l.type}`;if((r?console.groupCollapsed:console.group)(`%c ${m}`,`color: ${n.title}; font-weight: bold`),console.log(`%c ${i.action}:`,`color: ${n.action}; font-weight: bold`,l),s.diff){let A=Ie(u,g),x=Object.keys(A).length;console.log(`%c ${i.diff} (${i.changesCount}: ${x}):`,`color: ${n.diff}; font-weight: bold`,A)}return s.showFullState&&(console.groupCollapsed(`%c ${i.showFullState}`,`color: ${n.fullState}; font-weight: bold`),console.log(`%c ${i.prevState}:`,`color: ${n.prevState}; font-weight: bold`,u),console.log(`%c ${i.nextState}:`,`color: ${n.nextState}; font-weight: bold`,g),console.groupEnd()),a&&console.log(`%c ${i.duration}: %c ${E}ms`,"font-weight: bold","color: #4CAF50"),console.groupEnd(),h}catch(h){throw console.error(`%c ${i.error}:`,`color: ${n.error}; font-weight: bold`,l.type,h),h}}};var R=require("rxjs"),w=require("rxjs/operators");var Se=require("rxjs"),$=require("rxjs/operators");var Oe=(o,e,t,s=0)=>{let r=re(e,t).map(a=>(0,Se.of)(a).pipe((0,$.delay)(s),(0,$.mergeMap)(o)));return(0,Se.of)(...r).pipe((0,$.concatAll)(),(0,$.toArray)())};var ae=require("rxjs"),Me=require("rxjs/operators");var Fe=(o,e,t,s=0)=>(0,ae.forkJoin)(re(e,t).map((r,a)=>(0,ae.timer)(a*s).pipe((0,Me.mergeMap)(()=>o(r)))));function Ye(o){let{actionType:e}=o;return e?t=>t.pipe((0,w.filter)(s=>s!==void 0&&s.type===e)):(console.warn("ofType: Action function does not have actionType property",o),(0,w.filter)(()=>!1))}function Xe(o){let e=o.map(t=>t.actionType).filter(Boolean);return e.length===0?(console.warn("ofTypes: No valid action types found in array",o),(0,w.filter)(()=>!1)):t=>t.pipe((0,w.filter)(s=>s!==void 0&&e.includes(s.type)))}function Ze(o){return e=>{let t=o.map(r=>r.actionType).filter(Boolean);if(t.length===0)return console.warn("ofTypesWaitAll: No valid action types found in array",o),(0,R.of)([]);let s=t.map((r,a)=>e.pipe((0,w.filter)(n=>n.type===r),(0,w.take)(1),(0,w.map)(n=>({index:a,action:n}))));return(0,R.combineLatest)(s).pipe((0,w.map)(r=>(r.sort((a,n)=>a.index-n.index),r.map(a=>a.action))))}}function et(o,...e){return o.pipe((0,w.map)(t=>e.map(s=>s(t))))}function tt(o,e){return o.pipe((0,w.map)(t=>{let s={};for(let[r,a]of Object.entries(e))s[r]=a(t);return s}))}function rt({validator:o,apiCall:e}){return(0,R.pipe)((0,w.switchMap)(t=>{let s=()=>e(t,{chunkRequest:Fe,chunkRequestConsistent:Oe});if(!o)return s();let r=o(t),{conditions:a,skipAction:n}=r;return a.every(Boolean)?s():Array.isArray(n)?(0,R.of)(...n?.filter(Boolean).map(c=>typeof c=="function"?c():c)):(0,R.of)(typeof n=="function"?n():n)}))}var H=class{constructor(e,t={},s,r={},a={}){this.storage=e;this.externalStates=t;this.dispatchers=s;this.services=r;this.config=a;this.subscribeToDispatchers(),this.state$=new R.Observable(n=>{this.storage.getState().then(c=>n.next(c));let i=this.storage.subscribeToAll(()=>{this.storage.getState().then(c=>n.next(c))});return()=>i()}).pipe((0,w.share)())}effects=[];subscriptions=[];running=!1;action$=new R.Subject;state$;subscribeToDispatchers(){for(let[e,t]of Object.entries(this.dispatchers)){let s=t.actions.subscribe(r=>{this.action$.next(r)});this.subscriptions.push(s)}}add(e){return this.effects.push(e),this.running&&this.subscribeToEffect(e),this}addEffects(e){return e.forEach(t=>this.add(t)),this}start(){return this.running?this:(this.effects.forEach(e=>this.subscribeToEffect(e)),this.running=!0,this)}stop(){return this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.running=!1,this}subscribeToEffect(e){try{let s=e(this.action$.asObservable(),this.state$,this.externalStates,this.dispatchers,this.services,this.config).pipe((0,w.catchError)(r=>(console.error("Error in effect:",r),(0,R.of)(null)))).subscribe(r=>{if(r!=null&&typeof r=="function")try{r()}catch(a){console.error("Error calling effect result function:",a)}});this.subscriptions.push(s)}catch(t){console.error("Error setting up effect:",t)}}};function st(o){return o}function nt(o){return o}function at(...o){return(e,t,s,r,a,n)=>{let i=o.map(c=>{try{return c(e,t,s,r,a,n)}catch(d){return console.error("Error in one of combined effects:",d),(0,R.of)(null)}});return(0,R.merge)(...i)}}async function Be(o){let e=o.createStorageFn?await o.createStorageFn():o.storage,t=[],s={storage:e,selectors:{},destroy:async()=>{for(let i of t)await i()}};t.push(()=>e.destroy());let r,a,n;if(o.createSelectorsFn)try{a=new U(e);let i=o.externalSelectors||{};s.selectors=o.createSelectorsFn(a,i),typeof a.destroy=="function"&&t.push(()=>a.destroy())}catch(i){console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F selectors:",i)}if(o.createDispatcherFn&&(r=o.createDispatcherFn(e),s.dispatcher=r,r&&"dispatch"in r&&(s.actions=r.dispatch,typeof r.destroy=="function"&&t.push(()=>r.destroy()))),o.createEffectConfig&&r)try{let{dispatchers:i,api:c,config:d,externalStates:l}=o.createEffectConfig(r),p=l||{};n=new H(e,p,i,c,d),Array.isArray(o.effects)&&o.effects.forEach(u=>{n&&n.add(u)}),n.start(),s.state$=n.state$,t.push(()=>{n&&n.stop()})}catch(i){console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u043C\u043E\u0434\u0443\u043B\u044F \u044D\u0444\u0444\u0435\u043A\u0442\u043E\u0432:",i)}return s}0&&(module.exports={ApiClient,Dispatcher,EffectsModule,IndexedDBStorage,LocalStorage,MemoryStorage,ResponseFormat,SelectorModule,StorageEvents,StoragePluginModule,apiLogger,broadcastMiddleware,combineEffects,createDispatcher,createEffect,createEffectBase,createSynapse,createSynapseCtx,createUniqueId,headersToObject,loggerDispatcherMiddleware,ofType,ofTypes,ofTypesWaitAll,selectorMap,selectorObject,useSelector,useStorageSubscribe,validateMap});
package/dist/react.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";var b=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var D=(t,e)=>{for(var o in e)b(t,o,{get:e[o],enumerable:!0})},M=(t,e,o,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of z(e))!F.call(t,r)&&r!==o&&b(t,r,{get:()=>e[r],enumerable:!(l=$(e,r))||l.enumerable});return t};var N=t=>M(b({},"__esModule",{value:!0}),t);var B={};D(B,{createSynapseCtx:()=>q,useSelector:()=>_,useStorageSubscribe:()=>j});module.exports=N(B);var T=require("react"),y=new Map;function _(t,e){let[o,l]=(0,T.useState)(e?.initialValue),[r,u]=(0,T.useState)(!!e?.withLoading),p=(0,T.useRef)(e?.initialValue),a=(0,T.useRef)(e?.equals||((s,i)=>s===i)),S=t.getId(),f=s=>{(p.current===void 0||!a.current(s,p.current))&&(p.current=s,l(s))};return(0,T.useEffect)(()=>{y.has(S)||y.set(S,{lastValue:void 0,listeners:new Set,unsubscribe:null});let s=y.get(S);return s.listeners.add(f),s.lastValue!==void 0?(f(s.lastValue),e?.withLoading&&u(!1)):(e?.withLoading&&u(!0),t.select().then(i=>{s.lastValue=i,s.listeners.forEach(d=>d(i)),e?.withLoading&&u(!1)}).catch(i=>{console.error(`useSelector: \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0438 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0434\u043B\u044F ${S}`,i),e?.withLoading&&u(!1)})),s.unsubscribe||(s.unsubscribe=t.subscribe({notify:i=>{s.lastValue=i,s.listeners.forEach(d=>{try{d(i)}catch(A){console.error(`useSelector: \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u0441\u043B\u0443\u0448\u0430\u0442\u0435\u043B\u044F \u0434\u043B\u044F ${S}`,A)}})}})),()=>{let i=y.get(S);i&&(i.listeners.delete(f),i.listeners.size===0&&(i.unsubscribe&&i.unsubscribe(),y.delete(S)))}},[t,S]),e?.withLoading?{data:o,isLoading:r}:o}var x=require("react"),j=(t,e)=>{let[o,l]=(0,x.useState)(void 0);return(0,x.useEffect)(()=>{let r=!0;(async()=>{try{let a=await t.getState(),S=e(a);r&&l(S)}catch(a){console.error("Failed to initialize storage value:",a)}})();let p;try{p=t.subscribe(e,a=>{r&&l(a)})}catch(a){console.error("Failed to subscribe to storage:",a),p=()=>{}}return()=>{r=!1,p()}},[t,e]),o};var c=require("react");var R=(t,e)=>{for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(typeof e[o]=="object"&&e[o]!==null&&!Array.isArray(e[o])?((!t[o]||typeof t[o]!="object")&&(t[o]={}),R(t[o],e[o])):t[o]=e[o])};var m=require("react/jsx-runtime"),h="useSynapseActions \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0438 \u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0430 contextSynapse",k="\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430:";function q(t,e){let{loadingComponent:o=null,mergeFn:l=R}=e||{},r=null,u=!1,p=(async()=>{try{r=await(t instanceof Promise?t:Promise.resolve(t)),u=!0}catch(n){console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 Synapse:",n)}})(),a=(0,c.createContext)(null),S=()=>{let n=(0,c.useContext)(a);if(!n)throw new Error(h);return n.storage},f=()=>{let n=(0,c.useContext)(a);if(!n)throw new Error(h);return n.selectors},s=()=>{let n=(0,c.useContext)(a);if(!n)throw new Error(h);if("actions"in n)return n.actions;throw new Error("useSynapseActions: actions \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0442\u0438\u043F\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u043D\u0430 \u0444\u0443\u043D\u043A\u0446\u0438\u044F createDispatcherFn \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430.")},i=()=>{let n=(0,c.useContext)(a);if(!n)throw new Error(h);if("state$"in n)return n.state$;throw new Error("useSynapseState$: state$ \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0442\u0438\u043F\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u043D\u044B \u0444\u0443\u043D\u043A\u0446\u0438\u0438 createDispatcherFn \u0438 createEffectConfig \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430.")};function d(n){function w({contextProps:g,...I}){let[O,W]=(0,c.useState)(!1),[P,L]=(0,c.useState)(u),V=(0,c.useRef)(`synapse-${r?.storage.name||"initializing"}`);return(0,c.useEffect)(()=>{u||p.then(()=>{L(!0)})},[]),(0,c.useEffect)(()=>{if(!P)return;let E=!0;return(async()=>{try{r&&g&&Object.keys(g).length>0&&await r.storage.update(C=>{l(C,g)}),E&&W(!0)}catch(C){console.error(`[${V.current}] ${k}`,C)}})(),()=>{E=!1}},[g,P]),P?O?(0,m.jsx)(a.Provider,{value:r,children:(0,m.jsx)(n,{...I})}):o||(0,m.jsx)("div",{children:"\u0418\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430..."}):o||(0,m.jsx)("div",{children:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430..."})}let v=n.displayName||n.name||"Component";return w.displayName=`SynapseContext(${v})`,w}return{contextSynapse:d,useSynapseStorage:S,useSynapseSelectors:f,useSynapseActions:s,useSynapseState$:i,cleanupSynapse:async()=>(await p,r?.destroy()||Promise.resolve())}}0&&(module.exports={createSynapseCtx,useSelector,useStorageSubscribe});