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/index.js CHANGED
@@ -1 +1 @@
1
- var ce={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 le(o){return`${o?`${o}|`:""}${Math.random().toString(36).substring(2,9)+Date.now().toString(36)}`}function de(o){let e={};return o.forEach((t,r)=>{e[r.toLowerCase()]=t}),e}function N(o={},e={}){return{...o,...e,getFromStorage:o.getFromStorage||(t=>{try{let r=localStorage.getItem(t);return r?JSON.parse(r):void 0}catch(r){console.warn(`[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0447\u0442\u0435\u043D\u0438\u044F \u0438\u0437 localStorage: ${r}`);return}}),getCookie:o.getCookie||(t=>{try{let r=document.cookie.match(new RegExp(`(?:^|; )${t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")}=([^;]*)`));return r?decodeURIComponent(r[1]):void 0}catch(r){console.warn(`[API] \u041E\u0448\u0438\u0431\u043A\u0430 \u0447\u0442\u0435\u043D\u0438\u044F cookie: ${r}`);return}})}}async function ue(o,e){let t=new Headers,r=e||N({},{});if(o)try{t=await Promise.resolve(o(t,r))}catch(s){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",s)}return t}function pe(o,e){return async(t,r)=>{let s=new Headers(t);if(o)try{s=await Promise.resolve(o(s,r))}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{s=await Promise.resolve(e(s,r))}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 s}}var k=(n=>(n.Json="json",n.Blob="blob",n.ArrayBuffer="arrayBuffer",n.Text="text",n.FormData="formData",n.Raw="raw",n))(k||{});function ge(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 X(o){let e=o.get("content-type")||"",t=o.get("content-disposition")||"",r=e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"),s=t.includes("attachment")||t.includes("filename=");return r||s}function Fe(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 he(o){let e=o.get("content-type")||"",t=o.get("content-disposition")||"",r=o.get("content-length");return X(o)?{filename:Fe(o),contentType:e,contentDisposition:t,size:r?parseInt(r,10):void 0}:void 0}async function Be(o,e){let t=e,r=o.headers.get("content-type")||"";!t&&r&&(X(o.headers)?t="blob":t=ge(r)),t||(t="json");try{let s;switch((t==="blob"||t==="arrayBuffer")&&(s=he(o.headers)),t){case"json":try{let n=await o.json();return o.ok?{data:n,fileMetadata:s}:{error:n,fileMetadata:s}}catch{let i=await o.text();return o.ok?{data:i,fileMetadata:s}:{error:i,fileMetadata:s}}case"text":{let n=await o.text();return o.ok?{data:n,fileMetadata:s}:{error:n,fileMetadata:s}}case"blob":{let n=await o.blob();return o.ok?{data:n,fileMetadata:s}:{error:n,fileMetadata:s}}case"arrayBuffer":{let n=await o.arrayBuffer();return o.ok?{data:n,fileMetadata:s}:{error:n,fileMetadata:s}}case"formData":{let n=await o.formData();return o.ok?{data:n,fileMetadata:s}:{error:n,fileMetadata:s}}case"raw":return o.ok?{data:o,fileMetadata:s}:{error:o,fileMetadata:s};default:let a=await o.blob();return o.ok?{data:a,fileMetadata:s}:{error:a,fileMetadata:s}}}catch(s){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})`,s),o.ok?{data:void 0}:{error:s}}}function ye(o){let{baseUrl:e,timeout:t=3e4,fetchFn:r=fetch,credentials:s="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,v=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(C=>m.searchParams.append(S,String(C))):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 R,w=new Promise((S,b)=>{g&&(R=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=r(m.toString(),{method:d,headers:i,body:f,signal:h,credentials:s}),b=await Promise.race([S,w]),{data:C,error:M,fileMetadata:ie}=await Be(b,v);return{data:C,error:M,ok:b.ok,status:b.status,statusText:b.statusText,headers:b.headers,fileDownloadResult:ie}}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{R&&window.clearTimeout(R)}}}function fe(o,e=[]){let t={};return!o||e.length===0||e.forEach(r=>{o.has(r)&&(t[r]=o.get(r)||"")}),t}var U=class{constructor(e,t,r,s,a,n){this.name=e;this.queryStorage=t;this.configCurrentEndpoint=r;this.cacheableHeaderKeys=s;this.globalCacheConfig=a;this.baseQueryConfig=n;this.prepareHeaders=pe(n.prepareHeaders,r.prepareHeaders),this.queryFunction=ye({baseUrl:n.baseUrl,fetchFn:n.fetchFn,timeout:n.timeout,credentials:n.credentials}),this.cacheableHeaders=[...s||[],...r.includeCacheableHeaderKeys||[]].filter(i=>!r.excludeCacheableHeaderKeys?.includes(i)),this.meta.name=e,this.meta.tags=r.tags??this.meta.tags,this.meta.invalidatesTags=r.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 r=le(this.name),s=new AbortController,a=new Set,n={status:"idle",requestParams:e,headers:{},error:void 0,data:void 0,fromCache:!1},i=N({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 ue(this.prepareHeaders,i),h=fe(u,t?.cacheableHeaderKeys?t.cacheableHeaderKeys:this.cacheableHeaders),g=this.queryStorage.shouldCache(this.configCurrentEndpoint,t),[y,v]=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),R={...t,signal:s.signal},w=await this.queryFunction(f,R,u);if(w.ok){let{headers:S,...b}=w;if(g){let C=this.queryStorage.createCacheConfig(this.configCurrentEndpoint);await this.queryStorage.setCachedResult(y,{...b,headers:de(S)},C,v??{},this.configCurrentEndpoint.tags??[],this.configCurrentEndpoint.invalidatesTags??[])}c({fromCache:!1,status:"success",data:w.data,error:void 0,headers:w.headers,requestParams:e}),this.endpointSubscribers.forEach(C=>{let M={status:"success",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};C(M)}),l({...w,fromCache:!1})}else c({fromCache:!1,status:"error",data:void 0,error:w.error,headers:w.headers,requestParams:e}),this.endpointSubscribers.forEach(S=>{let b={status:"error",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:w.error};S(b)}),p(w.error)}}catch(u){c({fromCache:!1,status:"error",data:void 0,error:u,headers:void 0,requestParams:e}),p(u)}});return{id:r,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:()=>{s&&!s.signal.aborted&&s.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 D=class{static createMetadata(e=0,t=[]){let r=Date.now(),s=e>0?r+e:1/0;return{createdAt:r,updatedAt:r,expiresAt:s,tags:t,createdAtDateTime:this.formatDateTime(r),updatedAtDateTime:this.formatDateTime(r),expiresAtDateTime:s===1/0?"never":this.formatDateTime(s)}}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 r=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join("&");return[new T(`${e}_${r}`,!0),t]}static hasAnyTag(e,t=[]){return!e.tags||!t.length?!1:t.some(r=>e.tags?.includes(r))}};var V=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 D.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(D.isExpired(t.metadata)){await this.storage.delete(e);return}let r={...t,metadata:D.updateMetadata(t.metadata)};return await this.storage.set(e,r),t.data}async setCachedResult(e,t,r,s,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=D.createMetadata(r.ttl,a),c={data:t,metadata:i,params:s};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 r=e.cache;t={...t,...r}}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 r of t){let s=await this.storage.get(r);s&&D.hasAnyTag(s.metadata,e)&&await this.storage.delete(r)}}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 r=await this.storage.get(t);r&&D.isExpired(r.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 me=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 V(this.storageExternal,this.globalCacheConfig).initialize(),await this.initializeEndpoints(),this}async initializeEndpoints(){let e=r=>r,t=await this.createEndpoints(e)||{};for(let[r,s]of Object.entries(t)){let a=r;this.endpoints[a]=new U(r,this.queryStorage,s,this.cacheableHeaderKeys,this.globalCacheConfig,this.baseQueryConfig)}}getEndpoints(){return this.endpoints}async request(e,t,r){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,r).wait()}catch(n){throw ce.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 x=!1,F=new Map;function Se(o){let e=0;if(o.length===0)return e.toString(36);for(let t=0;t<o.length;t++){let r=o.charCodeAt(t);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function A(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(!A(o[t],e[t]))return!1;return!0}if(typeof o=="object"&&typeof e=="object"){let t=Object.keys(o),r=Object.keys(e);return t.length!==r.length?!1:t.every(s=>Object.prototype.hasOwnProperty.call(e,s)?A(o[s],e[s]):!1)}return!1}function Te(o,e=A){let t,r,s=!1;return function(n){if(!s||t!==n){let i=o(n);(!s||!e(i,r))&&(r=i),t=n,s=!0}return r}}var j=class{constructor(e,t,r=A,s){this.name=e;this.equals=r;this.logger=s;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t),x&&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)){x&&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 x&&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 x&&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})}),()=>{x&&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(){x&&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}},H=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,x&&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,x&&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 n=t.toString();a=Se(n)}else{let n=t.map(c=>c.getId()).join("_"),i=r.toString();a=Se(n+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||{},n=a.name||this.generateName(s,e,s?void 0:t);if(this.localSelectorCache.has(n))return x&&console.log(`[${this.storageName}] Reusing cached selector: ${n}`),this.localSelectorCache.get(n).api;if(F.has(n)){let l=F.get(n);return l.refCount++,x&&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(s){let l=Te(e,a.equals||A),p=this.createSimpleSelector(l,{...a,name:n,equals:a.equals||A});i=p.api,d=p.unsubscribeFunctions}else{c=e;let l=this.createCombinedSelector(c,t,{...a,name:n,equals:a.equals||A});i=l.api,d=l.unsubscribeFunctions}return this.localSelectorCache.set(n,{api:i,dependencies:c,unsubscribeFunctions:d}),F.set(n,{api:i,refCount:1,unsubscribeFunctions:d}),x&&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){x&&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 j(t.name,r,t.equals||A,this.logger),a=s.getId();this.subscriptions.set(a,s);let i=[this.source.subscribeToAll(async c=>{c?.type==="storage:update"&&(x&&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=Te(p=>t(...p),r.equals||A),a=async()=>{let p=await Promise.all(e.map(u=>u.select()));return s(p)},n=new j(r.name,a,r.equals||A,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(){x&&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=F.get(t);r&&(r.refCount--,r.refCount<=0&&(r.unsubscribeFunctions.forEach(s=>s()),F.delete(t),x&&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}`)))}),x&&console.log(`[${this.storageName}] \u0423\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D`)}};var be=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 a of this.plugins.values())if(a.onBeforeSet)try{r=await a.onBeforeSet(r,s)}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 r}async executeAfterSet(e,t,r){let s=t,a=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterSet(e,s,a));for(let n of this.plugins.values())if(n.onAfterSet)try{s=await n.onAfterSet(e,s,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 s}async executeBeforeGet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeGet(r,s));for(let a of this.plugins.values())if(a.onBeforeGet)try{r=await a.onBeforeGet(r,s)}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 r}async executeAfterGet(e,t,r){let s=t,a=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterGet(e,s,a)),console.log("executeAfterGet",e,t,r);for(let n of this.plugins.values())if(n.onAfterGet)try{s=await n.onAfterGet(e,s,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 s}async executeBeforeDelete(e,t){let r=!0,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeDelete(e,s));for(let a of this.plugins.values())if(a.onBeforeDelete)try{r=await a.onBeforeDelete(e,s)&&r}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 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(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${s.name} onAfterDelete`,{key:e,error:a}),a}}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 Z=(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))(Z||{});var _=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 Ke(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:r,value:s})=>{o.storage.notifySubscribers(r,s)}));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 r=await o.storage.doGet(t.key);o.storage.notifySubscribers(t.key,r)}break;case"update":if(Array.isArray(t?.value)){for(let{key:r}of t.value){let s=await o.storage.doGet(r);o.storage.notifySubscribers(r,s)}o.storage.notifySubscribers("*",{type:"storage:update",key:t.value.map(({key:r})=>r),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 we=o=>{let{storageName:e,storageType:t}=o,r=`${t}-${e}`,s=new _(r,{debug:!0});return{name:"broadcast",setup:a=>(t==="memory"&&(s.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()}}}),s.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)}})),s.subscribe(async n=>{let{type:i,payload:c}=n;t==="memory"?await Ke(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)&&s.broadcast(i.type,i),c},cleanup:()=>{s.close()}}};var xe=(o={})=>{let e=o.batchSize??10,t=o.batchDelay??10,r=new Map,s=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=s.get(u);h&&(globalThis.clearTimeout(h),s.delete(u))},d=(u,h)=>{let g=globalThis.setTimeout(h,t);s.set(u,g)},l=async(u,h,g)=>{let y=r.get(u);if(!(!y||y.length===0)){r.delete(u),c(u);try{let v=y.map(f=>f.action),m=i(v);console.log(`\u{1F504} Batching ${u}: ${y.length} actions -> ${m.length} merged`,{original:v.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 R=await g(f);y.filter(S=>S.action.type===f.type&&S.action.key?.toString()===f.key?.toString()).forEach(S=>S.resolve(R))}catch(R){y.filter(S=>S.action.type===f.type&&S.action.key?.toString()===f.key?.toString()).forEach(S=>S.reject(R))}}catch(v){y.forEach(m=>m.reject(v))}}},p=async(u,h,g)=>new Promise((y,v)=>{let m=n(u),f=r.get(m);f||(f=[],r.set(m,f)),f.push({action:u,resolve:y,reject:v,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()=>{s.forEach(u=>globalThis.clearTimeout(u)),s.clear(),r.clear()},reducer:u=>h=>async g=>a(g)?p(g,u,h):h(g)}};var ve=(o={})=>{let{comparator:e=(s,a)=>{if(s===a)return!0;if(typeof s!="object"||typeof a!="object"||s===null||a===null)return s===a;let n=Object.keys(s),i=Object.keys(a);return n.length!==i.length?!1:n.every(c=>Object.prototype.hasOwnProperty.call(a,c)&&s[c]===a[c])},segments:t=[]}=o,r=new Map;return{name:"shallow-compare",setup:s=>{},reducer:s=>a=>async n=>{if(n.type!=="set"||t.length&&!t.includes(n.metadata?.segment??"default"))return a(n);let i=n.key,c=r.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 r.set(i,d),l}}};var z=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 a=await this.api.storage.doGet("");return Object.keys(a||{}).length>0?a:s.value?(await this.api.storage.doSet("",s.value),this.api.storage.doGet("")):a}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 a={...s,metadata:{...s.metadata,processed:!0,timestamp:s.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(r)(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 E(o){return o instanceof T&&o.isUnparseable()?[o.toString()]:o.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function P(o,e){return E(e).reduce((r,s)=>r===void 0?void 0:r[s],o)}function I(o,e,t){if(e==="")return t;let r=E(e);if(e instanceof T&&e.isUnparseable())return o[e.toString()]=t,o;let s=r.pop(),a=r.reduce((n,i)=>{let c=r[r.indexOf(i)+1],d=!Number.isNaN(Number(c));return i in n||(n[i]=d?[]:{}),n[i]},o);return a[s]=t,o}var O=class o{constructor(e,t,r,s){this.config=e;this.pluginExecutor=t;this.eventEmitter=r;this.logger=s;this.name=e.name,this.middlewareModule=new z({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={})=>xe(e),shallowCompare:(e={})=>ve(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,a=await this.middlewareModule.dispatch({type:"set",key:e,value:s,metadata:r}),n=a?.__metadata?.valueNotChanged===!0,i;if(n&&a?.__metadata?.originalValue!==void 0?i=a.__metadata.originalValue:i=await this.pluginExecutor?.executeAfterSet(e,a,r)??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(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 a=this.findChangedPaths(r,s);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(s[u],h)??s[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(r[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=P(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 r=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:r,changedPaths:a}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:r,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 r=!1;return this.subscribers.get(e).add(t),this.get(e).then(s=>{try{r||(r=!0,t(s))}catch(a){this.logger?.error("Error in initial callback",{key:e,error:a})}}),()=>{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 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 r=[],s=(a="")=>({get:(n,i)=>{if(typeof i=="symbol")return Reflect.get(n,i);let c=a?`${a}.${i}`:i;return r.push(c),new Proxy({},s(c))},has:(n,i)=>!0,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0}),apply:(n,i,c)=>new Proxy(()=>{},s(a))});try{e(new Proxy(t,s()))}catch{}return r.length===0?"":(r.sort((a,n)=>n.length-a.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(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:r,error:i})}})}findChangedPaths(e,t,r="",s=new Set,a=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(a.has(e))return s;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=r?`${r}.${i}`:i;c&&d&&typeof c=="object"&&typeof d=="object"&&!Array.isArray(c)&&!Array.isArray(d)?this.findChangedPaths(c,d,l,s,a):Array.isArray(c)&&Array.isArray(d)?this.isEqual(c,d)||s.add(l):this.isEqual(c,d)||s.add(l)}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 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:s,error:i}),t(n)}};return s?this.subscribeByKey(s,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 ee=class o{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){o.instances.has(e)||o.instances.set(e,new o(e,t,r));let s=o.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 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)},s.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 r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{this.logger?.debug(`Database "${this.dbName}" deleted successfully`),o.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}},te=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 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}),s(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)}),r(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(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)}},re=class o extends O{DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,r,s){super(e,t,r,s);let a=e.options;this.DB_NAME=a.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=a.dbVersion||1,this.dbManager=ee.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 a=await this.getCurrentDBVersion(e)||1,n=new te(e,a,r),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,r);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 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,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),{});s(d)},c.onerror=()=>a(c.error)}});if(e instanceof T&&e.isUnparseable())return new Promise((s,a)=>{let n=t.get(e.valueOf());n.onerror=()=>a(n.error),n.onsuccess=()=>s(n.result)});let r=E(e);if(r.length>1){let s=r[0];return new Promise((a,n)=>{let i=t.get(s);i.onerror=()=>n(i.error),i.onsuccess=()=>{let c=i.result;if(!c){a(void 0);return}let d=P(c,r.slice(1).join("."));a(d)}})}return new Promise((s,a)=>{let n=t.get(r[0]);n.onerror=()=>a(n.error),n.onsuccess=()=>s(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 r=await this.getObjectStore("readwrite");if(e instanceof T&&e.isUnparseable()){await this.putValueInStore(r,e.valueOf(),t);return}let s=E(e);if(s.length>1){let a=s[0];return new Promise((n,i)=>{let c=r.get(a);c.onerror=()=>i(c.error),c.onsuccess=()=>{let d=c.result||{},l=I(d,s.slice(1).join("."),t),p=r.put(l,a);p.onerror=()=>i(p.error),p.onsuccess=()=>n()}})}await this.putValueInStore(r,s[0],t)}async putValueInStore(e,t,r){return new Promise((s,a)=>{let n=e.put(r,t.valueOf());n.onerror=()=>a(n.error),n.onsuccess=()=>s()})}async doUpdate(e){let t=new Map,r=[];for(let{key:s,value:a}of e){if(s instanceof T&&s.isUnparseable()){r.push({key:s.valueOf(),value:a});continue}let n=E(s),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:s,value:a}of r){let n=await this.getObjectStore("readwrite");await this.putValueInStore(n,s,a)}for(let[s,a]of t){let i={...await this.doGet(s)||{}};for(let{path:d,value:l}of a)d.length===0?i=l:i=I(i,d.join("."),l);let c=await this.getObjectStore("readwrite");await this.putValueInStore(c,s,i)}}catch(s){throw this.logger?.error("Error during update:",{error:s}),s}}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 r=E(e);if(r.length===1)return new Promise((a,n)=>{let i=t.delete(r[0]);i.onerror=()=>n(i.error),i.onsuccess=()=>a(!0)});let s=r[0];return new Promise((a,n)=>{let i=t.get(s);i.onerror=()=>n(i.error),i.onsuccess=()=>{let c=i.result;if(!c){a(!1);return}let d=P(c,r.slice(0,-1).join(".")),l=r[r.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,s);p.onerror=()=>n(p.error),p.onsuccess=()=>a(!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 se=class extends O{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 T&&e.isUnparseable()?r[e.valueOf()]:P(r,e)}async doSet(e,t){let r=localStorage.getItem(this.name),s=r?JSON.parse(r):{};if(e instanceof T&&e.isUnparseable()){s[e.valueOf()]=t,localStorage.setItem(this.name,JSON.stringify(s));return}let a=I({...s},e,t);localStorage.setItem(this.name,JSON.stringify(a))}async doDelete(e){let t=localStorage.getItem(this.name);if(!t)return!1;let r=JSON.parse(t);if(e instanceof T&&e.isUnparseable()){let c=e.valueOf();return c in r?(delete r[c],localStorage.setItem(this.name,JSON.stringify(r)),!0):!1}let s=E(e),a=s.slice(0,-1).join("."),n=s[s.length-1],i=a?P(r,a):r;return!i||!(n in i)?!1:(delete i[n],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:a}of e)s instanceof T&&s.isUnparseable()?r[s.valueOf()]=a:I(r,s,a);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 ne=class extends O{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 T&&e.isUnparseable()?t[e.valueOf()]:P(t,e)}async doSet(e,t){let r=this.storage.get(this.name)||{};if(e instanceof T&&e.isUnparseable()){r[e.valueOf()]=t,this.storage.set(this.name,r);return}let s=I({...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 T&&e.isUnparseable()){let i=e.valueOf();return i in t?(delete t[i],this.storage.set(this.name,t),!0):!1}let r=E(e),s=r.slice(0,-1).join("."),a=r[r.length-1],n=s?P(t,s):t;return!n||!(a in n)?!1:(delete n[a],this.storage.set(this.name,t),!0)}async doUpdate(e){let r={...this.storage.get(this.name)||{}};for(let{key:s,value:a}of e)s instanceof T&&s.isUnparseable()?r[s.valueOf()]=a:I(r,s,a);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)}};import{useEffect as qe,useRef as Re,useState as Ee}from"react";var B=new Map;function _r(o,e){let[t,r]=Ee(e?.initialValue),[s,a]=Ee(!!e?.withLoading),n=Re(e?.initialValue),i=Re(e?.equals||((l,p)=>l===p)),c=o.getId(),d=l=>{(n.current===void 0||!i.current(l,n.current))&&(n.current=l,r(l))};return qe(()=>{B.has(c)||B.set(c,{lastValue:void 0,listeners:new Set,unsubscribe:null});let l=B.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=B.get(c);p&&(p.listeners.delete(d),p.listeners.size===0&&(p.unsubscribe&&p.unsubscribe(),B.delete(c)))}},[o,c]),e?.withLoading?{data:t,isLoading:s}:t}import{useEffect as Ne,useState as ke}from"react";var Wr=(o,e)=>{let[t,r]=ke(void 0);return Ne(()=>{let s=!0;(async()=>{try{let i=await o.getState(),c=e(i);s&&r(c)}catch(i){console.error("Failed to initialize storage value:",i)}})();let n;try{n=o.subscribe(e,i=>{s&&r(i)})}catch(i){console.error("Failed to subscribe to storage:",i),n=()=>{}}return()=>{s=!1,n()}},[o,e]),t};import{createContext as Ue,useContext as W,useEffect as Pe,useRef as Ve,useState as Ae}from"react";function L(o,e=1){if(e<=0)throw new Error("Size must be greater than 0");if(!o||!o.length)return[];let t=[],r=o.length,s=0;for(;s<r;)t.push(o.slice(s,s+e)),s+=e;return t}var ae=(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]={}),ae(o[t],e[t])):o[t]=e[t])};import{jsx as Q}from"react/jsx-runtime";var G="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",je="\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 ls(o,e){let{loadingComponent:t=null,mergeFn:r=ae}=e||{},s=null,a=!1,n=(async()=>{try{s=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=Ue(null),c=()=>{let g=W(i);if(!g)throw new Error(G);return g.storage},d=()=>{let g=W(i);if(!g)throw new Error(G);return g.selectors},l=()=>{let g=W(i);if(!g)throw new Error(G);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=W(i);if(!g)throw new Error(G);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[R,w]=Ae(!1),[S,b]=Ae(a),C=Ve(`synapse-${s?.storage.name||"initializing"}`);return Pe(()=>{a||n.then(()=>{b(!0)})},[]),Pe(()=>{if(!S)return;let M=!0;return(async()=>{try{s&&m&&Object.keys(m).length>0&&await s.storage.update(q=>{r(q,m)}),M&&w(!0)}catch(q){console.error(`[${C.current}] ${je}`,q)}})(),()=>{M=!1}},[m,S]),S?R?Q(i.Provider,{value:s,children:Q(g,{...f})}):t||Q("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||Q("div",{children:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430..."})}let v=g.displayName||g.name||"Component";return y.displayName=`SynapseContext(${v})`,y}return{contextSynapse:u,useSynapseStorage:c,useSynapseSelectors:d,useSynapseActions:l,useSynapseState$:p,cleanupSynapse:async()=>(await n,s?.destroy()||Promise.resolve())}}import{Subject as Ce}from"rxjs";var oe=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 Ce;actions=this.actions$.asObservable();dispatch={};watchers={};storage;middlewareFunctions=[];middlewareAPI;use(...e){for(let t=0;t<e.length;t++)try{let r=e[t](this.middlewareAPI);this.middlewareFunctions.push(r)}catch(r){console.error(`Error initializing middleware [${t}]:`,r)}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 r=`[${this.storage.name}]${e.type}`,s=null,a=null,n=async i=>{let c=[i];if(t?.memoize&&s&&a&&t.memoize(c,s,a))return a;let d={type:r,meta:e.meta},l;if(this.middlewareFunctions.length>0){let p=async u=>t?.worker?this.executeInWorker(t.worker,r,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,r,c,e.action):l=await e.action(i);return d.payload=l,s=[...c],a=l,this.actions$.next(d),l};return n._type="dispatch",Object.defineProperty(n,"actionType",{value:r,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}`,r=new Ce,s,a=this.storage.subscribe(e.selector,i=>{if(!e.shouldTrigger||e.shouldTrigger(s,i)){let c={type:t,payload:i,meta:e.meta};this.actions$.next(c),r.next(c),s=i}}),n=()=>r.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,r,s){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:r,requestId:i}),setTimeout(()=>{e.removeEventListener("message",c),n(new Error(`Worker execution timeout for action: ${t}`))},3e4)})}};function Ts(o,e){let t=new oe(o),r=e(o.storage,{createAction:(s,a)=>t.createAction(s,a),createWatcher:s=>t.createWatcher(s)});for(let[s,a]of Object.entries(r))if(typeof a=="function"){let n=a._type;t[n][s]=a}return t}function De(o,e){let t={};return[...new Set([...Object.keys(o),...Object.keys(e)])].forEach(s=>{if(s in o&&s in e)if(typeof o[s]=="object"&&o[s]!==null&&typeof e[s]=="object"&&e[s]!==null&&!Array.isArray(o[s])&&!Array.isArray(e[s])){let a=De(o[s],e[s]);Object.keys(a).length>0&&(t[s]=a)}else JSON.stringify(o[s])!==JSON.stringify(e[s])&&(t[s]={PREV:o[s],NEXT:e[s]});else s in o?t[s]={PREV:o[s],NEXT:void 0}:t[s]={PREV:void 0,NEXT:e[s]}}),t}var ws=(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"}},r={...t,...o,translations:{...e,...o.translations||{}},colors:{...t.colors,...o.colors||{}}},{collapsed:s,duration:a,colors:n,translations:i}=r;return c=>d=>async l=>{let p=Date.now(),u=await c.getState();try{let h=await d(l),g=await c.getState(),v=Date.now()-p,m=`${l.type}`;if((s?console.groupCollapsed:console.group)(`%c ${m}`,`color: ${n.title}; font-weight: bold`),console.log(`%c ${i.action}:`,`color: ${n.action}; font-weight: bold`,l),r.diff){let R=De(u,g),w=Object.keys(R).length;console.log(`%c ${i.diff} (${i.changesCount}: ${w}):`,`color: ${n.diff}; font-weight: bold`,R)}return r.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 ${v}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}}};import{combineLatest as Je,merge as Ye,Observable as Xe,of as K,pipe as Ze,Subject as et}from"rxjs";import{catchError as tt,filter as $,map as J,share as rt,switchMap as st,take as nt}from"rxjs/operators";import{of as Ie}from"rxjs";import{concatAll as He,delay as _e,mergeMap as ze,toArray as Le}from"rxjs/operators";var Oe=(o,e,t,r=0)=>{let s=L(e,t).map(a=>Ie(a).pipe(_e(r),ze(o)));return Ie(...s).pipe(He(),Le())};import{forkJoin as We,timer as Ge}from"rxjs";import{mergeMap as Qe}from"rxjs/operators";var Me=(o,e,t,r=0)=>We(L(e,t).map((s,a)=>Ge(a*r).pipe(Qe(()=>o(s)))));function Gs(o){let{actionType:e}=o;return e?t=>t.pipe($(r=>r!==void 0&&r.type===e)):(console.warn("ofType: Action function does not have actionType property",o),$(()=>!1))}function Qs(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),$(()=>!1)):t=>t.pipe($(r=>r!==void 0&&e.includes(r.type)))}function Js(o){return e=>{let t=o.map(s=>s.actionType).filter(Boolean);if(t.length===0)return console.warn("ofTypesWaitAll: No valid action types found in array",o),K([]);let r=t.map((s,a)=>e.pipe($(n=>n.type===s),nt(1),J(n=>({index:a,action:n}))));return Je(r).pipe(J(s=>(s.sort((a,n)=>a.index-n.index),s.map(a=>a.action))))}}function Ys(o,...e){return o.pipe(J(t=>e.map(r=>r(t))))}function Xs(o,e){return o.pipe(J(t=>{let r={};for(let[s,a]of Object.entries(e))r[s]=a(t);return r}))}function Zs({validator:o,apiCall:e}){return Ze(st(t=>{let r=()=>e(t,{chunkRequest:Me,chunkRequestConsistent:Oe});if(!o)return r();let s=o(t),{conditions:a,skipAction:n}=s;return a.every(Boolean)?r():Array.isArray(n)?K(...n?.filter(Boolean).map(c=>typeof c=="function"?c():c)):K(typeof n=="function"?n():n)}))}var Y=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 Xe(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(rt())}effects=[];subscriptions=[];running=!1;action$=new et;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(tt(s=>(console.error("Error in effect:",s),K(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)}}};function en(o){return o}function tn(o){return o}function rn(...o){return(e,t,r,s,a,n)=>{let i=o.map(c=>{try{return c(e,t,r,s,a,n)}catch(d){return console.error("Error in one of combined effects:",d),K(null)}});return Ye(...i)}}async function at(o){let e=o.createStorageFn?await o.createStorageFn():o.storage,t=[],r={storage:e,selectors:{},destroy:async()=>{for(let i of t)await i()}};t.push(()=>e.destroy());let s,a,n;if(o.createSelectorsFn)try{a=new H(e);let i=o.externalSelectors||{};r.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&&(s=o.createDispatcherFn(e),r.dispatcher=s,s&&"dispatch"in s&&(r.actions=s.dispatch,typeof s.destroy=="function"&&t.push(()=>s.destroy()))),o.createEffectConfig&&s)try{let{dispatchers:i,api:c,config:d,externalStates:l}=o.createEffectConfig(s),p=l||{};n=new Y(e,p,i,c,d),Array.isArray(o.effects)&&o.effects.forEach(u=>{n&&n.add(u)}),n.start(),r.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 r}export{me as ApiClient,oe as Dispatcher,Y as EffectsModule,re as IndexedDBStorage,se as LocalStorage,ne as MemoryStorage,k as ResponseFormat,H as SelectorModule,Z as StorageEvents,be as StoragePluginModule,ce as apiLogger,we as broadcastMiddleware,rn as combineEffects,Ts as createDispatcher,tn as createEffect,en as createEffectBase,at as createSynapse,ls as createSynapseCtx,le as createUniqueId,de as headersToObject,ws as loggerDispatcherMiddleware,Gs as ofType,Qs as ofTypes,Js as ofTypesWaitAll,Ys as selectorMap,Xs as selectorObject,_r as useSelector,Wr as useStorageSubscribe,Zs as validateMap};
1
+ var le={debug:(n,...e)=>{process.env.NODE_ENV},log:(n,...e)=>{process.env.NODE_ENV},info:(n,...e)=>{},warn:(n,...e)=>{},error:(n,...e)=>{}};function de(n){return`${n?`${n}|`:""}${Math.random().toString(36).substring(2,9)+Date.now().toString(36)}`}function ue(n){let e={};return n.forEach((t,s)=>{e[s.toLowerCase()]=t}),e}function N(n={},e={}){return{...n,...e,getFromStorage:n.getFromStorage||(t=>{try{let s=localStorage.getItem(t);return s?JSON.parse(s):void 0}catch{return}}),getCookie:n.getCookie||(t=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch{return}})}}async function pe(n,e){let t=new Headers,s=e||N({},{});if(n)try{t=await Promise.resolve(n(t,s))}catch{}return t}function ge(n,e){return async(t,s)=>{let r=new Headers(t);if(n)try{r=await Promise.resolve(n(r,s))}catch{}if(e)try{r=await Promise.resolve(e(r,s))}catch{}return r}}var k=(a=>(a.Json="json",a.Blob="blob",a.ArrayBuffer="arrayBuffer",a.Text="text",a.FormData="formData",a.Raw="raw",a))(k||{});function he(n){let e=n.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 Z(n){let e=n.get("content-type")||"",t=n.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 Ke(n){let e=n.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 ye(n){let e=n.get("content-type")||"",t=n.get("content-disposition")||"",s=n.get("content-length");return Z(n)?{filename:Ke(n),contentType:e,contentDisposition:t,size:s?parseInt(s,10):void 0}:void 0}async function qe(n,e){let t=e,s=n.headers.get("content-type")||"";!t&&s&&(Z(n.headers)?t="blob":t=he(s)),t||(t="json");try{let r;switch((t==="blob"||t==="arrayBuffer")&&(r=ye(n.headers)),t){case"json":try{let a=await n.json();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}catch{let i=await n.text();return n.ok?{data:i,fileMetadata:r}:{error:i,fileMetadata:r}}case"text":{let a=await n.text();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}case"blob":{let a=await n.blob();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}case"arrayBuffer":{let a=await n.arrayBuffer();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}case"formData":{let a=await n.formData();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}case"raw":return n.ok?{data:n,fileMetadata:r}:{error:n,fileMetadata:r};default:let o=await n.blob();return n.ok?{data:o,fileMetadata:r}:{error:o,fileMetadata:r}}}catch(r){return n.ok?{data:void 0}:{error:r}}}function fe(n){let{baseUrl:e,timeout:t=3e4,fetchFn:s=fetch,credentials:r="same-origin"}=n;return async(o,a={},i)=>{let{path:c,method:d,body:l,query:p,responseFormat:u}=o,{signal:h,timeout:g=t,responseFormat:y}=a,v=y||u,f=new URL(c.startsWith("http")?c:`${e}${c}`);p&&Object.entries(p).forEach(([S,T])=>{T!=null&&(Array.isArray(T)?T.forEach(D=>f.searchParams.append(S,String(D))):f.searchParams.append(S,String(T)))});let m;if(l!==void 0)if(l instanceof FormData||l instanceof Blob)m=l;else if(typeof l=="object"&&l!==null)try{m=JSON.stringify(l),i.has("Content-Type")||i.set("Content-Type","application/json")}catch{m=String(l)}else m=String(l);let x,w=new Promise((S,T)=>{g&&(x=window.setTimeout(()=>{T(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(f.toString(),{method:d,headers:i,body:m,signal:h,credentials:r}),T=await Promise.race([S,w]),{data:D,error:M,fileMetadata:ce}=await qe(T,v);return{data:D,error:M,ok:T.ok,status:T.status,statusText:T.statusText,headers:T.headers,fileDownloadResult:ce}}catch(S){let T=S;return{error:T,ok:!1,status:0,statusText:T.message,headers:new Headers}}finally{x&&window.clearTimeout(x)}}}function me(n,e=[]){let t={};return!n||e.length===0||e.forEach(s=>{n.has(s)&&(t[s]=n.get(s)||"")}),t}var j=class{constructor(e,t,s,r,o,a){this.name=e;this.queryStorage=t;this.configCurrentEndpoint=s;this.cacheableHeaderKeys=r;this.globalCacheConfig=o;this.baseQueryConfig=a;this.prepareHeaders=ge(a.prepareHeaders,s.prepareHeaders),this.queryFunction=fe({baseUrl:a.baseUrl,fetchFn:a.fetchFn,timeout:a.timeout,credentials:a.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=de(this.name),r=new AbortController,o=new Set,a={status:"idle",requestParams:e,headers:{},error:void 0,data:void 0,fromCache:!1},i=N({requestParams:e},t?.context||{}),c=l=>{Object.assign(a,l),o.forEach(p=>{p({...a})})},d=new Promise(async(l,p)=>{try{let u=await pe(this.prepareHeaders,i),h=me(u,t?.cacheableHeaderKeys?t.cacheableHeaderKeys:this.cacheableHeaders),g=this.queryStorage.shouldCache(this.configCurrentEndpoint,t),[y,v]=this.queryStorage.createCacheKey(this.name,{...e,...h}),f;if(g&&(f=await this.queryStorage.getCachedResult(y)),f)c({fromCache:!0,status:"success",data:f.data,error:void 0,headers:f.headers,requestParams:e}),l({...f,fromCache:!0});else{c({fromCache:!1,status:"loading"});let m=this.configCurrentEndpoint.request(e,t?.context),x={...t,signal:r.signal},w=await this.queryFunction(m,x,u);if(w.ok){let{headers:S,...T}=w;if(g){let D=this.queryStorage.createCacheConfig(this.configCurrentEndpoint);await this.queryStorage.setCachedResult(y,{...T,headers:ue(S)},D,v??{},this.configCurrentEndpoint.tags??[],this.configCurrentEndpoint.invalidatesTags??[])}c({fromCache:!1,status:"success",data:w.data,error:void 0,headers:w.headers,requestParams:e}),this.endpointSubscribers.forEach(D=>{let M={status:"success",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};D(M)}),l({...w,fromCache:!1})}else c({fromCache:!1,status:"error",data:void 0,error:w.error,headers:w.headers,requestParams:e}),this.endpointSubscribers.forEach(S=>{let T={status:"error",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:w.error};S(T)}),p(w.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;o.add(l),l(a);let h=()=>o.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 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 C=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 b(e.join("_"))}static createApiKey(e,t){if(!t)return[new b(e,!0),t];let s=Object.entries(t).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>`${r}=${o}`).join("&");return[new b(`${e}_${s}`,!0),t]}static hasAnyTag(e,t=[]){return!e.tags||!t.length?!1:t.some(s=>e.tags?.includes(s))}};var U=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 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=>{})},e.interval))}getStorage(){return this.storage}createCacheKey(e,t){return C.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(C.isExpired(t.metadata)){await this.storage.delete(e);return}let s={...t,metadata:C.updateMetadata(t.metadata)};return await this.storage.set(e,s),t.data}async setCachedResult(e,t,s,r,o,a){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");a?.length&&await this.invalidateCacheByTags(a);let i=C.createMetadata(s.ttl,o),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&&C.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&&C.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 Se=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 U(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 o=s;this.endpoints[o]=new j(s,this.queryStorage,r,this.cacheableHeaderKeys,this.globalCacheConfig,this.baseQueryConfig)}}getEndpoints(){return this.endpoints}async request(e,t,s){let o=this.getEndpoints()[e];if(!o)throw new Error(`\u042D\u043D\u0434\u043F\u043E\u0438\u043D\u0442 ${String(e)} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`);try{return await o.request(t,s).wait()}catch(a){throw le.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043A ${String(e)}`,{error:a,params:t}),a}}async destroy(){await Promise.all(Object.values(this.endpoints).map(async e=>(e.destroy(),Promise.resolve()))),this.endpoints={},await this.queryStorage.destroy()}};var E=!1,F=new Map;function be(n){let e=0;if(n.length===0)return e.toString(36);for(let t=0;t<n.length;t++){let s=n.charCodeAt(t);e=(e<<5)-e+s,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function A(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(!A(n[t],e[t]))return!1;return!0}if(typeof n=="object"&&typeof e=="object"){let t=Object.keys(n),s=Object.keys(e);return t.length!==s.length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)?A(n[r],e[r]):!1)}return!1}function Te(n,e=A){let t,s,r=!1;return function(a){if(!r||t!==a){let i=n(a);(!r||!e(i,s))&&(s=i),t=a,r=!0}return s}}var V=class{constructor(e,t,s=A,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}},z=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",o="";if(e){let a=t.toString();o=be(a)}else{let a=t.map(c=>c.getId()).join("_"),i=s.toString();o=be(a+i)}return`${this.storageName}_${r}_${o}`}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(o){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:o})}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),o=r?t||{}:s||{},a=o.name||this.generateName(r,e,r?void 0:t);if(this.localSelectorCache.has(a))return this.localSelectorCache.get(a).api;if(F.has(a)){let l=F.get(a);return l.refCount++,l.api}let i,c,d=[];if(r){let l=Te(e,o.equals||A),p=this.createSimpleSelector(l,{...o,name:a,equals:o.equals||A});i=p.api,d=p.unsubscribeFunctions}else{c=e;let l=this.createCombinedSelector(c,t,{...o,name:a,equals:o.equals||A});i=l.api,d=l.unsubscribeFunctions}return this.localSelectorCache.set(a,{api:i,dependencies:c,unsubscribeFunctions:d}),F.set(a,{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 V(t.name,s,t.equals||A,this.logger),o=r.getId();this.subscriptions.set(o,r);let i=[this.source.subscribeToAll(async c=>{c?.type==="storage:update"&&(this.pendingUpdates.add(o),this.processPendingUpdates())})];return{api:{select:()=>s(),subscribe:c=>r.subscribe(c),getId:()=>o},unsubscribeFunctions:i}}createCombinedSelector(e,t,s){let r=Te(p=>t(...p),s.equals||A),o=async()=>{let p=await Promise.all(e.map(u=>u.select()));return r(p)},a=new V(s.name,o,s.equals||A,this.logger),i=a.getId();this.subscriptions.set(i,a);let c=null,d=()=>{c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,a.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:()=>o(),subscribe:p=>a.subscribe(p),getId:()=>i},unsubscribeFunctions:l}}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=F.get(t);s&&(s.refCount--,s.refCount<=0&&(s.unsubscribeFunctions.forEach(r=>r()),F.delete(t)))})}};var we=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 o of this.plugins.values())if(o.onBeforeSet)try{s=await o.onBeforeSet(s,r)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onBeforeSet`,{error:a}),a}return s}async executeAfterSet(e,t,s){let r=t,o=this.createContext(s);this.parentExecutor&&(r=await this.parentExecutor.executeAfterSet(e,r,o));for(let a of this.plugins.values())if(a.onAfterSet)try{r=await a.onAfterSet(e,r,o)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.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 o of this.plugins.values())if(o.onBeforeGet)try{s=await o.onBeforeGet(s,r)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onBeforeGet`,{key:e,error:a}),a}return s}async executeAfterGet(e,t,s){let r=t,o=this.createContext(s);this.parentExecutor&&(r=await this.parentExecutor.executeAfterGet(e,r,o));for(let a of this.plugins.values())if(a.onAfterGet)try{r=await a.onAfterGet(e,r,o)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.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 o of this.plugins.values())if(o.onBeforeDelete)try{s=await o.onBeforeDelete(e,r)&&s}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onBeforeDelete`,{key:e,error:a}),a}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(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${r.name} onAfterDelete`,{key:e,error:o}),o}}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 Ee=(r=>(r.IDLE="idle",r.LOADING="loading",r.READY="ready",r.ERROR="error",r))(Ee||{}),ee=(a=>(a.STORAGE_UPDATE="storage:update",a.STORAGE_DELETE="storage:delete",a.STORAGE_PATCH="storage:patch",a.STORAGE_SELECT="storage:select",a.STORAGE_CLEAR="storage:clear",a.STORAGE_DESTROY="storage:destroy",a))(ee||{});var L=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}error(...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 Ne(n,e,t){switch(e){case"set":t?.key!==void 0&&t?.value!==void 0&&(await n.storage.doSet(t.key,t.value),n.storage.notifySubscribers(t.key,t.value));break;case"update":Array.isArray(t?.value)&&(await n.storage.doUpdate(t.value),t.value.forEach(({key:s,value:r})=>{n.storage.notifySubscribers(s,r)}));break;case"delete":t?.key!==void 0&&(await n.storage.doDelete(t.key),n.storage.notifySubscribers(t.key,void 0));break;case"clear":await n.storage.doClear(),n.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}n.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:t?.value,source:"broadcast"})}async function ke(n,e,t){switch(e){case"set":if(t?.key!==void 0){let s=await n.storage.doGet(t.key);n.storage.notifySubscribers(t.key,s)}break;case"update":if(Array.isArray(t?.value)){for(let{key:s}of t.value){let r=await n.storage.doGet(s);n.storage.notifySubscribers(s,r)}n.storage.notifySubscribers("*",{type:"storage:update",key:t.value.map(({key:s})=>s),value:t.value,source:"broadcast"})}break;case"delete":t?.key!==void 0&&n.storage.notifySubscribers(t.key,void 0);break;case"clear":n.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}e!=="update"&&n.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:e==="delete"?void 0:t?.value,source:"broadcast"})}var ve=n=>{let{storageName:e,storageType:t}=n,s=`${t}-${e}`,r=new L(s,{debug:!0});return{name:"broadcast",setup:o=>(t==="memory"&&(r.setSyncHandler(async()=>{let a=await o.getState();return{type:"update",key:"*",value:Object.entries(a).map(([d,l])=>({key:d,value:l})),metadata:{batchUpdate:!0,timestamp:Date.now()}}}),r.requestSync().then(async a=>{if(a?.type==="update"&&Array.isArray(a.value))try{if(!a.value.every(c=>c&&typeof c=="object"&&"key"in c&&"value"in c))return;await o.storage.doUpdate(a.value),a.value.forEach(({key:c,value:d})=>{o.storage.notifySubscribers(c,d)}),o.storage.notifySubscribers("*",{type:"storage:update",value:a.value,source:"broadcast"})}catch{}})),r.subscribe(async a=>{let{type:i,payload:c}=a;t==="memory"?await Ne(o,i,c):await ke(o,i,c)})),reducer:o=>a=>async i=>{let c=await a(i);return["set","delete","clear","update"].includes(i.type)&&r.broadcast(i.type,i),c},cleanup:()=>{r.close()}}};var xe=(n={})=>{let e=n.batchSize??10,t=n.batchDelay??10,s=new Map,r=new Map,o=u=>u.type==="set"||u.type==="update",a=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 v=y.map(m=>m.action),f=i(v);for(let m of f)try{let x=await g(m);y.filter(S=>S.action.type===m.type&&S.action.key?.toString()===m.key?.toString()).forEach(S=>S.resolve(x))}catch(x){y.filter(S=>S.action.type===m.type&&S.action.key?.toString()===m.key?.toString()).forEach(S=>S.reject(x))}}catch(v){y.forEach(f=>f.reject(v))}}},p=async(u,h,g)=>new Promise((y,v)=>{let f=a(u),m=s.get(f);m||(m=[],s.set(f,m)),m.push({action:u,resolve:y,reject:v,timestamp:Date.now()}),c(f),m.length>=e?setImmediate(()=>l(f,h,g)):d(f,()=>l(f,h,g))});return{name:"batching",setup:()=>{},cleanup:async()=>{r.forEach(u=>globalThis.clearTimeout(u)),r.clear(),s.clear()},reducer:u=>h=>async g=>o(g)?p(g,u,h):h(g)}};var Re=(n={})=>{let{comparator:e=(r,o)=>{if(r===o)return!0;if(typeof r!="object"||typeof o!="object"||r===null||o===null)return r===o;let a=Object.keys(r),i=Object.keys(o);return a.length!==i.length?!1:a.every(c=>Object.prototype.hasOwnProperty.call(o,c)&&r[c]===o[c])},segments:t=[]}=n,s=new Map;return{name:"shallow-compare",setup:r=>{},reducer:r=>o=>async a=>{if(a.type!=="set"||t.length&&!t.includes(a.metadata?.segment??"default"))return o(a);let i=a.key,c=s.get(i),d=a.value;if(c!==void 0&&e(c,d))return{...c,t:{valueNotChanged:!0,originalValue:c}};let l=await o(a);return s.set(i,d),l}}};var H=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 o=await this.api.storage.doGet("");return Object.keys(o||{}).length>0?o:r.value?(await this.api.storage.doSet("",r.value),this.api.storage.doGet("")):o}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 o={...r,metadata:{...r.metadata,processed:!0,timestamp:r.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(s)(o)}}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 R(n){return n instanceof b&&n.isUnparseable()?[n.toString()]:n.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function P(n,e){return R(e).reduce((s,r)=>s===void 0?void 0:s[r],n)}function I(n,e,t){if(e==="")return t;let s=R(e);if(e instanceof b&&e.isUnparseable())return n[e.toString()]=t,n;let r=s.pop(),o=s.reduce((a,i)=>{let c=s[s.indexOf(i)+1],d=!Number.isNaN(Number(c));return i in a||(a[i]=d?[]:{}),a[i]},n);return o[r]=t,n}var O=class n{constructor(e,t,s,r){this.config=e;this.pluginExecutor=t;this.eventEmitter=s;this.logger=r;this.name=e.name,this.middlewareModule=new H({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(o){this.logger?.error("Error in status change callback",{error:o})}})}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={})=>xe(e),shallowCompare:(e={})=>Re(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,o=await this.middlewareModule.dispatch({type:"set",key:e,value:r,metadata:s}),a=o?.t?.valueNotChanged===!0,i;if(a&&o?.t?.originalValue!==void 0?i=o.t.originalValue:i=await this.pluginExecutor?.executeAfterSet(e,o,s)??o,!a){let d=[e.toString()];this.notifySubscribers(e,i),this.notifySubscribers(n.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 o=this.findChangedPaths(s,r);if(o.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(o)});let a=new Set;for(let u of o){let h=u.split(".")[0];a.add(h)}let i=await Promise.all(Array.from(a).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(o)}}),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(n.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:l,value:p,changedPaths:Array.from(o)});for(let u of o)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=P(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(o)}})}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 o=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(n.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:s,changedPaths:o}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:s,changedPaths:o}})}}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(n.GLOBAL_SUBSCRIPTION_KEY)||this.subscribers.set(n.GLOBAL_SUBSCRIPTION_KEY,new Set),this.subscribers.get(n.GLOBAL_SUBSCRIPTION_KEY).add(e),()=>{let t=this.subscribers.get(n.GLOBAL_SUBSCRIPTION_KEY);t&&(t.delete(e),t.size===0&&this.subscribers.delete(n.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(o){this.logger?.error("Error in initial callback",{key:e,error:o})}}),()=>{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 o=Object.keys(e),a=Object.keys(t);return o.length!==a.length?!1:o.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=(o="")=>({get:(a,i)=>{if(typeof i=="symbol")return Reflect.get(a,i);let c=o?`${o}.${i}`:i;return s.push(c),new Proxy({},r(c))},has:(a,i)=>!0,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0}),apply:(a,i,c)=>new Proxy(()=>{},r(o))});try{e(new Proxy(t,r()))}catch{}return s.length===0?"":(s.sort((o,a)=>a.length-o.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(a=>{try{a(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,o=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(o.has(e))return r;o.set(e,!0);let a=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let i of a){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,o):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 o=async a=>{try{if(a==null){let d=await this.getState(),l=e(d);t(l);return}if(typeof a!="object"||a===null){t(a);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(a)}};return r?this.subscribeByKey(r,o):this.subscribeToAll(()=>{this.getState().then(a=>{t(e(a))})})}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 te=class n{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){n.instances.has(e)||n.instances.set(e,new n(e,t,s));let r=n.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 o=0;o<this.db.objectStoreNames.length;o++)this.storeNames.add(this.db.objectStoreNames[o]);this.logger?.debug(`Database "${this.dbName}" opened successfully`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),t(this.db)},r.onupgradeneeded=o=>{let a=o.target.result;this.logger?.debug(`Upgrading database "${this.dbName}" to version ${this.dbVersion}`);for(let i of e)a.objectStoreNames.contains(i)||(this.logger?.debug(`Creating store "${i}"`),a.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`),n.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}},re=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 o=indexedDB.open(this.dbName,e);o.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:o.error}),r(o.error)},o.onsuccess=()=>{this.db=o.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)},o.onupgradeneeded=a=>{let i=a.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)}},se=class n extends O{DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,s,r){super(e,t,s,r);let o=e.options;this.DB_NAME=o.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=o.dbVersion||1,this.dbManager=te.getInstance(this.DB_NAME,this.DB_VERSION,r)}async doInitialize(){try{if(this.logger?.debug(`Initializing IndexedDB storage "${this.STORE_NAME}"`),await this.dbManager.ensureStoreExists(this.STORE_NAME),!(await this.dbManager.initialize()).objectStoreNames.contains(this.STORE_NAME))throw new Error(`Store "${this.STORE_NAME}" not found after initialization`);return this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this.logger?.debug(`IndexedDB storage "${this.STORE_NAME}" initialized successfully`),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=()=>{t(0)}}catch{t(0)}})}static async createStorages(e,t,s){let o=await this.getCurrentDBVersion(e)||1,a=new re(e,o,s),i=Object.values(t).map(d=>d.name);await a.ensureStoresExist(i);let c={};for(let[d,l]of Object.entries(t)){let p=new n({...l,options:{dbName:e,dbVersion:a.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,o)=>{let a=t.getAll();a.onerror=()=>o(a.error),a.onsuccess=()=>{let i=a.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=()=>o(c.error)}});if(e instanceof b&&e.isUnparseable())return new Promise((r,o)=>{let a=t.get(e.valueOf());a.onerror=()=>o(a.error),a.onsuccess=()=>r(a.result)});let s=R(e);if(s.length>1){let r=s[0];return new Promise((o,a)=>{let i=t.get(r);i.onerror=()=>a(i.error),i.onsuccess=()=>{let c=i.result;if(!c){o(void 0);return}let d=P(c,s.slice(1).join("."));o(d)}})}return new Promise((r,o)=>{let a=t.get(s[0]);a.onerror=()=>o(a.error),a.onsuccess=()=>r(a.result)})}async doSet(e,t){if(e===""){let o=await this.getObjectStore("readwrite");return new Promise((a,i)=>{let c=o.transaction;c.oncomplete=()=>{a()},c.onerror=()=>{i(c.error)};let d=o.clear();d.onsuccess=()=>{let l=Object.entries(t);for(let[p,u]of l)o.put(u,p)},d.onerror=()=>{i(d.error)}})}let s=await this.getObjectStore("readwrite");if(e instanceof b&&e.isUnparseable()){await this.putValueInStore(s,e.valueOf(),t);return}let r=R(e);if(r.length>1){let o=r[0];return new Promise((a,i)=>{let c=s.get(o);c.onerror=()=>i(c.error),c.onsuccess=()=>{let d=c.result||{},l=I(d,r.slice(1).join("."),t),p=s.put(l,o);p.onerror=()=>i(p.error),p.onsuccess=()=>a()}})}await this.putValueInStore(s,r[0],t)}async putValueInStore(e,t,s){return new Promise((r,o)=>{let a=e.put(s,t.valueOf());a.onerror=()=>o(a.error),a.onsuccess=()=>r()})}async doUpdate(e){let t=new Map,s=[];for(let{key:r,value:o}of e){if(r instanceof b&&r.isUnparseable()){s.push({key:r.valueOf(),value:o});continue}let a=R(r),i=a[0],c=a.slice(1);t.has(i)||t.set(i,[]),t.get(i).push({path:c,value:o})}try{for(let{key:r,value:o}of s){let a=await this.getObjectStore("readwrite");await this.putValueInStore(a,r,o)}for(let[r,o]of t){let i={...await this.doGet(r)||{}};for(let{path:d,value:l}of o)d.length===0?i=l:i=I(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 b&&e.isUnparseable())return new Promise((o,a)=>{let i=t.delete(e.valueOf());i.onerror=()=>a(i.error),i.onsuccess=()=>o(!0)});let s=R(e);if(s.length===1)return new Promise((o,a)=>{let i=t.delete(s[0]);i.onerror=()=>a(i.error),i.onsuccess=()=>o(!0)});let r=s[0];return new Promise((o,a)=>{let i=t.get(r);i.onerror=()=>a(i.error),i.onsuccess=()=>{let c=i.result;if(!c){o(!1);return}let d=P(c,s.slice(0,-1).join(".")),l=s[s.length-1];if(!d||!(l in d)){o(!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=()=>a(p.error),p.onsuccess=()=>o(!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 ne=class extends O{constructor(e,t,s,r){super(e,t,s,r)}async doInitialize(){try{return this.logger?.debug(`Initializing LocalStorage "${this.name}"`),this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this.logger?.debug(`LocalStorage "${this.name}" initialized successfully`),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 b&&e.isUnparseable()?s[e.valueOf()]:P(s,e)}async doSet(e,t){let s=localStorage.getItem(this.name),r=s?JSON.parse(s):{};if(e instanceof b&&e.isUnparseable()){r[e.valueOf()]=t,localStorage.setItem(this.name,JSON.stringify(r));return}let o=I({...r},e,t);localStorage.setItem(this.name,JSON.stringify(o))}async doDelete(e){let t=localStorage.getItem(this.name);if(!t)return!1;let s=JSON.parse(t);if(e instanceof b&&e.isUnparseable()){let c=e.valueOf();return c in s?(delete s[c],localStorage.setItem(this.name,JSON.stringify(s)),!0):!1}let r=R(e),o=r.slice(0,-1).join("."),a=r[r.length-1],i=o?P(s,o):s;return!i||!(a in i)?!1:(delete i[a],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:o}of e)r instanceof b&&r.isUnparseable()?s[r.valueOf()]=o:I(s,r,o);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 B=class extends O{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()]:P(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=I({...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=R(e),r=s.slice(0,-1).join("."),o=s[s.length-1],a=r?P(t,r):t;return!a||!(o in a)?!1:(delete a[o],this.storage.set(this.name,t),!0)}async doUpdate(e){let s={...this.storage.get(this.name)||{}};for(let{key:r,value:o}of e)r instanceof b&&r.isUnparseable()?s[r.valueOf()]=o:I(s,r,o);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{useEffect as je,useRef as Pe,useState as Ae}from"react";var $=new Map;function Xr(n,e){let[t,s]=Ae(e?.initialValue),[r,o]=Ae(!!e?.withLoading),a=Pe(e?.initialValue),i=Pe(e?.equals||((l,p)=>l===p)),c=n.getId(),d=l=>{(a.current===void 0||!i.current(l,a.current))&&(a.current=l,s(l))};return je(()=>{$.has(c)||$.set(c,{lastValue:void 0,listeners:new Set,unsubscribe:null});let l=$.get(c);return l.listeners.add(d),l.lastValue!==void 0?(d(l.lastValue),e?.withLoading&&o(!1)):(e?.withLoading&&o(!0),n.select().then(p=>{l.lastValue=p,l.listeners.forEach(u=>u(p)),e?.withLoading&&o(!1)}).catch(p=>{e?.withLoading&&o(!1)})),l.unsubscribe||(l.unsubscribe=n.subscribe({notify:p=>{l.lastValue=p,l.listeners.forEach(u=>{try{u(p)}catch{}})}})),()=>{let p=$.get(c);p&&(p.listeners.delete(d),p.listeners.size===0&&(p.unsubscribe&&p.unsubscribe(),$.delete(c)))}},[n,c]),e?.withLoading?{data:t,isLoading:r}:t}import{useEffect as Ue,useState as Ve}from"react";var ts=(n,e)=>{let[t,s]=Ve(void 0);return Ue(()=>{let r=!0;(async()=>{try{let i=await n.getState(),c=e(i);r&&s(c)}catch{}})();let a;try{a=n.subscribe(e,i=>{r&&s(i)})}catch{a=()=>{}}return()=>{r=!1,a()}},[n,e]),t};import{createContext as ze,useContext as W,useEffect as Ce,useRef as Le,useState as Ie}from"react";function _(n,e=1){if(e<=0)throw new Error("Size must be greater than 0");if(!n||!n.length)return[];let t=[],s=n.length,r=0;for(;r<s;)t.push(n.slice(r,r+e)),r+=e;return t}var ae=(n,e)=>{for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(typeof e[t]=="object"&&e[t]!==null&&!Array.isArray(e[t])?((!n[t]||typeof n[t]!="object")&&(n[t]={}),ae(n[t],e[t])):n[t]=e[t])};import{jsx as Q}from"react/jsx-runtime";var G="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";function ms(n,e){let{loadingComponent:t=null,mergeFn:s=ae}=e||{},r=null,o=!1,a=(async()=>{try{r=await(n instanceof Promise?n:Promise.resolve(n)),o=!0}catch{}})(),i=ze(null),c=()=>{let g=W(i);if(!g)throw new Error(G);return g.storage},d=()=>{let g=W(i);if(!g)throw new Error(G);return g.selectors},l=()=>{let g=W(i);if(!g)throw new Error(G);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=W(i);if(!g)throw new Error(G);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:f,...m}){let[x,w]=Ie(!1),[S,T]=Ie(o),D=Le(`synapse-${r?.storage.name||"initializing"}`);return Ce(()=>{o||a.then(()=>{T(!0)})},[]),Ce(()=>{if(!S)return;let M=!0;return(async()=>{try{r&&f&&Object.keys(f).length>0&&await r.storage.update(X=>{s(X,f)}),M&&w(!0)}catch{}})(),()=>{M=!1}},[f,S]),S?x?Q(i.Provider,{value:r,children:Q(g,{...m})}):t||Q("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||Q("div",{children:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430..."})}let v=g.displayName||g.name||"Component";return y.displayName=`SynapseContext(${v})`,y}return{contextSynapse:u,useSynapseStorage:c,useSynapseSelectors:d,useSynapseActions:l,useSynapseState$:p,cleanupSynapse:async()=>(await a,r?.destroy()||Promise.resolve())}}import{Observable as He,Subject as De}from"rxjs";var oe=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 De;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,o=null,a=async i=>{let c=[i];if(t?.memoize&&r&&o&&t.memoize(c,r,o))return o;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 f=>g(f))(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],o=l,this.actions$.next(d),l};return a.r="dispatch",Object.defineProperty(a,"actionType",{value:s,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(a,"meta",{value:e.meta,writable:!1,enumerable:!0}),a}createWatcher(e){let t=`[${this.storage.name}]${e.type}`,s=new De,r,o=async()=>{let c=await this.storage.getState();return e.selector(c)},a=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 He(d=>{let l=!1;o().then(u=>{if(!e.shouldTrigger||e.shouldTrigger(void 0,u)){let h={type:t,payload:u,meta:{...e.meta,isInitial:!0}};d.next(h),r=u,l=!0}}).catch(u=>{d.error(u)});let p=c.subscribe({next:u=>{l&&u.payload===r||d.next(u)},error:u=>d.error(u),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:a,writable:!1,enumerable:!0}),i}async executeInWorker(e,t,s,r){return new Promise((o,a)=>{let i=`${t}_${Date.now()}_${Math.random()}`,c=d=>{d.data.requestId===i&&(e.removeEventListener("message",c),d.data.error?a(new Error(d.data.error)):o(d.data.result))};e.addEventListener("message",c),e.postMessage({type:t,args:s,requestId:i}),setTimeout(()=>{e.removeEventListener("message",c),a(new Error(`Worker execution timeout for action: ${t}`))},3e4)})}};function Oe(n,e){let t=new oe(n),s=e(n.storage,{createAction:(r,o)=>t.createAction(r,o),createWatcher:r=>t.createWatcher(r)});for(let[r,o]of Object.entries(s))if(typeof o=="function"){let a=o.r;t[a][r]=o}return t}function Me(n,e){let t={};return[...new Set([...Object.keys(n),...Object.keys(e)])].forEach(r=>{if(r in n&&r in e)if(typeof n[r]=="object"&&n[r]!==null&&typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(n[r])&&!Array.isArray(e[r])){let o=Me(n[r],e[r]);Object.keys(o).length>0&&(t[r]=o)}else JSON.stringify(n[r])!==JSON.stringify(e[r])&&(t[r]={PREV:n[r],NEXT:e[r]});else r in n?t[r]={PREV:n[r],NEXT:void 0}:t[r]={PREV:void 0,NEXT:e[r]}}),t}var As=(n={})=>{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,...n,translations:{...e,...n.translations||{}},colors:{...t.colors,...n.colors||{}}},{collapsed:r,duration:o,colors:a,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(),v=Date.now()-p,f=`${l.type}`;if((r?console.groupCollapsed:console.group)(`%c ${f}`,`color: ${a.title}; font-weight: bold`),s.diff){let x=Me(u,g),w=Object.keys(x).length}return s.showFullState,h}catch(h){throw h}}};import{combineLatest as Ze,merge as et,Observable as tt,of as K,pipe as rt,Subject as st}from"rxjs";import{catchError as nt,filter as q,map as J,share as at,switchMap as ot,take as it}from"rxjs/operators";import{of as Fe}from"rxjs";import{concatAll as _e,delay as We,mergeMap as Ge,toArray as Qe}from"rxjs/operators";var Be=(n,e,t,s=0)=>{let r=_(e,t).map(o=>Fe(o).pipe(We(s),Ge(n)));return Fe(...r).pipe(_e(),Qe())};import{forkJoin as Je,timer as Ye}from"rxjs";import{mergeMap as Xe}from"rxjs/operators";var $e=(n,e,t,s=0)=>Je(_(e,t).map((r,o)=>Ye(o*s).pipe(Xe(()=>n(r)))));function Zs(n){let{actionType:e}=n;return e?t=>t.pipe(q(s=>s!==void 0&&s.type===e)):q(()=>!1)}function en(n){let e=n.map(t=>t.actionType).filter(Boolean);return e.length===0?q(()=>!1):t=>t.pipe(q(s=>s!==void 0&&e.includes(s.type)))}function tn(n){return e=>{let t=n.map(r=>r.actionType).filter(Boolean);if(t.length===0)return K([]);let s=t.map((r,o)=>e.pipe(q(a=>a.type===r),it(1),J(a=>({index:o,action:a}))));return Ze(s).pipe(J(r=>(r.sort((o,a)=>o.index-a.index),r.map(o=>o.action))))}}function rn(n,...e){return n.pipe(J(t=>e.map(s=>s(t))))}function sn(n,e){return n.pipe(J(t=>{let s={};for(let[r,o]of Object.entries(e))s[r]=o(t);return s}))}function nn({validator:n,apiCall:e}){return rt(ot(t=>{let s=()=>e(t,{chunkRequest:$e,chunkRequestConsistent:Be});if(!n)return s();let r=n(t),{conditions:o,skipAction:a}=r;return o.every(Boolean)?s():Array.isArray(a)?K(...a?.filter(Boolean).map(c=>typeof c=="function"?c():c)):K(typeof a=="function"?a():a)}))}var Y=class{constructor(e,t={},s,r={},o={}){this.storage=e;this.externalStates=t;this.dispatchers=s;this.services=r;this.config=o;this.subscribeToDispatchers(),this.state$=new tt(a=>{this.storage.getState().then(c=>a.next(c));let i=this.storage.subscribeToAll(()=>{this.storage.getState().then(c=>a.next(c))});return()=>i()}).pipe(at())}effects=[];subscriptions=[];running=!1;action$=new st;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(nt(r=>K(null))).subscribe(r=>{if(r!=null&&typeof r=="function")try{r()}catch{}});this.subscriptions.push(s)}catch{}}};function an(n){return n}function on(n){return n}function cn(...n){return(e,t,s,r,o,a)=>{let i=n.map(c=>{try{return c(e,t,s,r,o,a)}catch{return K(null)}});return et(...i)}}function ct(n){if(!n.storage&&!n.createStorageFn)throw new Error('Synapse config must have either "storage" or "createStorageFn"');if(n.storage&&n.createStorageFn)throw new Error('Synapse config cannot have both "storage" and "createStorageFn". Choose one.');if(n.effects&&!n.createDispatcherFn)throw new Error('Effects require dispatcher. Add "createDispatcherFn" to config.');if(n.createEffectConfig&&!n.createDispatcherFn)throw new Error('Effect config requires dispatcher. Add "createDispatcherFn" to config.');if(n.dependencies){if(!Array.isArray(n.dependencies))throw new Error("Dependencies must be an array");n.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(n.createStorageFn&&typeof n.createStorageFn!="function")throw new Error('"createStorageFn" must be a function');if(n.createDispatcherFn&&typeof n.createDispatcherFn!="function")throw new Error('"createDispatcherFn" must be a function');if(n.createSelectorsFn&&typeof n.createSelectorsFn!="function")throw new Error('"createSelectorsFn" must be a function');if(n.createEffectConfig&&typeof n.createEffectConfig!="function")throw new Error('"createEffectConfig" must be a function');if(n.effects){if(!Array.isArray(n.effects))throw new Error("Effects must be an array");n.effects.forEach((e,t)=>{if(typeof e!="function")throw new Error(`Effect at index ${t} must be a function`)})}if(n.externalSelectors&&typeof n.externalSelectors!="object")throw new Error("External selectors must be an object")}async function lt(n=[]){n.length!==0&&await Promise.all(n.map(async(e,t)=>{try{await e.storage.waitForReady()}catch(s){throw new Error(`Dependency ${t} initialization failed: ${s}`)}}))}async function ie(n){try{ct(n)}catch(i){throw i}await lt(n.dependencies);let e=n.createStorageFn?await n.createStorageFn():n.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,o,a;if(n.createSelectorsFn)try{o=new z(e);let i=n.externalSelectors||{};s.selectors=n.createSelectorsFn(o,i),typeof o.destroy=="function"&&t.push(()=>o.destroy())}catch{}if(n.createDispatcherFn&&(r=n.createDispatcherFn(e),s.dispatcher=r,r&&"dispatch"in r&&(s.actions=r.dispatch,typeof r.destroy=="function"&&t.push(()=>r.destroy()))),n.createEffectConfig&&r)try{let{dispatchers:i,api:c,config:d,externalStates:l}=n.createEffectConfig(r),p=l||{};a=new Y(e,p,i,c,d),Array.isArray(n.effects)&&n.effects.forEach(u=>{a&&a.add(u)}),await a.start(),s.state$=a.state$,t.push(()=>{a&&a.stop()})}catch{}return s}function dt(n,e){return e==="*"?!0:e.includes("*")?new RegExp("^"+e.replace(/\*/g,".*")+"$").test(n):n===e}async function ut(n,e){let t=await n.getState(),s=Object.entries(t.events||{});if(s.length>e){let o=s.sort((a,i)=>i[1].timestamp-a[1].timestamp).slice(0,e);await n.set("events",Object.fromEntries(o))}}var pt=(n={})=>ie({createStorageFn:async()=>new B({name:n.name||"eventBus",initialState:{events:{},subscriptions:{}}}).initialize(),createDispatcherFn:e=>Oe({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:o,metadata:a={}})=>{let i=`${r}_${Date.now()}_${Math.random()}`;return await t.set(`events.${i}`,{id:i,event:r,data:o,metadata:{ttl:a.ttl||null,priority:a.priority||"normal",...a},timestamp:Date.now()}),n.autoCleanup&&await ut(t,n.maxEvents||1e3),{eventId:i,event:r,data:o}}}),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:o,options:a={}})=>{let i=`sub_${Date.now()}_${Math.random()}`,c=t.subscribe(d=>d.events,d=>{Object.values(d||{}).forEach(l=>{if(dt(l.event,r)){if(a.priority&&l.metadata.priority!==a.priority)return;try{o(l.data,l)}catch{}}})});return await t.set(`subscriptions.${i}`,{id:i,pattern:r,options:a,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:o=100})=>{let a=await t.getState();return Object.values(a.events||{}).filter(i=>i.event===r).sort((i,c)=>c.timestamp-i.timestamp).slice(0,o)}}),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 o=Date.now()-r;await t.update(a=>{Object.keys(a.events||{}).forEach(i=>{a.events[i].timestamp<o&&delete a.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{Se as ApiClient,oe as Dispatcher,Y as EffectsModule,se as IndexedDBStorage,ne as LocalStorage,B as MemoryStorage,k as ResponseFormat,z as SelectorModule,ee as StorageEvents,we as StoragePluginModule,Ee as StorageStatus,le as apiLogger,ve as broadcastMiddleware,cn as combineEffects,Oe as createDispatcher,on as createEffect,an as createEffectBase,pt as createEventBus,ie as createSynapse,ms as createSynapseCtx,de as createUniqueId,ue as headersToObject,As as loggerDispatcherMiddleware,Zs as ofType,en as ofTypes,tn as ofTypesWaitAll,rn as selectorMap,sn as selectorObject,Xr as useSelector,ts as useStorageSubscribe,nn as validateMap};
package/dist/react.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { S as SelectorAPI } from './selector.interface-CA5y-kD_.js';
2
- import { I as IStorage } from './storage.interface-Dl8SLUd1.js';
2
+ import { j as IStorage } from './storage.interface-2HKvqdAJ.js';
3
3
  import { ComponentType } from 'react';
4
4
  import { Observable } from 'rxjs';
5
- import { SynapseStoreWithEffects, SynapseStoreWithDispatcher, SynapseStoreBasic } from './utils.js';
6
- import './dispatcher.module-jd8U_ZEs.js';
5
+ import { b as SynapseStoreWithEffects, a as SynapseStoreWithDispatcher, S as SynapseStoreBasic } from './createSynapse-CzeX0ONj.js';
6
+ import './dispatcher.module-DjMloBXe.js';
7
7
 
8
8
  interface UseSelectorOptions<T> {
9
9
  /** Начальное значение до загрузки данных из селектора */
package/dist/react.js CHANGED
@@ -1 +1 @@
1
- import{useEffect as z,useRef as A,useState as w}from"react";var f=new Map;function q(n,e){let[t,l]=w(e?.initialValue),[a,p]=w(!!e?.withLoading),S=A(e?.initialValue),i=A(e?.equals||((r,s)=>r===s)),c=n.getId(),u=r=>{(S.current===void 0||!i.current(r,S.current))&&(S.current=r,l(r))};return z(()=>{f.has(c)||f.set(c,{lastValue:void 0,listeners:new Set,unsubscribe:null});let r=f.get(c);return r.listeners.add(u),r.lastValue!==void 0?(u(r.lastValue),e?.withLoading&&p(!1)):(e?.withLoading&&p(!0),n.select().then(s=>{r.lastValue=s,r.listeners.forEach(T=>T(s)),e?.withLoading&&p(!1)}).catch(s=>{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}`,s),e?.withLoading&&p(!1)})),r.unsubscribe||(r.unsubscribe=n.subscribe({notify:s=>{r.lastValue=s,r.listeners.forEach(T=>{try{T(s)}catch(C){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}`,C)}})}})),()=>{let s=f.get(c);s&&(s.listeners.delete(u),s.listeners.size===0&&(s.unsubscribe&&s.unsubscribe(),f.delete(c)))}},[n,c]),e?.withLoading?{data:t,isLoading:a}:t}import{useEffect as F,useState as D}from"react";var G=(n,e)=>{let[t,l]=D(void 0);return F(()=>{let a=!0;(async()=>{try{let i=await n.getState(),c=e(i);a&&l(c)}catch(i){console.error("Failed to initialize storage value:",i)}})();let S;try{S=n.subscribe(e,i=>{a&&l(i)})}catch(i){console.error("Failed to subscribe to storage:",i),S=()=>{}}return()=>{a=!1,S()}},[n,e]),t};import{createContext as M,useContext as y,useEffect as E,useRef as N,useState as v}from"react";var P=(n,e)=>{for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(typeof e[t]=="object"&&e[t]!==null&&!Array.isArray(e[t])?((!n[t]||typeof n[t]!="object")&&(n[t]={}),P(n[t],e[t])):n[t]=e[t])};import{jsx as g}from"react/jsx-runtime";var m="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",_="\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 ce(n,e){let{loadingComponent:t=null,mergeFn:l=P}=e||{},a=null,p=!1,S=(async()=>{try{a=await(n instanceof Promise?n:Promise.resolve(n)),p=!0}catch(o){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:",o)}})(),i=M(null),c=()=>{let o=y(i);if(!o)throw new Error(m);return o.storage},u=()=>{let o=y(i);if(!o)throw new Error(m);return o.selectors},r=()=>{let o=y(i);if(!o)throw new Error(m);if("actions"in o)return o.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.")},s=()=>{let o=y(i);if(!o)throw new Error(m);if("state$"in o)return o.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 T(o){function b({contextProps:d,...O}){let[W,L]=v(!1),[x,V]=v(p),$=N(`synapse-${a?.storage.name||"initializing"}`);return E(()=>{p||S.then(()=>{V(!0)})},[]),E(()=>{if(!x)return;let R=!0;return(async()=>{try{a&&d&&Object.keys(d).length>0&&await a.storage.update(h=>{l(h,d)}),R&&L(!0)}catch(h){console.error(`[${$.current}] ${_}`,h)}})(),()=>{R=!1}},[d,x]),x?W?g(i.Provider,{value:a,children:g(o,{...O})}):t||g("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||g("div",{children:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430..."})}let I=o.displayName||o.name||"Component";return b.displayName=`SynapseContext(${I})`,b}return{contextSynapse:T,useSynapseStorage:c,useSynapseSelectors:u,useSynapseActions:r,useSynapseState$:s,cleanupSynapse:async()=>(await S,a?.destroy()||Promise.resolve())}}export{ce as createSynapseCtx,q as useSelector,G as useStorageSubscribe};
1
+ import{useEffect as $,useRef as R,useState as A}from"react";var f=new Map;function k(o,e){let[t,l]=A(e?.initialValue),[a,p]=A(!!e?.withLoading),c=R(e?.initialValue),i=R(e?.equals||((n,s)=>n===s)),S=o.getId(),u=n=>{(c.current===void 0||!i.current(n,c.current))&&(c.current=n,l(n))};return $(()=>{f.has(S)||f.set(S,{lastValue:void 0,listeners:new Set,unsubscribe:null});let n=f.get(S);return n.listeners.add(u),n.lastValue!==void 0?(u(n.lastValue),e?.withLoading&&p(!1)):(e?.withLoading&&p(!0),o.select().then(s=>{n.lastValue=s,n.listeners.forEach(T=>T(s)),e?.withLoading&&p(!1)}).catch(s=>{e?.withLoading&&p(!1)})),n.unsubscribe||(n.unsubscribe=o.subscribe({notify:s=>{n.lastValue=s,n.listeners.forEach(T=>{try{T(s)}catch{}})}})),()=>{let s=f.get(S);s&&(s.listeners.delete(u),s.listeners.size===0&&(s.unsubscribe&&s.unsubscribe(),f.delete(S)))}},[o,S]),e?.withLoading?{data:t,isLoading:a}:t}import{useEffect as z,useState as F}from"react";var U=(o,e)=>{let[t,l]=F(void 0);return z(()=>{let a=!0;(async()=>{try{let i=await o.getState(),S=e(i);a&&l(S)}catch{}})();let c;try{c=o.subscribe(e,i=>{a&&l(i)})}catch{c=()=>{}}return()=>{a=!1,c()}},[o,e]),t};import{createContext as N,useContext as y,useEffect as E,useRef as _,useState as w}from"react";var h=(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]={}),h(o[t],e[t])):o[t]=e[t])};import{jsx as g}from"react/jsx-runtime";var m="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";function ae(o,e){let{loadingComponent:t=null,mergeFn:l=h}=e||{},a=null,p=!1,c=(async()=>{try{a=await(o instanceof Promise?o:Promise.resolve(o)),p=!0}catch{}})(),i=N(null),S=()=>{let r=y(i);if(!r)throw new Error(m);return r.storage},u=()=>{let r=y(i);if(!r)throw new Error(m);return r.selectors},n=()=>{let r=y(i);if(!r)throw new Error(m);if("actions"in r)return r.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.")},s=()=>{let r=y(i);if(!r)throw new Error(m);if("state$"in r)return r.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 T(r){function C({contextProps:d,...O}){let[W,L]=w(!1),[x,V]=w(p),D=_(`synapse-${a?.storage.name||"initializing"}`);return E(()=>{p||c.then(()=>{V(!0)})},[]),E(()=>{if(!x)return;let P=!0;return(async()=>{try{a&&d&&Object.keys(d).length>0&&await a.storage.update(b=>{l(b,d)}),P&&L(!0)}catch{}})(),()=>{P=!1}},[d,x]),x?W?g(i.Provider,{value:a,children:g(r,{...O})}):t||g("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||g("div",{children:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430..."})}let v=r.displayName||r.name||"Component";return C.displayName=`SynapseContext(${v})`,C}return{contextSynapse:T,useSynapseStorage:S,useSynapseSelectors:u,useSynapseActions:n,useSynapseState$:s,cleanupSynapse:async()=>(await c,a?.destroy()||Promise.resolve())}}export{ae as createSynapseCtx,k as useSelector,U as useStorageSubscribe};
@@ -1,7 +1,7 @@
1
- import { a as EnhancedMiddleware } from './dispatcher.module-jd8U_ZEs.js';
2
- export { A as Action, b as ActionDefinition, f as ActionsResult, d as ActionsSetup, c as ActionsSetupWithUtils, C as CreateDispatcherType, g as DispatchActions, D as DispatchFunction, k as Dispatcher, p as DispatcherActions, j as DispatcherMiddleware, i as DispatcherMiddlewareAPI, o as Effect, n as EffectBase, x as EffectsModule, E as EnhancedMiddlewareAPI, m as ExternalStates, e as ExtractResultType, T as TypedAction, V as ValidateConfig, q as ValidateMapRequestUtils, h as WatcherActions, W as WatcherFunction, B as combineEffects, l as createDispatcher, z as createEffect, y as createEffectBase, r as ofType, s as ofTypes, t as ofTypesWaitAll, u as selectorMap, v as selectorObject, w as validateMap } from './dispatcher.module-jd8U_ZEs.js';
1
+ import { a as EnhancedMiddleware } from './dispatcher.module-DjMloBXe.js';
2
+ export { A as Action, b as ActionDefinition, e as ActionsResult, c as ActionsSetupWithUtils, C as CreateDispatcherType, f as DispatchActions, D as DispatchFunction, j as Dispatcher, o as DispatcherActions, i as DispatcherMiddleware, h as DispatcherMiddlewareAPI, n as Effect, m as EffectBase, w as EffectsModule, E as EnhancedMiddlewareAPI, l as ExternalStates, d as ExtractResultType, T as TypedAction, V as ValidateConfig, p as ValidateMapRequestUtils, g as WatcherActions, W as WatcherFunction, z as combineEffects, k as createDispatcher, y as createEffect, x as createEffectBase, q as ofType, r as ofTypes, s as ofTypesWaitAll, t as selectorMap, u as selectorObject, v as validateMap } from './dispatcher.module-DjMloBXe.js';
3
3
  import 'rxjs';
4
- import './storage.interface-Dl8SLUd1.js';
4
+ import './storage.interface-2HKvqdAJ.js';
5
5
 
6
6
  interface LoggerTranslations {
7
7
  action: string;
package/dist/reactive.js CHANGED
@@ -1 +1 @@
1
- import{Subject as S}from"rxjs";var m=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 S;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}`,n=null,a=null,i=async o=>{let c=[o];if(t?.memoize&&n&&a&&t.memoize(c,n,a))return a;let l={type:s,meta:e.meta},p;if(this.middlewareFunctions.length>0){let T=async u=>t?.worker?this.executeInWorker(t.worker,s,c,e.action):Promise.resolve(e.action(o));for(let u=this.middlewareFunctions.length-1;u>=0;u--){let d=this.middlewareFunctions[u],y=T;T=async x=>d(async R=>y(R))(x)}p=await T(l)}else t?.worker?p=await this.executeInWorker(t.worker,s,c,e.action):p=await e.action(o);return l.payload=p,n=[...c],a=p,this.actions$.next(l),p};return i._type="dispatch",Object.defineProperty(i,"actionType",{value:s,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(i,"meta",{value:e.meta,writable:!1,enumerable:!0}),i}createWatcher(e){let t=`[${this.storage.name}]${e.type}`,s=new S,n,a=this.storage.subscribe(e.selector,o=>{if(!e.shouldTrigger||e.shouldTrigger(n,o)){let c={type:t,payload:o,meta:e.meta};this.actions$.next(c),s.next(c),n=o}}),i=()=>s.asObservable();return i._type="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:a,writable:!1,enumerable:!0}),i}async executeInWorker(e,t,s,n){return new Promise((a,i)=>{let o=`${t}_${Date.now()}_${Math.random()}`,c=l=>{l.data.requestId===o&&(e.removeEventListener("message",c),l.data.error?i(new Error(l.data.error)):a(l.data.result))};e.addEventListener("message",c),e.postMessage({type:t,args:s,requestId:o}),setTimeout(()=>{e.removeEventListener("message",c),i(new Error(`Worker execution timeout for action: ${t}`))},3e4)})}};function H(r,e){let t=new m(r),s=e(r.storage,{createAction:(n,a)=>t.createAction(n,a),createWatcher:n=>t.createWatcher(n)});for(let[n,a]of Object.entries(s))if(typeof a=="function"){let i=a._type;t[i][n]=a}return t}function w(r,e){let t={};return[...new Set([...Object.keys(r),...Object.keys(e)])].forEach(n=>{if(n in r&&n in e)if(typeof r[n]=="object"&&r[n]!==null&&typeof e[n]=="object"&&e[n]!==null&&!Array.isArray(r[n])&&!Array.isArray(e[n])){let a=w(r[n],e[n]);Object.keys(a).length>0&&(t[n]=a)}else JSON.stringify(r[n])!==JSON.stringify(e[n])&&(t[n]={PREV:r[n],NEXT:e[n]});else n in r?t[n]={PREV:r[n],NEXT:void 0}:t[n]={PREV:void 0,NEXT:e[n]}}),t}var Y=(r={})=>{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,...r,translations:{...e,...r.translations||{}},colors:{...t.colors,...r.colors||{}}},{collapsed:n,duration:a,colors:i,translations:o}=s;return c=>l=>async p=>{let T=Date.now(),u=await c.getState();try{let d=await l(p),y=await c.getState(),A=Date.now()-T,R=`${p.type}`;if((n?console.groupCollapsed:console.group)(`%c ${R}`,`color: ${i.title}; font-weight: bold`),console.log(`%c ${o.action}:`,`color: ${i.action}; font-weight: bold`,p),s.diff){let v=w(u,y),O=Object.keys(v).length;console.log(`%c ${o.diff} (${o.changesCount}: ${O}):`,`color: ${i.diff}; font-weight: bold`,v)}return s.showFullState&&(console.groupCollapsed(`%c ${o.showFullState}`,`color: ${i.fullState}; font-weight: bold`),console.log(`%c ${o.prevState}:`,`color: ${i.prevState}; font-weight: bold`,u),console.log(`%c ${o.nextState}:`,`color: ${i.nextState}; font-weight: bold`,y),console.groupEnd()),a&&console.log(`%c ${o.duration}: %c ${A}ms`,"font-weight: bold","color: #4CAF50"),console.groupEnd(),d}catch(d){throw console.error(`%c ${o.error}:`,`color: ${i.error}; font-weight: bold`,p.type,d),d}}};import{combineLatest as q,merge as B,Observable as K,of as f,pipe as L,Subject as V}from"rxjs";import{catchError as N,filter as h,map as b,share as _,switchMap as U,take as z}from"rxjs/operators";import{of as E}from"rxjs";import{concatAll as $,delay as C,mergeMap as W,toArray as k}from"rxjs/operators";function g(r,e=1){if(e<=0)throw new Error("Size must be greater than 0");if(!r||!r.length)return[];let t=[],s=r.length,n=0;for(;n<s;)t.push(r.slice(n,n+e)),n+=e;return t}var D=(r,e,t,s=0)=>{let n=g(e,t).map(a=>E(a).pipe(C(s),W(r)));return E(...n).pipe($(),k())};import{forkJoin as M,timer as j}from"rxjs";import{mergeMap as I}from"rxjs/operators";var P=(r,e,t,s=0)=>M(g(e,t).map((n,a)=>j(a*s).pipe(I(()=>r(n)))));function Ce(r){let{actionType:e}=r;return e?t=>t.pipe(h(s=>s!==void 0&&s.type===e)):(console.warn("ofType: Action function does not have actionType property",r),h(()=>!1))}function We(r){let e=r.map(t=>t.actionType).filter(Boolean);return e.length===0?(console.warn("ofTypes: No valid action types found in array",r),h(()=>!1)):t=>t.pipe(h(s=>s!==void 0&&e.includes(s.type)))}function ke(r){return e=>{let t=r.map(n=>n.actionType).filter(Boolean);if(t.length===0)return console.warn("ofTypesWaitAll: No valid action types found in array",r),f([]);let s=t.map((n,a)=>e.pipe(h(i=>i.type===n),z(1),b(i=>({index:a,action:i}))));return q(s).pipe(b(n=>(n.sort((a,i)=>a.index-i.index),n.map(a=>a.action))))}}function Me(r,...e){return r.pipe(b(t=>e.map(s=>s(t))))}function je(r,e){return r.pipe(b(t=>{let s={};for(let[n,a]of Object.entries(e))s[n]=a(t);return s}))}function Ie({validator:r,apiCall:e}){return L(U(t=>{let s=()=>e(t,{chunkRequest:P,chunkRequestConsistent:D});if(!r)return s();let n=r(t),{conditions:a,skipAction:i}=n;return a.every(Boolean)?s():Array.isArray(i)?f(...i?.filter(Boolean).map(c=>typeof c=="function"?c():c)):f(typeof i=="function"?i():i)}))}var F=class{constructor(e,t={},s,n={},a={}){this.storage=e;this.externalStates=t;this.dispatchers=s;this.services=n;this.config=a;this.subscribeToDispatchers(),this.state$=new K(i=>{this.storage.getState().then(c=>i.next(c));let o=this.storage.subscribeToAll(()=>{this.storage.getState().then(c=>i.next(c))});return()=>o()}).pipe(_())}effects=[];subscriptions=[];running=!1;action$=new V;state$;subscribeToDispatchers(){for(let[e,t]of Object.entries(this.dispatchers)){let s=t.actions.subscribe(n=>{this.action$.next(n)});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(N(n=>(console.error("Error in effect:",n),f(null)))).subscribe(n=>{if(n!=null&&typeof n=="function")try{n()}catch(a){console.error("Error calling effect result function:",a)}});this.subscriptions.push(s)}catch(t){console.error("Error setting up effect:",t)}}};function qe(r){return r}function Be(r){return r}function Ke(...r){return(e,t,s,n,a,i)=>{let o=r.map(c=>{try{return c(e,t,s,n,a,i)}catch(l){return console.error("Error in one of combined effects:",l),f(null)}});return B(...o)}}export{m as Dispatcher,F as EffectsModule,Ke as combineEffects,H as createDispatcher,Be as createEffect,qe as createEffectBase,Y as loggerDispatcherMiddleware,Ce as ofType,We as ofTypes,ke as ofTypesWaitAll,Me as selectorMap,je as selectorObject,Ie as validateMap};
1
+ import{Observable as O,Subject as A}from"rxjs";var m=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 A;actions=this.actions$.asObservable();dispatch={};watchers={};storage;middlewareFunctions=[];middlewareAPI;use(...e){for(let t=0;t<e.length;t++)try{let r=e[t](this.middlewareAPI);this.middlewareFunctions.push(r)}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 r=`[${this.storage.name}]${e.type}`,n=null,i=null,a=async l=>{let o=[l];if(t?.memoize&&n&&i&&t.memoize(o,n,i))return i;let c={type:r,meta:e.meta},u;if(this.middlewareFunctions.length>0){let d=async p=>t?.worker?this.executeInWorker(t.worker,r,o,e.action):Promise.resolve(e.action(l));for(let p=this.middlewareFunctions.length-1;p>=0;p--){let T=this.middlewareFunctions[p],b=d;d=async x=>T(async R=>b(R))(x)}u=await d(c)}else t?.worker?u=await this.executeInWorker(t.worker,r,o,e.action):u=await e.action(l);return c.payload=u,n=[...o],i=u,this.actions$.next(c),u};return a.e="dispatch",Object.defineProperty(a,"actionType",{value:r,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(a,"meta",{value:e.meta,writable:!1,enumerable:!0}),a}createWatcher(e){let t=`[${this.storage.name}]${e.type}`,r=new A,n,i=async()=>{let o=await this.storage.getState();return e.selector(o)},a=this.storage.subscribe(e.selector,o=>{if(!e.shouldTrigger||e.shouldTrigger(n,o)){let c={type:t,payload:o,meta:e.meta};this.actions$.next(c),r.next(c),n=o}}),l=()=>{let o=r.asObservable();return e.notifyAfterSubscribe?new O(c=>{let u=!1;i().then(p=>{if(!e.shouldTrigger||e.shouldTrigger(void 0,p)){let T={type:t,payload:p,meta:{...e.meta,isInitial:!0}};c.next(T),n=p,u=!0}}).catch(p=>{c.error(p)});let d=o.subscribe({next:p=>{u&&p.payload===n||c.next(p)},error:p=>c.error(p),complete:()=>c.complete()});return()=>{d.unsubscribe()}}):o};return l.e="watchers",Object.defineProperty(l,"actionType",{value:t,writable:!1,enumerable:!0}),e.meta&&Object.defineProperty(l,"meta",{value:e.meta,writable:!1,enumerable:!0}),Object.defineProperty(l,"unsubscribe",{value:a,writable:!1,enumerable:!0}),l}async executeInWorker(e,t,r,n){return new Promise((i,a)=>{let l=`${t}_${Date.now()}_${Math.random()}`,o=c=>{c.data.requestId===l&&(e.removeEventListener("message",o),c.data.error?a(new Error(c.data.error)):i(c.data.result))};e.addEventListener("message",o),e.postMessage({type:t,args:r,requestId:l}),setTimeout(()=>{e.removeEventListener("message",o),a(new Error(`Worker execution timeout for action: ${t}`))},3e4)})}};function H(s,e){let t=new m(s),r=e(s.storage,{createAction:(n,i)=>t.createAction(n,i),createWatcher:n=>t.createWatcher(n)});for(let[n,i]of Object.entries(r))if(typeof i=="function"){let a=i.e;t[a][n]=i}return t}function v(s,e){let t={};return[...new Set([...Object.keys(s),...Object.keys(e)])].forEach(n=>{if(n in s&&n in e)if(typeof s[n]=="object"&&s[n]!==null&&typeof e[n]=="object"&&e[n]!==null&&!Array.isArray(s[n])&&!Array.isArray(e[n])){let i=v(s[n],e[n]);Object.keys(i).length>0&&(t[n]=i)}else JSON.stringify(s[n])!==JSON.stringify(e[n])&&(t[n]={PREV:s[n],NEXT:e[n]});else n in s?t[n]={PREV:s[n],NEXT:void 0}:t[n]={PREV:void 0,NEXT:e[n]}}),t}var Y=(s={})=>{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"}},r={...t,...s,translations:{...e,...s.translations||{}},colors:{...t.colors,...s.colors||{}}},{collapsed:n,duration:i,colors:a,translations:l}=r;return o=>c=>async u=>{let d=Date.now(),p=await o.getState();try{let T=await c(u),b=await o.getState(),P=Date.now()-d,R=`${u.type}`;if((n?console.groupCollapsed:console.group)(`%c ${R}`,`color: ${a.title}; font-weight: bold`),r.diff){let F=v(p,b),X=Object.keys(F).length}return r.showFullState,T}catch(T){throw T}}};import{combineLatest as q,merge as B,Observable as K,of as f,pipe as L,Subject as V}from"rxjs";import{catchError as N,filter as h,map as g,share as U,switchMap as z,take as _}from"rxjs/operators";import{of as S}from"rxjs";import{concatAll as $,delay as C,mergeMap as W,toArray as k}from"rxjs/operators";function y(s,e=1){if(e<=0)throw new Error("Size must be greater than 0");if(!s||!s.length)return[];let t=[],r=s.length,n=0;for(;n<r;)t.push(s.slice(n,n+e)),n+=e;return t}var w=(s,e,t,r=0)=>{let n=y(e,t).map(i=>S(i).pipe(C(r),W(s)));return S(...n).pipe($(),k())};import{forkJoin as M,timer as j}from"rxjs";import{mergeMap as I}from"rxjs/operators";var E=(s,e,t,r=0)=>M(y(e,t).map((n,i)=>j(i*r).pipe(I(()=>s(n)))));function $e(s){let{actionType:e}=s;return e?t=>t.pipe(h(r=>r!==void 0&&r.type===e)):h(()=>!1)}function Ce(s){let e=s.map(t=>t.actionType).filter(Boolean);return e.length===0?h(()=>!1):t=>t.pipe(h(r=>r!==void 0&&e.includes(r.type)))}function We(s){return e=>{let t=s.map(n=>n.actionType).filter(Boolean);if(t.length===0)return f([]);let r=t.map((n,i)=>e.pipe(h(a=>a.type===n),_(1),g(a=>({index:i,action:a}))));return q(r).pipe(g(n=>(n.sort((i,a)=>i.index-a.index),n.map(i=>i.action))))}}function ke(s,...e){return s.pipe(g(t=>e.map(r=>r(t))))}function Me(s,e){return s.pipe(g(t=>{let r={};for(let[n,i]of Object.entries(e))r[n]=i(t);return r}))}function je({validator:s,apiCall:e}){return L(z(t=>{let r=()=>e(t,{chunkRequest:E,chunkRequestConsistent:w});if(!s)return r();let n=s(t),{conditions:i,skipAction:a}=n;return i.every(Boolean)?r():Array.isArray(a)?f(...a?.filter(Boolean).map(o=>typeof o=="function"?o():o)):f(typeof a=="function"?a():a)}))}var D=class{constructor(e,t={},r,n={},i={}){this.storage=e;this.externalStates=t;this.dispatchers=r;this.services=n;this.config=i;this.subscribeToDispatchers(),this.state$=new K(a=>{this.storage.getState().then(o=>a.next(o));let l=this.storage.subscribeToAll(()=>{this.storage.getState().then(o=>a.next(o))});return()=>l()}).pipe(U())}effects=[];subscriptions=[];running=!1;action$=new V;state$;subscribeToDispatchers(){for(let[e,t]of Object.entries(this.dispatchers)){let r=t.actions.subscribe(n=>{this.action$.next(n)});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}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 r=e(this.action$.asObservable(),this.state$,this.externalStates,this.dispatchers,this.services,this.config).pipe(N(n=>f(null))).subscribe(n=>{if(n!=null&&typeof n=="function")try{n()}catch{}});this.subscriptions.push(r)}catch{}}};function Ie(s){return s}function qe(s){return s}function Be(...s){return(e,t,r,n,i,a)=>{let l=s.map(o=>{try{return o(e,t,r,n,i,a)}catch{return f(null)}});return B(...l)}}export{m as Dispatcher,D as EffectsModule,Be as combineEffects,H as createDispatcher,qe as createEffect,Ie as createEffectBase,Y as loggerDispatcherMiddleware,$e as ofType,Ce as ofTypes,We as ofTypesWaitAll,ke as selectorMap,Me as selectorObject,je as validateMap};