@but212/atom-effect 0.13.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- 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 +32 -78
- package/dist/index.mjs +709 -780
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se={ONE_SECOND_MS:1e3},U={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},x={DISPOSED:1,EXECUTING:2},h={DIRTY:1,IDLE:2,PENDING:4,RESOLVED:8,REJECTED:16,RECOMPUTING:32,HAS_ERROR:64},T={SYNC:1,NOTIFICATION_SCHEDULED:2},ie={MAX_SIZE:1e3,WARMUP_SIZE:100},y={MAX_EXECUTIONS_PER_SECOND:1e3,CLEANUP_THRESHOLD:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10},w={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},I=1073741823,ne=20,z=1<<ne-1,l=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",re=Object.freeze([]);class p extends Error{constructor(e,t=null,i=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=i,this.timestamp=new Date}}class b extends p{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class S extends p{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class N extends p{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}const u={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation is pending. No default value provided",COMPUTED_COMPUTATION_FAILED:"Computed computation failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computed computation failed",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Error during individual atom subscriber execution",EFFECT_MUST_BE_FUNCTION:"Effect function must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup function execution failed",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},M=Symbol("debugName"),oe=Symbol("id"),V=Symbol("type"),k=Symbol("noDefaultValue");function he(s){return"dependencies"in s&&Array.isArray(s.dependencies)}let Q=0;function X(s,e,t){if(s._visitedEpoch!==t){if(s._visitedEpoch=t,s===e)throw new b("Indirect circular dependency detected");if(he(s)){const i=s.dependencies;for(let n=0;n<i.length;n++){const r=i[n];r&&X(r,e,t)}}}}const f={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:w.MAX_DEPENDENCIES,warnInfiniteLoop:w.WARN_INFINITE_LOOP,warn(s,e){this.enabled&&s&&console.warn(`[Atom Effect] ${e}`)},checkCircular(s,e){if(s===e)throw new b("Direct circular dependency detected");this.enabled&&(Q++,X(s,e,Q))},attachDebugInfo(s,e,t){if(!this.enabled)return;const i=s;i[M]=`${e}_${t}`,i[oe]=t,i[V]=e},getDebugName(s){if(s!=null&&M in s)return s[M]},getDebugType(s){if(s!=null&&V in s)return s[V]}};let ue=1;const ce=()=>ue++;class H{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this.id=ce()&I}rotatePhase(){return this.version=this.version+1&I,this.version}getShift(e){return this.version-e&I}}class Y extends H{subscribe(e){if(typeof e=="object"&&e!==null&&"execute"in e)return this._addSubscriber(this._getObjSubs(),e);if(typeof e!="function")throw new p(u.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);return this._addSubscriber(this._getFnSubs(),e)}subscriberCount(){return(this._fnSubs?.length??0)+(this._objSubs?.length??0)}_addSubscriber(e,t){if(e.indexOf(t)!==-1)return()=>{};e.push(t);let i=!1;return()=>{if(i)return;i=!0;const n=e.indexOf(t);if(n!==-1){const r=e.length-1;n!==r&&(e[n]=e[r]),e.pop()}}}_notifySubscribers(e,t){const i=this._fnSubs;if(i)for(let r=i.length-1;r>=0;r--)try{const o=i[r];o&&o(e,t)}catch(o){console.error(new p(u.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,o))}const n=this._objSubs;if(n)for(let r=n.length-1;r>=0;r--)try{const o=n[r];o&&o.execute()}catch(o){console.error(new p(u.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,o))}}}class B{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=l?{acquired:0,released:0,rejected:{frozen:0,tooLarge:0,poolFull:0}}:null}acquire(){return l&&this.stats&&this.stats.acquired++,this.pool.pop()??[]}release(e,t){if(!(t&&e===t)){if(Object.isFrozen(e)){l&&this.stats&&this.stats.rejected.frozen++;return}if(e.length>this.maxReusableCapacity){l&&this.stats&&this.stats.rejected.tooLarge++;return}if(this.pool.length>=this.maxPoolSize){l&&this.stats&&this.stats.rejected.poolFull++;return}e.length=0,this.pool.push(e),l&&this.stats&&this.stats.released++}}getStats(){if(!l||!this.stats)return null;const{acquired:e,released:t,rejected:i}=this.stats,n=i.frozen+i.tooLarge+i.poolFull;return{acquired:e,released:t,rejected:i,leaked:e-t-n,poolSize:this.pool.length}}reset(){this.pool.length=0,l&&this.stats&&(this.stats.acquired=0,this.stats.released=0,this.stats.rejected={frozen:0,tooLarge:0,poolFull:0})}}const _=Object.freeze([]),d=Object.freeze([]),a=Object.freeze([]),D=new B,C=new B,E=new B;function $(s){return s!==null&&typeof s=="object"&&"value"in s&&"subscribe"in s&&typeof s.subscribe=="function"}function _e(s){if(f.enabled&&(s==null||typeof s=="object")){const e=f.getDebugType(s);if(e)return e==="computed"}return $(s)&&"invalidate"in s&&typeof s.invalidate=="function"}function ae(s){return s!==null&&typeof s=="object"&&"dispose"in s&&"run"in s&&typeof s.dispose=="function"&&typeof s.run=="function"}function J(s){return s!=null&&typeof s.then=="function"}function le(s){return typeof s=="object"&&s!==null}function fe(s){return(typeof s=="object"||typeof s=="function")&&s!==null&&typeof s.addDependency=="function"}function de(s){return typeof s=="function"&&typeof s.addDependency!="function"}function Ee(s){return le(s)&&typeof s.execute=="function"}function W(s,e,t,i){if(e){if(fe(e)){e.addDependency(s);return}if(de(e)){const n=e;t.indexOf(n)===-1&&t.push(n);return}Ee(e)&&i.indexOf(e)===-1&&i.push(e)}}function pe(s,e,t,i){if(e!==_&&t!==d)for(let r=0;r<e.length;r++){const o=e[r];o&&(o._tempUnsub=t[r])}const n=C.acquire();n.length=s.length;for(let r=0;r<s.length;r++){const o=s[r];o&&(o._tempUnsub?(n[r]=o._tempUnsub,o._tempUnsub=void 0):(f.checkCircular(o,i),n[r]=o.subscribe(i)))}if(e!==_)for(let r=0;r<e.length;r++){const o=e[r];o?._tempUnsub&&(o._tempUnsub(),o._tempUnsub=void 0)}return t!==d&&C.release(t),n}let F=0;function K(){return F=F+1&I||1,F}function ge(){return F}let P=0,j=0,v=!1;function q(){return v?(l&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(v=!0,P=P+1&I,j=0,!0)}function G(){v=!1}function Se(){return v?++j:0}class be{constructor(){this.queueA=[],this.queueB=[],this.queue=this.queueA,this.queueSize=0,this.urgentQueueA=[],this.urgentQueueB=[],this.urgentQueue=this.urgentQueueA,this.urgentQueueSize=0,this._epoch=0,this.isProcessing=!1,this.isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=y.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}schedule(e,t){if(typeof e!="function")throw new N("Scheduler callback must be a function");if(e._nextEpoch!==this._epoch)if(e._nextEpoch=this._epoch,this.isBatching||this.isFlushingSync)this.batchQueue[this.batchQueueSize++]=e;else{const i=this._calculateUrgency(e,t);this.urgentQueue[this.urgentQueueSize]=e,this.queue[this.queueSize]=e,this.urgentQueueSize+=i,this.queueSize+=i^1,this.isProcessing||this.flush()}}_calculateUrgency(e,t){if(!t||e._cachedVersion===void 0)return 0;const i=t.getShift(e._cachedVersion);return z-1-i>>>31&1}flush(){this.isProcessing||this.queueSize===0&&this.urgentQueueSize===0||(this.isProcessing=!0,queueMicrotask(()=>{try{if(this.queueSize===0&&this.urgentQueueSize===0)return;const e=q();this._drainQueue(),e&&G()}finally{this.isProcessing=!1,(this.queueSize>0||this.urgentQueueSize>0)&&!this.isBatching&&this.flush()}}))}flushSync(){this.isFlushingSync=!0;const e=q();try{this._mergeBatchQueue(),this._drainQueue()}finally{this.isFlushingSync=!1,e&&G()}}_mergeBatchQueue(){if(this._epoch++,this.batchQueueSize>0){for(let e=0;e<this.batchQueueSize;e++){const t=this.batchQueue[e];t&&t._nextEpoch!==this._epoch&&(t._nextEpoch=this._epoch,this.queue[this.queueSize++]=t)}this.batchQueueSize=0}}_drainQueue(){let e=0;for(;this.urgentQueueSize>0||this.queueSize>0;){if(++e>this.maxFlushIterations){this._handleFlushOverflow();return}this.urgentQueueSize>0&&this._processUrgentQueue(),this.queueSize>0&&this._processCurrentQueue(),this._mergeBatchQueue()}}_processUrgentQueue(){const e=this.urgentQueue,t=this.urgentQueueSize;this.urgentQueue=this.urgentQueue===this.urgentQueueA?this.urgentQueueB:this.urgentQueueA,this.urgentQueueSize=0,this._epoch++,this._processJobs(e,t)}_processCurrentQueue(){const e=this.queue,t=this.queueSize;this.queue=this.queue===this.queueA?this.queueB:this.queueA,this.queueSize=0,this._epoch++,this._processJobs(e,t)}_handleFlushOverflow(){console.error(new N(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this.queueSize=0,this.queue.length=0,this.urgentQueueSize=0,this.urgentQueue.length=0,this.batchQueueSize=0}_processJobs(e,t){for(let i=0;i<t;i++){const n=e[i];if(n)try{n()}catch(r){console.error(new N("Error occurred during scheduler execution",r))}}e.length=0}startBatch(){this.batchDepth++,this.isBatching=!0}endBatch(){this.batchDepth=Math.max(0,this.batchDepth-1),this.batchDepth===0&&(this.flushSync(),this.isBatching=!1)}setMaxFlushIterations(e){if(e<y.MIN_FLUSH_ITERATIONS)throw new N(`Max flush iterations must be at least ${y.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const R=new be;class ye{constructor(){this.current=null}run(e,t){const i=this.current;this.current=e;try{return t()}finally{this.current=i}}getCurrent(){return this.current}}const m=new ye;function Z(s){if(typeof s!="function")throw new p("Untracked callback must be a function");const e=m.current;m.current=null;try{return s()}finally{m.current=e}}class De extends Y{constructor(e,t){super(),this._fnSubs=null,this._objSubs=null,this._value=e,t&&(this.flags|=T.SYNC),f.attachDebugInfo(this,"atom",this.id)}_getFnSubs(){return this._fnSubs??=[],this._fnSubs}_getObjSubs(){return this._objSubs??=[],this._objSubs}get value(){const e=m.current;return e&&W(this,e,this._getFnSubs(),this._getObjSubs()),this._value}set value(e){if(Object.is(this._value,e))return;const t=this._value;this._value=e,this.rotatePhase(),((this._fnSubs?.length??0)>0||(this._objSubs?.length??0)>0)&&this._scheduleNotification(t)}_scheduleNotification(e){if(this.flags&T.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,this.flags|=T.NOTIFICATION_SCHEDULED),this.flags&T.SYNC&&!R.isBatching){this._flushNotifications();return}this._notifyTask||(this._notifyTask=()=>this._flushNotifications()),R.schedule(this._notifyTask)}_flushNotifications(){if(!(this.flags&T.NOTIFICATION_SCHEDULED))return;const e=this._pendingOldValue,t=this._value;this._pendingOldValue=void 0,this.flags&=-3,this._notifySubscribers(t,e)}peek(){return this._value}dispose(){this._fnSubs=null,this._objSubs=null,this._value=void 0,this._notifyTask=void 0}}function Ie(s,e={}){return new De(s,e.sync??!1)}function O(s,e,t){if(s instanceof TypeError)return new e(`Type error (${t}): ${s.message}`,s);if(s instanceof ReferenceError)return new e(`Reference error (${t}): ${s.message}`,s);if(s instanceof p)return s;const i=s instanceof Error?s.message:String(s),n=s instanceof Error?s:null;return new e(`Unexpected error (${t}): ${i}`,n)}const ee=h.RESOLVED|h.PENDING|h.REJECTED,L=Array(ee+1).fill(U.IDLE);L[h.RESOLVED]=U.RESOLVED;L[h.PENDING]=U.PENDING;L[h.REJECTED]=U.REJECTED;class te extends Y{constructor(e,t={}){if(typeof e!="function")throw new b(u.COMPUTED_MUST_BE_FUNCTION);if(super(),this._fnSubs=null,this._objSubs=null,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this.MAX_ASYNC_RETRIES=3,this._value=void 0,this.flags=h.DIRTY|h.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:k,this._hasDefaultValue=this._defaultValue!==k,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._dependencies=_,this._dependencyVersions=a,this._unsubscribes=d,this._notifyJob=()=>{const i=this._fnSubs;if(i)for(let r=i.length-1;r>=0;r--)try{const o=i[r];o&&o(void 0,void 0)}catch(o){console.error(o)}const n=this._objSubs;if(n)for(let r=n.length-1;r>=0;r--)try{const o=n[r];o&&o.execute()}catch(o){console.error(o)}},this._trackable=Object.assign(()=>this._markDirty(),{addDependency:i=>{}}),f.attachDebugInfo(this,"computed",this.id),f.enabled){const i=this;i.subscriberCount=this.subscriberCount.bind(this),i.isDirty=()=>this._isDirty(),i.dependencies=this._dependencies,i.stateFlags=this._getFlagsAsString()}if(t.lazy===!1)try{this._recompute()}catch{}}_getFnSubs(){return this._fnSubs??=[],this._fnSubs}_getObjSubs(){return this._objSubs??=[],this._objSubs}get value(){return this._registerTracking(),this._computeValue()}peek(){return this._value}get state(){return this._registerTracking(),this._getAsyncState()}get hasError(){if(this._registerTracking(),this._isRejected())return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t&&"hasError"in t&&t.hasError)return!0}return!1}get isValid(){return!this.hasError}get errors(){if(this._registerTracking(),!this.hasError)return re;const e=ge();if(this._errorCacheEpoch===e&&this._cachedErrors!==null)return this._cachedErrors;const t=new Set;this._error&&t.add(this._error);for(let i=0;i<this._dependencies.length;i++){const n=this._dependencies[i];if(n&&"errors"in n){const r=n.errors;for(let o=0;o<r.length;o++){const c=r[o];c&&t.add(c)}}}return this._cachedErrors=Object.freeze([...t]),this._errorCacheEpoch=e,this._cachedErrors}get lastError(){return this._registerTracking(),this._error}get isPending(){return this._registerTracking(),this._isPending()}get isResolved(){return this._registerTracking(),this._isResolved()}invalidate(){this._markDirty(),this._dependencyVersions!==a&&(E.release(this._dependencyVersions),this._dependencyVersions=a),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){if(this._unsubscribes!==d){for(let e=0;e<this._unsubscribes.length;e++){const t=this._unsubscribes[e];t&&t()}C.release(this._unsubscribes),this._unsubscribes=d}this._dependencies!==_&&(D.release(this._dependencies),this._dependencies=_),this._dependencyVersions!==a&&(E.release(this._dependencyVersions),this._dependencyVersions=a),this._fnSubs=null,this._objSubs=null,this.flags=h.DIRTY|h.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID,this._cachedErrors=null,this._errorCacheEpoch=-1}_isDirty(){return(this.flags&h.DIRTY)!==0}_setDirty(){this.flags|=h.DIRTY}_clearDirty(){this.flags&=-2}_isIdle(){return(this.flags&h.IDLE)!==0}_setIdle(){this.flags|=h.IDLE,this.flags&=-29}_isPending(){return(this.flags&h.PENDING)!==0}_setPending(){this.flags|=h.PENDING,this.flags&=-27}_isResolved(){return(this.flags&h.RESOLVED)!==0}_setResolved(){this.flags|=h.RESOLVED,this.flags&=-87}_isRejected(){return(this.flags&h.REJECTED)!==0}_setRejected(){this.flags|=h.REJECTED|h.HAS_ERROR,this.flags&=-15}_isRecomputing(){return(this.flags&h.RECOMPUTING)!==0}_setRecomputing(e){const t=h.RECOMPUTING;this.flags=this.flags&~t|-Number(e)&t}_getAsyncState(){return L[this.flags&ee]}_getFlagsAsString(){const e=[];return this._isDirty()&&e.push("DIRTY"),this._isIdle()&&e.push("IDLE"),this._isPending()&&e.push("PENDING"),this._isResolved()&&e.push("RESOLVED"),this._isRejected()&&e.push("REJECTED"),this._isRecomputing()&&e.push("RECOMPUTING"),e.join(" | ")}_computeValue(){return this._isRecomputing()?this._value:((this._isDirty()||this._isIdle())&&this._recompute(),this._isPending()?this._handlePending():this._isRejected()?this._handleRejected():this._value)}_recompute(){if(this._isRecomputing())return;this._setRecomputing(!0);const e=this._prepareComputationContext();let t=!1;try{const i=m.run(this._trackable,this._fn);this._commitDependencies(e),t=!0,J(i)?this._handleAsyncComputation(i):this._handleSyncResult(i)}catch(i){if(!t)try{this._commitDependencies(e),t=!0}catch(n){this._handleComputationError(n)}this._handleComputationError(i)}finally{this._cleanupContext(e,t),this._setRecomputing(!1)}}_prepareComputationContext(){const e=this._dependencies,t=this._dependencyVersions,i=D.acquire(),n=E.acquire(),r=K(),o={depCount:0},c=g=>{g._lastSeenEpoch!==r&&(g._lastSeenEpoch=r,o.depCount<i.length?(i[o.depCount]=g,n[o.depCount]=g.version):(i.push(g),n.push(g.version)),o.depCount++)},A=this._trackable.addDependency;return this._trackable.addDependency=c,{prevDeps:e,prevVersions:t,nextDeps:i,nextVersions:n,originalAdd:A,state:o}}_commitDependencies(e){const{nextDeps:t,nextVersions:i,state:n,prevDeps:r}=e;t.length=n.depCount,i.length=n.depCount,this._unsubscribes=pe(t,r,this._unsubscribes,this),this._dependencies=t,this._dependencyVersions=i}_cleanupContext(e,t){this._trackable.addDependency=e.originalAdd,t?(e.prevDeps!==_&&D.release(e.prevDeps),e.prevVersions!==a&&E.release(e.prevVersions)):(D.release(e.nextDeps),E.release(e.nextVersions))}_getAggregateShift(){let e=0;const t=this._dependencies,i=this._dependencyVersions;for(let n=0;n<t.length;n++){const r=t[n],o=i[n];r&&o!==void 0&&(e=e+r.getShift(o)&I)}return e}isUrgent(){return this._getAggregateShift()>=z}_handleSyncResult(e){this._finalizeResolution(e)}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._notifyJob(),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=this._promiseId>=this.MAX_PROMISE_ID?1:this._promiseId+1;const t=this._promiseId;e.then(i=>{if(t!==this._promiseId)return;const r=this._captureVersionSnapshot()-this._asyncStartAggregateVersion&I;if(z-1-r>>>31&1){if(this._asyncRetryCount<this.MAX_ASYNC_RETRIES){this._asyncRetryCount++,this._markDirty();return}const c=new b(`Async drift exceeded threshold after ${this.MAX_ASYNC_RETRIES} retries. Dependencies changed too rapidly for stable computation.`);this._handleAsyncRejection(c);return}this._handleAsyncResolution(i)}).catch(i=>{t===this._promiseId&&this._handleAsyncRejection(i)})}_captureVersionSnapshot(){let e=0;const t=this._dependencies;for(let i=0;i<t.length;i++){const n=t[i];n&&(e=e+n.version&I)}return e}_handleAsyncResolution(e){this._finalizeResolution(e),this._notifyJob()}_finalizeResolution(e){(!this._isResolved()||!this._equal(this._value,e))&&this.rotatePhase(),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1}_handleAsyncRejection(e){const t=O(e,b,u.COMPUTED_ASYNC_COMPUTATION_FAILED);if(!this._isRejected()&&this.rotatePhase(),this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(n){console.error(u.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}this._notifyJob()}_handleComputationError(e){const t=O(e,b,u.COMPUTED_COMPUTATION_FAILED);if(this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1),this._onError)try{this._onError(t)}catch(i){console.error(u.CALLBACK_ERROR_IN_ERROR_HANDLER,i)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new b(u.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){if(this._error?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw this._error}execute(){this._markDirty()}_markDirty(){this._isRecomputing()||this._isDirty()||(this._setDirty(),this._notifyJob())}_registerTracking(){W(this,m.getCurrent(),this._getFnSubs(),this._getObjSubs())}}Object.freeze(te.prototype);function Ce(s,e={}){return new te(s,e)}class me extends H{constructor(e,t={}){super(),this.run=()=>{if(this.isDisposed)throw new S(u.EFFECT_MUST_BE_FUNCTION);this._dependencyVersions!==a&&(E.release(this._dependencyVersions),this._dependencyVersions=a),this.execute()},this.dispose=()=>{if(!this.isDisposed){if(this._setDisposed(),this._safeCleanup(),this._unsubscribes!==d){for(let n=0;n<this._unsubscribes.length;n++){const r=this._unsubscribes[n];r&&r()}C.release(this._unsubscribes),this._unsubscribes=d}this._dependencies!==_&&(D.release(this._dependencies),this._dependencies=_),this._dependencyVersions!==a&&(E.release(this._dependencyVersions),this._dependencyVersions=a)}},this.addDependency=n=>{if(this.isExecuting&&this._nextDeps&&this._nextUnsubs&&this._nextVersions){const r=this._currentEpoch;if(n._lastSeenEpoch===r)return;n._lastSeenEpoch=r,this._nextDeps.push(n),this._nextVersions.push(n.version),n._tempUnsub?(this._nextUnsubs.push(n._tempUnsub),n._tempUnsub=void 0):this._subscribeTo(n)}},this.execute=()=>{if(this.isDisposed||this.isExecuting||!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const n=this._prepareEffectExecutionContext();let r=!1;try{const o=m.run(this,this._fn);this._commitEffect(n),r=!0,this._checkLoopWarnings(),J(o)?o.then(c=>{!this.isDisposed&&typeof c=="function"&&(this._cleanup=c)}).catch(c=>{this._handleExecutionError(c)}):this._cleanup=typeof o=="function"?o:null}catch(o){r=!0,this._handleExecutionError(o),this._cleanup=null}finally{this._cleanupEffect(n,r),this._setExecuting(!1)}},this._cleanup=null,this._dependencies=_,this._dependencyVersions=a,this._unsubscribes=d,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._onError=t.onError??null,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??y.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??y.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._historyPtr=0;const i=Number.isFinite(this._maxExecutions);this._historyCapacity=i?Math.min(this._maxExecutions+1,y.MAX_EXECUTIONS_PER_SECOND+1):0,this._history=l&&i&&this._historyCapacity>0?new Array(this._historyCapacity).fill(0):null,this._executionCount=0,f.attachDebugInfo(this,"effect",this.id)}_prepareEffectExecutionContext(){const e=this._dependencies,t=this._dependencyVersions,i=this._unsubscribes,n=D.acquire(),r=E.acquire(),o=C.acquire(),c=K();if(e!==_&&i!==d)for(let A=0;A<e.length;A++){const g=e[A];g&&(g._tempUnsub=i[A])}return this._nextDeps=n,this._nextVersions=r,this._nextUnsubs=o,this._currentEpoch=c,{prevDeps:e,prevVersions:t,prevUnsubs:i,nextDeps:n,nextVersions:r,nextUnsubs:o}}_commitEffect(e){const t=e.nextDeps.length;e.nextDeps.length=t,e.nextVersions.length=t,this._dependencies=e.nextDeps,this._dependencyVersions=e.nextVersions,this._unsubscribes=e.nextUnsubs}_cleanupEffect(e,t){if(this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,t){if(e.prevDeps!==_){for(let i=0;i<e.prevDeps.length;i++){const n=e.prevDeps[i];n?._tempUnsub&&(n._tempUnsub(),n._tempUnsub=void 0)}D.release(e.prevDeps)}e.prevUnsubs!==d&&C.release(e.prevUnsubs),e.prevVersions!==a&&E.release(e.prevVersions)}else{D.release(e.nextDeps),E.release(e.nextVersions);for(let i=0;i<e.nextUnsubs.length;i++)e.nextUnsubs[i]?.();if(C.release(e.nextUnsubs),e.prevDeps!==_)for(let i=0;i<e.prevDeps.length;i++){const n=e.prevDeps[i];n&&(n._tempUnsub=void 0)}}}_subscribeTo(e){try{const t=e.subscribe(()=>{this._trackModifications&&this.isExecuting&&(e._modifiedAtEpoch=this._currentEpoch),this._sync?this.execute():R.schedule(this.execute)});this._nextUnsubs&&this._nextUnsubs.push(t)}catch(t){console.error(O(t,S,u.EFFECT_EXECUTION_FAILED)),this._nextUnsubs&&this._nextUnsubs.push(()=>{})}}get isDisposed(){return(this.flags&x.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&x.EXECUTING)!==0}_setDisposed(){this.flags|=x.DISPOSED}_setExecuting(e){const t=x.EXECUTING;this.flags=this.flags&~t|-Number(e)&t}_safeCleanup(){if(this._cleanup){try{this._cleanup()}catch(e){console.error(O(e,S,u.EFFECT_CLEANUP_FAILED))}this._cleanup=null}}_checkInfiniteLoop(){if(this._lastFlushEpoch!==P&&(this._lastFlushEpoch=P,this._executionsInEpoch=0),this._executionsInEpoch++,this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),Se()>y.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,this._history&&this._maxExecutions>0){const e=Date.now(),t=this._historyPtr,i=this._historyCapacity;this._history[t]=e;const n=(t+1)%i,r=this._history[n]??0;if(this._historyPtr=n,r>0&&e-r<se.ONE_SECOND_MS){const o=new S(`Effect executed ${i} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(o),this._onError&&this._onError(o),l)throw o}}}_throwInfiniteLoopError(e){const t=new S(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${j}`);throw this.dispose(),console.error(t),t}_shouldExecute(){if(this._dependencies===_||this._dependencyVersions===a)return!0;for(let e=0;e<this._dependencies.length;e++){const t=this._dependencies[e];if(t){if("value"in t)try{Z(()=>t.value)}catch{return!0}if(t.version!==this._dependencyVersions[e])return!0}}return!1}_handleExecutionError(e){const t=O(e,S,u.EFFECT_EXECUTION_FAILED);console.error(t),this._onError&&this._onError(t)}_checkLoopWarnings(){if(this._trackModifications&&f.enabled){const e=this._dependencies;for(let t=0;t<e.length;t++){const i=e[t];i&&i._modifiedAtEpoch===this._currentEpoch&&f.warn(!0,`Effect is reading a dependency (${f.getDebugName(i)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function Ae(s,e={}){if(typeof s!="function")throw new S(u.EFFECT_MUST_BE_FUNCTION);const t=new me(s,e);return t.execute(),t}function Re(s){if(typeof s!="function")throw new p("Batch callback must be a function");R.startBatch();try{return s()}finally{R.endBatch()}}exports.AsyncState=U;exports.AtomError=p;exports.ComputedError=b;exports.DEBUG_CONFIG=w;exports.DEBUG_RUNTIME=f;exports.EffectError=S;exports.POOL_CONFIG=ie;exports.SCHEDULER_CONFIG=y;exports.SchedulerError=N;exports.atom=Ie;exports.batch=Re;exports.computed=Ce;exports.effect=Ae;exports.isAtom=$;exports.isComputed=_e;exports.isEffect=ae;exports.scheduler=R;exports.untracked=Z;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const oe={ONE_SECOND_MS:1e3},v={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},g={DISPOSED:1,HAS_FN_SUBS:2,HAS_OBJ_SUBS:4},S={...g,EXECUTING:8},u={...g,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512},I={...g,SYNC:8,NOTIFICATION_SCHEDULED:16},ce={MAX_SIZE:1e3,WARMUP_SIZE:100},R={MAX_EXECUTIONS_PER_SECOND:1e3,CLEANUP_THRESHOLD:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10,BATCH_QUEUE_SHRINK_THRESHOLD:1e3},H={MAX_DEPENDENCIES:1e3,WARN_INFINITE_LOOP:!0},x=1073741823,E=typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",he=Object.freeze([]);class D extends Error{constructor(e,t=null,s=!0){super(e),this.name="AtomError",this.cause=t,this.recoverable=s,this.timestamp=new Date}}class C extends D{constructor(e,t=null){super(e,t,!0),this.name="ComputedError"}}class T extends D{constructor(e,t=null){super(e,t,!1),this.name="EffectError"}}class F extends D{constructor(e,t=null){super(e,t,!1),this.name="SchedulerError"}}const l={COMPUTED_MUST_BE_FUNCTION:"Computed function must be a function",COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber listener must be a function or Subscriber object",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation is pending. No default value provided",COMPUTED_COMPUTATION_FAILED:"Computed computation failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computed computation failed",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected during computation",COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED:"Failed to subscribe to dependency",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscription listener must be a function or Subscriber object",ATOM_SUBSCRIBER_EXECUTION_FAILED:"Error occurred while executing atom subscribers",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Error during individual atom subscriber execution",EFFECT_MUST_BE_FUNCTION:"Effect function must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup function execution failed",EFFECT_DISPOSED:"Cannot run a disposed effect",LARGE_DEPENDENCY_GRAPH:i=>`Large dependency graph detected: ${i} dependencies`,UNSUBSCRIBE_NON_EXISTENT:"Attempted to unsubscribe a non-existent listener",CALLBACK_ERROR_IN_ERROR_HANDLER:"Error occurred during onError callback execution"},w=Symbol("debugName"),ue=Symbol("id"),k=Symbol("type"),Y=Symbol("noDefaultValue");function _e(i){return"dependencies"in i&&Array.isArray(i.dependencies)}let q=0;function K(i,e,t){if(i._visitedEpoch!==t){if(i._visitedEpoch=t,i===e)throw new C("Indirect circular dependency detected");if(_e(i)){const s=i.dependencies;for(let n=0;n<s.length;n++){const r=s[n];r&&K(r,e,t)}}}}const b={enabled:typeof process<"u"&&process.env?.NODE_ENV==="development",maxDependencies:H.MAX_DEPENDENCIES,warnInfiniteLoop:H.WARN_INFINITE_LOOP,warn(i,e){this.enabled&&i&&console.warn(`[Atom Effect] ${e}`)},checkCircular(i,e){if(i===e)throw new C("Direct circular dependency detected");this.enabled&&(q++,K(i,e,q))},attachDebugInfo(i,e,t){if(!this.enabled)return;const s=i;s[w]=`${e}_${t}`,s[ue]=t,s[k]=e},getDebugName(i){if(i!=null&&w in i)return i[w]},getDebugType(i){if(i!=null&&k in i)return i[k]}};let le=1;const ae=()=>le++;class W{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=-1,this._modifiedAtEpoch=-1,this._visitedEpoch=-1,this.id=ae()&x,this._tempUnsub=void 0}getShift(e){return this.version-e&x}}class Z extends W{subscribe(e){if(typeof e=="function")return this._addSubscriber(this._fnSubs,e,g.HAS_FN_SUBS);if(e!==null&&typeof e=="object"&&"execute"in e)return this._addSubscriber(this._objSubs,e,g.HAS_OBJ_SUBS);throw new D(l.ATOM_SUBSCRIBER_MUST_BE_FUNCTION)}subscriberCount(){return this._fnSubs.length+this._objSubs.length}_addSubscriber(e,t,s){if(e.indexOf(t)!==-1)return E&&console.warn("Attempted to subscribe the same listener twice. Ignoring duplicate subscription."),()=>{};e.push(t),this.flags|=s;let r=!1;return()=>{if(r)return;r=!0;const o=e.indexOf(t);if(o!==-1){const c=e.pop();o<e.length&&(e[o]=c),this.flags&=~(e.length===0?s:0)}}}_notifySubscribers(e,t){const s=this.flags,n=g.HAS_FN_SUBS|g.HAS_OBJ_SUBS;if(s&n){if(s&g.HAS_FN_SUBS){const r=this._fnSubs;for(let o=0,c=r.length;o<c;o++){const h=r[o];if(h)try{h(e,t)}catch(_){console.error(new D(l.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,_))}}}if(s&g.HAS_OBJ_SUBS){const r=this._objSubs;for(let o=0,c=r.length;o<c;o++){const h=r[o];if(h)try{h.execute()}catch(_){console.error(new D(l.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED,_))}}}}}}class fe{constructor(){this.acquired=0,this.released=0,this.rejected=new Ee}}class Ee{constructor(){this.frozen=0,this.tooLarge=0,this.poolFull=0}}class j{constructor(){this.pool=[],this.maxPoolSize=50,this.maxReusableCapacity=256,this.stats=E?new fe:null}acquire(){const e=this.stats;return E&&e&&e.acquired++,this.pool.pop()??[]}release(e,t){if(t&&e===t||Object.isFrozen(e)){const c=this.stats;E&&c&&e!==t&&c.rejected.frozen++;return}const s=e.length,n=this.pool,r=n.length;if(s>this.maxReusableCapacity||r>=this.maxPoolSize){const c=this.stats;E&&c&&(s>this.maxReusableCapacity?c.rejected.tooLarge++:c.rejected.poolFull++);return}e.length=0,n.push(e);const o=this.stats;E&&o&&o.released++}getStats(){const e=this.stats;if(!E||!e)return null;const{acquired:t,released:s,rejected:n}=e,r=n.frozen+n.tooLarge+n.poolFull;return{acquired:t,released:s,rejected:{frozen:n.frozen,tooLarge:n.tooLarge,poolFull:n.poolFull},leaked:t-s-r,poolSize:this.pool.length}}reset(){this.pool.length=0;const e=this.stats;E&&e&&(e.acquired=0,e.released=0,e.rejected.frozen=0,e.rejected.tooLarge=0,e.rejected.poolFull=0)}}const d=Object.freeze([]),A=Object.freeze([]),p=Object.freeze([]),y=new j,m=new j,N=new j;function O(i,e,t,s){if(e!=null){if((typeof e=="object"||typeof e=="function")&&typeof e.addDependency=="function"){e.addDependency(i);return}if(typeof e=="function"){const n=e;t.indexOf(n)===-1&&(t.push(n),i.flags|=g.HAS_FN_SUBS);return}typeof e=="object"&&typeof e.execute=="function"&&s.indexOf(e)===-1&&(s.push(e),i.flags|=g.HAS_OBJ_SUBS)}}function Q(i,e,t,s){const n=i.length,r=e.length,o=e!==d&&r>0;if(o)for(let h=0;h<r;h++){const _=e[h];_&&(_._tempUnsub=t[h])}const c=m.acquire();c.length=n;for(let h=0;h<n;h++){const _=i[h];if(!_)continue;const a=_._tempUnsub;a?(c[h]=a,_._tempUnsub=void 0):(b.checkCircular(_,s),c[h]=_.subscribe(s))}if(o)for(let h=0;h<r;h++){const _=e[h];if(_){const a=_._tempUnsub;a&&(a(),_._tempUnsub=void 0)}}return t!==A&&m.release(t),c}let L=0;function ee(){return L=L+1&x||1,L}function de(){return L}let G=0,z=0,M=!1;function J(){return M?(E&&console.warn("Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"),!1):(M=!0,G=G+1&x||1,z=0,!0)}function $(){M=!1}function pe(){return M?++z:0}class Se{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this.isProcessing=!1,this.isBatching=!1,this.batchDepth=0,this.batchQueue=[],this.batchQueueSize=0,this.isFlushingSync=!1,this.maxFlushIterations=R.MAX_FLUSH_ITERATIONS}get phase(){return this.isProcessing||this.isFlushingSync?2:this.isBatching?1:0}get queueSize(){return this._size}schedule(e){if(E&&typeof e!="function")throw new F("Scheduler callback must be a function");const t=this._epoch;if(e._nextEpoch!==t){if(e._nextEpoch=t,this.isBatching||this.isFlushingSync){this.batchQueue[this.batchQueueSize++]=e;return}this._queueBuffer[this._bufferIndex][this._size++]=e,this.isProcessing||this.flush()}}flush(){this.isProcessing||this._size===0||(this.isProcessing=!0,queueMicrotask(()=>{try{if(this._size===0)return;const e=J();this._drainQueue(),e&&$()}finally{this.isProcessing=!1,this._size>0&&!this.isBatching&&this.flush()}}))}flushSync(){this.isFlushingSync=!0;const e=J();try{this._mergeBatchQueue(),this._drainQueue()}finally{this.isFlushingSync=!1,e&&$()}}_mergeBatchQueue(){const e=this.batchQueueSize;if(e===0)return;const t=++this._epoch,s=this.batchQueue,n=this._queueBuffer[this._bufferIndex];let r=this._size;for(let o=0;o<e;o++){const c=s[o];c._nextEpoch!==t&&(c._nextEpoch=t,n[r++]=c)}this._size=r,this.batchQueueSize=0,s.length>R.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let e=0;const t=this.maxFlushIterations;for(;this._size>0;){if(++e>t){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const e=this._bufferIndex,t=this._queueBuffer[e],s=this._size,n=e^1;this._bufferIndex=n,this._size=0,this._epoch++,this._processJobs(t,s)}_handleFlushOverflow(){console.error(new F(`Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`)),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this.batchQueueSize=0}_processJobs(e,t){for(let s=0;s<t;s++)try{e[s]()}catch(n){console.error(new F("Error occurred during scheduler execution",n))}e.length=0}startBatch(){this.batchDepth++,this.isBatching=!0}endBatch(){if(this.batchDepth===0){E&&console.warn("endBatch() called without matching startBatch(). Ignoring.");return}this.batchDepth--,this.batchDepth===0&&(this.flushSync(),this.isBatching=!1)}setMaxFlushIterations(e){if(e<R.MIN_FLUSH_ITERATIONS)throw new F(`Max flush iterations must be at least ${R.MIN_FLUSH_ITERATIONS}`);this.maxFlushIterations=e}}const U=new Se;class ge{constructor(){this.current=null}run(e,t){const s=this.current;this.current=e;try{return t()}finally{this.current=s}}getCurrent(){return this.current}}const f=new ge;function te(i){if(typeof i!="function")throw new D("Untracked callback must be a function");const e=f.current;f.current=null;try{return i()}finally{f.current=e}}class be extends Z{constructor(e,t){super(),this._value=e,this._pendingOldValue=void 0,this._notifyTask=void 0,this._fnSubs=[],this._objSubs=[],t&&(this.flags|=I.SYNC),b.attachDebugInfo(this,"atom",this.id)}get value(){const e=f.current;return e&&O(this,e,this._fnSubs,this._objSubs),this._value}set value(e){const t=this._value;if(Object.is(t,e))return;this._value=e,this.version=this.version+1&x;const s=this.flags,n=I.HAS_FN_SUBS|I.HAS_OBJ_SUBS;s&n&&this._scheduleNotification(t)}_scheduleNotification(e){let t=this.flags;if(t&I.NOTIFICATION_SCHEDULED||(this._pendingOldValue=e,this.flags=t|=I.NOTIFICATION_SCHEDULED),t&I.SYNC&&!U.isBatching){this._flushNotifications();return}let s=this._notifyTask;s||(s=this._notifyTask=()=>this._flushNotifications()),U.schedule(s)}_flushNotifications(){const e=this.flags;if(!(e&I.NOTIFICATION_SCHEDULED)||e&I.DISPOSED)return;const t=this._pendingOldValue,s=this._value;this._pendingOldValue=void 0,this.flags&=-17,this._notifySubscribers(s,t)}peek(){return this._value}dispose(){this.flags&I.DISPOSED||(this._fnSubs=[],this._objSubs=[],this.flags|=I.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._notifyTask=void 0)}}function Ie(i,e={}){return new be(i,e.sync??!1)}function P(i,e,t){if(i instanceof TypeError)return new e(`Type error (${t}): ${i.message}`,i);if(i instanceof ReferenceError)return new e(`Reference error (${t}): ${i.message}`,i);if(i instanceof D)return i;const s=i instanceof Error?i.message:String(i),n=i instanceof Error?i:null;return new e(`Unexpected error (${t}): ${s}`,n)}function se(i){return i!==null&&typeof i=="object"&&"value"in i&&"subscribe"in i&&typeof i.subscribe=="function"}function De(i){if(b.enabled&&i!=null&&typeof i=="object"){const e=b.getDebugType(i);if(e)return e==="computed"}return se(i)&&"invalidate"in i&&typeof i.invalidate=="function"}function Ce(i){return i!==null&&typeof i=="object"&&"dispose"in i&&"run"in i&&typeof i.dispose=="function"&&typeof i.run=="function"}function ie(i){return i!=null&&typeof i.then=="function"}const ne=u.RESOLVED|u.PENDING|u.REJECTED,V=Array(ne+1).fill(v.IDLE);V[u.RESOLVED]=v.RESOLVED;V[u.PENDING]=v.PENDING;V[u.REJECTED]=v.REJECTED;class Ne{constructor(e){this._owner=e,this._epoch=-1,this._nextDeps=d,this._nextVersions=p,this._depCount=0}execute(){this._owner._markDirty()}addDependency(e){if(e._lastSeenEpoch===this._epoch)return;e._lastSeenEpoch=this._epoch;const t=this._depCount,s=this._nextDeps,n=this._nextVersions;t<s.length?(s[t]=e,n[t]=e.version):(s.push(e),n.push(e.version)),this._depCount=t+1}reset(){this._epoch=-1,this._nextDeps=d,this._nextVersions=p,this._depCount=0}}class re extends Z{constructor(e,t={}){if(typeof e!="function")throw new C(l.COMPUTED_MUST_BE_FUNCTION);if(super(),this.MAX_ASYNC_RETRIES=3,this._value=void 0,this.flags=u.DIRTY|u.IDLE,this._error=null,this._promiseId=0,this._equal=t.equal??Object.is,this._fn=e,this._defaultValue="defaultValue"in t?t.defaultValue:Y,this._hasDefaultValue=this._defaultValue!==Y,this._onError=t.onError??null,this.MAX_PROMISE_ID=Number.MAX_SAFE_INTEGER-1,this._fnSubs=[],this._objSubs=[],this._dependencies=d,this._dependencyVersions=p,this._unsubscribes=A,this._cachedErrors=null,this._errorCacheEpoch=-1,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._trackable=new Ne(this),b.attachDebugInfo(this,"computed",this.id),b.enabled){const s=this;s.subscriberCount=this.subscriberCount.bind(this),s.isDirty=()=>(this.flags&u.DIRTY)!==0,s.dependencies=this._dependencies,s.stateFlags=""}if(t.lazy===!1)try{this._recompute()}catch{}}get value(){const e=f.current;e&&O(this,e,this._fnSubs,this._objSubs);const t=this.flags;if(t&u.RECOMPUTING){if(this._hasDefaultValue)return this._defaultValue;throw new C(l.COMPUTED_CIRCULAR_DEPENDENCY)}t&(u.DIRTY|u.IDLE)&&this._recompute();const s=this.flags;return s&u.PENDING?this._handlePending():s&u.REJECTED?this._handleRejected():this._value}peek(){return this._value}get state(){const e=f.current;return e&&O(this,e,this._fnSubs,this._objSubs),V[this.flags&ne]}get hasError(){const e=f.current;if(e&&O(this,e,this._fnSubs,this._objSubs),this.flags&(u.REJECTED|u.HAS_ERROR))return!0;const s=this._dependencies;for(let n=0,r=s.length;n<r;n++){const o=s[n];if(o&&o.flags&u.HAS_ERROR)return!0}return!1}get isValid(){return!this.hasError}get errors(){const e=f.current;if(e&&O(this,e,this._fnSubs,this._objSubs),!this.hasError)return he;const t=de();if(this._errorCacheEpoch===t&&this._cachedErrors!==null)return this._cachedErrors;const s=new Set;this._error&&s.add(this._error);const n=this._dependencies;for(let o=0,c=n.length;o<c;o++){const h=n[o];if(h&&"errors"in h){const _=h.errors;for(let a=0,B=_.length;a<B;a++){const X=_[a];X&&s.add(X)}}}const r=Object.freeze([...s]);return this._cachedErrors=r,this._errorCacheEpoch=t,r}get lastError(){const e=f.current;return e&&O(this,e,this._fnSubs,this._objSubs),this._error}get isPending(){const e=f.current;return e&&O(this,e,this._fnSubs,this._objSubs),(this.flags&u.PENDING)!==0}get isResolved(){const e=f.current;return e&&O(this,e,this._fnSubs,this._objSubs),(this.flags&u.RESOLVED)!==0}invalidate(){this._markDirty();const e=this._dependencyVersions;e!==p&&(N.release(e),this._dependencyVersions=p),this._errorCacheEpoch=-1,this._cachedErrors=null}dispose(){const e=this._unsubscribes;if(e!==A){for(let n=0,r=e.length;n<r;n++){const o=e[n];o&&o()}m.release(e),this._unsubscribes=A}const t=this._dependencies;t!==d&&(y.release(t),this._dependencies=d);const s=this._dependencyVersions;s!==p&&(N.release(s),this._dependencyVersions=p),this._fnSubs=[],this._objSubs=[],this.flags=u.DISPOSED|u.DIRTY|u.IDLE,this._error=null,this._value=void 0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID,this._cachedErrors=null,this._errorCacheEpoch=-1}_clearDirty(){this.flags&=-9}_setPending(){this.flags=(this.flags|u.PENDING)&-209}_isResolved(){return(this.flags&u.RESOLVED)!==0}_setResolved(){this.flags=(this.flags|u.RESOLVED)&-689}_isRejected(){return(this.flags&u.REJECTED)!==0}_setRejected(){this.flags=this.flags&-113|(u.REJECTED|u.HAS_ERROR)}_setRecomputing(e){const t=u.RECOMPUTING;this.flags=this.flags&~t|(e?-1:0)&t}_recompute(){if(this.flags&u.RECOMPUTING)return;this._setRecomputing(!0);const e=this._trackable,t=this._dependencies,s=this._dependencyVersions;e._epoch=ee(),e._nextDeps=y.acquire(),e._nextVersions=N.acquire(),e._depCount=0;let n=!1;try{const r=f.run(e,this._fn),o=e._nextDeps,c=e._nextVersions,h=e._depCount;o.length=h,c.length=h,this._unsubscribes=Q(o,t,this._unsubscribes,this),this._dependencies=o,this._dependencyVersions=c,n=!0,ie(r)?this._handleAsyncComputation(r):this._finalizeResolution(r)}catch(r){let o=r;if(!n)try{const c=e._nextDeps,h=e._nextVersions,_=e._depCount;c.length=_,h.length=_,this._unsubscribes=Q(c,t,this._unsubscribes,this),this._dependencies=c,this._dependencyVersions=h,n=!0}catch(c){o=c}this._handleComputationError(o)}finally{n?(t!==d&&y.release(t),s!==p&&N.release(s)):(y.release(e._nextDeps),N.release(e._nextVersions)),e.reset(),this._setRecomputing(!1)}}_handleAsyncComputation(e){this._setPending(),this._clearDirty(),this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%this.MAX_PROMISE_ID;const t=this._promiseId;e.then(s=>{if(t!==this._promiseId)return;if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){if(this._asyncRetryCount<this.MAX_ASYNC_RETRIES){this._asyncRetryCount++,this._markDirty();return}const o=new C(`Async drift exceeded threshold after ${this.MAX_ASYNC_RETRIES} retries.`);this._handleAsyncRejection(o);return}this._finalizeResolution(s),this._notifySubscribers(s,void 0)}).catch(s=>{t===this._promiseId&&this._handleAsyncRejection(s)})}_captureVersionSnapshot(){let e=0;const t=this._dependencies;for(let s=0,n=t.length;s<n;s++){const r=t[s];if(r){const o=r.version;e=((e<<5)-e|0)+o&x}}return e}_handleAsyncRejection(e){const t=P(e,C,l.COMPUTED_ASYNC_COMPUTATION_FAILED);this.flags&u.REJECTED||(this.version=this.version+1&x),this._error=t,this._setRejected(),this._clearDirty();const s=this._onError;if(s)try{s(t)}catch(n){console.error(l.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}this._notifySubscribers(void 0,void 0)}_finalizeResolution(e){(!(this.flags&u.RESOLVED)||!this._equal(this._value,e))&&(this.version=this.version+1&x),this._value=e,this._clearDirty(),this._setResolved(),this._error=null,this._setRecomputing(!1),this._cachedErrors=null,this._errorCacheEpoch=-1}_handleComputationError(e){const t=P(e,C,l.COMPUTED_COMPUTATION_FAILED);this._error=t,this._setRejected(),this._clearDirty(),this._setRecomputing(!1);const s=this._onError;if(s)try{s(t)}catch(n){console.error(l.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}throw t}_handlePending(){if(this._hasDefaultValue)return this._defaultValue;throw new C(l.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}_handleRejected(){const e=this._error;if(e?.recoverable&&this._hasDefaultValue)return this._defaultValue;throw e}execute(){this._markDirty()}_markDirty(){const e=this.flags;e&(u.RECOMPUTING|u.DIRTY)||(this.flags=e|u.DIRTY,this._notifySubscribers(void 0,void 0))}}Object.freeze(re.prototype);function Re(i,e={}){return new re(i,e)}class Oe extends W{constructor(e,t={}){super(),this._cleanup=null,this._dependencies=d,this._dependencyVersions=p,this._unsubscribes=A,this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null,this._executeTask=void 0,this._onError=t.onError??null,this._currentEpoch=-1,this._lastFlushEpoch=-1,this._executionsInEpoch=0,this._fn=e,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??R.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??R.MAX_EXECUTIONS_PER_EFFECT,this._trackModifications=t.trackModifications??!1,this._executionCount=0,this._historyPtr=0;const s=Number.isFinite(this._maxExecutions),n=s?Math.min(this._maxExecutions+1,R.MAX_EXECUTIONS_PER_SECOND+1):0;this._historyCapacity=n,this._history=E&&s&&n>0?new Array(n).fill(0):null,this._execId=0,b.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&S.DISPOSED)throw new T(l.EFFECT_DISPOSED);this.execute(!0)}dispose(){const e=this.flags;if(e&S.DISPOSED)return;this.flags=e|S.DISPOSED,this._safeCleanup();const t=this._unsubscribes;if(t!==A){for(let r=0,o=t.length;r<o;r++){const c=t[r];c&&c()}m.release(t),this._unsubscribes=A}const s=this._dependencies;s!==d&&(y.release(s),this._dependencies=d);const n=this._dependencyVersions;n!==p&&(N.release(n),this._dependencyVersions=p),this._executeTask=void 0}addDependency(e){if(!(this.flags&S.EXECUTING))return;const s=this._currentEpoch;if(e._lastSeenEpoch===s)return;e._lastSeenEpoch=s;const n=this._nextDeps,r=this._nextVersions,o=this._nextUnsubs;if(!n||!r||!o)return;n.push(e),r.push(e.version);const c=e._tempUnsub;c?(o.push(c),e._tempUnsub=void 0):this._subscribeTo(e)}execute(e=!1){if(this.flags&(S.DISPOSED|S.EXECUTING)||!e&&!this._shouldExecute())return;this._checkInfiniteLoop(),this._setExecuting(!0),this._safeCleanup();const s=this._prepareEffectExecutionContext();let n=!1;try{const r=f.run(this,this._fn),o=s.nextDeps.length;s.nextDeps.length=o,s.nextVersions.length=o,this._dependencies=s.nextDeps,this._dependencyVersions=s.nextVersions,this._unsubscribes=s.nextUnsubs,n=!0,this._checkLoopWarnings();const c=++this._execId;ie(r)?r.then(h=>{const _=c!==this._execId,a=this.flags&S.DISPOSED;if(_||a){if(typeof h=="function")try{h()}catch(B){this._handleExecutionError(B,l.EFFECT_CLEANUP_FAILED)}return}typeof h=="function"&&(this._cleanup=h)}).catch(h=>{c===this._execId&&this._handleExecutionError(h)}):this._cleanup=typeof r=="function"?r:null}catch(r){n=!0,this._handleExecutionError(r),this._cleanup=null}finally{this._cleanupEffect(s,n),this._setExecuting(!1)}}_prepareEffectExecutionContext(){const e=this._dependencies,t=this._dependencyVersions,s=this._unsubscribes,n=y.acquire(),r=N.acquire(),o=m.acquire(),c=ee();if(e!==d)for(let h=0,_=e.length;h<_;h++){const a=e[h];a&&(a._tempUnsub=s[h])}return this._nextDeps=n,this._nextVersions=r,this._nextUnsubs=o,this._currentEpoch=c,{prevDeps:e,prevVersions:t,prevUnsubs:s,nextDeps:n,nextVersions:r,nextUnsubs:o}}_cleanupEffect(e,t){this._nextDeps=null,this._nextVersions=null,this._nextUnsubs=null;const s=e.prevDeps;if(t){if(s!==d){for(let n=0,r=s.length;n<r;n++){const o=s[n],c=o?o._tempUnsub:void 0;c&&(c(),o&&(o._tempUnsub=void 0))}y.release(s)}e.prevUnsubs!==A&&m.release(e.prevUnsubs),e.prevVersions!==p&&N.release(e.prevVersions)}else{y.release(e.nextDeps),N.release(e.nextVersions);const n=e.nextUnsubs;for(let r=0,o=n.length;r<o;r++)n[r]?.();if(m.release(n),s!==d)for(let r=0,o=s.length;r<o;r++){const c=s[r];c&&(c._tempUnsub=void 0)}}}_subscribeTo(e){try{const t=e.subscribe(()=>{if(this._trackModifications&&this.flags&S.EXECUTING&&(e._modifiedAtEpoch=this._currentEpoch),this._sync){this.execute();return}let n=this._executeTask;n||(n=this._executeTask=()=>this.execute()),U.schedule(n)}),s=this._nextUnsubs;s&&s.push(t)}catch(t){console.error(P(t,T,l.EFFECT_EXECUTION_FAILED));const s=this._nextUnsubs;s&&s.push(()=>{})}}get isDisposed(){return(this.flags&S.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&S.EXECUTING)!==0}_setExecuting(e){const t=S.EXECUTING;this.flags=this.flags&~t|(e?-1:0)&t}_safeCleanup(){const e=this._cleanup;if(e){try{e()}catch(t){this._handleExecutionError(t,l.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoop(){const e=G;this._lastFlushEpoch!==e&&(this._lastFlushEpoch=e,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),pe()>R.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++;const s=this._history;if(s){const n=Date.now(),r=this._historyPtr,o=this._historyCapacity;s[r]=n;const c=(r+1)%o;this._historyPtr=c;const h=s[c]??0;if(h>0&&n-h<oe.ONE_SECOND_MS){const _=new T(`Effect executed ${o} times within 1 second. Infinite loop suspected`);if(this.dispose(),console.error(_),this._onError&&this._onError(_),E)throw _;return}}}_throwInfiniteLoopError(e){const t=new T(`Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${z}`);throw this.dispose(),console.error(t),t}_shouldExecute(){const e=this._dependencies;if(e.length===0)return!0;const t=this._dependencyVersions;for(let s=0,n=e.length;s<n;s++){const r=e[s];if(r){if(r.version!==t[s])return!0;if("value"in r)try{te(()=>r.value)}catch{return!0}}}return!1}_handleExecutionError(e,t=l.EFFECT_EXECUTION_FAILED){const s=P(e,T,t);console.error(s);const n=this._onError;if(n)try{n(s)}catch(r){console.error(P(r,T,l.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_checkLoopWarnings(){if(this._trackModifications&&b.enabled){const e=this._dependencies,t=this._currentEpoch;for(let s=0,n=e.length;s<n;s++){const r=e[s];r&&r._modifiedAtEpoch===t&&b.warn(!0,`Effect is reading a dependency (${b.getDebugName(r)||"unknown"}) that it just modified. Infinite loop may occur`)}}}}function Te(i,e={}){if(typeof i!="function")throw new T(l.EFFECT_MUST_BE_FUNCTION);const t=new Oe(i,e);return t.execute(),t}function Ae(i){if(typeof i!="function")throw new D("Batch callback must be a function");U.startBatch();try{return i()}finally{U.endBatch()}}exports.AsyncState=v;exports.AtomError=D;exports.ComputedError=C;exports.DEBUG_CONFIG=H;exports.DEBUG_RUNTIME=b;exports.EffectError=T;exports.POOL_CONFIG=ce;exports.SCHEDULER_CONFIG=R;exports.SchedulerError=F;exports.atom=Ie;exports.batch=Ae;exports.computed=Re;exports.effect=Te;exports.isAtom=se;exports.isComputed=De;exports.isEffect=Ce;exports.scheduler=U;exports.untracked=te;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|