@but212/atom-effect 0.30.0 → 0.31.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/dist/atom-effect.min.js +1 -1
- package/dist/atom-effect.min.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +24 -46
- package/dist/index.mjs +532 -478
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/atom-effect.min.js
CHANGED
|
@@ -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,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(u=typeof globalThis<"u"?globalThis:u||self,l(u.AtomEffect={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var l={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},Bt=Object.freeze({ASYNC_STATE:l.IDLE|l.PENDING|l.RESOLVED|l.REJECTED,COMPUTED_DIRTY_MASK:l.DIRTY|l.RECOMPUTING|l.FORCE_COMPUTE}),F=Object.freeze({IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"}),T=Object.freeze({DISPOSED:l.DISPOSED,EXECUTING:l.EFFECT_EXECUTING}),V=Object.freeze({DISPOSED:l.DISPOSED,IS_COMPUTED:l.IS_COMPUTED,DIRTY:l.DIRTY,IDLE:l.IDLE,PENDING:l.PENDING,RESOLVED:l.RESOLVED,REJECTED:l.REJECTED,RECOMPUTING:l.RECOMPUTING,HAS_ERROR:l.HAS_ERROR,FORCE_COMPUTE:l.FORCE_COMPUTE}),D=Object.freeze({DISPOSED:l.DISPOSED,SYNC:l.ATOM_SYNC,NOTIFICATION_SCHEDULED:l.ATOM_NOTIFICATION_SCHEDULED}),p=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,B=Object.freeze({WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3,LOOP_THRESHOLD:100}),dt=Object.freeze({MAX_PROMISE_ID:k}),U=Object.freeze({UNINITIALIZED:-1,MIN:1}),ot=!1;try{ot=!!(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__||ot),ut=Object.freeze([]),N=class rt 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(){const e=this.cause;if(e==null)return[this];const s=[this];let i=e,n=null;for(;i!=null&&(s.push(i),!(i===this||n?.has(i)));){if(i instanceof rt)i=i.cause;else if(i instanceof Error)i=i.cause;else break;s.length>3&&(n===null?n=new Set(s):n.add(i))}return s}toJSON(e){const s=e??new Set;if(s.has(this))return{name:this.name,message:"[Circular Reference]",recoverable:this.recoverable,code:this.code};s.add(this);let i=this.cause;return i instanceof rt?i=i.toJSON(s):i instanceof Error&&(i={name:i.name,message:i.message,stack:i.stack,cause:i.cause}),{name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,stack:this.stack,cause:i}}static format(e,s,i){return`${e} (${s}): ${i}`}},y=class extends N{constructor(...t){super(...t),this.name="ComputedError"}},m=class extends N{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="EffectError"}},L=class extends N{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 w(t,e,s){return t instanceof N?new e(`${t.name} (${s}): ${t.message}`,t,t.recoverable,t.code):t instanceof Error?new e(`${t.name||"Error"} (${s}): ${t.message}`,t):new e(`Unexpected error (${s}): ${String(t)}`,t)}var ht=Symbol("AtomEffect.DebugName"),pt=Symbol("AtomEffect.Id"),lt=Symbol("AtomEffect.Type"),Y=Symbol("AtomEffect.NoDefaultValue"),It="[Atom Effect]",H=()=>{},Ct=class{constructor(){this.enabled=!0,this.warnInfiniteLoop=B.WARN_INFINITE_LOOP,this._updateCounts=new Map,this._nodeRegistry=new Map,this._threshold=B.LOOP_THRESHOLD,this._cleanupScheduled=!1,this.warn=(t,e)=>{this.enabled&&t&&console.warn(`${It} ${e}`)},this.registerNode=t=>{this._nodeRegistry.set(t.id,new WeakRef(t))},this.attachDebugInfo=(t,e,s,i)=>{if(!this.enabled)return;const n=t;n[ht]=i??`${e}_${s}`,n[pt]=s,n[lt]=e,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,queueMicrotask(()=>{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!=null)return t[ht]},this.getDebugType=t=>{if(t!=null)return t[lt]}}},Dt={enabled:!1,warnInfiniteLoop:!1,warn:H,registerNode:H,attachDebugInfo:H,trackUpdate:H,dumpGraph:()=>[],getDebugName:()=>{},getDebugType:()=>{}},E=a?new Ct:Dt,gt=1,St=()=>gt++|0,ct=class{constructor(){this._count=0,this._actualCount=0,this._s0=null,this._s1=null,this._s2=null,this._s3=null,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;s[t-4]=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),3+e.length}_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){if(t<4)return t===0?this._s0:t===1?this._s1:t===2?this._s2:t===3?this._s3:null;const e=this._overflow;return e===null?null:e[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):this._shrinkPhysicalSizeFrom(t))}_shrinkPhysicalSizeFrom(t){if(t===this._count-1){if(this._count--,this._count>4){const e=this._overflow;for(;this._count>4&&e[this._count-5]===null;)this._count--}this._count===4&&this._s3===null&&(this._count=3,this._s2===null&&(this._count=2,this._s1===null&&(this._count=1,this._s0===null&&(this._count=0))))}}truncateFrom(t){t<=3&&(t<=3&&this._s3!==null&&(this._onItemRemoved(this._s3),this._s3=null,this._actualCount--),t<=2&&this._s2!==null&&(this._onItemRemoved(this._s2),this._s2=null,this._actualCount--),t<=1&&this._s1!==null&&(this._onItemRemoved(this._s1),this._s1=null,this._actualCount--),t<=0&&this._s0!==null&&(this._onItemRemoved(this._s0),this._s0=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){if(t(this._s0),e>1&&(t(this._s1),e>2&&(t(this._s2),e>3&&(t(this._s3),e>4)))){const n=this._overflow;for(let r=0,o=n.length;r<o;r++)t(n[r])}return}let s=0;if(this._s0!==null&&(t(this._s0),++s>=e)||this._s1!==null&&(t(this._s1),++s>=e)||this._s2!==null&&(t(this._s2),++s>=e)||this._s3!==null&&(t(this._s3),++s>=e))return;const i=this._overflow;if(i!==null)for(let n=0,r=i.length;n<r;n++){const o=i[n];if(o!=null&&(t(o),++s>=e))return}}compact(){const t=this._actualCount;if(t===this._count)return;if(t===0){this.clear();return}let e=0;const s=this._count;for(let i=0;i<s;i++){const n=this.getAt(i);if(n!==null&&(i!==e&&(this._rawWrite(e,n),this._rawWrite(i,null)),e++,e===t))break}this._count=t,this._overflow!==null&&(e<=4?this._overflow=null:this._overflow.length=e-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()}},_t=class extends ct{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!==null&&this._map.delete(s.node),e!==null&&this._map.set(e.node,t))}claimExisting(t,e){const s=this._count;if(s<=e)return!1;let i=null;if(e<4?e===0?i=this._s0:e===1?i=this._s1:e===2?i=this._s2:i=this._s3:i=this._overflow[e-4]??null,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);let n=-1,r=null,o=e+1;for(;o<4&&o<s;o++){const h=o===1?this._s1:o===2?this._s2:this._s3;if(h&&h.node===t&&h.unsub){n=o,r=h;break}}if(n===-1&&o<s){const h=this._overflow;for(let f=o-4,v=s-4;f<v;f++){const C=h[f];if(C&&C.node===t&&C.unsub){n=f+4,r=C;break}}}return n!==-1?(r.version=t.version,this._rawWrite(e,r),this._rawWrite(n,i),!0):!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;this._s0?.unsub&&t.set(this._s0.node,0),this._s1?.unsub&&t.set(this._s1.node,1),this._s2?.unsub&&t.set(this._s2.node,2),this._s3?.unsub&&t.set(this._s3.node,3);const e=this._overflow;if(e!==null)for(let s=0,i=e.length;s<i;s++){const n=e[s];n?.unsub&&t.set(n.node,s+4)}return t}insertNew(t,e){let s=null;if(t<4)t===0?(s=this._s0,this._s0=e):t===1?(s=this._s1,this._s1=e):t===2?(s=this._s2,this._s2=e):(s=this._s3,this._s3=e);else{this._overflow===null&&(this._overflow=[]);const i=this._overflow;s=i[t-4]??null,i[t-4]=e}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)}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}},P=Symbol.for("atom-effect/brand"),I={Atom:1,Writable:2,Computed:4,Effect:8};function $(t,e){return!t||typeof t!="object"&&typeof t!="function"?!1:!!(t[P]&e)}function vt(t){return $(t,I.Atom)}function Tt(t){return $(t,I.Computed)}function mt(t){return $(t,I.Effect)}function W(t){return t instanceof Promise?!0:t===null||typeof t!="object"?!1:typeof t.then=="function"}var j=class{constructor(t,e,s=void 0){this.node=t,this.version=e,this.unsub=s}},Ot=class{constructor(t=void 0,e=void 0){this.fn=t,this.sub=e}notify(t,e){const s=this.fn,i=this.sub;if(s===void 0&&i===void 0)return;const n=_,r=n.current;if(r===null){s!==void 0&&s(t,e),i!==void 0&&i.execute();return}n.current=null;try{s!==void 0&&s(t,e),i!==void 0&&i.execute()}finally{n.current=r}}},Nt=class{constructor(){this.current=null}run(t,e){if(this.current===t)return e();const s=this.current;this.current=t;try{if(!a)return e();const i=e();return E.warn(W(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 Nt;function G(t){const e=_,s=e.current;if(s===null)return t();e.current=null;try{return t()}finally{e.current=s}}var q=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=U.UNINITIALIZED,this._notifying=0,this._hotIndex=-1,this.id=St()&k,this._nextEpoch=void 0,this._slots=null,this._deps=null}get isDisposed(){return(this.flags&V.DISPOSED)!==0}get isComputed(){return(this.flags&V.IS_COMPUTED)!==0}get hasError(){return!1}subscribe(t){const e=typeof t=="function";if(!e&&(t===null||typeof t.execute!="function"))throw w(new TypeError("Invalid subscriber"),N,c.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let s=this._slots;if(s===null&&(s=new ct,this._slots=s),s.size>0){let n=!1;if(s._s0!==null&&(s._s0.fn===t||s._s0.sub===t)||s._s1!==null&&(s._s1.fn===t||s._s1.sub===t)||s._s2!==null&&(s._s2.fn===t||s._s2.sub===t)||s._s3!==null&&(s._s3.fn===t||s._s3.sub===t))n=!0;else{const r=s._overflow;if(r!==null){const o=r.length;if(e)for(let h=0;h<o;h++){const f=r[h];if(f!==null&&f?.fn===t){n=!0;break}}else for(let h=0;h<o;h++){const f=r[h];if(f!==null&&f?.sub===t){n=!0;break}}}}if(n)return a&&console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`),()=>{}}const i=new Ot(e?t:void 0,e?void 0:t);return s.add(i),()=>this._unsubscribe(i)}_unsubscribe(t){const e=this._slots;e!==null&&(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{if(s._s0!==null)try{s._s0.notify(t,e)}catch(n){this._logNotifyError(n)}if(s._s1!==null)try{s._s1.notify(t,e)}catch(n){this._logNotifyError(n)}if(s._s2!==null)try{s._s2.notify(t,e)}catch(n){this._logNotifyError(n)}if(s._s3!==null)try{s._s3.notify(t,e)}catch(n){this._logNotifyError(n)}const i=s._overflow;if(i!==null)for(let n=0,r=i.length;n<r;n++){const o=i[n];if(o!==null)try{o?.notify(t,e)}catch(h){this._logNotifyError(h)}}}finally{--this._notifying===0&&s.compact()}}}_logNotifyError(t){console.error(w(t,N,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()}},K=0;function J(){const t=K+1&k;return K=t===0?1:t,K}function Z(t){const e=t+1&k;return e===0?1:e}var tt=0,X=!1,ft=0;function bt(){return ft}function at(){return X?(a&&console.warn("startFlush() called during flush - ignored"),!1):(X=!0,ft=J(),tt=0,!0)}function Et(){X=!1}function At(){if(!X)return 0;const t=++tt;if(t<=p.MAX_EXECUTIONS_PER_FLUSH)return t;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${p.MAX_EXECUTIONS_PER_FLUSH}`)}var yt=class{constructor(){this._bufferIndex=0,this._size=0,this._epoch=0,this._batchDepth=0,this._batchQueueSize=0,this._maxFlushIterations=p.MAX_FLUSH_ITERATIONS,this._isProcessing=!1,this._isFlushingSync=!1,this._buffer0=[],this._buffer1=[],this._batchQueue=[],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 L(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._bufferIndex===0?this._buffer0:this._buffer1;s[this._size++]=t,this._isProcessing||this._flush()}_flush(){this._isProcessing||this._size===0&&this._batchQueueSize===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0&&this._batchQueueSize===0)return;const t=at();this._drainQueue(),t&&Et()}finally{this._isProcessing=!1}}_flushSync(){if(this._size===0&&this._batchQueueSize===0)return;const t=this._isFlushingSync;this._isFlushingSync=!0;const e=at();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=t,e&&Et()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;const e=++this._epoch|0,s=this._batchQueue,i=this._bufferIndex===0?this._buffer0:this._buffer1;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>p.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=t===0?this._buffer0:this._buffer1,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 L("Error occurred during scheduler execution",r))}}}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;console.error(new L(c.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._buffer0.length=0,this._buffer1.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<p.MIN_FLUSH_ITERATIONS)throw new L(`Max iterations must be at least ${p.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},g=new yt;function wt(t){if(a&&typeof t!="function")throw new TypeError(c.BATCH_CALLBACK_MUST_BE_FUNCTION);g.startBatch();try{return t()}finally{g.endBatch()}}var M=null;function Rt(t){return t?new Promise((e,s)=>{g.schedule(()=>{try{t(),e()}catch(i){s(i)}})}):M||(M=new Promise(e=>{g.schedule(()=>{M=null,e()})}),M)}var Ft=class extends q{constructor(t,e){super(),this[P]=I.Atom|I.Writable,this._value=t,this._equal=e.equal??Object.is,e.sync&&(this.flags|=D.SYNC),a&&E.attachDebugInfo(this,"atom",this.id,e.name)}get isNotificationScheduled(){return(this.flags&D.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&D.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))return;this._value=t,this.version=Z(this.version),a&&E.trackUpdate(this.id,E.getDebugName(this));const s=this.flags,i=D.NOTIFICATION_SCHEDULED;if((s&i)!==0)return;const n=this._slots;if(n===null||n.size===0)return;this._pendingOldValue=e;const r=s|i;if(this.flags=r,(r&D.SYNC)!==0&&!g.isBatching){this._notifying===0&&this._flushNotifications();return}g.schedule(this)}execute(){this._flushNotifications()}_flushNotifications(){const t=D.NOTIFICATION_SCHEDULED,e=D.DISPOSED,s=D.SYNC,i=t|e;let n=this.flags;for(;(n&i)===t;){const r=this._pendingOldValue;this._pendingOldValue=void 0,this.flags=n&=~t;const o=this._value;if(this._equal(o,r)||this._notifySubscribers(o,r),n=this.flags,(n&s)===0||g.isBatching)break}}peek(){return this._value}dispose(){const t=this.flags,e=D.DISPOSED;(t&e)===0&&(this.flags=t|e,this._slots?.clear(),this._value=void 0,this._pendingOldValue=void 0,this._equal=Object.is)}_deepDirtyCheck(){return!1}};function Ut(t,e={}){return new Ft(t,e)}var{IDLE:O,DIRTY:d,PENDING:R,RESOLVED:S,REJECTED:b,HAS_ERROR:et,RECOMPUTING:A,DISPOSED:Q,IS_COMPUTED:x,FORCE_COMPUTE:st}=V,Lt=class extends q{constructor(t,e={}){if(typeof t!="function")throw new y(c.COMPUTED_MUST_BE_FUNCTION);if(super(),this[P]=I.Atom|I.Computed,this._promiseId=0,this._trackEpoch=U.UNINITIALIZED,this._trackCount=0,this._error=null,this._deps=new _t,this._value=void 0,this.flags=x|d|O,this._equal=e.equal??Object.is,this._computation=t,this._defaultValue="defaultValue"in e?e.defaultValue:Y,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&b)!==0}get isRecomputing(){return(this.flags&A)!==0}get value(){const t=_.current;t!==null&&t.addDependency(this);const e=this.flags;if((e&(S|d|O|Q|A))===S)return this._value;if((e&Q)!==0)throw new y(c.COMPUTED_DISPOSED);if((e&A)!==0){const n=this._defaultValue;if(n!==Y)return n;throw new y(c.COMPUTED_CIRCULAR_DEPENDENCY)}if((e&(d|O))!==0){const n=this._deps;if((e&(O|st))!==0||n.size===0||this._isDirty()?this._recompute():this.flags&=~d,(this.flags&S)!==0)return this._value}const s=this._defaultValue,i=s!==Y;if((this.flags&R)!==0){if(i)return s;throw new y(c.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if((this.flags&b)!==0){if(i)return s;throw this._error}return this._value}peek(){return this._value}get state(){const t=_.current;t!==null&&t.addDependency(this);const e=this.flags;return(e&S)!==0?F.RESOLVED:(e&R)!==0?F.PENDING:(e&b)!==0?F.REJECTED:F.IDLE}get hasError(){const t=_.current;if(t!==null&&t.addDependency(this),(this.flags&(b|et))!==0)return!0;const e=this._deps;return e.hasComputeds?G(()=>{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!==null&&t.addDependency(this);const e=this._error,s=this._deps;if(!s.hasComputeds)return e===null?ut:Object.freeze([e]);const i=[];return e!==null&&i.push(e),G(()=>{const n=s.size;for(let r=0;r<n;r++){const o=s.getAt(r)?.node;o!==void 0&&(o.flags&x)!==0&&this._accumulateErrors(o,i)}}),i.length===0?ut: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!==void 0&&(o.flags&x)!==0&&this._accumulateErrors(o,e)}}get lastError(){const t=_.current;return t!==null&&t.addDependency(this),this._error}get isPending(){const t=_.current;return t!==null&&t.addDependency(this),(this.flags&R)!==0}get isResolved(){const t=_.current;return t!==null&&t.addDependency(this),(this.flags&S)!==0}invalidate(){this.flags|=st,this._markDirty()}dispose(){(this.flags&Q)===0&&(this._deps.disposeAll(),this._slots!==null&&this._slots.clear(),this.flags=Q|d|O,this._error=null,this._value=void 0,this._hotIndex=-1)}addDependency(t){const e=this._trackEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,i=this._deps;let n=null;if(s<4)s===0?n=i._s0:s===1?n=i._s1:s===2?n=i._s2:n=i._s3;else{const r=i._overflow;r!==null&&(n=r[s-4]??null)}if(n!==null&&n.node===t)n.version=t.version;else if(!i.claimExisting(t,s)){const r=new j(t,t.version,t.subscribe(this));i.insertNew(s,r)}(t.flags&x)!==0&&(i.hasComputeds=!0)}_recompute(){if((this.flags&A)!==0)return;this.flags=(this.flags|A)&~st,this._trackEpoch=J(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const e=_.run(this,this._computation);this._deps.truncateFrom(this._trackCount),t=!0,W(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=U.UNINITIALIZED,this._trackCount=0,this.flags&=~A}}_handleAsyncComputation(t){this.flags=(this.flags|R)&~(O|d|S|b),this._notifySubscribers(void 0,void 0),this._promiseId=(this._promiseId+1)%dt.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=w(t,y,e);if((!this.isRejected||this._error!==i)&&(this.version=Z(this.version)),this._error=i,this.flags=this.flags&~(O|d|R|S)|b|et,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&S)===0||!this._equal(this._value,t))&&(this.version=Z(this.version)),this._value=t,this._error=null,this.flags=(e|S)&~(O|d|R|b|et)}execute(){this._markDirty()}_markDirty(){const t=this.flags;(t&(A|d))===0&&(this.flags=t|d,E.trackUpdate(this.id,E.getDebugName(this)),this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){const t=this._deps,e=t.size,s=this._hotIndex;return G(()=>{if(s!==-1&&s<e){const i=t.getAt(s);if(i!==null&&this._checkLinkDirty(i))return!0}for(let i=0;i<e;i++){if(i===s)continue;const n=t.getAt(i);if(n!==null&&this._checkLinkDirty(n))return this._hotIndex=i,!0}return this._hotIndex=-1,!1})}_checkLinkDirty(t){const e=t.node;if((e.flags&x)!==0)try{e.value}catch{a&&console.warn(`[atom-effect] Dependency #${e.id} threw during check`)}return e.version!==t.version}};function Pt(t,e={}){return new Lt(t,e)}var Mt=class extends q{constructor(t,e={}){super(),this[P]=I.Effect,this._currentEpoch=U.UNINITIALIZED,this._lastFlushEpoch=U.UNINITIALIZED,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._trackCount=0,this._cleanup=null,this._deps=new _t,this._fn=t,this._onError=e.onError??null,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??p.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??p.MAX_EXECUTIONS_PER_EFFECT,this._sync?this._notifyCallback=()=>this.execute():this._notifyCallback=()=>g.schedule(this),E.attachDebugInfo(this,"effect",this.id,e.name)}run(){if(this.isDisposed)throw new m(c.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=T.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}addDependency(t){if((this.flags&T.EXECUTING)===0||t._lastSeenEpoch===this._currentEpoch)return;t._lastSeenEpoch=this._currentEpoch;const e=this._trackCount++,s=this._deps,i=t.version;let n=null;if(e<4)e===0?n=s._s0:e===1?n=s._s1:e===2?n=s._s2:n=s._s3;else{const r=s._overflow;r!==null&&(n=r[e-4]??null)}n!==null&&n.node===t?n.version=i:s.claimExisting(t,e)||this._insertNewDependency(t,e,i),t.isComputed&&!s.hasComputeds&&(s.hasComputeds=!0)}_insertNewDependency(t,e,s){let i;try{i=new j(t,s,t.subscribe(this._notifyCallback))}catch(n){const r=w(n,m,c.EFFECT_EXECUTION_FAILED);if(console.error(r),this._onError)try{this._onError(r)}catch{}i=new j(t,s,void 0)}this._deps.insertNew(e,i)}execute(t=!1){const e=this.flags;if((e&(T.DISPOSED|T.EXECUTING))!==0)return;const s=this._deps;if(!t&&s.physicalSize>0&&!this._isDirty())return;this._checkInfiniteLoops(),E.trackUpdate(this.id,E.getDebugName(this)),this.flags=e|T.EXECUTING,this._execCleanup(),this._currentEpoch=J(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let i=!1;try{const n=_.run(this,this._fn);s.truncateFrom(this._trackCount),i=!0,typeof n=="function"?this._cleanup=n:W(n)?this._handleAsyncResult(n):this._cleanup=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.flags&T.DISPOSED)!==0){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))}_isDirty(){const t=this._deps,e=t.size;if(e===0)return!1;const s=this._hotIndex;if(s!==-1&&s<e){const i=t.getAt(s);if(i!==null){const n=i.node;if(!n.isComputed&&n.version!==i.version)return!0}}return this._deepDirtyCheck()}_deepDirtyCheck(){const t=this._deps,e=t.size,s=this._hotIndex,i=_.current;_.current=null;try{for(let n=0;n<e;n++){if(n===s)continue;const r=t.getAt(n);if(r===null)continue;const o=r.node;if(o.isComputed)try{o.value}catch{a&&console.warn(`[atom-effect] Dependency #${o.id} error in check`)}if(o.version!==r.version)return this._hotIndex=n,!0}return this._hotIndex=-1,!1}finally{_.current=i}}_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=bt();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),At()>p.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>=B.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const e=new m(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 m(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${tt}`);throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=c.EFFECT_EXECUTION_FAILED){const s=w(t,m,e);if(console.error(s),this._onError)try{this._onError(s)}catch(i){console.error(w(i,m,c.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function xt(t,e={}){if(typeof t!="function")throw new m(c.EFFECT_MUST_BE_FUNCTION);const s=new Mt(t,e);return s.execute(),s}function it(t,e,s,i){if(s===e.length)return i;const n=e[s];if(n==="__proto__"||n==="constructor"||n==="prototype")return t;const r=t!=null&&typeof t=="object"?t:{},o=r[n],h=it(o,e,s+1,i);if(Object.is(o,h))return t;if(Array.isArray(r)){const v=r.slice(),C=+n;return n.trim()!==""&&C>=0&&C%1===0?v[C]=h:v[n]=h,v}const f={...r};return f[n]=h,f}function z(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(r==="__proto__"||r==="constructor"||r==="prototype")return;s=s[r]}return s}function nt(t,e){const s=e.includes(".")?e.split("."):[e],i=new Set;return{get value(){return z(t.value,s)},set value(r){const o=t.peek(),h=it(o,s,0,r);h!==o&&(t.value=h)},peek:()=>z(t.peek(),s),subscribe(r){let o=z(t.peek(),s);const h=t.subscribe(f=>{const v=z(f,s);if(!Object.is(v,o)){const C=o;o=v,r(v,C)}});return i.add(h),()=>{h(),i.delete(h)}},subscriberCount:()=>i.size,dispose:()=>{i.forEach(r=>r()),i.clear()},[P]:I.Atom|I.Writable}}var zt=(t,e)=>nt(t,e),kt=t=>e=>nt(t,e);u.AsyncState=F,u.AtomError=N,u.ComputedError=y,u.DEBUG_CONFIG=B,u.EffectError=m,u.SCHEDULER_CONFIG=p,u.SchedulerError=L,u.aeNextTick=Rt,u.atom=Ut,u.atomLens=nt,u.batch=wt,u.composeLens=zt,u.computed=Pt,u.effect=xt,u.getPathValue=z,u.globalScheduler=g,u.isAtom=vt,u.isComputed=Tt,u.isEffect=mt,u.lensFor=kt,u.runtimeDebug=E,u.setDeepValue=it,u.untracked=G});
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=atom-effect.min.js.map
|