synapse-storage
Version:
Набор инструментов для управления состоянием и апи-запросами
2 lines (1 loc) • 8.56 kB
JavaScript
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};