@estjs/signals 0.0.15-beta.1

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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-Present jiangxd <jiangxd2016@gmail.com>
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # @estjs/signals
2
+
3
+ A high-performance, fine-grained reactivity library for **Essor**. It can also be used as a standalone library for managing state in any JavaScript application.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @estjs/signals
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { computed, effect, signal } from '@estjs/signals';
15
+
16
+ const count = signal(0);
17
+ const double = computed(() => count.value * 2);
18
+
19
+ effect(() => {
20
+ console.log(`Count: ${count.value}, Double: ${double.value}`);
21
+ });
22
+
23
+ count.value++; // Logs: Count: 1, Double: 2
24
+ ```
25
+
26
+
27
+ ## License
28
+
29
+ MIT
@@ -0,0 +1,10 @@
1
+ 'use strict';var shared=require('@estjs/shared');/**
2
+ * @estjs/signals v0.0.15-beta.1
3
+ * (c) 2023-Present jiangxd <jiangxd2016@gmail.com>
4
+ * @license MIT
5
+ **/
6
+ var qe=Object.defineProperty,Be=Object.defineProperties;var He=Object.getOwnPropertyDescriptors;var pe=Object.getOwnPropertySymbols;var $e=Object.prototype.hasOwnProperty,Je=Object.prototype.propertyIsEnumerable;var de=(e,t,n)=>t in e?qe(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n,U=(e,t)=>{for(var n in t||(t={}))$e.call(t,n)&&de(e,n,t[n]);if(pe)for(var n of pe(t))Je.call(t,n)&&de(e,n,t[n]);return e},he=(e,t)=>Be(e,He(t));var E={SET:"SET",ADD:"ADD",DELETE:"DELETE",CLEAR:"CLEAR"};var ee=Symbol(""),A=Symbol(""),_=Symbol(""),x=Symbol(""),v=Symbol("");function Y(e){let t=e.nextSubLink,n;e:do{let r=e.subNode,i=r.flag&64,o=r.flag&2,a=r.flag&-65;if(a&60?a&48||(a&12?a&4?!(a&48)&&Ee(e,r)?(r.flag=i|o|(a|8|32),a&=1):(a=0,r.flag=i|o):r.flag=i|o|(a&-9|32):(a=0,r.flag=i|o)):r.flag=i|o|a|32,r.flag&2&&Te(r),a&1){let s=r.subLink;if(s){let g=(e=s).nextSubLink;g&&(n={value:t,prev:n},t=g);continue}}if(t){e=t,t=e.nextSubLink;continue}for(;n;)if(e=n.value,n=n.prev,e){t=e.nextSubLink;continue e}break}while(true)}function te(e){for(;e;){let t=e.subNode,n=t.flag&64,r=t.flag&-65;if(!(r&16)&&r&33){let i=n|r&-33|16;t.flag=i,i&2&&Te(t),r&1&&t.subLink&&te(t.subLink);}e=e.nextSubLink;}}function Te(e){e.active&&e.notify();}var O=0,y,C=false;function M(e,t){if(C)return;let n=t.depLinkTail;if(n&&n.depNode===e)return n;let r=n?n.nextDepLink:t.depLink;if(r&&r.depNode===e)return r.version=O,t.depLinkTail=r,r;let i=e.subLinkTail;if(i&&i.version===O&&i.subNode===t)return t.depLinkTail=i,i;let o={version:O,depNode:e,subNode:t,prevSubLink:i,nextSubLink:void 0,prevDepLink:n,nextDepLink:r};return r&&(r.prevDepLink=o),n?n.nextDepLink=o:t.depLink=o,i?i.nextSubLink=o:e.subLink=o,e.subLinkTail=o,t.depLinkTail=o,o}function N(e,t=e.subNode){let n=e.depNode,r=e.prevSubLink,i=e.nextSubLink,o=e.prevDepLink,a=e.nextDepLink;if(a?a.prevDepLink=o:t.depLinkTail=o,o?o.nextDepLink=a:t.depLink=a,i?i.prevSubLink=r:n.subLinkTail=r,r)r.nextSubLink=i;else if(n.subLink=i,i===void 0){let s=n.depLink;for(;s;)s=N(s,n);n.depLinkTail=void 0,n.flag|=16;}return e.depNode=void 0,e.subNode=void 0,e.prevSubLink=void 0,e.nextSubLink=void 0,e.prevDepLink=void 0,e.nextDepLink=void 0,a}function j(e,t){let n=[{link:e,owner:t}],r=[];for(;n.length>0;){let i=n.pop(),o=i.link,a=i.owner;for(;o;){let s=o.depNode,g=s.flag;if(a.flag&16)return true;if((g&17)===17){let d=s.subLink;d&&d.nextSubLink&&V(d);for(let u of r)u.flag&32&&(u.flag=u.flag&-33|16);return true}(g&33)===33?s.depLink?(r.push(s),n.push({link:s.depLink,owner:s})):s.flag&=-33:g&32&&(s.flag&=-33),o=o.nextDepLink;}}for(let i of r)i.flag&=-33;return t.flag&32&&(t.flag&=-33),false}function V(e){for(;e;){let t=e.subNode,n=t.flag&64,r=t.flag&-65;(r&48)===32&&(t.flag=n|r|16),e=e.nextSubLink;}}function ne(e){let t=y;return y=e,t}function K(e){return O++,e.depLinkTail=void 0,e.flag=e.flag&-57|4,ne(e)}function W(e,t){y=t;let n=e.depLinkTail,r=n?n.nextDepLink:e.depLink;for(;r;)r=N(r,e);e.flag&=-5;}function Qe(e){let t=ne(void 0),n=C;C=true;try{return e()}finally{C=n,ne(t);}}function Ee(e,t){let n=t.depLinkTail;for(;n;){if(n===e)return true;n=n.prevDepLink;}return false}var re=new WeakMap;function f(e,t){if(!y||C)return;let n=re.get(e);n||(n=new Map,re.set(e,n));let r=n.get(t);r||(r=new Set,n.set(t,r)),r.has(y)||r.add(y);}function p(e,t,n,r){let i=re.get(e);if(!i)return;let o=new Set;if(n!==void 0)if(Array.isArray(n))n.forEach(a=>{let s=i.get(a);s&&s.forEach(g=>o.add(g));});else {let a=i.get(n);a&&a.forEach(s=>o.add(s));}if(t==="ADD"||t==="DELETE"||t==="CLEAR"){let a=Symbol("iterate"),s=Symbol("arrayIterate"),g=Array.isArray(e)?s:a,d=i.get(g);d&&d.forEach(u=>o.add(u));}o.forEach(a=>{var s;a.flag&2?(s=a.notify)==null||s.call(a):a.flag&1&&(a.flag|=16,a.subLink&&Y(a.subLink));});}var Se=new WeakMap;function c(e){if(!e||!shared.isObject(e))return e;let t=e._RAW;return t?c(t):T(e)?c(e.peek()):e}var _e=rt();function rt(){let e={};return ["includes","indexOf","lastIndexOf"].forEach(t=>{e[t]=function(...n){let r=c(this);f(r,v);let i=r[t](...n);if((i===-1||i===false)&&n.length>0){let o=n.map(a=>c(a));i=r[t](...o);}return i};}),["find","findIndex","findLast","findLastIndex"].forEach(t=>{e[t]=function(...n){let r=c(this),i=b(this);f(r,v);let o=r[t](...n);return (t==="find"||t==="findLast")&&shared.isObject(o)&&!i?h(o):o};}),["push","pop","shift","unshift","splice","sort","reverse","fill","copyWithin"].forEach(t=>{e[t]=function(...n){let r=c(this),i=Array.prototype[t].apply(r,n);return p(r,E.SET,A),p(r,E.SET,v),i};}),["toReversed","toSorted","toSpliced"].forEach(t=>{e[t]=function(...n){let r=c(this),i=b(this);if(f(r,v),t==="toSpliced")for(let a=0,s=r.length;a<s;a++)f(r,`${a}`);let o=Array.prototype[t].apply(r,n);return Array.isArray(o)?o.map(a=>shared.isObject(a)?h(a,i):a):o};}),["concat","slice","filter","map","flatMap","flat"].forEach(t=>{e[t]=function(...n){let r=c(this);return f(r,v),Array.prototype[t].apply(r,n)};}),["join","toString","toLocaleString"].forEach(t=>{e[t]=function(...n){let r=c(this);return f(r,v),Array.prototype[t].apply(r,n)};}),["values","keys","entries",Symbol.iterator].forEach(t=>{e[t]=function(){let n=c(this),r=b(this);f(n,A);let i=t===Symbol.iterator?n[Symbol.iterator]():n[t]();return {next(){let{value:o,done:a}=i.next();return a?{value:o,done:a}:Array.isArray(o)?{value:o.map(s=>shared.isObject(s)?h(s,r):s),done:a}:{value:shared.isObject(o)?h(o,r):o,done:a}},[Symbol.iterator](){return this}}};}),e}var be=e=>({get:(t,n,r)=>{if(n==="_RAW")return t;if(n==="_IS_REACTIVE")return true;if(n==="_IS_SHALLOW")return e;if(shared.hasOwn(_e,n))return _e[n];let i=Reflect.get(t,n,r);return shared.isStringNumber(n)&&f(t,n),f(t,A),shared.isObject(i)&&!e?h(i):i},set:(t,n,r,i)=>{let o=Reflect.get(t,n,i),a=Reflect.set(t,n,r,i);return shared.hasChanged(r,o)&&(shared.isStringNumber(n)?p(t,E.SET,[n,v,A]):p(t,E.SET,n)),a}}),it=be(true),ot=be(false),at={get(e,t){return t==="_IS_REACTIVE"?true:t==="_RAW"?e:Reflect.get(shared.hasOwn(me,t)?me:e,t,e)}},st={get(e,t){return t==="_IS_REACTIVE"?true:t==="_RAW"?e:Reflect.get(shared.hasOwn(ye,t)&&t in e?ye:e,t,e)}},me={get(e){let t=c(this);f(t,_);let n=t.get(e);return shared.isObject(n)&&!b(this)?h(n):n},set(e,t){let n=c(this),r=n.has(e),i=n.get(e),o=c(t);return n.set(e,o),(!r||shared.hasChanged(i,o))&&p(n,E.SET,_),this},add(e){let t=c(this),n=c(e),r=t.has(n);return t.add(n),r?p(t,E.SET,_):p(t,E.ADD,_),this},has(e){let t=c(this);f(t,_);let n=t.has(e);return !n&&shared.isObject(e)?t.has(c(e)):n},delete(e){let t=c(this),n=t.has(e),r=t.delete(e);return !r&&shared.isObject(e)&&(r=t.delete(c(e))),(n||r)&&p(t,E.DELETE,_),r},clear(){let e=c(this),t=e.size>0,n=e.clear();return t&&p(e,E.CLEAR,_),n},forEach(e,t){let n=c(this),r=b(this);f(n,_),n.forEach((i,o)=>{let a=r||!shared.isObject(i)?i:h(i),s=r||!shared.isObject(o)?o:h(o);e.call(t,a,s,this);});},[Symbol.iterator](){let e=c(this),t=b(this);f(e,_);let n=e[Symbol.iterator]();return {next(){let{value:r,done:i}=n.next();return i?{value:r,done:i}:t?{value:r,done:i}:Array.isArray(r)?{value:r.map(o=>shared.isObject(o)?h(o):o),done:i}:{value:shared.isObject(r)?h(r):r,done:i}},[Symbol.iterator](){return this}}},get size(){let e=c(this);return f(e,_),e.size},keys(){let e=c(this),t=b(this);f(e,_);let n=e.keys();return {next(){let{value:r,done:i}=n.next();return i?{value:r,done:i}:{value:t||!shared.isObject(r)?r:h(r),done:i}},[Symbol.iterator](){return this}}},values(){let e=c(this),t=b(this);f(e,_);let n=e.values();return {next(){let{value:r,done:i}=n.next();return i?{value:r,done:i}:{value:t||!shared.isObject(r)?r:h(r),done:i}},[Symbol.iterator](){return this}}},entries(){let e=c(this),t=b(this);f(e,_);let n=e.entries();return {next(){let{value:r,done:i}=n.next();return i?{value:r,done:i}:t?{value:r,done:i}:{value:r.map(o=>shared.isObject(o)?h(o):o),done:i}},[Symbol.iterator](){return this}}}},ye={get(e){let t=c(this);f(t,x);let n=t.get(e);return n===void 0&&k(e)&&(n=t.get(c(e))),shared.isObject(n)&&!b(this)?h(n):n},set(e,t){let n=c(this),r=c(e),i=n.has(r),o=n.get(r),a=c(t);return n.set(r,a),(!i||shared.hasChanged(o,a))&&p(n,E.SET,x),this},add(e){let t=c(this),n=c(e),r=t.has(n);return t.add(n),r||p(t,E.ADD,x),this},has(e){let t=c(this);f(t,x);let n=t.has(e);return !n&&k(e)&&(n=t.has(c(e))),n},delete(e){let t=c(this),n=c(e),r=t.has(n),i=t.delete(n);return (r||i)&&p(t,E.DELETE,x),i}},ct=e=>({get(t,n,r){if(n==="_RAW")return t;if(n==="_IS_REACTIVE")return true;if(n==="_IS_SHALLOW")return e;let i=Reflect.get(t,n,r),o=T(i)?i.value:i;return f(t,n),shared.isObject(o)&&!e?h(o):o},set:(t,n,r,i)=>{let o=Reflect.get(t,n,i),a=Reflect.set(t,n,c(r),i);return shared.hasChanged(r,o)&&p(t,E.SET,n),a},deleteProperty:(t,n)=>{let r=shared.hasOwn(t,n),i=Reflect.deleteProperty(t,n);return r&&i&&p(t,E.DELETE,n),i}});function h(e,t=false){if(!shared.isObject(e)||k(e))return e;let n=Se.get(e);if(n)return n;let r;shared.isArray(e)?r=t?it:ot:shared.isSet(e)||shared.isMap(e)?r=at:shared.isWeakMap(e)||shared.isWeakSet(e)?r=st:r=ct(t);let i=new Proxy(e,r);return Se.set(e,i),i}function k(e){return !!(e&&e._IS_REACTIVE)}function L(e){return k(e)||T(e)?e:h(e)}function B(e){return k(e)||T(e)?e:h(e,true)}function b(e){return !!(e&&e._IS_SHALLOW)}var ut=e=>shared.isObject(e)?L(e):e;var ve;ve="_IS_SIGNAL";var R=class{constructor(t,n=false){this.flag=1;this[ve]=true;this._oldValue=this._rawValue=t,n?this._value=shared.isObject(t)?B(t):t:this._value=shared.isObject(t)?L(t):t,this._IS_SHALLOW=n;}get dep(){return this}get value(){let t=y;if(t&&M(this,t),this.flag&16&&this.shouldUpdate()){let n=this.subLink;n&&V(n);}return this._value}set value(t){if(T(t)&&(t=t.peek()),t=c(t),!shared.hasChanged(this._rawValue,t))return;this.flag|=16,this._rawValue=t,this._IS_SHALLOW?this._value=shared.isObject(t)?B(t):t:this._value=shared.isObject(t)?L(t):t;let r=this.subLink;r&&Y(r);}shouldUpdate(){return this.flag&=-17,shared.hasChanged(this._oldValue,this._oldValue=this._rawValue)}peek(){return this._value}set(t){this.value=t;}update(t){let n=t(this.peek());T(n)?this.value=n.peek():this.value=n;}};function ft(e){return T(e)?e:new R(e)}function lt(e){return T(e)&&(e=e.peek()),new R(e,true)}function T(e){return !!e&&!!e._IS_SIGNAL}var $=new Set,ie=new Set,pt=Promise.resolve(),oe=false;function we(e){return e?new Promise((t,n)=>{queueMicrotask(()=>{try{e(),t();}catch(r){n(r);}});}):pt}function D(e){$.add(e),Le();}function Le(){oe||(oe=true,we(ae));}function De(e){ie.add(e),Le();}function ae(){for(oe=false,dt();$.size>0;){let e=Array.from($);$.clear();for(let t of e)try{t();}catch(n){}}}function dt(){let e=Array.from(ie);ie.clear();for(let t of e)try{t();}catch(n){}}function xe(e,t){switch(t){case "sync":return ()=>e();case "pre":return ()=>De(e);case "post":return ()=>D(e);default:return ()=>D(e)}}var J=0;function Q(e){Re();try{return e()}finally{Ie();}}function Re(){J++;}function Ie(){--J===0&&ae();}function se(){return J>0}function ht(){return J}var Ae;Ae="_IS_EFFECT";var ce=class{constructor(t,n){this.flag=18;this[Ae]=true;this._active=true;this.fn=t,n&&(this.scheduler=n.flush||n.scheduler,this.onStop=n.onStop,this.onTrack=n.onTrack,this.onTrigger=n.onTrigger);}get active(){return this._active}get dirty(){let t=this.flag;if(t&16)return true;if(t&32){if(this.depLink&&j(this.depLink,this))return this.flag=t&-33|16,true;this.flag=t&-33;}return false}pause(){this.flag|=256;}resume(){let n=this.flag&-257;this.flag=n;let r=(n&16)!==0,i=(n&32)!==0;(r||i)&&this.notify();}run(){if(!this._active)return this.fn();let t=this.flag;this.flag=t&-17|1024;let n=K(this);try{return this.fn()}catch(r){throw this.flag|=16,r}finally{this.flag&=-1025,W(this,n);}}getJob(){return this._job||(this._job=()=>this.run()),this._job}notify(){let t=this.flag;!this._active||t&1296||(this.flag=t|16,this.scheduler?shared.isFunction(this.scheduler)?this.scheduler(this):xe(()=>this.run(),this.scheduler)():se()?D(this.getJob()):this.run());}stop(){if(!this._active)return;this._active=false;let t=this.depLink;for(;t;)t=N(t,this);let n=this.subLink;for(;n;)n=N(n);this._job=void 0,this.depLinkTail=void 0,this.subLinkTail=void 0,this.onStop&&this.onStop();}};function z(e,t){let n=new ce(e,t);try{n.run();}catch(i){throw n.stop(),i}let r=()=>n.run();return r.effect=n,r.stop=()=>n.stop(),r}function Et(e){e.effect.stop();}function gt(e){return !!(e&&e._IS_EFFECT)}function St(e,t,n){let r=t;return z(()=>{r=e(r);},n)}var P=Symbol("computed-no-value"),Ve;Ve="_IS_COMPUTED";var X=class{constructor(t,n,r,i){this.flag=17;this[Ve]=true;this._value=P;this.getter=t,this.setter=n,this.onTrack=r,this.onTrigger=i,this.flag|=16;}get value(){y&&M(this,y);let t=this.flag,n=this._value!==P;return n&&!(t&48)?this._value:!n||t&16?(this.recompute(),this._value):(t&32&&(this.depLink&&j(this.depLink,this)?this.recompute():this.flag=t&-33),this._value)}set value(t){this.setter&&this.setter(t);}peek(){return this._value===P&&this.recompute(),this._value}recompute(){let t=this._value,n=t!==P,r=K(this);try{let i=this.getter(),o=this.flag,a=-49;!n||shared.hasChanged(t,i)?(this._value=i,this.flag=o&a,this.subLink&&te(this.subLink)):this.flag=o&a;}catch(i){throw this.flag&=-49,i}finally{W(this,r);}}shouldUpdate(){let t=this._value!==P,n=this._value;return this.recompute(),t?shared.hasChanged(this._value,n):true}};function ue(e){if(G(e))return e;if(!e)throw new Error("[Computed] Invalid argument: computed() requires a getter function or options object.");if(shared.isFunction(e))return new X(e);if(shared.isPlainObject(e)){let{get:t,set:n,onTrack:r,onTrigger:i}=e;if(!t)throw new Error(`[Computed] Invalid options: getter function is required.
7
+ Usage: computed({ get: () => value, set: (v) => { ... } })`);if(!shared.isFunction(t))throw new TypeError(`[Computed] Invalid options: getter must be a function.
8
+ Received: ${typeof t}`);return new X(t,n,r,i)}throw new Error(`[Computed] Invalid argument: expected a function or options object.
9
+ Received: ${typeof e}`)}function G(e){return !!e&&!!e._IS_COMPUTED}function mt(e){let{state:t,getters:n,actions:r}=e,i=U({},t),o=L(t),a=new Set,s=new Set,g={patch$(u){Q(()=>{Object.assign(o,u);}),a.forEach(S=>S(o)),s.forEach(S=>S(o));},subscribe$(u){a.add(u);},unsubscribe$(u){a.delete(u);},onAction$(u){s.add(u);},reset$(){Q(()=>{Object.assign(o,i);}),a.forEach(u=>u(o)),s.forEach(u=>u(o));}},d=U(he(U({},o),{state:o}),g);if(n)for(let u in n){let S=n[u];S&&Object.defineProperty(d,u,{get(){return ue(()=>S.call(d,o)).value},enumerable:true,configurable:true});}if(r)for(let u in r){let S=r[u];S&&(d[u]=(...Ke)=>{let We=S.apply(o,Ke);return s.forEach(Fe=>Fe(o)),We});}return d}function yt(e){let t=new e,n=Object.create(null),r={},i={};return Object.getOwnPropertyNames(t).forEach(o=>{n[o]=t[o];}),Object.getOwnPropertyNames(e.prototype).forEach(o=>{let a=Object.getOwnPropertyDescriptor(e.prototype,o);a&&(typeof a.get=="function"?r[o]=function(){return a.get.call(this)}:typeof a.value=="function"&&o!=="constructor"&&(i[o]=function(...s){return a.value.apply(this,s)}));}),{state:n,getters:r,actions:i}}function bt(e){return ()=>{let t;typeof e=="function"?t=yt(e):t=e;let n=mt(t);return typeof e=="function"&&Object.keys(t.actions||{}).forEach(r=>{n[r]=t.actions[r].bind(n);}),n}}var Pe,Ge,Z=class extends(Ge=R,Pe="_IS_REF",Ge){constructor(n){super(n,true);this[Pe]=true;}get value(){return f(this,ee),this._value}set value(n){T(n)&&(n=n.value),fe(n)&&(n=n.value),shared.hasChanged(this._value,n)&&(this._value=n,this.subLink&&V(this.subLink),p(this,"SET",ee));}};function vt(e=void 0){return fe(e)?e:T(e)?new Z(e.peek()):new Z(e)}function fe(e){return !!e&&!!e._IS_REF}var Ye={},Oe=new WeakMap;function w(e,t=new Set){if(!shared.isObject(e)||t.has(e))return e;if(t.add(e),T(e)||G(e))return w(e.value,t);if(Array.isArray(e))for(let n of e)w(n,t);else shared.isMap(e)?(e.forEach(n=>{w(n,t);}),e.keys(),e.values()):shared.isSet(e)?(e.forEach(n=>{w(n,t);}),e.values()):Object.keys(e).forEach(n=>{w(e[n],t);});return e}function I(e){if(!shared.isObject(e))return e;if(Array.isArray(e))return e.map(n=>I(n));if(shared.isMap(e)){let n=new Map;return e.forEach((r,i)=>{n.set(i,I(r));}),n}if(shared.isSet(e)){let n=new Set;return e.forEach(r=>{n.add(I(r));}),n}let t={};for(let n of Object.keys(e))t[n]=I(e[n]);return t}function Lt(e){return Array.isArray(e)?()=>e.map(t=>T(t)||G(t)?t.value:k(t)?w(t):shared.isFunction(t)?t():t):shared.isFunction(e)?e:T(e)?()=>e.value:shared.isObject(e)&&"value"in e?()=>e.value:k(e)?()=>w(e):()=>e}function Dt(e,t,n={}){let {immediate:r=false,deep:i=false}=n,o=Ye,s=Lt(e),g=()=>{let u=d.effect;if(!u.run)return;let S=u.run();shared.hasChanged(S,o)&&(t(S,o===Ye?void 0:o),o=I(S));},d=z(()=>{let u=s();return i&&w(u),u},{scheduler:()=>D(g)});return r?g():o=I(d.effect.run()),()=>{d.stop();let u=Oe.get(d.effect);u&&(u.forEach(S=>S()),Oe.delete(d.effect));}}exports.TriggerOpTypes=E;exports.batch=Q;exports.computed=ue;exports.createStore=bt;exports.effect=z;exports.endBatch=Ie;exports.getBatchDepth=ht;exports.isBatching=se;exports.isComputed=G;exports.isEffect=gt;exports.isReactive=k;exports.isRef=fe;exports.isShallow=b;exports.isSignal=T;exports.memoEffect=St;exports.nextTick=we;exports.queueJob=D;exports.queuePreFlushCb=De;exports.reactive=L;exports.ref=vt;exports.shallowReactive=B;exports.shallowSignal=lt;exports.signal=ft;exports.startBatch=Re;exports.stop=Et;exports.toRaw=c;exports.toReactive=ut;exports.trigger=p;exports.untrack=Qe;exports.watch=Dt;//# sourceMappingURL=signals.cjs.js.map
10
+ //# sourceMappingURL=signals.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/constants.ts","../src/propagation.ts","../src/link.ts","../src/reactive.ts","../src/signal.ts","../src/scheduler.ts","../src/batch.ts","../src/effect.ts","../src/computed.ts","../src/store.ts","../src/ref.ts","../src/watch.ts"],"names":["TriggerOpTypes","SIGNAL_KEY","ARRAY_KEY","COLLECTION_KEY","WEAK_COLLECTION_KEY","ARRAY_ITERATE_KEY","propagate","link","next","stack","top","sub","queueBit","watcherBit","flags","isValidLink","enqueueEffect","subSubs","nextSub","shallowPropagate","newFlags","effect","currentLinkVersion","activeSub","isUntracking","linkReactiveNode","depNode","subNode","prevDep","nextDep","prevSub","newLink","unlinkReactiveNode","linkNode","toRemove","checkDirty","pendingNodes","frame","current","owner","dep","depFlags","subs","node","setActiveSub","prev","startTracking","endTracking","depsTail","untrack","fn","prevUntracking","checkLink","targetMap","track","target","key","depsMap","trigger","type","newValue","effects","k","ITERATE_KEY","iterationKey","iterationDep","_a","reactiveCaches","toRaw","value","isObject","raw","isSignal","arrayInstrumentations","createArrayInstrumentations","instrumentations","args","arr","res","rawArgs","arg","isShallowMode","isShallow","reactiveImpl","i","l","item","rawIterator","done","v","arrayHandlers","shallow","receiver","hasOwn","isStringNumber","oldValue","result","hasChanged","shallowArrayHandlers","deepArrayHandlers","collectionHandlers","collectionInstrumentations","weakCollectionHandlers","weakInstrumentations","hadKey","rawValue","hadValue","hasKey","hadItems","callback","thisArg","wrappedValue","wrappedKey","isReactive","rawKey","objectHandlers","valueUnwrapped","existingProxy","handler","isArray","isSet","isMap","isWeakMap","isWeakSet","proxy","reactive","shallowReactive","toReactive","SignalImpl","updater","nextValue","signal","shallowSignal","queue","activePreFlushCbs","p","isFlushPending","nextTick","resolve","reject","error","queueJob","job","queueFlush","flushJobs","queuePreFlushCb","cb","flushPreFlushCbs","jobs","_error","callbacks","createScheduler","flush","batchDepth","batch","startBatch","endBatch","isBatching","getBatchDepth","EffectImpl","options","nextFlags","wasDirty","wasPending","isFunction","effectInstance","runner","stop","isEffect","memoEffect","initialState","currentState","NO_VALUE","ComputedImpl","getter","setter","onTrack","onTrigger","hasValue","clearMask","computed","getterOrOptions","isComputed","isPlainObject","get","set","createOptionsStore","state","getters","actions","initState","__spreadValues","reactiveState","subscriptions","actionCallbacks","defaultActions","payload","store","__spreadProps","action","createClassStore","StoreClass","instance","descriptor","createStore","storeDefinition","_b","RefImpl","isRef","ref","INITIAL_WATCHER_VALUE","cleanupMap","traverse","seen","element","cloneValue","cloned","resolveSource","source","s","watch","immediate","deep","currentEffect","cleanups"],"mappings":";;;;;ocAyEO,IAAMA,CAAAA,CAAiB,CAC5B,GAAA,CAAK,KAAA,CACL,IAAK,KAAA,CACL,MAAA,CAAQ,QAAA,CACR,KAAA,CAAO,OACT,EAiCO,IAAMC,EAAAA,CAA4B,MAAA,CAAgC,EAAE,CAAA,CAG9DC,CAAAA,CAA2B,MAAA,CAA+B,EAAE,EAG5DC,CAAAA,CAAgC,MAAA,CAAoC,EAAE,CAAA,CAGtEC,CAAAA,CAAqC,MAAA,CAAwC,EAAE,CAAA,CAY/EC,CAAAA,CAAmC,MAAA,CAAuC,EAAE,EClHlF,SAASC,CAAAA,CAAUC,CAAAA,CAAkB,CAE1C,IAAIC,CAAAA,CAAyBD,CAAAA,CAAK,WAAA,CAE9BE,CAAAA,CAIJC,CAAAA,CAAK,EAAG,CACN,IAAMC,CAAAA,CAAMJ,CAAAA,CAAK,OAAA,CAGXK,CAAAA,CAAWD,CAAAA,CAAI,KAAO,EAAA,CACtBE,CAAAA,CAAaF,CAAAA,CAAI,IAAA,CAAO,CAAA,CAC1BG,CAAAA,CAAQH,CAAAA,CAAI,IAAA,CAAO,GAAA,CA2CvB,GAtCIG,CAAAA,CACC,EAAA,CAQMA,CAAAA,CAAS,EAAA,GAKPA,EAAS,EAAA,CAITA,CAAAA,CAAQ,CAAA,CAIV,EAAEA,CAAAA,CAAS,EAAA,CAAA,EAAiDC,GAAYR,CAAAA,CAAMI,CAAG,CAAA,EAE1FA,CAAAA,CAAI,IAAA,CAAOC,CAAAA,CAAWC,GAAcC,CAAAA,CAAQ,CAAA,CAAyB,EAAA,CAAA,CACrEA,CAAAA,EAAS,CAAA,GAGTA,CAAAA,CAAQ,CAAA,CACRH,CAAAA,CAAI,IAAA,CAAOC,CAAAA,CAAW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A,OAAI+E,CAAAA,CACF/E,CAAAA,EAAI,CAGJ/C,CAAAA,CAAWwH,EAAWjD,CAAAA,CAAO,MAAA,CAAO,GAAA,EAAK,CAAA,CAIpC,IAAM,CACXA,CAAAA,CAAO,IAAA,EAGG,CAGV,IAAM0D,CAAAA,CAAWb,EAAAA,CAAW,GAAA,CAAI7C,CAAAA,CAAO,MAAM,CAAA,CACzC0D,IACFA,CAAAA,CAAS,OAAA,CAAQ9K,CAAAA,EAAMA,CAAAA,EAAI,CAAA,CAC3BiK,GAAW,MAAA,CAAO7C,CAAAA,CAAO,MAAM,CAAA,EAEnC,CACF","file":"signals.cjs.js","sourcesContent":["/**\r\n * Reactive node state flags\r\n */\r\nexport const enum ReactiveFlags {\r\n /** No state flags */\r\n NONE = 0,\r\n\r\n /**\r\n * Mutable flag - The node's value can change\r\n *\r\n * Signal and Computed are mutable, triggering propagation when their values change.\r\n * Immutable nodes (like constants) don't set this flag.\r\n */\r\n // eslint-disable-next-line unicorn/prefer-math-trunc\r\n MUTABLE = 1 << 0, // 0b00000001 = 1\r\n\r\n /**\r\n * Watching flag - The node is being watched by an Effect\r\n *\r\n * Set when an Effect depends on this node.\r\n * Used to determine whether to add the Effect to the execution queue.\r\n */\r\n WATCHING = 1 << 1, // 0b00000010 = 2\r\n\r\n /**\r\n * Recursion check flag - Currently checking for circular dependencies\r\n *\r\n * Set during the checkDirty process to detect and handle circular dependencies.\r\n * Prevents infinite recursion.\r\n */\r\n RECURSED_CHECK = 1 << 2, // 0b00000100 = 4\r\n\r\n /**\r\n * Recursed flag - Already in the recursion chain\r\n *\r\n * Marks that the node has already appeared in the current propagation path.\r\n * Used to handle complex dependency graph structures.\r\n */\r\n RECURSED = 1 << 3, // 0b00001000 = 8\r\n\r\n /**\r\n * Dirty flag - The node's value has changed but hasn't propagated yet\r\n *\r\n * Set when a Signal value changes.\r\n * Also set when Computed detects dependency changes.\r\n * Indicates need to recompute or notify subscribers.\r\n */\r\n DIRTY = 1 << 4, // 0b00010000 = 16\r\n\r\n /**\r\n * Pending flag - The node may need updating\r\n *\r\n * Set during propagation, indicating the node's dependencies may have become dirty.\r\n * Need to call checkDirty to confirm if update is actually needed.\r\n */\r\n PENDING = 1 << 5, // 0b00100000 = 32\r\n\r\n /**\r\n * Queued flag - Effect has been added to the execution queue\r\n *\r\n * Prevents the same Effect from being added to the queue multiple times.\r\n * This flag is cleared before queue execution.\r\n */\r\n QUEUED = 1 << 6, // 0b01000000 = 64\r\n}\r\n\r\n// Define specific flags for effects\r\nexport enum EffectFlags {\r\n ALLOW_RECURSE = 1 << 7, // Allow recursive calls\r\n PAUSED = 1 << 8, // Paused\r\n STOP = 1 << 10, // Stopped\r\n}\r\n// Define operation type constants\r\nexport const TriggerOpTypes = {\r\n SET: 'SET',\r\n ADD: 'ADD',\r\n DELETE: 'DELETE',\r\n CLEAR: 'CLEAR',\r\n} as const;\r\n\r\n/**\r\n * Internal flags used to mark and identify different types of reactive objects.\r\n * These flags are attached as properties to objects to indicate their reactive characteristics.\r\n */\r\nexport enum SignalFlags {\r\n /** Mark an object as reactive */\r\n IS_REACTIVE = '_IS_REACTIVE',\r\n\r\n /** Mark an object as readonly */\r\n IS_READONLY = '_IS_READONLY',\r\n\r\n /** Mark an object as shallow reactive (only top-level properties are reactive) */\r\n IS_SHALLOW = '_IS_SHALLOW',\r\n\r\n /** Used to access the raw (non-reactive) version of an object */\r\n RAW = '_RAW',\r\n\r\n /** Mark an object as a signal */\r\n IS_SIGNAL = '_IS_SIGNAL',\r\n\r\n /** Mark an object as a computed property */\r\n IS_COMPUTED = '_IS_COMPUTED',\r\n\r\n /** Mark an object as a ref */\r\n IS_REF = '_IS_REF',\r\n\r\n /** Mark an object as an effect */\r\n IS_EFFECT = '_IS_EFFECT',\r\n}\r\n\r\n/** Symbol used to track signal value changes */\r\nexport const SIGNAL_KEY: unique symbol = Symbol(__DEV__ ? 'Signal_Key' : '');\r\n\r\n/** Symbol used to track array operation changes */\r\nexport const ARRAY_KEY: unique symbol = Symbol(__DEV__ ? 'Array_Key' : '');\r\n\r\n/** Symbol used to track regular collection (Map/Set) operation changes */\r\nexport const COLLECTION_KEY: unique symbol = Symbol(__DEV__ ? 'Collection_Key' : '');\r\n\r\n/** Symbol used to track weak collection (WeakMap/WeakSet) operation changes */\r\nexport const WEAK_COLLECTION_KEY: unique symbol = Symbol(__DEV__ ? 'WeakCollection_Key' : '');\r\n\r\n/** Symbol used to track iteration operations */\r\nexport const ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'Iterate_Key' : '');\r\n\r\n/** Symbol used to track Map key iteration operations */\r\nexport const MAP_KEY_ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'MapKeyIterate_Key' : '');\r\n\r\n/** Symbol used to track computed property dependencies */\r\nexport const COMPUTED_KEY: unique symbol = Symbol(__DEV__ ? 'Computed_Key' : '');\r\n\r\n/** Unique symbol used to track array iteration */\r\nexport const ARRAY_ITERATE_KEY: unique symbol = Symbol(__DEV__ ? 'Array_Iterate_Key' : '');\r\n\r\nexport type TRACKING_KEY =\r\n | typeof SIGNAL_KEY\r\n | typeof ARRAY_KEY\r\n | typeof COLLECTION_KEY\r\n | typeof WEAK_COLLECTION_KEY\r\n | typeof ITERATE_KEY\r\n | typeof MAP_KEY_ITERATE_KEY\r\n | typeof COMPUTED_KEY;\r\n","import { ReactiveFlags } from './constants';\nimport { type Link, type ReactiveNode, isValidLink } from './link';\n\ninterface LinkStackNode {\n /** Link value */\n value: Link | undefined;\n /** Previous stack node */\n prev?: LinkStackNode;\n}\n\n/**\n * Propagate changes to all subscribers\n *\n * This is the core propagation algorithm of the reactive system.\n * When a Signal value changes, propagate the DIRTY flag along the subscriber chain.\n *\n * @param link - Starting Link of the subscriber chain\n */\nexport function propagate(link: Link): void {\n // Next sibling Link\n let next: Link | undefined = link.nextSubLink;\n // Explicit stack for depth-first traversal\n let stack: LinkStackNode | undefined;\n\n // Main loop - traverse the entire dependency graph\n // eslint-disable-next-line no-restricted-syntax\n top: do {\n const sub = link.subNode;\n\n // Extract state flags\n const queueBit = sub.flag & ReactiveFlags.QUEUED;\n const watcherBit = sub.flag & ReactiveFlags.WATCHING;\n let flags = sub.flag & ~ReactiveFlags.QUEUED;\n\n // State machine - decide operation based on current node state\n if (\n !(\n flags &\n (ReactiveFlags.DIRTY |\n ReactiveFlags.PENDING |\n ReactiveFlags.RECURSED |\n ReactiveFlags.RECURSED_CHECK)\n )\n ) {\n // Case 1: Clean state -> mark as PENDING\n sub.flag = queueBit | watcherBit | flags | ReactiveFlags.PENDING;\n } else if (flags & (ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) {\n // Case 2: Already DIRTY or PENDING -> no change, but continue propagation\n // This branch is important: when a node has multiple dependencies (diamond dependency),\n // the first dependency propagation marks it as PENDING, the second should not clear this flag\n // Keep original flags unchanged\n } else if (!(flags & (ReactiveFlags.RECURSED | ReactiveFlags.RECURSED_CHECK))) {\n // Case 3: Already processed but not in recursion chain -> clear flags\n flags = ReactiveFlags.NONE;\n sub.flag = queueBit | watcherBit;\n } else if (!(flags & ReactiveFlags.RECURSED_CHECK)) {\n // Case 4: In recursion chain but not checked -> mark PENDING\n sub.flag =\n queueBit | watcherBit | ((flags & ~ReactiveFlags.RECURSED) | ReactiveFlags.PENDING);\n } else if (!(flags & (ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) && isValidLink(link, sub)) {\n // Case 5: Recursion check and Link valid -> allow propagation\n sub.flag = queueBit | watcherBit | (flags | ReactiveFlags.RECURSED | ReactiveFlags.PENDING);\n flags &= ReactiveFlags.MUTABLE;\n } else {\n // Case 6: Other cases -> clear flags\n flags = ReactiveFlags.NONE;\n sub.flag = queueBit | watcherBit;\n }\n\n // If it's an Effect, add to execution queue\n if (sub.flag & ReactiveFlags.WATCHING) {\n enqueueEffect(sub as any);\n }\n\n // Continue propagating downward\n if (flags & ReactiveFlags.MUTABLE) {\n const subSubs = sub.subLink;\n if (subSubs) {\n // Has subscribers, go one level deeper\n const nextSub = (link = subSubs).nextSubLink;\n if (nextSub) {\n // Save current context to stack\n stack = { value: next, prev: stack };\n next = nextSub;\n }\n continue;\n }\n }\n\n // Process sibling nodes\n if (next) {\n link = next;\n next = link.nextSubLink;\n continue;\n }\n\n // Backtrack to parent level\n while (stack) {\n link = stack.value!;\n stack = stack.prev;\n if (link) {\n next = link.nextSubLink;\n continue top;\n }\n }\n\n // All nodes processed\n break;\n } while (true);\n}\n\n/**\n * Shallow propagate - only mark direct subscribers\n *\n * Does not recursively propagate, only affects one level of subscribers.\n * Mainly used for Computed values to update their direct subscribers.\n *\n * @param link - Starting Link of the subscriber chain\n */\nexport function shallowPropagate(link: Link | undefined): void {\n while (link) {\n const sub = link.subNode;\n const queueBit = sub.flag & ReactiveFlags.QUEUED;\n const flags = sub.flag & ~ReactiveFlags.QUEUED;\n\n // Process PENDING or clean state nodes, mark them as DIRTY\n if (!(flags & ReactiveFlags.DIRTY) && flags & (ReactiveFlags.MUTABLE | ReactiveFlags.PENDING)) {\n // Mark as DIRTY, clear PENDING flag using bitwise operations\n const newFlags = queueBit | (flags & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n sub.flag = newFlags;\n\n // If it's an Effect, add to execution queue\n if (newFlags & ReactiveFlags.WATCHING) {\n enqueueEffect(sub as Effect);\n }\n\n // If it's a MUTABLE node (like Computed), continue shallow propagation\n if (flags & ReactiveFlags.MUTABLE && sub.subLink) {\n shallowPropagate(sub.subLink);\n }\n }\n\n link = link.nextSubLink;\n }\n}\n\n/**\n * Effect interface\n *\n * Objects implementing this interface can be scheduled for execution.\n */\nexport interface Effect extends ReactiveNode {\n /** Whether the Effect is active */\n active: boolean;\n\n /** Execute the Effect */\n notify(): void;\n\n /** Trigger debug hook (optional) */\n onTrigger?(event: any): void;\n}\n\nexport function enqueueEffect(effect: Effect): void {\n // Check if Effect is active\n if (!effect.active) {\n return;\n }\n\n // Directly call notify, let effect decide how to handle\n effect.notify();\n}\n\n/**\n * Clear propagation flags\n *\n * After batch update ends, clear all flags set during propagation.\n *\n * @param node - The node to clear\n */\nexport function clearPropagationFlags(node: ReactiveNode): void {\n node.flag &= ~(ReactiveFlags.PENDING | ReactiveFlags.RECURSED | ReactiveFlags.RECURSED_CHECK);\n}\n","import { error, isFunction } from '@estjs/shared';\nimport { ReactiveFlags } from './constants';\nimport { type Effect, propagate } from './propagation';\n\n/**\n * Link - Bidirectional connection in the dependency graph\n *\n * A Link connects two ReactiveNodes:\n * - depNode: The dependency node (data source)\n * - subNode: The subscriber node (data consumer)\n *\n * Links form doubly-linked lists in two directions:\n * 1. Subscriber Chain: Connects all subscribers of the same dependency\n * 2. Dependency Chain: Connects all dependencies of the same subscriber\n *\n * @example\n * ```\n * Signal A ←─┐\n * ├─→ Effect X\n * Signal B ←─┘\n *\n * Link1: A → X (A's subscriber chain, X's dependency chain)\n * Link2: B → X (B's subscriber chain, X's dependency chain)\n * ```\n */\nexport interface Link {\n /**\n * Version number\n *\n * Used to detect stale Links.\n * The global version number increments each time dependency tracking starts.\n * Links with old versions will be cleaned up.\n *\n */\n version: number;\n\n /**\n * Dependency node - The data source being depended on\n * Examples: Signal, Computed\n */\n depNode: ReactiveNode;\n\n /**\n * Subscriber node - The consumer of the data\n * Examples: Effect, Computed\n */\n subNode: ReactiveNode;\n\n // Connects multiple subscribers of the same depNode\n\n /** Previous subscriber Link */\n prevSubLink?: Link;\n\n /** Next subscriber Link */\n nextSubLink?: Link;\n\n // Connects multiple dependencies of the same subNode\n\n /** Previous dependency Link */\n prevDepLink?: Link;\n\n /** Next dependency Link */\n nextDepLink?: Link;\n}\n\n/**\n * Debugger event types for tracking reactive operations\n */\nexport type DebuggerEventType = 'get' | 'set' | 'add' | 'delete' | 'clear' | 'iterate';\n\n/**\n * Debugger event for tracking reactive operations\n *\n * This event is passed to onTrack and onTrigger callbacks to provide\n * detailed information about reactive operations for debugging purposes.\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrack(event) {\n * console.log('Tracked:', event.type, event.key);\n * },\n * onTrigger(event) {\n * console.log('Triggered:', event.type, event.key, event.newValue);\n * }\n * });\n * ```\n */\nexport interface DebuggerEvent {\n /** The effect or computed that is tracking/being triggered */\n effect: ReactiveNode;\n /** The reactive object being accessed or modified */\n target: object;\n /** The type of operation */\n type: DebuggerEventType | string;\n /** The property key being accessed or modified (optional) */\n key?: any;\n /** The new value being set (optional, only for trigger events) */\n newValue?: any;\n}\n\n/**\n * ReactiveNode - Reactive node interface\n *\n * All objects participating in the reactive system implement this interface.\n * Includes Signal, Computed, Effect, Reactive objects, etc.\n *\n * Nodes form a dependency graph through Links:\n * - depLink: List of nodes I depend on\n * - subLink: List of nodes that depend on me\n */\nexport interface ReactiveNode {\n /**\n * Dependency chain head - The first node I depend on\n *\n * Traverse all dependencies through nextDepLink.\n */\n depLink?: Link;\n\n /**\n * Subscriber chain head - The first node that depends on me\n *\n * Traverse all subscribers through nextSubLink.\n */\n subLink?: Link;\n\n /**\n * Dependency chain tail - The last node I depend on\n *\n * Used for O(1) time complexity linked list append operations.\n */\n depLinkTail?: Link;\n\n /**\n * Subscriber chain tail - The last node that depends on me\n *\n * Used for O(1) time complexity linked list append operations.\n */\n subLinkTail?: Link;\n\n /**\n * State flags\n * @see ReactiveFlags\n */\n flag: ReactiveFlags;\n\n /**\n * Optional debugging hook called when dependencies are tracked\n */\n onTrack?: (event: DebuggerEvent) => void;\n\n /**\n * Optional debugging hook called when reactive changes are triggered\n */\n onTrigger?: (event: DebuggerEvent) => void;\n}\n\n/**\n * Current Link version number\n *\n * Increments each time dependency tracking starts.\n * Used to identify and clean up stale Links.\n */\nlet currentLinkVersion = 0;\n\n/**\n * Currently active subscriber\n *\n * Set to the current node when Effect/Computed executes.\n * When a Signal is accessed, it automatically establishes a Link with activeSub.\n */\nexport let activeSub: ReactiveNode | undefined;\n\n/**\n * Whether tracking is disabled\n *\n * The untrack() function temporarily sets this to true.\n * During this time, accessing Signals won't establish dependencies.\n */\nlet isUntracking = false;\n\n/**\n * Get whether currently in untrack mode\n */\nexport function getIsUntracking(): boolean {\n return isUntracking;\n}\n\nexport function linkReactiveNode(depNode: ReactiveNode, subNode: ReactiveNode): Link | undefined {\n // If in untrack mode, don't establish any dependencies\n // This is used by untrack() to access reactive values without creating dependencies\n if (isUntracking) {\n return undefined;\n }\n\n const prevDep = subNode.depLinkTail;\n if (prevDep && prevDep.depNode === depNode) {\n // Same dependency as last time - return existing Link immediately\n // This is the fastest path: single pointer comparison\n return prevDep;\n }\n\n const nextDep = prevDep ? prevDep.nextDepLink : subNode.depLink;\n if (nextDep && nextDep.depNode === depNode) {\n // Found a reusable Link! Update its version to mark it as \"still in use\"\n // Links with old versions will be cleaned up by endTracking()\n (nextDep as any).version = currentLinkVersion;\n // Move the tail pointer forward to this Link\n subNode.depLinkTail = nextDep;\n return nextDep;\n }\n\n const prevSub = depNode.subLinkTail;\n if (prevSub && prevSub.version === currentLinkVersion && prevSub.subNode === subNode) {\n // This Link was just created in the current tracking cycle\n // Update subscriber's tail to point to it\n subNode.depLinkTail = prevSub;\n return prevSub;\n }\n\n // No reusable Link found - need to create a new one\n // This happens on first execution or when dependency order changes\n const newLink: Link = {\n version: currentLinkVersion,\n depNode,\n subNode,\n // Subscriber chain pointers (horizontal)\n prevSubLink: prevSub,\n nextSubLink: undefined,\n // Dependency chain pointers (vertical)\n prevDepLink: prevDep,\n nextDepLink: nextDep,\n };\n\n // Insert the new Link into the subscriber's dependency chain\n // This maintains the doubly-linked list structure\n if (nextDep) {\n // There's a Link after this position - update its back pointer\n nextDep.prevDepLink = newLink;\n }\n if (prevDep) {\n // There's a Link before this position - update its forward pointer\n prevDep.nextDepLink = newLink;\n } else {\n // This is the first dependency - update the head pointer\n subNode.depLink = newLink;\n }\n\n // Insert the new Link into the dependency's subscriber chain\n if (prevSub) {\n // There are existing subscribers - append to the end\n prevSub.nextSubLink = newLink;\n } else {\n // This is the first subscriber - update the head pointer\n depNode.subLink = newLink;\n }\n\n // Tail pointers enable O(1) append operations\n // Without them, we'd need O(n) traversal to find the end of the list\n depNode.subLinkTail = newLink;\n subNode.depLinkTail = newLink;\n\n // In development mode, notify debugging tools about the new dependency\n if (__DEV__) {\n if (subNode.onTrack && isFunction(subNode?.onTrack)) {\n subNode.onTrack({\n effect: subNode,\n target: depNode,\n type: 'get',\n key: undefined,\n });\n }\n }\n\n return newLink;\n}\n\n/**\n * Remove a dependency link\n */\nexport function unlinkReactiveNode(\n linkNode: Link,\n subNode: ReactiveNode = linkNode.subNode,\n): Link | undefined {\n const depNode = linkNode.depNode;\n const prevSub = linkNode.prevSubLink;\n const nextSub = linkNode.nextSubLink;\n const prevDep = linkNode.prevDepLink;\n const nextDep = linkNode.nextDepLink;\n\n // Update the doubly-linked list pointers in the subscriber's dependency chain\n // This removes the link from the vertical chain (all dependencies of subNode)\n if (nextDep) {\n nextDep.prevDepLink = prevDep;\n } else {\n // This was the tail - update tail pointer\n subNode.depLinkTail = prevDep;\n }\n if (prevDep) {\n prevDep.nextDepLink = nextDep;\n } else {\n // This was the head - update head pointer\n subNode.depLink = nextDep;\n }\n\n // Update the doubly-linked list pointers in the dependency's subscriber chain\n // This removes the link from the horizontal chain (all subscribers of depNode)\n if (nextSub) {\n nextSub.prevSubLink = prevSub;\n } else {\n // This was the tail - update tail pointer\n depNode.subLinkTail = prevSub;\n }\n if (prevSub) {\n prevSub.nextSubLink = nextSub;\n } else {\n // This was the head - update head pointer and check for cascading cleanup\n depNode.subLink = nextSub;\n\n // If depNode has no more subscribers, it doesn't need to track its dependencies\n // This is a critical optimization for memory management\n if (nextSub === undefined) {\n // No more subscribers - clean up all dependencies recursively\n let toRemove = depNode.depLink;\n while (toRemove) {\n toRemove = unlinkReactiveNode(toRemove, depNode);\n }\n\n // Clear tail pointer to ensure no dangling references\n depNode.depLinkTail = undefined;\n\n // Mark as dirty so it recomputes on next access\n // This is important for computed values that might be accessed again later\n depNode.flag |= ReactiveFlags.DIRTY;\n\n // Development mode verification\n if (__DEV__) {\n // Verify that all links were properly cleared\n if (depNode.depLink) {\n error(\n '[Link] Cascading cleanup failed: depNode still has dependency links. ' +\n 'This indicates a bug in the unlinking logic.',\n );\n }\n }\n }\n }\n\n // Clear all references in the link to enable garbage collection\n // This is important for preventing memory leaks\n (linkNode as any).depNode = undefined;\n (linkNode as any).subNode = undefined;\n linkNode.prevSubLink = undefined;\n linkNode.nextSubLink = undefined;\n linkNode.prevDepLink = undefined;\n linkNode.nextDepLink = undefined;\n\n // Return the next link in the dependency chain for iteration\n return nextDep;\n}\n\n/**\n * Check stack frame\n *\n * Used to save check state in iterative implementation.\n */\ninterface CheckStackFrame {\n /** The Link currently being checked */\n link: Link | undefined;\n /** The node that owns the Link */\n owner: ReactiveNode;\n}\n\n/**\n * Check if the dependency chain is dirty\n *\n * This function determines whether a subscriber node needs to recompute by checking\n * if any of its dependencies (or transitive dependencies) are dirty.\n *\n * ## Algorithm Overview\n *\n * The algorithm performs a depth-first traversal of the dependency graph using an\n * explicit stack to avoid recursion limits. It handles three main scenarios:\n *\n * 1. **DIRTY dependencies**: If any dependency is marked DIRTY, the subscriber is dirty\n * 2. **PENDING dependencies**: Dependencies that might be dirty - need deeper checking\n * 3. **Clean dependencies**: Dependencies that are confirmed clean\n *\n * ## Why Use an Explicit Stack?\n *\n * JavaScript has a limited call stack (~10,000 frames). In complex reactive systems,\n * dependency chains can be arbitrarily deep (e.g., computed1 → computed2 → ... → computedN).\n * Using an explicit stack allows us to handle unlimited depth without stack overflow.\n *\n * ## Algorithm Steps\n *\n * 1. Initialize stack with the subscriber's dependency chain\n * 2. For each dependency in the chain:\n * - If DIRTY: Mark path as dirty and return true\n * - If PENDING + MUTABLE: Push its dependencies onto stack for deeper checking\n * - Otherwise: Clear PENDING flag (confirmed clean)\n * 3. Track PENDING nodes encountered during traversal\n * 4. If dirty found: Mark all PENDING nodes on path as DIRTY\n * 5. If no dirty found: Clear all PENDING flags\n *\n * ## Edge Cases Handled\n *\n * - **Diamond dependencies**: A node with multiple paths to the same dependency\n * - The algorithm correctly handles this by checking all paths\n * - **Circular dependencies**: Prevented by the RECURSED flag in propagation\n * - **Deep chains**: Handled by explicit stack instead of recursion\n * - **Multiple subscribers**: Uses shallowPropagate to update sibling subscribers\n *\n * ## Performance Characteristics\n *\n * - Time complexity: O(n) where n is the total number of dependencies in the chain\n * - Space complexity: O(d) where d is the maximum depth of the dependency graph\n * - Early exit: Returns immediately when first DIRTY dependency is found\n *\n * @param link - The starting Link of the dependency chain to check\n * @param sub - The subscriber node that owns this dependency chain\n * @returns true if any dependency is dirty (subscriber needs recomputation), false otherwise\n *\n * @example\n * ```typescript\n * // Simple case: signal → computed\n * const s = signal(1);\n * const c = computed(() => s.value * 2);\n * s.value = 2; // Marks s as DIRTY\n * // When accessing c.value, checkDirty(c.depLink, c) returns true\n *\n * // Complex case: diamond dependency\n * const s = signal(1);\n * const c1 = computed(() => s.value * 2);\n * const c2 = computed(() => s.value + 1);\n * const c3 = computed(() => c1.value + c2.value);\n * // c3 depends on both c1 and c2, which both depend on s\n * // checkDirty correctly handles both paths to s\n * ```\n */\nexport function checkDirty(link: Link, sub: ReactiveNode): boolean {\n // Use explicit stack instead of recursion to support arbitrary depth\n // Each stack frame contains:\n // - link: The dependency Link to check\n // - owner: The ReactiveNode that owns this Link\n const stack: CheckStackFrame[] = [{ link, owner: sub }];\n\n // Track all PENDING nodes encountered during traversal\n // If we find a DIRTY dependency, we'll mark all these as DIRTY too\n // This ensures the entire path from dirty source to subscriber is marked\n const pendingNodes: ReactiveNode[] = [];\n\n // Process stack frames until empty (depth-first traversal)\n while (stack.length > 0) {\n const frame = stack.pop()!;\n let current = frame.link;\n const owner = frame.owner;\n\n // Traverse all dependencies at the current level (linked list)\n // This handles nodes with multiple dependencies (e.g., computed(() => a.value + b.value))\n while (current) {\n const dep = current.depNode;\n const depFlags = dep.flag;\n\n // If owner is already marked DIRTY, no need to continue checking\n // This can happen in diamond dependencies where multiple paths lead to same node\n if (owner.flag & ReactiveFlags.DIRTY) {\n return true;\n }\n\n // Dependency is both MUTABLE (can change) and DIRTY (has changed)\n // This means the subscriber definitely needs to recompute\n if (\n (depFlags & (ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY)) ===\n (ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY)\n ) {\n const subs = dep.subLink;\n // If this dependency has multiple subscribers, propagate to all of them\n // This ensures sibling subscribers are also marked dirty\n if (subs && subs.nextSubLink) {\n shallowPropagate(subs);\n }\n\n // Mark all PENDING nodes on the path from dirty source to subscriber as DIRTY\n // This is crucial for correctness: if A depends on B depends on C, and C is dirty,\n // then both B and A should be marked dirty\n for (const node of pendingNodes) {\n if (node.flag & ReactiveFlags.PENDING) {\n node.flag = (node.flag & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n }\n }\n return true;\n }\n\n // Dependency is MUTABLE and PENDING (might be dirty, need to check its dependencies)\n // This is the recursive case - we need to check if this dependency's dependencies are dirty\n if (\n (depFlags & (ReactiveFlags.MUTABLE | ReactiveFlags.PENDING)) ===\n (ReactiveFlags.MUTABLE | ReactiveFlags.PENDING)\n ) {\n if (dep.depLink) {\n // Add this node to pending list - we'll mark it dirty if we find dirty dependencies\n pendingNodes.push(dep);\n // Push this dependency's dependencies onto stack for checking\n // This is the key optimization: instead of recursive call, we use explicit stack\n // This allows handling chains like: computed1 → computed2 → ... → computedN → signal\n stack.push({ link: dep.depLink, owner: dep });\n } else {\n // No dependencies means this is a leaf node (e.g., a Signal)\n // If it's PENDING but has no dependencies, it's actually clean\n dep.flag &= ~ReactiveFlags.PENDING;\n }\n } else if (depFlags & ReactiveFlags.PENDING) {\n // Dependency is PENDING but not MUTABLE (or already checked)\n // Clear the PENDING flag - this dependency is confirmed clean\n dep.flag &= ~ReactiveFlags.PENDING;\n }\n\n // Move to next dependency in the chain (horizontal traversal)\n current = current.nextDepLink;\n }\n }\n\n // We've checked all dependencies and found no DIRTY ones\n // Clear PENDING flags from all nodes we encountered\n for (const node of pendingNodes) {\n node.flag &= ~ReactiveFlags.PENDING;\n }\n\n // Clear subscriber's PENDING flag\n if (sub.flag & ReactiveFlags.PENDING) {\n sub.flag &= ~ReactiveFlags.PENDING;\n }\n\n // All dependencies are clean - subscriber doesn't need recomputation\n return false;\n}\n\n/**\n * Shallow propagate - Only mark direct subscribers as dirty\n *\n * Does not recursively propagate, only affects one level of subscribers.\n * Used for Computed to update its subscribers.\n *\n * @param link - The starting Link of the subscriber chain\n */\nexport function shallowPropagate(link: Link | undefined): void {\n while (link) {\n const sub = link.subNode;\n const queueBit = sub.flag & ReactiveFlags.QUEUED;\n const flags = sub.flag & ~ReactiveFlags.QUEUED;\n\n // Only process nodes in PENDING state\n if ((flags & (ReactiveFlags.PENDING | ReactiveFlags.DIRTY)) === ReactiveFlags.PENDING) {\n // Mark as DIRTY\n sub.flag = queueBit | flags | ReactiveFlags.DIRTY;\n }\n\n link = link.nextSubLink;\n }\n}\n\n/**\n * Set the active subscriber\n *\n * @param sub - The new active subscriber\n * @returns The previous active subscriber\n */\nexport function setActiveSub(sub?: ReactiveNode): ReactiveNode | undefined {\n const prev = activeSub;\n activeSub = sub;\n return prev;\n}\n\n/**\n * Start tracking dependencies\n *\n * Called before Effect/Computed execution.\n * Increments version number, stale Links will be cleaned up.\n *\n * @param sub - The subscriber node to track\n * @returns The previous active subscriber\n */\nexport function startTracking(sub: ReactiveNode): ReactiveNode | undefined {\n // Increment version number to mark new tracking cycle\n currentLinkVersion++;\n\n // Reset tracking state\n sub.depLinkTail = undefined;\n\n // Clear recursion and dirty flags, set recursion check flag\n sub.flag =\n (sub.flag & ~(ReactiveFlags.RECURSED | ReactiveFlags.DIRTY | ReactiveFlags.PENDING)) |\n ReactiveFlags.RECURSED_CHECK;\n\n return setActiveSub(sub);\n}\n\n/**\n * End tracking dependencies\n *\n * Called after Effect/Computed execution.\n * Cleans up stale Links (version number less than current version).\n *\n * @param sub - The tracked subscriber node\n * @param prevSub - The previous active subscriber\n */\nexport function endTracking(sub: ReactiveNode, prevSub: ReactiveNode | undefined): void {\n // Restore previous active subscriber\n activeSub = prevSub;\n\n // Clean up stale Links\n const depsTail = sub.depLinkTail;\n let toRemove = depsTail ? depsTail.nextDepLink : sub.depLink;\n\n while (toRemove) {\n toRemove = unlinkReactiveNode(toRemove, sub);\n }\n\n // Clear recursion check flag\n sub.flag &= ~ReactiveFlags.RECURSED_CHECK;\n}\n\n/**\n * Execute function with tracking disabled\n *\n * During function execution, accessing Signals won't establish dependencies.\n *\n * @param fn - The function to execute\n * @returns The function's return value\n */\nexport function untrack<T>(fn: () => T): T {\n const prevSub = setActiveSub(undefined);\n const prevUntracking = isUntracking;\n isUntracking = true;\n\n try {\n return fn();\n } finally {\n isUntracking = prevUntracking;\n setActiveSub(prevSub);\n }\n}\n\n/**\n * Validate if a Link is still valid\n *\n * Checks if the Link is still in the subscriber's dependency chain.\n * Used to prevent propagation through stale Links.\n *\n * @param checkLink - The Link to validate\n * @param sub - The subscriber node\n * @returns true if the Link is valid\n */\nexport function isValidLink(checkLink: Link, sub: ReactiveNode): boolean {\n let link = sub.depLinkTail;\n\n while (link) {\n if (link === checkLink) {\n return true;\n }\n link = link.prevDepLink;\n }\n\n return false;\n}\n\n/**\n * Global dependency map for reactive objects\n *\n * This WeakMap stores the dependency relationships for reactive objects (created by reactive()).\n * Structure: WeakMap<target, Map<key, Set<ReactiveNode>>>\n *\n * - WeakMap allows garbage collection of unused reactive objects\n * - Map stores per-property dependencies\n * - Set stores all subscribers for each property\n *\n * This is separate from the Link-based dependency tracking used by Signal/Computed/Effect.\n * It's specifically for tracking property access on reactive objects.\n */\nconst targetMap = new WeakMap<object, Map<string | symbol, Set<ReactiveNode>>>();\n\n/**\n * Track a dependency on a reactive object property\n *\n * This function establishes a dependency relationship between the currently active\n * subscriber (effect/computed) and a specific property of a reactive object.\n *\n * ## When is this called?\n *\n * - When accessing a property on a reactive object: `reactiveObj.prop`\n * - When accessing array elements: `reactiveArray[0]`\n * - When calling array methods: `reactiveArray.length`, `reactiveArray.includes()`\n * - When iterating collections: `for (const item of reactiveArray)`\n *\n * ## How it works\n *\n * 1. Check if there's an active subscriber (effect/computed currently executing)\n * 2. Get or create the dependency map for the target object\n * 3. Get or create the dependency set for the specific property\n * 4. Add the active subscriber to the set\n * 5. Call debug hook if in development mode\n *\n * ## Relationship with Link-based tracking\n *\n * This function is used for reactive objects, while linkReactiveNode() is used for\n * Signal/Computed dependencies. Both systems work together:\n *\n * ```typescript\n * const obj = reactive({ count: 0 });\n * const sig = signal(1);\n *\n * effect(() => {\n * console.log(obj.count); // Uses track()\n * console.log(sig.value); // Uses linkReactiveNode()\n * });\n * ```\n *\n * ## Performance considerations\n *\n * - WeakMap lookup: O(1) average case\n * - Map lookup: O(1) average case\n * - Set.has() and Set.add(): O(1) average case\n * - Overall: O(1) for tracking a single property\n *\n * @param target - The reactive object being accessed\n * @param key - The property key being accessed (string, number, or symbol)\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, name: 'Alice' });\n *\n * effect(() => {\n * // track(state, 'count') is called automatically\n * console.log(state.count);\n * });\n *\n * // Changing count will trigger the effect\n * state.count++; // trigger(state, 'SET', 'count', 1)\n * ```\n */\nexport function track(target: object, key: string | symbol): void {\n // Only track if there's an active subscriber (effect/computed currently executing)\n // and tracking is not disabled (not in untrack() call)\n if (!activeSub || isUntracking) {\n return;\n }\n\n // Each target object has a Map of its property dependencies\n let depsMap = targetMap.get(target);\n if (!depsMap) {\n depsMap = new Map();\n targetMap.set(target, depsMap);\n }\n\n // Each property has a Set of subscribers that depend on it\n let dep = depsMap.get(key);\n if (!dep) {\n dep = new Set();\n depsMap.set(key, dep);\n }\n\n // Only add if not already present (Set automatically handles duplicates)\n if (!dep.has(activeSub)) {\n dep.add(activeSub);\n\n // In development mode, notify debugging tools about the dependency\n // This enables features like dependency visualization and tracking logs\n if (__DEV__ && isFunction(activeSub.onTrack)) {\n activeSub.onTrack({\n effect: activeSub,\n target,\n type: 'get',\n key,\n });\n }\n }\n}\n\n/**\n * Trigger updates for subscribers of a reactive object property\n *\n * This function notifies all subscribers (effects/computed) that depend on a specific\n * property of a reactive object that the property has changed.\n *\n * ## When is this called?\n *\n * - When setting a property: `reactiveObj.prop = value` → trigger(obj, 'SET', 'prop', value)\n * - When adding a property: `reactiveObj.newProp = value` → trigger(obj, 'ADD', 'newProp', value)\n * - When deleting a property: `delete reactiveObj.prop` → trigger(obj, 'DELETE', 'prop')\n * - When clearing a collection: `reactiveArray.length = 0` → trigger(obj, 'CLEAR')\n * - When mutating arrays: `reactiveArray.push(item)` → trigger(obj, 'SET', 'length', newLength)\n *\n * ## Operation Types\n *\n * - **SET**: Property value changed (most common)\n * - **ADD**: New property added (affects iteration)\n * - **DELETE**: Property removed (affects iteration)\n * - **CLEAR**: Collection cleared (affects iteration)\n *\n * ## Iteration Dependencies\n\n * @param target - The reactive object that changed\n * @param type - The type of operation: 'SET' | 'ADD' | 'DELETE' | 'CLEAR'\n * @param key - The property key that changed (optional for CLEAR operations)\n * @param newValue - The new value (optional, used for debugging)\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, items: [1, 2, 3] });\n *\n * effect(() => {\n * console.log(state.count); // Depends on 'count'\n * });\n *\n * effect(() => {\n * console.log(state.items.length); // Depends on 'items' and iteration\n * });\n *\n * // Triggers first effect only\n * state.count = 1; // trigger(state, 'SET', 'count', 1)\n *\n * // Triggers second effect (changes length and iteration)\n * state.items.push(4); // trigger(state.items, 'SET', 'length', 4)\n * // trigger(state.items, 'ADD', '3', 4)\n * ```\n */\nexport function trigger(\n target: object,\n type: string,\n key?: string | symbol | (string | symbol)[],\n newValue?: unknown,\n): void {\n // If this target has no tracked dependencies, nothing to do\n const depsMap = targetMap.get(target);\n if (!depsMap) {\n return;\n }\n\n // Use Set to automatically deduplicate effects\n // This is important for diamond dependencies where an effect might be\n // reached through multiple paths\n const effects = new Set<ReactiveNode>();\n\n // Collect all effects that depend on the specific property that changed\n if (key !== undefined) {\n if (Array.isArray(key)) {\n key.forEach(k => {\n const dep = depsMap.get(k);\n if (dep) {\n dep.forEach(effect => effects.add(effect));\n }\n });\n } else {\n const dep = depsMap.get(key);\n if (dep) {\n dep.forEach(effect => effects.add(effect));\n }\n }\n }\n\n // For operations that affect iteration (ADD/DELETE/CLEAR), we need to trigger\n // effects that iterate over the collection\n\n if (type === 'ADD' || type === 'DELETE' || type === 'CLEAR') {\n // Use different iteration keys for arrays vs objects\n // This allows more precise dependency tracking\n const ITERATE_KEY = Symbol('iterate');\n const ARRAY_ITERATE_KEY = Symbol('arrayIterate');\n\n const iterationKey = Array.isArray(target) ? ARRAY_ITERATE_KEY : ITERATE_KEY;\n const iterationDep = depsMap.get(iterationKey);\n if (iterationDep) {\n iterationDep.forEach(effect => effects.add(effect));\n }\n }\n\n // Process each effect that needs to be notified\n effects.forEach(effect => {\n // In development mode, notify debugging tools about the trigger\n if (__DEV__ && isFunction(effect.onTrigger)) {\n effect.onTrigger({\n effect,\n target,\n type,\n key,\n newValue,\n });\n }\n\n // Effects and Computed values need different handling\n\n if (effect.flag & ReactiveFlags.WATCHING) {\n (effect as Effect).notify?.();\n } else if (effect.flag & ReactiveFlags.MUTABLE) {\n effect.flag |= ReactiveFlags.DIRTY;\n if (effect.subLink) {\n propagate(effect.subLink);\n }\n }\n });\n}\n","import {\n hasChanged,\n hasOwn,\n isArray,\n isMap,\n isObject,\n isSet,\n isStringNumber,\n isWeakMap,\n isWeakSet,\n warn,\n} from '@estjs/shared';\nimport {\n ARRAY_ITERATE_KEY,\n ARRAY_KEY,\n COLLECTION_KEY,\n SignalFlags,\n TriggerOpTypes,\n WEAK_COLLECTION_KEY,\n} from './constants';\nimport { isSignal } from './signal';\nimport { track, trigger } from './link';\n\n// Use WeakMap to cache created reactive proxies to avoid duplicate creation.\nconst reactiveCaches = new WeakMap<object, object>();\n\n/**\n * Return the raw underlying value of a reactive proxy or signal.\n * Recursively unwraps nested reactive objects and arrays.\n *\n * @param value - Reactive or signal value.\n * @returns Raw value without any reactive wrapping.\n */\nexport function toRaw<T>(value: T): T {\n if (!value || !isObject(value)) {\n return value as T;\n }\n\n const raw = (value as any)[SignalFlags.RAW];\n if (raw) {\n // Recursively unwrap in case the raw value is also reactive\n return toRaw(raw);\n }\n\n // Check if it's a signal and unwrap without triggering dependencies\n if (isSignal(value)) {\n return toRaw(value.peek()) as T;\n }\n\n // For all other cases (non-reactive objects, arrays, collections, etc.), return as-is\n // Arrays, Maps, Sets, etc. that aren't reactive proxies are already \"raw\"\n return value as T;\n}\n\nconst arrayInstrumentations = createArrayInstrumentations();\n\n/**\n * Create enhanced versions of array methods that include dependency tracking.\n * Includes search, modification, and iteration methods.\n *\n * @returns An object that maps method keys to enhanced functions.\n */\nfunction createArrayInstrumentations() {\n const instrumentations: Record<string | symbol, Function> = {};\n\n // Search methods: track array iteration and handle reactive object arguments\n ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this) as any[];\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n // First try with the original arguments\n let res = arr[key as keyof typeof arr](...args);\n\n // If lookup fails and we have arguments, try with raw values\n // This handles cases where reactive objects are passed as search values\n if ((res === -1 || res === false) && args.length > 0) {\n const rawArgs = args.map(arg => toRaw(arg));\n res = arr[key as keyof typeof arr](...rawArgs);\n }\n\n return res;\n };\n });\n\n // Search methods that return elements: track iteration and maintain reactivity\n ['find', 'findIndex', 'findLast', 'findLastIndex'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this) as any[];\n const isShallowMode = isShallow(this);\n\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n const res = arr[key as keyof typeof arr](...args);\n\n // For find/findLast, make result reactive if needed\n if ((key === 'find' || key === 'findLast') && isObject(res) && !isShallowMode) {\n return reactiveImpl(res);\n }\n\n return res;\n };\n });\n\n // Mutation methods: trigger array changes\n ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin'].forEach(\n key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n // Call the method using Array.prototype to ensure it works correctly\n const res = Array.prototype[key].apply(arr, args);\n // Trigger change notification for the entire array\n trigger(arr, TriggerOpTypes.SET, ARRAY_KEY);\n // Also trigger ARRAY_ITERATE_KEY since array content/order changed\n trigger(arr, TriggerOpTypes.SET, ARRAY_ITERATE_KEY);\n return res;\n };\n },\n );\n\n // ES2023 methods that return new arrays: track access and maintain reactivity\n ['toReversed', 'toSorted', 'toSpliced'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track iteration access to the entire array\n track(arr, ARRAY_ITERATE_KEY);\n\n // For toSpliced, track all individual elements since they're being accessed\n if (key === 'toSpliced') {\n for (let i = 0, l = arr.length; i < l; i++) {\n track(arr, `${i}`);\n }\n }\n\n // Call the native method\n const res = Array.prototype[key].apply(arr, args);\n\n // Return directly if result is not an array\n if (!Array.isArray(res)) {\n return res;\n }\n\n // Make object elements reactive (deep or shallow based on parent mode)\n return res.map(item => (isObject(item) ? reactiveImpl(item, isShallowMode) : item));\n };\n });\n\n // Methods that return new arrays but don't modify original: track and maintain reactivity\n ['concat', 'slice', 'filter', 'map', 'flatMap', 'flat'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n\n // Track iteration access\n track(arr, ARRAY_ITERATE_KEY);\n\n // Call the native method\n const res = Array.prototype[key].apply(arr, args);\n\n return res;\n };\n });\n\n // Methods that return strings: only track, no reactivity needed\n ['join', 'toString', 'toLocaleString'].forEach(key => {\n instrumentations[key] = function (this: unknown[], ...args: unknown[]) {\n const arr = toRaw(this);\n // Track iteration access\n track(arr, ARRAY_ITERATE_KEY);\n return Array.prototype[key].apply(arr, args);\n };\n });\n\n // Iterator methods: track access and maintain reactivity\n ['values', 'keys', 'entries', Symbol.iterator].forEach(key => {\n instrumentations[key] = function (this: unknown[]) {\n const arr = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track changes to the entire array\n track(arr, ARRAY_KEY);\n\n const rawIterator = key === Symbol.iterator ? arr[Symbol.iterator]() : arr[key]();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Handle entries (returns [index, value] or [value, value] for Set)\n if (Array.isArray(value)) {\n return {\n value: value.map(v => (isObject(v) ? reactiveImpl(v, isShallowMode) : v)),\n done,\n };\n }\n\n // Handle values and keys - make objects reactive\n return {\n value: isObject(value) ? reactiveImpl(value, isShallowMode) : value,\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n };\n });\n\n return instrumentations;\n}\n\n/**\n * Proxy handler for reactive arrays.\n * Intercepts get and set operations to perform dependency tracking and trigger changes.\n *\n * @param shallow - Indicates whether reactivity should be shallow.\n * @returns Object containing array get and set traps.\n */\nconst arrayHandlers = (shallow: boolean) => ({\n get: (target: any, key: string | symbol, receiver: any) => {\n // Intercept operation to get the raw object.\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Intercept operation to check if it's a reactive object.\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n // Intercept operation to check if it's shallow.\n if (key === SignalFlags.IS_SHALLOW) {\n return shallow;\n }\n // If it's an enhanced method, return the enhanced version.\n if (hasOwn(arrayInstrumentations, key)) {\n return arrayInstrumentations[key];\n }\n\n const value = Reflect.get(target, key, receiver);\n\n // If accessing a numeric index, track that index.\n if (isStringNumber(key)) {\n track(target, key);\n }\n // Track general access to the array.\n track(target, ARRAY_KEY);\n\n // If value is object and needs deep reactivity, return its reactive version.\n if (isObject(value) && !shallow) {\n return reactiveImpl(value);\n }\n return value;\n },\n set: (target: any, key: string | symbol, value: unknown, receiver: any) => {\n const oldValue = Reflect.get(target, key, receiver);\n const result = Reflect.set(target, key, value, receiver);\n if (hasChanged(value, oldValue)) {\n // For numeric indices, we need to trigger multiple dependencies\n if (isStringNumber(key)) {\n trigger(target, TriggerOpTypes.SET, [key, ARRAY_ITERATE_KEY, ARRAY_KEY]);\n } else {\n // For non-numeric keys (like 'length'), just trigger that key\n trigger(target, TriggerOpTypes.SET, key);\n }\n }\n return result;\n },\n});\n\nconst shallowArrayHandlers = arrayHandlers(true);\nconst deepArrayHandlers = arrayHandlers(false);\n\n// Proxy handler for Map and Set collections.\nconst collectionHandlers: ProxyHandler<Map<unknown, unknown> | Set<unknown>> = {\n get(target, key: string | symbol) {\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Return enhanced method or original method.\n return Reflect.get(\n hasOwn(collectionInstrumentations, key) ? collectionInstrumentations : target,\n key,\n target,\n );\n },\n};\n\n// Proxy handler for WeakMap and WeakSet collections.\nconst weakCollectionHandlers: ProxyHandler<WeakMap<object, unknown> | WeakSet<object>> = {\n get(target, key: string | symbol) {\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.RAW) {\n return target;\n }\n // Return enhanced method or original method.\n return Reflect.get(\n hasOwn(weakInstrumentations, key) && key in target ? weakInstrumentations : target,\n key,\n target,\n );\n },\n};\n\n// Enhanced versions of Map and Set collection methods.\nconst collectionInstrumentations = {\n get(this: Map<unknown, unknown>, key: unknown) {\n const target = toRaw(this);\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const value = target.get(key);\n\n // For deep reactive mode, wrap object values in reactive proxy\n if (isObject(value) && !isShallow(this)) {\n return reactiveImpl(value);\n }\n\n return value;\n },\n set(this: Map<unknown, unknown>, key: unknown, value: unknown) {\n const target = toRaw(this);\n const hadKey = target.has(key);\n const oldValue = target.get(key);\n\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n target.set(key, rawValue);\n\n // Only trigger if value actually changed or key is new\n if (!hadKey || hasChanged(oldValue, rawValue)) {\n trigger(target, TriggerOpTypes.SET, COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n add(this: Set<unknown>, value: unknown) {\n const target = toRaw(this);\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n const hadValue = target.has(rawValue);\n\n target.add(rawValue);\n\n // Trigger even if value already exists, as this is still a write operation\n // This ensures consistency with reactive tracking\n if (!hadValue) {\n trigger(target, TriggerOpTypes.ADD, COLLECTION_KEY);\n } else {\n // Even if value exists, trigger SET to notify watchers\n trigger(target, TriggerOpTypes.SET, COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n has(key: unknown) {\n const target = toRaw(this);\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n // Try with original key first, then with raw key\n // This handles reactive objects as keys\n const hasKey = target.has(key);\n if (!hasKey && isObject(key)) {\n return target.has(toRaw(key));\n }\n\n return hasKey;\n },\n delete(key: unknown) {\n const target = toRaw(this);\n const hadKey = target.has(key);\n\n // Try deleting with original key first\n let result = target.delete(key);\n\n // If failed and key is an object, try with raw key\n if (!result && isObject(key)) {\n result = target.delete(toRaw(key));\n }\n\n // Only trigger if something was actually deleted\n if (hadKey || result) {\n trigger(target, TriggerOpTypes.DELETE, COLLECTION_KEY);\n }\n\n return result;\n },\n clear() {\n const target = toRaw(this);\n const hadItems = target.size > 0;\n const result = target.clear();\n\n // Only trigger if collection had items\n if (hadItems) {\n trigger(target, TriggerOpTypes.CLEAR, COLLECTION_KEY);\n }\n\n return result;\n },\n forEach(\n this: Map<unknown, unknown> | Set<unknown>,\n callback: (value: unknown, key: unknown, map: Map<unknown, unknown> | Set<unknown>) => void,\n thisArg?: unknown,\n ) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n // Wrap callback to provide reactive values in deep mode\n target.forEach((value: unknown, key: unknown) => {\n const wrappedValue = isShallowMode || !isObject(value) ? value : reactiveImpl(value);\n const wrappedKey = isShallowMode || !isObject(key) ? key : reactiveImpl(key);\n\n callback.call(thisArg, wrappedValue, wrappedKey, this);\n });\n },\n [Symbol.iterator](this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target[Symbol.iterator]();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // In shallow mode, return as-is\n if (isShallowMode) {\n return { value, done };\n }\n\n // For Map entries [key, value], wrap both if they're objects\n if (Array.isArray(value)) {\n return {\n value: value.map(v => (isObject(v) ? reactiveImpl(v) : v)),\n done,\n };\n }\n\n // For Set values, wrap if object\n return {\n value: isObject(value) ? reactiveImpl(value) : value,\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n get size() {\n const target = toRaw(this);\n // Track access to size property\n track(target, COLLECTION_KEY);\n return target.size;\n },\n keys(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.keys();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Wrap keys if they're objects and in deep mode\n return {\n value: isShallowMode || !isObject(value) ? value : reactiveImpl(value),\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n values(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.values();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // Wrap values if they're objects and in deep mode\n return {\n value: isShallowMode || !isObject(value) ? value : reactiveImpl(value),\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n entries(this: Map<unknown, unknown> | Set<unknown>) {\n const target = toRaw(this);\n const isShallowMode = isShallow(this);\n\n // Track access to the collection\n track(target, COLLECTION_KEY);\n\n const rawIterator = target.entries();\n\n return {\n next() {\n const { value, done } = rawIterator.next();\n\n if (done) {\n return { value, done };\n }\n\n // In shallow mode, return as-is\n if (isShallowMode) {\n return { value, done };\n }\n\n // Wrap both key and value if they're objects\n return {\n value: value.map((v: unknown) => (isObject(v) ? reactiveImpl(v) : v)),\n done,\n };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n },\n};\n\n// Enhanced versions of WeakMap and WeakSet collection methods.\nconst weakInstrumentations = {\n get(this: WeakMap<object, unknown>, key: object) {\n const target = toRaw(this);\n // Track access to the weak collection\n track(target, WEAK_COLLECTION_KEY);\n\n // Try with original key first\n let value = target.get(key);\n\n // If not found and key is reactive, try with raw key\n if (value === undefined && isReactive(key)) {\n value = target.get(toRaw(key));\n }\n\n // For deep reactive mode, wrap object values in reactive proxy\n if (isObject(value) && !isShallow(this)) {\n return reactiveImpl(value);\n }\n\n return value;\n },\n set(this: WeakMap<object, unknown>, key: object, value: unknown) {\n const target = toRaw(this);\n const rawKey = toRaw(key);\n const hadKey = target.has(rawKey);\n const oldValue = target.get(rawKey);\n\n // Store raw value to avoid nested reactive wrapping\n const rawValue = toRaw(value);\n target.set(rawKey, rawValue);\n\n // Only trigger if value actually changed or key is new\n if (!hadKey || hasChanged(oldValue, rawValue)) {\n trigger(target, TriggerOpTypes.SET, WEAK_COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n add(this: WeakSet<object>, value: object) {\n const target = toRaw(this);\n const rawValue = toRaw(value);\n const hadValue = target.has(rawValue);\n\n target.add(rawValue);\n\n // Only trigger if value is new\n if (!hadValue) {\n trigger(target, TriggerOpTypes.ADD, WEAK_COLLECTION_KEY);\n }\n\n return this; // Return the reactive proxy, not the raw target\n },\n has(key: object) {\n const target = toRaw(this);\n // Track access to the weak collection\n track(target, WEAK_COLLECTION_KEY);\n\n // Try with original key first\n let hasKey = target.has(key);\n\n // If not found and key is reactive, try with raw key\n if (!hasKey && isReactive(key)) {\n hasKey = target.has(toRaw(key));\n }\n\n return hasKey;\n },\n delete(key: object) {\n const target = toRaw(this);\n const rawKey = toRaw(key);\n const hadKey = target.has(rawKey);\n\n const result = target.delete(rawKey);\n\n // Only trigger if something was actually deleted\n if (hadKey || result) {\n trigger(target, TriggerOpTypes.DELETE, WEAK_COLLECTION_KEY);\n }\n\n return result;\n },\n};\n\n/**\n * Proxy handler for plain objects (non-collection types).\n * Intercepts get, set, and delete operations to manage reactivity.\n *\n * @param shallow - Indicates whether to create shallow reactive proxy.\n * @returns Object containing get, set, and delete traps.\n */\nconst objectHandlers = (shallow: boolean) => ({\n get(target: object, key: string | symbol, receiver: object) {\n if (key === SignalFlags.RAW) {\n return target;\n }\n if (key === SignalFlags.IS_REACTIVE) {\n return true;\n }\n if (key === SignalFlags.IS_SHALLOW) {\n return shallow;\n }\n\n const value = Reflect.get(target, key, receiver);\n\n // Auto-unwrap signals.\n const valueUnwrapped = isSignal(value) ? value.value : value;\n\n // Collect dependencies for accessed properties.\n track(target, key);\n\n // If needed, recursively wrap the value in a reactive proxy.\n if (isObject(valueUnwrapped) && !shallow) {\n return reactiveImpl(valueUnwrapped);\n }\n return valueUnwrapped;\n },\n set: (target: object, key: string | symbol, value: unknown, receiver: object) => {\n const oldValue = Reflect.get(target, key, receiver);\n // When setting value, ensure the raw value is set.\n const result = Reflect.set(target, key, toRaw(value), receiver);\n if (hasChanged(value, oldValue)) {\n trigger(target, TriggerOpTypes.SET, key, value);\n }\n return result;\n },\n deleteProperty: (target: object, key: string | symbol) => {\n const hadKey = hasOwn(target, key);\n const result = Reflect.deleteProperty(target, key);\n if (hadKey && result) {\n trigger(target, TriggerOpTypes.DELETE, key, undefined);\n }\n return result;\n },\n});\n\n/**\n * Create a reactive proxy for the given target object.\n *\n * @param target - The target object to wrap.\n * @param shallow - If true, only top-level properties are reactive.\n * @returns The reactive proxy of the target object.\n */\nexport function reactiveImpl<T extends object>(target: T, shallow = false): T {\n if (!isObject(target)) {\n return target;\n }\n\n // If target object is already reactive, return directly.\n if (isReactive(target)) {\n return target;\n }\n\n // Check if proxy already exists in cache.\n const existingProxy = reactiveCaches.get(target);\n if (existingProxy) {\n return existingProxy as T;\n }\n\n // Choose appropriate handler based on target type.\n let handler;\n if (isArray(target)) {\n handler = shallow ? shallowArrayHandlers : deepArrayHandlers;\n } else if (isSet(target) || isMap(target)) {\n handler = collectionHandlers;\n } else if (isWeakMap(target) || isWeakSet(target)) {\n handler = weakCollectionHandlers;\n } else {\n handler = objectHandlers(shallow);\n }\n\n // Create and cache proxy.\n const proxy = new Proxy(target, handler);\n reactiveCaches.set(target, proxy);\n return proxy;\n}\n\n/**\n * Check if the target object is reactive.\n *\n * @param target - The object to check.\n * @returns True if the object is reactive, false otherwise.\n */\nexport function isReactive(target: unknown): boolean {\n return !!(target && target[SignalFlags.IS_REACTIVE]);\n}\n\n/**\n * Create a reactive proxy for the given target object. If the object is already reactive, return directly.\n *\n * @template T - The type of the object to make reactive\n * @param target - The object to make reactive\n * @returns The reactive proxy of the target object\n *\n * @example\n * ```typescript\n * const state = reactive({ count: 0, nested: { value: 1 } });\n * // Both state.count and state.nested.value are reactive\n * ```\n */\nexport function reactive<T extends object>(target: T): T {\n // Guard: If already reactive, return directly to prevent double wrapping\n if (isReactive(target)) {\n if (__DEV__) {\n warn(\n '[Reactive] Target is already reactive. Returning existing reactive proxy to avoid double wrapping.',\n );\n }\n return target;\n }\n\n // Guard: If target is a signal, warn and unwrap it\n if (isSignal(target)) {\n if (__DEV__) {\n warn(\n '[Reactive] Creating a reactive proxy from a signal is not recommended. ' +\n 'Use the signal directly or access its value property.',\n );\n }\n // Return the signal as-is since signals are already reactive\n return target;\n }\n\n return reactiveImpl(target);\n}\n\n/**\n * Create a shallow reactive proxy for the given object. Only root-level properties are reactive.\n *\n * @template T - The type of the object to make shallow reactive\n * @param target - The object to make shallow reactive\n * @returns The shallow reactive proxy of the object\n *\n * @example\n * ```typescript\n * const state = shallowReactive({ count: 0, nested: { value: 1 } });\n * // Only state.count is reactive, not state.nested.value\n * ```\n */\nexport function shallowReactive<T extends object>(target: T): T {\n // Guard: If already reactive, check if it's shallow\n if (isReactive(target)) {\n if (__DEV__) {\n if (isShallow(target)) {\n warn(\n '[ShallowReactive] Target is already a shallow reactive proxy. ' +\n 'Returning existing proxy to avoid double wrapping.',\n );\n } else {\n warn(\n '[ShallowReactive] Target is already a deep reactive proxy. ' +\n 'Cannot convert deep reactive to shallow reactive. Returning existing proxy.',\n );\n }\n }\n return target;\n }\n\n // Guard: If target is a signal, warn and unwrap it\n if (isSignal(target)) {\n if (__DEV__) {\n warn(\n '[ShallowReactive] Creating a reactive proxy from a signal is not recommended. ' +\n 'Use the signal directly or access its value property.',\n );\n }\n // Return the signal as-is since signals are already reactive\n return target;\n }\n\n return reactiveImpl(target, true);\n}\n\n/**\n * Check if the target object is a shallow reactive proxy.\n *\n * @param value - The object to check.\n * @returns True if the object is shallow reactive, false otherwise.\n */\nexport function isShallow(value: unknown): boolean {\n return !!(value && value[SignalFlags.IS_SHALLOW]);\n}\n\n/**\n * Return a reactive proxy for the given value (if possible).\n * If the given value is not an object, return the original value itself.\n *\n * @param value - The value that needs a reactive proxy created for it.\n */\nexport const toReactive = <T extends unknown>(value: T): T =>\n isObject(value) ? reactive(value) : value;\n\n/**\n * Type alias representing a reactive object.\n *\n * @template T - The type of the original object.\n */\nexport type Reactive<T extends object> = T;\n","// Import shared utility functions for checking value changes, object types, and sending warnings in development mode.\nimport { hasChanged, isObject, warn } from '@estjs/shared';\nimport { activeSub, linkReactiveNode, shallowPropagate } from './link';\nimport { ReactiveFlags, SignalFlags } from './constants';\nimport { reactive, shallowReactive, toRaw } from './reactive';\nimport { propagate } from './propagation';\nimport type { Link, ReactiveNode } from './link';\n\n/**\n * Signal is a reactive primitive that holds a value and notifies subscribers when the value changes.\n * It provides methods for reading, writing, and observing value changes.\n *\n * @template T - The type of value held by the Signal\n */\nexport interface Signal<T> {\n /**\n * The current value of the Signal. Reading this property tracks dependencies,\n * and writing to it notifies subscribers of changes.\n */\n value: T;\n\n /**\n * Get the current value without establishing a dependency relationship.\n * Useful when you need to read the value without tracking dependencies.\n *\n * @returns The current value\n */\n peek(): T;\n\n /**\n * Set a new value without notifying subscribers.\n * Used for batching multiple updates together.\n *\n * @param value - The new value to set\n */\n set(value: T): void;\n\n /**\n * Update the value using a function that receives the current value.\n * This is an atomic operation that only notifies subscribers once.\n *\n * @param updater - A function that receives the current value and returns the new value\n */\n update(updater: (prev: T) => T): void;\n}\n\n/**\n * A more precise type for the value held by a signal.\n * This type helps TypeScript understand the type of the unwrapped value.\n *\n * @template T - The type of value held by the signal\n */\nexport type SignalValue<T> = T extends Signal<infer V> ? V : never;\n/**\n * Extract the value type from a Signal\n *\n * @template T - The Signal type\n *\n * @example\n * ```typescript\n * import { signal, type SignalType } from '@estjs/signals';\n *\n * const count = signal(0);\n * type CountValue = SignalType<typeof count>; // number\n * ```\n */\nexport type SignalType<T> = T extends Signal<infer V> ? V : never;\n\n/**\n * Internal implementation of the Signal interface.\n * This class manages reactive state and handles dependency tracking.\n\n * @template T - The type of value held by the Signal\n */\nexport class SignalImpl<T> implements ReactiveNode {\n // Implement ReactiveNode interface\n depLink?: Link | undefined;\n subLink?: Link | undefined;\n depLinkTail?: Link | undefined;\n subLinkTail?: Link | undefined;\n flag: ReactiveFlags = ReactiveFlags.MUTABLE; // Initial state is \"mutable\"\n\n private _oldValue: T; // Store old value for comparison\n private _rawValue: T; // Store raw (non-proxied) new value\n\n _value: T; // Store current value (may be a reactive proxy)\n\n private readonly [SignalFlags.IS_SHALLOW]: boolean; // Mark whether it's shallow reactive\n\n // @ts-ignore\n private readonly [SignalFlags.IS_SIGNAL] = true as const; // Mark as Signal\n\n /**\n * Create a new Signal with the given initial value.\n *\n * @param value - Initial value\n * @param shallow - Whether only the top level should be reactive\n */\n constructor(value?: T, shallow = false) {\n this._oldValue = this._rawValue = value as T;\n // In shallow mode, wrap objects/arrays/collections in shallow reactive proxy\n // In deep mode, wrap objects in deep reactive proxy\n if (shallow) {\n this._value = (isObject(value) ? shallowReactive(value as object) : value) as T;\n } else {\n this._value = (isObject(value) ? reactive(value as object) : value) as T;\n }\n this[SignalFlags.IS_SHALLOW] = shallow;\n }\n\n // dep getter, returns itself for dependency collection\n get dep(): this {\n return this;\n }\n\n get value(): T {\n const sub = activeSub;\n if (sub) {\n linkReactiveNode(this, sub);\n }\n\n if (this.flag & ReactiveFlags.DIRTY && this.shouldUpdate()) {\n // Cache subLink locally to avoid repeated property access\n const subs = this.subLink;\n if (subs) {\n shallowPropagate(subs);\n }\n }\n\n return this._value;\n }\n\n // value setter, triggers update when value changes\n set value(value: T) {\n // If the new value is another signal, unwrap it\n if (isSignal(value)) {\n if (__DEV__) {\n warn(\n 'Setting a signal value to another signal is not recommended. ' +\n 'The value will be unwrapped automatically.',\n );\n }\n value = (value as Signal<T>).peek() as T;\n }\n\n // Extract raw value\n value = toRaw(value);\n\n if (!hasChanged(this._rawValue, value)) {\n return;\n }\n\n // Mark as dirty using bitwise OR\n this.flag |= ReactiveFlags.DIRTY;\n this._rawValue = value;\n\n // Cache shallow flag locally to avoid repeated property access\n const shallow = this[SignalFlags.IS_SHALLOW];\n\n // In shallow mode, wrap in shallow reactive proxy; in deep mode, wrap in deep reactive proxy\n if (shallow) {\n this._value = (isObject(value) ? shallowReactive(value as object) : value) as T;\n } else {\n this._value = (isObject(value) ? reactive(value as object) : value) as T;\n }\n\n // Cache subLink locally to avoid repeated property access\n const subs = this.subLink;\n if (subs) {\n propagate(subs); // Propagate notification\n }\n }\n\n // Check if the value should be update\n shouldUpdate(): boolean {\n // Clear \"dirty\" flag using bitwise AND with NOT\n this.flag &= ~ReactiveFlags.DIRTY;\n // Compare old value with new raw value, and update old value\n return hasChanged(this._oldValue, (this._oldValue = this._rawValue));\n }\n\n // Get current value without triggering dependency tracking\n peek(): T {\n return this._value;\n }\n\n // set method is an alias for the value setter\n set(value: T): void {\n this.value = value;\n }\n\n // Update value using an updater function\n update(updater: (prev: T) => T): void {\n const nextValue = updater(this.peek());\n // Handle case where updater function returns a signal\n if (isSignal(nextValue)) {\n if (__DEV__) {\n warn(\n 'Returning a signal from an update function is not recommended. The value will be unwrapped.',\n );\n }\n this.value = nextValue.peek() as T;\n } else {\n this.value = nextValue;\n }\n }\n}\n\n/**\n * Create a new signal with the given initial value.\n * The signal will track all nested properties of object values.\n *\n * @template T - The type of value to store in the signal\n * @param value - Initial value (defaults to undefined)\n * @returns A new signal instance\n *\n * @example\n * ```typescript\n * const count = signal(0);\n * const user = signal({ name: 'John' });\n * const empty = signal(); // undefined\n * ```\n */\nexport function signal<T>(value?: T): Signal<T> {\n // If the value is already a signal, return it directly to avoid duplicate creation\n if (isSignal(value)) {\n if (__DEV__) {\n warn(\n 'Creating a signal with another signal is not recommended. The value will be unwrapped.',\n );\n }\n return value as Signal<T>;\n }\n return new SignalImpl(value);\n}\n\n/**\n * Create a new shallow signal with the given initial value.\n * Only the top-level properties of object values are reactive.\n *\n * @template T - The type of value to store in the signal\n * @param value - Initial value (defaults to undefined)\n * @returns A new shallow signal instance\n *\n * @example\n * ```typescript\n * const state = shallowSignal({ nested: { value: 1 } });\n * // Only state.nested is reactive, not state.nested.value\n * ```\n */\nexport function shallowSignal<T>(value?: T): Signal<T> {\n // If the value is a signal, extract its value\n if (isSignal(value)) {\n if (__DEV__) {\n warn(\n 'Creating a shallow signal with another signal is not recommended. The value will be unwrapped.',\n );\n }\n value = value.peek() as T;\n }\n return new SignalImpl(value, true);\n}\n\n/**\n * Type guard to check if a value is a Signal instance.\n *\n * @template T - The type of value held by the signal\n * @param value - The value to check\n * @returns true if the value is a Signal instance\n */\nexport function isSignal<T>(value: unknown): value is Signal<T> {\n return !!value && !!value[SignalFlags.IS_SIGNAL];\n}\n","import { error, warn } from '@estjs/shared';\n\n/**\n * Represents a task (job) that can be scheduled for execution\n */\nexport type Job = () => void;\n\n/**\n * Represents a callback function that should be executed before the main task queue\n */\nexport type PreFlushCallback = () => void;\n\n/**\n * Represents the possible flush timing strategies for effects\n *\n * - 'pre': Execute before the main queue (useful for component updates)\n * - 'post': Execute after the main queue (default behavior)\n * - 'sync': Execute immediately and synchronously (use sparingly)\n */\nexport type FlushTiming = 'pre' | 'post' | 'sync';\n\n// Main task queue storing jobs waiting to be executed\n// Using Set for automatic deduplication\nconst queue: Set<Job> = new Set();\n\n// Pre-flush callback queue, cleared before main task queue execution\n// Using Set for automatic deduplication\nconst activePreFlushCbs: Set<PreFlushCallback> = new Set();\n\n// Resolved Promise used to schedule tasks into the microtask queue\nconst p = Promise.resolve();\n\n// Flag to prevent duplicate flush scheduling, ensuring only one schedule per event loop\nlet isFlushPending = false;\n\n/**\n * Schedules a function to be executed in the next microtask\n *\n * If no function is provided, returns a Promise that resolves in the next microtask.\n * This is useful for waiting until the DOM is update or deferring execution.\n *\n * @param fn - Optional function to execute\n * @returns A Promise that resolves after the function execution\n */\nexport function nextTick(fn?: () => void): Promise<void> {\n if (fn) {\n return new Promise((resolve, reject) => {\n queueMicrotask(() => {\n try {\n fn();\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n }\n return p;\n}\n\n/**\n * Adds a job to the main queue and ensures it will be executed\n *\n * Jobs are automatically deduplicated - the same job reference won't be added multiple times.\n * This is useful for batching updates and avoiding redundant work.\n * @param job - The job to enqueue\n */\nexport function queueJob(job: Job): void {\n queue.add(job); // Set automatically deduplicates\n queueFlush();\n}\n\n/**\n * Schedules a queue flush in the next microtask if one hasn't been scheduled yet\n *\n * @internal\n */\nfunction queueFlush(): void {\n if (!isFlushPending) {\n isFlushPending = true;\n nextTick(flushJobs);\n }\n}\n\n/**\n * Adds a callback to be executed before the main queue processing\n *\n * Pre-flush callbacks are useful for setup work that needs to run before effects,\n * such as computing derived values or preparing state.\n * @param cb - The callback to execute before the main queue\n */\nexport function queuePreFlushCb(cb: PreFlushCallback): void {\n activePreFlushCbs.add(cb); // Set automatically deduplicates\n queueFlush();\n}\n\n/**\n * Executes all enqueued jobs and pre-flush callbacks\n *\n * This function runs in a microtask and processes the entire queue.\n * Jobs are executed in order, with error handling to prevent one failing job from blocking others.\n *\n * ## Cleanup Process\n *\n * 1. Reset flush pending flag\n * 2. Execute pre-flush callbacks and clear their queue\n * 3. Execute main jobs and clear their queue\n * 4. Handle jobs queued during flush\n *\n * ## Memory Management\n *\n * - Jobs queued during flush are executed in the same cycle\n * - Error handling prevents one failing job from blocking others\n * - All temporary state is cleared after execution\n *\n * @internal\n */\nexport function flushJobs(): void {\n isFlushPending = false;\n\n // Execute pre-flush callbacks first\n flushPreFlushCbs();\n\n // Process jobs until queue is empty\n // This handles jobs queued during flush\n while (queue.size > 0) {\n // Convert Set to array and clear the Set\n const jobs = Array.from(queue);\n queue.clear();\n\n // Execute all jobs with error handling\n for (const job of jobs) {\n try {\n job();\n } catch (_error) {\n if (__DEV__) {\n error('Error executing queued job:', _error);\n }\n }\n }\n }\n}\n\n/**\n * Executes all pre-flush callbacks\n *\n * Pre-flush callbacks are executed before the main job queue.\n * This is useful for setup work that needs to run before effects.\n *\n * ## Cleanup Process\n *\n * 1. Copy callbacks to array\n * 2. Clear the callback queue immediately\n * 3. Execute all callbacks with error handling\n *\n * @internal\n */\nfunction flushPreFlushCbs(): void {\n // Convert Set to array and clear the Set immediately\n // This allows new callbacks to be queued during execution\n const callbacks = Array.from(activePreFlushCbs);\n activePreFlushCbs.clear();\n\n // Execute all callbacks with error handling\n for (const callback of callbacks) {\n try {\n callback();\n } catch (_error) {\n if (__DEV__) {\n error('Error executing pre-flush callback:', _error);\n }\n }\n }\n}\n\n/**\n * Creates a scheduler function for an effect based on the specified flush timing\n *\n * This is used internally by the effect system to control when effects execute:\n * - 'sync': Immediate execution (blocking)\n * - 'pre': Before main queue (setup phase)\n * - 'post': After main queue (cleanup/side effects)\n * @param effect - The effect function to schedule\n * @param flush - When to execute the effect\n * @returns A scheduler function that will run the effect at the appropriate time\n */\nexport function createScheduler(\n effect: () => void,\n flush: FlushTiming,\n): () => void | Promise<void> {\n switch (flush) {\n case 'sync':\n return () => effect();\n case 'pre':\n return () => queuePreFlushCb(effect);\n case 'post':\n return () => queueJob(effect);\n default:\n if (__DEV__) {\n warn(`Invalid flush timing: ${flush}. Defaulting to 'post'.`);\n }\n return () => queueJob(effect);\n }\n}\n","import { error, warn } from '@estjs/shared';\nimport { flushJobs } from './scheduler';\n/**\n * Batch update depth\n *\n * Supports nested batch calls.\n * Effects are only flushed when the outermost batch ends.\n */\nlet batchDepth = 0;\n\n/**\n * Execute a function in batch mode\n *\n * Executes the function in a batch context, where all Signal changes\n * are deferred and processed together after the batch ends.\n *\n * @param fn - The function to execute in batch mode\n * @returns The return value of the function\n *\n * @example\n * ```typescript\n * const x = signal(0);\n * const y = signal(0);\n *\n * effect(() => {\n * console.log('Sum:', x.value + y.value);\n * });\n *\n * // Without batch - Effect executes 2 times\n * x.value = 1; // Effect executes\n * y.value = 2; // Effect executes\n *\n * // With batch - Effect executes only 1 time\n * batch(() => {\n * x.value = 10;\n * y.value = 20;\n * }); // Effect executes once\n * ```\n */\nexport function batch<T>(fn: () => T): T {\n startBatch();\n try {\n return fn();\n } finally {\n endBatch();\n }\n}\n\n/**\n * Start batch update\n *\n * Increases batch depth.\n * During batch, Effects won't execute immediately.\n */\nexport function startBatch(): void {\n batchDepth++;\n}\n\n/**\n * End batch update\n *\n * Decreases batch depth.\n * When depth reaches zero, flush all queued Effects and clean up.\n *\n * ## Cleanup Process\n *\n * When the outermost batch ends:\n * 1. Flush all queued jobs (effects execute)\n * 2. Job queue is automatically cleared by flushJobs()\n * 3. Temporary flags (QUEUED, DIRTY) are cleared by effect execution\n *\n */\nexport function endBatch(): void {\n if (__DEV__ && batchDepth === 0) {\n warn(\n '[Batch] endBatch() called without matching startBatch(). ' +\n 'This may indicate unbalanced batch calls in your code.',\n );\n return;\n }\n\n // Decrement and check in one operation\n if (--batchDepth === 0) {\n // Outermost batch ended, execute all Effects\n // flushJobs() will:\n // 1. Execute all queued effects\n // 2. Clear the job queue (Set.clear())\n // 3. Reset the flush pending flag\n flushJobs();\n\n // Development mode verification\n if (__DEV__ && batchDepth !== 0) {\n error(\n '[Batch] Batch depth is not zero after endBatch(). ' +\n `Current depth: ${batchDepth}. This indicates a bug in batch management.`,\n );\n }\n }\n}\n\n/**\n * Check if currently in batch update mode\n *\n * @returns true if currently in batch\n */\nexport function isBatching(): boolean {\n return batchDepth > 0;\n}\n\n/**\n * Get current batch depth\n *\n * Mainly used for debugging.\n *\n * @returns Current batch nesting depth\n */\nexport function getBatchDepth(): number {\n return batchDepth;\n}\n","import { error, isFunction, warn } from '@estjs/shared';\nimport { EffectFlags, ReactiveFlags, SignalFlags } from './constants';\nimport { checkDirty, endTracking, startTracking, unlinkReactiveNode } from './link';\nimport { isBatching } from './batch';\nimport { createScheduler, queueJob } from './scheduler';\nimport type { Computed } from './computed';\nimport type { Signal } from './signal';\nimport type { Reactive } from './reactive';\nimport type { DebuggerEvent, Link, ReactiveNode } from './link';\nimport type { FlushTiming } from './scheduler';\n\n/**\n * Unwrap a Signal, Computed, or Reactive type to get the underlying value type\n *\n * @template T - The wrapped type\n *\n * @example\n * ```typescript\n * import type { Signal, Computed, Reactive, Unwrap } from '@estjs/signals';\n *\n * type Count = Unwrap<Signal<number>>; // number\n * type User = Unwrap<Reactive<{ name: string }>>; // { name: string }\n * type Double = Unwrap<Computed<number>>; // number\n * ```\n */\nexport type Unwrap<T> =\n T extends Signal<infer V>\n ? V\n : T extends Computed<infer V>\n ? V\n : T extends Reactive<infer V extends object>\n ? V\n : T;\n\n/**\n * Effect function type\n */\nexport type EffectFunction<T = any> = () => T;\n\n/**\n * Effect scheduler function type\n */\nexport type EffectScheduler = (effect: EffectImpl) => void;\n\n/**\n * Effect options configuration\n */\nexport interface EffectOptions {\n /**\n * Custom scheduler for controlling when the effect runs\n * Can be a function or a timing string ('sync', 'pre', 'post')\n */\n scheduler?: EffectScheduler | FlushTiming;\n\n /**\n * Alias for scheduler - controls when the effect runs\n * Can be 'sync', 'pre', or 'post'\n */\n flush?: FlushTiming;\n\n /**\n * Callback invoked when the effect is stopped\n * Useful for cleanup operations\n */\n onStop?: () => void;\n\n /**\n * Debug callback invoked when a dependency is tracked\n * Only called in development mode\n *\n * @param event - Information about the tracked dependency\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrack(event) {\n * console.log('Tracked:', event.type, event.key);\n * }\n * });\n * ```\n */\n onTrack?: (event: DebuggerEvent) => void;\n\n /**\n * Debug callback invoked when the effect is triggered by a dependency change\n * Only called in development mode\n *\n * @param event - Information about what triggered the effect\n *\n * @example\n * ```typescript\n * effect(() => {\n * console.log(signal.value);\n * }, {\n * onTrigger(event) {\n * console.log('Triggered by:', event.type, event.key, event.newValue);\n * }\n * });\n * ```\n */\n onTrigger?: (event: DebuggerEvent) => void;\n}\n\n/**\n * Effect runner function with attached effect instance\n */\nexport interface EffectRunner<T = any> {\n (): T;\n effect: EffectImpl<T>;\n stop: () => void;\n}\n\n/**\n * Effect implementation class\n *\n * Implements the ReactiveNode interface, acting as a subscriber in the reactive system.\n *\n * Core features:\n * - Automatically tracks dependent reactive values\n * - Automatically re-executes when dependencies change\n * - Supports custom scheduling strategies\n * - Complete lifecycle management\n *\n * @template T - The return type of the effect function\n */\nexport class EffectImpl<T = any> implements ReactiveNode {\n // ===== ReactiveNode interface implementation =====\n depLink?: Link;\n subLink?: Link;\n depLinkTail?: Link;\n subLinkTail?: Link;\n flag: ReactiveFlags = ReactiveFlags.WATCHING | ReactiveFlags.DIRTY;\n\n // @ts-ignore\n private readonly [SignalFlags.IS_EFFECT] = true as const;\n\n // ===== Core properties =====\n readonly fn: EffectFunction<T>;\n readonly scheduler?: EffectScheduler | FlushTiming;\n readonly onStop?: () => void;\n readonly onTrack?: (event: DebuggerEvent) => void;\n readonly onTrigger?: (event: DebuggerEvent) => void;\n readonly flash?: 'sync' | 'pre' | 'post';\n\n // ===== State management =====\n private _active = true;\n\n /**\n * Create an Effect instance\n *\n * @param fn - The effect function\n * @param options - Configuration options\n */\n constructor(fn: EffectFunction<T>, options?: EffectOptions) {\n this.fn = fn;\n\n if (options) {\n // Use flush as an alias for scheduler if provided\n this.scheduler = options.flush || options.scheduler;\n this.onStop = options.onStop;\n this.onTrack = options.onTrack;\n this.onTrigger = options.onTrigger;\n }\n }\n\n /**\n * Check if the Effect is active\n */\n get active(): boolean {\n return this._active;\n }\n\n /**\n * Check if the Effect is dirty (needs re-execution)\n\n */\n get dirty(): boolean {\n const flags = this.flag;\n\n // Explicitly marked as dirty\n if (flags & ReactiveFlags.DIRTY) {\n return true;\n }\n\n // Pending state, need to check dependencies\n if (flags & ReactiveFlags.PENDING) {\n if (this.depLink && checkDirty(this.depLink, this)) {\n // Use bitwise operations to set DIRTY and clear PENDING in one operation\n this.flag = (flags & ~ReactiveFlags.PENDING) | ReactiveFlags.DIRTY;\n return true;\n }\n // Dependencies unchanged, clear pending flag using cached flags\n this.flag = flags & ~ReactiveFlags.PENDING;\n }\n\n return false;\n }\n\n /**\n * Pause Effect execution\n *\n * When an effect is paused:\n * - It stops responding to dependency changes\n * - Notifications are ignored (see notify method)\n * - DIRTY and PENDING flags are still set when dependencies change\n * - The effect remains active and maintains its dependency links\n *\n * Use cases:\n * - Temporarily disable effects during bulk updates\n * - Prevent effects from running during initialization\n * - Control when side effects should execute\n *\n * @example\n * ```typescript\n * const count = signal(0);\n * const runner = effect(() => console.log(count.value));\n *\n * runner.effect.pause();\n * count.value = 1; // Effect won't run\n * count.value = 2; // Effect won't run\n * runner.effect.resume(); // Effect runs once with latest value\n * ```\n */\n pause(): void {\n this.flag |= EffectFlags.PAUSED;\n }\n\n /**\n * Resume Effect execution\n *\n * When an effect is resumed:\n * - The PAUSED flag is cleared\n * - If dependencies changed during pause (DIRTY or PENDING flags set),\n * the effect executes immediately via notify()\n * - If no changes occurred, the effect simply becomes active again\n *\n * State management:\n * - Clears PAUSED flag atomically\n * - Checks for accumulated DIRTY/PENDING flags\n * - Triggers execution if needed\n *\n * @example\n * ```typescript\n * const count = signal(0);\n * const runner = effect(() => console.log(count.value));\n *\n * runner.effect.pause();\n * count.value = 1; // Queued\n * count.value = 2; // Queued\n * runner.effect.resume(); // Executes once with count.value = 2\n * ```\n */\n resume(): void {\n const flags = this.flag;\n const nextFlags = flags & ~EffectFlags.PAUSED;\n\n this.flag = nextFlags;\n\n // Check if there are pending updates that accumulated during pause\n const wasDirty = (nextFlags & ReactiveFlags.DIRTY) !== 0;\n const wasPending = (nextFlags & ReactiveFlags.PENDING) !== 0;\n\n if (wasDirty || wasPending) {\n this.notify();\n }\n }\n\n /**\n * Execute the Effect function\n *\n * Core execution flow:\n * 1. Check if active\n * 2. Clear dirty flag\n * 3. Start tracking dependencies\n * 4. Execute user function\n * 5. End tracking, clean up stale dependencies\n\n * @returns The return value of the effect function\n */\n run(): T {\n // Already stopped, execute without tracking\n if (!this._active) {\n return this.fn();\n }\n\n // Cache flags and use bitwise operations to update multiple flags efficiently\n const flags = this.flag;\n this.flag = (flags & ~ReactiveFlags.DIRTY) | EffectFlags.STOP;\n\n // Start dependency tracking\n const prevSub = startTracking(this);\n\n try {\n // Execute the effect function\n return this.fn();\n } catch (error) {\n // Execution error, restore dirty flag\n this.flag |= ReactiveFlags.DIRTY;\n\n throw error;\n } finally {\n // Clear running flag\n this.flag &= ~EffectFlags.STOP;\n // End tracking, clean up stale dependencies\n endTracking(this, prevSub);\n }\n }\n\n private _job?: () => void;\n\n /**\n * Get or create the job function for this effect\n */\n private getJob(): () => void {\n if (!this._job) {\n this._job = () => this.run();\n }\n return this._job;\n }\n\n /**\n * Notify that the Effect needs to execute\n *\n * Called by dependent reactive values.\n * Decides whether to execute immediately or defer based on scheduling strategy.\n */\n notify(): void {\n // Cache flags for efficient checking\n const flags = this.flag;\n\n // Early exit: check multiple conditions using bitwise operations\n // Already stopped, paused, running, or dirty - ignore notification\n if (!this._active || flags & (EffectFlags.PAUSED | EffectFlags.STOP | ReactiveFlags.DIRTY)) {\n return;\n }\n\n // Mark as dirty\n this.flag = flags | ReactiveFlags.DIRTY;\n\n // Trigger callback\n if (__DEV__ && this.onTrigger) {\n this.onTrigger({\n effect: this,\n target: {},\n type: 'set',\n });\n }\n\n // Use scheduler or decide execution method based on batch state\n if (this.scheduler) {\n if (isFunction(this.scheduler)) {\n this.scheduler(this);\n } else {\n // Create and immediately call the scheduler for flush timing\n const schedulerFn = createScheduler(() => this.run(), this.scheduler);\n schedulerFn();\n }\n } else if (isBatching()) {\n // When in batch, queue for execution\n queueJob(this.getJob());\n } else {\n // In normal case, execute immediately and synchronously\n this.run();\n }\n }\n\n /**\n * Stop the Effect\n *\n * After stopping:\n * - No longer responds to dependency changes\n * - Disconnects all dependency links\n * - Clears cached job function\n * - Calls onStop callback\n * - Verifies complete cleanup in development mode\n */\n stop(): void {\n if (!this._active) {\n if (__DEV__) {\n warn('[Effect] Attempting to stop an already stopped effect.');\n }\n return;\n }\n\n this._active = false;\n\n // Disconnect all dependency links\n // This removes this effect from all signals/computed it depends on\n let dep = this.depLink;\n while (dep) {\n dep = unlinkReactiveNode(dep, this);\n }\n\n // Disconnect all subscription links\n // This removes any subscribers that depend on this effect (rare but possible)\n let sub = this.subLink;\n while (sub) {\n sub = unlinkReactiveNode(sub);\n }\n\n // Clear cached job function to free memory\n this._job = undefined;\n\n // Clear link tail pointers to ensure no dangling references\n this.depLinkTail = undefined;\n this.subLinkTail = undefined;\n\n // Verify cleanup in development mode\n if (__DEV__) {\n // Verify all links are properly cleared\n if (this.depLink) {\n error(\n '[Effect] Cleanup verification failed: depLink not cleared. ' +\n 'This indicates a memory leak in the dependency tracking system.',\n );\n }\n if (this.subLink) {\n error(\n '[Effect] Cleanup verification failed: subLink not cleared. ' +\n 'This indicates a memory leak in the subscription system.',\n );\n }\n }\n\n // Call stop callback\n if (this.onStop) {\n this.onStop();\n }\n }\n}\n\n/**\n * Create and immediately execute an Effect\n *\n * @param fn - The effect function\n * @param options - Configuration options\n * @returns Effect runner\n *\n * @example\n * ```typescript\n * const count = signal(0);\n *\n * // Basic usage\n * const runner = effect(() => {\n * console.log('Count:', count.value);\n * });\n *\n * count.value = 1; // Automatically executes, prints 'Count: 1'\n *\n * // Manual execution\n * runner();\n *\n * // Stop\n * runner.effect.stop();\n *\n * // Custom scheduling\n * effect(() => {\n * console.log(count.value);\n * }, {\n * scheduler: (eff) => {\n * setTimeout(() => eff.run(), 100);\n * }\n * });\n * ```\n */\nexport function effect<T = any>(fn: EffectFunction<T>, options?: EffectOptions): EffectRunner<T> {\n const effectInstance = new EffectImpl(fn, options);\n\n try {\n // Execute immediately once\n effectInstance.run();\n } catch (_error) {\n // First execution failed, stop Effect and rethrow\n effectInstance.stop();\n if (__DEV__) {\n error(\n '[Effect] Effect failed during initial execution and has been stopped. ' +\n 'Fix the error in your effect function.',\n _error,\n );\n }\n throw _error;\n }\n\n // Create runner function\n const runner: any = () => effectInstance.run();\n runner.effect = effectInstance;\n runner.stop = () => effectInstance.stop();\n\n return runner as EffectRunner<T>;\n}\n\n/**\n * Stop Effect execution\n *\n * @param runner - The effect runner\n */\nexport function stop(runner: EffectRunner): void {\n runner.effect.stop();\n}\n\n/**\n * Type guard - Check if value is an Effect\n *\n * @param value - The value to check\n * @returns true if value is an Effect\n */\nexport function isEffect(value: any): value is EffectImpl {\n return !!(value && value[SignalFlags.IS_EFFECT]);\n}\n\n// ==================== Memoized Effect ====================\n\n/**\n * Memoized effect function type\n *\n * @template T - State type\n * @param prevState - State from previous execution\n * @returns New state\n */\nexport type MemoEffectFn<T> = (prevState: T) => T;\n\n/**\n * Create a memoized Effect\n *\n * A memoized effect remembers the return value from the previous execution\n * and passes it as a parameter on the next execution.\n *\n * Use cases:\n * - Incremental DOM updates\n * - Avoiding duplicate operations\n * - State persistence\n * - Difference detection\n *\n * @param fn - The memoized function\n * @param initialState - Initial state\n * @param options - Configuration options\n * @returns Effect runner\n *\n * @example\n * ```typescript\n * const width = signal(100);\n *\n * // Only update DOM when width changes\n * memoEffect(prev => {\n * const current = width.value;\n *\n * if (current !== prev.width) {\n * element.style.width = `${current}px`;\n * prev.width = current;\n * }\n *\n * return prev;\n * }, { width: 0 });\n * ```\n */\nexport function memoEffect<T>(\n fn: MemoEffectFn<T>,\n initialState: T,\n options?: EffectOptions,\n): EffectRunner<void> {\n let currentState = initialState;\n\n const effectFn = () => {\n // Pass current state each time\n // fn may modify the passed object, so the return value is the update state\n const result = fn(currentState);\n currentState = result;\n };\n\n return effect(effectFn, options);\n}\n","import { error, hasChanged, isFunction, isPlainObject, warn } from '@estjs/shared';\nimport { ReactiveFlags, SignalFlags } from './constants';\nimport { activeSub, checkDirty, endTracking, linkReactiveNode, startTracking } from './link';\nimport { shallowPropagate } from './propagation';\nimport type { DebuggerEvent, Link, ReactiveNode } from './link';\n\n/**\n * Computed getter function type\n */\nexport type ComputedGetter<T> = () => T;\n\n/**\n * Computed setter function type\n */\nexport type ComputedSetter<T> = (value: T) => void;\n\n/**\n * Computed options configuration\n */\nexport interface ComputedOptions<T> {\n /** Getter function to compute the value */\n get: ComputedGetter<T>;\n\n /** Optional setter function to make the computed writable */\n set?: ComputedSetter<T>;\n\n /**\n * Debug callback invoked when a dependency is tracked\n * Only called in development mode\n *\n * @param event - Information about the tracked dependency\n */\n onTrack?: (event: DebuggerEvent) => void;\n\n /**\n * Debug callback invoked when the computed is triggered by a dependency change\n * Only called in development mode\n *\n * @param event - Information about what triggered the recomputation\n */\n onTrigger?: (event: DebuggerEvent) => void;\n}\n\n/**\n * Computed interface\n */\nexport interface Computed<T> {\n readonly value: T;\n peek(): T;\n}\n/**\n * Extract the value type from a Computed\n *\n * @template T - The Computed type\n *\n * @example\n * ```typescript\n * import { computed, type ComputedType } from '@estjs/signals';\n *\n * const doubled = computed(() => count.value * 2);\n * type DoubledValue = ComputedType<typeof doubled>; // number\n * ```\n */\nexport type ComputedType<T> = T extends Computed<infer V> ? V : never;\n\n/**\n * Sentinel symbol used to represent \"no value\" state in computed\n * Using a Symbol ensures it cannot conflict with any actual computed value\n */\nconst NO_VALUE = Symbol('computed-no-value');\n\n/**\n * Computed implementation class\n *\n * Implements both Computed and ReactiveNode interfaces.\n * Features:\n * - Lazy evaluation: only computes when accessed\n * - Smart caching: returns cached value when dependencies haven't changed\n * - Automatic tracking: automatically tracks dependencies during computation\n *\n * @template T - The type of the computed value\n */\nexport class ComputedImpl<T = any> implements Computed<T>, ReactiveNode {\n // ===== ReactiveNode interface implementation =====\n depLink?: Link;\n subLink?: Link;\n depLinkTail?: Link;\n subLinkTail?: Link;\n flag: ReactiveFlags = ReactiveFlags.MUTABLE | ReactiveFlags.DIRTY;\n\n //@ts-ignore\n private readonly [SignalFlags.IS_COMPUTED] = true as const;\n\n // ===== Core properties =====\n readonly getter: ComputedGetter<T>;\n readonly setter?: ComputedSetter<T>;\n\n // ===== Debug hooks =====\n readonly onTrack?: (event: DebuggerEvent) => void;\n readonly onTrigger?: (event: DebuggerEvent) => void;\n\n // ===== Cache =====\n // Use symbol sentinel to distinguish \"no value\" from undefined/null values\n private _value: T | typeof NO_VALUE = NO_VALUE;\n\n /**\n * Create a Computed instance\n *\n * @param getter - The computation function\n * @param setter - Optional setter function\n * @param onTrack - Optional debug callback for dependency tracking\n * @param onTrigger - Optional debug callback for triggers\n */\n constructor(\n getter: ComputedGetter<T>,\n setter?: ComputedSetter<T>,\n onTrack?: (event: DebuggerEvent) => void,\n onTrigger?: (event: DebuggerEvent) => void,\n ) {\n this.getter = getter;\n this.setter = setter;\n this.onTrack = onTrack;\n this.onTrigger = onTrigger;\n this.flag |= ReactiveFlags.DIRTY;\n }\n\n get value(): T {\n // Track dependencies if accessed within an effect or computed\n if (activeSub) {\n linkReactiveNode(this, activeSub);\n }\n\n // Cache flag and hasValue to reduce property access\n const flags = this.flag;\n const hasValue = this._value !== NO_VALUE;\n\n if (hasValue && !(flags & (ReactiveFlags.DIRTY | ReactiveFlags.PENDING))) {\n return this._value as T;\n }\n\n // Dirty state or no value: must recompute\n if (!hasValue || flags & ReactiveFlags.DIRTY) {\n this.recompute();\n return this._value as T;\n }\n\n // Pending state: check if dependencies actually changed\n if (flags & ReactiveFlags.PENDING) {\n if (this.depLink && checkDirty(this.depLink, this)) {\n // Dependencies changed, recompute\n this.recompute();\n } else {\n // Dependencies unchanged, clear pending flag using cached flags\n this.flag = flags & ~ReactiveFlags.PENDING;\n }\n }\n\n return this._value as T;\n }\n\n /**\n * Set value (only effective when setter is provided)\n *\n * @param newValue - The new value\n */\n set value(newValue: T) {\n if (this.setter) {\n this.setter(newValue);\n } else if (__DEV__) {\n warn(\n '[Computed] Cannot set readonly computed value. ' +\n 'Provide a setter in the computed options to make it writable.\\n' +\n 'Example: computed({ get: () => value, set: (v) => { ... } })',\n );\n }\n }\n\n /**\n * Read value without tracking dependencies\n *\n * @returns Current value\n */\n peek(): T {\n if (this._value === NO_VALUE) {\n this.recompute();\n }\n return this._value as T;\n }\n\n /**\n * Recompute the value\n *\n * computation logic:\n * 1. Start tracking dependencies\n * 2. Execute getter function\n * 3. Check if value changed using optimized comparison\n * 4. If changed, update cache and notify subscribers\n * 5. End tracking, clean up stale dependencies\n * @private\n */\n private recompute(): void {\n // Store old value for change detection\n // Use NO_VALUE sentinel to distinguish initial state from undefined/null values\n const oldValue = this._value;\n const hadValue = oldValue !== NO_VALUE;\n\n // Start tracking dependencies\n const prevSub = startTracking(this);\n\n try {\n // Execute computation\n const newValue = this.getter();\n\n // Cache current flags for efficient bitwise operations\n const flags = this.flag;\n // Pre-calculate the mask for clearing DIRTY and PENDING flags\n const clearMask = ~(ReactiveFlags.DIRTY | ReactiveFlags.PENDING);\n\n // - If no previous value, always consider it changed\n // - Otherwise use hasChanged for proper comparison (handles NaN, etc.)\n const valueChanged = !hadValue || hasChanged(oldValue as any, newValue);\n\n if (valueChanged) {\n // Update cache\n this._value = newValue;\n\n // Clear DIRTY and PENDING flags in single operation using cached flags\n this.flag = flags & clearMask;\n\n // Debug hook: notify about the trigger\n if (__DEV__ && this.onTrigger) {\n this.onTrigger({\n effect: this,\n target: this as any,\n type: 'set',\n key: 'value',\n newValue,\n });\n }\n\n // Notify subscribers only when value actually changed\n // This prevents unnecessary propagation\n if (this.subLink) {\n shallowPropagate(this.subLink);\n }\n } else {\n // Value unchanged, only clear flags using cached flags\n // No need to propagate since subscribers already have correct value\n this.flag = flags & clearMask;\n }\n } catch (_error) {\n // On error, ensure flags are cleared to prevent stuck dirty state\n this.flag &= ~(ReactiveFlags.DIRTY | ReactiveFlags.PENDING);\n\n if (__DEV__) {\n error(\n '[Computed] Error occurred while computing value. ' +\n 'Check your getter function for errors.',\n _error,\n );\n }\n\n throw _error;\n } finally {\n // End tracking, clean up stale dependencies\n // This removes links to dependencies that are no longer accessed\n endTracking(this, prevSub);\n }\n }\n\n /**\n * Check if update is needed\n *\n * Internal use, called by reactive system.\n *\n * @returns true if value changed\n */\n shouldUpdate(): boolean {\n const hadValue = this._value !== NO_VALUE;\n const oldValue = this._value;\n\n this.recompute();\n\n if (!hadValue) {\n return true;\n }\n\n return hasChanged(this._value, oldValue);\n }\n}\n\n/**\n * Create a Computed value\n *\n * @param getterOrOptions - Computation function or configuration object\n * @returns Computed instance\n *\n * @example\n * ```typescript\n * // Read-only computed\n * const count = signal(0);\n * const doubled = computed(() => count.value * 2);\n *\n * console.log(doubled.value); // 0\n * count.value = 5;\n * console.log(doubled.value); // 10\n *\n * // Writable computed\n * const firstName = signal('John');\n * const lastName = signal('Doe');\n *\n * const fullName = computed({\n * get: () => `${firstName.value} ${lastName.value}`,\n * set: (value) => {\n * const [first, last] = value.split(' ');\n * firstName.value = first;\n * lastName.value = last;\n * }\n * });\n *\n * fullName.value = 'Jane Smith';\n * console.log(firstName.value); // 'Jane'\n * ```\n */\nexport function computed<T>(\n getterOrOptions: ComputedGetter<T> | ComputedOptions<T>,\n): ComputedImpl<T> {\n // Guard: Prevent passing computed to computed\n if (isComputed(getterOrOptions)) {\n if (__DEV__) {\n warn(\n '[Computed] Creating a computed from another computed is not recommended. ' +\n 'The existing computed will be returned to avoid unnecessary wrapping.',\n );\n }\n return getterOrOptions as unknown as ComputedImpl<T>;\n }\n\n // Validate input\n if (!getterOrOptions) {\n throw new Error(\n '[Computed] Invalid argument: computed() requires a getter function or options object.',\n );\n }\n\n if (isFunction(getterOrOptions)) {\n return new ComputedImpl(getterOrOptions);\n }\n\n if (isPlainObject(getterOrOptions)) {\n const { get, set, onTrack, onTrigger } = getterOrOptions;\n\n if (!get) {\n throw new Error(\n '[Computed] Invalid options: getter function is required.\\n' +\n 'Usage: computed({ get: () => value, set: (v) => { ... } })',\n );\n }\n\n if (!isFunction(get)) {\n throw new TypeError(\n '[Computed] Invalid options: getter must be a function.\\n' + `Received: ${typeof get}`,\n );\n }\n\n return new ComputedImpl(get, set, onTrack, onTrigger);\n }\n\n throw new Error(\n '[Computed] Invalid argument: expected a function or options object.\\n' +\n `Received: ${typeof getterOrOptions}`,\n );\n}\n\n/**\n * Type guard - Check if value is Computed\n *\n * @param value - The value to check\n * @returns true if value is Computed\n */\nexport function isComputed<T>(value: unknown): value is Computed<T> {\n return !!value && !!value[SignalFlags.IS_COMPUTED];\n}\n","import { warn } from '@estjs/shared';\nimport { batch, computed, reactive } from './';\n\n/**\n * Represents a store's state object.\n * Must be a plain object containing the store's reactive state.\n */\nexport type State = Record<string, any>;\n\n/**\n * Represents a store's getters object.\n * Each getter is a function that receives the state and returns a computed value.\n */\nexport type Getters<S extends State> = Record<string, (state: S) => any>;\n\n/**\n * Represents a store's actions object.\n * Each action is a function that can modify the store's state.\n */\nexport type Actions = Record<string, (...args: any[]) => any>;\n\n/**\n * Configuration options for creating a store.\n *\n * @template S - The type of the store's state\n * @template G - The type of the store's getters\n * @template A - The type of the store's actions\n */\nexport interface StoreOptions<S extends State, G extends Getters<S>, A extends Actions> {\n /** The initial state of the store */\n state: S;\n /** Computed values derived from the state */\n getters?: G;\n /** Methods that can modify the store's state */\n actions?: A;\n}\n\n/**\n * Payload for patching store state.\n * Must be a partial object matching the store's state shape.\n */\nexport type PatchPayload<S> = Partial<S>;\n\n/**\n * Callback function for store subscriptions and action notifications.\n */\nexport type StoreCallback<S> = (state: S) => void;\n\n/**\n * Built-in actions available on all stores.\n *\n * @template S - The type of the store's state\n */\nexport interface StoreActions<S extends State> {\n /**\n * Updates multiple state properties at once.\n * Triggers a single update notification.\n *\n * @param payload - Object containing state updates\n */\n patch$: (payload: PatchPayload<S>) => void;\n\n /**\n * Subscribes to state changes.\n * The callback is called whenever the state changes.\n *\n * @param callback - Function to call on state changes\n */\n subscribe$: (callback: StoreCallback<S>) => void;\n\n /**\n * Unsubscribes from state changes.\n *\n * @param callback - The callback to remove\n */\n unsubscribe$: (callback: StoreCallback<S>) => void;\n\n /**\n * Subscribes to action executions.\n * The callback is called whenever an action is executed.\n *\n * @param callback - Function to call on action execution\n */\n onAction$: (callback: StoreCallback<S>) => void;\n\n /**\n * Resets the store state to its initial values.\n */\n reset$: () => void;\n}\n\n/**\n * Computed values from getters.\n *\n * @template G - The type of the store's getters\n */\ntype GetterValues<G extends Getters<any>> = {\n [K in keyof G]: ReturnType<G[K]>;\n};\n\n/**\n * Creates a store from options (state, getters, and actions).\n *\n * @template S - The type of the store's state\n * @template G - The type of the store's getters\n * @template A - The type of the store's actions\n * @param options - Store configuration options\n * @returns The store instance\n * @internal\n */\nfunction createOptionsStore<S extends State, G extends Getters<S>, A extends Actions>(\n options: StoreOptions<S, G, A>,\n) {\n if (__DEV__ && !options.state) {\n warn('Store state is required');\n throw new Error('Store state is required');\n }\n\n const { state, getters, actions } = options;\n const initState = { ...state };\n const reactiveState = reactive(state);\n\n const subscriptions = new Set<StoreCallback<S>>();\n const actionCallbacks = new Set<StoreCallback<S>>();\n\n const defaultActions: StoreActions<S> = {\n patch$(payload: PatchPayload<S>) {\n if (__DEV__ && !payload) {\n warn('Patch payload is required');\n return;\n }\n\n // Use batch for better performance\n batch(() => {\n Object.assign(reactiveState, payload);\n });\n\n // Notify subscribers\n subscriptions.forEach(callback => callback(reactiveState));\n actionCallbacks.forEach(callback => callback(reactiveState));\n },\n\n subscribe$(callback: StoreCallback<S>) {\n if (__DEV__ && !callback) {\n warn('Subscribe callback is required');\n return;\n }\n subscriptions.add(callback);\n },\n\n unsubscribe$(callback: StoreCallback<S>) {\n subscriptions.delete(callback);\n },\n\n onAction$(callback: StoreCallback<S>) {\n if (__DEV__ && !callback) {\n warn('Action callback is required');\n return;\n }\n actionCallbacks.add(callback);\n },\n\n reset$() {\n // Use batch for better performance\n batch(() => {\n Object.assign(reactiveState, initState);\n });\n\n // Notify subscribers\n subscriptions.forEach(callback => callback(reactiveState));\n actionCallbacks.forEach(callback => callback(reactiveState));\n },\n };\n\n const store = {\n ...reactiveState,\n state: reactiveState,\n ...defaultActions,\n } as S & GetterValues<G> & A & StoreActions<S> & { state: S };\n\n // Add getters as computed properties\n if (getters) {\n for (const key in getters) {\n const getter = getters[key];\n if (getter) {\n Object.defineProperty(store, key, {\n get() {\n return computed(() => getter.call(store, reactiveState)).value;\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n }\n\n // Add actions with automatic notification\n if (actions) {\n for (const key in actions) {\n const action = actions[key];\n if (action) {\n (store as any)[key] = (...args: any[]) => {\n const result = action.apply(reactiveState, args);\n actionCallbacks.forEach(callback => callback(reactiveState));\n return result;\n };\n }\n }\n }\n\n return store;\n}\n/**\n * Creates store options from a class definition.\n *\n * @template S - The type of the store's state\n * @param StoreClass - The store class\n * @returns Store options derived from the class\n * @internal\n */\nfunction createClassStore<S extends State>(\n StoreClass: new () => S,\n): StoreOptions<\n S,\n Record<string, (...args: any[]) => any>,\n Record<string, (...args: any[]) => any>\n> {\n const instance = new StoreClass();\n const state = Object.create(null);\n const getters: Record<string, (...args: any[]) => any> = {};\n const actions: Record<string, (...args: any[]) => any> = {};\n\n // Extract instance properties as state\n Object.getOwnPropertyNames(instance).forEach(key => {\n state[key] = instance[key];\n });\n\n // Extract prototype methods and getters\n Object.getOwnPropertyNames(StoreClass.prototype).forEach(key => {\n const descriptor = Object.getOwnPropertyDescriptor(StoreClass.prototype, key);\n if (descriptor) {\n if (typeof descriptor.get === 'function') {\n getters[key] = function (this: S) {\n return descriptor.get!.call(this);\n };\n } else if (typeof descriptor.value === 'function' && key !== 'constructor') {\n actions[key] = function (this: S, ...args: any[]) {\n return descriptor.value.apply(this, args);\n };\n }\n }\n });\n\n return {\n state,\n getters,\n actions,\n };\n}\n\n/**\n * Store definition type that can be either a class or an options object.\n */\ntype StoreDefinition<S extends State, G extends Getters<S>, A extends Actions> =\n | (new () => S)\n | ({\n state: S;\n getters?: G;\n actions?: A;\n } & ThisType<S & GetterValues<G> & A & StoreActions<S>>);\n\n/**\n * Creates a new store with the given definition.\n * The store can be defined either as a class or as an options object.\n *\n * @template S - The type of the store's state\n * @template G - The type of the store's getters\n * @template A - The type of the store's actions\n * @param storeDefinition - The store definition (class or options)\n * @returns A function that creates a new store instance\n *\n * @example\n * ```ts\n * // Options-based store\n * const useCounter = createStore({\n * state: { count: 0 },\n * getters: {\n * double: state => state.count * 2\n * },\n * actions: {\n * increment() {\n * this.count++;\n * }\n * }\n * });\n *\n * // Class-based store\n * class Counter {\n * count = 0;\n *\n * get double() {\n * return this.count * 2;\n * }\n *\n * increment() {\n * this.count++;\n * }\n * }\n *\n * const useCounter = createStore(Counter);\n * ```\n */\nexport function createStore<S extends State, G extends Getters<S>, A extends Actions>(\n storeDefinition: StoreDefinition<S, G, A>,\n): () => S & GetterValues<G> & A & StoreActions<S> & { state: S } {\n if (__DEV__ && !storeDefinition) {\n warn('Store definition is required');\n throw new Error('Store definition is required');\n }\n\n return () => {\n let options: StoreOptions<S, G, A>;\n\n if (typeof storeDefinition === 'function') {\n options = createClassStore(storeDefinition) as StoreOptions<S, G, A>;\n } else {\n options = storeDefinition;\n }\n\n const store = createOptionsStore(options);\n\n // For class-based stores, bind methods to the store\n if (typeof storeDefinition === 'function') {\n Object.keys(options.actions || {}).forEach(key => {\n (store as any)[key] = (options.actions as any)[key].bind(store);\n });\n }\n\n return store;\n };\n}\n","import { hasChanged, info } from '@estjs/shared';\nimport { SIGNAL_KEY, SignalFlags } from './constants';\nimport { shallowPropagate, track, trigger } from './link';\nimport { type Signal, SignalImpl, isSignal } from './signal';\n\n/**\n * A Ref is a special type of Signal used primarily for DOM element references.\n * It provides methods to read, write, and observe changes to the value.\n *\n * @template T - The type of value held by the ref\n */\nexport interface Ref<T> extends Signal<T> {\n /**\n * The current value of the ref. Reading this property will track dependencies,\n * and writing to it will notify subscribers of changes.\n */\n value: T;\n}\n\n/**\n * Internal implementation of the Ref interface.\n * This class extends SignalImpl but only overrides the get value() method\n * to provide direct access to the underlying value without reactive wrapping.\n *\n * @template T - The type of value held by the ref\n * @internal\n */\nclass RefImpl<T> extends SignalImpl<T> implements Ref<T> {\n // @ts-ignore\n private readonly [SignalFlags.IS_REF] = true;\n\n /**\n * Creates a new ref with the given initial value.\n *\n * @param value - The initial value\n */\n constructor(value: T) {\n super(value, true);\n }\n\n get value(): T {\n track(this, SIGNAL_KEY);\n // ref just proxy the value without reactive wrapping\n return this._value;\n }\n\n set value(newValue: T) {\n // Handle nested signals by unwrapping them\n if (isSignal(newValue)) {\n newValue = newValue.value as T;\n }\n if (isRef(newValue)) {\n newValue = newValue.value as T;\n }\n\n // Only trigger updates if the value has actually changed\n if (hasChanged(this._value, newValue)) {\n this._value = newValue;\n\n if (this.subLink) {\n shallowPropagate(this.subLink);\n }\n\n // Keep the old system for backward compatibility\n trigger(this, 'SET', SIGNAL_KEY);\n }\n }\n}\n\n/**\n * Creates a new ref with the given initial value.\n * Unlike signals, refs don't create reactive proxies for object values.\n *\n * @template T - The type of value to store in the ref\n * @param value - The initial value\n * @returns A new ref instance\n *\n * @example\n * ```ts\n * const divRef = ref();\n * <div ref={divRef}></div>\n * ```\n */\nexport function ref<T>(value: T = undefined as unknown as T): Ref<T> {\n if (isRef(value)) {\n if (__DEV__) {\n info('Creating a ref with another ref is not recommended. The value will be unwrapped.');\n }\n return value as Ref<T>;\n }\n\n if (isSignal(value)) {\n if (__DEV__) {\n info('Creating a ref with a signal is not recommended. The value will be unwrapped.');\n }\n return new RefImpl(value.peek() as T);\n }\n\n return new RefImpl(value);\n}\n\n/**\n * Type guard to check if a value is a Ref instance.\n *\n * @template T - The type of value held by the ref\n * @param value - The value to check\n * @returns True if the value is a Ref instance\n */\nexport function isRef<T>(value: unknown): value is Ref<T> {\n return !!value && !!value[SignalFlags.IS_REF];\n}\n","import { hasChanged, isFunction, isMap, isObject, isSet } from '@estjs/shared';\nimport { queueJob } from './scheduler';\nimport { isSignal } from './signal';\nimport { isReactive } from './reactive';\nimport { isComputed } from './computed';\nimport { effect } from './effect';\nimport type { Effect } from './propagation';\n\n// A unique initial value used to identify if watcher is running for the first time.\nconst INITIAL_WATCHER_VALUE = {};\n\n// Watch function options interface.\ninterface WatchOptions {\n immediate?: boolean; // Whether to execute callback immediately once\n deep?: boolean; // Whether to deeply traverse source to track nested changes\n}\n\n// Watch source type, can be value, ref/signal, getter function or array.\ntype WatchSource<T = any> = T | { value: T } | (() => T);\n// Watch callback function type.\ntype WatchCallback<T = any> = (newValue: T, oldValue: T | undefined) => void;\n\n// Use WeakMap to store cleanup functions for each effect.\nconst cleanupMap = new WeakMap<Effect, (() => void)[]>();\n\n/**\n * Recursively traverse a value, accessing all its properties to trigger dependency tracking.\n * @param value - The value to traverse.\n * @param seen - Set used to prevent circular references.\n * @returns The original value.\n */\nfunction traverse(value: any, seen = new Set()) {\n // If not an object or already traversed, stop.\n if (!isObject(value) || seen.has(value)) {\n return value;\n }\n\n seen.add(value);\n // If it's a signal or computed, traverse its .value.\n if (isSignal(value) || isComputed(value)) {\n return traverse(value.value, seen);\n }\n // If it's an array, traverse all its elements.\n if (Array.isArray(value)) {\n for (const element of value) {\n traverse(element, seen);\n }\n // If it's a Map, traverse all its values, and access keys and values to track changes.\n } else if (isMap(value)) {\n value.forEach((v: any) => {\n traverse(v, seen);\n });\n value.keys();\n value.values();\n // If it's a Set, traverse all its values to track changes.\n } else if (isSet(value)) {\n value.forEach((v: any) => {\n traverse(v, seen);\n });\n value.values();\n // If it's a plain object, traverse all its keys.\n } else {\n Object.keys(value).forEach(key => {\n traverse(value[key], seen);\n });\n }\n\n return value;\n}\n\n/**\n * Create a deep clone of a value for comparison purposes.\n * Handles plain objects, arrays, Map, Set, and primitives.\n * @param value - The value to clone.\n * @returns A deep clone of the value.\n */\nfunction cloneValue<T>(value: T): T {\n if (!isObject(value)) {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(item => cloneValue(item)) as unknown as T;\n }\n\n if (isMap(value)) {\n const cloned = new Map();\n value.forEach((v, k) => {\n cloned.set(k, cloneValue(v));\n });\n return cloned as unknown as T;\n }\n\n if (isSet(value)) {\n const cloned = new Set();\n value.forEach(v => {\n cloned.add(cloneValue(v));\n });\n return cloned as unknown as T;\n }\n\n // Plain object\n const cloned: any = {};\n for (const key of Object.keys(value as object)) {\n cloned[key] = cloneValue((value as any)[key]);\n }\n return cloned as T;\n}\n\n/**\n * Resolve watch sources of various forms into a standard getter function.\n * @param source - The watch source passed by the user.\n * @returns A getter function that returns the current source value.\n */\nfunction resolveSource<T>(source: WatchSource<T>): () => T {\n // If source is an array, return a getter that traverses the array and unwraps each element.\n if (Array.isArray(source)) {\n return () =>\n source.map(s => {\n if (isSignal(s) || isComputed(s)) {\n return s.value;\n }\n if (isReactive(s)) {\n return traverse(s);\n }\n if (isFunction(s)) {\n return s();\n }\n return s;\n }) as unknown as T;\n }\n\n // If source is a function, use it directly as getter.\n if (isFunction(source)) {\n return source as () => T;\n }\n\n // If source is a signal, return a getter that reads its .value.\n if (isSignal(source)) {\n return () => source.value as unknown as T;\n }\n\n // If source is a ref-like object, return a getter that reads its .value.\n if (isObject(source) && 'value' in source) {\n return () => source.value as T;\n }\n\n // If source is a reactive object, return a getter that deeply traverses it.\n if (isReactive(source as any)) {\n return () => traverse(source as any) as unknown as T;\n }\n\n // Otherwise, source is a plain value, return a getter that directly returns the value.\n return () => source as T;\n}\n\n/**\n * Watch one or more reactive data sources and execute callback when sources change.\n * @param source - The source(s) to watch.\n * @param callback - The callback function to execute when source changes.\n * @param options - Configuration options like immediate and deep.\n * @returns A function to stop watching.\n */\nexport function watch<T = any>(\n source: WatchSource<T>,\n callback: WatchCallback<T>,\n options: WatchOptions = {},\n): () => void {\n const { immediate = false, deep = false } = options;\n // Initialize oldValue as a special object to determine if it's the first execution.\n let oldValue: any = INITIAL_WATCHER_VALUE;\n let cleanup: (() => void) | undefined;\n\n // Resolve source to a getter function.\n const getter = resolveSource(source);\n\n // job is the function that actually executes the callback, called by the scheduler.\n const job = () => {\n const currentEffect = runner.effect;\n if (!currentEffect.run) {\n return;\n }\n\n // Run effect to get new value.\n const newValue = currentEffect.run();\n\n // Execute the previously registered cleanup function before calling callback.\n if (cleanup) {\n cleanup();\n }\n\n // If value has changed, execute callback.\n if (hasChanged(newValue, oldValue)) {\n callback(newValue, oldValue === INITIAL_WATCHER_VALUE ? undefined : (oldValue as T));\n // Update oldValue for next comparison (clone to snapshot current state).\n oldValue = cloneValue(newValue);\n }\n };\n\n // Create an effect to track getter dependencies.\n const runner = effect(\n () => {\n const value = getter();\n // If deep watching, recursively traverse value to track all nested properties.\n if (deep) {\n traverse(value);\n }\n return value;\n },\n {\n // Use scheduler to queue job, implementing async and debouncing.\n scheduler: () => queueJob(job),\n },\n );\n\n // If immediate is set, execute job immediately once.\n if (immediate) {\n job();\n } else {\n // Otherwise, run effect once first to collect initial value as oldValue.\n oldValue = cloneValue(runner.effect.run());\n }\n\n // Return a stop function.\n return () => {\n runner.stop();\n // Execute cleanup function if exists.\n if (cleanup) {\n cleanup();\n }\n // Clean up all cleanup functions associated with this effect.\n const cleanups = cleanupMap.get(runner.effect);\n if (cleanups) {\n cleanups.forEach(fn => fn());\n cleanupMap.delete(runner.effect);\n }\n };\n}\n"]}