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