@but212/atom-effect 0.30.1 → 0.32.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 +21 -11
- package/dist/atom-effect.min.js +1 -1
- package/dist/atom-effect.min.js.map +1 -1
- package/dist/constants.d.ts +157 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/core/atom.d.ts +19 -0
- package/dist/core/atom.d.ts.map +1 -0
- package/dist/core/base.d.ts +136 -0
- package/dist/core/base.d.ts.map +1 -0
- package/dist/core/buffers.d.ts +113 -0
- package/dist/core/buffers.d.ts.map +1 -0
- package/dist/core/computed.d.ts +84 -0
- package/dist/core/computed.d.ts.map +1 -0
- package/dist/core/effect.d.ts +52 -0
- package/dist/core/effect.d.ts.map +1 -0
- package/dist/core/index.d.ts +8 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/lens.d.ts +102 -0
- package/dist/core/lens.d.ts.map +1 -0
- package/dist/core/scheduler.d.ts +145 -0
- package/dist/core/scheduler.d.ts.map +1 -0
- package/dist/core/tracking.d.ts +123 -0
- package/dist/core/tracking.d.ts.map +1 -0
- package/dist/errors.d.ts +163 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +8 -510
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +1078 -913
- package/dist/index.mjs.map +1 -1
- package/dist/symbols.d.ts +30 -0
- package/dist/symbols.d.ts.map +1 -0
- package/dist/types.d.ts +259 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/debug.d.ts +20 -0
- package/dist/utils/debug.d.ts.map +1 -0
- package/dist/utils/index.d.ts +13 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/type-guards.d.ts +81 -0
- package/dist/utils/type-guards.d.ts.map +1 -0
- package/package.json +15 -14
package/README.md
CHANGED
|
@@ -4,45 +4,55 @@
|
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|

|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Core reactive state management engine implementing an epoch-based dependency tracking system.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
## Overview
|
|
10
|
+
|
|
11
|
+
This package provides the foundational primitives for reactive programming in JavaScript environments. It manages state synchronization through a pull-based dependency graph, ensuring deterministic execution and automatic resource management.
|
|
12
|
+
|
|
13
|
+
- **Target**: ES2021+
|
|
14
|
+
- **Architecture**: Epoch-based push/pull propagation
|
|
15
|
+
- **Features**: Atomic batching, lazy evaluation, and explicit effect cleanup.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
10
18
|
|
|
11
19
|
```bash
|
|
12
20
|
npm install @but212/atom-effect
|
|
13
21
|
```
|
|
14
22
|
|
|
15
|
-
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
The following example demonstrates the primary primitives for state initialization, derivation, and side-effect orchestration.
|
|
16
26
|
|
|
17
27
|
```typescript
|
|
18
28
|
import { atom, computed, effect } from '@but212/atom-effect';
|
|
19
29
|
|
|
20
|
-
// 1.
|
|
30
|
+
// 1. Initialize State
|
|
21
31
|
const count = atom(0);
|
|
22
32
|
const multiplier = atom(2);
|
|
23
33
|
|
|
24
|
-
// 2. Derive State (Lazy &
|
|
34
|
+
// 2. Derive State (Lazy Evaluation & Identity Caching)
|
|
25
35
|
const doubled = computed(() => count.value * multiplier.value);
|
|
26
36
|
|
|
27
|
-
// 3.
|
|
37
|
+
// 3. Side-Effect Orchestration
|
|
28
38
|
const effectHandle = effect(() => {
|
|
29
39
|
console.log(`Count: ${count.value}, Doubled: ${doubled.value}`);
|
|
30
40
|
});
|
|
31
41
|
// Output: "Count: 0, Doubled: 0"
|
|
32
42
|
|
|
33
|
-
// 4.
|
|
43
|
+
// 4. State Modification
|
|
34
44
|
count.value = 1;
|
|
35
45
|
// Output: "Count: 1, Doubled: 2"
|
|
36
46
|
|
|
37
|
-
// 5.
|
|
47
|
+
// 5. Explicit Disposal
|
|
38
48
|
effectHandle.dispose();
|
|
39
49
|
```
|
|
40
50
|
|
|
41
51
|
## Documentation
|
|
42
52
|
|
|
43
|
-
- [**
|
|
44
|
-
- [**API Reference**](./docs/API.md):
|
|
45
|
-
- [**
|
|
53
|
+
- [**Technical Overview**](./docs/ONBOARDING.md): Core concepts, mental model, and architectural boundaries.
|
|
54
|
+
- [**API Reference**](./docs/API.md): Specification for `atom`, `computed`, `effect`, `batch`, and `untracked`.
|
|
55
|
+
- [**Internals**](./docs/ARCHITECTURE.md): Deep dive into the epoch-based propagation algorithm and dependency slot management.
|
|
46
56
|
|
|
47
57
|
## License
|
|
48
58
|
|
package/dist/atom-effect.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(u,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(u=typeof globalThis<"u"?globalThis:u||self,h(u.AtomEffect={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var h={DISPOSED:1,IS_COMPUTED:2,DIRTY:256,RECOMPUTING:512,HAS_ERROR:1024,FORCE_COMPUTE:2048,IDLE:65536,PENDING:1<<17,RESOLVED:1<<18,REJECTED:1<<19,ATOM_SYNC:1<<24,ATOM_NOTIFICATION_SCHEDULED:1<<25,EFFECT_EXECUTING:1<<28},kt=Object.freeze({ASYNC_STATE:h.IDLE|h.PENDING|h.RESOLVED|h.REJECTED,COMPUTED_DIRTY_MASK:h.DIRTY|h.RECOMPUTING|h.FORCE_COMPUTE}),R=Object.freeze({IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"}),T=Object.freeze({DISPOSED:h.DISPOSED,EXECUTING:h.EFFECT_EXECUTING}),G=Object.freeze({DISPOSED:h.DISPOSED,IS_COMPUTED:h.IS_COMPUTED,DIRTY:h.DIRTY,IDLE:h.IDLE,PENDING:h.PENDING,RESOLVED:h.RESOLVED,REJECTED:h.REJECTED,RECOMPUTING:h.RECOMPUTING,HAS_ERROR:h.HAS_ERROR,FORCE_COMPUTE:h.FORCE_COMPUTE}),f=Object.freeze({DISPOSED:h.DISPOSED,SYNC:h.ATOM_SYNC,NOTIFICATION_SCHEDULED:h.ATOM_NOTIFICATION_SCHEDULED}),I=Object.freeze({MAX_EXECUTIONS_PER_SECOND:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10,BATCH_QUEUE_SHRINK_THRESHOLD:1e3}),k=1073741823,z=Object.freeze({WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3,LOOP_THRESHOLD:100}),Et=Object.freeze({MAX_PROMISE_ID:k}),F=Object.freeze({UNINITIALIZED:-1,MIN:1}),it=!1;try{it=!!(typeof globalThis<"u"&&globalThis.__ATOM_DEBUG__||typeof sessionStorage<"u"&&sessionStorage.getItem("__ATOM_DEBUG__")==="true")}catch{}var a=(typeof process<"u"&&process.env,typeof __DEV__<"u"&&!!__DEV__||it),nt=Object.freeze([]),C=class st extends Error{constructor(e,s=null,i=!0,n){super(e),this.cause=s,this.recoverable=i,this.code=n,this.name="AtomError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getChain(){if(this.cause===null||this.cause===void 0)return[this];const e=[this],s=new Set([this]);let i=this.cause;for(;i!=null;){const n=s.has(i);if(e.push(i),n)break;if(s.add(i),i instanceof st)i=i.cause;else if(i instanceof Error&&"cause"in i)i=i.cause;else break}return e}toJSON(e=new Set){if(e.has(this))return{name:this.name,message:"[Circular Reference]",recoverable:this.recoverable,code:this.code};e.add(this);let s=this.cause;return this.cause instanceof st?s=this.cause.toJSON(e):this.cause instanceof Error&&(s={name:this.cause.name,message:this.cause.message,stack:this.cause.stack,cause:this.cause.cause}),{name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,stack:this.stack,cause:s}}static format(e,s,i){return`${e} (${s}): ${i}`}},N=class extends C{constructor(...t){super(...t),this.name="ComputedError"}},S=class extends C{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="EffectError"}},w=class extends C{constructor(t,e=null,s=!1,i){super(t,e,s,i),this.name="SchedulerError"}},c={COMPUTED_MUST_BE_FUNCTION:"Computed target must be a function",COMPUTED_ASYNC_PENDING_NO_DEFAULT:"Async computation pending with no default value",COMPUTED_COMPUTATION_FAILED:"Computation execution failed",COMPUTED_ASYNC_COMPUTATION_FAILED:"Async computation execution failed",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected",COMPUTED_DISPOSED:"Attempted to access disposed computed",ATOM_SUBSCRIBER_MUST_BE_FUNCTION:"Subscriber must be a function or Subscriber object",ATOM_INDIVIDUAL_SUBSCRIBER_FAILED:"Subscriber execution failed",EFFECT_MUST_BE_FUNCTION:"Effect target must be a function",EFFECT_EXECUTION_FAILED:"Effect execution failed",EFFECT_CLEANUP_FAILED:"Effect cleanup failed",EFFECT_DISPOSED:"Attempted to run disposed effect",SCHEDULER_FLUSH_OVERFLOW:(t,e)=>`Maximum flush iterations (${t}) exceeded. ${e} jobs dropped. Possible infinite loop.`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Exception encountered in onError handler",EFFECT_FREQUENCY_LIMIT_EXCEEDED:"Effect executed too frequently within 1 second. Suspected infinite loop.",SCHEDULER_CALLBACK_MUST_BE_FUNCTION:"Scheduler callback must be a function",SCHEDULER_END_BATCH_WITHOUT_START:"endBatch() called without matching startBatch(). Ignoring.",BATCH_CALLBACK_MUST_BE_FUNCTION:"Batch callback must be a function"};function b(t,e,s){if(t instanceof C)return new e(C.format(t.name,s,t.message),t,t.recoverable,t.code);if(t instanceof Error){const i=t.name||t.constructor.name||"Error";return new e(C.format(i,s,t.message),t)}return new e(C.format("Unexpected error",s,String(t)),t)}var rt=Symbol("AtomEffect.DebugName"),dt=Symbol("AtomEffect.Id"),ot=Symbol("AtomEffect.Type"),X=Symbol("AtomEffect.NoDefaultValue"),pt="[Atom Effect]",It=class{constructor(){this.enabled=!0,this.warnInfiniteLoop=z.WARN_INFINITE_LOOP,this._updateCounts=new Map,this._nodeRegistry=new Map,this._threshold=z.LOOP_THRESHOLD,this._cleanupScheduled=!1,this.warn=(t,e)=>{this.enabled&&t&&console.warn(`${pt} ${e}`)},this.registerNode=t=>{this._nodeRegistry.set(t.id,new WeakRef(t))},this.attachDebugInfo=(t,e,s,i)=>{this.enabled&&(Object.defineProperties(t,{[rt]:{value:i??`${e}_${s}`,configurable:!0},[dt]:{value:s,configurable:!0},[ot]:{value:e,configurable:!0}}),this.registerNode(t))},this.trackUpdate=(t,e)=>{if(!this.enabled||!this.warnInfiniteLoop)return;const s=this._updateCounts,i=(s.get(t)??0)+1;i>this._threshold?this.warn(!0,`Infinite loop detected for ${e??`dependency ${t}`}. Over ${this._threshold} updates in a single execution scope.`):s.set(t,i),this._cleanupScheduled||(this._cleanupScheduled=!0,Promise.resolve().then(()=>{this._updateCounts.clear(),this._cleanupScheduled=!1}))},this.dumpGraph=()=>{const t=[];for(const[e,s]of this._nodeRegistry){const i=s.deref();i?t.push({id:e,name:this.getDebugName(i),type:this.getDebugType(i),updateCount:this._updateCounts.get(e)??0}):(this._nodeRegistry.delete(e),this._updateCounts.delete(e))}return t},this.getDebugName=t=>{if(t)return t[rt]},this.getDebugType=t=>{if(t)return t[ot]}}},Ct={enabled:!1,warnInfiniteLoop:!1,warn:()=>{},registerNode:()=>{},attachDebugInfo:()=>{},trackUpdate:()=>{},dumpGraph:()=>[],getDebugName:()=>{},getDebugType:()=>{}},E=a?new It:Ct,gt=1,Dt=()=>gt++|0,ut=class{constructor(){this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._count=0,this._actualCount=0,this._overflow=null,this._freeIndices=null}_rawWrite(t,e){if(t<4)t===0?this._s0=e:t===1?this._s1=e:t===2?this._s2=e:this._s3=e;else{this._overflow===null&&(this._overflow=[]);const s=this._overflow,i=t-4;s[i]=e}}_rawAdd(t){if(this._s0===null)return this._s0=t,0;if(this._s1===null)return this._s1=t,1;if(this._s2===null)return this._s2=t,2;if(this._s3===null)return this._s3=t,3;this._overflow===null&&(this._overflow=[]);const e=this._overflow,s=this._freeIndices;if(s!==null&&s.length>0){const i=s.pop();return e[i]=t,i+4}return e.push(t),4+e.length-1}_rawSwap(t,e){if(t===e)return;const s=this.getAt(t),i=this.getAt(e);this._rawWrite(t,i),this._rawWrite(e,s)}get size(){return this._actualCount}get physicalSize(){return this._count}getAt(t){return t<4?t===0?this._s0:t===1?this._s1:t===2?this._s2:this._s3:this._overflow?.[t-4]??null}setAt(t,e){const s=this.getAt(t);s!==e&&(this._rawWrite(t,e),s===null?this._actualCount++:e===null&&this._actualCount--,e!==null&&t>=this._count?this._count=t+1:e===null&&this._shrinkPhysicalSizeFrom(t))}_shrinkPhysicalSizeFrom(t){if(t===this._count-1)for(this._count--;this._count>0&&this.getAt(this._count-1)==null;)this._count--}truncateFrom(t){t<=3&&(t<=0&&this._s0!==null&&(this._onItemRemoved(this._s0),this._s0=null,this._actualCount--),t<=1&&this._s1!==null&&(this._onItemRemoved(this._s1),this._s1=null,this._actualCount--),t<=2&&this._s2!==null&&(this._onItemRemoved(this._s2),this._s2=null,this._actualCount--),t<=3&&this._s3!==null&&(this._onItemRemoved(this._s3),this._s3=null,this._actualCount--));const e=this._overflow;if(e!==null){const s=t>4?t-4:0,i=e.length;for(let n=s;n<i;n++){const r=e[n];r!=null&&(this._onItemRemoved(r),e[n]=null,this._actualCount--)}t<=4?this._overflow=null:e.length=t-4}this._count=t,this._actualCount<0&&(this._actualCount=0),this._freeIndices=null}_onItemRemoved(t){}add(t){const e=this._rawAdd(t);return e>=this._count&&(this._count=e+1),this._actualCount++,e}remove(t){let e=-1;if(this._s0===t)e=0;else if(this._s1===t)e=1;else if(this._s2===t)e=2;else if(this._s3===t)e=3;else{const s=this._overflow;s!==null&&(e=s.indexOf(t),e!==-1&&(e+=4))}return e!==-1?(this._rawWrite(e,null),this._shrinkPhysicalSizeFrom(e),this._actualCount--,e>=4&&(this._freeIndices===null&&(this._freeIndices=[]),this._freeIndices.push(e-4)),!0):!1}has(t){if(this._actualCount===0)return!1;if(this._s0===t||this._s1===t||this._s2===t||this._s3===t)return!0;const e=this._overflow;return e!==null?e.indexOf(t)!==-1:!1}forEach(t){const e=this._actualCount;if(e===0)return;if(e===this._count){this._s0!=null&&t(this._s0),this._s1!=null&&t(this._s1),this._s2!=null&&t(this._s2),this._s3!=null&&t(this._s3);const n=this._overflow;if(n!==null)for(let r=0,o=n.length;r<o;r++){const l=n[r];l!=null&&t(l)}return}let s=0;const i=this._count;for(let n=0;n<i;n++){const r=this.getAt(n);if(r!=null&&(t(r),++s>=e))break}}compact(){if(this._actualCount===this._count)return;let t=0;const e=this._count;for(let s=0;s<e;s++){const i=this.getAt(s);i!=null&&(s!==t&&(this._rawWrite(t,i),this._rawWrite(s,null)),t++)}this._count=this._actualCount,this._overflow!==null&&(t<=4?this._overflow=null:this._overflow.length=t-4),this._freeIndices=null}clear(){this._s0=this._s1=this._s2=this._s3=null,this._count=0,this._actualCount=0,this._overflow=null,this._freeIndices=null}dispose(){this.clear()}},ht=class extends ut{constructor(...t){super(...t),this._map=null,this._SCAN_THRESHOLD=32,this.hasComputeds=!1}prepareTracking(){this.hasComputeds=!1}_onItemRemoved(t){t.unsub?.()}setAt(t,e){const s=this.getAt(t);super.setAt(t,e),this._map!==null&&(s?.unsub&&this._map.delete(s.node),e?.unsub&&this._map.set(e.node,t))}claimExisting(t,e){const s=this._count;if(s<=e)return!1;const i=this.getAt(e);if(i&&i.node===t&&i.unsub)return i.version=t.version,!0;if(this._map!==null||s-e>this._SCAN_THRESHOLD)return this._claimViaMap(t,e);for(let n=e+1;n<s;n++){const r=this.getAt(n);if(r&&r.node===t&&r.unsub)return r.version=t.version,this._rawSwap(n,e),!0}return!1}_claimViaMap(t,e){this._map===null&&(this._map=this._initMap());const s=this._map,i=s.get(t);if(i===void 0||i<e)return!1;const n=this.getAt(i);if(n==null||!n.unsub)return!1;if(n.version=t.version,i!==e){const r=this.getAt(e);this._rawSwap(i,e),s.set(t,e),r?.unsub&&s.set(r.node,i)}return!0}_initMap(){const t=new Map;for(let e=0;e<this._count;e++){const s=this.getAt(e);s?.unsub&&t.set(s.node,e)}return t}insertNew(t,e){const s=this.getAt(t);if(s!==null){const i=this._rawAdd(s);i>=this._count&&(this._count=i+1),this._map!==null&&s.unsub&&this._map.set(s.node,i)}this._rawWrite(t,e),t>=this._count&&(this._count=t+1),this._actualCount++,this._map!==null&&e.unsub&&this._map.set(e.node,t)}add(t){const e=super.add(t);return this._map!==null&&t.unsub&&this._map.set(t.node,e),e}remove(t){throw new Error("remove() prohibited")}compact(){}truncateFrom(t){super.truncateFrom(t),this._map!==null&&(this._map=null)}disposeAll(){this.truncateFrom(0),this.hasComputeds=!1}},U=Symbol.for("atom-effect/brand"),g={Atom:1,Writable:2,Computed:4,Effect:8};function Q(t,e){if(!t)return!1;const s=typeof t;return(s==="object"||s==="function")&&!!((t[U]??0)&e)}function St(t){return Q(t,g.Atom)}function mt(t){return Q(t,g.Computed)}function Tt(t){return Q(t,g.Effect)}function Y(t){if(t instanceof Promise)return!0;if(!t)return!1;const e=typeof t;return(e==="object"||e==="function")&&typeof t.then=="function"}var V=class{constructor(t,e,s=void 0){this.node=t,this.version=e,this.unsub=s}},vt=class{constructor(t=void 0,e=void 0){this.fn=t,this.sub=e}notify(t,e){L(()=>{const s=this.fn;s!==void 0&&s(t,e);const i=this.sub;i!==void 0&&i.execute()})}},Ot=class{constructor(){this.current=null}run(t,e){if(this.current===t)return e();const s=this.current;this.current=t;try{const i=e();return a&&E.warn(Y(i),'Detected Promise returned within tracking context. Dependencies accessed after "await" will NOT be tracked. Consider using synchronous tracking before the async boundary.'),i}finally{this.current=s}}},_=new Ot;function L(t){const e=_,s=e.current;if(s===null)return t();e.current=null;try{return t()}finally{e.current=s}}var j=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=F.UNINITIALIZED,this._nextEpoch=void 0,this._notifying=0,this._hotIndex=-1,this._slots=null,this._deps=null,this.id=Dt()&k}get isDisposed(){return(this.flags&G.DISPOSED)!==0}get isComputed(){return(this.flags&G.IS_COMPUTED)!==0}get hasError(){return!1}subscribe(t){const e=typeof t=="function";if(!e&&(!t||typeof t.execute!="function"))throw b(new TypeError("Invalid subscriber"),C,c.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let s=this._slots;s||(s=new ut,this._slots=s);let i=!1;if(s._s0!=null&&(e?s._s0.fn===t:s._s0.sub===t))i=!0;else if(s._s1!=null&&(e?s._s1.fn===t:s._s1.sub===t))i=!0;else if(s._s2!=null&&(e?s._s2.fn===t:s._s2.sub===t))i=!0;else if(s._s3!=null&&(e?s._s3.fn===t:s._s3.sub===t))i=!0;else{const r=s._overflow;if(r!=null)for(let o=0,l=r.length;o<l;o++){const p=r[o];if(p!=null&&(e?p.fn===t:p.sub===t)){i=!0;break}}}if(i)return a&&console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`),()=>{};const n=new vt(e?t:void 0,e?void 0:t);return s.add(n),()=>this._unsubscribe(n)}_unsubscribe(t){const e=this._slots;e&&(e.remove(t),this._notifying===0&&e.compact())}subscriberCount(){const t=this._slots;return t===null?0:t.size}_notifySubscribers(t,e){const s=this._slots;if(!(s===null||s.size===0)){this._notifying++;try{let i=s._s0;if(i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s1,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s2,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}if(i=s._s3,i!=null)try{i.notify(t,e)}catch(r){this._logNotifyError(r)}const n=s._overflow;if(n!=null)for(let r=0,o=n.length;r<o;r++){const l=n[r];if(l!=null)try{l.notify(t,e)}catch(p){this._logNotifyError(p)}}}finally{--this._notifying===0&&s.compact()}}}_logNotifyError(t){console.error(b(t,C,c.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED))}_isDirty(){const t=this._deps;if(t===null||t.size===0)return!1;const e=this._hotIndex;if(e!==-1){const s=t.getAt(e);if(s!=null&&s.node.version!==s.version)return!0}return this._deepDirtyCheck()}},W=0;function $(){const t=W+1&k;return W=t===0?1:t,W}function q(t){const e=t+1&k;return e===0?1:e}var K=0,B=!1,ct=0;function Nt(){return ct}function lt(){return B?(a&&console.warn("startFlush() called during flush - ignored"),!1):(B=!0,ct=$(),K=0,!0)}function _t(){B=!1}function bt(){if(!B)return 0;const t=++K;if(t<=I.MAX_EXECUTIONS_PER_FLUSH)return t;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${I.MAX_EXECUTIONS_PER_FLUSH}`)}var At=class{constructor(){this._queueBuffer=[[],[]],this._bufferIndex=0,this._size=0,this._epoch=0,this._isProcessing=!1,this._isFlushingSync=!1,this._batchDepth=0,this._batchQueue=[],this._batchQueueSize=0,this._maxFlushIterations=I.MAX_FLUSH_ITERATIONS,this.onOverflow=null,this._boundRunLoop=this._runLoop.bind(this)}get queueSize(){return this._size+this._batchQueueSize}get isBatching(){return this._batchDepth>0}schedule(t){if(a&&typeof t!="function"&&(!t||typeof t.execute!="function"))throw new w(c.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);const e=this._epoch;if(t._nextEpoch===e)return;if(t._nextEpoch=e,this._batchDepth>0||this._isFlushingSync){this._batchQueue[this._batchQueueSize++]=t;return}const s=this._queueBuffer[this._bufferIndex];s[this._size++]=t,this._isProcessing||this._flush()}_flush(){this._isProcessing||this._size===0||(this._isProcessing=!0,queueMicrotask(this._boundRunLoop))}_runLoop(){try{if(this._size===0&&this._batchQueueSize===0)return;const t=lt();this._drainQueue(),t&&_t()}finally{this._isProcessing=!1}}_flushSync(){if(this._size===0&&this._batchQueueSize===0)return;const t=this._isFlushingSync;this._isFlushingSync=!0;const e=lt();try{this._mergeBatchQueue(),this._drainQueue()}finally{this._isFlushingSync=t,e&&_t()}}_mergeBatchQueue(){const t=this._batchQueueSize;if(t===0)return;this._epoch=this._epoch+1|0;const e=this._epoch,s=this._batchQueue,i=this._queueBuffer[this._bufferIndex];let n=this._size;for(let r=0;r<t;r++){const o=s[r];o._nextEpoch!==e&&(o._nextEpoch=e,i[n++]=o),s[r]=void 0}this._size=n,this._batchQueueSize=0,s.length>I.BATCH_QUEUE_SHRINK_THRESHOLD&&(s.length=0)}_drainQueue(){let t=0;for(;this._size>0||this._batchQueueSize>0;){if(++t>this._maxFlushIterations){this._handleFlushOverflow();return}this._batchQueueSize>0&&this._mergeBatchQueue(),this._size>0&&this._processQueue()}}_processQueue(){const t=this._bufferIndex,e=this._queueBuffer[t],s=this._size;this._bufferIndex=t^1,this._size=0,this._epoch=this._epoch+1|0;for(let i=0;i<s;i++){const n=e[i];e[i]=void 0;try{typeof n=="function"?n():n.execute()}catch(r){console.error(new w("Error occurred during scheduler execution",r))}}}_handleFlushOverflow(){const t=this._size+this._batchQueueSize;console.error(new w(c.SCHEDULER_FLUSH_OVERFLOW(this._maxFlushIterations,t))),this._size=0,this._queueBuffer[0].length=0,this._queueBuffer[1].length=0,this._batchQueueSize=0,this._batchQueue.length=0;const e=this.onOverflow;if(e)try{e(t)}catch{}}startBatch(){this._batchDepth++}endBatch(){if(this._batchDepth===0){a&&console.warn(c.SCHEDULER_END_BATCH_WITHOUT_START);return}--this._batchDepth===0&&(this._isFlushingSync||this._flushSync())}setMaxFlushIterations(t){if(t<I.MIN_FLUSH_ITERATIONS)throw new w(`Max iterations must be at least ${I.MIN_FLUSH_ITERATIONS}`);this._maxFlushIterations=t}},v=new At;function yt(t){if(a&&typeof t!="function")throw new TypeError(c.BATCH_CALLBACK_MUST_BE_FUNCTION);v.startBatch();try{return t()}finally{v.endBatch()}}var Rt=class extends j{constructor(t,e){super(),this[U]=g.Atom|g.Writable,this._value=t,this._equal=e.equal??Object.is,e.sync&&(this.flags|=f.SYNC),E.attachDebugInfo(this,"atom",this.id,e.name)}get isNotificationScheduled(){return(this.flags&f.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&f.SYNC)!==0}get value(){const t=_.current;return t?.addDependency(this),this._value}set value(t){const e=this._value;if(this._equal(e,t)||(this._value=t,this.version=q(this.version),E.trackUpdate(this.id,E.getDebugName(this)),(this.flags&f.NOTIFICATION_SCHEDULED)!==0))return;const s=this._slots;s==null||s.size===0||(this._pendingOldValue=e,this.flags|=f.NOTIFICATION_SCHEDULED,(this.flags&f.SYNC)!==0&&!v.isBatching?this._notifying===0&&this._flushNotifications():v.schedule(this))}execute(){this._flushNotifications()}_flushNotifications(){const t=f.NOTIFICATION_SCHEDULED,e=f.DISPOSED,s=f.SYNC;for(;(this.flags&(t|e))===t;){const i=this._pendingOldValue;if(this._pendingOldValue=void 0,this.flags&=~t,this._equal(this._value,i)||this._notifySubscribers(this._value,i),(this.flags&s)===0||v.isBatching)break}}peek(){return this._value}dispose(){const t=this.flags;(t&f.DISPOSED)===0&&(this._slots?.clear(),this.flags=t|f.DISPOSED,this._value=void 0,this._pendingOldValue=void 0,this._equal=Object.is)}_deepDirtyCheck(){return!1}[Symbol.dispose](){this.dispose()}};function Ft(t,e={}){return new Rt(t,e)}var{IDLE:m,DIRTY:d,PENDING:A,RESOLVED:D,REJECTED:O,HAS_ERROR:H,RECOMPUTING:P,DISPOSED:J,IS_COMPUTED:M,FORCE_COMPUTE:Z}=G,wt=class extends j{constructor(t,e={}){if(typeof t!="function")throw new N(c.COMPUTED_MUST_BE_FUNCTION);if(super(),this[U]=g.Atom|g.Computed,this._error=null,this._promiseId=0,this._deps=new ht,this._trackEpoch=F.UNINITIALIZED,this._trackCount=0,this._value=void 0,this.flags=M|d|m,this._equal=e.equal??Object.is,this._fn=t,this._defaultValue="defaultValue"in e?e.defaultValue:X,this._onError=e.onError??null,E.attachDebugInfo(this,"computed",this.id,e.name),e.lazy===!1)try{this._recompute()}catch{}}get isDirty(){return(this.flags&d)!==0}get isRejected(){return(this.flags&O)!==0}get isRecomputing(){return(this.flags&P)!==0}get _hasErrorInternal(){return(this.flags&H)!==0}_track(){_.current?.addDependency(this)}get value(){const t=_.current;t?.addDependency(this);let e=this.flags;if((e&(D|d|m))===D)return this._value;if((e&J)!==0)throw new N(c.COMPUTED_DISPOSED);if((e&P)!==0){const n=this._defaultValue;if(n!==X)return n;throw new N(c.COMPUTED_CIRCULAR_DEPENDENCY)}if((e&(d|m))!==0){const n=this._deps;if((e&m)===0&&(e&Z)===0&&n.size>0&&!this._isDirty()?e=this.flags&=~d:(this._recompute(),e=this.flags),(e&D)!==0)return this._value}const s=this._defaultValue,i=s!==X;if((e&A)!==0){if(i)return s;throw new N(c.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}if((e&O)!==0){if(i)return s;throw this._error}return this._value}peek(){return this._value}get state(){const t=_.current;t?.addDependency(this);const e=this.flags;return(e&D)!==0?R.RESOLVED:(e&A)!==0?R.PENDING:(e&O)!==0?R.REJECTED:R.IDLE}get hasError(){const t=_.current;if(t?.addDependency(this),(this.flags&(O|H))!==0)return!0;const e=this._deps;return e.hasComputeds?L(()=>{const s=e.size;for(let i=0;i<s;i++)if(e.getAt(i)?.node.hasError)return!0;return!1}):!1}get isValid(){return!this.hasError}get errors(){const t=_.current;t?.addDependency(this);const e=this._error,s=this._deps;if(!s.hasComputeds)return e==null?nt:Object.freeze([e]);const i=[];return e!=null&&i.push(e),L(()=>{const n=s.size;for(let r=0;r<n;r++){const o=s.getAt(r)?.node;o!=null&&(o.flags&M)!==0&&this._accumulateErrors(o,i)}}),i.length===0?nt:Object.freeze(i)}_accumulateErrors(t,e){const s=t._error;s!=null&&!e.includes(s)&&e.push(s);const i=t._deps;if(!i.hasComputeds)return;const n=i.size;for(let r=0;r<n;r++){const o=i.getAt(r)?.node;o!=null&&(o.flags&M)!==0&&this._accumulateErrors(o,e)}}get lastError(){const t=_.current;return t?.addDependency(this),this._error}get isPending(){const t=_.current;return t?.addDependency(this),(this.flags&A)!==0}get isResolved(){const t=_.current;return t?.addDependency(this),(this.flags&D)!==0}invalidate(){this.flags|=Z,this._markDirty()}dispose(){(this.flags&J)===0&&(this._deps.disposeAll(),this._slots!=null&&this._slots.clear(),this.flags=J|d|m,this._error=null,this._value=void 0,this._hotIndex=-1)}[Symbol.dispose](){this.dispose()}addDependency(t){const e=this._trackEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,i=this._deps,n=i.getAt(s);if(n!=null&&n.node===t)n.version=t.version;else if(!i.claimExisting(t,s)){const r=new V(t,t.version,t.subscribe(this));i.insertNew(s,r)}(t.flags&M)!==0&&(i.hasComputeds=!0)}_recompute(){if(this.isRecomputing)return;this.flags=(this.flags|P)&~Z,this._trackEpoch=$(),this._trackCount=0,this._deps.prepareTracking(),this._hotIndex=-1;let t=!1;try{const e=_.run(this,this._fn);this._deps.truncateFrom(this._trackCount),t=!0,Y(e)?this._handleAsyncComputation(e):this._finalizeResolution(e)}catch(e){if(!t)try{this._deps.truncateFrom(this._trackCount)}catch(s){a&&console.warn("[atom-effect] _commitDeps failed during error recovery:",s)}this._handleError(e,c.COMPUTED_COMPUTATION_FAILED,!0)}finally{this._trackEpoch=F.UNINITIALIZED,this._trackCount=0,this.flags&=~P}}_handleAsyncComputation(t){this.flags=(this.flags|A)&~(m|d|D|O),this._notifySubscribers(void 0,void 0),this._promiseId=(this._promiseId+1)%Et.MAX_PROMISE_ID;const e=this._promiseId;t.then(s=>{if(e===this._promiseId){if(this._isDirty())return this._markDirty();this._finalizeResolution(s),this._notifySubscribers(s,void 0)}},s=>e===this._promiseId&&this._handleError(s,c.COMPUTED_ASYNC_COMPUTATION_FAILED))}_handleError(t,e,s=!1){const i=b(t,N,e);if((!this.isRejected||this._error!==i)&&(this.version=q(this.version)),this._error=i,this.flags=this.flags&~(m|d|A|D)|O|H,this._onError)try{this._onError(i)}catch(n){console.error(c.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(this._notifySubscribers(void 0,void 0),s)throw i}_finalizeResolution(t){const e=this.flags;((e&D)===0||!this._equal(this._value,t))&&(this.version=q(this.version)),this._value=t,this._error=null,this.flags=(e|D)&~(m|d|A|O|H)}execute(){this._markDirty()}_markDirty(){const t=this.flags;(t&(P|d))===0&&(this.flags=t|d,E.trackUpdate(this.id,E.getDebugName(this)),this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){const t=this._deps;return L(()=>{const e=t.size;for(let s=0;s<e;s++){const i=t.getAt(s);if(i==null)continue;const n=i.node;if((n.flags&M)!==0)try{n.value}catch{a&&console.warn(`[atom-effect] Dependency #${n.id} threw during dirty check`)}if(n.version!==i.version)return this._hotIndex=s,!0}return this._hotIndex=-1,!1})}};function Ut(t,e={}){return new wt(t,e)}var Lt=class extends j{constructor(t,e={}){super(),this[U]=g.Effect,this._cleanup=null,this._deps=new ht,this._currentEpoch=F.UNINITIALIZED,this._lastFlushEpoch=F.UNINITIALIZED,this._fn=t,this._onError=e.onError??null,this._sync=e.sync??!1,this._maxExecutions=e.maxExecutionsPerSecond??I.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=e.maxExecutionsPerFlush??I.MAX_EXECUTIONS_PER_EFFECT,this._executionsInEpoch=0,this._executionCount=0,this._windowStart=0,this._windowCount=0,this._execId=0,this._trackCount=0,this._sync?this._notifyCallback=()=>this.execute():this._notifyCallback=()=>v.schedule(this),E.attachDebugInfo(this,"effect",this.id,e.name)}run(){if(this.isDisposed)throw new S(c.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=T.DISPOSED,this._execCleanup(),this._deps?.disposeAll())}[Symbol.dispose](){this.dispose()}addDependency(t){if((this.flags&T.EXECUTING)===0)return;const e=this._currentEpoch;if(t._lastSeenEpoch===e)return;t._lastSeenEpoch=e;const s=this._trackCount++,i=this._deps;let n;switch(s){case 0:n=i._s0;break;case 1:n=i._s1;break;case 2:n=i._s2;break;case 3:n=i._s3;break;default:n=i.getAt(s)}n!=null&&n.node===t?n.version=t.version:i.claimExisting(t,s)||this._insertNewDependency(t,s),t.isComputed&&(i.hasComputeds=!0)}_insertNewDependency(t,e){let s;try{const i=t.subscribe(this._notifyCallback);s=new V(t,t.version,i)}catch(i){const n=b(i,S,c.EFFECT_EXECUTION_FAILED);if(console.error(n),this._onError)try{this._onError(n)}catch{}s=new V(t,t.version,void 0)}this._deps.insertNew(e,s)}execute(t=!1){const e=this.flags;if((e&(T.DISPOSED|T.EXECUTING))!==0)return;const s=this._deps;if(!t&&s.size>0&&!this._isDirty())return;this._checkInfiniteLoops(),E.trackUpdate(this.id,E.getDebugName(this)),this.flags=e|T.EXECUTING,this._execCleanup(),this._currentEpoch=$(),this._trackCount=0,s.prepareTracking(),this._hotIndex=-1;let i=!1;try{const n=_.run(this,this._fn);s.truncateFrom(this._trackCount),i=!0,Y(n)?this._handleAsyncResult(n):this._cleanup=typeof n=="function"?n:null}catch(n){if(!i)try{s.truncateFrom(this._trackCount)}catch(r){a&&console.warn("[atom-effect] _commitDeps failed during error recovery:",r)}this._handleExecutionError(n),this._cleanup=null}finally{this.flags&=~T.EXECUTING}}_handleAsyncResult(t){const e=++this._execId;t.then(s=>{if(e!==this._execId||this.isDisposed){if(typeof s=="function")try{s()}catch(i){this._handleExecutionError(i,c.EFFECT_CLEANUP_FAILED)}return}typeof s=="function"&&(this._cleanup=s)},s=>e===this._execId&&this._handleExecutionError(s))}_deepDirtyCheck(){const t=_.current;_.current=null;const e=this._deps;try{const s=e.size;for(let i=0;i<s;i++){const n=e.getAt(i);if(n==null)continue;const r=n.node;if(r.isComputed&&this._tryPullComputed(r),r.version!==n.version)return this._hotIndex=i,!0}return!1}finally{_.current=t}}_tryPullComputed(t){try{t.value}catch{a&&console.warn(`[atom-effect] Dependency #${t.id} threw during dirty check`)}}_execCleanup(){const t=this._cleanup;if(t!=null){this._cleanup=null;try{t()}catch(e){this._handleExecutionError(e,c.EFFECT_CLEANUP_FAILED)}}}_checkInfiniteLoops(){const t=Nt();this._lastFlushEpoch!==t&&(this._lastFlushEpoch=t,this._executionsInEpoch=0),++this._executionsInEpoch>this._maxExecutionsPerFlush&&this._throwInfiniteLoopError("per-effect"),bt()>I.MAX_EXECUTIONS_PER_FLUSH&&this._throwInfiniteLoopError("global"),this._executionCount++,a&&this._checkFrequencyLimit()}_checkFrequencyLimit(){if(!Number.isFinite(this._maxExecutions))return;const t=Date.now();if(t-this._windowStart>=z.EFFECT_FREQUENCY_WINDOW){this._windowStart=t,this._windowCount=1;return}if(++this._windowCount>this._maxExecutions){const e=new S(c.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(e),e}}get executionCount(){return this._executionCount}get isExecuting(){return(this.flags&T.EXECUTING)!==0}_throwInfiniteLoopError(t){const e=new S(`Infinite loop detected (${t}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${K}`);throw this.dispose(),console.error(e),e}_handleExecutionError(t,e=c.EFFECT_EXECUTION_FAILED){const s=b(t,S,e);if(console.error(s),this._onError)try{this._onError(s)}catch(i){console.error(b(i,S,c.CALLBACK_ERROR_IN_ERROR_HANDLER))}}};function Pt(t,e={}){if(typeof t!="function")throw new S(c.EFFECT_MUST_BE_FUNCTION);const s=new Lt(t,e);return s.execute(),s}var at=/^(?:__proto__|constructor|prototype)$/;function tt(t,e,s,i){if(s===e.length)return i;const n=e[s];if(at.test(n))return t;const r=t!=null&&typeof t=="object"?t:{},o=r[n],l=tt(o,e,s+1,i);if(Object.is(o,l))return t;if(Array.isArray(r)){const p=r.slice(),y=Number(n);return n.trim()!==""&&Number.isInteger(y)&&y>=0?p[y]=l:p[n]=l,p}return{...r,[n]:l}}function x(t,e){let s=t;const i=e.length;for(let n=0;n<i;n++){if(s==null)return;const r=e[n];if(at.test(r))return;s=s[r]}return s}function et(t,e){const s=e.includes(".")?e.split("."):[e],i=new Set,n=()=>{i.forEach(r=>r()),i.clear()};return{get value(){return x(t.value,s)},set value(r){const o=t.peek(),l=tt(o,s,0,r);l!==o&&(t.value=l)},peek:()=>x(t.peek(),s),subscribe(r){const o=t.subscribe((l,p)=>{const y=x(l,s),ft=x(p,s);Object.is(y,ft)||r(y,ft)});return i.add(o),()=>{o(),i.delete(o)}},subscriberCount:()=>i.size,dispose:n,[Symbol.dispose]:n,[U]:g.Atom|g.Writable}}var Mt=(t,e)=>et(t,e),xt=t=>e=>et(t,e);u.AsyncState=R,u.AtomError=C,u.ComputedError=N,u.DEBUG_CONFIG=z,u.EffectError=S,u.SCHEDULER_CONFIG=I,u.SchedulerError=w,u.atom=Ft,u.atomLens=et,u.batch=yt,u.composeLens=Mt,u.computed=Ut,u.effect=Pt,u.getPathValue=x,u.globalScheduler=v,u.isAtom=St,u.isComputed=mt,u.isEffect=Tt,u.lensFor=xt,u.runtimeDebug=E,u.setDeepValue=tt,u.untracked=L});
|
|
1
|
+
(function(u,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):(u=typeof globalThis<"u"?globalThis:u||self,_(u.AtomEffect={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var _={CORE:0,COMPUTED:8,ASYNC:16,PRIMITIVE:24},c={DISPOSED:1<<_.CORE+0,IS_COMPUTED:1<<_.CORE+1,DIRTY:1<<_.COMPUTED+0,RECOMPUTING:1<<_.COMPUTED+1,HAS_ERROR:1<<_.COMPUTED+2,FORCE_COMPUTE:1<<_.COMPUTED+3,IDLE:1<<_.ASYNC+0,PENDING:1<<_.ASYNC+1,RESOLVED:1<<_.ASYNC+2,REJECTED:1<<_.ASYNC+3,ATOM_SYNC:1<<_.PRIMITIVE+0,ATOM_NOTIFICATION_SCHEDULED:1<<_.PRIMITIVE+1,EFFECT_EXECUTING:1<<_.PRIMITIVE+4},Xt=Object.freeze({ASYNC_STATE:c.IDLE|c.PENDING|c.RESOLVED|c.REJECTED,COMPUTED_DIRTY_MASK:c.DIRTY|c.RECOMPUTING|c.FORCE_COMPUTE}),w=Object.freeze({IDLE:"idle",PENDING:"pending",RESOLVED:"resolved",REJECTED:"rejected"}),N=Object.freeze({DISPOSED:c.DISPOSED,EXECUTING:c.EFFECT_EXECUTING}),U=Object.freeze({DISPOSED:c.DISPOSED,IS_COMPUTED:c.IS_COMPUTED,DIRTY:c.DIRTY,IDLE:c.IDLE,PENDING:c.PENDING,RESOLVED:c.RESOLVED,REJECTED:c.REJECTED,RECOMPUTING:c.RECOMPUTING,HAS_ERROR:c.HAS_ERROR,FORCE_COMPUTE:c.FORCE_COMPUTE}),D=Object.freeze({DISPOSED:c.DISPOSED,SYNC:c.ATOM_SYNC,NOTIFICATION_SCHEDULED:c.ATOM_NOTIFICATION_SCHEDULED}),I=Object.freeze({MAX_EXECUTIONS_PER_SECOND:1e3,MAX_EXECUTIONS_PER_EFFECT:100,MAX_EXECUTIONS_PER_FLUSH:1e4,MAX_FLUSH_ITERATIONS:1e3,MIN_FLUSH_ITERATIONS:10,BATCH_QUEUE_SHRINK_THRESHOLD:1e3}),Ce=1073741823,ee=Object.freeze({WARN_INFINITE_LOOP:!0,EFFECT_FREQUENCY_WINDOW:1e3,LOOP_THRESHOLD:100}),k=Object.freeze({UNINITIALIZED:-1,MIN:1}),We=()=>{try{return!!(typeof globalThis<"u"&&globalThis.__ATOM_DEBUG__||typeof sessionStorage<"u"&&sessionStorage.getItem("__ATOM_DEBUG__")==="true")}catch{return!1}},$e=()=>{try{return!1}catch{return!1}},V={node:typeof process<"u"&&process.env&&process.env.NODE_ENV!=="production",bundler:typeof __DEV__<"u"&&!!__DEV__,esm:typeof process>"u"&&$e(),runtime:We()},p=V.node||V.bundler||V.esm||V.runtime,Ke=Object.freeze([]),Qe=Symbol.for("atom-effect.Option"),qe=Symbol.for("atom-effect.Result"),Wt=Object.freeze({ok:!1,value:void 0,[Qe]:!0}),$t=Object.freeze({ok:!0,value:void 0,error:void 0,[qe]:!0}),Je=[0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,-1],E=4,Ze=15,Se=class{constructor(){this._count=0,this._actualCount=0,this._mask=0,this._s0=null,this._s1=null,this._s2=null,this._s3=null,this._overflow=null,this._freeIndices=null,this._lockCount=0,this._pendingCompact=!1}_firstFreeSlot(e){return Je[e&Ze]}_rawWrite(e,t){if(e<E){const s=1<<e;t===null?this._mask&=~s:this._mask|=s,e===0?this._s0=t:e===1?this._s1=t:e===2?this._s2=t:e===3&&(this._s3=t)}else this._overflow||(this._overflow=[]),this._overflow[e-E]=t}_rawAdd(e){const t=this._mask,s=this._firstFreeSlot(t);if(s!==-1)return this._mask=t|1<<s,s===0?this._s0=e:s===1?this._s1=e:s===2?this._s2=e:this._s3=e,s;this._overflow||(this._overflow=[]);const r=this._overflow,i=this._freeIndices;if(i?.length){const n=i.pop();return r[n]=e,n+E}return r.push(e),E-1+r.length}_rawSwap(e,t){if(e===t)return;const s=this.at(e),r=this.at(t);this._rawWrite(e,r),this._rawWrite(t,s)}get length(){return this._count}get size(){return this._actualCount}at(e){if(e<E)return e===0?this._s0:e===1?this._s1:e===2?this._s2:e===3?this._s3:null;const t=this._overflow;return t?t[e-E]??null:null}setAt(e,t){const s=this.at(e);s!==t&&(this._rawWrite(e,t),s===null?this._actualCount++:t===null&&this._actualCount--,t!==null?e>=this._count&&(this._count=e+1):this._shrinkPhysicalSizeFrom(e))}_shrinkPhysicalSizeFrom(e){if(e===this._count-1){if(this._count--,this._count>E){const t=this._overflow;for(;this._count>E&&t[this._count-(E+1)]==null;)this._count--}this._count<=E&&(this._count=32-Math.clz32(this._mask))}}truncateFrom(e){const t=this._count;if(!(e>=t)){for(let s=e;s<t;s++)this.at(s)!==null&&this._actualCount--;e<E?(this._mask&=(1<<e)-1,e<=0&&(this._s0=null),e<=1&&(this._s1=null),e<=2&&(this._s2=null),e<=3&&(this._s3=null),this._overflow=null):this._overflow&&(this._overflow.length=e-E),this._count=e,this._freeIndices=null}}push(e){const t=this._rawAdd(e);return t>=this._count&&(this._count=t+1),this._actualCount++,t}remove(e){if(this._actualCount===0)return!1;const t=this._mask;if(t&1&&this._s0===e)return this._removeAt(0);if(t&2&&this._s1===e)return this._removeAt(1);if(t&4&&this._s2===e)return this._removeAt(2);if(t&8&&this._s3===e)return this._removeAt(3);const s=this._overflow;if(s){for(let r=0,i=s.length;r<i;r++)if(s[r]===e)return s[r]=null,this._actualCount--,this._shrinkPhysicalSizeFrom(r+E),this._freeIndices||(this._freeIndices=[]),this._freeIndices.push(r),!0}return!1}_removeAt(e){return this._rawWrite(e,null),this._actualCount--,this._shrinkPhysicalSizeFrom(e),!0}has(e){if(this._actualCount===0)return!1;const t=this._mask;if(t&1&&this._s0===e||t&2&&this._s1===e||t&4&&this._s2===e||t&8&&this._s3===e)return!0;const s=this._overflow;if(s){for(let r=0,i=s.length;r<i;r++)if(s[r]===e)return!0}return!1}forEach(e){if(this._actualCount===0)return;const t=this._mask;t&1&&e(this._s0),t&2&&e(this._s1),t&4&&e(this._s2),t&8&&e(this._s3);const s=this._overflow;if(s)for(let r=0,i=s.length;r<i;r++){const n=s[r];n!=null&&e(n)}}some(e){if(this._actualCount===0)return!1;const t=this._mask;if(t&1&&e(this._s0)||t&2&&e(this._s1)||t&4&&e(this._s2)||t&8&&e(this._s3))return!0;const s=this._overflow;if(s)for(let r=0,i=s.length;r<i;r++){const n=s[r];if(n!=null&&e(n))return!0}return!1}compact(){if(this._lockCount>0){this._pendingCompact=!0;return}const e=this._actualCount,t=this._count;if(e===t)return;if(e===0){this.clear();return}let s=0;const r=this._overflow;for(let i=0;i<t;i++){const n=this.at(i);if(n!==null&&(i!==s&&(this._rawWrite(s,n),this._rawWrite(i,null)),++s===e))break}this._count=e,r!==null&&(s<=E?this._overflow=null:r.length=s-E),this._freeIndices=null,this._pendingCompact=!1}lock(){this._lockCount++}unlock(){--this._lockCount===0&&this._pendingCompact&&this.compact()}clear(){this._s0=this._s1=this._s2=this._s3=null,this._count=0,this._actualCount=0,this._mask=0,this._overflow=null,this._freeIndices=null,this._pendingCompact=!1}dispose(){this.clear()}get isLocked(){return this._lockCount>0}};function te(e){return e instanceof Promise?!0:e===null||typeof e!="object"&&typeof e!="function"?!1:typeof e.then=="function"}var et=Object.prototype.hasOwnProperty;function tt(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;const s=e,r=t,i=Object.keys(s);if(i.length!==Object.keys(r).length)return!1;for(const n of i)if(!et.call(r,n)||!Object.is(s[n],r[n]))return!1;return!0}var T=class extends Error{constructor(e,t=null,s=!0,r){super(e),this.cause=t,this.recoverable=s,this.code=r,this.name="AtomError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getChain(){const e=[],t=new Set;let s=this;for(;s!=null&&!t.has(s);)e.push(s),t.add(s),s=s?.cause;return e}toJSON(e=new Set){return e.has(this)?{name:this.name,message:"[Circular Reference]",recoverable:this.recoverable,code:this.code}:(e.add(this),{name:this.name,message:this.message,code:this.code,recoverable:this.recoverable,stack:this.stack,cause:ge(this.cause,e)})}static format(e,t,s){return`${e} (${t}): ${s}`}},F=class extends T{constructor(...e){super(...e),this.name="ComputedError"}},b=class extends T{constructor(e,t=null,s=!1,r){super(e,t,s,r),this.name="EffectError"}},G=class extends T{constructor(e,t=null,s=!1,r){super(e,t,s,r),this.name="SchedulerError"}},f={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:(e,t)=>`Maximum flush iterations (${e}) exceeded. ${t} jobs dropped. Possible infinite loop.`,CALLBACK_ERROR_IN_ERROR_HANDLER:"Exception encountered in onError handler",EFFECT_FREQUENCY_LIMIT_EXCEEDED:"Effect executed too frequently within 1 second. Suspected infinite loop.",SCHEDULER_CALLBACK_MUST_BE_FUNCTION:"Scheduler callback must be a function",SCHEDULER_END_BATCH_WITHOUT_START:"endBatch() called without matching startBatch(). Ignoring.",BATCH_CALLBACK_MUST_BE_FUNCTION:"Batch callback must be a function"};function x(e,t,s){const r=st(e);return new t(T.format(r.name,s,r.message),e,r.recoverable,r.code)}function st(e){return e instanceof T?{name:e.name,message:e.message,recoverable:e.recoverable,code:e.code}:e instanceof Error?{name:e.name,message:e.message,recoverable:!0,code:e?.code}:{name:"Unexpected error",message:String(e),recoverable:!0,code:void 0}}function ge(e,t){return e==null||typeof e!="object"?e:t.has(e)?"[Circular Reference]":e instanceof T?e.toJSON(t):e instanceof Error?(t.add(e),{name:e.name,message:e.message,stack:e.stack,cause:ge(e.cause,t)}):e}var v=Symbol.for("atom-effect/brand"),h={Atom:1,Writable:2,Computed:4,Effect:8},se=Symbol("AtomEffect.NoDefaultValue"),rt={[h.Atom]:"atom",[h.Computed]:"computed",[h.Effect]:"effect"},it=h.Atom|h.Computed|h.Effect,re="[Atom Effect]",P=()=>{},nt=class{constructor(){this.enabled=!0,this.warnInfiniteLoop=ee.WARN_INFINITE_LOOP,this._updateCounts=new Map,this._registry=new Map,this.trackGraph=!1,this._finalizer=new FinalizationRegistry(e=>{this._registry.delete(e),this._updateCounts.delete(e)}),this._threshold=ee.LOOP_THRESHOLD,this._cleanupScheduled=!1,this._failedEvaluations=new Set,this._failureCleanupScheduled=!1,this._resetUpdateCounts=()=>{this._updateCounts.clear(),this._cleanupScheduled=!1},this._resetFailedEvaluations=()=>{this._failedEvaluations.clear(),this._failureCleanupScheduled=!1}}warn(e,t){this.enabled&&e&&console.warn(`${re} ${t}`)}registerNode(e){const t=e.id,s=this._getOrCreateMetadata(e,t);s.ref=new WeakRef(e),this._finalizer.register(e,t)}attachDebugInfo(e,t,s,r){if(!this.enabled||r===void 0&&!this.trackGraph)return;let i=this._registry.get(s);i?(r!==void 0&&(i.name=r),i.type=t):(i={name:r??`${t}_${s}`,type:t},this._registry.set(s,i)),this.registerNode(e)}trackUpdate(e,t){if(!this.enabled||!this.warnInfiniteLoop)return;const s=this._updateCounts,r=(s.get(e)||0)+1;s.set(e,r),r>this._threshold&&r===this._threshold+1&&console.warn(`${re} Infinite loop detected for ${t??`dependency ${e}`}. Detected ${r} updates within a single execution scope, exceeding the threshold of ${this._threshold}.`),this._cleanupScheduled||(this._cleanupScheduled=!0,queueMicrotask(this._resetUpdateCounts))}trackEvaluationFailure(e){!this.enabled||this._failedEvaluations.has(e)||(this._failedEvaluations.add(e),console.warn(`${re} Dependency #${e} evaluation failed during dirty check.`),this._failureCleanupScheduled||(this._failureCleanupScheduled=!0,queueMicrotask(this._resetFailedEvaluations)))}dumpGraph(){const e=this._registry;if(e.size===0)return[];const t=[],s=this._updateCounts;for(const[r,i]of e)this.trackGraph&&i.ref?.deref()===void 0||t.push({id:r,name:i.name,type:i.type,updateCount:s.get(r)??0});return t}getDebugName(e){if(!this.enabled||!e)return;const t=e.id;if(t===void 0)return;const s=this._registry.get(t);return s?s.name:`${this._getTypeFromBrand(e)??"unknown"}_${t}`}getDebugType(e){if(!this.enabled||!e)return;const t=e.id;if(t===void 0)return;const s=this._registry.get(t);return s?s.type:this._getTypeFromBrand(e)}_getOrCreateMetadata(e,t){let s=this._registry.get(t);if(!s){const r=this._getTypeFromBrand(e)??"unknown";s={name:`${r}_${t}`,type:r},this._registry.set(t,s)}return s}_getTypeFromBrand(e){const t=e[v];return t!==void 0?rt[t&it]:void 0}},ot={enabled:!1,warnInfiniteLoop:!1,trackGraph:!1,warn:P,registerNode:P,attachDebugInfo:P,trackUpdate:P,dumpGraph:()=>[],getDebugName:()=>{},getDebugType:()=>{},trackEvaluationFailure:P},S=p?new nt:ot,ut=1,ct=()=>ut++,Y={get:()=>{},set:()=>{},delete:()=>{}},De=class extends Map{};function Ie(){return{slots:new Se,map:Y,hasComputeds:!1}}function Te(e){e.hasComputeds=!1}function ve(e,t,s){const{slots:r}=e;if(r.length<=s)return!1;const i=r.at(s);if(i?.node===t&&i.unsub)return i.version=t.version,!0;const n=lt(e,t,s);if(n===-1)return!1;const o=r.at(n);o.version=t.version;const l=r.at(s);return ie(e,s,o),ie(e,n,l),!0}function lt(e,t,s){const r=e.map.get(t);if(r!==void 0)return r>=s?r:-1;const i=e.slots;for(let n=s+1,o=i.length;n<o;n++){const l=i.at(n);if(l?.node===t&&l.unsub)return n}return-1}function Oe(e,t,s){const r=e.slots.at(t);ie(e,t,s),r!==null&&at(e,r)}function ie(e,t,s){const r=e.slots.at(t);e.slots.setAt(t,s),r&&e.map.delete(r.node),s?.unsub&&(e.map===Y&&(e.map=new De),e.map.set(s.node,t))}function at(e,t){const s=e.slots.push(t);return t.unsub&&(e.map===Y&&(e.map=new De),e.map.set(t.node,s)),s}var ht={0:e=>e.node.version!==e.version,[U.IS_COMPUTED]:e=>{const t=e.node;try{t.value}catch{p&&S.trackEvaluationFailure(t.id)}return t.version!==e.version}};function L(e){const t=e.slots,s=t.length;if(t.size===0)return!1;const r=ht;for(let i=0;i<s;i++){const n=t.at(i);if(n&&r[n.node.flags&U.IS_COMPUTED](n))return!0}return!1}function ft(e){const t=e.slots,s=t.length;for(let r=0;r<s;r++){const i=t.at(r);if(!i)continue;const n=i.node;if(n.version!==i.version||(n.flags&U.DIRTY)!==0)return!0}return!1}function ne(e,t){const s=e.slots,r=s.length;for(let i=t;i<r;i++){const n=s.at(i);if(n){const o=n.unsub;if(o)try{o()}catch(l){p&&console.error("[atom-effect] Unsubscribe failed:",l)}}}s.truncateFrom(t),e.map=Y}function me(e){ne(e,0),e.hasComputeds=!1}function Ne(e,t,s=void 0){return{node:e,version:t,unsub:s}}function be(e=void 0,t=void 0){return{fn:e,sub:t}}function _t(e,t,s){if(e!==null)try{const{fn:r,sub:i}=e;r!==void 0&&r(t,s),i!==void 0&&i.execute()}catch(r){console.error("[atom-effect] Subscriber failed:",r)}}function Et(){return{stack:[],current:null}}function oe(e,t){e.stack.push(t),e.current=t}function Ae(e){const t=e.stack;t.pop();const s=t.length;e.current=s>0?t[s-1]:null}function ue(e,t){const s=e.stack;s.length=t;const r=s.length;e.current=r>0?s[r-1]:null}function Re(e,t,s){if(e.current===t)return s();oe(e,t);try{return s()}finally{Ae(e)}}function dt(e){e.stack.length=0,e.current=null}var a=Et();function ce(e){if(a.current===null)return e();oe(a,null);try{return e()}finally{Ae(a)}}var le=class{constructor(){this.flags=0,this.version=0,this._lastSeenEpoch=k.UNINITIALIZED,this._nextEpoch=void 0,this.id=ct()&Ce,this._slots=null,this._deps=null}get isDisposed(){return(this.flags&U.DISPOSED)!==0}get isComputed(){return(this.flags&U.IS_COMPUTED)!==0}get isNotifying(){return this._slots?.isLocked??!1}_hasFlag(e){return(this.flags&e)!==0}get hasError(){return!1}subscribe(e){let t;if(typeof e=="function"?t=be(e,void 0):e!=null&&typeof e.execute=="function"&&(t=be(void 0,e)),!t)throw x(new TypeError("Invalid subscriber"),T,f.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);let s=this._slots;if(s===null)this._slots=s=new Se;else if(this._hasSubscription(e))return p&&console.warn(`[atom-effect] Duplicate subscription ignored on node ${this.id}`),()=>{};return s.push(t),()=>this._unsubscribe(t)}_hasSubscription(e){const t=this._slots;return!t||t.size===0?!1:t.some(s=>s.fn===e||s.sub===e)}_unsubscribe(e){const t=this._slots;t!==null&&(t.remove(e),t.compact())}subscriberCount(){return this._slots?.size??0}_notifySubscribers(e,t){const s=this._slots;if(!s||s.size===0)return;const r=a.stack.length;oe(a,null),s.lock();try{s.forEach(i=>{_t(i,e,t)})}finally{ue(a,r),s.unlock()}}_isDirty(){return this._deps?L(this._deps):!1}_isShallowDirty(){return this._deps?ft(this._deps):!1}},ye=e=>{const t=e+1&Ce;return t===0?1:t};function ae(e){return ye(e)}var pt=0,he=1,fe=2,j=4,Ct=fe|j;function St(){return{size:0,epoch:0,batchQueueSize:0,state:pt,batchDepth:0,maxFlushIterations:I.MAX_FLUSH_ITERATIONS,sessionActive:!1,sessionEpoch:0,sessionExecutionCount:0,activeBuffer:[],standbyBuffer:[],batchBuffer:[],onOverflow:null}}function Ue(e,t){const s=e.batchQueueSize;if(s===0)return;const r=t(),i=e.batchBuffer,n=e.activeBuffer;let o=e.size;for(let l=0;l<s;l++){const y=i[l];y._nextEpoch!==r&&(y._nextEpoch=r,n[o++]=y),i[l]=void 0}e.size=o,e.batchQueueSize=0,i.length>I.BATCH_QUEUE_SHRINK_THRESHOLD&&(i.length=0)}function Fe(e,t,s,r){let i=0;const n=e.maxFlushIterations;for(;e.size>0||e.batchQueueSize>0;){if(++i>n){r(e);return}e.batchQueueSize>0&&Ue(e,t),e.size>0&&s(e)}}function we(e,t){const s=e.activeBuffer,r=e.size;e.activeBuffer=e.standbyBuffer,e.standbyBuffer=s,e.size=0,t();for(let i=0;i<r;i++){const n=s[i];s[i]=void 0;try{typeof n=="function"?n():n.execute()}catch(o){console.error(new G("Error occurred during scheduler execution",o))}}}function ke(e){const t=e.size+e.batchQueueSize;if(console.error(new G(f.SCHEDULER_FLUSH_OVERFLOW(e.maxFlushIterations,t))),e.size=0,e.activeBuffer.length=0,e.standbyBuffer.length=0,e.batchQueueSize=0,e.batchBuffer.length=0,e.onOverflow)try{e.onOverflow(t)}catch{}}function A(e){return e.epoch=ye(e.epoch),e.epoch}function Pe(e){return e.sessionActive?(p&&console.warn("startFlush() called during flush - ignored"),!1):(e.sessionActive=!0,e.sessionEpoch=A(e),e.sessionExecutionCount=0,!0)}function Le(e){e.sessionActive=!1}function gt(e){if(!e.sessionActive)return 0;const t=++e.sessionExecutionCount;if(t<=I.MAX_EXECUTIONS_PER_FLUSH)return t;throw new Error(`[atom-effect] Infinite loop detected: flush execution count exceeded ${I.MAX_EXECUTIONS_PER_FLUSH}`)}function X(e,t){if(p&&typeof t!="function"&&(!t||typeof t.execute!="function"))throw new G(f.SCHEDULER_CALLBACK_MUST_BE_FUNCTION);t._nextEpoch!==e.epoch&&(t._nextEpoch=e.epoch,(e.state&Ct)===0?e.activeBuffer[e.size++]=t:e.batchBuffer[e.batchQueueSize++]=t,(e.state&he)===0&&(e.state|=he,queueMicrotask(()=>{try{if(e.size===0&&e.batchQueueSize===0)return;const s=Pe(e);Fe(e,()=>A(e),r=>we(r,()=>A(r)),r=>ke(r)),s&&Le(e)}catch(s){throw dt(a),s}finally{e.state&=~he}})))}function Dt(e){if(e.size===0&&e.batchQueueSize===0)return;const t=e.state;e.state|=fe;const s=Pe(e);try{Ue(e,()=>A(e)),Fe(e,()=>A(e),r=>we(r,()=>A(r)),r=>ke(r))}finally{e.state=t,s&&Le(e)}}function It(e){e.batchDepth++,e.state|=j}function Tt(e){if(e.batchDepth===0){p&&console.warn(f.SCHEDULER_END_BATCH_WITHOUT_START);return}--e.batchDepth===0&&(e.state&=~j,(e.state&fe)===0&&Dt(e))}function Me(e){return(e.state&j)!==0}var C=St(),Be=()=>A(C),vt=()=>C.sessionEpoch,Ot=()=>gt(C);function ze(e){if(p&&typeof e!="function")throw new TypeError(f.BATCH_CALLBACK_MUST_BE_FUNCTION);It(C);try{return e()}finally{Tt(C)}}var M=null;function mt(e){return e?new Promise((t,s)=>{X(C,()=>{try{e(),t()}catch(r){s(r)}})}):M||(M=new Promise(t=>{X(C,()=>{M=null,t()})}),M)}var Nt=class extends le{constructor(e,t){super(),this[v]=h.Atom|h.Writable,this._value=e,this._equal=t.equal??Object.is,t.sync&&(this.flags|=D.SYNC),S.attachDebugInfo(this,"atom",this.id,t.name)}get isNotificationScheduled(){return(this.flags&D.NOTIFICATION_SCHEDULED)!==0}get isSync(){return(this.flags&D.SYNC)!==0}get value(){return a.current?.addDependency(this),this._value}set value(e){if(this._equal(this._value,e))return;const t=this._value;this._value=e,this.version=ae(this.version),p&&S.trackUpdate(this.id,S.getDebugName(this)),this._scheduleNotification(t)}_scheduleNotification(e){const t=this.flags,s=D.NOTIFICATION_SCHEDULED;(t&s)!==0||!this._slots?.length||(this._pendingOldValue=e,this.flags|=s,(t&D.SYNC)!==0&&!Me(C)?this.isNotifying||this._flushNotifications():X(C,this))}execute(){this._flushNotifications()}_flushNotifications(){const e=D.NOTIFICATION_SCHEDULED,t=e|D.DISPOSED,s=(this.flags&D.SYNC)!==0&&!Me(C);for(;(this.flags&t)===e;){const r=this._pendingOldValue,i=this._value;if(this._pendingOldValue=void 0,this.flags&=~e,this._equal(i,r)||this._notifySubscribers(i,r),!s)break}}peek(){return this._value}dispose(){const e=D.DISPOSED;(this.flags&e)===0&&(this.flags|=e,this._slots?.clear(),this._value=void 0,this._pendingOldValue=void 0,this._equal=Object.is)}_deepDirtyCheck(){return!1}};function bt(e,t={}){return new Nt(e,t)}function W(e,t){return!e||typeof e!="object"&&typeof e!="function"?!1:!!(e[v]&t)}function At(e){return W(e,h.Atom)}function Rt(e){return W(e,h.Writable)}function yt(e){return W(e,h.Computed)}function Ut(e){return W(e,h.Effect)}function B(e,t=!1){const s={};for(let r=0;r<e.length;r++){const i=t?e[r].peek():e[r].value;i&&typeof i=="object"&&Object.assign(s,i)}return s}var{IDLE:z,DIRTY:O,PENDING:H,RESOLVED:m,REJECTED:R,HAS_ERROR:_e,RECOMPUTING:g,DISPOSED:$,IS_COMPUTED:He,FORCE_COMPUTE:K}=U,Ve=H|R,Ft=z|K,Ge=R|_e,Ee=z|O|H|m|R|_e,Q={TO_RECOMPUTING:{clear:K,set:g},TO_RESOLVED:{clear:Ee|g,set:m},TO_PENDING:{clear:Ee|g,set:H},TO_REJECTED:{clear:Ee|g,set:R|_e}},q=(e,t)=>e&~t.clear|t.set;function wt(e,t,s,r){if((e&m)!==0)return t;const i=r!==se,n=e&Ve;if(n===0)return t;if(i)return r;throw n===R?s??new Error("REJECTED without error"):new F(f.COMPUTED_ASYNC_PENDING_NO_DEFAULT)}function kt(e,t){const s=(e&Ve)!==0;return(e&Ft)!==0||L(t)||!s&&t.slots.size===0}function xe(e,t){const s=[],r=new Set,i=n=>{if(r.has(n.id))return!1;if(r.add(n.id),(n.flags&Ge)!==0&&(s.push(n.lastError??new Error("Internal Inconsistency: MASK_ERROR flag set but error is null")),t))return!0;const o=n._deps;if(o?.hasComputeds)for(let l=0,y=o.slots.length;l<y;l++){const d=o.slots.at(l);if(d?.node.isComputed&&i(d.node))return!0}return!1};return i(e),s}var Pt=class extends le{constructor(e,t={}){if(typeof e!="function")throw new F(f.COMPUTED_MUST_BE_FUNCTION);if(super(),this[v]=h.Atom|h.Computed,this._activeSessionId=0,this._sessionCounter=0,this._trackEpoch=k.UNINITIALIZED,this._trackCount=0,this._error=null,this._deps=Ie(),this._value=void 0,this.flags=He|O|z,this._equal=t.equal??Object.is,this._computation=e,this._defaultValue="defaultValue"in t?t.defaultValue:se,this._onError=t.onError??null,S.attachDebugInfo(this,"computed",this.id,t.name),t.lazy===!1)try{this._recompute()}catch{}}get isDirty(){return(this.flags&O)!==0}get isRejected(){return(this.flags&R)!==0}get isRecomputing(){return(this.flags&g)!==0}get value(){if(a.current?.addDependency(this),this._isStable())return this._value;if(this._ensureNotDisposed(),(this.flags&g)!==0){if(this._defaultValue!==se)return this._defaultValue;throw new F(f.COMPUTED_CIRCULAR_DEPENDENCY)}return kt(this.flags,this._deps)?this._recompute():this.flags&=~O,wt(this.flags,this._value,this._error,this._defaultValue)}_isStable(){const e=m|O|z|$|g;return(this.flags&e)===m}_ensureNotDisposed(){if((this.flags&$)!==0)throw new F(f.COMPUTED_DISPOSED)}peek(){return this._value}get state(){a.current?.addDependency(this);const e=this.flags;return(e&m)!==0?w.RESOLVED:(e&H)!==0?w.PENDING:(e&R)!==0?w.REJECTED:w.IDLE}get hasError(){return a.current?.addDependency(this),(this.flags&Ge)!==0?!0:this._deps.hasComputeds?ce(()=>xe(this,!0).length>0):!1}get isValid(){return!this.hasError}get errors(){return a.current?.addDependency(this),this._deps.hasComputeds?ce(()=>Object.freeze(xe(this,!1))):this._error?Object.freeze([this._error]):Ke}get lastError(){return a.current?.addDependency(this),this._error}get isPending(){return a.current?.addDependency(this),(this.flags&H)!==0}get isResolved(){return a.current?.addDependency(this),(this.flags&m)!==0}invalidate(){this.flags|=K,this._markDirty()}dispose(){(this.flags&$)===0&&(me(this._deps),this._slots?.clear(),this.flags=$|O|z,this._error=null,this._value=void 0)}addDependency(e){const t=this._trackEpoch;if(e._lastSeenEpoch===t)return;e._lastSeenEpoch=t;const s=this._trackCount++,r=this._deps,i=r.slots.at(s);i?.node===e?i.version=e.version:ve(r,e,s)||Oe(r,s,Ne(e,e.version,e.subscribe(this))),(e.flags&He)!==0&&(r.hasComputeds=!0)}_recompute(){if((this.flags&g)!==0)return;this.flags=q(this.flags,Q.TO_RECOMPUTING);const e=a.stack.length;this._startTracking();let t,s=!1,r;try{try{t=Re(a,this,this._computation)}catch(i){throw ue(a,e),i}}catch(i){s=!0,r=i}s?(this._commitDeps(),this._handleError(r,f.COMPUTED_COMPUTATION_FAILED,!1)):(this._commitDeps(),te(t)?this._handleAsyncComputation(t):this._finalizeResolution(t)),this._trackEpoch=k.UNINITIALIZED,this._trackCount=0,this.flags&=~g}_startTracking(){this._trackEpoch=Be(),this._trackCount=0,Te(this._deps)}_commitDeps(){try{ne(this._deps,this._trackCount)}catch(e){p&&console.warn("[atom-effect] _commitDeps failed during error recovery:",e)}}_handleAsyncComputation(e){this.flags=q(this.flags,Q.TO_PENDING),this._notifySubscribers(void 0,void 0);const t=++this._sessionCounter;this._activeSessionId=t,e.then(s=>{if(this._activeSessionId===t){if(this._isDirty())return this._markDirty();this._finalizeResolution(s),this._notifySubscribers(s,void 0)}},s=>{this._activeSessionId===t&&this._handleError(s,f.COMPUTED_ASYNC_COMPUTATION_FAILED)})}_handleError(e,t,s=!1){const r=x(e,F,t),i=this._error;if((!this.isRejected||i!==r)&&(this.version=ae(this.version)),this._error=r,this.flags=q(this.flags,Q.TO_REJECTED),this._onError)try{this._onError(r)}catch(n){console.error(f.CALLBACK_ERROR_IN_ERROR_HANDLER,n)}if(this._notifySubscribers(void 0,void 0),s)throw r}_finalizeResolution(e){((this.flags&m)===0||!this._equal(this._value,e))&&(this.version=ae(this.version)),this._value=e,this._error=null,this.flags=q(this.flags,Q.TO_RESOLVED)}execute(){this._markDirty()}_markDirty(){const e=this.flags;(e&(g|O))!==0||!(e&K)&&!this._isShallowDirty()||(this.flags=e|O,S.trackUpdate(this.id,S.getDebugName(this)),this._notifySubscribers(void 0,void 0))}_deepDirtyCheck(){return L(this._deps)}};function Ye(e,t={}){return new Pt(e,t)}function Lt(...e){return Ye(()=>B(e))}function Mt(){return{loopCount:0,lastFlushEpoch:k.UNINITIALIZED,windowCount:0,windowStart:0,totalExecutions:0}}function Bt(e,t,s,r,i){e.lastFlushEpoch!==s&&(e.lastFlushEpoch=s,e.loopCount=0),++e.loopCount>t&&i("per-effect"),r()>I.MAX_EXECUTIONS_PER_FLUSH&&i("global"),e.totalExecutions++}function zt(e,t,s){if(!Number.isFinite(t))return;const r=Date.now();if(r-e.windowStart>=ee.EFFECT_FREQUENCY_WINDOW){e.windowStart=r,e.windowCount=1;return}++e.windowCount>t&&s()}var Ht=class extends le{constructor(e,t={}){super(),this[v]=h.Effect,this._trackEpoch=k.UNINITIALIZED,this._trackCount=0,this._trackSessionId=0,this._budget=Mt(),this._deps=Ie(),this._cleanup=null,this._fn=e,this._onError=t.onError??null,this._sync=t.sync??!1,this._maxExecutions=t.maxExecutionsPerSecond??I.MAX_EXECUTIONS_PER_SECOND,this._maxExecutionsPerFlush=t.maxExecutionsPerFlush??I.MAX_EXECUTIONS_PER_EFFECT,this._notifyCallback=this._sync?()=>this.execute():()=>X(C,this),S.attachDebugInfo(this,"effect",this.id,t.name)}run(){if(this.isDisposed)throw new b(f.EFFECT_DISPOSED);this.execute(!0)}dispose(){this.isDisposed||(this.flags|=N.DISPOSED,this._execCleanup(),this._deps&&me(this._deps))}get executionCount(){return this._budget.totalExecutions}get isExecuting(){return(this.flags&N.EXECUTING)!==0}get isDisposed(){return(this.flags&N.DISPOSED)!==0}execute(e=!1){if(!this._prepareExecution(e))return;this._execCleanup(),this._startTracking();const t=a.stack.length;let s,r=!1,i;try{try{s=Re(a,this,this._fn)}catch(n){throw ue(a,t),n}}catch(n){r=!0,i=n}this._commitDeps(),r?this._handleExecutionError(i):this._handleResult(s),this.flags&=~N.EXECUTING}_prepareExecution(e){return(this.flags&(N.DISPOSED|N.EXECUTING))!==0||!(e||this._deps.slots.length===0||this._isDirty())?!1:(this._validateBudget(),S.trackUpdate(this.id,S.getDebugName(this)),this.flags|=N.EXECUTING,!0)}addDependency(e){if(!this.isExecuting||e._lastSeenEpoch===this._trackEpoch)return;e._lastSeenEpoch=this._trackEpoch;const t=this._trackCount++,s=this._deps,r=e.version,i=s.slots.at(t);i?.node===e?i.version=r:ve(s,e,t)||this._insertNewDependency(e,t,r),e.isComputed&&!s.hasComputeds&&(s.hasComputeds=!0)}_insertNewDependency(e,t,s){const r=Ne(e,s,e.subscribe(this._notifyCallback));Oe(this._deps,t,r)}_startTracking(){this._trackEpoch=Be(),this._trackCount=0,Te(this._deps)}_commitDeps(){try{ne(this._deps,this._trackCount)}catch(e){p&&console.warn("[atom-effect] _commitDeps failed during error recovery:",e)}}_handleResult(e){typeof e=="function"?this._cleanup=e:te(e)?this._handleAsyncResult(e):this._cleanup=null}_handleAsyncResult(e){const t=++this._trackSessionId;e.then(s=>{if(this._trackSessionId!==t||this.isDisposed){if(typeof s=="function")try{s()}catch(r){this._handleExecutionError(r,f.EFFECT_CLEANUP_FAILED)}return}typeof s=="function"&&(this._cleanup=s)},s=>{this._trackSessionId===t&&this._handleExecutionError(s)})}_execCleanup(){const e=this._cleanup;if(e){this._cleanup=null;try{e()}catch(t){this._handleExecutionError(t,f.EFFECT_CLEANUP_FAILED)}}}_validateBudget(){Bt(this._budget,this._maxExecutionsPerFlush,vt(),Ot,e=>this._abortExecution(e)),p&&zt(this._budget,this._maxExecutions,()=>{const e=new b(f.EFFECT_FREQUENCY_LIMIT_EXCEEDED);throw this.dispose(),this._handleExecutionError(e),e})}_abortExecution(e){const t=new b(e==="per-effect"?`Infinite loop detected (per-effect): executed ${this._budget.loopCount} times in current flush.`:"Infinite loop detected (global): exceeded total execution limit per flush.");throw this.dispose(),console.error(t),t}_handleExecutionError(e,t=f.EFFECT_EXECUTION_FAILED){const s=x(e,b,t);if(console.error(s),this._onError)try{this._onError(s)}catch(r){console.error(x(r,b,f.CALLBACK_ERROR_IN_ERROR_HANDLER))}}_isDirty(){return L(this._deps)}_deepDirtyCheck(){return L(this._deps)}};function Vt(e,t={}){if(typeof e!="function")throw new b(f.EFFECT_MUST_BE_FUNCTION);const s=new Ht(e,t);return s.execute(),s}var je=new Set(["__proto__","constructor","prototype"]);function Gt(e,t,s){if(Array.isArray(e)){const n=[...e];return n[t]=s,n}if(e instanceof Map){const n=new Map(e);return n.set(t,s),n}const r=Object.getPrototypeOf(e);if(r===Object.prototype||r===null)return{...e,[t]:s};const i=Object.create(r);return Object.assign(i,e),i[t]=s,i}function de(e,t,s,r){if(s===t.length)return r;const i=t[s];if(je.has(i)||e==null||typeof e!="object")return e;const n=e instanceof Map?e.get(i):e[i],o=de(n,t,s+1,r);return Object.is(n,o)?e:Gt(e,i,o)}function Xe(e,t){let s=e;const r=t.length;for(let i=0;i<r;i++){if(s==null)return;s instanceof Map?s=s.get(t[i]):s=s[t[i]]}return s}function pe(e,t){const s=t.split("."),r=s.some(d=>je.has(d)),i=new Set;let n=null,o;const l=d=>r?void 0:Xe(d,s),y=()=>{const d=l(e.peek());if(!Object.is(d,o)){const J=o;o=d,i.forEach(Z=>Z(d,J))}};return{get value(){return l(e.value)},set value(d){if(r)return;const J=e.peek(),Z=de(J,s,0,d);Z!==J&&(e.value=Z)},peek:()=>l(e.peek()),subscribe(d){return i.size===0&&(o=l(e.peek()),n=e.subscribe(y)),i.add(d),()=>{i.delete(d),i.size===0&&n&&(n(),n=null)}},subscriberCount:()=>i.size,dispose:()=>{n?.(),n=null,i.clear()},[v]:h.Atom|h.Writable}}var xt=(e,t)=>pe(e,t),Yt=e=>t=>pe(e,t);function jt(...e){let t;const s=new Set,r=[],i=()=>{const n=B(e,!0);if(!tt(n,t)){const o=t;t=n;for(const l of s)l(n,o)}};return{get value(){return B(e)},set value(n){ze(()=>{for(let o=0;o<e.length;o++)e[o].value=n})},peek:()=>B(e,!0),subscribe:n=>{if(s.size===0){t=B(e,!0);for(let o=0;o<e.length;o++)r.push(e[o].subscribe(i))}return s.add(n),()=>{if(s.delete(n),s.size===0){for(const o of r)o();r.length=0}}},subscriberCount:()=>s.size,dispose:()=>{for(const n of r)n();r.length=0,s.clear()},[v]:h.Atom|h.Writable}}u.AsyncState=w,u.AtomError=T,u.BRAND=v,u.BrandFlags=h,u.ComputedError=F,u.EffectError=b,u.IS_DEV=p,u.SCHEDULER_CONFIG=I,u.SchedulerError=G,u.aeNextTick=mt,u.atom=bt,u.atomLens=pe,u.batch=ze,u.composeLens=xt,u.computed=Ye,u.effect=Vt,u.getPathValue=Xe,u.globalScheduler=C,u.isAtom=At,u.isComputed=yt,u.isEffect=Ut,u.isPromise=te,u.isWritable=Rt,u.lensFor=Yt,u.mergeAtoms=Lt,u.mergeLenses=jt,u.runtimeDebug=S,u.setDeepValue=de,u.untracked=ce});
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=atom-effect.min.js.map
|