@zedux/atoms
Version:
A Molecular State Engine for React
3 lines (2 loc) • 35.1 kB
JavaScript
(function(u,O){typeof exports=="object"&&typeof module<"u"?O(exports):typeof define=="function"&&define.amd?define(["exports"],O):(u=typeof globalThis<"u"?globalThis:u||self,O(u.ZeduxAtoms={}))})(this,function(u){"use strict";const O=i=>{const t=Object.getPrototypeOf(i);return t?Object.getPrototypeOf(t)?"complex object":"object":"prototype-less object"},Nt=i=>{const t=typeof i;return t!=="object"?t:i?Array.isArray(i)?"array":O(i):"null"},j=i=>{const t=e=>{const s={type:t.type};return typeof e<"u"&&(s.payload=e),s};return t.type=i,t},K=(i,t)=>typeof i=="string"?i:i.type,Bt=(i,t)=>i.map(e=>K(e)),Pt=i=>{const t={},e=(s=i,n)=>{const r=t[n.type]||[];return xt(r,s,n)};return e.reduce=(s,n)=>{const r=Array.isArray(s)?Bt(s):[K(s)];return Mt(t,r,n),e},e},Mt=(i,t,e)=>{t.forEach(s=>{i[s]||(i[s]=[]),i[s].push(e)})},xt=(i,t,e)=>i.reduce((s,n)=>n(s,e.payload,e),t),_=(i,t)=>{var e;return((e=i==null?void 0:i.constructor)===null||e===void 0?void 0:e.$$typeof)===t.$$typeof},N=i=>{if(typeof i!="object"||!i)return!1;const t=Object.getPrototypeOf(i);return t?Object.getPrototypeOf(t)===null:!1},k="@@zedux/",f={batch:`${k}batch`,delegate:`${k}delegate`,hydrate:`${k}hydrate`,ignore:`${k}ignore`,inherit:`${k}inherit`,merge:`${k}merge`,prime:`${k}prime`},w=1,B=2,tt=3,et=4,Dt=Symbol.for("zedux.store"),Gt=(i,t,e)=>{const s={};return Object.entries(i).forEach(([n,r])=>{const o=[...e,n];s[n]=st(r,t,o)}),s},zt=(i,t,e,s)=>i===B?{type:i}:i===tt?{type:i,reducer:t}:{type:i,destroy:e(s,t),reducer:Ut(t),store:t},Ht=i=>typeof i=="function"?tt:i&&_(i,m)?et:N(i)?w:B,st=(i,t,e=[])=>{const s=Ht(i);return s!==w?zt(s,i,t,e):{type:s,children:Gt(i,t,e)}},Ut=i=>(e,s)=>{(s.type===f.hydrate||s.type===f.merge)&&(s={type:f.hydrate,payload:e});const n={metaType:f.inherit,payload:s};return i.dispatch(n)},Wt=(i,{create:t,get:e,isNode:s,set:n,size:r})=>(o=t(),c)=>{let h=t(),a=!1;return Object.keys(i).forEach(d=>{const{reducer:l}=i[d],p=s(o)?e(o,d):void 0,x=l(p,c);h=n(h,d,x),a||(a=x!==p)}),a||(a=!s(o)||!Object.keys(i).length&&!!r(o)),a?h:o},D=i=>{if(!i)return;const{children:t,destroy:e}=i;e&&e(),t&&Object.values(t).forEach(D)},nt=(i,t,e)=>{const s=Object.assign({},i.children);return Object.keys(t.children).forEach(n=>{var r;const o=t.children[n],c=(r=i.children)===null||r===void 0?void 0:r[n],h=it(c,o,e);if(h.type===B){delete s[n];return}s[n]=h}),{children:s,reducer:Wt(s,e),type:w}},it=(i,t,e)=>t.type!==w?(D(i),t):!i||i.type!==w?(D(i),nt({type:B},t,e)):nt(i,t,e),rt=(i,t,e)=>{if(!e.isNode(i)||!e.isNode(t))return[t,t!==i];let s=!1;const n=e.clone(i);return e.iterate(t,(r,o)=>{const c=e.get(n,r),[h,a]=e.isNode(o)?rt(c,o,e):[o,o!==c];a&&(s||(s=a),e.set(n,r,h))}),[s?n:i,s]},Lt=(i,t,e)=>!t||!e?i.payload:(t.payload=i.payload,e),ot=(i,t)=>{for(;i.metaType;){if(i.metaType===t)return i.metaData;i=i.payload}},ct=i=>{for(;i.metaType;)i=i.payload;return i},at=(i,t)=>{let e=i,s=null,n=null;for(;e.metaType;){if(e.metaType===t)return Lt(e,s,n);const r=Object.assign({},e);s&&(s.payload=r),s=r,e=e.payload,n||(n=s)}return i},G="Minified Error",Ft=(i,t)=>{for(const e of t){if(i.type!==w)throw new ReferenceError(G);if(i=i.children[e],!i)throw new ReferenceError(G)}return i},Zt=(i,t)=>{const e=ot(t,f.delegate);if(!e||!i)return!1;const s=Ft(i,e);if(s.type!==et)throw new TypeError(G);s.store.dispatch(at(t,f.delegate))},ht=(i,t,e,s)=>{if(!t.length)return e;const n=s.clone(i),r=t[0];return s.set(n,r,ht(s.get(i,r),t.slice(1),e,s))},Vt=Object.freeze(Object.defineProperty({__proto__:null,clone:i=>Object.assign({},i),create:()=>({}),get:(i,t)=>i[t],isNode:N,iterate:(i,t)=>{Object.entries(i).forEach(([e,s])=>t(e,s))},set:(i,t,e)=>(i[t]=e,i),size:i=>Object.keys(i).length},Symbol.toStringTag,{value:"Module"})),Xt={scheduleNow:i=>i.task()},ut={type:f.prime},C=(i,t)=>new m(i,t);class m{constructor(t,e){this._isSolo=!0,this._subscribers=[],this.dispatch=s=>this._isSolo?this._dispatch(s):(this._scheduler.scheduleNow({task:()=>this._dispatch(s),type:0}),this._state),this.setState=(s,n)=>this._isSolo?this._setState(s,n):(this._scheduler.scheduleNow({task:()=>this._setState(s,n),type:0}),this._state),this._state=e,this._scheduler=m._scheduler||Xt,t&&this.use(t)}actionStream(){return{[Symbol.observable](){return this},"@@observable"(){return this},subscribe:t=>this.subscribe({effects:({action:e,error:s})=>{var n,r;s&&typeof t!="function"?(n=t.error)===null||n===void 0||n.call(t,s):e&&(typeof t=="function"?t(e):(r=t.next)===null||r===void 0||r.call(t,e))}})}}getState(){return this._state}setStateDeep(t,e){return this._isSolo?this._setState(t,e,!0):(this._scheduler.scheduleNow({task:()=>this._setState(t,e,!0),type:0}),this._state)}subscribe(t){const e=typeof t=="function"?{next:t}:t;return this._subscribers.push(e),{unsubscribe:()=>{this._subscribers=this._subscribers.filter(n=>n!==e)}}}use(t){const e=st(t,(n,r)=>this._registerChildStore(n,r)),s=this._tree=it(this._tree,e,this.constructor.hierarchyConfig);return(this._rootReducer=s.reducer)&&this._dispatchAction(ut,ut,this._state),this}_register(t){const e=this._parents||(this._parents=[]);return e.push(t),this._isSolo=!1,()=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)}}[Symbol.observable](){return this}"@@observable"(){return this}_dispatch(t){return Zt(this._tree,t)!==!1?this._state:this._routeAction(t)}_dispatchAction(t,e,s){this._isDispatching=!0;let n,r=s;try{this._rootReducer&&(r=this._rootReducer(s,e))}catch(o){throw n=o,o}finally{this._isDispatching=!1,this._notify(r,t,n)}return r}_dispatchHydration(t,e,s){const n=e===f.hydrate?t:rt(this._state,t,this.constructor.hierarchyConfig)[0];if(n===this._state&&!s)return this._state;const r={meta:s,payload:n,type:e};return this._dispatchAction(r,r,n)}_dispatchStateSetter(t,e,s){let n;try{n=t(this._state)}catch(r){throw r}return this._dispatchHydration(n,s?f.merge:f.hydrate,e)}_doNotify(t){const{_subscribers:e}=this,s=t.newState!==t.oldState;for(const n of e)t.error&&n.error&&n.error(t.error),s&&n.next&&n.next(t.newState,t.oldState,t.action),n.effects&&n.effects(t)}_notify(t,e,s){var n;const r={action:e,error:s,newState:t,oldState:this._state,store:this};if(this._state=t,this._isSolo)return this._doNotify(r);this._scheduler.scheduleNow({task:()=>this._doNotify(r),type:1}),(n=this._parents)===null||n===void 0||n.forEach(o=>o(r))}_registerChildStore(t,e){this._isSolo=!1;const s=({action:n,error:r,newState:o,oldState:c})=>{if(this._isDispatching)return;const h=o===c?this._state:ht(this._state,t,o,this.constructor.hierarchyConfig),a={metaType:f.delegate,metaData:t,payload:n};this._notify(h,a,r)};return e._register(s)}_routeAction(t){const e=ct(t);return e.type===f.hydrate||e.type===f.merge?this._dispatchHydration(e.payload,e.type,e.meta):this._dispatchAction(t,e,this._state)}_setState(t,e,s=!1){return typeof t=="function"?this._dispatchStateSetter(t,e,s):this._dispatchHydration(t,s?f.merge:f.hydrate,e)}}m.hierarchyConfig=Vt,m.$$typeof=Dt;const g={ecosystemWiped:j("ecosystemWiped"),edgeCreated:j("edgeCreated"),edgeRemoved:j("edgeRemoved"),evaluationFinished:j("evaluationFinished"),instanceReused:j("instanceReused"),stateChanged:j("stateChanged"),statusChanged:j("statusChanged")},dt=i=>({error:i,isError:!0,isLoading:!1,isSuccess:!1,status:"error"}),z=i=>({data:i,isError:!1,isLoading:!0,isSuccess:!1,status:"loading"}),lt=i=>({data:i,isError:!1,isLoading:!1,isSuccess:!0,status:"success"}),H=1,R=2,A=4,U=(i,t)=>!i||!t||i.length!==t.length||i.some((e,s)=>t[s]!==e),v="@@zedux",ft=class{constructor(i){this.promise=void 0,this.value=i,this.store=_(i,m)?i:void 0,_(i,ft)&&Object.assign(this,i)}addExports(i){return this.exports?this.exports={...this.exports,...i}:this.exports=i,this}setExports(i){return this.exports=i,this}setPromise(i){return this.promise=i,this}setTtl(i){return this.ttl=i,this}};let P=ft;P.$$typeof=Symbol.for(`${v}/AtomApi`);class I{addDependent({callback:t,operation:e="addDependent"}={}){const s=this.ecosystem._idGenerator.generateNodeId();return this.ecosystem._graph.addEdge(s,this.id,e,H|R,t),()=>this.ecosystem._graph.removeEdge(s,this.id)}}I.$$typeof=Symbol.for(`${v}/AtomInstanceBase`);const yt=1,W=2,pt=i=>_(i,m)?yt:W,qt=i=>{const t=pt(i),e=t===yt?i:C();return t===W&&e.setState(typeof i=="function"?()=>i:i),[t,e]};class L extends I{constructor(t,e,s,n){super(),this.ecosystem=t,this.template=e,this.id=s,this.params=n,this.status="Initializing",this.nextReasons=[],this.dispatch=r=>this.store.dispatch(r),this.setState=(r,o)=>this.store.setState(r,o),this.setStateDeep=(r,o)=>this.store.setStateDeep(r,o),this._scheduleEvaluation=(r,o)=>{this.status!=="Destroyed"&&(this.nextReasons.push(r),!(this.nextReasons.length>1)&&this.ecosystem._scheduler.schedule({id:this.id,task:this.evaluationTask,type:2},o))},this.evaluationTask=()=>this._evaluationTask(),this._createdAt=t._idGenerator.now(),this.exports=this.exports,this.promise=this.promise,this.store=this.store,this._promiseStatus=this._promiseStatus}destroy(t){var s,n,r,o;if(this.status==="Destroyed"||!t&&((s=this.ecosystem._graph.nodes[this.id])!=null&&s.refCount))return;(n=this._cancelDestruction)==null||n.call(this),this._cancelDestruction=void 0,this._setStatus("Destroyed"),this.nextReasons.length&&this.ecosystem._scheduler.unschedule(this.evaluationTask);const e=[];(r=this._injectors)==null||r.forEach(c=>{var h;if(c.type!=="@@zedux/effect"){e.push(c);return}(h=c.cleanup)==null||h.call(c)}),e.forEach(c=>{var h;(h=c.cleanup)==null||h.call(c)}),this.ecosystem._graph.removeDependencies(this.id),(o=this._subscription)==null||o.unsubscribe(),this.ecosystem._destroyAtomInstance(this.id)}getState(){return this.store.getState()}invalidate(t="invalidate",e="External"){this._scheduleEvaluation({operation:t,sourceType:e,type:"cache invalidated"},!1),this.ecosystem._scheduler.flush()}get _infusedSetter(){if(this._set)return this._set;const t=(e,s)=>this.setState(e,s);return this._set=Object.assign(t,this.exports)}_init(){const t=this._doEvaluate();[this._stateType,this.store]=qt(t),this._subscription=this.store.subscribe((s,n,r)=>{if(this._isEvaluating){this._bufferedUpdate={newState:s,oldState:n,action:r};return}this._handleStateChange(s,n,r)}),this._setStatus("Active"),this.ecosystem._graph.flushUpdates();const e=this.ecosystem._consumeHydration(this);this.template.manualHydration||typeof e>"u"||this.store.setState(e)}_scheduleDestruction(){if(this.status!=="Active")return;this._setStatus("Stale");const t=this._getTtl();if(t==null||t===-1)return;if(t===0)return this.destroy();if(typeof t=="number"){const s=setTimeout(()=>{this._cancelDestruction=void 0,this.destroy()},t);this._cancelDestruction=()=>{this._setStatus("Active"),this._cancelDestruction=void 0,clearTimeout(s)};return}if(typeof t.then=="function"){let s=!1;Promise.allSettled([t]).then(()=>{this._cancelDestruction=void 0,s||this.destroy()}),this._cancelDestruction=()=>{this._setStatus("Active"),this._cancelDestruction=void 0,s=!0};return}const e=t.subscribe(()=>{this._cancelDestruction=void 0,this.destroy()});this._cancelDestruction=()=>{this._setStatus("Active"),this._cancelDestruction=void 0,e.unsubscribe()}}_doEvaluate(){const{_evaluationStack:t,_graph:e}=this.ecosystem;this._nextInjectors=[];let s;t.start(this),this._isEvaluating=!0,e.bufferUpdates(this.id);try{s=this._evaluate()}catch(n){throw this._nextInjectors.forEach(r=>{var o;(o=r.cleanup)==null||o.call(r)}),this._nextInjectors=void 0,e.destroyBuffer(),n}finally{t.finish(),this._isEvaluating=!1,this._bufferedUpdate&&(this._handleStateChange(this._bufferedUpdate.newState,this._bufferedUpdate.oldState,this._bufferedUpdate.action),this._bufferedUpdate=void 0),this.prevReasons=this.nextReasons,this.nextReasons=[]}return this._injectors=this._nextInjectors,this._nextInjectors=void 0,this.status!=="Initializing"&&e.flushUpdates(),s}_evaluate(){var e;const{_value:t}=this.template;if(typeof t!="function")return t;try{const s=t(...this.params);if(!_(s,P))return s;const n=this.api=s;return this.status==="Initializing"&&n.exports&&(this.exports=n.exports),typeof((e=n.value)==null?void 0:e.then)=="function"?this._setPromise(n.value,!0):(n.promise&&this._setPromise(n.promise),n.value)}catch(s){throw console.error(`Zedux: Error while evaluating atom "${this.template.key}" with params:`,this.params,s),s}}_evaluationTask(){const t=this._doEvaluate();pt(t)===W&&this.store.setState(typeof t=="function"?()=>t:t)}_getTtl(){var e,s;if(((e=this.api)==null?void 0:e.ttl)==null)return this.template.ttl??((s=this.ecosystem.atomDefaults)==null?void 0:s.ttl);const{ttl:t}=this.api;return typeof t=="function"?t():t}_handleStateChange(t,e,s){this.ecosystem._graph.scheduleDependents(this.id,this.nextReasons,t,e,!1),this.ecosystem._mods.stateChanged&&this.ecosystem.modBus.dispatch(g.stateChanged({action:s,instance:this,newState:t,oldState:e,reasons:this.nextReasons})),s.meta!==f.batch&&this.ecosystem._scheduler.flush()}_setStatus(t){const e=this.status;this.status=t,this.ecosystem._mods.statusChanged&&this.ecosystem.modBus.dispatch(g.statusChanged({newStatus:t,node:this,oldStatus:e}))}_setPromise(t,e){var r;const s=(r=this.store)==null?void 0:r.getState();if(t===this.promise)return s;this.promise=t,t.then(o=>{this.promise===t&&(this._promiseStatus="success",e&&this.store.setState(lt(o)))}).catch(o=>{this.promise===t&&(this._promiseStatus="error",this._promiseError=o,e&&this.store.setState(dt(o)))});const n=z(s==null?void 0:s.data);return this._promiseStatus=n.status,this.ecosystem._graph.scheduleDependents(this.id,this.nextReasons,void 0,void 0,!0,"promise changed","Updated",!0),n}}const _t=(i,t,e)=>new gt(i,t,e);let y=[];const T=()=>y[y.length-1].node,Qt=i=>y=i;class Yt{constructor(t){this.ecosystem=t;const{_graph:e,selectors:s}=t,n=(c,h)=>{const{id:a,store:d}=t.getInstance(c,h);return y.length&&e.addEdge(y[y.length-1].node.id,a,"get",0),d.getState()},r=(c,h,a)=>{const d=t.getInstance(c,h);return y.length&&e.addEdge(y[y.length-1].node.id,d.id,(a==null?void 0:a[1])||"getInstance",(a==null?void 0:a[0])??A),d},o=(c,...h)=>{if(!y.length)return t.select(c,...h);const a=s.getCache(c,h);return e.addEdge(y[y.length-1].node.id,a.id,"select",0),a.result};this.atomGetters={ecosystem:t,get:n,getInstance:r,select:o}}finish(){const t=y.pop(),{_idGenerator:e,_mods:s,modBus:n}=this.ecosystem;if(y.length||(m._scheduler=void 0),!t||!s.evaluationFinished)return;const r=t.start?e.now(!0)-t.start:0,o={node:t.node,time:r};n.dispatch(g.evaluationFinished(o))}read(){return y[y.length-1]}start(t){const{_idGenerator:e,_mods:s,_scheduler:n}=this.ecosystem,r={node:t,start:s.evaluationFinished?e.now(!0):void 0};y.push(r),m._scheduler=n}}const F=()=>T().ecosystem._evaluationStack.atomGetters;class M{constructor(t,e,s){this.key=t,this._value=e,this._config=s,Object.assign(this,s)}}M.$$typeof=Symbol.for(`${v}/AtomTemplateBase`);class gt extends M{constructor(t,e,s){super(t,(...n)=>e(F(),...n),s),this._get=e}_createInstance(t,e,s){return new L(t,this,e,s)}getInstanceId(t,e){const s=this.key;return e!=null&&e.length?`${s}-${t._idGenerator.hashParams(e,t.complexParams)}`:s}override(t){const e=_t(this.key,t||this._get,this._config);return e._isOverride=!0,e}}const mt=(i,t,e)=>new St(i,t,e);class St extends M{_createInstance(t,e,s){return new L(t,this,e,s)}getInstanceId(t,e){const s=this.key;return e!=null&&e.length?`${s}-${t._idGenerator.hashParams(e,t.complexParams)}`:s}override(t){const e=mt(this.key,t,this._config);return e._isOverride=!0,e}}let E=C(null,{});const vt=i=>E.getState()[i],Jt=()=>({stack:y,store:E}),Kt=i=>{E=i.store,Qt(i.stack)},te=()=>{Object.values(E.getState().ecosystems).forEach(t=>{t.destroy(!0)})},Z=({ecosystem:i,nodes:t},e)=>{const s=t[e];s&&!s.refCount&&(s.isSelector?i.selectors._destroySelector(e):i._instances[e]._scheduleDestruction())},ee=({ecosystem:i,nodes:t},e)=>{var n,r;t[e].isSelector||(r=(n=i._instances[e])._cancelDestruction)==null||r.call(n)};class se{constructor(t){this.ecosystem=t,this.nodes={},this.updateStack=[]}addEdge(t,e,s,n,r){const{ecosystem:o,updateStack:c}=this,h={callback:r,createdAt:o._idGenerator.now(),flags:n,operation:s};if(!c.length)return this.finishAddingEdge(t,e,h);const{dependencies:a,key:d}=c[c.length-1],l=a.get(e);return!l||l.flags>n?(a.set(e,h),h):l}addNode(t,e){this.nodes[t]||(this.nodes[t]={dependencies:new Map,dependents:new Map,isSelector:e,refCount:0,weight:1})}bufferUpdates(t){this.updateStack.push({key:t,dependencies:new Map})}destroyBuffer(){const{dependencies:t,key:e}=this.updateStack[this.updateStack.length-1],s=this.nodes[e].dependencies;for(const n of t.keys())s.get(n)||Z(this,n);this.updateStack.pop()}flushUpdates(){const{nodes:t,updateStack:e}=this,{dependencies:s,key:n}=e[e.length-1],r=t[n].dependencies;for(const o of r.keys()){const c=t[o].dependents.get(n);if(c.flags&(H|R))continue;const h=s.get(o);(!h||h.flags!==c.flags)&&this.removeEdge(n,o)}for(const[o,c]of s.entries())r.get(o)||this.finishAddingEdge(n,o,c);e.pop()}removeDependencies(t){const e=this.nodes[t];if(!e)return;const s=e.dependencies;if(s)for(const n of s.keys())this.removeEdge(t,n)}removeEdge(t,e){const s=this.nodes[e],n=this.nodes[t];if(n&&n.dependencies.delete(e),!s)return;const r=s.dependents.get(t);if(!r){s.isSelector&&Z(this,e);return}s.dependents.delete(t),s.refCount--,r.flags&A||this.recalculateNodeWeight(t,-s.weight);const{_instances:o,_mods:c,_scheduler:h,modBus:a,selectors:d}=this.ecosystem;r.task&&h.unschedule(r.task),c.edgeRemoved&&a.dispatch(g.edgeRemoved({dependency:o[e]||d._items[e],dependent:o[t]||d._items[t]||t,edge:r})),Z(this,e)}removeNode(t){const e=this.nodes[t];if(e){this.scheduleDependents(t,[],void 0,void 0,!0,"node destroyed","Destroyed",!0);for(const[s,n]of e.dependents.entries()){n.flags&A||this.recalculateNodeWeight(s,-e.weight);const r=this.nodes[s];r&&r.dependencies.delete(t)}delete this.nodes[t]}}scheduleDependents(t,e,s,n,r,o="state changed",c="Updated",h=!1){const{_instances:a,_scheduler:d,selectors:l}=this.ecosystem,p=a[t],x=l._items[t],Tt=this.nodes[t];for(const[Y,S]of Tt.dependents.entries()){if(S.task){if(c!=="Destroyed")continue;d.unschedule(S.task)}if(S.flags&A&&!h)continue;const J={newState:s,oldState:n,operation:S.operation,reasons:e,sourceId:t,sourceType:Tt.isSelector?"AtomSelector":"Atom",type:o};if(!(S.flags&R)){if(this.nodes[Y].isSelector){l._scheduleEvaluation(Y,J,r);continue}a[Y]._scheduleEvaluation(J,r);continue}const Ot=()=>{var $t;S.task=void 0,($t=S.callback)==null||$t.call(S,c,p?p.store.getState():x.result,J)};d.schedule({flags:S.flags,task:Ot,type:3},r),S.task=Ot}}finishAddingEdge(t,e,s){const n=this.nodes[e];if(!n)return;s.flags&R||this.nodes[t].dependencies.set(e,!0),n.dependents.set(t,s),n.refCount++,ee(this,e),s.flags&A||this.recalculateNodeWeight(t,n.weight);const{_instances:r,_mods:o,modBus:c,selectors:h}=this.ecosystem;return o.edgeCreated&&c.dispatch(g.edgeCreated({dependency:r[e]||h._items[e],dependent:r[t]||h._items[t]||t,edge:s})),s}recalculateNodeWeight(t,e){const s=this.nodes[t];if(s){s.weight+=e;for(const n of s.dependents.keys())this.recalculateNodeWeight(n,e)}}}class ne{constructor(){this.idCounter=0,this.weakCache=new WeakMap,this.generateId=t=>`${t}-${++this.idCounter}${Math.random().toString(36).slice(2,8)}`}generateNodeId(){return this.generateId("no")}hashParams(t,e){return JSON.stringify(t,(s,n)=>_(n,I)?n.id:n&&(N(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):!e||Array.isArray(n)?n:typeof n=="function"?this.cacheFn(n):typeof(n==null?void 0:n.constructor)=="function"?this.cacheClass(n):n))}now(t){return t&&typeof performance<"u"?performance.now():Date.now()}cacheClass(t){let e=this.weakCache.get(t);return e||(e=this.generateId(t.constructor.name||"UnknownClass"),this.weakCache.set(t,e),e)}cacheFn(t){let e=this.weakCache.get(t);return e||(e=this.generateId(t.name||"anonFn"),this.weakCache.set(t,e),e)}}class ie{constructor(t){this.ecosystem=t,this.jobs=[],this.nows=[]}flush(){this._isRunning||(this._handle&&(clearTimeout(this._handle),this._handle=void 0),this.runJobs())}schedule(t,e=!0){t.type===4?this.jobs.push(t):this.insertJob(t),e&&this.jobs.length===1&&this.setTimeout()}scheduleNow(t){if(this._isRunningNows&&t.type===0)return t.task();this.nows[t.type===1?"push":"unshift"](t),this.runJobs(!0)}unschedule(t){const e=this.jobs.findIndex(s=>s.task===t);e!==-1&&this.jobs.splice(e,1)}wipe(){this.jobs=this.jobs.filter(t=>t.type===3)}findIndex(t,e=Math.ceil(this.jobs.length/2)-1,s=1){const n=this.jobs[e];if(n==null)return e;const r=t(n);if(!r)return e;const o=2**s;if(o>this.jobs.length)return e+(r===1?1:0);const h=Math.round(this.jobs.length/o),a=Math.min(this.jobs.length-1,Math.max(0,e+Math.ceil(h/2)*r));return this.findIndex(t,a,s+1)}insertJob(t){const{nodes:e}=this.ecosystem._graph,s=t.flags??0,n=t.id?e[t.id].weight:0,r=this.findIndex(o=>{if(o.type!==t.type)return+(t.type-o.type>0)||-1;if(o.id){const c=e[o.id].weight;return n<c?-1:+(n>c)}return s<o.flags?-1:+(s>o.flags)});r===-1?this.jobs.push(t):this.jobs.splice(r,0,t)}runJobs(t){if(this._isRunningNows){this._runAfterNows=!t;return}const e=t?this.nows:this.jobs,s=t?"_isRunningNows":"_isRunning",n=this.nows;this[s]=!0;try{for(;e.length;)(n.length?n:e).shift().task()}finally{this[s]=!1}this._runAfterNows&&(this._runAfterNows=!1,this.runJobs())}setTimeout(){this._isRunning||(this._handle=setTimeout(()=>{this._handle=void 0,this.runJobs()}))}}const re=(i,t)=>i===t;class b{constructor(t,e,s){this.id=t,this.selectorRef=e,this.args=s,this.nextReasons=[]}}b.$$typeof=Symbol.for(`${v}/SelectorCache`);class oe{constructor(t){this.ecosystem=t,this._items={},this._refBaseKeys=new WeakMap}addDependent(t,{callback:e,operation:s="addDependent"}={}){const{_graph:n,_idGenerator:r}=this.ecosystem,o=r.generateNodeId();return n.addEdge(o,t.id,s,H|R,e),()=>n.removeEdge(o,t.id)}dehydrate(t){const e=this.findAll(t);return Object.keys(e).forEach(s=>{e[s]=e[s].result}),e}destroyCache(t,e,s){const n=_(t,b)?t.id:this.getCacheId(t,e),r=_(t,b)?t:this._items[n];if(!r||r.isDestroyed)return;const o=this.ecosystem._graph.nodes[n];(s||!o.refCount)&&this._destroySelector(n)}find(t,e){if(_(t,b))return t;if(typeof t=="string")return Object.values(this.findAll(t))[0];const s=this.getCacheId(t,e,!0);return s&&this._items[s]}findAll(t=""){const e={},s=typeof t=="string"?t.toLowerCase():_(t,b)?t.id:this.getBaseKey(t,!0)||this._getIdealCacheId(t);return Object.values(this._items).sort((n,r)=>n.id.localeCompare(r.id)).forEach(n=>{(!s||n.id.toLowerCase().includes(s))&&(e[n.id]=n)}),e}getCache(t,e=[]){if(_(t,b))return t;const s=t,n=this.getCacheId(s,e);let r=this._items[n];return r||(r=new b(n,s,e),this._items[n]=r,this.ecosystem._graph.addNode(n,!0),this.runSelector(n,e,!0),r)}getCacheId(t,e,s){const{complexParams:n,_idGenerator:r}=this.ecosystem,o=e!=null&&e.length?r.hashParams(e,n):"",c=this.getBaseKey(t,s);return o?`${c}-${o}`:c}_destroySelector(t){const e=this._items[t];if(!e)return;const{_graph:s,_scheduler:n,_mods:r,modBus:o}=this.ecosystem;e.nextReasons.length&&e.task&&n.unschedule(e.task),s.removeDependencies(t),s.removeNode(t),delete this._items[t],e.isDestroyed=!0,r.statusChanged&&o.dispatch(g.statusChanged({newStatus:"Destroyed",node:e,oldStatus:"Active"}))}_getIdealCacheId(t){var s;const e=t.name||((s=t.selector)==null?void 0:s.name);return e!=="selector"&&e||void 0}_scheduleEvaluation(t,e,s){const n=this._items[t];if(n.nextReasons.push(e),n.nextReasons.length>1)return;const r=()=>{n.task=void 0,this.runSelector(t,n.args)};n.task=r,this.ecosystem._scheduler.schedule({id:t,task:r,type:2},s)}_swapRefs(t,e,s=[]){const n=this._refBaseKeys.get(t.selectorRef);n&&(this._refBaseKeys.set(e,n),this._refBaseKeys.delete(t.selectorRef),t.selectorRef=e,this.runSelector(t.id,s,!1,!0))}_wipe(){Object.keys(this._items).forEach(t=>{this._destroySelector(t)}),this._refBaseKeys=new WeakMap}getBaseKey(t,e){const s=this._refBaseKeys.get(t);if(s||e)return s;const n=this._getIdealCacheId(t)||"unnamed",r=this.ecosystem._idGenerator.generateId(`@-${n}`);return this._refBaseKeys.set(t,r),r}runSelector(t,e,s,n){const{_evaluationStack:r,_graph:o,_mods:c,modBus:h}=this.ecosystem;o.bufferUpdates(t);const a=this._items[t],d=typeof a.selectorRef=="function"?a.selectorRef:a.selectorRef.selector,l=typeof a.selectorRef!="function"&&a.selectorRef.resultsComparator||re;r.start(a);try{const p=d(r.atomGetters,...e);!s&&!l(p,a.result)?(n||o.scheduleDependents(t,a.nextReasons,p,a.result),c.stateChanged&&h.dispatch(g.stateChanged({cache:a,newState:p,oldState:a.result,reasons:a.nextReasons})),a.result=p):s&&(a.result=p,c.statusChanged&&h.dispatch(g.statusChanged({newStatus:"Active",node:a,oldStatus:"Initializing"})))}catch(p){throw o.destroyBuffer(),console.error(`Zedux encountered an error while running selector with id "${t}":`,p),p}finally{r.finish(),a.prevReasons=a.nextReasons,a.nextReasons=[]}o.flushUpdates()}}const ce=Object.keys(g).reduce((i,t)=>(i[t]=0,i),{}),V=i=>i.reduce((t,e)=>(t[e.key]=e,t),{});class bt{constructor(t){var e;this.modBus=C(),this.overrides={},this.selectors=new oe(this),this._graph=new se(this),this._evaluationStack=new Yt(this),this._idGenerator=new ne,this._instances={},this._mods={...ce},this._refCount=0,this._scheduler=new ie(this),this._storage={},this.isInitialized=!1,this.plugins=[],Object.assign(this,t),this.id||(this.id=this._idGenerator.generateId("es")),t.overrides&&this.setOverrides(t.overrides),this.context=this.context,this.isInitialized=!0,this.cleanup=(e=t.onReady)==null?void 0:e.call(t,this)}addOverrides(t){this.overrides={...this.overrides,...V(t)},t.forEach(e=>{const s=this.findAll(e);Object.values(s).forEach(n=>n.destroy(!0))})}batch(t){const e=this._scheduler,s=e._isRunning;e._isRunning=!0;const n=t();return e._isRunning=s,e.flush(),n}dehydrate({exclude:t,excludeFlags:e,include:s,includeFlags:n,transform:r=!0}={}){return Object.values(this._instances).filter(({id:c,template:h})=>t&&t.some(a=>typeof a=="string"?c.toLowerCase().includes(a.toLowerCase()):h.key===a.key)||e&&e.some(a=>{var d;return(d=h.flags)==null?void 0:d.includes(a)})?!1:!!(!s&&!n||s&&s.some(a=>typeof a=="string"?c.toLowerCase().includes(a.toLowerCase()):h.key===a.key)||n&&n.some(a=>{var d;return(d=h.flags)==null?void 0:d.includes(a)}))).reduce((c,{id:h,store:a,template:d})=>{const l=a.getState();return c[h]=r&&d.dehydrate?d.dehydrate(l):l,c},{})}destroy(t){!t&&this._refCount>0||(this.wipe(),!E.getState()[this.id])||(this.plugins.forEach(({cleanup:s})=>s()),this.plugins=[],E.setState(s=>{const n={...s};return delete n[this.id],n}))}find(t,e){const s=typeof t=="string";if(!s){const r=t.getInstanceId(this,e),o=this._instances[r];if(o)return o}if(e)return this._instances[s?t:`${t.key}-${this._idGenerator.hashParams(e,this.complexParams)}`];const n=this.findAll(t);return s&&n[t]||Object.values(n)[0]}findAll(t){const e=t==null?void 0:t.key,s=e||(t==null?void 0:t.toLowerCase()),n={};return Object.values(this._instances).filter(r=>!s||(e?r.template.key===t.key:r.id.toLowerCase().includes(s))).sort((r,o)=>r.id.localeCompare(o.id)).forEach(r=>{n[r.id]=r}),n}get(t,e){return _(t,I)?t.store.getState():this.getInstance(t,e).store.getState()}getInstance(t,e){if(_(t,I))return t.status==="Destroyed"?this.getInstance(t.template,t.params):t;const s=t.getInstanceId(this,e),n=this._instances[s];if(n)return this._mods.instanceReused&&this.modBus.dispatch(g.instanceReused({instance:n,template:t})),n;const r=this.resolveAtom(t);this._graph.addNode(s);const o=r._createInstance(this,s,e||[]);return this._instances[s]=o,o._init(),o}hydrate(t,e){this.hydration={...this.hydration,...t},(e==null?void 0:e.retroactive)!==!1&&Object.entries(t).forEach(([s,n])=>{const r=this._instances[s];r&&(r.setState(r.template.hydrate?r.template.hydrate(n):n),delete this.hydration[s])})}registerPlugin(t){if(this.plugins.some(r=>r.plugin===t))return;const e=t.modStore.subscribe((r,o)=>{this.recalculateMods(r,o)}),s=t.registerEcosystem(this),n=()=>{e.unsubscribe(),s&&s()};this.plugins.push({cleanup:n,plugin:t}),this.recalculateMods(t.modStore.getState())}removeOverrides(t){this.overrides=V(Object.values(this.overrides).filter(e=>t.every(s=>(typeof s=="string"?s:s.key)!==e.key))),t.forEach(e=>{const s=this.findAll(e);Object.values(s).forEach(n=>n.destroy(!0))})}reset(t){var s;this.wipe();const e=this.context;typeof t<"u"&&(this.context=t),this.cleanup=(s=this.onReady)==null?void 0:s.call(this,this,e)}select(t,...e){if(_(t,b))return t.result;const s=t,n=this.selectors.find(s,e);return n?n.result:(typeof s=="function"?s:s.selector)({ecosystem:this,get:this.get.bind(this),getInstance:this.getInstance.bind(this),select:this.select.bind(this)},...e)}setOverrides(t){const e=this.overrides;this.overrides=V(t),this.isInitialized&&(t.forEach(s=>{const n=this.findAll(s);Object.values(n).forEach(r=>{r.destroy(!0)})}),Object.values(e).forEach(s=>{const n=this.findAll(s);Object.values(n).forEach(r=>{r.destroy(!0)})}))}unregisterPlugin(t){const e=this.plugins.findIndex(s=>s.plugin===t);e!==-1&&(this.plugins[e].cleanup(),this.plugins.splice(e,1),this.recalculateMods(void 0,t.modStore.getState()))}viewGraph(t){const{nodes:e}=this._graph;if(t!=="top-down"&&t!=="bottom-up"){const r={};return Object.keys(e).forEach(o=>{const c=e[o];r[o]={dependencies:[...c.dependencies.keys()].map(h=>({key:h,operation:e[h].dependents.get(o).operation})),dependents:[...c.dependents.keys()].map(h=>({key:h,operation:c.dependents.get(h).operation})),weight:c.weight}}),r}const s={};Object.keys(e).forEach(r=>{const o=e[r];(t==="bottom-up"?[...o.dependents.values()].every(h=>h.flags&R):!o.dependencies.size)&&(s[r]={})});const n=r=>{if(!r)return;const o=t==="bottom-up"?r.dependencies:r.dependents,c={};for(const h of o.keys()){const a=n(e[h]);a&&(c[h]=a)}return c};return Object.keys(s).forEach(r=>{const o=e[r],c=n(o);c&&(s[r]=c)}),s}why(){var t;return(t=this._evaluationStack.read())==null?void 0:t.node.nextReasons}wipe(){var o;const{_instances:t,_mods:e,_scheduler:s,modBus:n,selectors:r}=this;(o=this.cleanup)==null||o.call(this),Object.values(t).forEach(c=>{c.destroy(!0)}),this.hydration=void 0,r._wipe(),s.wipe(),s.flush(),e.ecosystemWiped&&n.dispatch(g.ecosystemWiped({ecosystem:this}))}_consumeHydration(t){var s;const e=(s=this.hydration)==null?void 0:s[t.id];if(!(typeof e>"u"))return delete this.hydration[t.id],t.template.hydrate?t.template.hydrate(e):e}_decrementRefCount(){this._refCount--,this.destroyOnUnmount&&this.destroy()}_destroyAtomInstance(t){this._graph.removeNode(t),delete this._instances[t]}_incrementRefCount(){this._refCount++}recalculateMods(t,e){e&&e.forEach(s=>{this._mods[s]--}),t&&t.forEach(s=>{this._mods[s]++})}resolveAtom(t){var o;const{flags:e,overrides:s}=this,r=s[t.key]||t;return e&&((o=r.flags)==null||o.find(c=>!e.includes(c))),r}}class jt{constructor({initialMods:t=[],registerEcosystem:e}={}){this.modStore=C(null,t),this.registerEcosystem=e||(()=>{})}}jt.actions=g;const kt=i=>new P(i),ae=(i={})=>{if(i!=null&&i.id){const e=vt(i.id);if(e)return e}const t=new bt(i);return E.setStateDeep({[t.id]:t}),t},$=(i,t,e)=>(...n)=>{const r=T(),{_injectors:o,_nextInjectors:c,status:h,template:a}=r;if(h==="Initializing"){const p=t(r,...n);return p.type,c==null||c.push(p),p.result}const d=o==null?void 0:o[c==null?void 0:c.length],l=e?e(d,r,...n):d;return c==null||c.push(l),l.result},X="injectAtomInstance",q=$(X,(i,t,e,s)=>({result:i.ecosystem._evaluationStack.atomGetters.getInstance(t,e,[s!=null&&s.subscribe?0:A,(s==null?void 0:s.operation)||X]),type:`${v}/atom`}),(i,t,e,s,n)=>{const r=t.ecosystem._evaluationStack.atomGetters.getInstance(e,s,[n!=null&&n.subscribe?0:A,(n==null?void 0:n.operation)||X]);return i.result=r,i}),he=(i,...t)=>T().ecosystem._evaluationStack.atomGetters.select(i,...t),ue=(i,t)=>{const e=q(i,t,{operation:"injectAtomState",subscribe:!0});return[e.getState(),e._infusedSetter]},de=(i,t)=>q(i,t,{operation:"injectAtomValue",subscribe:!0}).store.getState(),Q=$("injectMemo",(i,t,e)=>({type:`${v}/memo`,deps:e,result:t()}),(i,t,e,s)=>{const r=U(i.deps,s)?e():i.result;return i.deps=s,i.result=r,i}),le=(i,t)=>{const{ecosystem:e}=F();return Q(()=>(...s)=>e.batch(()=>i(...s)),t)},At=(i,t)=>()=>{const s=i();t.cleanup=typeof s=="function"?s:void 0},Et=$("injectEffect",(i,t,e,s)=>{const n={deps:e,type:`${v}/effect`};if(!i.ecosystem.ssr){const r=At(t,n);n.cleanup=()=>{i.ecosystem._scheduler.unschedule(r),n.cleanup=void 0},s!=null&&s.synchronous?r():i.ecosystem._scheduler.schedule({task:r,type:4})}return n},(i,t,e,s,n)=>{var c;if(t.ecosystem.ssr||!U(i==null?void 0:i.deps,s))return i;(c=i.cleanup)==null||c.call(i);const o=At(e,i);return i.cleanup=()=>{t.ecosystem._scheduler.unschedule(o),i.cleanup=void 0},i.deps=s,n!=null&&n.synchronous?o():t.ecosystem._scheduler.schedule({task:o,type:4}),i}),fe=()=>{const i=T();return()=>i.invalidate("injectInvalidate","Injector")},wt=(i,t)=>t.subscribe((e,s,n)=>{if(i._isEvaluating||n.meta===f.ignore)return;const r=(n==null?void 0:n.meta)===f.batch;i._scheduleEvaluation({newState:e,oldState:s,operation:"injectStore",reasons:[{action:n,newState:e,oldState:s,operation:"dispatch",sourceType:"Store",type:"state changed"}],sourceType:"Injector",type:"state changed"},r),r||i.ecosystem._scheduler.flush()}),Ct=$("injectStore",(i,t,e)=>{var c;const s=(e==null?void 0:e.subscribe)??!0,r=(typeof t=="function"?t:h=>C(null,h??t))(e!=null&&e.hydrate?(c=i.ecosystem.hydration)==null?void 0:c[i.id]:void 0),o=s&&wt(i,r);return{cleanup:o?()=>o.unsubscribe():void 0,result:r,type:`${v}/store`}},(i,t,e,s)=>{const n=(s==null?void 0:s.subscribe)??!0;if(!!i.cleanup===n)return i;if(!n)return i.cleanup(),i.cleanup=void 0,i;const o=wt(t,i.result);return i.cleanup=()=>o.unsubscribe(),i}),Rt=$("injectRef",(i,t)=>({result:{current:t},type:`${v}/ref`})),It=()=>T().nextReasons,ye=(i,t,{dataOnly:e,initialState:s,runOnInvalidate:n,...r}={})=>{const o=Rt({counter:0}),c=Ct(e?s:z(s),r);return n&&It().some(h=>h.type==="cache invalidated")&&o.current.counter++,o.current.promise=Q(()=>{const h=o.current.controller,a=typeof AbortController<"u"?new AbortController:void 0;o.current.controller=a;const d=i(o.current.controller);return d===o.current.promise?o.current.promise:(h&&h.abort("updated"),e||c.setStateDeep(l=>z(l.data)),d.then(l=>{a!=null&&a.signal.aborted||c.setState(e?l:lt(l))}).catch(l=>{e||a!=null&&a.signal.aborted||c.setStateDeep(dt(l))}),d)},t&&[...t,o.current.counter]),Et(()=>()=>{const h=o.current.controller;h&&h.abort("destroyed")},[]),kt(c).setPromise(o.current.promise)},pe=T;u.AtomApi=P,u.AtomInstance=L,u.AtomInstanceBase=I,u.AtomTemplate=St,u.AtomTemplateBase=M,u.Ecosystem=bt,u.IonTemplate=gt,u.SelectorCache=b,u.Store=m,u.ZeduxPlugin=jt,u.actionFactory=j,u.api=kt,u.atom=mt,u.createEcosystem=ae,u.createReducer=Pt,u.createStore=C,u.detailedTypeof=Nt,u.getEcosystem=vt,u.getInternals=Jt,u.getMetaData=ot,u.haveDepsChanged=U,u.injectAtomGetters=F,u.injectAtomInstance=q,u.injectAtomSelector=he,u.injectAtomState=ue,u.injectAtomValue=de,u.injectCallback=le,u.injectEffect=Et,u.injectInvalidate=fe,u.injectMemo=Q,u.injectPromise=ye,u.injectRef=Rt,u.injectSelf=pe,u.injectStore=Ct,u.injectWhy=It,u.ion=_t,u.is=_,u.isPlainObject=N,u.removeAllMeta=ct,u.removeMeta=at,u.setInternals=Kt,u.wipe=te,u.zeduxTypes=f,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
//# sourceMappingURL=zedux-atoms.umd.min.js.map