@but212/atom-effect 0.24.0 → 0.25.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.mjs +335 -292
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/atom-effect.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(h,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(h=typeof globalThis<"u"?globalThis:h||self,E(h.AtomEffect={}))})(this,function(h){Object.defineProperty(h,Symbol.toStringTag,{value:"Module"});var E={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},f={DISPOSED:1,EXECUTING:8},L={DISPOSED:1,IS_COMPUTED:2,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512,FORCE_COMPUTE:1024},d={DISPOSED:1,SYNC:8,NOTIFICATION_SCHEDULED:16},I={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},M={WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3},j={MAX_ASYNC_RETRIES:3,MAX_PROMISE_ID:Number.MAX_SAFE_INTEGER-1},v={UNINITIALIZED:-1,MIN:1},P=1073741823,W={VERSION_BITS:16},Ot=(typeof process<"u"&&process.env,!1),ut=Object.freeze([]),B=class{constructor(t,s,e=void 0){this.node=t,this.version=s,this.unsub=e}},lt=class{constructor(t,s){this.fn=t,this.sub=s}notify(t,s){this.fn?this.fn(t,s):this.sub&&this.sub.execute()}},D=class extends Error{constructor(t,s=null,e=!0){super(t),this.cause=s,this.recoverable=e,this.name="AtomError"}},g=class extends D{constructor(t,s=null){super(t,s,!0),this.name="ComputedError"}},C=class extends D{constructor(t,s=null){super(t,s,!1),this.name="EffectError"}},b=class extends D{constructor(t,s=null){super(t,s,!1),this.name="SchedulerError"}},u={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,s)=>`Maximum flush iterations (${t}) exceeded. ${s} 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"},K=class{constructor(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._epoch=v.UNINITIALIZED,this._overflow=null}get size(){return this._count}getAt(t){if(t===0)return this._s0;if(t===1)return this._s1;if(t===2)return this._s2;if(t===3)return this._s3;const s=this._overflow;if(s!==null&&t>=4){const e=t-4;if(e<s.length)return s[e]||null}return null}setAt(t,s){if(t===0)this._s0=s;else if(t===1)this._s1=s;else if(t===2)this._s2=s;else if(t===3)this._s3=s;else{this._overflow??=[];const e=this._overflow;e[t-4]=s}t>=this._count&&(this._count=t+1)}truncateFrom(t){const s=this._count;if(t>=s)return;if(t<=0){const i=this._s0;i!=null&&(this._onItemRemoved(i),this._s0=null)}if(t<=1){const i=this._s1;i!=null&&(this._onItemRemoved(i),this._s1=null)}if(t<=2){const i=this._s2;i!=null&&(this._onItemRemoved(i),this._s2=null)}if(t<=3){const i=this._s3;i!=null&&(this._onItemRemoved(i),this._s3=null)}const e=this._overflow;if(e!==null&&s>4){const i=t>4?t-4:0,n=e.length;for(let r=i;r<n;r++){const o=e[r];o!=null&&(this._onItemRemoved(o),e[r]=null)}t<=4?(e.length=0,this._overflow=null):e.length=t-4}this._count=t}_onItemRemoved(t){}add(t){if(this._s0===null){this._s0=t,this._count++;return}if(this._s1===null){this._s1=t,this._count++;return}if(this._s2===null){this._s2=t,this._count++;return}if(this._s3===null){this._s3=t,this._count++;return}if(this._overflow===null)this._overflow=[t];else{const s=this._overflow;for(let e=0,i=s.length;e<i;e++)if(s[e]===null){s[e]=t,this._count++;return}s.push(t)}this._count++}remove(t){if(this._s0===t)return this._s0=null,this._count--,!0;if(this._s1===t)return this._s1=null,this._count--,!0;if(this._s2===t)return this._s2=null,this._count--,!0;if(this._s3===t)return this._s3=null,this._count--,!0;const s=this._overflow;if(s==null)return!1;for(let e=0,i=s.length;e<i;e++)if(s[e]===t)return s[e]=null,this._count--,!0;return!1}has(t){const s=this._count;if(s===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;if(s<=4)return!1;const e=this._overflow;if(e!=null){let i=0;this._s0!=null&&i++,this._s1!=null&&i++,this._s2!=null&&i++,this._s3!=null&&i++;for(let n=0,r=e.length;n<r;n++){const o=e[n];if(o!=null){if(o===t)return!0;if(++i===s)break}}}return!1}forEach(t){const s=this._count;if(s===0)return;const e=this._s0;e!=null&&t(e);const i=this._s1;i!=null&&t(i);const n=this._s2;n!=null&&t(n);const r=this._s3;if(r!=null&&t(r),s<=4)return;const o=this._overflow;if(o!=null){let c=0;e!=null&&c++,i!=null&&c++,n!=null&&c++,r!=null&&c++;for(let l=0,O=o.length;l<O;l++){const F=o[l];if(F!=null&&(t(F),++c===s))return}}}forEachIndexed(t){const s=this._count;if(s===0)return 0;let e=0;const i=this._s0;i!=null&&(t(i),e++);const n=this._s1;n!=null&&(t(n),e++);const r=this._s2;r!=null&&(t(r),e++);const o=this._s3;if(o!=null&&(t(o),e++),s<=4||e===s)return e;const c=this._overflow;if(c!=null)for(let l=0,O=c.length;l<O;l++){const F=c[l];if(F!=null&&(t(F),++e===s))break}return e}compact(){const t=this._overflow;if(t===null||t.length===0)return;let s=0;for(;s<t.length;)if(t[s]===null){const e=t.pop();s<t.length&&e!=null&&(t[s]=e)}else s++;t.length===0&&(this._overflow=null)}clear(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._overflow!==null&&(this._overflow.length=0,this._overflow=null)}dispose(){this.clear()}},Z=Symbol("AtomEffect.DebugName"),ct=Symbol("AtomEffect.Id"),J=Symbol("AtomEffect.Type"),H=Symbol("AtomEffect.NoDefaultValue"),U={enabled:!1,warnInfiniteLoop:M.WARN_INFINITE_LOOP,warn(t,s){},attachDebugInfo(t,s,e){},getDebugName:t=>t?.[Z],getDebugType:t=>t?.[J]},_t=1,ft=()=>_t++;function T(t,s,e){if(t instanceof D)return t;const i=t instanceof Error,n=i?t.message:String(t),r=i?t:void 0;return new s(`${i?t.constructor.name:"Unexpected error"} (${e}): ${n}`,r)}var x=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=v.UNINITIALIZED,this.id=ft()&P,this._slots=null,this._notifying=0,this._deps=null,this._hotIndex=-1}subscribe(t){const s=typeof t=="function";if(!s&&(!t||typeof t.execute!="function"))throw T(new TypeError("Invalid subscriber"),D,u.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let e=this._slots;e||(e=new K,this._slots=e);let i=!1;if(e.forEach(r=>{(s?r.fn===t:r.sub===t)&&(i=!0)}),i)return()=>{};const n=new lt(s?t:void 0,s?void 0:t);return e.add(n),()=>this._unsubscribe(n)}_unsubscribe(t){if(this._slots){if(this._notifying>0){this._slots.remove(t);return}this._slots.remove(t),this._slots.compact()}}subscriberCount(){return this._slots?this._slots.size:0}_notifySubscribers(t,s){const e=this._slots;if(!(!e||e.size===0)){this._notifying++;try{e.forEach(i=>{try{i.notify(t,s)}catch(n){console.error(T(n,D,u.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}})}finally{this._notifying--,this._notifying===0&&e.compact()}}}_isDirty(){const t=this._deps;if(!t||t.size===0)return!1;if(this._hotIndex!==-1){const s=t.getAt(this._hotIndex);if(s!=null&&s.node.version!==s.version)return!0}return!t.hasComputeds&&!t.isDirtyFast()?!1:this._deepDirtyCheck()}},z=0,G=()=>(z=z+1&1073741823||1,z),V=t=>t+1&P,k=0,w=!1,tt=0,st=()=>tt;function et(){return w?!1:(w=!0,tt=G(),k=0,!0)}var it=()=>{w=!1},at=()=>w?++k:0,X=(function(t){return t[t.IDLE=0]="IDLE",t[t.BATCHING=1]="BATCHING",t[t.FLUSHING=2]="FLUSHING",t})({}),Et=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!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 phase(){return this._isProcessing||this._isFlushingSync?X.FLUSHING:this._isBatching?X.BATCHING:X.IDLE}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(t){if(t._nextEpoch!==this._epoch){if(t._nextEpoch=this._epoch,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}this._queueBuffer[this._bufferIndex][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)return;const t=et();this._drainQueue(),t&&it()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this._flush()}}_flushSync(){this._isFlushingSync=!0;const t=et();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&it()}}_mergeBatchQueue(){if(this._batchQueueSize===0)return;const t=++this._epoch,s=this._batchQueue,e=this._queueBuffer[this._bufferIndex];let i=this._size;s.slice(0,this._batchQueueSize).forEach(n=>{n._nextEpoch!==t&&(n._nextEpoch=t,e[i++]=n)}),this._size=i,this._batchQueueSize=0,s.length>I.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let t=0;for(;this._size>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const t=this._bufferIndex,s=this._queueBuffer[t],e=this._size;this._bufferIndex=t^1,this._size=0,this._epoch++;for(let i=0;i<e;i++)try{const n=s[i];typeof n=="function"?n():n.execute()}catch(n){console.error(new b("Error occurred during scheduler execution",n))}s.length=0}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;if(console.error(new b(u.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0,this.onOverflow)try{this.onOverflow(t)}catch{}}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){this._batchDepth!==0&&--this._batchDepth===0&&(this._flushSync(),this._isBatching=!1)}setMaxFlushIterations(t){if(t<I.MIN_FLUSH_ITERATIONS)throw new b(`Max flush iterations must be at least ${I.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},A=new Et,Q=Symbol.for("atom-effect/atom"),nt=Symbol.for("atom-effect/computed"),rt=Symbol.for("atom-effect/effect"),dt=Symbol.for("atom-effect/writable"),_={current:null,run(t,s){const e=this.current;this.current=t;try{return s()}finally{this.current=e}}};function pt(t){const s=_.current;if(s===null)return t();_.current=null;try{return t()}finally{_.current=s}}var It=class extends x{constructor(t,s){super(),this._pendingOldValue=void 0,this[Q]=!0,this[dt]=!0,this._value=t,s&&(this.flags|=d.SYNC),U.attachDebugInfo(this,"atom",this.id)}get value(){const t=_.current;return t?.addDependency(this),this._value}set value(t){const s=this._value;if(Object.is(s,t))return;this._value=t,this.version=V(this.version);const e=this._slots,i=this.flags;if(e==null||e.size===0||i&d.NOTIFICATION_SCHEDULED)return;this._pendingOldValue=s;const n=i|d.NOTIFICATION_SCHEDULED;if(this.flags=n,(n&d.SYNC)!==0&&!A.isBatching){this._flushNotifications();return}A.schedule(this)}execute(){this._flushNotifications()}_flushNotifications(){const t=this.flags;if(!(t&d.NOTIFICATION_SCHEDULED)||t&d.DISPOSED)return;const s=this._pendingOldValue;this._pendingOldValue=void 0,this.flags&=~d.NOTIFICATION_SCHEDULED,this._notifySubscribers(this._value,s)}peek(){return this._value}dispose(){this.flags&d.DISPOSED||(this._slots?.clear(),this.flags|=d.DISPOSED,this._value=void 0,this._pendingOldValue=void 0)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function Ct(t,s={}){return new It(t,s.sync??!1)}var ot=class extends K{constructor(){super(),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1,this._depsHash=0,this._map=null,this.hasComputeds=!1,this._depsHash=0}prepareTracking(){this.hasComputeds=!1}_onItemRemoved(t){const s=t.unsub;s&&s()}claimExisting(t,s){const e=this._count;if(s>=e)return!1;const i=e-s;if(this._map!==null||i>this._SCAN_THRESHOLD)return this._claimViaMap(t,s);if(s<4){if(s<=0){const o=this._s0;if(o&&o.node===t&&o.unsub)return o.version=t.version,!0}if(s<=1&&e>1){const o=this._s1;if(o&&o.node===t&&o.unsub)return o.version=t.version,s!==1&&(this._s1=this._s0,this._s0=o),!0}if(s<=2&&e>2){const o=this._s2;if(o&&o.node===t&&o.unsub)return o.version=t.version,s!==2&&this._swapInline(2,s,o),!0}if(s<=3&&e>3){const o=this._s3;if(o&&o.node===t&&o.unsub)return o.version=t.version,s!==3&&this._swapInline(3,s,o),!0}}const n=s>4?s:4,r=this._overflow;if(r)for(let o=n-4,c=r.length;o<c;o++){const l=r[o];if(l&&l.node===t&&l.unsub)return l.version=t.version,this._swapGeneral(o+4,s,l),!0}return!1}_claimViaMap(t,s){if(this._map===null){this._map=new Map;const n=this._count;for(let r=s;r<n;r++){const o=this.getAt(r);o?.unsub&&this._map.set(o.node,r)}}const e=this._map.get(t);if(e===void 0||e<s)return!1;const i=this.getAt(e);if(i==null||!i.unsub)return!1;if(i.version=t.version,e!==s){const n=this.getAt(s);this.setAt(s,i),this.setAt(e,n),n?.unsub&&this._map.set(n.node,e),this._map.set(t,s)}return!0}_swapInline(t,s,e){const i=this.getAt(s);this.setAt(s,e),this.setAt(t,i)}_swapGeneral(t,s,e){if(t===s)return;const i=this.getAt(s);this.setAt(s,e),this.setAt(t,i)}insertNew(t,s){const e=this._count;if(t<e){const i=this.getAt(t);i!=null&&(this.add(i),this._map!==null&&i.unsub&&this._map.set(i.node,this._count-1))}t===0?this._s0=s:t===1?this._s1=s:t===2?this._s2=s:t===3?this._s3=s:this.setAt(t,s),t>=e&&(this._count=t+1)}truncateFrom(t){t>=this._count||(super.truncateFrom(t),this._map!==null&&(this._map.clear(),this._map=null))}seal(){const t=this._count;if(t<=0){this._depsHash=0;return}let s=0;const e=W.VERSION_BITS,i=this._s0;if(i&&(s=s+(i.version<<e)+i.node.id|0),t>1){const n=this._s1;n&&(s=s+(n.version<<e)+n.node.id|0)}if(t>2){const n=this._s2;n&&(s=s+(n.version<<e)+n.node.id|0)}if(t>3){const n=this._s3;n&&(s=s+(n.version<<e)+n.node.id|0);const r=this._overflow;if(r)for(let o=0,c=r.length;o<c;o++){const l=r[o];l&&(s=s+(l.version<<e)+l.node.id|0)}}this._depsHash=s}isDirtyFast(){const t=this._count;if(t<=0)return!1;let s=0;const e=W.VERSION_BITS,i=this._s0;if(i){const n=i.node;s=s+(n.version<<e)+n.id|0}if(t>1){const n=this._s1;if(n){const r=n.node;s=s+(r.version<<e)+r.id|0}}if(t>2){const n=this._s2;if(n){const r=n.node;s=s+(r.version<<e)+r.id|0}}if(t>3){const n=this._s3;if(n){const o=n.node;s=s+(o.version<<e)+o.id|0}const r=this._overflow;if(r)for(let o=0,c=r.length;o<c;o++){const l=r[o];if(l){const O=l.node;s=s+(O.version<<e)+O.id|0}}}return s!==this._depsHash}captureVersionSnapshot(){const t=this._count;if(t<=0)return 0;let s=0;const e=this._s0;if(e&&(s=(s<<5)-s+e.node.version|0),t>1){const i=this._s1;i&&(s=(s<<5)-s+i.node.version|0)}if(t>2){const i=this._s2;i&&(s=(s<<5)-s+i.node.version|0)}if(t>3){const i=this._s3;i&&(s=(s<<5)-s+i.node.version|0);const n=this._overflow;if(n)for(let r=0,o=n.length;r<o;r++){const c=n[r];c&&(s=(s<<5)-s+c.node.version|0)}}return s}disposeAll(){this._count>0&&this.truncateFrom(0),this.hasComputeds=!1,this._map!==null&&(this._map.clear(),this._map=null)}remove(t){throw new Error("remove() is strictly prohibited in DepSlotBuffer to preserve sequential cache paths.")}compact(){}};function St(t){return t!==null&&typeof t=="object"&&Q in t}function vt(t){return t!==null&&typeof t=="object"&&nt in t}function Dt(t){return t!==null&&typeof t=="object"&&rt in t}function ht(t){return t!==null&&typeof t=="object"&&typeof t.then=="function"}var{IDLE:S,DIRTY:a,PENDING:N,RESOLVED:p,REJECTED:m,HAS_ERROR:y,RECOMPUTING:R,DISPOSED:Y,IS_COMPUTED:$,FORCE_COMPUTE:q}=L,gt=class extends x{constructor(t,s={}){if(typeof t!="function")throw new g(u.COMPUTED_MUST_BE_FUNCTION);if(super(),this[Q]=!0,this[nt]=!0,this._error=null,this._promiseId=0,this._deps=new ot,this._asyncStartAggregateVersion=0,this._asyncRetryCount=0,this._lastDriftEpoch=v.UNINITIALIZED,this._trackEpoch=v.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=$|a|S,this._equal=s.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in s?s.defaultValue:H,this._onError=s.onError??null,this._maxAsyncRetries=(s.maxAsyncRetries??j.MAX_ASYNC_RETRIES)&P,U.attachDebugInfo(this,"computed",this.id),s.lazy===!1)try{this._recompute()}catch{}}_track(){_.current?.addDependency(this)}get value(){this._track();const t=this.flags;if((t&(p|a|S))===p)return this._value;if(t&Y)throw new g(u.COMPUTED_DISPOSED);if(t&R){if(this._defaultValue!==H)return this._defaultValue;throw new g(u.COMPUTED_CIRCULAR_DEPENDENCY)}if(t&(a|S)&&((t&S)===0&&(t&q)===0&&this._deps.size>0&&!this._isDirty()?this.flags&=~a:this._recompute(),this.flags&p))return this._value;const s=this._defaultValue,e=s!==H;if(this.flags&N){if(e)return s;throw new g(u.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(this.flags&m){if(e)return s;throw this._error}return this._value}peek(){return this._value}get state(){this._track();const t=this.flags;return t&p?E.RESOLVED:t&N?E.PENDING:t&m?E.REJECTED:E.IDLE}get hasError(){if(this._track(),this.flags&(m|y))return!0;const t=this._deps,s=t.size;for(let e=0;e<s;e++){const i=t.getAt(e);if(i!=null&&i.node.flags&y)return!0}return!1}get isValid(){return!this.hasError}get errors(){this._track();const t=[];this._error&&t.push(this._error);const s=this._deps,e=s.size;for(let i=0;i<e;i++){const n=s.getAt(i);if(n==null)continue;const r=n.node;r.flags&y&&this._collectErrorsFromDep(r,t)}return t.length===0?ut:Object.freeze(t)}_collectErrorsFromDep(t,s){const e=t.errors,i=e.length;for(let n=0;n<i;n++){const r=e[n];r!=null&&!s.includes(r)&&s.push(r)}}get lastError(){return this._track(),this._error}get isPending(){return this._track(),(this.flags&N)!==0}get isResolved(){return this._track(),(this.flags&p)!==0}invalidate(){this.flags|=q,this._markDirty()}dispose(){this.flags&Y||(this._deps.disposeAll(),this._slots?.clear(),this.flags=Y|a|S,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){if(t._lastSeenEpoch===this._trackEpoch)return;t._lastSeenEpoch=this._trackEpoch;const s=this._trackCount,e=this._deps.getAt(s);if(e!=null&&e.node===t)e.version=t.version;else if(!this._deps.claimExisting(t,s)){const i=new B(t,t.version,t.subscribe(this));this._deps.insertNew(s,i)}t.flags&$&&(this._deps.hasComputeds=!0),this._trackCount=s+1}_recompute(){if(this.flags&R)return;this.flags=(this.flags|R)&~q,this._trackEpoch=G(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const s=_.run(this,this._fn);this._deps.truncateFrom(this._trackCount),this._deps.seal(),t=!0,ht(s)?this._handleAsyncComputation(s):this._finalizeResolution(s)}catch(s){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch{}this._handleError(s,u.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=v.UNINITIALIZED,this._trackCount=0,this.flags&=~R}}_handleAsyncComputation(t){this.flags=(this.flags|N)&~(S|a|p|m),this._notifySubscribers(void 0,void 0),this._asyncStartAggregateVersion=this._captureVersionSnapshot(),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%j.MAX_PROMISE_ID;const s=this._promiseId;t.then(e=>{if(s===this._promiseId){if(this._captureVersionSnapshot()!==this._asyncStartAggregateVersion){const i=st();return this._lastDriftEpoch!==i&&(this._lastDriftEpoch=i,this._asyncRetryCount=0),this._asyncRetryCount++<this._maxAsyncRetries?this._markDirty():this._handleError(new g(`Async drift threshold exceeded after ${this._maxAsyncRetries} retries.`),u.COMPUTED_ASYNC_COMPUTATION_FAILED)}this._finalizeResolution(e),this._notifySubscribers(e,void 0)}},e=>s===this._promiseId&&this._handleError(e,u.COMPUTED_ASYNC_COMPUTATION_FAILED))}_captureVersionSnapshot(){return this._deps.captureVersionSnapshot()}_handleError(t,s,e=!1){const i=T(t,g,s);if(!e&&!(this.flags&m)&&(this.version=V(this.version)),this._error=i,this.flags=this.flags&~(S|a|N|p)|m|y,this._onError)try{this._onError(i)}catch(n){console.error(u.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(e)throw i;this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){(!(this.flags&p)||!this._equal(this._value,t))&&(this.version=V(this.version)),this._value=t,this._error=null,this.flags=(this.flags|p)&~(S|a|N|m|y)}execute(){this._markDirty()}_markDirty(){this.flags&(R|a)||(this.flags|=a,this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){const t=this._deps,s=_.current;_.current=null;try{const e=t.size;for(let i=0;i<e;i++){const n=t.getAt(i);if(n==null)continue;const r=n.node;if(r.flags&$)try{r.value}catch{}if(r.version!==n.version)return this._hotIndex=i,!0}return this._hotIndex=-1,!1}finally{_.current=s}}};function mt(t,s={}){return new gt(t,s)}var Tt=class extends x{constructor(t,s={}){super(),this[rt]=!0,this._cleanup=null,this._deps=new ot,this._currentEpoch=v.UNINITIALIZED,this._lastFlushEpoch=v.UNINITIALIZED,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._trackCount=0,this._fn=t,this._onError=s.onError??null,this._sync=s.sync??!1,this._maxExecutions=s.maxExecutionsPerSecond??I.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=s.maxExecutionsPerFlush??I.MAX_EXECUTIONS_PER_EFFECT,this._sync?this._notifyCallback=()=>this.execute():this._notifyCallback=()=>A.schedule(this),U.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&f.DISPOSED)throw new C(u.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.flags&f.DISPOSED||(this.flags|=f.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if(!(this.flags&f.EXECUTING))return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const e=this._trackCount,i=this._deps,n=i.getAt(e);n!=null&&n.node===t?n.version=t.version:i.claimExisting(t,e)||this._insertNewDependency(t,e),t.flags&L.IS_COMPUTED&&(i.hasComputeds=!0),this._trackCount=e+1}_insertNewDependency(t,s){let e;try{const i=t.subscribe(this._notifyCallback);e=new B(t,t.version,i)}catch(i){const n=T(i,C,u.EFFECT_EXECUTION_FAILED);if(console.error(n),this._onError)try{this._onError(n)}catch{}e=new B(t,t.version,void 0)}this._deps.insertNew(s,e)}execute(t=!1){if(this.flags&(f.DISPOSED|f.EXECUTING))return;const s=this._deps;if(!t&&s.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),this.flags|=f.EXECUTING,this._execCleanup(),this._currentEpoch=G(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let e=!1;try{const i=_.run(this,this._fn);s.truncateFrom(this._trackCount),s.seal(),e=!0,ht(i)?this._handleAsyncResult(i):this._cleanup=typeof i=="function"?i:null}catch(i){if(!e)try{s.truncateFrom(this._trackCount)}catch{}this._handleExecutionError(i),this._cleanup=null}finally{this.flags&=~f.EXECUTING}}_handleAsyncResult(t){const s=++this._execId;t.then(e=>{if(s!==this._execId||this.flags&f.DISPOSED){if(typeof e=="function")try{e()}catch(i){this._handleExecutionError(i,u.EFFECT_CLEANUP_FAILED)}return}typeof e=="function"&&(this._cleanup=e)},e=>s===this._execId&&this._handleExecutionError(e))}_deepDirtyCheck(){const t=_.current;_.current=null;const s=this._deps;try{const e=s.size;for(let i=0;i<e;i++){const n=s.getAt(i);if(n==null)continue;const r=n.node;if(r.flags&L.IS_COMPUTED&&this._tryPullComputed(r),r.version!==n.version)return this._hotIndex=i,!0}return!1}finally{_.current=t}}_tryPullComputed(t){try{t.value}catch{}}_execCleanup(){if(this._cleanup){try{this._cleanup()}catch(t){this._handleExecutionError(t,u.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoops(){const t=st();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),at()>I.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=M.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const s=new C(u.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(s),s}}get isDisposed(){return(this.flags&f.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&f.EXECUTING)!==0}_throwInfiniteLoopError(t){const s=new C(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${k}`);throw this.dispose(),console.error(s),s}_handleExecutionError(t,s=u.EFFECT_EXECUTION_FAILED){const e=T(t,C,s);if(console.error(e),this._onError)try{this._onError(e)}catch(i){console.error(T(i,C,u.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function At(t,s={}){if(typeof t!="function")throw new C(u.EFFECT_MUST_BE_FUNCTION);const e=new Tt(t,s);return e.execute(),e}function Nt(t){if(typeof t!="function")throw new TypeError(u.BATCH_CALLBACK_MUST_BE_FUNCTION);A.startBatch();try{return t()}finally{A.endBatch()}}h.AsyncState=E,h.AtomError=D,h.ComputedError=g,h.DEBUG_CONFIG=M,h.DEBUG_RUNTIME=U,h.EffectError=C,h.SCHEDULER_CONFIG=I,h.SchedulerError=b,h.atom=Ct,h.batch=Nt,h.computed=mt,h.effect=At,h.isAtom=St,h.isComputed=vt,h.isEffect=Dt,h.scheduler=A,h.untracked=pt});
|
|
1
|
+
(function(l,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(l=typeof globalThis<"u"?globalThis:l||self,p(l.AtomEffect={}))})(this,function(l){Object.defineProperty(l,Symbol.toStringTag,{value:"Module"});var p={IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"},f={DISPOSED:1,EXECUTING:8},L={DISPOSED:1,IS_COMPUTED:2,DIRTY:8,IDLE:16,PENDING:32,RESOLVED:64,REJECTED:128,RECOMPUTING:256,HAS_ERROR:512,FORCE_COMPUTE:1024},I={DISPOSED:1,SYNC:8,NOTIFICATION_SCHEDULED:16},g={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},M={WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3},W={MAX_ASYNC_RETRIES:3,MAX_PROMISE_ID:Number.MAX_SAFE_INTEGER-1},v={UNINITIALIZED:-1,MIN:1},P=1073741823,K={VERSION_BITS:16},Ot=(typeof process<"u"&&process.env,!1),Z=Object.freeze([]),B=class{constructor(t,s,e=void 0){this.node=t,this.version=s,this.unsub=e}},lt=class{constructor(t,s){this.fn=t,this.sub=s}notify(t,s){this.fn?this.fn(t,s):this.sub&&this.sub.execute()}},m=class extends Error{constructor(t,s=null,e=!0){super(t),this.cause=s,this.recoverable=e,this.name="AtomError"}},T=class extends m{constructor(t,s=null){super(t,s,!0),this.name="ComputedError"}},D=class extends m{constructor(t,s=null){super(t,s,!1),this.name="EffectError"}},R=class extends m{constructor(t,s=null){super(t,s,!1),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,s)=>`Maximum flush iterations (${t}) exceeded. ${s} 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"},J=class{constructor(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._overflow=null}get size(){return this._count}getAt(t){switch(t){case 0:return this._s0;case 1:return this._s1;case 2:return this._s2;case 3:return this._s3;default:{const s=this._overflow;if(s!==null&&t>=4){const e=t-4;if(e<s.length)return s[e]??null}return null}}}setAt(t,s){switch(t){case 0:this._s0=s;break;case 1:this._s1=s;break;case 2:this._s2=s;break;case 3:this._s3=s;break;default:{this._overflow??=[];const e=this._overflow;e[t-4]=s}}t>=this._count&&(this._count=t+1)}truncateFrom(t){const s=this._count;if(t>=s)return;if(t<=3)switch(t){case 0:{const i=this._s0;i!=null&&(this._onItemRemoved(i),this._s0=null)}case 1:{const i=this._s1;i!=null&&(this._onItemRemoved(i),this._s1=null)}case 2:{const i=this._s2;i!=null&&(this._onItemRemoved(i),this._s2=null)}case 3:{const i=this._s3;i!=null&&(this._onItemRemoved(i),this._s3=null)}}const e=this._overflow;if(e!==null&&s>4){const i=t>4?t-4:0,n=e.length;for(let r=i;r<n;r++){const o=e[r];o!=null&&(this._onItemRemoved(o),e[r]=null)}t<=4?(e.length=0,this._overflow=null):e.length=t-4}this._count=t}_onItemRemoved(t){}add(t){if(this._s0===null){this._s0=t,this._count++;return}if(this._s1===null){this._s1=t,this._count++;return}if(this._s2===null){this._s2=t,this._count++;return}if(this._s3===null){this._s3=t,this._count++;return}if(this._overflow===null)this._overflow=[t];else{const s=this._overflow;for(let e=0,i=s.length;e<i;e++)if(s[e]===null){s[e]=t,this._count++;return}s.push(t)}this._count++}remove(t){if(this._s0===t)return this._s0=null,this._count--,!0;if(this._s1===t)return this._s1=null,this._count--,!0;if(this._s2===t)return this._s2=null,this._count--,!0;if(this._s3===t)return this._s3=null,this._count--,!0;const s=this._overflow;if(s==null)return!1;for(let e=0,i=s.length;e<i;e++)if(s[e]===t)return s[e]=null,this._count--,!0;return!1}has(t){const s=this._count;if(s===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;if(s<=4)return!1;const e=this._overflow;if(e!=null){let i=0;this._s0!=null&&i++,this._s1!=null&&i++,this._s2!=null&&i++,this._s3!=null&&i++;for(let n=0,r=e.length;n<r;n++){const o=e[n];if(o!=null){if(o===t)return!0;if(++i===s)break}}}return!1}forEach(t){const s=this._count;if(s===0)return;const e=this._s0;e!=null&&t(e);const i=this._s1;i!=null&&t(i);const n=this._s2;n!=null&&t(n);const r=this._s3;if(r!=null&&t(r),s<=4)return;const o=this._overflow;if(o!=null){let h=0;e!=null&&h++,i!=null&&h++,n!=null&&h++,r!=null&&h++;for(let u=0,d=o.length;u<d;u++){const a=o[u];if(a!=null&&(t(a),++h===s))return}}}forEachIndexed(t){const s=this._count;if(s===0)return 0;let e=0;const i=this._s0;i!=null&&(t(i),e++);const n=this._s1;n!=null&&(t(n),e++);const r=this._s2;r!=null&&(t(r),e++);const o=this._s3;if(o!=null&&(t(o),e++),s<=4||e===s)return e;const h=this._overflow;if(h!=null)for(let u=0,d=h.length;u<d;u++){const a=h[u];if(a!=null&&(t(a),++e===s))break}return e}compact(){const t=this._overflow;if(t===null||t.length===0)return;let s=0;for(;s<t.length;)if(t[s]===null){const e=t.pop();s<t.length&&e!=null&&(t[s]=e)}else s++;t.length===0&&(this._overflow=null)}clear(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._overflow!==null&&(this._overflow.length=0,this._overflow=null)}dispose(){this.clear()}},tt=Symbol("AtomEffect.DebugName"),ct=Symbol("AtomEffect.Id"),st=Symbol("AtomEffect.Type"),H=Symbol("AtomEffect.NoDefaultValue"),U={enabled:!1,warnInfiniteLoop:M.WARN_INFINITE_LOOP,warn(t,s){},attachDebugInfo(t,s,e){},getDebugName:t=>t?.[tt],getDebugType:t=>t?.[st]},_t=1,ft=()=>_t++;function N(t,s,e){if(t instanceof m)return t;const i=t instanceof Error,n=i?t.message:String(t),r=i?t:void 0;return new s(`${i?t.constructor.name:"Unexpected error"} (${e}): ${n}`,r)}var x=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=v.UNINITIALIZED,this._notifying=0,this._hotIndex=-1,this._slots=null,this._deps=null,this.id=ft()&P}subscribe(t){const s=typeof t=="function";if(!s&&(!t||typeof t.execute!="function"))throw N(new TypeError("Invalid subscriber"),m,c.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let e=this._slots;e||(e=new J,this._slots=e);let i=!1;if(e.forEach(r=>{(s?r.fn===t:r.sub===t)&&(i=!0)}),i)return()=>{};const n=new lt(s?t:void 0,s?void 0:t);return e.add(n),()=>this._unsubscribe(n)}_unsubscribe(t){if(this._slots){if(this._notifying>0){this._slots.remove(t);return}this._slots.remove(t),this._slots.compact()}}subscriberCount(){return this._slots?this._slots.size:0}_notifySubscribers(t,s){const e=this._slots;if(!(!e||e.size===0)){this._notifying++;try{e.forEach(i=>{try{i.notify(t,s)}catch(n){console.error(N(n,m,c.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}})}finally{this._notifying--,this._notifying===0&&e.compact()}}}_isDirty(){const t=this._deps;if(!t||t.size===0)return!1;if(this._hotIndex!==-1){const s=t.getAt(this._hotIndex);if(s!=null&&s.node.version!==s.version)return!0}return!t.hasComputeds&&!t.isDirtyFast()?!1:this._deepDirtyCheck()}},z=0,k=()=>(z=z+1&1073741823||1,z),G=t=>t+1&P,X=0,w=!1,et=0,it=()=>et;function nt(){return w?!1:(w=!0,et=k(),X=0,!0)}var rt=()=>{w=!1},at=()=>w?++X:0,V=(function(t){return t[t.IDLE=0]="IDLE",t[t.BATCHING=1]="BATCHING",t[t.FLUSHING=2]="FLUSHING",t})({}),Et=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isBatching=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=g.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get phase(){return this._isProcessing||this._isFlushingSync?V.FLUSHING:this._isBatching?V.BATCHING:V.IDLE}get queueSize(){return this._size}get isBatching(){return this._isBatching}schedule(t){if(t._nextEpoch!==this._epoch){if(t._nextEpoch=this._epoch,this._isBatching||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}this._queueBuffer[this._bufferIndex][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)return;const t=nt();this._drainQueue(),t&&rt()}finally{this._isProcessing=!1,this._size>0&&!this._isBatching&&this._flush()}}_flushSync(){this._isFlushingSync=!0;const t=nt();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=!1,t&&rt()}}_mergeBatchQueue(){if(this._batchQueueSize===0)return;const t=++this._epoch,s=this._batchQueue,e=this._queueBuffer[this._bufferIndex];let i=this._size;for(let n=0;n<this._batchQueueSize;n++){const r=s[n];r._nextEpoch!==t&&(r._nextEpoch=t,e[i++]=r)}this._size=i,this._batchQueueSize=0,s.length=0}_drainQueue(){let t=0;for(;this._size>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._processQueue(),this._mergeBatchQueue()}}_processQueue(){const t=this._bufferIndex,s=this._queueBuffer[t],e=this._size;this._bufferIndex=t^1,this._size=0,this._epoch++;for(let i=0;i<e;i++)try{const n=s[i];typeof n=="function"?n():n.execute()}catch(n){console.error(new R("Error occurred during scheduler execution",n))}s.length=0}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;if(console.error(new R(c.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[this._bufferIndex].length=0,this._batchQueueSize=0,this.onOverflow)try{this.onOverflow(t)}catch{}}startBatch(){this._batchDepth++,this._isBatching=!0}endBatch(){this._batchDepth!==0&&--this._batchDepth===0&&(this._flushSync(),this._isBatching=!1)}setMaxFlushIterations(t){if(t<g.MIN_FLUSH_ITERATIONS)throw new R(`Max flush iterations must be at least ${g.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},O=new Et,Q=Symbol.for("atom-effect/atom"),ot=Symbol.for("atom-effect/computed"),ht=Symbol.for("atom-effect/effect"),dt=Symbol.for("atom-effect/writable"),_={current:null,run(t,s){const e=this.current;this.current=t;try{return s()}finally{this.current=e}}};function pt(t){const s=_.current;if(s===null)return t();_.current=null;try{return t()}finally{_.current=s}}var It=class extends x{constructor(t,s){super(),this[Q]=!0,this[dt]=!0,this._value=t,this._pendingOldValue=void 0,s&&(this.flags|=I.SYNC),U.attachDebugInfo(this,"atom",this.id)}get value(){const t=_.current;return t?.addDependency(this),this._value}set value(t){const s=this._value;if(Object.is(s,t))return;this._value=t,this.version=G(this.version);const e=this._slots,i=this.flags;if(e==null||e.size===0||i&I.NOTIFICATION_SCHEDULED)return;this._pendingOldValue=s;const n=i|I.NOTIFICATION_SCHEDULED;if(this.flags=n,(n&I.SYNC)!==0&&!O.isBatching){this._flushNotifications();return}O.schedule(this)}execute(){this._flushNotifications()}_flushNotifications(){const t=this.flags;if(!(t&I.NOTIFICATION_SCHEDULED)||t&I.DISPOSED)return;const s=this._pendingOldValue;this._pendingOldValue=void 0,this.flags&=~I.NOTIFICATION_SCHEDULED,this._notifySubscribers(this._value,s)}peek(){return this._value}dispose(){this.flags&I.DISPOSED||(this._slots?.clear(),this.flags|=I.DISPOSED,this._value=void 0,this._pendingOldValue=void 0)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function Ct(t,s={}){return new It(t,s.sync??!1)}var Y=class extends J{constructor(){super(),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1,this._depsHash=0,this._map=null,this.hasComputeds=!1,this._depsHash=0}prepareTracking(){this.hasComputeds=!1}_onItemRemoved(t){const s=t.unsub;s&&s()}claimExisting(t,s){const e=this._count;if(s>=e)return!1;const i=e-s;if(this._map!==null||i>this._SCAN_THRESHOLD)return this._claimViaMap(t,s);if(s<4)switch(s){case 0:{const o=this._s0;if(o&&o.node===t&&o.unsub)return o.version=t.version,!0}case 1:if(e>1){const o=this._s1;if(o&&o.node===t&&o.unsub)return o.version=t.version,s!==1&&(this._s1=this._s0,this._s0=o),!0}case 2:if(e>2){const o=this._s2;if(o&&o.node===t&&o.unsub){if(o.version=t.version,s!==2){const h=s===0?this._s0:this._s1;s===0?this._s0=o:this._s1=o,this._s2=h}return!0}}case 3:if(e>3){const o=this._s3;if(o&&o.node===t&&o.unsub){if(o.version=t.version,s!==3){let h;s===0?(h=this._s0,this._s0=o):s===1?(h=this._s1,this._s1=o):(h=this._s2,this._s2=o),this._s3=h}return!0}}}const n=s>4?s:4,r=this._overflow;if(r)for(let o=n-4,h=r.length;o<h;o++){const u=r[o];if(u&&u.node===t&&u.unsub)return u.version=t.version,this._swapGeneral(o+4,s,u),!0}return!1}_claimViaMap(t,s){if(this._map===null){this._map=new Map;const n=this._count;s<4&&(s<=0&&this._s0?.unsub&&this._map.set(this._s0.node,0),s<=1&&this._s1?.unsub&&this._map.set(this._s1.node,1),s<=2&&this._s2?.unsub&&this._map.set(this._s2.node,2),s<=3&&this._s3?.unsub&&this._map.set(this._s3.node,3));const r=this._overflow;if(r&&n>4){const o=s>4?s:4;for(let h=o-4,u=r.length;h<u;h++){const d=r[h];d?.unsub&&this._map.set(d.node,h+4)}}}const e=this._map.get(t);if(e===void 0||e<s)return!1;const i=this.getAt(e);if(i==null||!i.unsub)return!1;if(i.version=t.version,e!==s){const n=this.getAt(s);this.setAt(s,i),this.setAt(e,n),n?.unsub&&this._map.set(n.node,e),this._map.set(t,s)}return!0}_swapInline(t,s,e){const i=this.getAt(s);this.setAt(s,e),this.setAt(t,i)}_swapGeneral(t,s,e){if(t===s)return;const i=this.getAt(s);if(this.setAt(s,e),t===0)this._s0=i;else if(t===1)this._s1=i;else if(t===2)this._s2=i;else if(t===3)this._s3=i;else{const n=this._overflow;n[t-4]=i}}insertNew(t,s){const e=this._count;if(t<e){const i=this.getAt(t);i!=null&&(this.add(i),this._map!==null&&i.unsub&&this._map.set(i.node,this._count-1))}if(t===0)this._s0=s;else if(t===1)this._s1=s;else if(t===2)this._s2=s;else if(t===3)this._s3=s;else{let i=this._overflow;i||(i=[],this._overflow=i),i[t-4]=s}t>=e&&(this._count=t+1)}truncateFrom(t){t>=this._count||(super.truncateFrom(t),this._map!==null&&(this._map.clear(),this._map=null))}seal(){const t=this._count,s=K.VERSION_BITS;let e=0;switch(t){case 0:this._depsHash=0;return;case 1:{const i=this._s0;e=e+(i.version<<s)+i.node.id|0;break}case 2:{const i=this._s0,n=this._s1;e=e+(i.version<<s)+i.node.id|0,e=e+(n.version<<s)+n.node.id|0;break}case 3:{const i=this._s0,n=this._s1,r=this._s2;e=e+(i.version<<s)+i.node.id|0,e=e+(n.version<<s)+n.node.id|0,e=e+(r.version<<s)+r.node.id|0;break}default:{const i=this._s0,n=this._s1,r=this._s2,o=this._s3;if(e=e+(i.version<<s)+i.node.id|0,e=e+(n.version<<s)+n.node.id|0,e=e+(r.version<<s)+r.node.id|0,e=e+(o.version<<s)+o.node.id|0,t>4){const h=this._overflow;for(let u=0,d=h.length;u<d;u++){const a=h[u];e=e+(a.version<<s)+a.node.id|0}}}}this._depsHash=e}isDirtyFast(){const t=this._count,s=K.VERSION_BITS;let e=0;switch(t){case 0:return!1;case 1:{const i=this._s0.node;e=e+(i.version<<s)+i.id|0;break}case 2:{const i=this._s0.node,n=this._s1.node;e=e+(i.version<<s)+i.id|0,e=e+(n.version<<s)+n.id|0;break}case 3:{const i=this._s0.node,n=this._s1.node,r=this._s2.node;e=e+(i.version<<s)+i.id|0,e=e+(n.version<<s)+n.id|0,e=e+(r.version<<s)+r.id|0;break}default:{const i=this._s0.node,n=this._s1.node,r=this._s2.node,o=this._s3.node;if(e=e+(i.version<<s)+i.id|0,e=e+(n.version<<s)+n.id|0,e=e+(r.version<<s)+r.id|0,e=e+(o.version<<s)+o.id|0,t>4){const h=this._overflow;for(let u=0,d=h.length;u<d;u++){const a=h[u].node;e=e+(a.version<<s)+a.id|0}}}}return e!==this._depsHash}disposeAll(){this._count>0&&this.truncateFrom(0),this.hasComputeds=!1,this._map!==null&&(this._map.clear(),this._map=null)}remove(t){throw new Error("remove() is strictly prohibited in DepSlotBuffer to preserve sequential cache paths.")}compact(){}};function vt(t){return t!==null&&typeof t=="object"&&Q in t}function Dt(t){return t!==null&&typeof t=="object"&&ot in t}function St(t){return t!==null&&typeof t=="object"&&ht in t}function ut(t){return t!==null&&typeof t=="object"&&typeof t.then=="function"}var{IDLE:S,DIRTY:E,PENDING:y,RESOLVED:C,REJECTED:A,HAS_ERROR:b,RECOMPUTING:F,DISPOSED:j,IS_COMPUTED:$,FORCE_COMPUTE:q}=L,gt=class extends x{constructor(t,s={}){if(typeof t!="function")throw new T(c.COMPUTED_MUST_BE_FUNCTION);if(super(),this[Q]=!0,this[ot]=!0,this._error=null,this._promiseId=0,this._deps=new Y,this._asyncRetryCount=0,this._lastDriftEpoch=v.UNINITIALIZED,this._trackEpoch=v.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=$|E|S,this._equal=s.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in s?s.defaultValue:H,this._onError=s.onError??null,this._maxAsyncRetries=(s.maxAsyncRetries??W.MAX_ASYNC_RETRIES)&P,U.attachDebugInfo(this,"computed",this.id),s.lazy===!1)try{this._recompute()}catch{}}_track(){_.current?.addDependency(this)}get value(){this._track();const t=this.flags;if((t&(C|E|S))===C)return this._value;if(t&j)throw new T(c.COMPUTED_DISPOSED);if(t&F){if(this._defaultValue!==H)return this._defaultValue;throw new T(c.COMPUTED_CIRCULAR_DEPENDENCY)}if(t&(E|S)&&((t&S)===0&&(t&q)===0&&this._deps.size>0&&!this._isDirty()?this.flags&=~E:this._recompute(),this.flags&C))return this._value;const s=this._defaultValue,e=s!==H;if(this.flags&y){if(e)return s;throw new T(c.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if(this.flags&A){if(e)return s;throw this._error}return this._value}peek(){return this._value}get state(){this._track();const t=this.flags;return t&C?p.RESOLVED:t&y?p.PENDING:t&A?p.REJECTED:p.IDLE}get hasError(){if(this._track(),this.flags&(A|b))return!0;const t=this._deps;if(!t.hasComputeds)return!1;const s=t.size;for(let e=0;e<s;e++){const i=t.getAt(e);if(i!=null&&i.node.flags&b)return!0}return!1}get isValid(){return!this.hasError}get errors(){this._track();const t=[];this._error&&t.push(this._error);const s=this._deps;if(!s.hasComputeds)return t.length===0?Z:Object.freeze(t);const e=s.size;for(let i=0;i<e;i++){const n=s.getAt(i);if(n==null)continue;const r=n.node;r.flags&b&&this._collectErrorsFromDep(r,t)}return t.length===0?Z:Object.freeze(t)}_collectErrorsFromDep(t,s){const e=t.errors,i=e.length;for(let n=0;n<i;n++){const r=e[n];r!=null&&!s.includes(r)&&s.push(r)}}get lastError(){return this._track(),this._error}get isPending(){return this._track(),(this.flags&y)!==0}get isResolved(){return this._track(),(this.flags&C)!==0}invalidate(){this.flags|=q,this._markDirty()}dispose(){this.flags&j||(this._deps.disposeAll(),this._slots?.clear(),this.flags=j|E|S,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){if(t._lastSeenEpoch===this._trackEpoch)return;t._lastSeenEpoch=this._trackEpoch;const s=this._trackCount,e=this._deps.getAt(s);if(e!=null&&e.node===t)e.version=t.version;else if(!this._deps.claimExisting(t,s)){const i=new B(t,t.version,t.subscribe(this));this._deps.insertNew(s,i)}t.flags&$&&(this._deps.hasComputeds=!0),this._trackCount=s+1}_recompute(){if(this.flags&F)return;this.flags=(this.flags|F)&~q,this._trackEpoch=k(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const s=_.run(this,this._fn);this._deps.truncateFrom(this._trackCount),this._deps.seal(),t=!0,ut(s)?this._handleAsyncComputation(s):this._finalizeResolution(s)}catch(s){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch{}this._handleError(s,c.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=v.UNINITIALIZED,this._trackCount=0,this.flags&=~F}}_handleAsyncComputation(t){this.flags=(this.flags|y)&~(S|E|C|A),this._notifySubscribers(void 0,void 0),this._asyncRetryCount=0,this._promiseId=(this._promiseId+1)%W.MAX_PROMISE_ID;const s=this._promiseId;t.then(e=>{if(s===this._promiseId){if(this._isDirty()){const i=it();return this._lastDriftEpoch!==i&&(this._lastDriftEpoch=i,this._asyncRetryCount=0),this._asyncRetryCount++<this._maxAsyncRetries?this._markDirty():this._handleError(new T(`Async drift threshold exceeded after ${this._maxAsyncRetries} retries.`),c.COMPUTED_ASYNC_COMPUTATION_FAILED)}this._finalizeResolution(e),this._notifySubscribers(e,void 0)}},e=>s===this._promiseId&&this._handleError(e,c.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,s,e=!1){const i=N(t,T,s);if(!e&&!(this.flags&A)&&(this.version=G(this.version)),this._error=i,this.flags=this.flags&~(S|E|y|C)|A|b,this._onError)try{this._onError(i)}catch(n){console.error(c.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(e)throw i;this._notifySubscribers(void 0,void 0)}_finalizeResolution(t){(!(this.flags&C)||!this._equal(this._value,t))&&(this.version=G(this.version)),this._value=t,this._error=null,this.flags=(this.flags|C)&~(S|E|y|A|b)}execute(){this._markDirty()}_markDirty(){this.flags&(F|E)||(this.flags|=E,this._notifySubscribers(void 0,void 0))}_isDirty(){const t=this._deps;return t.hasComputeds?this._deepDirtyCheck():t.isDirtyFast()}_deepDirtyCheck(){const t=this._deps,s=_.current;_.current=null;try{const e=t.size;for(let i=0;i<e;i++){const n=t.getAt(i);if(n==null)continue;const r=n.node;if(r.flags&$)try{r.value}catch{}if(r.version!==n.version)return this._hotIndex=i,!0}return this._hotIndex=-1,!1}finally{_.current=s}}};function mt(t,s={}){return new gt(t,s)}var Tt=class extends x{constructor(t,s={}){super(),this[ht]=!0,this._cleanup=null,this._deps=new Y,this._currentEpoch=v.UNINITIALIZED,this._lastFlushEpoch=v.UNINITIALIZED,this._fn=t,this._onError=s.onError??null,this._sync=s.sync??!1,this._maxExecutions=s.maxExecutionsPerSecond??g.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=s.maxExecutionsPerFlush??g.MAX_EXECUTIONS_PER_EFFECT,this._cleanup=null,this._deps=new Y,this._currentEpoch=v.UNINITIALIZED,this._lastFlushEpoch=v.UNINITIALIZED,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=()=>O.schedule(this),U.attachDebugInfo(this,"effect",this.id)}run(){if(this.flags&f.DISPOSED)throw new D(c.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.flags&f.DISPOSED||(this.flags|=f.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if(!(this.flags&f.EXECUTING))return;const s=this._currentEpoch;if(t._lastSeenEpoch===s)return;t._lastSeenEpoch=s;const e=this._trackCount,i=this._deps;let n;e===0?n=i._s0:e===1?n=i._s1:e===2?n=i._s2:e===3?n=i._s3:n=i.getAt(e),n!=null&&n.node===t?n.version=t.version:i.claimExisting(t,e)||this._insertNewDependency(t,e),t.flags&L.IS_COMPUTED&&(i.hasComputeds=!0),this._trackCount=e+1}_insertNewDependency(t,s){let e;try{const i=t.subscribe(this._notifyCallback);e=new B(t,t.version,i)}catch(i){const n=N(i,D,c.EFFECT_EXECUTION_FAILED);if(console.error(n),this._onError)try{this._onError(n)}catch{}e=new B(t,t.version,void 0)}this._deps.insertNew(s,e)}execute(t=!1){if(this.flags&(f.DISPOSED|f.EXECUTING))return;const s=this._deps;if(!t&&s.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),this.flags|=f.EXECUTING,this._execCleanup(),this._currentEpoch=k(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let e=!1;try{const i=_.run(this,this._fn);s.truncateFrom(this._trackCount),s.seal(),e=!0,ut(i)?this._handleAsyncResult(i):this._cleanup=typeof i=="function"?i:null}catch(i){if(!e)try{s.truncateFrom(this._trackCount)}catch{}this._handleExecutionError(i),this._cleanup=null}finally{this.flags&=~f.EXECUTING}}_isDirty(){const t=this._deps;return t.hasComputeds?this._deepDirtyCheck():t.isDirtyFast()}_handleAsyncResult(t){const s=++this._execId;t.then(e=>{if(s!==this._execId||this.flags&f.DISPOSED){if(typeof e=="function")try{e()}catch(i){this._handleExecutionError(i,c.EFFECT_CLEANUP_FAILED)}return}typeof e=="function"&&(this._cleanup=e)},e=>s===this._execId&&this._handleExecutionError(e))}_deepDirtyCheck(){const t=_.current;_.current=null;const s=this._deps;try{const e=s.size;for(let i=0;i<e;i++){const n=s.getAt(i);if(n==null)continue;const r=n.node;if(r.flags&L.IS_COMPUTED&&this._tryPullComputed(r),r.version!==n.version)return this._hotIndex=i,!0}return!1}finally{_.current=t}}_tryPullComputed(t){try{t.value}catch{}}_execCleanup(){if(this._cleanup){try{this._cleanup()}catch(t){this._handleExecutionError(t,c.EFFECT_CLEANUP_FAILED)}this._cleanup=null}}_checkInfiniteLoops(){const t=it();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),at()>g.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=M.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const s=new D(c.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(s),s}}get isDisposed(){return(this.flags&f.DISPOSED)!==0}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&f.EXECUTING)!==0}_throwInfiniteLoopError(t){const s=new D(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${X}`);throw this.dispose(),console.error(s),s}_handleExecutionError(t,s=c.EFFECT_EXECUTION_FAILED){const e=N(t,D,s);if(console.error(e),this._onError)try{this._onError(e)}catch(i){console.error(N(i,D,c.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function At(t,s={}){if(typeof t!="function")throw new D(c.EFFECT_MUST_BE_FUNCTION);const e=new Tt(t,s);return e.execute(),e}function Nt(t){if(typeof t!="function")throw new TypeError(c.BATCH_CALLBACK_MUST_BE_FUNCTION);O.startBatch();try{return t()}finally{O.endBatch()}}l.AsyncState=p,l.AtomError=m,l.ComputedError=T,l.DEBUG_CONFIG=M,l.DEBUG_RUNTIME=U,l.EffectError=D,l.SCHEDULER_CONFIG=g,l.SchedulerError=R,l.atom=Ct,l.batch=Nt,l.computed=mt,l.effect=At,l.isAtom=vt,l.isComputed=Dt,l.isEffect=St,l.scheduler=O,l.untracked=pt});
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=atom-effect.min.js.map
|