@but212/atom-effect 0.4.0 → 0.5.1

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.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const re={ONE_SECOND_MS:1e3},F={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},P={DISPOSED:1,EXECUTING:2},o={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},ce={MAX_SIZE:1e3,WARMUP_SIZE:100},I={MAX_EXECUTIONS_PER_SECOND:100,CLEANUP_THRESHOLD:100,MAX_EXECUTIONS_PER_EFFECT:50,MAX_EXECUTIONS_PER_FLUSH:5e3,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10},k={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},O=1073741823,E=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production";class d extends Error{constructor(e,t=null,i=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=i,this.timestamp=new Date}}class m extends d{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class g extends d{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class T extends d{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}function A(s,e,t){if(s instanceof TypeError)return new e(`Type error (${t}): ${s.message}`,s);if(s instanceof ReferenceError)return new e(`Reference error (${t}): ${s.message}`,s);if(s instanceof d)return s;const i=s instanceof Error?s.message:String(s),n=s instanceof Error?s:null;return new e(`Unexpected error (${t}): ${i}`,n)}function Y(s){return s!=null&&typeof s.then=="function"}const l={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber listener must be a function or Subscriber object",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation is pending. No default value provided",COMPUTED_COMPUTATION_FAILED:"Computed computation failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computed computation failed",COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED:"Failed to subscribe to dependency",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_SUBSCRIBER_EXECUTION_FAILED:"Error occurred while executing atom subscribers",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Error during individual atom subscriber execution",EFFECT_MUST_BE_FUNCTION:"Effect function must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup function execution failed",LARGE_DEPENDENCY_GRAPH:s=>`Large dependency graph detected: ${s} dependencies`,UNSUBSCRIBE_NON_EXISTENT:"Attempted to unsubscribe a non-existent listener",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},w=Symbol("debugName"),ue=Symbol("id"),V=Symbol("type"),G=Symbol("noDefaultValue");function oe(s){return"dependencies"in s&&Array.isArray(s.dependencies)}let X=0;function Q(s,e,t){if(s._visitedEpoch!==t){if(s._visitedEpoch=t,s===e)throw new m("Indirect circular dependency detected");if(oe(s)){const i=s.dependencies;for(let n=0;n<i.length;n++){const r=i[n];r&&Q(r,e,t)}}}}const b={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:k.MAX_DEPENDENCIES,warnInfiniteLoop:k.WARN_INFINITE_LOOP,warn(s,e){this.enabled&&s&&console.warn(`[Atom Effect] ${e}`)},checkCircular(s,e){if(s===e)throw new m("Direct circular dependency detected");this.enabled&&(X++,Q(s,e,X))},attachDebugInfo(s,e,t){if(!this.enabled)return;const i=s;i[w]=`${e}_${t}`,i[ue]=t,i[V]=e},getDebugName(s){if(s!=null&&w in s)return s[w]},getDebugType(s){if(s!=null&&V in s)return s[V]}};let he=1;const le=()=>he++;class J{constructor(){this.id=le()&O,this.flags=0}}class W extends J{constructor(){super(),this.version=0,this._lastSeenEpoch=-1}subscribe(e){if(typeof e=="object"&&e!==null&&"execute"in e)return this._objectSubscribers.add(e);if(typeof e!="function")throw new d(l.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(e)}subscriberCount(){return this._functionSubscribers.size+this._objectSubscribers.size}_notifySubscribers(e,t){this._functionSubscribers.forEachSafe(i=>i(e,t),i=>console.error(new d(l.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,i))),this._objectSubscribers.forEachSafe(i=>i.execute(),i=>console.error(new d(l.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,i)))}}let B=0;function K(){return B=(B+1|0)&O,B}let M=0,j=0,L=!1;function H(){return L?(E&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(L=!0,M=M+1&O,j=0,!0)}function $(){L=!1}function _e(){return L?++j:0}class ae{constructor(){this.queueA=[],this.queueB=[],this.queue=this.queueA,this.queueSize=0,this._epoch=0,this.isProcessing=!1,this.isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=I.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e){if(typeof e!="function")throw new T("Scheduler callback must be a function");e._nextEpoch!==this._epoch&&(e._nextEpoch=this._epoch,this.isBatching||this.isFlushingSync?this.batchQueue[this.batchQueueSize++]=e:(this.queue[this.queueSize++]=e,this.isProcessing||this.flush()))}flush(){if(this.isProcessing||this.queueSize===0)return;this.isProcessing=!0;const e=this.queue,t=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++,queueMicrotask(()=>{const i=H();for(let n=0;n<t;n++)try{e[n]?.()}catch(r){console.error(new T("Error occurred during scheduler execution",r))}e.length=0,this.isProcessing=!1,i&&$(),this.queueSize>0&&!this.isBatching&&this.flush()})}flushSync(){this.isFlushingSync=!0;const e=H();try{if(this._epoch++,this.batchQueueSize>0){for(let i=0;i<this.batchQueueSize;i++){const n=this.batchQueue[i];n._nextEpoch!==this._epoch&&(n._nextEpoch=this._epoch,this.queue[this.queueSize++]=n)}this.batchQueueSize=0}let t=0;for(;this.queueSize>0;){if(++t>this.maxFlushIterations){console.error(new T(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this.queueSize=0,this.queue.length=0,this.batchQueueSize=0;break}const i=this.queue,n=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++;for(let r=0;r<n;r++)try{i[r]?.()}catch(c){console.error(new T("Error occurred during batch execution",c))}if(i.length=0,this.batchQueueSize>0){for(let r=0;r<this.batchQueueSize;r++)this.queue[this.queueSize++]=this.batchQueue[r];this.batchQueueSize=0}}}finally{this.isFlushingSync=!1,e&&$()}}startBatch(){this.batchDepth++,this.isBatching=!0}endBatch(){this.batchDepth=Math.max(0,this.batchDepth-1),this.batchDepth===0&&(this.flushSync(),this.isBatching=!1)}setMaxFlushIterations(e){if(e<I.MIN_FLUSH_ITERATIONS)throw new T(`Max flush iterations must be at least ${I.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const U=new ae;function fe(s){if(typeof s!="function")throw new d("Batch callback must be a function");U.startBatch();try{return s()}catch(e){throw new d("Error occurred during batch execution",e)}finally{U.endBatch()}}const R={current:null,run(s,e){const t=this.current;this.current=s;try{return e()}finally{this.current=t}},getCurrent(){return this.current}};function de(s){return typeof s=="object"&&s!==null}function Z(s){return(typeof s=="object"||typeof s=="function")&&s!==null&&typeof s.addDependency=="function"}function ee(s){return typeof s=="function"&&typeof s.addDependency!="function"}function te(s){return de(s)&&typeof s.execute=="function"}function se(s){if(typeof s!="function")throw new d("Untracked callback must be a function");const e=R.current;R.current=null;try{return s()}catch(t){throw new d("Error occurred during untracked execution",t)}finally{R.current=e}}class v{constructor(){this.subscribers=null}add(e){if(this.subscribers||(this.subscribers=[]),this.subscribers.indexOf(e)!==-1)return()=>{};this.subscribers.push(e);let t=!1;return()=>{t||(t=!0,this.remove(e))}}remove(e){if(!this.subscribers)return!1;const t=this.subscribers.indexOf(e);if(t===-1)return!1;const i=this.subscribers.length-1;return t!==i&&(this.subscribers[t]=this.subscribers[i]),this.subscribers.pop(),!0}has(e){return this.subscribers?this.subscribers.indexOf(e)!==-1:!1}forEach(e){if(this.subscribers)for(let t=0;t<this.subscribers.length;t++)e(this.subscribers[t],t)}forEachSafe(e,t){if(this.subscribers)for(let i=0;i<this.subscribers.length;i++)try{e(this.subscribers[i],i)}catch(n){t?t(n):console.error("[SubscriberManager] Error in subscriber callback:",n)}}get size(){return this.subscribers?.length??0}get hasSubscribers(){return this.subscribers!==null&&this.subscribers.length>0}clear(){this.subscribers=null}toArray(){return this.subscribers?[...this.subscribers]:[]}}class Ee extends W{constructor(e,t){super(),this._isNotificationScheduled=!1,this._value=e,this._functionSubscribersStore=new v,this._objectSubscribersStore=new v,this._sync=t,this._notifyTask=this._flushNotifications.bind(this),b.attachDebugInfo(this,"atom",this.id)}get _functionSubscribers(){return this._functionSubscribersStore}get _objectSubscribers(){return this._objectSubscribersStore}get value(){const e=R.getCurrent();return e&&this._track(e),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this.version=this.version+1&O,this._value=e,!(!this._functionSubscribersStore.hasSubscribers&&!this._objectSubscribersStore.hasSubscribers)&&this._scheduleNotification(t)}_track(e){if(Z(e)){e.addDependency(this);return}if(ee(e)){this._functionSubscribersStore.add(e);return}te(e)&&this._objectSubscribersStore.add(e)}_scheduleNotification(e){this._isNotificationScheduled||(this._pendingOldValue=e,this._isNotificationScheduled=!0),this._sync&&!U.isBatching?this._flushNotifications():U.schedule(this._notifyTask)}_flushNotifications(){if(!this._isNotificationScheduled)return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this._isNotificationScheduled=!1,this._notifySubscribers(t,e)}peek(){return this._value}dispose(){this._functionSubscribersStore.clear(),this._objectSubscribersStore.clear(),this._value=void 0}}function be(s,e={}){return new Ee(s,e.sync??!1)}const a=Object.freeze([]),p=Object.freeze([]),f=Object.freeze([]);class z{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=E?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return E&&this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(e,t){if(!(t&&e===t)){if(Object.isFrozen(e)){E&&this.stats&&this.stats.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){E&&this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.maxPoolSize){E&&this.stats&&this.stats.rejected.poolFull++;return}e.length=0,this.pool.push(e),E&&this.stats&&this.stats.released++}}getStats(){if(!E||!this.stats)return null;const{acquired:e,released:t,rejected:i}=this.stats,n=i.frozen+i.tooLarge+i.poolFull;return{acquired:e,released:t,rejected:i,leaked:e-t-n,poolSize:this.pool.length}}reset(){this.pool.length=0,E&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const D=new z,N=new z,S=new z;function q(s,e,t,i){if(e!==a&&t!==p)for(let r=0;r<e.length;r++){const c=e[r];c&&(c._tempUnsub=t[r])}const n=N.acquire();n.length=s.length;for(let r=0;r<s.length;r++){const c=s[r];c&&(c._tempUnsub?(n[r]=c._tempUnsub,c._tempUnsub=void 0):(b.checkCircular(c,i),n[r]=c.subscribe(i)))}if(e!==a)for(let r=0;r<e.length;r++){const c=e[r];c?._tempUnsub&&(c._tempUnsub(),c._tempUnsub=void 0)}return t!==p&&N.release(t),n}class ie extends W{constructor(e,t={}){if(typeof e!="function")throw new m(l.COMPUTED_MUST_BE_FUNCTION);if(super(),this._value=void 0,this.flags=o.DIRTY|o.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:G,this._hasDefaultValue=this._defaultValue!==G,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._functionSubscribersStore=new v,this._objectSubscribersStore=new v,this._dependencies=a,this._dependencyVersions=f,this._unsubscribes=p,this._notifyJob=()=>{this._functionSubscribersStore.forEachSafe(i=>i(),i=>console.error(i)),this._objectSubscribersStore.forEachSafe(i=>i.execute(),i=>console.error(i))},this._trackable=Object.assign(()=>this._markDirty(),{addDependency:i=>{}}),b.attachDebugInfo(this,"computed",this.id),b.enabled){const i=this;i.subscriberCount=()=>this._functionSubscribersStore.size+this._objectSubscribersStore.size,i.isDirty=()=>this._isDirty(),i.dependencies=this._dependencies,i.stateFlags=this._getFlagsAsString()}if(t.lazy===!1)try{this._recompute()}catch{}}get _functionSubscribers(){return this._functionSubscribersStore}get _objectSubscribers(){return this._objectSubscribersStore}get value(){const e=this._computeValue();return this._registerTracking(),e}peek(){return this._value}get state(){return this._getAsyncState()}get hasError(){return this._isRejected()}get lastError(){return this._error}get isPending(){return this._isPending()}get isResolved(){return this._isResolved()}invalidate(){this._markDirty(),this._dependencyVersions!==f&&(S.release(this._dependencyVersions),this._dependencyVersions=f)}dispose(){if(this._unsubscribes!==p){for(let e=0;e<this._unsubscribes.length;e++){const t=this._unsubscribes[e];t&&t()}N.release(this._unsubscribes),this._unsubscribes=p}this._dependencies!==a&&(D.release(this._dependencies),this._dependencies=a),this._dependencyVersions!==f&&(S.release(this._dependencyVersions),this._dependencyVersions=f),this._functionSubscribersStore.clear(),this._objectSubscribersStore.clear(),this.flags=o.DIRTY|o.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID}_isDirty(){return(this.flags&o.DIRTY)!==0}_setDirty(){this.flags|=o.DIRTY}_clearDirty(){this.flags&=-2}_isIdle(){return(this.flags&o.IDLE)!==0}_setIdle(){this.flags|=o.IDLE,this.flags&=-29}_isPending(){return(this.flags&o.PENDING)!==0}_setPending(){this.flags|=o.PENDING,this.flags&=-27}_isResolved(){return(this.flags&o.RESOLVED)!==0}_setResolved(){this.flags|=o.RESOLVED,this.flags&=-87}_isRejected(){return(this.flags&o.REJECTED)!==0}_setRejected(){this.flags|=o.REJECTED|o.HAS_ERROR,this.flags&=-15}_isRecomputing(){return(this.flags&o.RECOMPUTING)!==0}_setRecomputing(e){const t=o.RECOMPUTING;this.flags=this.flags&~t|-Number(e)&t}_getAsyncState(){return this._isResolved()?F.RESOLVED:this._isPending()?F.PENDING:this._isRejected()?F.REJECTED:F.IDLE}_getFlagsAsString(){const e=[];return this._isDirty()&&e.push("DIRTY"),this._isIdle()&&e.push("IDLE"),this._isPending()&&e.push("PENDING"),this._isResolved()&&e.push("RESOLVED"),this._isRejected()&&e.push("REJECTED"),this._isRecomputing()&&e.push("RECOMPUTING"),e.join(" | ")}_computeValue(){return this._isRecomputing()?this._value:((this._isDirty()||this._isIdle())&&this._recompute(),this._isPending()?this._handlePending():this._isRejected()?this._handleRejected():this._value)}_recompute(){if(this._isRecomputing())return;this._setRecomputing(!0);const e=this._dependencies,t=this._dependencyVersions,i=D.acquire(),n=S.acquire(),r=K();let c=0;const x=h=>{h._lastSeenEpoch!==r&&(h._lastSeenEpoch=r,c<i.length?(i[c]=h,n[c]=h.version):(i.push(h),n.push(h.version)),c++)},y=this._trackable.addDependency;this._trackable.addDependency=x;let C=!1;try{const h=R.run(this._trackable,this._fn);if(i.length=c,n.length=c,Y(h)){this._unsubscribes=q(i,e,this._unsubscribes,this),this._dependencies=i,this._dependencyVersions=n,C=!0,this._handleAsyncComputation(h),this._setRecomputing(!1);return}this._unsubscribes=q(i,e,this._unsubscribes,this),this._dependencies=i,this._dependencyVersions=n,C=!0,this._handleSyncResult(h)}catch(h){i.length=c,n.length=c,this._unsubscribes=q(i,e,this._unsubscribes,this),this._dependencies=i,this._dependencyVersions=n,C=!0,this._handleComputationError(h)}finally{this._trackable.addDependency=y,C?(e!==a&&D.release(e),t!==f&&S.release(t)):(D.release(i),S.release(n))}}_handleSyncResult(e){(!this._isResolved()||!this._equal(this._value,e))&&(this.version=this.version+1&O),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1)}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._promiseId=this._promiseId>=this.MAX_PROMISE_ID?1:this._promiseId+1;const t=this._promiseId;e.then(i=>{t===this._promiseId&&this._handleAsyncResolution(i)}).catch(i=>{t===this._promiseId&&this._handleAsyncRejection(i)})}_handleAsyncResolution(e){(!this._isResolved()||!this._equal(this._value,e))&&(this.version=this.version+1&O),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1)}_handleAsyncRejection(e){const t=A(e,m,l.COMPUTED_ASYNC_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(i){console.error(l.CALLBACK_ERROR_IN_ERROR_HANDLER,i)}this._notifySubscribers(void 0,void 0)}_handleComputationError(e){const t=A(e,m,l.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(i){console.error(l.CALLBACK_ERROR_IN_ERROR_HANDLER,i)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new m(l.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){if(this._error?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw this._error}execute(){this._markDirty()}_markDirty(){this._isRecomputing()||this._isDirty()||(this._setDirty(),this._notifyJob())}_registerTracking(){const e=R.getCurrent();if(e){if(Z(e)){e.addDependency(this);return}if(ee(e)){this._functionSubscribersStore.add(e);return}te(e)&&this._objectSubscribersStore.add(e)}}}Object.freeze(ie.prototype);function pe(s,e={}){return new ie(s,e)}class Se extends J{constructor(e,t={}){super(),this.run=()=>{if(this.isDisposed)throw new g(l.EFFECT_MUST_BE_FUNCTION);this._dependencyVersions!==f&&(S.release(this._dependencyVersions),this._dependencyVersions=f),this.execute()},this.dispose=()=>{if(!this.isDisposed){if(this._setDisposed(),this._safeCleanup(),this._unsubscribes!==p){for(let i=0;i<this._unsubscribes.length;i++){const n=this._unsubscribes[i];n&&n()}N.release(this._unsubscribes),this._unsubscribes=p}this._dependencies!==a&&(D.release(this._dependencies),this._dependencies=a),this._dependencyVersions!==f&&(S.release(this._dependencyVersions),this._dependencyVersions=f)}},this.addDependency=i=>{if(this.isExecuting&&this._nextDeps&&this._nextUnsubs&&this._nextVersions){const n=this._currentEpoch;if(i._lastSeenEpoch===n)return;i._lastSeenEpoch=n,this._nextDeps.push(i),this._nextVersions.push(i.version),i._tempUnsub?(this._nextUnsubs.push(i._tempUnsub),i._tempUnsub=void 0):this._subscribeTo(i)}},this.execute=()=>{if(this.isDisposed||this.isExecuting||!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const i=this._dependencies,n=this._dependencyVersions,r=this._unsubscribes,c=D.acquire(),x=S.acquire(),y=N.acquire(),C=K();if(i!==a&&r!==p)for(let u=0;u<i.length;u++){const _=i[u];_&&(_._tempUnsub=r[u])}this._nextDeps=c,this._nextVersions=x,this._nextUnsubs=y,this._currentEpoch=C;let h=!1;try{const u=R.run(this,this._fn);this._dependencies=c,this._dependencyVersions=x,this._unsubscribes=y,h=!0,this._checkLoopWarnings(),Y(u)?u.then(_=>{!this.isDisposed&&typeof _=="function"&&(this._cleanup=_)}).catch(_=>{console.error(A(_,g,l.EFFECT_EXECUTION_FAILED))}):this._cleanup=typeof u=="function"?u:null}catch(u){h=!0,console.error(A(u,g,l.EFFECT_EXECUTION_FAILED)),this._cleanup=null}finally{if(this._setExecuting(!1),this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,h){if(i!==a){for(let u=0;u<i.length;u++){const _=i[u];_?._tempUnsub&&(_._tempUnsub(),_._tempUnsub=void 0)}D.release(i)}r!==p&&N.release(r),n!==f&&S.release(n)}else{D.release(c),S.release(x);for(let u=0;u<y.length;u++)y[u]?.();if(N.release(y),i!==a)for(let u=0;u<i.length;u++){const _=i[u];_&&(_._tempUnsub=void 0)}}}},this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??I.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??I.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._cleanup=null,this._dependencies=a,this._dependencyVersions=f,this._unsubscribes=p,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._history=E?[]:null,this._executionCount=0,b.attachDebugInfo(this,"effect",this.id)}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&(e._modifiedAtEpoch=this._currentEpoch),this._sync?this.execute():U.schedule(this.execute)});this._nextUnsubs&&this._nextUnsubs.push(t)}catch(t){console.error(A(t,g,l.EFFECT_EXECUTION_FAILED)),this._nextUnsubs&&this._nextUnsubs.push(()=>{})}}get isDisposed(){return(this.flags&P.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&P.EXECUTING)!==0}_setDisposed(){this.flags|=P.DISPOSED}_setExecuting(e){const t=P.EXECUTING;this.flags=this.flags&~t|-Number(e)&t}_safeCleanup(){if(this._cleanup){try{this._cleanup()}catch(e){console.error(A(e,g,l.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_checkInfiniteLoop(){if(this._lastFlushEpoch!==M&&(this._lastFlushEpoch=M,this._executionsInEpoch=0),this._executionsInEpoch++,this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),_e()>I.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,this._history){const e=Date.now();this._history.push(e),this._history.length>I.MAX_EXECUTIONS_PER_SECOND+10&&this._history.shift(),this._checkTimestampLoop(e)}}_checkTimestampLoop(e){const t=this._history;if(!t||this._maxExecutions<=0)return;const i=e-re.ONE_SECOND_MS;let n=0;for(let r=t.length-1;r>=0&&!(t[r]<i);r--)n++;if(n>this._maxExecutions){const r=new g(`Effect executed ${n} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(r),E)throw r}}_throwInfiniteLoopError(e){const t=new g(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${j}`);throw this.dispose(),console.error(t),t}_shouldExecute(){if(this._dependencies===a||this._dependencyVersions===f)return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t){if("value"in t)try{se(()=>t.value)}catch{return!0}if(t.version!==this._dependencyVersions[e])return!0}}return!1}_checkLoopWarnings(){if(this._trackModifications&&b.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const i=e[t];i&&i._modifiedAtEpoch===this._currentEpoch&&b.warn(!0,`Effect is reading a dependency (${b.getDebugName(i)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function ge(s,e={}){if(typeof s!="function")throw new g(l.EFFECT_MUST_BE_FUNCTION);const t=new Se(s,e);return t.execute(),t}function ne(s){return s!==null&&typeof s=="object"&&"value"in s&&"subscribe"in s&&typeof s.subscribe=="function"}function Ie(s){if(b.enabled&&(s==null||typeof s=="object")){const e=b.getDebugType(s);if(e)return e==="computed"}return ne(s)&&"invalidate"in s&&typeof s.invalidate=="function"}function De(s){return s!==null&&typeof s=="object"&&"dispose"in s&&"run"in s&&typeof s.dispose=="function"&&typeof s.run=="function"}exports.AsyncState=F;exports.AtomError=d;exports.ComputedError=m;exports.DEBUG_CONFIG=k;exports.DEBUG_RUNTIME=b;exports.EffectError=g;exports.POOL_CONFIG=ce;exports.SCHEDULER_CONFIG=I;exports.SchedulerError=T;exports.atom=be;exports.batch=fe;exports.computed=pe;exports.effect=ge;exports.isAtom=ne;exports.isComputed=Ie;exports.isEffect=De;exports.scheduler=U;exports.untracked=se;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const te={ONE_SECOND_MS:1e3},T={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},O={DISPOSED:1,EXECUTING:2},u={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},se={MAX_SIZE:1e3,WARMUP_SIZE:100},S={MAX_EXECUTIONS_PER_SECOND:1e3,CLEANUP_THRESHOLD:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10},V={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},N=1073741823,l=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production";class p extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class D extends p{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class b extends p{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class A extends p{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}const c={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber listener must be a function or Subscriber object",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation is pending. No default value provided",COMPUTED_COMPUTATION_FAILED:"Computed computation failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computed computation failed",COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED:"Failed to subscribe to dependency",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_SUBSCRIBER_EXECUTION_FAILED:"Error occurred while executing atom subscribers",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Error during individual atom subscriber execution",EFFECT_MUST_BE_FUNCTION:"Effect function must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup function execution failed",LARGE_DEPENDENCY_GRAPH:i=>`Large dependency graph detected: ${i} dependencies`,UNSUBSCRIBE_NON_EXISTENT:"Attempted to unsubscribe a non-existent listener",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},P=Symbol("debugName"),ie=Symbol("id"),M=Symbol("type"),q=Symbol("noDefaultValue");function ne(i){return"dependencies"in i&&Array.isArray(i.dependencies)}let k=0;function G(i,e,t){if(i._visitedEpoch!==t){if(i._visitedEpoch=t,i===e)throw new D("Indirect circular dependency detected");if(ne(i)){const s=i.dependencies;for(let n=0;n<s.length;n++){const r=s[n];r&&G(r,e,t)}}}}const a={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:V.MAX_DEPENDENCIES,warnInfiniteLoop:V.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e){if(i===e)throw new D("Direct circular dependency detected");this.enabled&&(k++,G(i,e,k))},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[P]=`${e}_${t}`,s[ie]=t,s[M]=e},getDebugName(i){if(i!=null&&P in i)return i[P]},getDebugType(i){if(i!=null&&M in i)return i[M]}};let re=1;const oe=()=>re++;class X{constructor(){this.id=oe()&N,this.flags=0}}class H extends X{constructor(){super(),this.version=0,this._lastSeenEpoch=-1}subscribe(e){if(typeof e=="object"&&e!==null&&"execute"in e)return this._objectSubscribers.add(e);if(typeof e!="function")throw new p(c.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(e)}subscriberCount(){return this._functionSubscribers.size+this._objectSubscribers.size}_notifySubscribers(e,t){this._functionSubscribers.forEachSafe(s=>s(e,t),s=>console.error(new p(c.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s))),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(new p(c.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s)))}}let L=0;function $(){return L=(L+1|0)&N,L}let U=0,w=0,x=!1;function j(){return x?(l&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(x=!0,U=U+1&N,w=0,!0)}function z(){x=!1}function ue(){return x?++w:0}class ce{constructor(){this.queueA=[],this.queueB=[],this.queue=this.queueA,this.queueSize=0,this._epoch=0,this.isProcessing=!1,this.isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=S.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e){if(typeof e!="function")throw new A("Scheduler callback must be a function");e._nextEpoch!==this._epoch&&(e._nextEpoch=this._epoch,this.isBatching||this.isFlushingSync?this.batchQueue[this.batchQueueSize++]=e:(this.queue[this.queueSize++]=e,this.isProcessing||this.flush()))}flush(){if(this.isProcessing||this.queueSize===0)return;this.isProcessing=!0;const e=this.queue,t=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++,queueMicrotask(()=>{const s=j();this._processJobs(e,t),this.isProcessing=!1,s&&z(),this.queueSize>0&&!this.isBatching&&this.flush()})}flushSync(){this.isFlushingSync=!0;const e=j();try{this._mergeBatchQueue(),this._drainQueue()}finally{this.isFlushingSync=!1,e&&z()}}_mergeBatchQueue(){if(this._epoch++,this.batchQueueSize>0){for(let e=0;e<this.batchQueueSize;e++){const t=this.batchQueue[e];t&&t._nextEpoch!==this._epoch&&(t._nextEpoch=this._epoch,this.queue[this.queueSize++]=t)}this.batchQueueSize=0}}_drainQueue(){let e=0;for(;this.queueSize>0;){if(++e>this.maxFlushIterations){this._handleFlushOverflow();break}this._processCurrentQueue(),this._mergeBatchQueue()}}_processCurrentQueue(){const e=this.queue,t=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++,this._processJobs(e,t)}_handleFlushOverflow(){console.error(new A(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this.queueSize=0,this.queue.length=0,this.batchQueueSize=0}_processJobs(e,t){for(let s=0;s<t;s++)try{e[s]?.()}catch(n){console.error(new A("Error occurred during scheduler execution",n))}e.length=0}startBatch(){this.batchDepth++,this.isBatching=!0}endBatch(){this.batchDepth=Math.max(0,this.batchDepth-1),this.batchDepth===0&&(this.flushSync(),this.isBatching=!1)}setMaxFlushIterations(e){if(e<S.MIN_FLUSH_ITERATIONS)throw new A(`Max flush iterations must be at least ${S.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const R=new ce;function he(i){if(typeof i!="function")throw new p("Batch callback must be a function");R.startBatch();try{return i()}finally{R.endBatch()}}const m={current:null,run(i,e){const t=this.current;this.current=i;try{return e()}finally{this.current=t}},getCurrent(){return this.current}};function Q(i){if(typeof i!="function")throw new p("Untracked callback must be a function");const e=m.current;m.current=null;try{return i()}finally{m.current=e}}class F{constructor(){this.subscribers=null}add(e){if(this.subscribers||(this.subscribers=[]),this.subscribers.indexOf(e)!==-1)return()=>{};this.subscribers.push(e);let t=!1;return()=>{t||(t=!0,this.remove(e))}}remove(e){if(!this.subscribers)return!1;const t=this.subscribers.indexOf(e);if(t===-1)return!1;const s=this.subscribers.length-1;return t!==s&&(this.subscribers[t]=this.subscribers[s]),this.subscribers.pop(),!0}has(e){return this.subscribers?this.subscribers.indexOf(e)!==-1:!1}forEach(e){if(this.subscribers)for(let t=0;t<this.subscribers.length;t++)e(this.subscribers[t],t)}forEachSafe(e,t){if(this.subscribers)for(let s=0;s<this.subscribers.length;s++)try{e(this.subscribers[s],s)}catch(n){t?t(n):console.error("[SubscriberManager] Error in subscriber callback:",n)}}get size(){return this.subscribers?.length??0}get hasSubscribers(){return this.subscribers!==null&&this.subscribers.length>0}clear(){this.subscribers=null}toArray(){return this.subscribers?[...this.subscribers]:[]}}function Y(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function _e(i){if(a.enabled&&(i==null||typeof i=="object")){const e=a.getDebugType(i);if(e)return e==="computed"}return Y(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function le(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}function J(i){return i!=null&&typeof i.then=="function"}function ae(i){return typeof i=="object"&&i!==null}function W(i){return(typeof i=="object"||typeof i=="function")&&i!==null&&typeof i.addDependency=="function"}function K(i){return typeof i=="function"&&typeof i.addDependency!="function"}function Z(i){return ae(i)&&typeof i.execute=="function"}class fe extends H{constructor(e,t){super(),this._isNotificationScheduled=!1,this._value=e,this._functionSubscribersStore=new F,this._objectSubscribersStore=new F,this._sync=t,this._notifyTask=this._flushNotifications.bind(this),a.attachDebugInfo(this,"atom",this.id)}get _functionSubscribers(){return this._functionSubscribersStore}get _objectSubscribers(){return this._objectSubscribersStore}get value(){const e=m.getCurrent();return e&&this._track(e),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this.version=this.version+1&N,this._value=e,!(!this._functionSubscribersStore.hasSubscribers&&!this._objectSubscribersStore.hasSubscribers)&&this._scheduleNotification(t)}_track(e){if(W(e)){e.addDependency(this);return}if(K(e)){this._functionSubscribersStore.add(e);return}Z(e)&&this._objectSubscribersStore.add(e)}_scheduleNotification(e){this._isNotificationScheduled||(this._pendingOldValue=e,this._isNotificationScheduled=!0),this._sync&&!R.isBatching?this._flushNotifications():R.schedule(this._notifyTask)}_flushNotifications(){if(!this._isNotificationScheduled)return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this._isNotificationScheduled=!1,this._notifySubscribers(t,e)}peek(){return this._value}dispose(){this._functionSubscribersStore.clear(),this._objectSubscribersStore.clear(),this._value=void 0}}function de(i,e={}){return new fe(i,e.sync??!1)}class B{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=l?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return l&&this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(e,t){if(!(t&&e===t)){if(Object.isFrozen(e)){l&&this.stats&&this.stats.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){l&&this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.maxPoolSize){l&&this.stats&&this.stats.rejected.poolFull++;return}e.length=0,this.pool.push(e),l&&this.stats&&this.stats.released++}}getStats(){if(!l||!this.stats)return null;const{acquired:e,released:t,rejected:s}=this.stats,n=s.frozen+s.tooLarge+s.poolFull;return{acquired:e,released:t,rejected:s,leaked:e-t-n,poolSize:this.pool.length}}reset(){this.pool.length=0,l&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const h=Object.freeze([]),f=Object.freeze([]),_=Object.freeze([]),g=new B,I=new B,d=new B;function pe(i,e,t,s){if(e!==h&&t!==f)for(let r=0;r<e.length;r++){const o=e[r];o&&(o._tempUnsub=t[r])}const n=I.acquire();n.length=i.length;for(let r=0;r<i.length;r++){const o=i[r];o&&(o._tempUnsub?(n[r]=o._tempUnsub,o._tempUnsub=void 0):(a.checkCircular(o,s),n[r]=o.subscribe(s)))}if(e!==h)for(let r=0;r<e.length;r++){const o=e[r];o?._tempUnsub&&(o._tempUnsub(),o._tempUnsub=void 0)}return t!==f&&I.release(t),n}function C(i,e,t){if(i instanceof TypeError)return new e(`Type error (${t}): ${i.message}`,i);if(i instanceof ReferenceError)return new e(`Reference error (${t}): ${i.message}`,i);if(i instanceof p)return i;const s=i instanceof Error?i.message:String(i),n=i instanceof Error?i:null;return new e(`Unexpected error (${t}): ${s}`,n)}class ee extends H{constructor(e,t={}){if(typeof e!="function")throw new D(c.COMPUTED_MUST_BE_FUNCTION);if(super(),this._value=void 0,this.flags=u.DIRTY|u.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:q,this._hasDefaultValue=this._defaultValue!==q,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._functionSubscribersStore=new F,this._objectSubscribersStore=new F,this._dependencies=h,this._dependencyVersions=_,this._unsubscribes=f,this._notifyJob=()=>{this._functionSubscribersStore.forEachSafe(s=>s(),s=>console.error(s)),this._objectSubscribersStore.forEachSafe(s=>s.execute(),s=>console.error(s))},this._trackable=Object.assign(()=>this._markDirty(),{addDependency:s=>{}}),a.attachDebugInfo(this,"computed",this.id),a.enabled){const s=this;s.subscriberCount=()=>this._functionSubscribersStore.size+this._objectSubscribersStore.size,s.isDirty=()=>this._isDirty(),s.dependencies=this._dependencies,s.stateFlags=this._getFlagsAsString()}if(t.lazy===!1)try{this._recompute()}catch{}}get _functionSubscribers(){return this._functionSubscribersStore}get _objectSubscribers(){return this._objectSubscribersStore}get value(){const e=this._computeValue();return this._registerTracking(),e}peek(){return this._value}get state(){return this._getAsyncState()}get hasError(){return this._isRejected()}get lastError(){return this._error}get isPending(){return this._isPending()}get isResolved(){return this._isResolved()}invalidate(){this._markDirty(),this._dependencyVersions!==_&&(d.release(this._dependencyVersions),this._dependencyVersions=_)}dispose(){if(this._unsubscribes!==f){for(let e=0;e<this._unsubscribes.length;e++){const t=this._unsubscribes[e];t&&t()}I.release(this._unsubscribes),this._unsubscribes=f}this._dependencies!==h&&(g.release(this._dependencies),this._dependencies=h),this._dependencyVersions!==_&&(d.release(this._dependencyVersions),this._dependencyVersions=_),this._functionSubscribersStore.clear(),this._objectSubscribersStore.clear(),this.flags=u.DIRTY|u.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID}_isDirty(){return(this.flags&u.DIRTY)!==0}_setDirty(){this.flags|=u.DIRTY}_clearDirty(){this.flags&=-2}_isIdle(){return(this.flags&u.IDLE)!==0}_setIdle(){this.flags|=u.IDLE,this.flags&=-29}_isPending(){return(this.flags&u.PENDING)!==0}_setPending(){this.flags|=u.PENDING,this.flags&=-27}_isResolved(){return(this.flags&u.RESOLVED)!==0}_setResolved(){this.flags|=u.RESOLVED,this.flags&=-87}_isRejected(){return(this.flags&u.REJECTED)!==0}_setRejected(){this.flags|=u.REJECTED|u.HAS_ERROR,this.flags&=-15}_isRecomputing(){return(this.flags&u.RECOMPUTING)!==0}_setRecomputing(e){const t=u.RECOMPUTING;this.flags=this.flags&~t|-Number(e)&t}_getAsyncState(){return this._isResolved()?T.RESOLVED:this._isPending()?T.PENDING:this._isRejected()?T.REJECTED:T.IDLE}_getFlagsAsString(){const e=[];return this._isDirty()&&e.push("DIRTY"),this._isIdle()&&e.push("IDLE"),this._isPending()&&e.push("PENDING"),this._isResolved()&&e.push("RESOLVED"),this._isRejected()&&e.push("REJECTED"),this._isRecomputing()&&e.push("RECOMPUTING"),e.join(" | ")}_computeValue(){return this._isRecomputing()?this._value:((this._isDirty()||this._isIdle())&&this._recompute(),this._isPending()?this._handlePending():this._isRejected()?this._handleRejected():this._value)}_recompute(){if(this._isRecomputing())return;this._setRecomputing(!0);const e=this._prepareComputationContext();let t=!1;try{const s=m.run(this._trackable,this._fn);J(s)?(this._commitDependencies(e),t=!0,this._handleAsyncComputation(s)):(this._commitDependencies(e),t=!0,this._handleSyncResult(s))}catch(s){this._commitDependencies(e),t=!0,this._handleComputationError(s)}finally{this._cleanupContext(e,t),this._setRecomputing(!1)}}_prepareComputationContext(){const e=this._dependencies,t=this._dependencyVersions,s=g.acquire(),n=d.acquire(),r=$(),o={depCount:0},v=E=>{E._lastSeenEpoch!==r&&(E._lastSeenEpoch=r,o.depCount<s.length?(s[o.depCount]=E,n[o.depCount]=E.version):(s.push(E),n.push(E.version)),o.depCount++)},y=this._trackable.addDependency;return this._trackable.addDependency=v,{prevDeps:e,prevVersions:t,nextDeps:s,nextVersions:n,originalAdd:y,state:o}}_commitDependencies(e){const{nextDeps:t,nextVersions:s,state:n,prevDeps:r}=e;t.length=n.depCount,s.length=n.depCount,this._unsubscribes=pe(t,r,this._unsubscribes,this),this._dependencies=t,this._dependencyVersions=s}_cleanupContext(e,t){this._trackable.addDependency=e.originalAdd,t?(e.prevDeps!==h&&g.release(e.prevDeps),e.prevVersions!==_&&d.release(e.prevVersions)):(g.release(e.nextDeps),d.release(e.nextVersions))}_handleSyncResult(e){(!this._isResolved()||!this._equal(this._value,e))&&(this.version=this.version+1&N),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1)}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._promiseId=this._promiseId>=this.MAX_PROMISE_ID?1:this._promiseId+1;const t=this._promiseId;e.then(s=>{t===this._promiseId&&this._handleAsyncResolution(s)}).catch(s=>{t===this._promiseId&&this._handleAsyncRejection(s)})}_handleAsyncResolution(e){(!this._isResolved()||!this._equal(this._value,e))&&(this.version=this.version+1&N),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1)}_handleAsyncRejection(e){const t=C(e,D,c.COMPUTED_ASYNC_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(s){console.error(c.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}this._notifySubscribers(void 0,void 0)}_handleComputationError(e){const t=C(e,D,c.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(s){console.error(c.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new D(c.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){if(this._error?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw this._error}execute(){this._markDirty()}_markDirty(){this._isRecomputing()||this._isDirty()||(this._setDirty(),this._notifyJob())}_registerTracking(){const e=m.getCurrent();if(e){if(W(e)){e.addDependency(this);return}if(K(e)){this._functionSubscribersStore.add(e);return}Z(e)&&this._objectSubscribersStore.add(e)}}}Object.freeze(ee.prototype);function Ee(i,e={}){return new ee(i,e)}class be extends X{constructor(e,t={}){super(),this.run=()=>{if(this.isDisposed)throw new b(c.EFFECT_MUST_BE_FUNCTION);this._dependencyVersions!==_&&(d.release(this._dependencyVersions),this._dependencyVersions=_),this.execute()},this.dispose=()=>{if(!this.isDisposed){if(this._setDisposed(),this._safeCleanup(),this._unsubscribes!==f){for(let s=0;s<this._unsubscribes.length;s++){const n=this._unsubscribes[s];n&&n()}I.release(this._unsubscribes),this._unsubscribes=f}this._dependencies!==h&&(g.release(this._dependencies),this._dependencies=h),this._dependencyVersions!==_&&(d.release(this._dependencyVersions),this._dependencyVersions=_)}},this.addDependency=s=>{if(this.isExecuting&&this._nextDeps&&this._nextUnsubs&&this._nextVersions){const n=this._currentEpoch;if(s._lastSeenEpoch===n)return;s._lastSeenEpoch=n,this._nextDeps.push(s),this._nextVersions.push(s.version),s._tempUnsub?(this._nextUnsubs.push(s._tempUnsub),s._tempUnsub=void 0):this._subscribeTo(s)}},this.execute=()=>{if(this.isDisposed||this.isExecuting||!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const s=this._prepareEffectContext();let n=!1;try{const r=m.run(this,this._fn);this._commitEffect(s),n=!0,this._checkLoopWarnings(),J(r)?r.then(o=>{!this.isDisposed&&typeof o=="function"&&(this._cleanup=o)}).catch(o=>{console.error(C(o,b,c.EFFECT_EXECUTION_FAILED))}):this._cleanup=typeof r=="function"?r:null}catch(r){n=!0,console.error(C(r,b,c.EFFECT_EXECUTION_FAILED)),this._cleanup=null}finally{this._cleanupEffect(s,n),this._setExecuting(!1)}},this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??S.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??S.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._cleanup=null,this._dependencies=h,this._dependencyVersions=_,this._unsubscribes=f,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._history=l?[]:null,this._executionCount=0,a.attachDebugInfo(this,"effect",this.id)}_prepareEffectContext(){const e=this._dependencies,t=this._dependencyVersions,s=this._unsubscribes,n=g.acquire(),r=d.acquire(),o=I.acquire(),v=$();if(e!==h&&s!==f)for(let y=0;y<e.length;y++){const E=e[y];E&&(E._tempUnsub=s[y])}return this._nextDeps=n,this._nextVersions=r,this._nextUnsubs=o,this._currentEpoch=v,{prevDeps:e,prevVersions:t,prevUnsubs:s,nextDeps:n,nextVersions:r,nextUnsubs:o}}_commitEffect(e){const t=e.nextDeps.length;e.nextDeps.length=t,e.nextVersions.length=t,this._dependencies=e.nextDeps,this._dependencyVersions=e.nextVersions,this._unsubscribes=e.nextUnsubs}_cleanupEffect(e,t){if(this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,t){if(e.prevDeps!==h){for(let s=0;s<e.prevDeps.length;s++){const n=e.prevDeps[s];n?._tempUnsub&&(n._tempUnsub(),n._tempUnsub=void 0)}g.release(e.prevDeps)}e.prevUnsubs!==f&&I.release(e.prevUnsubs),e.prevVersions!==_&&d.release(e.prevVersions)}else{g.release(e.nextDeps),d.release(e.nextVersions);for(let s=0;s<e.nextUnsubs.length;s++)e.nextUnsubs[s]?.();if(I.release(e.nextUnsubs),e.prevDeps!==h)for(let s=0;s<e.prevDeps.length;s++){const n=e.prevDeps[s];n&&(n._tempUnsub=void 0)}}}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&(e._modifiedAtEpoch=this._currentEpoch),this._sync?this.execute():R.schedule(this.execute)});this._nextUnsubs&&this._nextUnsubs.push(t)}catch(t){console.error(C(t,b,c.EFFECT_EXECUTION_FAILED)),this._nextUnsubs&&this._nextUnsubs.push(()=>{})}}get isDisposed(){return(this.flags&O.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&O.EXECUTING)!==0}_setDisposed(){this.flags|=O.DISPOSED}_setExecuting(e){const t=O.EXECUTING;this.flags=this.flags&~t|-Number(e)&t}_safeCleanup(){if(this._cleanup){try{this._cleanup()}catch(e){console.error(C(e,b,c.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_checkInfiniteLoop(){if(this._lastFlushEpoch!==U&&(this._lastFlushEpoch=U,this._executionsInEpoch=0),this._executionsInEpoch++,this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),ue()>S.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,this._history){const e=Date.now();this._history.push(e),this._history.length>S.MAX_EXECUTIONS_PER_SECOND+10&&this._history.shift(),this._checkTimestampLoop(e)}}_checkTimestampLoop(e){const t=this._history;if(!t||this._maxExecutions<=0)return;const s=e-te.ONE_SECOND_MS;let n=0;for(let r=t.length-1;r>=0&&!(t[r]<s);r--)n++;if(n>this._maxExecutions){const r=new b(`Effect executed ${n} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(r),l)throw r}}_throwInfiniteLoopError(e){const t=new b(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${w}`);throw this.dispose(),console.error(t),t}_shouldExecute(){if(this._dependencies===h||this._dependencyVersions===_)return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t){if("value"in t)try{Q(()=>t.value)}catch{return!0}if(t.version!==this._dependencyVersions[e])return!0}}return!1}_checkLoopWarnings(){if(this._trackModifications&&a.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const s=e[t];s&&s._modifiedAtEpoch===this._currentEpoch&&a.warn(!0,`Effect is reading a dependency (${a.getDebugName(s)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function Se(i,e={}){if(typeof i!="function")throw new b(c.EFFECT_MUST_BE_FUNCTION);const t=new be(i,e);return t.execute(),t}exports.AsyncState=T;exports.AtomError=p;exports.ComputedError=D;exports.DEBUG_CONFIG=V;exports.DEBUG_RUNTIME=a;exports.EffectError=b;exports.POOL_CONFIG=se;exports.SCHEDULER_CONFIG=S;exports.SchedulerError=A;exports.atom=de;exports.batch=he;exports.computed=Ee;exports.effect=Se;exports.isAtom=Y;exports.isComputed=_e;exports.isEffect=le;exports.scheduler=R;exports.untracked=Q;
2
2
  //# sourceMappingURL=index.cjs.map