@but212/atom-effect 0.2.1 → 0.3.0

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/README.md CHANGED
@@ -108,6 +108,11 @@ const effectObj = effect(() => {
108
108
  effectObj.dispose(); // Stop the effect
109
109
  ```
110
110
 
111
+ **Options:**
112
+
113
+ - `sync` - Run synchronously (default: `false`)
114
+ - `maxExecutionsPerFlush` - Maximum executions per flush cycle to prevent infinite loops (default: `SCHEDULER_CONFIG.MAX_EXECUTIONS_PER_FLUSH`)
115
+
111
116
  ### `batch(fn)`
112
117
 
113
118
  Batches multiple updates to run effects only once.
@@ -162,43 +167,6 @@ effect(() => {
162
167
  });
163
168
  ```
164
169
 
165
- ### API Integration
166
-
167
- ```typescript
168
- const userId = atom(1);
169
- const userData = computed(async () => {
170
- const res = await fetch(`/api/users/${userId.value}`);
171
- if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
172
- return res.json();
173
- }, {
174
- defaultValue: null,
175
- onError: (e) => console.error('Failed to fetch user data:', e)
176
- });
177
-
178
- effect(() => {
179
- if (userData.value) {
180
- console.log('User loaded:', userData.value.name);
181
- }
182
- });
183
- ```
184
-
185
- ### Persistent State
186
-
187
- ```typescript
188
- function persistentAtom<T>(key: string, initialValue: T) {
189
- const stored = localStorage.getItem(key);
190
- const a = atom<T>(stored ? JSON.parse(stored) : initialValue);
191
-
192
- effect(() => {
193
- localStorage.setItem(key, JSON.stringify(a.value));
194
- });
195
-
196
- return a;
197
- }
198
-
199
- const theme = persistentAtom('theme', 'light');
200
- ```
201
-
202
170
  ## Utilities
203
171
 
204
172
  ### Type Guards
@@ -243,20 +211,20 @@ try {
243
211
 
244
212
  | Operation | Performance |
245
213
  | --- | --- |
246
- | Atom creation | ~5.2M ops/sec |
247
- | Atom read/write | ~4.7M ops/sec |
248
- | Computed creation | ~1.67M ops/sec |
249
- | Computed recomputation | ~572K ops/sec |
250
- | Effect execution | ~402K ops/sec |
251
- | Batch update (2 atoms) | ~2.16M ops/sec |
252
- | Untracked read | ~3.2M ops/sec |
214
+ | Atom creation | ~4.9M ops/sec |
215
+ | Atom read/write | ~4.3M ops/sec |
216
+ | Computed creation | ~1.71M ops/sec |
217
+ | Computed recomputation | ~566K ops/sec |
218
+ | Effect execution | ~515K ops/sec |
219
+ | Batch update (2 atoms) | ~1.92M ops/sec |
220
+ | Untracked read | ~3.29M ops/sec |
253
221
 
254
222
  See [docs/BENCHMARKS.md](./docs/BENCHMARKS.md) for details.
255
223
 
256
224
  ## Testing
257
225
 
258
226
  ```bash
259
- pnpm test # Run all tests (400+ test cases)
227
+ pnpm test # Run all tests (299 test cases)
260
228
  pnpm test:coverage # With coverage
261
229
  pnpm bench # Run benchmarks
262
230
  ```
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},m={DISPOSED:1,EXECUTING:2},c={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},B={MAX_SIZE:1e3,WARMUP_SIZE:100},P={MAX_EXECUTIONS_PER_SECOND:100,CLEANUP_THRESHOLD:100},F={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},C=1073741823;class _ extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class p extends _{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class E extends _{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class g extends _{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}function y(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 _)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)}function M(i){return i!=null&&typeof i.then=="function"}const o={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber listener must be a function",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",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"};class q{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=1e3}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e){if(typeof e!="function")throw new g("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(()=>{for(let s=0;s<t;s++)try{e[s]?.()}catch(n){console.error(new g("Error occurred during scheduler execution",n))}e.length=0,this.isProcessing=!1,this.queueSize>0&&!this.isBatching&&this.flush()})}flushSync(){this.isFlushingSync=!0;try{if(this._epoch++,this.batchQueueSize>0){for(let t=0;t<this.batchQueueSize;t++){const s=this.batchQueue[t];s._nextEpoch!==this._epoch&&(s._nextEpoch=this._epoch,this.queue[this.queueSize++]=s)}this.batchQueueSize=0}let e=0;for(;this.queueSize>0;){if(++e>this.maxFlushIterations){console.error(new g(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop in reactive dependencies. Consider increasing the limit with scheduler.setMaxFlushIterations()`)),this.queueSize=0,this.queue.length=0,this.batchQueueSize=0;break}const t=this.queue,s=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++;for(let n=0;n<s;n++)try{t[n]?.()}catch(r){console.error(new g("Error occurred during batch execution",r))}if(t.length=0,this.batchQueueSize>0){for(let n=0;n<this.batchQueueSize;n++)this.queue[this.queueSize++]=this.batchQueue[n];this.batchQueueSize=0}}}finally{this.isFlushingSync=!1}}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<10)throw new g("Max flush iterations must be at least 10");this.maxFlushIterations=e}}const S=new q;function k(i){if(typeof i!="function")throw new _("Batch callback must be a function");S.startBatch();try{return i()}catch(e){throw new _("Error occurred during batch execution",e)}finally{S.endBatch()}}const D={current:null,run(i,e){const t=this.current;this.current=i;try{return e()}finally{this.current=t}},getCurrent(){return this.current}};function z(i){if(typeof i!="function")throw new _("Untracked callback must be a function");const e=D.current;D.current=null;try{return i()}catch(t){throw new _("Error occurred during untracked execution",t)}finally{D.current=e}}const T=Symbol("debugName"),G=Symbol("id"),A=Symbol("type"),U=Symbol("noDefaultValue");function V(i){return i!==null&&typeof i=="object"&&"dependencies"in i&&i.dependencies instanceof Set}const a={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:F.MAX_DEPENDENCIES,warnInfiniteLoop:F.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e,t=new Set){if(i===e)throw new p("Direct circular dependency detected");if(this.enabled){if(t.has(i))throw new p("Indirect circular dependency detected");if(t.add(i),V(i))for(const s of i.dependencies)this.checkCircular(s,e,t)}},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[T]=`${e}_${t}`,s[G]=t,s[A]=e},getDebugName(i){if(i!==null&&typeof i=="object"&&T in i)return i[T]},getDebugType(i){if(i!==null&&typeof i=="object"&&A in i)return i[A]}};let j=1;const x=()=>j++;class N{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.size>0}clear(){this.subscribers=null}toArray(){return this.subscribers?[...this.subscribers]:[]}}class X{constructor(e,t){this._isNotificationScheduled=!1,this.id=x()&C,this.version=0,this.flags=0,this._lastSeenEpoch=-1,this._value=e,this._functionSubscribers=new N,this._objectSubscribers=new N,this._sync=t,this._notifyTask=this._flushNotifications.bind(this),a.attachDebugInfo(this,"atom",this.id)}get value(){const e=D.getCurrent();return e!=null&&this._track(e),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this.version=this.version+1&C;const s=this.version;this._value=e,!(!this._functionSubscribers.hasSubscribers&&!this._objectSubscribers.hasSubscribers)&&this._notify(e,t,s)}_track(e){if(typeof e=="function"){const t=e;t.addDependency!==void 0?t.addDependency(this):this._functionSubscribers.add(e)}else{const t=e;t.addDependency!==void 0?t.addDependency(this):t.execute!==void 0&&this._objectSubscribers.add(t)}}_notify(e,t,s){this._isNotificationScheduled||(this._pendingOldValue=t,this._isNotificationScheduled=!0),this._sync&&!S.isBatching?this._flushNotifications():S.schedule(this._notifyTask)}_flushNotifications(){if(!this._isNotificationScheduled)return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this._isNotificationScheduled=!1,this._functionSubscribers.forEachSafe(s=>s(t,e),s=>console.error(new _(o.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s))),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(new _(o.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s)))}subscribe(e){if(typeof e!="function")throw new _(o.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(e)}peek(){return this._value}dispose(){this._functionSubscribers.clear(),this._objectSubscribers.clear(),this._value=void 0}subscriberCount(){return this._functionSubscribers.size+this._objectSubscribers.size}}function Y(i,e={}){return new X(i,e.sync??!1)}let O=0;function L(){return O=(O+1|0)&C,O}const f=process.env.NODE_ENV!=="production",l=Object.freeze([]);class Q{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=f?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return f&&this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(e,t){if(!(t&&e===t)){if(Object.isFrozen(e)){f&&this.stats&&this.stats.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){f&&this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.maxPoolSize){f&&this.stats&&this.stats.rejected.poolFull++;return}e.length=0,this.pool.push(e),f&&this.stats&&this.stats.released++}}getStats(){if(!f||!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,f&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const b=new Q;class w{constructor(e,t={}){if(typeof e!="function")throw new p(o.COMPUTED_MUST_BE_FUNCTION);if(this.id=x()&C,this.version=0,this.flags=0,this._lastSeenEpoch=-1,this._value=void 0,this._stateFlags=c.DIRTY|c.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:U,this._hasDefaultValue=this._defaultValue!==U,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._functionSubscribers=new N,this._objectSubscribers=new N,this._dependencies=l,this._subscriptions=new Map,this._recomputeJob=()=>{if(this._isDirty())try{this._recompute()}catch{}},this._notifyJob=()=>{this._functionSubscribers.forEachSafe(s=>s(),s=>console.error(s)),this._objectSubscribers.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._functionSubscribers.size+this._objectSubscribers.size,s.isDirty=()=>this._isDirty(),s.dependencies=this._dependencies,s.stateFlags=this._getFlagsAsString()}if(t.lazy===!1)try{this._recompute()}catch{}}get value(){if((this._stateFlags&(c.RESOLVED|c.DIRTY))===c.RESOLVED)return this._registerTracking(),this._value;const t=this._computeValue();return this._registerTracking(),t}subscribe(e){if(typeof e!="function")throw new p(o.COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(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()}dispose(){if(this._dependencies!==l){for(const e of this._dependencies){const t=this._subscriptions.get(e.id);t&&t(),this._subscriptions.delete(e.id)}b.release(this._dependencies)}this._dependencies=l,this._functionSubscribers.clear(),this._objectSubscribers.clear(),this._stateFlags=c.DIRTY|c.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID}_isDirty(){return(this._stateFlags&c.DIRTY)!==0}_setDirty(){this._stateFlags|=c.DIRTY}_clearDirty(){this._stateFlags&=-2}_isIdle(){return(this._stateFlags&c.IDLE)!==0}_setIdle(){this._stateFlags|=c.IDLE,this._stateFlags&=-29}_isPending(){return(this._stateFlags&c.PENDING)!==0}_setPending(){this._stateFlags|=c.PENDING,this._stateFlags&=-27}_isResolved(){return(this._stateFlags&c.RESOLVED)!==0}_setResolved(){this._stateFlags|=c.RESOLVED,this._stateFlags&=-87}_isRejected(){return(this._stateFlags&c.REJECTED)!==0}_setRejected(){this._stateFlags|=c.REJECTED|c.HAS_ERROR,this._stateFlags&=-15}_isRecomputing(){return(this._stateFlags&c.RECOMPUTING)!==0}_setRecomputing(e){e?this._stateFlags|=c.RECOMPUTING:this._stateFlags&=-33}_getAsyncState(){return this._isPending()?I.PENDING:this._isResolved()?I.RESOLVED:this._isRejected()?I.REJECTED:I.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._isPending()?this._handlePending():this._isRejected()?this._handleRejected():(this._isDirty()||this._isIdle())&&(this._recompute(),this._isPending())?this._handlePending():this._value}_recompute(){if(!this._isDirty()&&this._isResolved())return;this._setRecomputing(!0);const e=this._dependencies,t=b.acquire(),s=L();let n=0;const r=h=>{h._lastSeenEpoch!==s&&(h._lastSeenEpoch=s,n<t.length?t[n]=h:t.push(h),n++)},u=this._trackable.addDependency;this._trackable.addDependency=r;let d=!1;try{const h=D.run(this._trackable,this._fn);if(t.length=n,M(h)){this._syncDependencies(e,t,s),this._dependencies=t,d=!0,this._handleAsyncComputation(h),this._setRecomputing(!1);return}this._syncDependencies(e,t,s),this._dependencies=t,d=!0,this._handleSyncResult(h)}catch(h){t.length=n,this._syncDependencies(e,t,s),this._dependencies=t,d=!0,this._handleComputationError(h)}finally{this._trackable.addDependency=u,d?e!==l&&b.release(e):b.release(t)}}_syncDependencies(e,t,s){if(e!==l)for(let n=0;n<e.length;n++){const r=e[n];if(r&&r._lastSeenEpoch!==s){const u=this._subscriptions.get(r.id);u&&(u(),this._subscriptions.delete(r.id))}}for(let n=0;n<t.length;n++){const r=t[n];if(r&&!this._subscriptions.has(r.id)){a.checkCircular(r,this);const u=r.subscribe(()=>this._markDirty());this._subscriptions.set(r.id,u)}}}_handleSyncResult(e){const t=!this._isResolved()||!this._equal(this._value,e);this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),t&&this._notifySubscribers()}_handleAsyncComputation(e){this._setPending(),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){const t=!this._isResolved()||!this._equal(this._value,e);this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),t&&this._notifySubscribers()}_handleAsyncRejection(e){const t=y(e,p,o.COMPUTED_ASYNC_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError&&typeof this._onError=="function")try{this._onError(t)}catch(s){console.error(o.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}this._notifySubscribers()}_handleComputationError(e){const t=y(e,p,o.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError&&typeof this._onError=="function")try{this._onError(t)}catch(s){console.error(o.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new p(o.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){if(this._error?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw this._error}_markDirty(){this._isRecomputing()||this._isDirty()||(this._setDirty(),this._setIdle(),(this._functionSubscribers.hasSubscribers||this._objectSubscribers.hasSubscribers)&&S.schedule(this._recomputeJob))}_notifySubscribers(){!this._functionSubscribers.hasSubscribers&&!this._objectSubscribers.hasSubscribers||S.schedule(this._notifyJob)}_registerTracking(){const e=D.getCurrent();if(e)if(typeof e=="object"&&e!==null&&e.addDependency)e.addDependency(this);else if(typeof e=="function"){const t=e;t.addDependency?t.addDependency(this):this._functionSubscribers.add(e)}else e.execute&&this._objectSubscribers.add(e)}}Object.freeze(w.prototype);function $(i,e={}){return new w(i,e)}class H{constructor(e,t={}){this.run=()=>{if(this.isDisposed)throw new E(o.EFFECT_MUST_BE_FUNCTION);this.execute()},this.dispose=()=>{if(!this.isDisposed&&(this._setDisposed(),this._safeCleanup(),this._dependencies!==l)){for(const s of this._dependencies){const n=this._subscriptions.get(s.id);n&&n(),this._subscriptions.delete(s.id)}b.release(this._dependencies),this._dependencies=l}},this.addDependency=s=>{if(this.isExecuting&&this._nextDeps){const n=s,r=this._currentEpoch;if(n._lastSeenEpoch===r)return;n._lastSeenEpoch=r,this._nextDeps.push(n),this._subscriptions.has(n.id)||this._subscribeTo(n)}},this.execute=()=>{if(this.isDisposed||this.isExecuting)return;const s=Date.now();this._recordExecution(s),this._setExecuting(!0),this._safeCleanup(),this._modifiedDeps.clear();const n=this._dependencies,r=b.acquire(),u=L();this._nextDeps=r,this._currentEpoch=u;let d=!1;try{const h=D.run(this,this._fn);this._syncDependencies(n,u),this._dependencies=r,d=!0,this._checkLoopWarnings(),M(h)?h.then(R=>{!this.isDisposed&&typeof R=="function"&&(this._cleanup=R)}).catch(R=>{console.error(y(R,E,o.EFFECT_EXECUTION_FAILED))}):this._cleanup=typeof h=="function"?h:null}catch(h){this._syncDependencies(n,u),this._dependencies=r,d=!0,console.error(y(h,E,o.EFFECT_EXECUTION_FAILED)),this._cleanup=null}finally{this._setExecuting(!1),this._nextDeps=null,d?n!==l&&b.release(n):b.release(r)}},this._id=x()&C,this._flags=0,this._currentEpoch=-1,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??P.MAX_EXECUTIONS_PER_SECOND,this._trackModifications=t.trackModifications??!1,this._cleanup=null,this._dependencies=l,this._subscriptions=new Map,this._nextDeps=null,this._modifiedDeps=new Set,this._historyCapacity=this._maxExecutions+5,this._history=new Float64Array(this._historyCapacity),this._historyIdx=0,this._historyCount=0,this._executionCount=0,a.attachDebugInfo(this,"effect",this._id)}_syncDependencies(e,t){if(e!==l)for(let s=0;s<e.length;s++){const n=e[s];if(n&&n._lastSeenEpoch!==t){const r=this._subscriptions.get(n.id);r&&(r(),this._subscriptions.delete(n.id))}}}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&this._modifiedDeps.add(e),this._sync?this.execute():S.schedule(this.execute)});this._subscriptions.set(e.id,t)}catch(t){console.error(y(t,E,o.EFFECT_EXECUTION_FAILED))}}get isDisposed(){return(this._flags&m.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this._flags&m.EXECUTING)!==0}_setDisposed(){this._flags|=m.DISPOSED}_setExecuting(e){e?this._flags|=m.EXECUTING:this._flags&=-3}_safeCleanup(){if(this._cleanup&&typeof this._cleanup=="function"){try{this._cleanup()}catch(e){console.error(y(e,E,o.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_recordExecution(e){if(this._maxExecutions<=0)return;const t=e-1e3;this._history[this._historyIdx]=e,this._historyIdx=(this._historyIdx+1)%this._historyCapacity,this._historyCount<this._historyCapacity&&this._historyCount++,this._executionCount++;let s=0,n=(this._historyIdx-1+this._historyCapacity)%this._historyCapacity;for(let r=0;r<this._historyCount&&!(this._history[n]<t);r++)s++,n=(n-1+this._historyCapacity)%this._historyCapacity;if(s>this._maxExecutions){const r=`Effect executed ${s} times within 1 second. Infinite loop suspected`,u=new E(r);if(this.dispose(),console.error(u),a.enabled)throw u}}_checkLoopWarnings(){if(this._trackModifications&&a.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const s=e[t];s&&this._modifiedDeps.has(s)&&a.warn(!0,`Effect is reading a dependency (${a.getDebugName(s)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function J(i,e={}){if(typeof i!="function")throw new E(o.EFFECT_MUST_BE_FUNCTION);const t=new H(i,e);return t.execute(),t}function v(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function W(i){if(a.enabled){const e=a.getDebugType(i);if(e)return e==="computed"}return v(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function K(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}exports.AsyncState=I;exports.AtomError=_;exports.ComputedError=p;exports.DEBUG_CONFIG=F;exports.DEBUG_RUNTIME=a;exports.EffectError=E;exports.POOL_CONFIG=B;exports.SCHEDULER_CONFIG=P;exports.SchedulerError=g;exports.atom=Y;exports.batch=k;exports.computed=$;exports.effect=J;exports.isAtom=v;exports.isComputed=W;exports.isEffect=K;exports.scheduler=S;exports.untracked=z;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},C={DISPOSED:1,EXECUTING:2},c={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},G={MAX_SIZE:1e3,WARMUP_SIZE:100},R={MAX_EXECUTIONS_PER_SECOND:100,CLEANUP_THRESHOLD:100,MAX_EXECUTIONS_PER_EFFECT:50,MAX_EXECUTIONS_PER_FLUSH:5e3},x={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},y=1073741823,P=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production";class a extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class p extends a{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class d extends a{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class D extends a{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}function I(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 a)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)}function k(i){return i!=null&&typeof i.then=="function"}const h={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber listener must be a function",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",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"};let O=0;function q(){return O=(O+1|0)&y,O}let N=0,L=0,T=!1;function w(){return T?(P&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(T=!0,N=N+1&y,L=0,!0)}function v(){T=!1}function j(){return T?++L:0}class X{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=1e3}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e){if(typeof e!="function")throw new D("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=w();for(let n=0;n<t;n++)try{e[n]?.()}catch(r){console.error(new D("Error occurred during scheduler execution",r))}e.length=0,this.isProcessing=!1,s&&v(),this.queueSize>0&&!this.isBatching&&this.flush()})}flushSync(){this.isFlushingSync=!0;const e=w();try{if(this._epoch++,this.batchQueueSize>0){for(let s=0;s<this.batchQueueSize;s++){const n=this.batchQueue[s];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 D(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop in reactive dependencies. Consider increasing the limit with scheduler.setMaxFlushIterations()`)),this.queueSize=0,this.queue.length=0,this.batchQueueSize=0;break}const s=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{s[r]?.()}catch(u){console.error(new D("Error occurred during batch execution",u))}if(s.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&&v()}}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<10)throw new D("Max flush iterations must be at least 10");this.maxFlushIterations=e}}const S=new X;function $(i){if(typeof i!="function")throw new a("Batch callback must be a function");S.startBatch();try{return i()}catch(e){throw new a("Error occurred during batch execution",e)}finally{S.endBatch()}}const g={current:null,run(i,e){const t=this.current;this.current=i;try{return e()}finally{this.current=t}},getCurrent(){return this.current}};function Y(i){if(typeof i!="function")throw new a("Untracked callback must be a function");const e=g.current;g.current=null;try{return i()}catch(t){throw new a("Error occurred during untracked execution",t)}finally{g.current=e}}const A=Symbol("debugName"),Q=Symbol("id"),U=Symbol("type"),B=Symbol("noDefaultValue");function H(i){return i!==null&&typeof i=="object"&&"dependencies"in i&&i.dependencies instanceof Set}const l={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:x.MAX_DEPENDENCIES,warnInfiniteLoop:x.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e,t=new Set){if(i===e)throw new p("Direct circular dependency detected");if(this.enabled){if(t.has(i))throw new p("Indirect circular dependency detected");if(t.add(i),H(i))for(const s of i.dependencies)this.checkCircular(s,e,t)}},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[A]=`${e}_${t}`,s[Q]=t,s[U]=e},getDebugName(i){if(i!==null&&typeof i=="object"&&A in i)return i[A]},getDebugType(i){if(i!==null&&typeof i=="object"&&U in i)return i[U]}};let J=1;const M=()=>J++;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.size>0}clear(){this.subscribers=null}toArray(){return this.subscribers?[...this.subscribers]:[]}}class W{constructor(e,t){this._isNotificationScheduled=!1,this.id=M()&y,this.version=0,this.flags=0,this._lastSeenEpoch=-1,this._value=e,this._functionSubscribers=new F,this._objectSubscribers=new F,this._sync=t,this._notifyTask=this._flushNotifications.bind(this),l.attachDebugInfo(this,"atom",this.id)}get value(){const e=g.getCurrent();return e!=null&&this._track(e),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this.version=this.version+1&y;const s=this.version;this._value=e,!(!this._functionSubscribers.hasSubscribers&&!this._objectSubscribers.hasSubscribers)&&this._notify(e,t,s)}_track(e){if(typeof e=="function"){const t=e;t.addDependency!==void 0?t.addDependency(this):this._functionSubscribers.add(e)}else{const t=e;t.addDependency!==void 0?t.addDependency(this):t.execute!==void 0&&this._objectSubscribers.add(t)}}_notify(e,t,s){this._isNotificationScheduled||(this._pendingOldValue=t,this._isNotificationScheduled=!0),this._sync&&!S.isBatching?this._flushNotifications():S.schedule(this._notifyTask)}_flushNotifications(){if(!this._isNotificationScheduled)return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this._isNotificationScheduled=!1,this._functionSubscribers.forEachSafe(s=>s(t,e),s=>console.error(new a(h.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s))),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(new a(h.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,s)))}subscribe(e){if(typeof e!="function")throw new a(h.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(e)}peek(){return this._value}dispose(){this._functionSubscribers.clear(),this._objectSubscribers.clear(),this._value=void 0}subscriberCount(){return this._functionSubscribers.size+this._objectSubscribers.size}}function K(i,e={}){return new W(i,e.sync??!1)}const E=process.env.NODE_ENV!=="production",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: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,E&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const b=new Z;class z{constructor(e,t={}){if(typeof e!="function")throw new p(h.COMPUTED_MUST_BE_FUNCTION);if(this.id=M()&y,this.version=0,this.flags=0,this._lastSeenEpoch=-1,this._value=void 0,this._stateFlags=c.DIRTY|c.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:B,this._hasDefaultValue=this._defaultValue!==B,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._functionSubscribers=new F,this._objectSubscribers=new F,this._dependencies=f,this._subscriptions=new Map,this._recomputeJob=()=>{if(this._isDirty())try{this._recompute()}catch{}},this._notifyJob=()=>{this._functionSubscribers.forEachSafe(s=>s(),s=>console.error(s)),this._objectSubscribers.forEachSafe(s=>s.execute(),s=>console.error(s))},this._trackable=Object.assign(()=>this._markDirty(),{addDependency:s=>{}}),l.attachDebugInfo(this,"computed",this.id),l.enabled){const s=this;s.subscriberCount=()=>this._functionSubscribers.size+this._objectSubscribers.size,s.isDirty=()=>this._isDirty(),s.dependencies=this._dependencies,s.stateFlags=this._getFlagsAsString()}if(t.lazy===!1)try{this._recompute()}catch{}}get value(){if((this._stateFlags&(c.RESOLVED|c.DIRTY))===c.RESOLVED)return this._registerTracking(),this._value;const t=this._computeValue();return this._registerTracking(),t}subscribe(e){if(typeof e!="function")throw new p(h.COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION);return this._functionSubscribers.add(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()}dispose(){if(this._dependencies!==f){for(const e of this._dependencies){const t=this._subscriptions.get(e.id);t&&t(),this._subscriptions.delete(e.id)}b.release(this._dependencies)}this._dependencies=f,this._functionSubscribers.clear(),this._objectSubscribers.clear(),this._stateFlags=c.DIRTY|c.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID}_isDirty(){return(this._stateFlags&c.DIRTY)!==0}_setDirty(){this._stateFlags|=c.DIRTY}_clearDirty(){this._stateFlags&=-2}_isIdle(){return(this._stateFlags&c.IDLE)!==0}_setIdle(){this._stateFlags|=c.IDLE,this._stateFlags&=-29}_isPending(){return(this._stateFlags&c.PENDING)!==0}_setPending(){this._stateFlags|=c.PENDING,this._stateFlags&=-27}_isResolved(){return(this._stateFlags&c.RESOLVED)!==0}_setResolved(){this._stateFlags|=c.RESOLVED,this._stateFlags&=-87}_isRejected(){return(this._stateFlags&c.REJECTED)!==0}_setRejected(){this._stateFlags|=c.REJECTED|c.HAS_ERROR,this._stateFlags&=-15}_isRecomputing(){return(this._stateFlags&c.RECOMPUTING)!==0}_setRecomputing(e){const t=c.RECOMPUTING;this._stateFlags=this._stateFlags&~t|-Number(e)&t}_getAsyncState(){return this._isPending()?m.PENDING:this._isResolved()?m.RESOLVED:this._isRejected()?m.REJECTED:m.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._isPending()?this._handlePending():this._isRejected()?this._handleRejected():(this._isDirty()||this._isIdle())&&(this._recompute(),this._isPending())?this._handlePending():this._value}_recompute(){if(!this._isDirty()&&this._isResolved())return;this._setRecomputing(!0);const e=this._dependencies,t=b.acquire(),s=q();let n=0;const r=o=>{o._lastSeenEpoch!==s&&(o._lastSeenEpoch=s,n<t.length?t[n]=o:t.push(o),n++)},u=this._trackable.addDependency;this._trackable.addDependency=r;let _=!1;try{const o=g.run(this._trackable,this._fn);if(t.length=n,k(o)){this._syncDependencies(e,t,s),this._dependencies=t,_=!0,this._handleAsyncComputation(o),this._setRecomputing(!1);return}this._syncDependencies(e,t,s),this._dependencies=t,_=!0,this._handleSyncResult(o)}catch(o){t.length=n,this._syncDependencies(e,t,s),this._dependencies=t,_=!0,this._handleComputationError(o)}finally{this._trackable.addDependency=u,_?e!==f&&b.release(e):b.release(t)}}_syncDependencies(e,t,s){if(e!==f)for(let n=0;n<e.length;n++){const r=e[n];if(r&&r._lastSeenEpoch!==s){const u=this._subscriptions.get(r.id);u&&(u(),this._subscriptions.delete(r.id))}}for(let n=0;n<t.length;n++){const r=t[n];if(r&&!this._subscriptions.has(r.id)){l.checkCircular(r,this);const u=r.subscribe(()=>this._markDirty());this._subscriptions.set(r.id,u)}}}_handleSyncResult(e){const t=!this._isResolved()||!this._equal(this._value,e);this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),t&&this._notifySubscribers()}_handleAsyncComputation(e){this._setPending(),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){const t=!this._isResolved()||!this._equal(this._value,e);this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),t&&this._notifySubscribers()}_handleAsyncRejection(e){const t=I(e,p,h.COMPUTED_ASYNC_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError&&typeof this._onError=="function")try{this._onError(t)}catch(s){console.error(h.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}this._notifySubscribers()}_handleComputationError(e){const t=I(e,p,h.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError&&typeof this._onError=="function")try{this._onError(t)}catch(s){console.error(h.CALLBACK_ERROR_IN_ERROR_HANDLER,s)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new p(h.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){if(this._error?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw this._error}_markDirty(){this._isRecomputing()||this._isDirty()||(this._setDirty(),this._setIdle(),(this._functionSubscribers.hasSubscribers||this._objectSubscribers.hasSubscribers)&&S.schedule(this._recomputeJob))}_notifySubscribers(){!this._functionSubscribers.hasSubscribers&&!this._objectSubscribers.hasSubscribers||S.schedule(this._notifyJob)}_registerTracking(){const e=g.getCurrent();if(e)if(typeof e=="object"&&e!==null&&e.addDependency)e.addDependency(this);else if(typeof e=="function"){const t=e;t.addDependency?t.addDependency(this):this._functionSubscribers.add(e)}else e.execute&&this._objectSubscribers.add(e)}}Object.freeze(z.prototype);function ee(i,e={}){return new z(i,e)}class te{constructor(e,t={}){this.run=()=>{if(this.isDisposed)throw new d(h.EFFECT_MUST_BE_FUNCTION);this.execute()},this.dispose=()=>{if(!this.isDisposed&&(this._setDisposed(),this._safeCleanup(),this._dependencies!==f)){for(const s of this._dependencies){const n=this._subscriptions.get(s.id);n&&n(),this._subscriptions.delete(s.id)}b.release(this._dependencies),this._dependencies=f}},this.addDependency=s=>{if(this.isExecuting&&this._nextDeps){const n=s,r=this._currentEpoch;if(n._lastSeenEpoch===r)return;n._lastSeenEpoch=r,this._nextDeps.push(n),this._subscriptions.has(n.id)||this._subscribeTo(n)}},this.execute=()=>{if(this.isDisposed||this.isExecuting)return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup(),this._modifiedDeps.clear();const s=this._dependencies,n=b.acquire(),r=q();this._nextDeps=n,this._currentEpoch=r;let u=!1;try{const _=g.run(this,this._fn);this._syncDependencies(s,r),this._dependencies=n,u=!0,this._checkLoopWarnings(),k(_)?_.then(o=>{!this.isDisposed&&typeof o=="function"&&(this._cleanup=o)}).catch(o=>{console.error(I(o,d,h.EFFECT_EXECUTION_FAILED))}):this._cleanup=typeof _=="function"?_:null}catch(_){this._syncDependencies(s,r),this._dependencies=n,u=!0,console.error(I(_,d,h.EFFECT_EXECUTION_FAILED)),this._cleanup=null}finally{this._setExecuting(!1),this._nextDeps=null,u?s!==f&&b.release(s):b.release(n)}},this._id=M()&y,this._flags=0,this._currentEpoch=-1,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??R.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??R.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._cleanup=null,this._dependencies=f,this._subscriptions=new Map,this._nextDeps=null,this._modifiedDeps=new Set,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._history=P?[]:null,this._executionCount=0,l.attachDebugInfo(this,"effect",this._id)}_syncDependencies(e,t){if(e!==f)for(let s=0;s<e.length;s++){const n=e[s];if(n&&n._lastSeenEpoch!==t){const r=this._subscriptions.get(n.id);r&&(r(),this._subscriptions.delete(n.id))}}}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&this._modifiedDeps.add(e),this._sync?this.execute():S.schedule(this.execute)});this._subscriptions.set(e.id,t)}catch(t){console.error(I(t,d,h.EFFECT_EXECUTION_FAILED))}}get isDisposed(){return(this._flags&C.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this._flags&C.EXECUTING)!==0}_setDisposed(){this._flags|=C.DISPOSED}_setExecuting(e){const t=C.EXECUTING;this._flags=this._flags&~t|-Number(e)&t}_safeCleanup(){if(this._cleanup&&typeof this._cleanup=="function"){try{this._cleanup()}catch(e){console.error(I(e,d,h.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_checkInfiniteLoop(){if(this._lastFlushEpoch!==N&&(this._lastFlushEpoch=N,this._executionsInEpoch=0),this._executionsInEpoch++,this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),j()>R.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,this._history){const e=Date.now();this._history.push(e),this._history.length>R.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-1e3;let n=0;for(let r=t.length-1;r>=0&&!(t[r]<s);r--)n++;if(n>this._maxExecutions){const r=new d(`Effect executed ${n} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(r),P)throw r}}_throwInfiniteLoopError(e){const t=new d(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${L}`);throw this.dispose(),console.error(t),t}_checkLoopWarnings(){if(this._trackModifications&&l.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const s=e[t];s&&this._modifiedDeps.has(s)&&l.warn(!0,`Effect is reading a dependency (${l.getDebugName(s)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function se(i,e={}){if(typeof i!="function")throw new d(h.EFFECT_MUST_BE_FUNCTION);const t=new te(i,e);return t.execute(),t}function V(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function ie(i){if(l.enabled){const e=l.getDebugType(i);if(e)return e==="computed"}return V(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function ne(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}exports.AsyncState=m;exports.AtomError=a;exports.ComputedError=p;exports.DEBUG_CONFIG=x;exports.DEBUG_RUNTIME=l;exports.EffectError=d;exports.POOL_CONFIG=G;exports.SCHEDULER_CONFIG=R;exports.SchedulerError=D;exports.atom=K;exports.batch=$;exports.computed=ee;exports.effect=se;exports.isAtom=V;exports.isComputed=ie;exports.isEffect=ne;exports.scheduler=S;exports.untracked=Y;
2
2
  //# sourceMappingURL=index.cjs.map