@but212/atom-effect 0.30.0 → 0.30.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.
@@ -1,3 +1,3 @@
1
- (function(u,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(u=typeof globalThis<"u"?globalThis:u||self,h(u.AtomEffect={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var h={DISPOSED:1,IS_COMPUTED:2,DIRTY:256,RECOMPUTING:512,HAS_ERROR:1024,FORCE_COMPUTE:2048,IDLE:65536,PENDING:1<<17,RESOLVED:1<<18,REJECTED:1<<19,ATOM_SYNC:1<<24,ATOM_NOTIFICATION_SCHEDULED:1<<25,EFFECT_EXECUTING:1<<28},xt=Object.freeze({ASYNC_STATE:h.IDLE|h.PENDING|h.RESOLVED|h.REJECTED,COMPUTED_DIRTY_MASK:h.DIRTY|h.RECOMPUTING|h.FORCE_COMPUTE}),y=Object.freeze({IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"}),T=Object.freeze({DISPOSED:h.DISPOSED,EXECUTING:h.EFFECT_EXECUTING}),G=Object.freeze({DISPOSED:h.DISPOSED,IS_COMPUTED:h.IS_COMPUTED,DIRTY:h.DIRTY,IDLE:h.IDLE,PENDING:h.PENDING,RESOLVED:h.RESOLVED,REJECTED:h.REJECTED,RECOMPUTING:h.RECOMPUTING,HAS_ERROR:h.HAS_ERROR,FORCE_COMPUTE:h.FORCE_COMPUTE}),f=Object.freeze({DISPOSED:h.DISPOSED,SYNC:h.ATOM_SYNC,NOTIFICATION_SCHEDULED:h.ATOM_NOTIFICATION_SCHEDULED}),I=Object.freeze({MAX_EXECUTIONS_PER_SECOND:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10,BATCH_QUEUE_SHRINK_THRESHOLD:1e3}),z=1073741823,k=Object.freeze({WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3,LOOP_THRESHOLD:100}),ft=Object.freeze({MAX_PROMISE_ID:z}),R=Object.freeze({UNINITIALIZED:-1,MIN:1}),it=!1;try{it=!!(typeof globalThis<"u"&&globalThis.__ATOM_DEBUG__||typeof sessionStorage<"u"&&sessionStorage.getItem("__ATOM_DEBUG__")==="true")}catch{}var a=(typeof process<"u"&&process.env,typeof __DEV__<"u"&&!!__DEV__||it),nt=Object.freeze([]),C=class st extends Error{constructor(e,s=null,i=!0,n){super(e),this.cause=s,this.recoverable=i,this.code=n,this.name="AtomError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getChain(){if(this.cause===null||this.cause===void 0)return[this];const e=[this],s=new Set([this]);let i=this.cause;for(;i!=null;){const n=s.has(i);if(e.push(i),n)break;if(s.add(i),i instanceof st)i=i.cause;else if(i instanceof Error&&"cause"in i)i=i.cause;else break}return e}toJSON(e=new Set){if(e.has(this))return{name:this.name,message:"[Circular Reference]",recoverable:this.recoverable,code:this.code};e.add(this);let s=this.cause;return this.cause instanceof st?s=this.cause.toJSON(e):this.cause instanceof Error&&(s={name:this.cause.name,message:this.cause.message,stack:this.cause.stack,cause:this.cause.cause}),{name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,stack:this.stack,cause:s}}static format(e,s,i){return`${e} (${s}): ${i}`}},N=class extends C{constructor(...t){super(...t),this.name="ComputedError"}},S=class extends C{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="EffectError"}},F=class extends C{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="SchedulerError"}},c={COMPUTED_MUST_BE_FUNCTION:"Computed target must be a function",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation pending with no default value",COMPUTED_COMPUTATION_FAILED:"Computation execution failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computation execution failed",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected",COMPUTED_DISPOSED:"Attempted to access disposed computed",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber must be a function or Subscriber object",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Subscriber execution failed",EFFECT_MUST_BE_FUNCTION:"Effect target must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup failed",EFFECT_DISPOSED:"Attempted to run disposed effect",SCHEDULER_FLUSH_OVERFLOW:(t,e)=>`Maximum flush iterations (${t}) exceeded. ${e} jobs dropped. Possible infinite loop.`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Exception encountered in onError handler",EFFECT_FREQUENCY_LIMIT_EXCEEDED:"Effect executed too frequently within 1 second. Suspected infinite loop.",SCHEDULER_CALLBACK_MUST_BE_FUNCTION:"Scheduler callback must be a function",SCHEDULER_END_BATCH_WITHOUT_START:"endBatch() called without matching startBatch(). Ignoring.",BATCH_CALLBACK_MUST_BE_FUNCTION:"Batch callback must be a function"};function b(t,e,s){if(t instanceof C)return new e(C.format(t.name,s,t.message),t,t.recoverable,t.code);if(t instanceof Error){const i=t.name||t.constructor.name||"Error";return new e(C.format(i,s,t.message),t)}return new e(C.format("Unexpected error",s,String(t)),t)}var rt=Symbol("AtomEffect.DebugName"),Et=Symbol("AtomEffect.Id"),ot=Symbol("AtomEffect.Type"),X=Symbol("AtomEffect.NoDefaultValue"),dt="[Atom Effect]",pt=class{constructor(){this.enabled=!0,this.warnInfiniteLoop=k.WARN_INFINITE_LOOP,this._updateCounts=new Map,this._nodeRegistry=new Map,this._threshold=k.LOOP_THRESHOLD,this._cleanupScheduled=!1,this.warn=(t,e)=>{this.enabled&&t&&console.warn(`${dt} ${e}`)},this.registerNode=t=>{this._nodeRegistry.set(t.id,new WeakRef(t))},this.attachDebugInfo=(t,e,s,i)=>{this.enabled&&(Object.defineProperties(t,{[rt]:{value:i??`${e}_${s}`,configurable:!0},[Et]:{value:s,configurable:!0},[ot]:{value:e,configurable:!0}}),this.registerNode(t))},this.trackUpdate=(t,e)=>{if(!this.enabled||!this.warnInfiniteLoop)return;const s=this._updateCounts,i=(s.get(t)??0)+1;i>this._threshold?this.warn(!0,`Infinite loop detected for ${e??`dependency ${t}`}. Over ${this._threshold} updates in a single execution scope.`):s.set(t,i),this._cleanupScheduled||(this._cleanupScheduled=!0,Promise.resolve().then(()=>{this._updateCounts.clear(),this._cleanupScheduled=!1}))},this.dumpGraph=()=>{const t=[];for(const[e,s]of this._nodeRegistry){const i=s.deref();i?t.push({id:e,name:this.getDebugName(i),type:this.getDebugType(i),updateCount:this._updateCounts.get(e)??0}):(this._nodeRegistry.delete(e),this._updateCounts.delete(e))}return t},this.getDebugName=t=>{if(t)return t[rt]},this.getDebugType=t=>{if(t)return t[ot]}}},It={enabled:!1,warnInfiniteLoop:!1,warn:()=>{},registerNode:()=>{},attachDebugInfo:()=>{},trackUpdate:()=>{},dumpGraph:()=>[],getDebugName:()=>{},getDebugType:()=>{}},E=a?new pt:It,Ct=1,gt=()=>Ct++|0,ut=class{constructor(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._actualCount=0,this._overflow=null,this._freeIndices=null}_rawWrite(t,e){if(t<4)t===0?this._s0=e:t===1?this._s1=e:t===2?this._s2=e:this._s3=e;else{this._overflow===null&&(this._overflow=[]);const s=this._overflow,i=t-4;s[i]=e}}_rawAdd(t){if(this._s0===null)return this._s0=t,0;if(this._s1===null)return this._s1=t,1;if(this._s2===null)return this._s2=t,2;if(this._s3===null)return this._s3=t,3;this._overflow===null&&(this._overflow=[]);const e=this._overflow,s=this._freeIndices;if(s!==null&&s.length>0){const i=s.pop();return e[i]=t,i+4}return e.push(t),4+e.length-1}_rawSwap(t,e){if(t===e)return;const s=this.getAt(t),i=this.getAt(e);this._rawWrite(t,i),this._rawWrite(e,s)}get size(){return this._actualCount}get physicalSize(){return this._count}getAt(t){return t<4?t===0?this._s0:t===1?this._s1:t===2?this._s2:this._s3:this._overflow?.[t-4]??null}setAt(t,e){const s=this.getAt(t);s!==e&&(this._rawWrite(t,e),s===null?this._actualCount++:e===null&&this._actualCount--,e!==null&&t>=this._count?this._count=t+1:e===null&&this._shrinkPhysicalSizeFrom(t))}_shrinkPhysicalSizeFrom(t){if(t===this._count-1)for(this._count--;this._count>0&&this.getAt(this._count-1)==null;)this._count--}truncateFrom(t){t<=3&&(t<=0&&this._s0!==null&&(this._onItemRemoved(this._s0),this._s0=null,this._actualCount--),t<=1&&this._s1!==null&&(this._onItemRemoved(this._s1),this._s1=null,this._actualCount--),t<=2&&this._s2!==null&&(this._onItemRemoved(this._s2),this._s2=null,this._actualCount--),t<=3&&this._s3!==null&&(this._onItemRemoved(this._s3),this._s3=null,this._actualCount--));const e=this._overflow;if(e!==null){const s=t>4?t-4:0,i=e.length;for(let n=s;n<i;n++){const r=e[n];r!=null&&(this._onItemRemoved(r),e[n]=null,this._actualCount--)}t<=4?this._overflow=null:e.length=t-4}this._count=t,this._actualCount<0&&(this._actualCount=0),this._freeIndices=null}_onItemRemoved(t){}add(t){const e=this._rawAdd(t);return e>=this._count&&(this._count=e+1),this._actualCount++,e}remove(t){let e=-1;if(this._s0===t)e=0;else if(this._s1===t)e=1;else if(this._s2===t)e=2;else if(this._s3===t)e=3;else{const s=this._overflow;s!==null&&(e=s.indexOf(t),e!==-1&&(e+=4))}return e!==-1?(this._rawWrite(e,null),this._shrinkPhysicalSizeFrom(e),this._actualCount--,e>=4&&(this._freeIndices===null&&(this._freeIndices=[]),this._freeIndices.push(e-4)),!0):!1}has(t){if(this._actualCount===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;const e=this._overflow;return e!==null?e.indexOf(t)!==-1:!1}forEach(t){const e=this._actualCount;if(e===0)return;if(e===this._count){this._s0!=null&&t(this._s0),this._s1!=null&&t(this._s1),this._s2!=null&&t(this._s2),this._s3!=null&&t(this._s3);const n=this._overflow;if(n!==null)for(let r=0,o=n.length;r<o;r++){const l=n[r];l!=null&&t(l)}return}let s=0;const i=this._count;for(let n=0;n<i;n++){const r=this.getAt(n);if(r!=null&&(t(r),++s>=e))break}}compact(){if(this._actualCount===this._count)return;let t=0;const e=this._count;for(let s=0;s<e;s++){const i=this.getAt(s);i!=null&&(s!==t&&(this._rawWrite(t,i),this._rawWrite(s,null)),t++)}this._count=this._actualCount,this._overflow!==null&&(t<=4?this._overflow=null:this._overflow.length=t-4),this._freeIndices=null}clear(){this._s0=this._s1=this._s2=this._s3=null,this._count=0,this._actualCount=0,this._overflow=null,this._freeIndices=null}dispose(){this.clear()}},ht=class extends ut{constructor(...t){super(...t),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1}prepareTracking(){this.hasComputeds=!1}_onItemRemoved(t){t.unsub?.()}setAt(t,e){const s=this.getAt(t);super.setAt(t,e),this._map!==null&&(s?.unsub&&this._map.delete(s.node),e?.unsub&&this._map.set(e.node,t))}claimExisting(t,e){const s=this._count;if(s<=e)return!1;const i=this.getAt(e);if(i&&i.node===t&&i.unsub)return i.version=t.version,!0;if(this._map!==null||s-e>this._SCAN_THRESHOLD)return this._claimViaMap(t,e);for(let n=e+1;n<s;n++){const r=this.getAt(n);if(r&&r.node===t&&r.unsub)return r.version=t.version,this._rawSwap(n,e),!0}return!1}_claimViaMap(t,e){this._map===null&&(this._map=this._initMap());const s=this._map,i=s.get(t);if(i===void 0||i<e)return!1;const n=this.getAt(i);if(n==null||!n.unsub)return!1;if(n.version=t.version,i!==e){const r=this.getAt(e);this._rawSwap(i,e),s.set(t,e),r?.unsub&&s.set(r.node,i)}return!0}_initMap(){const t=new Map;for(let e=0;e<this._count;e++){const s=this.getAt(e);s?.unsub&&t.set(s.node,e)}return t}insertNew(t,e){const s=this.getAt(t);if(s!==null){const i=this._rawAdd(s);i>=this._count&&(this._count=i+1),this._map!==null&&s.unsub&&this._map.set(s.node,i)}this._rawWrite(t,e),t>=this._count&&(this._count=t+1),this._actualCount++,this._map!==null&&e.unsub&&this._map.set(e.node,t)}add(t){const e=super.add(t);return this._map!==null&&t.unsub&&this._map.set(t.node,e),e}remove(t){throw new Error("remove() prohibited")}compact(){}truncateFrom(t){super.truncateFrom(t),this._map!==null&&(this._map=null)}disposeAll(){this.truncateFrom(0),this.hasComputeds=!1}},w=Symbol.for("atom-effect/brand"),g={Atom:1,Writable:2,Computed:4,Effect:8};function Q(t,e){if(!t)return!1;const s=typeof t;return(s==="object"||s==="function")&&!!((t[w]??0)&e)}function Dt(t){return Q(t,g.Atom)}function St(t){return Q(t,g.Computed)}function mt(t){return Q(t,g.Effect)}function Y(t){if(t instanceof Promise)return!0;if(!t)return!1;const e=typeof t;return(e==="object"||e==="function")&&typeof t.then=="function"}var V=class{constructor(t,e,s=void 0){this.node=t,this.version=e,this.unsub=s}},Tt=class{constructor(t=void 0,e=void 0){this.fn=t,this.sub=e}notify(t,e){U(()=>{const s=this.fn;s!==void 0&&s(t,e);const i=this.sub;i!==void 0&&i.execute()})}},vt=class{constructor(){this.current=null}run(t,e){if(this.current===t)return e();const s=this.current;this.current=t;try{const i=e();return a&&E.warn(Y(i),'Detected Promise returned within tracking context. Dependencies accessed after "await" will NOT be tracked. Consider using synchronous tracking before the async boundary.'),i}finally{this.current=s}}},_=new vt;function U(t){const e=_,s=e.current;if(s===null)return t();e.current=null;try{return t()}finally{e.current=s}}var j=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=R.UNINITIALIZED,this._nextEpoch=void 0,this._notifying=0,this._hotIndex=-1,this._slots=null,this._deps=null,this.id=gt()&z}get isDisposed(){return(this.flags&G.DISPOSED)!==0}get isComputed(){return(this.flags&G.IS_COMPUTED)!==0}get hasError(){return!1}subscribe(t){const e=typeof t=="function";if(!e&&(!t||typeof t.execute!="function"))throw b(new TypeError("Invalid subscriber"),C,c.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let s=this._slots;s||(s=new ut,this._slots=s);let i=!1;if(s._s0!=null&&(e?s._s0.fn===t:s._s0.sub===t))i=!0;else if(s._s1!=null&&(e?s._s1.fn===t:s._s1.sub===t))i=!0;else if(s._s2!=null&&(e?s._s2.fn===t:s._s2.sub===t))i=!0;else if(s._s3!=null&&(e?s._s3.fn===t:s._s3.sub===t))i=!0;else{const r=s._overflow;if(r!=null)for(let o=0,l=r.length;o<l;o++){const p=r[o];if(p!=null&&(e?p.fn===t:p.sub===t)){i=!0;break}}}if(i)return a&&console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`),()=>{};const n=new Tt(e?t:void 0,e?void 0:t);return s.add(n),()=>this._unsubscribe(n)}_unsubscribe(t){const e=this._slots;e&&(e.remove(t),this._notifying===0&&e.compact())}subscriberCount(){const t=this._slots;return t===null?0:t.size}_notifySubscribers(t,e){const s=this._slots;if(!(s===null||s.size===0)){this._notifying++;try{let i=s._s0;if(i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s1,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s2,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s3,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}const n=s._overflow;if(n!=null)for(let r=0,o=n.length;r<o;r++){const l=n[r];if(l!=null)try{l.notify(t,e)}catch(p){this._logNotifyError(p)}}}finally{--this._notifying===0&&s.compact()}}}_logNotifyError(t){console.error(b(t,C,c.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}_isDirty(){const t=this._deps;if(t===null||t.size===0)return!1;const e=this._hotIndex;if(e!==-1){const s=t.getAt(e);if(s!=null&&s.node.version!==s.version)return!0}return this._deepDirtyCheck()}},W=0;function q(){const t=W+1&z;return W=t===0?1:t,W}function $(t){const e=t+1&z;return e===0?1:e}var K=0,B=!1,ct=0;function Ot(){return ct}function lt(){return B?(a&&console.warn("startFlush() called during flush - ignored"),!1):(B=!0,ct=q(),K=0,!0)}function _t(){B=!1}function Nt(){if(!B)return 0;const t=++K;if(t<=I.MAX_EXECUTIONS_PER_FLUSH)return t;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${I.MAX_EXECUTIONS_PER_FLUSH}`)}var bt=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=I.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get queueSize(){return this._size+this._batchQueueSize}get isBatching(){return this._batchDepth>0}schedule(t){if(a&&typeof t!="function"&&(!t||typeof t.execute!="function"))throw new F(c.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);const e=this._epoch;if(t._nextEpoch===e)return;if(t._nextEpoch=e,this._batchDepth>0||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}const s=this._queueBuffer[this._bufferIndex];s[this._size++]=t,this._isProcessing||this._flush()}_flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0&&this._batchQueueSize===0)return;const t=lt();this._drainQueue(),t&&_t()}finally{this._isProcessing=!1}}_flushSync(){if(this._size===0&&this._batchQueueSize===0)return;const t=this._isFlushingSync;this._isFlushingSync=!0;const e=lt();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=t,e&&_t()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;this._epoch=this._epoch+1|0;const e=this._epoch,s=this._batchQueue,i=this._queueBuffer[this._bufferIndex];let n=this._size;for(let r=0;r<t;r++){const o=s[r];o._nextEpoch!==e&&(o._nextEpoch=e,i[n++]=o),s[r]=void 0}this._size=n,this._batchQueueSize=0,s.length>I.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let t=0;for(;this._size>0||this._batchQueueSize>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._batchQueueSize>0&&this._mergeBatchQueue(),this._size>0&&this._processQueue()}}_processQueue(){const t=this._bufferIndex,e=this._queueBuffer[t],s=this._size;this._bufferIndex=t^1,this._size=0,this._epoch=this._epoch+1|0;for(let i=0;i<s;i++){const n=e[i];e[i]=void 0;try{typeof n=="function"?n():n.execute()}catch(r){console.error(new F("Error occurred during scheduler execution",r))}}}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;console.error(new F(c.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[0].length=0,this._queueBuffer[1].length=0,this._batchQueueSize=0,this._batchQueue.length=0;const e=this.onOverflow;if(e)try{e(t)}catch{}}startBatch(){this._batchDepth++}endBatch(){if(this._batchDepth===0){a&&console.warn(c.SCHEDULER_END_BATCH_WITHOUT_START);return}--this._batchDepth===0&&(this._isFlushingSync||this._flushSync())}setMaxFlushIterations(t){if(t<I.MIN_FLUSH_ITERATIONS)throw new F(`Max iterations must be at least ${I.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},v=new bt;function At(t){if(a&&typeof t!="function")throw new TypeError(c.BATCH_CALLBACK_MUST_BE_FUNCTION);v.startBatch();try{return t()}finally{v.endBatch()}}var yt=class extends j{constructor(t,e){super(),this[w]=g.Atom|g.Writable,this._value=t,this._equal=e.equal??Object.is,e.sync&&(this.flags|=f.SYNC),E.attachDebugInfo(this,"atom",this.id,e.name)}get isNotificationScheduled(){return(this.flags&f.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&f.SYNC)!==0}get value(){const t=_.current;return t?.addDependency(this),this._value}set value(t){const e=this._value;if(this._equal(e,t)||(this._value=t,this.version=$(this.version),E.trackUpdate(this.id,E.getDebugName(this)),(this.flags&f.NOTIFICATION_SCHEDULED)!==0))return;const s=this._slots;s==null||s.size===0||(this._pendingOldValue=e,this.flags|=f.NOTIFICATION_SCHEDULED,(this.flags&f.SYNC)!==0&&!v.isBatching?this._notifying===0&&this._flushNotifications():v.schedule(this))}execute(){this._flushNotifications()}_flushNotifications(){const t=f.NOTIFICATION_SCHEDULED,e=f.DISPOSED,s=f.SYNC;for(;(this.flags&(t|e))===t;){const i=this._pendingOldValue;if(this._pendingOldValue=void 0,this.flags&=~t,this._equal(this._value,i)||this._notifySubscribers(this._value,i),(this.flags&s)===0||v.isBatching)break}}peek(){return this._value}dispose(){const t=this.flags;(t&f.DISPOSED)===0&&(this._slots?.clear(),this.flags=t|f.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._equal=Object.is)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function Rt(t,e={}){return new yt(t,e)}var{IDLE:m,DIRTY:d,PENDING:A,RESOLVED:D,REJECTED:O,HAS_ERROR:H,RECOMPUTING:L,DISPOSED:J,IS_COMPUTED:P,FORCE_COMPUTE:Z}=G,Ft=class extends j{constructor(t,e={}){if(typeof t!="function")throw new N(c.COMPUTED_MUST_BE_FUNCTION);if(super(),this[w]=g.Atom|g.Computed,this._error=null,this._promiseId=0,this._deps=new ht,this._trackEpoch=R.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=P|d|m,this._equal=e.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in e?e.defaultValue:X,this._onError=e.onError??null,E.attachDebugInfo(this,"computed",this.id,e.name),e.lazy===!1)try{this._recompute()}catch{}}get isDirty(){return(this.flags&d)!==0}get isRejected(){return(this.flags&O)!==0}get isRecomputing(){return(this.flags&L)!==0}get _hasErrorInternal(){return(this.flags&H)!==0}_track(){_.current?.addDependency(this)}get value(){const t=_.current;t?.addDependency(this);let e=this.flags;if((e&(D|d|m))===D)return this._value;if((e&J)!==0)throw new N(c.COMPUTED_DISPOSED);if((e&L)!==0){const n=this._defaultValue;if(n!==X)return n;throw new N(c.COMPUTED_CIRCULAR_DEPENDENCY)}if((e&(d|m))!==0){const n=this._deps;if((e&m)===0&&(e&Z)===0&&n.size>0&&!this._isDirty()?e=this.flags&=~d:(this._recompute(),e=this.flags),(e&D)!==0)return this._value}const s=this._defaultValue,i=s!==X;if((e&A)!==0){if(i)return s;throw new N(c.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if((e&O)!==0){if(i)return s;throw this._error}return this._value}peek(){return this._value}get state(){const t=_.current;t?.addDependency(this);const e=this.flags;return(e&D)!==0?y.RESOLVED:(e&A)!==0?y.PENDING:(e&O)!==0?y.REJECTED:y.IDLE}get hasError(){const t=_.current;if(t?.addDependency(this),(this.flags&(O|H))!==0)return!0;const e=this._deps;return e.hasComputeds?U(()=>{const s=e.size;for(let i=0;i<s;i++)if(e.getAt(i)?.node.hasError)return!0;return!1}):!1}get isValid(){return!this.hasError}get errors(){const t=_.current;t?.addDependency(this);const e=this._error,s=this._deps;if(!s.hasComputeds)return e==null?nt:Object.freeze([e]);const i=[];return e!=null&&i.push(e),U(()=>{const n=s.size;for(let r=0;r<n;r++){const o=s.getAt(r)?.node;o!=null&&(o.flags&P)!==0&&this._accumulateErrors(o,i)}}),i.length===0?nt:Object.freeze(i)}_accumulateErrors(t,e){const s=t._error;s!=null&&!e.includes(s)&&e.push(s);const i=t._deps;if(!i.hasComputeds)return;const n=i.size;for(let r=0;r<n;r++){const o=i.getAt(r)?.node;o!=null&&(o.flags&P)!==0&&this._accumulateErrors(o,e)}}get lastError(){const t=_.current;return t?.addDependency(this),this._error}get isPending(){const t=_.current;return t?.addDependency(this),(this.flags&A)!==0}get isResolved(){const t=_.current;return t?.addDependency(this),(this.flags&D)!==0}invalidate(){this.flags|=Z,this._markDirty()}dispose(){(this.flags&J)===0&&(this._deps.disposeAll(),this._slots!=null&&this._slots.clear(),this.flags=J|d|m,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){const e=this._trackEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,i=this._deps,n=i.getAt(s);if(n!=null&&n.node===t)n.version=t.version;else if(!i.claimExisting(t,s)){const r=new V(t,t.version,t.subscribe(this));i.insertNew(s,r)}(t.flags&P)!==0&&(i.hasComputeds=!0)}_recompute(){if(this.isRecomputing)return;this.flags=(this.flags|L)&~Z,this._trackEpoch=q(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const e=_.run(this,this._fn);this._deps.truncateFrom(this._trackCount),t=!0,Y(e)?this._handleAsyncComputation(e):this._finalizeResolution(e)}catch(e){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch(s){a&&console.warn("[atom-effect] _commitDeps failed during error recovery:",s)}this._handleError(e,c.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=R.UNINITIALIZED,this._trackCount=0,this.flags&=~L}}_handleAsyncComputation(t){this.flags=(this.flags|A)&~(m|d|D|O),this._notifySubscribers(void 0,void 0),this._promiseId=(this._promiseId+1)%ft.MAX_PROMISE_ID;const e=this._promiseId;t.then(s=>{if(e===this._promiseId){if(this._isDirty())return this._markDirty();this._finalizeResolution(s),this._notifySubscribers(s,void 0)}},s=>e===this._promiseId&&this._handleError(s,c.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,e,s=!1){const i=b(t,N,e);if((!this.isRejected||this._error!==i)&&(this.version=$(this.version)),this._error=i,this.flags=this.flags&~(m|d|A|D)|O|H,this._onError)try{this._onError(i)}catch(n){console.error(c.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(this._notifySubscribers(void 0,void 0),s)throw i}_finalizeResolution(t){const e=this.flags;((e&D)===0||!this._equal(this._value,t))&&(this.version=$(this.version)),this._value=t,this._error=null,this.flags=(e|D)&~(m|d|A|O|H)}execute(){this._markDirty()}_markDirty(){const t=this.flags;(t&(L|d))===0&&(this.flags=t|d,E.trackUpdate(this.id,E.getDebugName(this)),this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){const t=this._deps;return U(()=>{const e=t.size;for(let s=0;s<e;s++){const i=t.getAt(s);if(i==null)continue;const n=i.node;if((n.flags&P)!==0)try{n.value}catch{a&&console.warn(`[atom-effect] Dependency #${n.id} threw during dirty check`)}if(n.version!==i.version)return this._hotIndex=s,!0}return this._hotIndex=-1,!1})}};function wt(t,e={}){return new Ft(t,e)}var Ut=class extends j{constructor(t,e={}){super(),this[w]=g.Effect,this._cleanup=null,this._deps=new ht,this._currentEpoch=R.UNINITIALIZED,this._lastFlushEpoch=R.UNINITIALIZED,this._fn=t,this._onError=e.onError??null,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??I.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??I.MAX_EXECUTIONS_PER_EFFECT,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._trackCount=0,this._sync?this._notifyCallback=()=>this.execute():this._notifyCallback=()=>v.schedule(this),E.attachDebugInfo(this,"effect",this.id,e.name)}run(){if(this.isDisposed)throw new S(c.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=T.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if((this.flags&T.EXECUTING)===0)return;const e=this._currentEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,i=this._deps;let n;switch(s){case 0:n=i._s0;break;case 1:n=i._s1;break;case 2:n=i._s2;break;case 3:n=i._s3;break;default:n=i.getAt(s)}n!=null&&n.node===t?n.version=t.version:i.claimExisting(t,s)||this._insertNewDependency(t,s),t.isComputed&&(i.hasComputeds=!0)}_insertNewDependency(t,e){let s;try{const i=t.subscribe(this._notifyCallback);s=new V(t,t.version,i)}catch(i){const n=b(i,S,c.EFFECT_EXECUTION_FAILED);if(console.error(n),this._onError)try{this._onError(n)}catch{}s=new V(t,t.version,void 0)}this._deps.insertNew(e,s)}execute(t=!1){const e=this.flags;if((e&(T.DISPOSED|T.EXECUTING))!==0)return;const s=this._deps;if(!t&&s.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),E.trackUpdate(this.id,E.getDebugName(this)),this.flags=e|T.EXECUTING,this._execCleanup(),this._currentEpoch=q(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let i=!1;try{const n=_.run(this,this._fn);s.truncateFrom(this._trackCount),i=!0,Y(n)?this._handleAsyncResult(n):this._cleanup=typeof n=="function"?n:null}catch(n){if(!i)try{s.truncateFrom(this._trackCount)}catch(r){a&&console.warn("[atom-effect] _commitDeps failed during error recovery:",r)}this._handleExecutionError(n),this._cleanup=null}finally{this.flags&=~T.EXECUTING}}_handleAsyncResult(t){const e=++this._execId;t.then(s=>{if(e!==this._execId||this.isDisposed){if(typeof s=="function")try{s()}catch(i){this._handleExecutionError(i,c.EFFECT_CLEANUP_FAILED)}return}typeof s=="function"&&(this._cleanup=s)},s=>e===this._execId&&this._handleExecutionError(s))}_deepDirtyCheck(){const t=_.current;_.current=null;const e=this._deps;try{const s=e.size;for(let i=0;i<s;i++){const n=e.getAt(i);if(n==null)continue;const r=n.node;if(r.isComputed&&this._tryPullComputed(r),r.version!==n.version)return this._hotIndex=i,!0}return!1}finally{_.current=t}}_tryPullComputed(t){try{t.value}catch{a&&console.warn(`[atom-effect] Dependency #${t.id} threw during dirty check`)}}_execCleanup(){const t=this._cleanup;if(t!=null){this._cleanup=null;try{t()}catch(e){this._handleExecutionError(e,c.EFFECT_CLEANUP_FAILED)}}}_checkInfiniteLoops(){const t=Ot();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),Nt()>I.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,a&&this._checkFrequencyLimit()}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=k.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const e=new S(c.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(e),e}}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&T.EXECUTING)!==0}_throwInfiniteLoopError(t){const e=new S(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${K}`);throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=c.EFFECT_EXECUTION_FAILED){const s=b(t,S,e);if(console.error(s),this._onError)try{this._onError(s)}catch(i){console.error(b(i,S,c.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function Lt(t,e={}){if(typeof t!="function")throw new S(c.EFFECT_MUST_BE_FUNCTION);const s=new Ut(t,e);return s.execute(),s}function tt(t,e,s,i){if(s===e.length)return i;const n=e[s],r=t!=null&&typeof t=="object"?t:{},o=r[n],l=tt(o,e,s+1,i);if(Object.is(o,l))return t;if(Array.isArray(r)){const p=r.slice(),x=Number.parseInt(n,10);return Number.isNaN(x)?p[n]=l:p[x]=l,p}return{...r,[n]:l}}function M(t,e){let s=t;const i=e.length;for(let n=0;n<i;n++){if(s==null)return;s=s[e[n]]}return s}function et(t,e){const s=e.includes(".")?e.split("."):[e],i=new Set,n=()=>{i.forEach(r=>r()),i.clear()};return{get value(){return M(t.value,s)},set value(r){const o=t.peek(),l=tt(o,s,0,r);l!==o&&(t.value=l)},peek:()=>M(t.peek(),s),subscribe(r){const o=t.subscribe((l,p)=>{const x=M(l,s),at=M(p,s);Object.is(x,at)||r(x,at)});return i.add(o),()=>{o(),i.delete(o)}},subscriberCount:()=>i.size,dispose:n,[Symbol.dispose]:n,[w]:g.Atom|g.Writable}}var Pt=(t,e)=>et(t,e),Mt=t=>e=>et(t,e);u.AsyncState=y,u.AtomError=C,u.ComputedError=N,u.DEBUG_CONFIG=k,u.EffectError=S,u.SCHEDULER_CONFIG=I,u.SchedulerError=F,u.atom=Rt,u.atomLens=et,u.batch=At,u.composeLens=Pt,u.computed=wt,u.effect=Lt,u.getPathValue=M,u.globalScheduler=v,u.isAtom=Dt,u.isComputed=St,u.isEffect=mt,u.lensFor=Mt,u.runtimeDebug=E,u.setDeepValue=tt,u.untracked=U});
1
+ (function(u,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(u=typeof globalThis<"u"?globalThis:u||self,h(u.AtomEffect={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var h={DISPOSED:1,IS_COMPUTED:2,DIRTY:256,RECOMPUTING:512,HAS_ERROR:1024,FORCE_COMPUTE:2048,IDLE:65536,PENDING:1<<17,RESOLVED:1<<18,REJECTED:1<<19,ATOM_SYNC:1<<24,ATOM_NOTIFICATION_SCHEDULED:1<<25,EFFECT_EXECUTING:1<<28},kt=Object.freeze({ASYNC_STATE:h.IDLE|h.PENDING|h.RESOLVED|h.REJECTED,COMPUTED_DIRTY_MASK:h.DIRTY|h.RECOMPUTING|h.FORCE_COMPUTE}),R=Object.freeze({IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"}),T=Object.freeze({DISPOSED:h.DISPOSED,EXECUTING:h.EFFECT_EXECUTING}),G=Object.freeze({DISPOSED:h.DISPOSED,IS_COMPUTED:h.IS_COMPUTED,DIRTY:h.DIRTY,IDLE:h.IDLE,PENDING:h.PENDING,RESOLVED:h.RESOLVED,REJECTED:h.REJECTED,RECOMPUTING:h.RECOMPUTING,HAS_ERROR:h.HAS_ERROR,FORCE_COMPUTE:h.FORCE_COMPUTE}),f=Object.freeze({DISPOSED:h.DISPOSED,SYNC:h.ATOM_SYNC,NOTIFICATION_SCHEDULED:h.ATOM_NOTIFICATION_SCHEDULED}),I=Object.freeze({MAX_EXECUTIONS_PER_SECOND:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10,BATCH_QUEUE_SHRINK_THRESHOLD:1e3}),k=1073741823,z=Object.freeze({WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3,LOOP_THRESHOLD:100}),Et=Object.freeze({MAX_PROMISE_ID:k}),F=Object.freeze({UNINITIALIZED:-1,MIN:1}),it=!1;try{it=!!(typeof globalThis<"u"&&globalThis.__ATOM_DEBUG__||typeof sessionStorage<"u"&&sessionStorage.getItem("__ATOM_DEBUG__")==="true")}catch{}var a=(typeof process<"u"&&process.env,typeof __DEV__<"u"&&!!__DEV__||it),nt=Object.freeze([]),C=class st extends Error{constructor(e,s=null,i=!0,n){super(e),this.cause=s,this.recoverable=i,this.code=n,this.name="AtomError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getChain(){if(this.cause===null||this.cause===void 0)return[this];const e=[this],s=new Set([this]);let i=this.cause;for(;i!=null;){const n=s.has(i);if(e.push(i),n)break;if(s.add(i),i instanceof st)i=i.cause;else if(i instanceof Error&&"cause"in i)i=i.cause;else break}return e}toJSON(e=new Set){if(e.has(this))return{name:this.name,message:"[Circular Reference]",recoverable:this.recoverable,code:this.code};e.add(this);let s=this.cause;return this.cause instanceof st?s=this.cause.toJSON(e):this.cause instanceof Error&&(s={name:this.cause.name,message:this.cause.message,stack:this.cause.stack,cause:this.cause.cause}),{name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,stack:this.stack,cause:s}}static format(e,s,i){return`${e} (${s}): ${i}`}},N=class extends C{constructor(...t){super(...t),this.name="ComputedError"}},S=class extends C{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="EffectError"}},w=class extends C{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="SchedulerError"}},c={COMPUTED_MUST_BE_FUNCTION:"Computed target must be a function",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation pending with no default value",COMPUTED_COMPUTATION_FAILED:"Computation execution failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computation execution failed",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected",COMPUTED_DISPOSED:"Attempted to access disposed computed",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber must be a function or Subscriber object",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Subscriber execution failed",EFFECT_MUST_BE_FUNCTION:"Effect target must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup failed",EFFECT_DISPOSED:"Attempted to run disposed effect",SCHEDULER_FLUSH_OVERFLOW:(t,e)=>`Maximum flush iterations (${t}) exceeded. ${e} jobs dropped. Possible infinite loop.`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Exception encountered in onError handler",EFFECT_FREQUENCY_LIMIT_EXCEEDED:"Effect executed too frequently within 1 second. Suspected infinite loop.",SCHEDULER_CALLBACK_MUST_BE_FUNCTION:"Scheduler callback must be a function",SCHEDULER_END_BATCH_WITHOUT_START:"endBatch() called without matching startBatch(). Ignoring.",BATCH_CALLBACK_MUST_BE_FUNCTION:"Batch callback must be a function"};function b(t,e,s){if(t instanceof C)return new e(C.format(t.name,s,t.message),t,t.recoverable,t.code);if(t instanceof Error){const i=t.name||t.constructor.name||"Error";return new e(C.format(i,s,t.message),t)}return new e(C.format("Unexpected error",s,String(t)),t)}var rt=Symbol("AtomEffect.DebugName"),dt=Symbol("AtomEffect.Id"),ot=Symbol("AtomEffect.Type"),X=Symbol("AtomEffect.NoDefaultValue"),pt="[Atom Effect]",It=class{constructor(){this.enabled=!0,this.warnInfiniteLoop=z.WARN_INFINITE_LOOP,this._updateCounts=new Map,this._nodeRegistry=new Map,this._threshold=z.LOOP_THRESHOLD,this._cleanupScheduled=!1,this.warn=(t,e)=>{this.enabled&&t&&console.warn(`${pt} ${e}`)},this.registerNode=t=>{this._nodeRegistry.set(t.id,new WeakRef(t))},this.attachDebugInfo=(t,e,s,i)=>{this.enabled&&(Object.defineProperties(t,{[rt]:{value:i??`${e}_${s}`,configurable:!0},[dt]:{value:s,configurable:!0},[ot]:{value:e,configurable:!0}}),this.registerNode(t))},this.trackUpdate=(t,e)=>{if(!this.enabled||!this.warnInfiniteLoop)return;const s=this._updateCounts,i=(s.get(t)??0)+1;i>this._threshold?this.warn(!0,`Infinite loop detected for ${e??`dependency ${t}`}. Over ${this._threshold} updates in a single execution scope.`):s.set(t,i),this._cleanupScheduled||(this._cleanupScheduled=!0,Promise.resolve().then(()=>{this._updateCounts.clear(),this._cleanupScheduled=!1}))},this.dumpGraph=()=>{const t=[];for(const[e,s]of this._nodeRegistry){const i=s.deref();i?t.push({id:e,name:this.getDebugName(i),type:this.getDebugType(i),updateCount:this._updateCounts.get(e)??0}):(this._nodeRegistry.delete(e),this._updateCounts.delete(e))}return t},this.getDebugName=t=>{if(t)return t[rt]},this.getDebugType=t=>{if(t)return t[ot]}}},Ct={enabled:!1,warnInfiniteLoop:!1,warn:()=>{},registerNode:()=>{},attachDebugInfo:()=>{},trackUpdate:()=>{},dumpGraph:()=>[],getDebugName:()=>{},getDebugType:()=>{}},E=a?new It:Ct,gt=1,Dt=()=>gt++|0,ut=class{constructor(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._actualCount=0,this._overflow=null,this._freeIndices=null}_rawWrite(t,e){if(t<4)t===0?this._s0=e:t===1?this._s1=e:t===2?this._s2=e:this._s3=e;else{this._overflow===null&&(this._overflow=[]);const s=this._overflow,i=t-4;s[i]=e}}_rawAdd(t){if(this._s0===null)return this._s0=t,0;if(this._s1===null)return this._s1=t,1;if(this._s2===null)return this._s2=t,2;if(this._s3===null)return this._s3=t,3;this._overflow===null&&(this._overflow=[]);const e=this._overflow,s=this._freeIndices;if(s!==null&&s.length>0){const i=s.pop();return e[i]=t,i+4}return e.push(t),4+e.length-1}_rawSwap(t,e){if(t===e)return;const s=this.getAt(t),i=this.getAt(e);this._rawWrite(t,i),this._rawWrite(e,s)}get size(){return this._actualCount}get physicalSize(){return this._count}getAt(t){return t<4?t===0?this._s0:t===1?this._s1:t===2?this._s2:this._s3:this._overflow?.[t-4]??null}setAt(t,e){const s=this.getAt(t);s!==e&&(this._rawWrite(t,e),s===null?this._actualCount++:e===null&&this._actualCount--,e!==null&&t>=this._count?this._count=t+1:e===null&&this._shrinkPhysicalSizeFrom(t))}_shrinkPhysicalSizeFrom(t){if(t===this._count-1)for(this._count--;this._count>0&&this.getAt(this._count-1)==null;)this._count--}truncateFrom(t){t<=3&&(t<=0&&this._s0!==null&&(this._onItemRemoved(this._s0),this._s0=null,this._actualCount--),t<=1&&this._s1!==null&&(this._onItemRemoved(this._s1),this._s1=null,this._actualCount--),t<=2&&this._s2!==null&&(this._onItemRemoved(this._s2),this._s2=null,this._actualCount--),t<=3&&this._s3!==null&&(this._onItemRemoved(this._s3),this._s3=null,this._actualCount--));const e=this._overflow;if(e!==null){const s=t>4?t-4:0,i=e.length;for(let n=s;n<i;n++){const r=e[n];r!=null&&(this._onItemRemoved(r),e[n]=null,this._actualCount--)}t<=4?this._overflow=null:e.length=t-4}this._count=t,this._actualCount<0&&(this._actualCount=0),this._freeIndices=null}_onItemRemoved(t){}add(t){const e=this._rawAdd(t);return e>=this._count&&(this._count=e+1),this._actualCount++,e}remove(t){let e=-1;if(this._s0===t)e=0;else if(this._s1===t)e=1;else if(this._s2===t)e=2;else if(this._s3===t)e=3;else{const s=this._overflow;s!==null&&(e=s.indexOf(t),e!==-1&&(e+=4))}return e!==-1?(this._rawWrite(e,null),this._shrinkPhysicalSizeFrom(e),this._actualCount--,e>=4&&(this._freeIndices===null&&(this._freeIndices=[]),this._freeIndices.push(e-4)),!0):!1}has(t){if(this._actualCount===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;const e=this._overflow;return e!==null?e.indexOf(t)!==-1:!1}forEach(t){const e=this._actualCount;if(e===0)return;if(e===this._count){this._s0!=null&&t(this._s0),this._s1!=null&&t(this._s1),this._s2!=null&&t(this._s2),this._s3!=null&&t(this._s3);const n=this._overflow;if(n!==null)for(let r=0,o=n.length;r<o;r++){const l=n[r];l!=null&&t(l)}return}let s=0;const i=this._count;for(let n=0;n<i;n++){const r=this.getAt(n);if(r!=null&&(t(r),++s>=e))break}}compact(){if(this._actualCount===this._count)return;let t=0;const e=this._count;for(let s=0;s<e;s++){const i=this.getAt(s);i!=null&&(s!==t&&(this._rawWrite(t,i),this._rawWrite(s,null)),t++)}this._count=this._actualCount,this._overflow!==null&&(t<=4?this._overflow=null:this._overflow.length=t-4),this._freeIndices=null}clear(){this._s0=this._s1=this._s2=this._s3=null,this._count=0,this._actualCount=0,this._overflow=null,this._freeIndices=null}dispose(){this.clear()}},ht=class extends ut{constructor(...t){super(...t),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1}prepareTracking(){this.hasComputeds=!1}_onItemRemoved(t){t.unsub?.()}setAt(t,e){const s=this.getAt(t);super.setAt(t,e),this._map!==null&&(s?.unsub&&this._map.delete(s.node),e?.unsub&&this._map.set(e.node,t))}claimExisting(t,e){const s=this._count;if(s<=e)return!1;const i=this.getAt(e);if(i&&i.node===t&&i.unsub)return i.version=t.version,!0;if(this._map!==null||s-e>this._SCAN_THRESHOLD)return this._claimViaMap(t,e);for(let n=e+1;n<s;n++){const r=this.getAt(n);if(r&&r.node===t&&r.unsub)return r.version=t.version,this._rawSwap(n,e),!0}return!1}_claimViaMap(t,e){this._map===null&&(this._map=this._initMap());const s=this._map,i=s.get(t);if(i===void 0||i<e)return!1;const n=this.getAt(i);if(n==null||!n.unsub)return!1;if(n.version=t.version,i!==e){const r=this.getAt(e);this._rawSwap(i,e),s.set(t,e),r?.unsub&&s.set(r.node,i)}return!0}_initMap(){const t=new Map;for(let e=0;e<this._count;e++){const s=this.getAt(e);s?.unsub&&t.set(s.node,e)}return t}insertNew(t,e){const s=this.getAt(t);if(s!==null){const i=this._rawAdd(s);i>=this._count&&(this._count=i+1),this._map!==null&&s.unsub&&this._map.set(s.node,i)}this._rawWrite(t,e),t>=this._count&&(this._count=t+1),this._actualCount++,this._map!==null&&e.unsub&&this._map.set(e.node,t)}add(t){const e=super.add(t);return this._map!==null&&t.unsub&&this._map.set(t.node,e),e}remove(t){throw new Error("remove() prohibited")}compact(){}truncateFrom(t){super.truncateFrom(t),this._map!==null&&(this._map=null)}disposeAll(){this.truncateFrom(0),this.hasComputeds=!1}},U=Symbol.for("atom-effect/brand"),g={Atom:1,Writable:2,Computed:4,Effect:8};function Q(t,e){if(!t)return!1;const s=typeof t;return(s==="object"||s==="function")&&!!((t[U]??0)&e)}function St(t){return Q(t,g.Atom)}function mt(t){return Q(t,g.Computed)}function Tt(t){return Q(t,g.Effect)}function Y(t){if(t instanceof Promise)return!0;if(!t)return!1;const e=typeof t;return(e==="object"||e==="function")&&typeof t.then=="function"}var V=class{constructor(t,e,s=void 0){this.node=t,this.version=e,this.unsub=s}},vt=class{constructor(t=void 0,e=void 0){this.fn=t,this.sub=e}notify(t,e){L(()=>{const s=this.fn;s!==void 0&&s(t,e);const i=this.sub;i!==void 0&&i.execute()})}},Ot=class{constructor(){this.current=null}run(t,e){if(this.current===t)return e();const s=this.current;this.current=t;try{const i=e();return a&&E.warn(Y(i),'Detected Promise returned within tracking context. Dependencies accessed after "await" will NOT be tracked. Consider using synchronous tracking before the async boundary.'),i}finally{this.current=s}}},_=new Ot;function L(t){const e=_,s=e.current;if(s===null)return t();e.current=null;try{return t()}finally{e.current=s}}var j=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=F.UNINITIALIZED,this._nextEpoch=void 0,this._notifying=0,this._hotIndex=-1,this._slots=null,this._deps=null,this.id=Dt()&k}get isDisposed(){return(this.flags&G.DISPOSED)!==0}get isComputed(){return(this.flags&G.IS_COMPUTED)!==0}get hasError(){return!1}subscribe(t){const e=typeof t=="function";if(!e&&(!t||typeof t.execute!="function"))throw b(new TypeError("Invalid subscriber"),C,c.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let s=this._slots;s||(s=new ut,this._slots=s);let i=!1;if(s._s0!=null&&(e?s._s0.fn===t:s._s0.sub===t))i=!0;else if(s._s1!=null&&(e?s._s1.fn===t:s._s1.sub===t))i=!0;else if(s._s2!=null&&(e?s._s2.fn===t:s._s2.sub===t))i=!0;else if(s._s3!=null&&(e?s._s3.fn===t:s._s3.sub===t))i=!0;else{const r=s._overflow;if(r!=null)for(let o=0,l=r.length;o<l;o++){const p=r[o];if(p!=null&&(e?p.fn===t:p.sub===t)){i=!0;break}}}if(i)return a&&console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`),()=>{};const n=new vt(e?t:void 0,e?void 0:t);return s.add(n),()=>this._unsubscribe(n)}_unsubscribe(t){const e=this._slots;e&&(e.remove(t),this._notifying===0&&e.compact())}subscriberCount(){const t=this._slots;return t===null?0:t.size}_notifySubscribers(t,e){const s=this._slots;if(!(s===null||s.size===0)){this._notifying++;try{let i=s._s0;if(i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s1,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s2,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s3,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}const n=s._overflow;if(n!=null)for(let r=0,o=n.length;r<o;r++){const l=n[r];if(l!=null)try{l.notify(t,e)}catch(p){this._logNotifyError(p)}}}finally{--this._notifying===0&&s.compact()}}}_logNotifyError(t){console.error(b(t,C,c.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}_isDirty(){const t=this._deps;if(t===null||t.size===0)return!1;const e=this._hotIndex;if(e!==-1){const s=t.getAt(e);if(s!=null&&s.node.version!==s.version)return!0}return this._deepDirtyCheck()}},W=0;function $(){const t=W+1&k;return W=t===0?1:t,W}function q(t){const e=t+1&k;return e===0?1:e}var K=0,B=!1,ct=0;function Nt(){return ct}function lt(){return B?(a&&console.warn("startFlush() called during flush - ignored"),!1):(B=!0,ct=$(),K=0,!0)}function _t(){B=!1}function bt(){if(!B)return 0;const t=++K;if(t<=I.MAX_EXECUTIONS_PER_FLUSH)return t;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${I.MAX_EXECUTIONS_PER_FLUSH}`)}var At=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=I.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get queueSize(){return this._size+this._batchQueueSize}get isBatching(){return this._batchDepth>0}schedule(t){if(a&&typeof t!="function"&&(!t||typeof t.execute!="function"))throw new w(c.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);const e=this._epoch;if(t._nextEpoch===e)return;if(t._nextEpoch=e,this._batchDepth>0||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}const s=this._queueBuffer[this._bufferIndex];s[this._size++]=t,this._isProcessing||this._flush()}_flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0&&this._batchQueueSize===0)return;const t=lt();this._drainQueue(),t&&_t()}finally{this._isProcessing=!1}}_flushSync(){if(this._size===0&&this._batchQueueSize===0)return;const t=this._isFlushingSync;this._isFlushingSync=!0;const e=lt();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=t,e&&_t()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;this._epoch=this._epoch+1|0;const e=this._epoch,s=this._batchQueue,i=this._queueBuffer[this._bufferIndex];let n=this._size;for(let r=0;r<t;r++){const o=s[r];o._nextEpoch!==e&&(o._nextEpoch=e,i[n++]=o),s[r]=void 0}this._size=n,this._batchQueueSize=0,s.length>I.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let t=0;for(;this._size>0||this._batchQueueSize>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._batchQueueSize>0&&this._mergeBatchQueue(),this._size>0&&this._processQueue()}}_processQueue(){const t=this._bufferIndex,e=this._queueBuffer[t],s=this._size;this._bufferIndex=t^1,this._size=0,this._epoch=this._epoch+1|0;for(let i=0;i<s;i++){const n=e[i];e[i]=void 0;try{typeof n=="function"?n():n.execute()}catch(r){console.error(new w("Error occurred during scheduler execution",r))}}}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;console.error(new w(c.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[0].length=0,this._queueBuffer[1].length=0,this._batchQueueSize=0,this._batchQueue.length=0;const e=this.onOverflow;if(e)try{e(t)}catch{}}startBatch(){this._batchDepth++}endBatch(){if(this._batchDepth===0){a&&console.warn(c.SCHEDULER_END_BATCH_WITHOUT_START);return}--this._batchDepth===0&&(this._isFlushingSync||this._flushSync())}setMaxFlushIterations(t){if(t<I.MIN_FLUSH_ITERATIONS)throw new w(`Max iterations must be at least ${I.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},v=new At;function yt(t){if(a&&typeof t!="function")throw new TypeError(c.BATCH_CALLBACK_MUST_BE_FUNCTION);v.startBatch();try{return t()}finally{v.endBatch()}}var Rt=class extends j{constructor(t,e){super(),this[U]=g.Atom|g.Writable,this._value=t,this._equal=e.equal??Object.is,e.sync&&(this.flags|=f.SYNC),E.attachDebugInfo(this,"atom",this.id,e.name)}get isNotificationScheduled(){return(this.flags&f.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&f.SYNC)!==0}get value(){const t=_.current;return t?.addDependency(this),this._value}set value(t){const e=this._value;if(this._equal(e,t)||(this._value=t,this.version=q(this.version),E.trackUpdate(this.id,E.getDebugName(this)),(this.flags&f.NOTIFICATION_SCHEDULED)!==0))return;const s=this._slots;s==null||s.size===0||(this._pendingOldValue=e,this.flags|=f.NOTIFICATION_SCHEDULED,(this.flags&f.SYNC)!==0&&!v.isBatching?this._notifying===0&&this._flushNotifications():v.schedule(this))}execute(){this._flushNotifications()}_flushNotifications(){const t=f.NOTIFICATION_SCHEDULED,e=f.DISPOSED,s=f.SYNC;for(;(this.flags&(t|e))===t;){const i=this._pendingOldValue;if(this._pendingOldValue=void 0,this.flags&=~t,this._equal(this._value,i)||this._notifySubscribers(this._value,i),(this.flags&s)===0||v.isBatching)break}}peek(){return this._value}dispose(){const t=this.flags;(t&f.DISPOSED)===0&&(this._slots?.clear(),this.flags=t|f.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._equal=Object.is)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function Ft(t,e={}){return new Rt(t,e)}var{IDLE:m,DIRTY:d,PENDING:A,RESOLVED:D,REJECTED:O,HAS_ERROR:H,RECOMPUTING:P,DISPOSED:J,IS_COMPUTED:M,FORCE_COMPUTE:Z}=G,wt=class extends j{constructor(t,e={}){if(typeof t!="function")throw new N(c.COMPUTED_MUST_BE_FUNCTION);if(super(),this[U]=g.Atom|g.Computed,this._error=null,this._promiseId=0,this._deps=new ht,this._trackEpoch=F.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=M|d|m,this._equal=e.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in e?e.defaultValue:X,this._onError=e.onError??null,E.attachDebugInfo(this,"computed",this.id,e.name),e.lazy===!1)try{this._recompute()}catch{}}get isDirty(){return(this.flags&d)!==0}get isRejected(){return(this.flags&O)!==0}get isRecomputing(){return(this.flags&P)!==0}get _hasErrorInternal(){return(this.flags&H)!==0}_track(){_.current?.addDependency(this)}get value(){const t=_.current;t?.addDependency(this);let e=this.flags;if((e&(D|d|m))===D)return this._value;if((e&J)!==0)throw new N(c.COMPUTED_DISPOSED);if((e&P)!==0){const n=this._defaultValue;if(n!==X)return n;throw new N(c.COMPUTED_CIRCULAR_DEPENDENCY)}if((e&(d|m))!==0){const n=this._deps;if((e&m)===0&&(e&Z)===0&&n.size>0&&!this._isDirty()?e=this.flags&=~d:(this._recompute(),e=this.flags),(e&D)!==0)return this._value}const s=this._defaultValue,i=s!==X;if((e&A)!==0){if(i)return s;throw new N(c.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if((e&O)!==0){if(i)return s;throw this._error}return this._value}peek(){return this._value}get state(){const t=_.current;t?.addDependency(this);const e=this.flags;return(e&D)!==0?R.RESOLVED:(e&A)!==0?R.PENDING:(e&O)!==0?R.REJECTED:R.IDLE}get hasError(){const t=_.current;if(t?.addDependency(this),(this.flags&(O|H))!==0)return!0;const e=this._deps;return e.hasComputeds?L(()=>{const s=e.size;for(let i=0;i<s;i++)if(e.getAt(i)?.node.hasError)return!0;return!1}):!1}get isValid(){return!this.hasError}get errors(){const t=_.current;t?.addDependency(this);const e=this._error,s=this._deps;if(!s.hasComputeds)return e==null?nt:Object.freeze([e]);const i=[];return e!=null&&i.push(e),L(()=>{const n=s.size;for(let r=0;r<n;r++){const o=s.getAt(r)?.node;o!=null&&(o.flags&M)!==0&&this._accumulateErrors(o,i)}}),i.length===0?nt:Object.freeze(i)}_accumulateErrors(t,e){const s=t._error;s!=null&&!e.includes(s)&&e.push(s);const i=t._deps;if(!i.hasComputeds)return;const n=i.size;for(let r=0;r<n;r++){const o=i.getAt(r)?.node;o!=null&&(o.flags&M)!==0&&this._accumulateErrors(o,e)}}get lastError(){const t=_.current;return t?.addDependency(this),this._error}get isPending(){const t=_.current;return t?.addDependency(this),(this.flags&A)!==0}get isResolved(){const t=_.current;return t?.addDependency(this),(this.flags&D)!==0}invalidate(){this.flags|=Z,this._markDirty()}dispose(){(this.flags&J)===0&&(this._deps.disposeAll(),this._slots!=null&&this._slots.clear(),this.flags=J|d|m,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){const e=this._trackEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,i=this._deps,n=i.getAt(s);if(n!=null&&n.node===t)n.version=t.version;else if(!i.claimExisting(t,s)){const r=new V(t,t.version,t.subscribe(this));i.insertNew(s,r)}(t.flags&M)!==0&&(i.hasComputeds=!0)}_recompute(){if(this.isRecomputing)return;this.flags=(this.flags|P)&~Z,this._trackEpoch=$(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const e=_.run(this,this._fn);this._deps.truncateFrom(this._trackCount),t=!0,Y(e)?this._handleAsyncComputation(e):this._finalizeResolution(e)}catch(e){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch(s){a&&console.warn("[atom-effect] _commitDeps failed during error recovery:",s)}this._handleError(e,c.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=F.UNINITIALIZED,this._trackCount=0,this.flags&=~P}}_handleAsyncComputation(t){this.flags=(this.flags|A)&~(m|d|D|O),this._notifySubscribers(void 0,void 0),this._promiseId=(this._promiseId+1)%Et.MAX_PROMISE_ID;const e=this._promiseId;t.then(s=>{if(e===this._promiseId){if(this._isDirty())return this._markDirty();this._finalizeResolution(s),this._notifySubscribers(s,void 0)}},s=>e===this._promiseId&&this._handleError(s,c.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,e,s=!1){const i=b(t,N,e);if((!this.isRejected||this._error!==i)&&(this.version=q(this.version)),this._error=i,this.flags=this.flags&~(m|d|A|D)|O|H,this._onError)try{this._onError(i)}catch(n){console.error(c.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(this._notifySubscribers(void 0,void 0),s)throw i}_finalizeResolution(t){const e=this.flags;((e&D)===0||!this._equal(this._value,t))&&(this.version=q(this.version)),this._value=t,this._error=null,this.flags=(e|D)&~(m|d|A|O|H)}execute(){this._markDirty()}_markDirty(){const t=this.flags;(t&(P|d))===0&&(this.flags=t|d,E.trackUpdate(this.id,E.getDebugName(this)),this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){const t=this._deps;return L(()=>{const e=t.size;for(let s=0;s<e;s++){const i=t.getAt(s);if(i==null)continue;const n=i.node;if((n.flags&M)!==0)try{n.value}catch{a&&console.warn(`[atom-effect] Dependency #${n.id} threw during dirty check`)}if(n.version!==i.version)return this._hotIndex=s,!0}return this._hotIndex=-1,!1})}};function Ut(t,e={}){return new wt(t,e)}var Lt=class extends j{constructor(t,e={}){super(),this[U]=g.Effect,this._cleanup=null,this._deps=new ht,this._currentEpoch=F.UNINITIALIZED,this._lastFlushEpoch=F.UNINITIALIZED,this._fn=t,this._onError=e.onError??null,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??I.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??I.MAX_EXECUTIONS_PER_EFFECT,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._trackCount=0,this._sync?this._notifyCallback=()=>this.execute():this._notifyCallback=()=>v.schedule(this),E.attachDebugInfo(this,"effect",this.id,e.name)}run(){if(this.isDisposed)throw new S(c.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=T.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if((this.flags&T.EXECUTING)===0)return;const e=this._currentEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,i=this._deps;let n;switch(s){case 0:n=i._s0;break;case 1:n=i._s1;break;case 2:n=i._s2;break;case 3:n=i._s3;break;default:n=i.getAt(s)}n!=null&&n.node===t?n.version=t.version:i.claimExisting(t,s)||this._insertNewDependency(t,s),t.isComputed&&(i.hasComputeds=!0)}_insertNewDependency(t,e){let s;try{const i=t.subscribe(this._notifyCallback);s=new V(t,t.version,i)}catch(i){const n=b(i,S,c.EFFECT_EXECUTION_FAILED);if(console.error(n),this._onError)try{this._onError(n)}catch{}s=new V(t,t.version,void 0)}this._deps.insertNew(e,s)}execute(t=!1){const e=this.flags;if((e&(T.DISPOSED|T.EXECUTING))!==0)return;const s=this._deps;if(!t&&s.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),E.trackUpdate(this.id,E.getDebugName(this)),this.flags=e|T.EXECUTING,this._execCleanup(),this._currentEpoch=$(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let i=!1;try{const n=_.run(this,this._fn);s.truncateFrom(this._trackCount),i=!0,Y(n)?this._handleAsyncResult(n):this._cleanup=typeof n=="function"?n:null}catch(n){if(!i)try{s.truncateFrom(this._trackCount)}catch(r){a&&console.warn("[atom-effect] _commitDeps failed during error recovery:",r)}this._handleExecutionError(n),this._cleanup=null}finally{this.flags&=~T.EXECUTING}}_handleAsyncResult(t){const e=++this._execId;t.then(s=>{if(e!==this._execId||this.isDisposed){if(typeof s=="function")try{s()}catch(i){this._handleExecutionError(i,c.EFFECT_CLEANUP_FAILED)}return}typeof s=="function"&&(this._cleanup=s)},s=>e===this._execId&&this._handleExecutionError(s))}_deepDirtyCheck(){const t=_.current;_.current=null;const e=this._deps;try{const s=e.size;for(let i=0;i<s;i++){const n=e.getAt(i);if(n==null)continue;const r=n.node;if(r.isComputed&&this._tryPullComputed(r),r.version!==n.version)return this._hotIndex=i,!0}return!1}finally{_.current=t}}_tryPullComputed(t){try{t.value}catch{a&&console.warn(`[atom-effect] Dependency #${t.id} threw during dirty check`)}}_execCleanup(){const t=this._cleanup;if(t!=null){this._cleanup=null;try{t()}catch(e){this._handleExecutionError(e,c.EFFECT_CLEANUP_FAILED)}}}_checkInfiniteLoops(){const t=Nt();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),bt()>I.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,a&&this._checkFrequencyLimit()}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=z.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const e=new S(c.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(e),e}}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&T.EXECUTING)!==0}_throwInfiniteLoopError(t){const e=new S(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${K}`);throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=c.EFFECT_EXECUTION_FAILED){const s=b(t,S,e);if(console.error(s),this._onError)try{this._onError(s)}catch(i){console.error(b(i,S,c.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function Pt(t,e={}){if(typeof t!="function")throw new S(c.EFFECT_MUST_BE_FUNCTION);const s=new Lt(t,e);return s.execute(),s}var at=/^(?:__proto__|constructor|prototype)$/;function tt(t,e,s,i){if(s===e.length)return i;const n=e[s];if(at.test(n))return t;const r=t!=null&&typeof t=="object"?t:{},o=r[n],l=tt(o,e,s+1,i);if(Object.is(o,l))return t;if(Array.isArray(r)){const p=r.slice(),y=Number(n);return n.trim()!==""&&Number.isInteger(y)&&y>=0?p[y]=l:p[n]=l,p}return{...r,[n]:l}}function x(t,e){let s=t;const i=e.length;for(let n=0;n<i;n++){if(s==null)return;const r=e[n];if(at.test(r))return;s=s[r]}return s}function et(t,e){const s=e.includes(".")?e.split("."):[e],i=new Set,n=()=>{i.forEach(r=>r()),i.clear()};return{get value(){return x(t.value,s)},set value(r){const o=t.peek(),l=tt(o,s,0,r);l!==o&&(t.value=l)},peek:()=>x(t.peek(),s),subscribe(r){const o=t.subscribe((l,p)=>{const y=x(l,s),ft=x(p,s);Object.is(y,ft)||r(y,ft)});return i.add(o),()=>{o(),i.delete(o)}},subscriberCount:()=>i.size,dispose:n,[Symbol.dispose]:n,[U]:g.Atom|g.Writable}}var Mt=(t,e)=>et(t,e),xt=t=>e=>et(t,e);u.AsyncState=R,u.AtomError=C,u.ComputedError=N,u.DEBUG_CONFIG=z,u.EffectError=S,u.SCHEDULER_CONFIG=I,u.SchedulerError=w,u.atom=Ft,u.atomLens=et,u.batch=yt,u.composeLens=Mt,u.computed=Ut,u.effect=Pt,u.getPathValue=x,u.globalScheduler=v,u.isAtom=St,u.isComputed=mt,u.isEffect=Tt,u.lensFor=xt,u.runtimeDebug=E,u.setDeepValue=tt,u.untracked=L});
2
2
 
3
3
  //# sourceMappingURL=atom-effect.min.js.map