UNPKG

@zedux/stores

Version:

The legacy composable store model of Zedux

2 lines (1 loc) 12.5 kB
(function(c,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("@zedux/atoms")):typeof define=="function"&&define.amd?define(["exports","@zedux/atoms"],h):(c=typeof globalThis<"u"?globalThis:c||self,h(c.ZeduxStores={},c.ZeduxAtoms))})(this,function(c,h){"use strict";const Y=s=>{const t=Object.getPrototypeOf(s);return t?Object.getPrototypeOf(t)?"complex object":"object":"prototype-less object"},tt=s=>{const t=typeof s;return t!=="object"?t:s?Array.isArray(s)?"array":Y(s):"null"},et=s=>{const t=e=>{const r={type:t.type};return typeof e<"u"&&(r.payload=e),r};return t.type=s,t},z=(s,t)=>typeof s=="string"?s:s.type,st=(s,t)=>s.map(e=>z(e)),rt=s=>{const t={},e=(r=s,i)=>{const n=t[i.type]||[];return nt(n,r,i)};return e.reduce=(r,i)=>{const n=Array.isArray(r)?st(r):[z(r)];return it(t,n,i),e},e},it=(s,t,e)=>{t.forEach(r=>{s[r]||(s[r]=[]),s[r].push(e)})},nt=(s,t,e)=>s.reduce((r,i)=>i(r,e.payload,e),t),y=(s,t)=>{var e;return((e=s==null?void 0:s.constructor)===null||e===void 0?void 0:e.$$typeof)===t.$$typeof},p=s=>{if(typeof s!="object"||!s)return!1;const t=Object.getPrototypeOf(s);return t?Object.getPrototypeOf(t)===null:!1},_="@@zedux/",u={batch:`${_}batch`,delegate:`${_}delegate`,hydrate:`${_}hydrate`,ignore:`${_}ignore`,inherit:`${_}inherit`,merge:`${_}merge`,prime:`${_}prime`},b=1,m=2,x=3,C=4,ot=Symbol.for("zedux.store"),ct=(s,t,e)=>{const r={};return Object.entries(s).forEach(([i,n])=>{const o=[...e,i];r[i]=N(n,t,o)}),r},ht=(s,t,e,r)=>s===m?{type:s}:s===x?{type:s,reducer:t}:{type:s,destroy:e(r,t),reducer:at(t),store:t},ut=s=>typeof s=="function"?x:s&&y(s,l)?C:p(s)?b:m,N=(s,t,e=[])=>{const r=ut(s);return r!==b?ht(r,s,t,e):{type:r,children:ct(s,t,e)}},at=s=>(e,r)=>{(r.type===u.hydrate||r.type===u.merge)&&(r={type:u.hydrate,payload:e});const i={metaType:u.inherit,payload:r};return s.dispatch(i)},dt=s=>(t={},e)=>{const r={};let i=!1;return Object.keys(s).forEach(n=>{const{reducer:o}=s[n],a=p(t)?t[n]:void 0,d=o(a,e);r[n]=d,i||(i=d!==a)}),i||(i=!p(t)||!Object.keys(s).length&&!!Object.keys(t).length),i?r:t},w=s=>{if(!s)return;const{children:t,destroy:e}=s;e&&e(),t&&Object.values(t).forEach(w)},R=(s,t)=>{const e=Object.assign({},s.children);return Object.keys(t.children).forEach(r=>{var i;const n=t.children[r],o=(i=s.children)===null||i===void 0?void 0:i[r],a=M(o,n);if(a.type===m){delete e[r];return}e[r]=a}),{children:e,reducer:dt(e),type:b}},M=(s,t)=>t.type!==b?(w(s),t):!s||s.type!==b?(w(s),R({type:m},t)):R(s,t),D=(s,t)=>{if(!p(s)||!p(t))return[t,t!==s];let e=!1;const r=Object.assign({},s);return Object.keys(t).forEach(i=>{const n=t[i],o=r[i],[a,d]=p(n)?D(o,n):[n,n!==o];d&&(e||(e=d),r[i]=a)}),[e?r:s,e]},lt=(s,t,e)=>!t||!e?s.payload:(t.payload=s.payload,e),H=(s,t)=>{for(;s.metaType;){if(s.metaType===t)return s.metaData;s=s.payload}},B=s=>{for(;s.metaType;)s=s.payload;return s},U=(s,t)=>{let e=s,r=null,i=null;for(;e.metaType;){if(e.metaType===t)return lt(e,r,i);const n=Object.assign({},e);r&&(r.payload=n),r=n,e=e.payload,i||(i=r)}return s},A="Minified Error",ft=(s,t)=>{for(const e of t){if(s.type!==b)throw new ReferenceError(A);if(s=s.children[e],!s)throw new ReferenceError(A)}return s},pt=(s,t)=>{const e=H(t,u.delegate);if(!e||!s)return!1;const r=ft(s,e);if(r.type!==C)throw new TypeError(A);r.store.dispatch(U(t,u.delegate))},F=(s,t,e)=>{if(!t.length)return e;const r=Object.assign({},s),i=t[0];return r[i]=F(s[i],t.slice(1),e),r},_t={scheduleNow:s=>s.j()},Z={type:u.prime},v=(s,t)=>new l(s,t);class l{constructor(t,e){this._isSolo=!0,this._subscribers=[],this.dispatch=r=>this._isSolo?this._dispatch(r):(this._scheduler.scheduleNow({j:()=>this._dispatch(r),T:0}),this._state),this.setState=(r,i)=>this._isSolo?this._setState(r,i):(this._scheduler.scheduleNow({j:()=>this._setState(r,i),T:0}),this._state),this._state=e,this._scheduler=l._scheduler||_t,t&&this.use(t)}actionStream(){return{[Symbol.observable](){return this},"@@observable"(){return this},subscribe:t=>this.subscribe({effects:({action:e,error:r})=>{var i,n;r&&typeof t!="function"?(i=t.error)===null||i===void 0||i.call(t,r):e&&(typeof t=="function"?t(e):(n=t.next)===null||n===void 0||n.call(t,e))}})}}getState(){return this._state}setStateDeep(t,e){return this._isSolo?this._setState(t,e,!0):(this._scheduler.scheduleNow({j:()=>this._setState(t,e,!0),T:0}),this._state)}subscribe(t){const e=typeof t=="function"?{next:t}:t;return this._subscribers.push(e),{unsubscribe:()=>{this._subscribers=this._subscribers.filter(i=>i!==e)}}}use(t){const e=N(t,(i,n)=>this._registerChildStore(i,n)),r=this._tree=M(this._tree,e);return(this._rootReducer=r.reducer)&&this._dispatchAction(Z,Z,this._state),this}_register(t){const e=this._parents||(this._parents=[]);return e.push(t),this._isSolo=!1,()=>{const r=e.indexOf(t);r>-1&&e.splice(r,1)}}[Symbol.observable](){return this}"@@observable"(){return this}_dispatch(t){return pt(this._tree,t)!==!1?this._state:this._routeAction(t)}_dispatchAction(t,e,r){this._isDispatching=!0;let i,n=r;try{this._rootReducer&&(n=this._rootReducer(r,e))}catch(o){throw i=o,o}finally{this._isDispatching=!1,this._notify(n,t,i)}return n}_dispatchHydration(t,e,r){const i=e===u.hydrate?t:D(this._state,t)[0];if(i===this._state&&!r)return this._state;const n={meta:r,payload:i,type:e};return this._dispatchAction(n,n,i)}_dispatchStateSetter(t,e,r){let i;try{i=t(this._state)}catch(n){throw n}return this._dispatchHydration(i,r?u.merge:u.hydrate,e)}_doNotify(t){const{_subscribers:e}=this,r=t.newState!==t.oldState;for(const i of e)t.error&&i.error&&i.error(t.error),r&&i.next&&i.next(t.newState,t.oldState,t.action),i.effects&&i.effects(t)}_notify(t,e,r){var i;const n={action:e,error:r,newState:t,oldState:this._state,store:this};if(this._state=t,this._isSolo)return this._doNotify(n);this._scheduler.scheduleNow({j:()=>this._doNotify(n),T:1}),(i=this._parents)===null||i===void 0||i.forEach(o=>o(n))}_registerChildStore(t,e){this._isSolo=!1;const r=({action:i,error:n,newState:o,oldState:a})=>{if(this._isDispatching)return;const d=o===a?this._state:F(this._state,t,o),f={metaType:u.delegate,metaData:t,payload:i};this._notify(d,f,n)};return e._register(r)}_routeAction(t){const e=B(t);return e.type===u.hydrate||e.type===u.merge?this._dispatchHydration(e.payload,e.type,e.meta):this._dispatchAction(t,e,this._state)}_setState(t,e,r=!1){return typeof t=="function"?this._dispatchStateSetter(t,e,r):this._dispatchHydration(t,r?u.merge:u.hydrate,e)}}l.$$typeof=ot;const j="@@zedux",yt=1,bt=3,G=s=>({error:s,isError:!0,isLoading:!1,isSuccess:!1,status:"error"}),T=s=>({data:s,isError:!1,isLoading:!0,isSuccess:!1,status:"loading"}),L=s=>({data:s,isError:!1,isLoading:!1,isSuccess:!0,status:"success"}),V=class{constructor(s){this.promise=void 0,this.value=s,this.store=y(s,l)?s:void 0,y(s,V)&&Object.assign(this,s)}addExports(s){return this.exports?this.exports={...this.exports,...s}:this.exports=s,this}setExports(s){return this.exports=s,this}setPromise(s){return this.promise=s,this}setTtl(s){return this.ttl=s,this}};let S=V;S.$$typeof=Symbol.for(`${j}/AtomApi`);const k=s=>new S(s),q=1,E=2,K=s=>y(s,l)?q:E,gt=s=>{const t=K(s),e=t===q?s:v();return t===E&&e.setState(typeof s=="function"?()=>s:s),[t,e]};class O extends h.AtomInstance{constructor(t,e,r,i){super(t,e,r,i),this.e=t,this.t=e,this.id=r,this.p=i,this.dispatch=n=>this.store.dispatch(n),this.setState=(n,o)=>this.store.setState(n,o),this.setStateDeep=(n,o)=>this.store.setStateDeep(n,o),this._createdAt=t._idGenerator.now()}destroy(t){var r,i;if(!h.zi.b(this,t))return;const e=[];(r=this._injectors)==null||r.forEach(n=>{var o;if(n.type!=="@@zedux/effect"){e.push(n);return}(o=n.cleanup)==null||o.call(n)}),e.forEach(n=>{var o;(o=n.cleanup)==null||o.call(n)}),(i=this._subscription)==null||i.unsubscribe(),h.zi.e(this)}getState(){return this.store.getState()}get(){return this.store.getState()}invalidate(){this.r({t:yt},!1),this.e._scheduler.flush()}mutate(){throw new Error("`.mutate()` is not supported in legacy, store-based atoms. Upgrade to the new `atom()` factory")}set(t,e){return this.setState(t,e&&Object.keys(e)[0])}j(){const{n:t,s:e}=h.zi.g();this._nextInjectors=[],this._isEvaluating=!0,l._scheduler=this.e._scheduler,h.zi.s(this);try{const r=this._eval();this.l==="Initializing"?([this._stateType,this.store]=gt(r),this._subscription=this.store.subscribe((i,n,o)=>{if(this._isEvaluating){this._bufferedUpdate={newState:i,oldState:n,action:o};return}this._handleStateChange(i,n,o)})):K(r)===E&&this.store.setState(typeof r=="function"?()=>r:r)}catch(r){throw this._nextInjectors.forEach(i=>{var n;(n=i.cleanup)==null||n.call(i)}),h.zi.d(t,e),r}finally{this._isEvaluating=!1,t||(l._scheduler=void 0),this._bufferedUpdate&&(this._handleStateChange(this._bufferedUpdate.newState,this._bufferedUpdate.oldState,this._bufferedUpdate.action),this._bufferedUpdate=void 0),this.w=[]}this._injectors=this._nextInjectors,this.l!=="Initializing"&&h.zi.f(t,e)}r(t,e){this.l!=="Destroyed"&&this.w.push(t)===1&&this.e._scheduler.schedule(this,e)}get _infusedSetter(){if(this._set)return this._set;const t=(e,r)=>this.setState(e,r);return this._set=Object.assign(t,this.exports)}_eval(){var e;const{_value:t}=this.t;if(typeof t!="function")return t;try{const r=t(...this.p);if(!y(r,S))return r;const i=this.api=r;return this.l==="Initializing"&&i.exports&&(this.exports=i.exports),typeof((e=i.value)==null?void 0:e.then)=="function"?this._setPromise(i.value,!0):(i.promise&&this._setPromise(i.promise),i.value)}catch(r){throw console.error(`Zedux: Error while evaluating atom "${this.t.key}" with params:`,this.p,r),r}}_handleStateChange(t,e,r){h.zi.u({p:e,r:this.w,s:this},!1),this.e._mods.stateChanged&&this.e.modBus.dispatch(h.ZeduxPlugin.actions.stateChanged({action:r,node:this,newState:t,oldState:e,reasons:this.w})),r.meta!==u.batch&&this.e._scheduler.flush()}_setPromise(t,e){var n;const r=(n=this.store)==null?void 0:n.getState();if(t===this.promise)return r;this.promise=t,t.then(o=>{this.promise===t&&(this._promiseStatus="success",e&&this.store.setState(L(o)))}).catch(o=>{this.promise===t&&(this._promiseStatus="error",this._promiseError=o,e&&this.store.setState(G(o)))});const i=T(r==null?void 0:r.data);return this._promiseStatus=i.status,h.zi.u({s:this,t:bt},!0,!0),i}}O.$$typeof=Symbol.for(`${j}/AtomInstance`);class I extends h.AtomTemplateBase{_createInstance(t,e,r){return new O(t,this,e,r)}getInstanceId(t,e){const r=this.key;return e!=null&&e.length?`${r}-${t._idGenerator.hashParams(e,t.complexParams)}`:r}override(t){const e=W(this.key,t,this._config);return e._isOverride=!0,e}}const W=(s,t,e)=>new I(s,t,e),$=(s,t)=>t.subscribe((e,r,i)=>{if(s._isEvaluating||i.meta===u.ignore)return;const n=(i==null?void 0:i.meta)===u.batch;s.r({p:r},n),n||s.e._scheduler.flush()}),X=h.zi.c("injectStore",(s,t,e)=>{var a;const r=(e==null?void 0:e.subscribe)??!0,n=(typeof t=="function"?t:d=>v(null,d??t))(e!=null&&e.hydrate?(a=s.e.hydration)==null?void 0:a[s.id]:void 0),o=r&&$(s,n);return{cleanup:o?()=>o.unsubscribe():void 0,result:n,type:`${j}/store`}},(s,t,e,r)=>{const i=(r==null?void 0:r.subscribe)??!0;if(!!s.cleanup===i)return s;if(!i)return s.cleanup(),s.cleanup=void 0,s;const o=$(t,s.result);return s.cleanup=()=>o.unsubscribe(),s}),mt=(s,t,{dataOnly:e,initialState:r,runOnInvalidate:i,...n}={})=>{const o=h.injectRef({counter:0}),a=X(e?r:T(r),n);return i&&h.injectWhy().some(d=>d.type==="cache invalidated")&&o.current.counter++,o.current.promise=h.injectMemo(()=>{const d=o.current.controller,f=typeof AbortController<"u"?new AbortController:void 0;o.current.controller=f;const P=s(o.current.controller);return P===o.current.promise?o.current.promise:(d&&d.abort("updated"),e||a.setStateDeep(g=>T(g.data)),P.then(g=>{f!=null&&f.signal.aborted||a.setState(e?g:L(g))}).catch(g=>{e||f!=null&&f.signal.aborted||a.setStateDeep(G(g))}),P)},t&&[...t,o.current.counter]),h.injectEffect(()=>()=>{const d=o.current.controller;d&&d.abort("destroyed")},[]),k(a).setPromise(o.current.promise)};class J extends I{constructor(t,e,r){super(t,(...i)=>e(h.injectAtomGetters(),...i),r),this._get=e}override(t){const e=Q(this.key,t||this._get,this._config);return e._isOverride=!0,e}}const Q=(s,t,e)=>new J(s,t,e);c.AtomApi=S,c.AtomInstance=O,c.AtomTemplate=I,c.IonTemplate=J,c.Store=l,c.actionFactory=et,c.api=k,c.atom=W,c.createReducer=rt,c.createStore=v,c.detailedTypeof=tt,c.doSubscribe=$,c.getMetaData=H,c.injectPromise=mt,c.injectStore=X,c.ion=Q,c.is=y,c.isPlainObject=p,c.removeAllMeta=B,c.removeMeta=U,c.zeduxTypes=u,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});