@alwatr/signal 9.3.0 → 9.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/signal-base.d.ts +6 -1
- package/dist/core/signal-base.d.ts.map +1 -1
- package/dist/main.js +3 -3
- package/dist/main.js.map +3 -3
- package/package.json +8 -8
- package/src/core/signal-base.ts +29 -26
|
@@ -22,7 +22,8 @@ export declare abstract class SignalBase<T> {
|
|
|
22
22
|
* The list of observers (listeners) subscribed to this signal.
|
|
23
23
|
* @protected
|
|
24
24
|
*/
|
|
25
|
-
protected readonly
|
|
25
|
+
protected readonly priorityObservers_: Set<Observer_<T>>;
|
|
26
|
+
protected readonly observers_: Set<Observer_<T>>;
|
|
26
27
|
/**
|
|
27
28
|
* A flag indicating whether the signal has been destroyed.
|
|
28
29
|
* @private
|
|
@@ -63,6 +64,10 @@ export declare abstract class SignalBase<T> {
|
|
|
63
64
|
* @protected
|
|
64
65
|
*/
|
|
65
66
|
protected notify_(value: T): void;
|
|
67
|
+
/**
|
|
68
|
+
* Executes a given observer's callback with the provided value, handling both synchronous and asynchronous callbacks.
|
|
69
|
+
*/
|
|
70
|
+
private executeObserver__;
|
|
66
71
|
/**
|
|
67
72
|
* Returns a Promise that resolves with the next value dispatched by the signal.
|
|
68
73
|
* This provides an elegant way to wait for a single, future event using `async/await`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signal-base.d.ts","sourceRoot":"","sources":["../../src/core/signal-base.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,gBAAgB,EAAE,YAAY,EAAC,MAAM,YAAY,CAAC;AAC7G,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,gBAAgB,CAAC;AAEjD;;;;;GAKG;AACH,8BAAsB,UAAU,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"signal-base.d.ts","sourceRoot":"","sources":["../../src/core/signal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{config_;name;observers_=[];isDestroyed__=!1;get isDestroyed(){return this.isDestroyed__}constructor(G){this.config_=G;this.name=G.name}removeObserver_(G){if(this.logger_.logMethod?.("removeObserver_"),this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}let H=this.observers_.indexOf(G);if(H!==-1)this.observers_.splice(H,1)}subscribe(G,H){this.logger_.logMethodArgs?.("subscribe.base",H),this.checkDestroyed_();let Q={callback:G,options:H};if(H?.priority)this.observers_.unshift(Q);else this.observers_.push(Q);return{unsubscribe:()=>this.removeObserver_(Q)}}notify_(G){if(this.logger_.logMethodArgs?.("notify_",G),this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}let H=[...this.observers_];for(let Q of H){if(Q.options?.once)this.removeObserver_(Q);try{let X=Q.callback(G);if(X instanceof Promise)X.catch((Z)=>this.logger_.error("notify_","async_callback_failed",Z,{observer:Q}))}catch(X){this.logger_.error("notify_","sync_callback_failed",X)}}}untilNext(){return this.logger_.logMethod?.("untilNext"),this.checkDestroyed_(),new Promise((G)=>{this.subscribe(G,{once:!0,priority:!0,receivePrevious:!1})})}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}this.isDestroyed__=!0,this.observers_.length=0,this.config_.onDestroy?.(),this.config_=null}checkDestroyed_(){if(this.isDestroyed__)throw this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal"),Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}import{delay as P}from"@alwatr/delay";import{createLogger as _}from"@alwatr/logger";class J extends q{logger_;constructor(G){super(G);this.logger_=_(`event-signal:${this.name}`),this.logger_.logMethod?.("constructor")}dispatch(G){this.logger_.logMethodArgs?.("dispatch",{payload:G}),this.checkDestroyed_(),P.nextMicrotask().then(()=>this.notify_(G))}}import{delay as $}from"@alwatr/delay";import{createLogger as U}from"@alwatr/logger";class Y extends q{value__;logger_;constructor(G){super({name:G.name,onDestroy:G.onDestroy});this.logger_=U(`state-signal:${this.name}`),this.value__=G.initialValue,this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){return this.checkDestroyed_(),this.value__}set(G){if(this.logger_.logMethodArgs?.("set",{newValue:G}),this.checkDestroyed_(),Object.is(this.value__,G)&&(typeof G!=="object"||G===null))return;this.value__=G,$.nextMicrotask().then(()=>this.notify_(G))}update(G){this.checkDestroyed_();let H=G(this.value__);this.logger_.logMethodFull?.("update",this.value__,H),this.set(H)}subscribe(G,H={}){if(this.logger_.logMethodArgs?.("subscribe",H),this.checkDestroyed_(),H.receivePrevious!==!1){if($.nextMicrotask().then(()=>{this.logger_.logStep?.("subscribe","immediate_callback"),G(this.value__)}).catch((Q)=>this.logger_.error("subscribe","immediate_callback_failed",Q)),H.once)return{unsubscribe:()=>{}}}return super.subscribe(G,H)}destroy(){this.value__=null,super.destroy()}asReadonly(){return this}}import{delay as D}from"@alwatr/delay";import{createLogger as E}from"@alwatr/logger";class M{config_;name;logger_;internalSignal_;dependencySubscriptions__=[];isRecalculating__=!1;constructor(G){this.config_=G;this.name=G.name,this.logger_=E(`computed-signal:${this.name}`),this.recalculate_=this.recalculate_.bind(this),this.logger_.logMethod?.("constructor"),this.internalSignal_=new Y({name:`compute-${this.name}_`,initialValue:this.config_.get()});for(let H of G.deps)this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:H.name}),this.dependencySubscriptions__.push(H.subscribe(this.recalculate_,{receivePrevious:!1}))}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(G,H){return this.internalSignal_.subscribe(G,H)}untilNext(){return this.internalSignal_.untilNext()}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(let G of this.dependencySubscriptions__)G.unsubscribe();this.dependencySubscriptions__.length=0,this.internalSignal_.destroy(),this.config_.onDestroy?.(),this.config_=null}async recalculate_(){if(this.logger_.logMethod?.("recalculate_"),this.internalSignal_.isDestroyed){this.logger_.incident?.("recalculate_","recalculate_on_destroyed_signal");return}if(this.isRecalculating__){this.logger_.logStep?.("recalculate_","skipping_recalculation_already_scheduled");return}this.isRecalculating__=!0;try{if(await D.nextMacrotask(),this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay"),this.isRecalculating__=!1;return}this.logger_.logStep?.("recalculate_","recalculating_value"),this.internalSignal_.set(this.config_.get())}catch(G){this.logger_.error("recalculate_","recalculation_failed",G)}this.isRecalculating__=!1}}import{delay as x}from"@alwatr/delay";import{createLogger as I}from"@alwatr/logger";class R{config_;name;logger_;dependencySubscriptions__=[];isRunning__=!1;isDestroyed__=!1;get isDestroyed(){return this.isDestroyed__}constructor(G){this.config_=G;this.name=G.name??`[${G.deps.map((H)=>H.name).join(", ")}]`,this.logger_=I(`effect-signal:${this.name}`),this.scheduleExecution_=this.scheduleExecution_.bind(this),this.logger_.logMethod?.("constructor");for(let H of G.deps)this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:H.name}),this.dependencySubscriptions__.push(H.subscribe(this.scheduleExecution_,{receivePrevious:!1}));if(G.runImmediately===!0)this.logger_.logStep?.("constructor","scheduling_initial_execution"),this.scheduleExecution_()}async scheduleExecution_(){if(this.logger_.logMethod?.("scheduleExecution_"),this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","schedule_execution_on_destroyed_signal");return}if(this.isRunning__){this.logger_.logStep?.("scheduleExecution_","skipped_because_already_running");return}this.isRunning__=!0;try{if(await x.nextMacrotask(),this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay"),this.isRunning__=!1;return}this.logger_.logStep?.("scheduleExecution_","executing_effect"),await this.config_.run()}catch(G){this.logger_.error("scheduleExecution_","effect_failed",G)}this.isRunning__=!1}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=!0;for(let G of this.dependencySubscriptions__)G.unsubscribe();this.dependencySubscriptions__.length=0,this.config_.onDestroy?.(),this.config_=null}}import{createDebouncer as N}from"@alwatr/debounce";import{createLocalStorageProvider as A}from"@alwatr/local-storage";class z extends Y{storageProvider__;storageDebouncer__;storageSyncSubscription__;constructor(G){let{name:H,storageKey:Q=H,saveDebounceDelay:X=500,initialValue:Z,onDestroy:K,schemaVersion:B}=G,F=A({name:Q,schemaVersion:B});super({name:H,initialValue:F.read()??Z,onDestroy:K});this.logger_.logMethodArgs?.("constructor",G),this.storageProvider__=F,this.storageDebouncer__=N({delay:X,leading:!1,trailing:!0,thisContext:this,func:this.syncStorage__}),this.storageSyncSubscription__=this.subscribe(this.storageDebouncer__.trigger,{receivePrevious:!1})}syncStorage__(G){this.logger_.logMethodArgs?.("syncStorage__",G),this.storageProvider__.write(G)}remove(){this.checkDestroyed_(),this.logger_.logMethod?.("remove"),this.storageProvider__.remove()}destroy(){this.logger_.logMethod?.("destroy"),this.storageDebouncer__.flush(),this.storageSyncSubscription__.unsubscribe(),super.destroy()}}import{createDebouncer as j}from"@alwatr/debounce";import{createSessionStorageProvider as C}from"@alwatr/session-storage";class L extends Y{storageProvider__;storageDebouncer__;storageSyncSubscription__;constructor(G){let{name:H,storageKey:Q=H,saveDebounceDelay:X=500,initialValue:Z,onDestroy:K}=G,B=C({name:Q});super({name:H,initialValue:B.read()??Z,onDestroy:K});this.logger_.logMethodArgs?.("constructor",G),this.storageProvider__=B,this.storageDebouncer__=j({delay:X,leading:!1,trailing:!0,thisContext:this,func:this.syncStorage__}),this.storageSyncSubscription__=this.subscribe(this.storageDebouncer__.trigger,{receivePrevious:!1})}syncStorage__(G){this.logger_.logMethodArgs?.("syncStorage__",G),this.storageProvider__.write(G)}remove(){this.checkDestroyed_(),this.logger_.logMethod?.("remove"),this.storageProvider__.remove()}destroy(){this.logger_.logMethod?.("destroy"),this.storageDebouncer__.flush(),this.storageSyncSubscription__.unsubscribe(),super.destroy()}}function HG(G){return new J(G)}function O(G){return new Y(G)}function W(G){return new M(G)}function WG(G){return new R(G)}function JG(G){return new z(G)}function zG(G){return new L(G)}import{createDebouncer as k}from"@alwatr/debounce";function _G(G,H){let Q=H.name??`${G.name}-debounced`,X=new Y({name:`${Q}-internal`,initialValue:G.get()}),Z=k({...H,thisContext:X,func:X.set}),K=G.subscribe(Z.trigger,{receivePrevious:!1});return W({name:Q,deps:[X],get:()=>X.get(),onDestroy:()=>{if(X.isDestroyed)return;K.unsubscribe(),Z.cancel(),X.destroy(),H.onDestroy?.(),H=null}})}function xG(G,H,Q=`${G.name}-filtered`){let X=G.get(),Z=H(X)?X:void 0,K=O({name:`${Q}-internal`,initialValue:Z}),B=G.subscribe((F)=>{if(H(F))K.set(F)});return W({name:Q,deps:[K],get:()=>K.get(),onDestroy:()=>{B.unsubscribe(),K.destroy()}})}function AG(G,H,Q=`${G.name}-mapped`){return W({name:Q,deps:[G],get:()=>H(G.get())})}export{O as createStateSignal,zG as createSessionStateSignal,JG as createPersistentStateSignal,AG as createMappedSignal,xG as createFilteredSignal,HG as createEventSignal,WG as createEffect,_G as createDebouncedSignal,W as createComputedSignal,Y as StateSignal,q as SignalBase,L as SessionStateSignal,z as PersistentStateSignal,J as EventSignal,R as EffectSignal,M as ComputedSignal};
|
|
1
|
+
/* 📦 @alwatr/signal v9.4.0 */
|
|
2
|
+
class q{config_;name;priorityObservers_=new Set;observers_=new Set;isDestroyed__=!1;get isDestroyed(){return this.isDestroyed__}constructor(G){this.config_=G;this.name=G.name}removeObserver_(G){if(this.logger_.logMethod?.("removeObserver_"),this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}this.priorityObservers_.delete(G),this.observers_.delete(G)}subscribe(G,H){this.logger_.logMethodArgs?.("subscribe.base",H),this.checkDestroyed_();let Q={callback:G,options:H};if(H?.priority)this.priorityObservers_.add(Q);else this.observers_.add(Q);return{unsubscribe:()=>this.removeObserver_(Q)}}notify_(G){if(this.logger_.logMethodArgs?.("notify_",G),this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}for(let H of this.priorityObservers_)this.executeObserver__(H,G);for(let H of this.observers_)this.executeObserver__(H,G)}executeObserver__(G,H){if(G.options?.once)this.removeObserver_(G);try{let Q=G.callback(H);if(Q instanceof Promise)Q.catch((X)=>this.logger_.error("notify_","async_callback_failed",X,{observer:G}))}catch(Q){this.logger_.error("notify_","sync_callback_failed",Q)}}untilNext(){return this.logger_.logMethod?.("untilNext"),this.checkDestroyed_(),new Promise((G)=>{this.subscribe(G,{once:!0,priority:!0,receivePrevious:!1})})}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}this.isDestroyed__=!0,this.priorityObservers_.clear(),this.observers_.clear(),this.config_.onDestroy?.(),this.config_=null}checkDestroyed_(){if(this.isDestroyed__)throw this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal"),Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}import{delay as P}from"@alwatr/delay";import{createLogger as _}from"@alwatr/logger";class J extends q{logger_;constructor(G){super(G);this.logger_=_(`event-signal:${this.name}`),this.logger_.logMethod?.("constructor")}dispatch(G){this.logger_.logMethodArgs?.("dispatch",{payload:G}),this.checkDestroyed_(),P.nextMicrotask().then(()=>this.notify_(G))}}import{delay as O}from"@alwatr/delay";import{createLogger as U}from"@alwatr/logger";class Y extends q{value__;logger_;constructor(G){super({name:G.name,onDestroy:G.onDestroy});this.logger_=U(`state-signal:${this.name}`),this.value__=G.initialValue,this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){return this.checkDestroyed_(),this.value__}set(G){if(this.logger_.logMethodArgs?.("set",{newValue:G}),this.checkDestroyed_(),Object.is(this.value__,G)&&(typeof G!=="object"||G===null))return;this.value__=G,O.nextMicrotask().then(()=>this.notify_(G))}update(G){this.checkDestroyed_();let H=G(this.value__);this.logger_.logMethodFull?.("update",this.value__,H),this.set(H)}subscribe(G,H={}){if(this.logger_.logMethodArgs?.("subscribe",H),this.checkDestroyed_(),H.receivePrevious!==!1){if(O.nextMicrotask().then(()=>{this.logger_.logStep?.("subscribe","immediate_callback"),G(this.value__)}).catch((Q)=>this.logger_.error("subscribe","immediate_callback_failed",Q)),H.once)return{unsubscribe:()=>{}}}return super.subscribe(G,H)}destroy(){this.value__=null,super.destroy()}asReadonly(){return this}}import{delay as D}from"@alwatr/delay";import{createLogger as E}from"@alwatr/logger";class M{config_;name;logger_;internalSignal_;dependencySubscriptions__=[];isRecalculating__=!1;constructor(G){this.config_=G;this.name=G.name,this.logger_=E(`computed-signal:${this.name}`),this.recalculate_=this.recalculate_.bind(this),this.logger_.logMethod?.("constructor"),this.internalSignal_=new Y({name:`compute-${this.name}_`,initialValue:this.config_.get()});for(let H of G.deps)this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:H.name}),this.dependencySubscriptions__.push(H.subscribe(this.recalculate_,{receivePrevious:!1}))}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(G,H){return this.internalSignal_.subscribe(G,H)}untilNext(){return this.internalSignal_.untilNext()}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(let G of this.dependencySubscriptions__)G.unsubscribe();this.dependencySubscriptions__.length=0,this.internalSignal_.destroy(),this.config_.onDestroy?.(),this.config_=null}async recalculate_(){if(this.logger_.logMethod?.("recalculate_"),this.internalSignal_.isDestroyed){this.logger_.incident?.("recalculate_","recalculate_on_destroyed_signal");return}if(this.isRecalculating__){this.logger_.logStep?.("recalculate_","skipping_recalculation_already_scheduled");return}this.isRecalculating__=!0;try{if(await D.nextMacrotask(),this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay"),this.isRecalculating__=!1;return}this.logger_.logStep?.("recalculate_","recalculating_value"),this.internalSignal_.set(this.config_.get())}catch(G){this.logger_.error("recalculate_","recalculation_failed",G)}this.isRecalculating__=!1}}import{delay as x}from"@alwatr/delay";import{createLogger as I}from"@alwatr/logger";class R{config_;name;logger_;dependencySubscriptions__=[];isRunning__=!1;isDestroyed__=!1;get isDestroyed(){return this.isDestroyed__}constructor(G){this.config_=G;this.name=G.name??`[${G.deps.map((H)=>H.name).join(", ")}]`,this.logger_=I(`effect-signal:${this.name}`),this.scheduleExecution_=this.scheduleExecution_.bind(this),this.logger_.logMethod?.("constructor");for(let H of G.deps)this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:H.name}),this.dependencySubscriptions__.push(H.subscribe(this.scheduleExecution_,{receivePrevious:!1}));if(G.runImmediately===!0)this.logger_.logStep?.("constructor","scheduling_initial_execution"),this.scheduleExecution_()}async scheduleExecution_(){if(this.logger_.logMethod?.("scheduleExecution_"),this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","schedule_execution_on_destroyed_signal");return}if(this.isRunning__){this.logger_.logStep?.("scheduleExecution_","skipped_because_already_running");return}this.isRunning__=!0;try{if(await x.nextMacrotask(),this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay"),this.isRunning__=!1;return}this.logger_.logStep?.("scheduleExecution_","executing_effect"),await this.config_.run()}catch(G){this.logger_.error("scheduleExecution_","effect_failed",G)}this.isRunning__=!1}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=!0;for(let G of this.dependencySubscriptions__)G.unsubscribe();this.dependencySubscriptions__.length=0,this.config_.onDestroy?.(),this.config_=null}}import{createDebouncer as N}from"@alwatr/debounce";import{createLocalStorageProvider as A}from"@alwatr/local-storage";class z extends Y{storageProvider__;storageDebouncer__;storageSyncSubscription__;constructor(G){let{name:H,storageKey:Q=H,saveDebounceDelay:X=500,initialValue:K,onDestroy:Z,schemaVersion:B}=G,F=A({name:Q,schemaVersion:B});super({name:H,initialValue:F.read()??K,onDestroy:Z});this.logger_.logMethodArgs?.("constructor",G),this.storageProvider__=F,this.storageDebouncer__=N({delay:X,leading:!1,trailing:!0,thisContext:this,func:this.syncStorage__}),this.storageSyncSubscription__=this.subscribe(this.storageDebouncer__.trigger,{receivePrevious:!1})}syncStorage__(G){this.logger_.logMethodArgs?.("syncStorage__",G),this.storageProvider__.write(G)}remove(){this.checkDestroyed_(),this.logger_.logMethod?.("remove"),this.storageProvider__.remove()}destroy(){this.logger_.logMethod?.("destroy"),this.storageDebouncer__.flush(),this.storageSyncSubscription__.unsubscribe(),super.destroy()}}import{createDebouncer as j}from"@alwatr/debounce";import{createSessionStorageProvider as C}from"@alwatr/session-storage";class L extends Y{storageProvider__;storageDebouncer__;storageSyncSubscription__;constructor(G){let{name:H,storageKey:Q=H,saveDebounceDelay:X=500,initialValue:K,onDestroy:Z}=G,B=C({name:Q});super({name:H,initialValue:B.read()??K,onDestroy:Z});this.logger_.logMethodArgs?.("constructor",G),this.storageProvider__=B,this.storageDebouncer__=j({delay:X,leading:!1,trailing:!0,thisContext:this,func:this.syncStorage__}),this.storageSyncSubscription__=this.subscribe(this.storageDebouncer__.trigger,{receivePrevious:!1})}syncStorage__(G){this.logger_.logMethodArgs?.("syncStorage__",G),this.storageProvider__.write(G)}remove(){this.checkDestroyed_(),this.logger_.logMethod?.("remove"),this.storageProvider__.remove()}destroy(){this.logger_.logMethod?.("destroy"),this.storageDebouncer__.flush(),this.storageSyncSubscription__.unsubscribe(),super.destroy()}}function HG(G){return new J(G)}function $(G){return new Y(G)}function W(G){return new M(G)}function WG(G){return new R(G)}function JG(G){return new z(G)}function zG(G){return new L(G)}import{createDebouncer as k}from"@alwatr/debounce";function _G(G,H){let Q=H.name??`${G.name}-debounced`,X=new Y({name:`${Q}-internal`,initialValue:G.get()}),K=k({...H,thisContext:X,func:X.set}),Z=G.subscribe(K.trigger,{receivePrevious:!1});return W({name:Q,deps:[X],get:()=>X.get(),onDestroy:()=>{if(X.isDestroyed)return;Z.unsubscribe(),K.cancel(),X.destroy(),H.onDestroy?.(),H=null}})}function xG(G,H,Q=`${G.name}-filtered`){let X=G.get(),K=H(X)?X:void 0,Z=$({name:`${Q}-internal`,initialValue:K}),B=G.subscribe((F)=>{if(H(F))Z.set(F)});return W({name:Q,deps:[Z],get:()=>Z.get(),onDestroy:()=>{B.unsubscribe(),Z.destroy()}})}function AG(G,H,Q=`${G.name}-mapped`){return W({name:Q,deps:[G],get:()=>H(G.get())})}export{$ as createStateSignal,zG as createSessionStateSignal,JG as createPersistentStateSignal,AG as createMappedSignal,xG as createFilteredSignal,HG as createEventSignal,WG as createEffect,_G as createDebouncedSignal,W as createComputedSignal,Y as StateSignal,q as SignalBase,L as SessionStateSignal,z as PersistentStateSignal,J as EventSignal,R as EffectSignal,M as ComputedSignal};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=6E44E6DCC7E28F2164756E2164756E21
|
|
5
5
|
//# sourceMappingURL=main.js.map
|
package/dist/main.js.map
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/core/signal-base.ts", "../src/core/event-signal.ts", "../src/core/state-signal.ts", "../src/core/computed-signal.ts", "../src/core/effect-signal.ts", "../src/core/persistent-state-signal.ts", "../src/core/session-state-signal.ts", "../src/creators/event.ts", "../src/creators/state.ts", "../src/creators/computed.ts", "../src/creators/effect.ts", "../src/creators/persistent-state.ts", "../src/creators/session-state.ts", "../src/operators/debounce.ts", "../src/operators/filter.ts", "../src/operators/map.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\n\n/**\n * An abstract base class for signal implementations.\n * It provides the core functionality for managing subscriptions (observers).\n *\n * @template T The type of data that the signal holds or dispatches.\n */\nexport abstract class SignalBase<T> {\n /**\n * The unique identifier for this signal instance.\n * Useful for debugging and logging.\n */\n public readonly name: string;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected abstract logger_: AlwatrLogger;\n\n /**\n * The list of observers (listeners) subscribed to this signal.\n * @protected\n */\n protected readonly
|
|
5
|
+
"import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\n\n/**\n * An abstract base class for signal implementations.\n * It provides the core functionality for managing subscriptions (observers).\n *\n * @template T The type of data that the signal holds or dispatches.\n */\nexport abstract class SignalBase<T> {\n /**\n * The unique identifier for this signal instance.\n * Useful for debugging and logging.\n */\n public readonly name: string;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected abstract logger_: AlwatrLogger;\n\n /**\n * The list of observers (listeners) subscribed to this signal.\n * @protected\n */\n protected readonly priorityObservers_ = new Set<Observer_<T>>();\n protected readonly observers_ = new Set<Observer_<T>>();\n\n /**\n * A flag indicating whether the signal has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n constructor(protected config_: SignalConfig) {\n this.name = config_.name;\n }\n\n /**\n * Removes a specific observer from the observers list.\n *\n * @param observer The observer instance to remove.\n * @protected\n */\n protected removeObserver_(observer: Observer_<T>): void {\n this.logger_.logMethod?.('removeObserver_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('removeObserver_', 'remove_observer_on_destroyed_signal');\n return;\n }\n\n this.priorityObservers_.delete(observer);\n this.observers_.delete(observer);\n }\n\n /**\n * Subscribes a listener function to this signal.\n *\n * The listener will be called whenever the signal is notified (e.g., when `dispatch` or `set` is called).\n *\n * @param callback The function to be called when the signal is dispatched.\n * @param options Subscription options to customize the behavior (e.g., `once`, `priority`).\n * @returns A `SubscribeResult` object with an `unsubscribe` method to remove the listener.\n */\n public subscribe(callback: ListenerCallback<T>, options?: SubscribeOptions): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe.base', options);\n this.checkDestroyed_();\n\n const observer: Observer_<T> = {callback, options};\n\n if (options?.priority) {\n this.priorityObservers_.add(observer);\n } else {\n this.observers_.add(observer);\n }\n\n // The returned unsubscribe function is a closure that calls the internal removal method.\n return {\n unsubscribe: (): void => this.removeObserver_(observer),\n };\n }\n\n /**\n * Notifies all registered observers about a new value.\n *\n * This method iterates through a snapshot of the current observers to prevent issues\n * with subscriptions changing during notification (e.g., an observer unsubscribing itself).\n *\n * @param value The new value to notify observers about.\n * @protected\n */\n protected notify_(value: T): void {\n this.logger_.logMethodArgs?.('notify_', value);\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('notify_', 'notify_on_destroyed_signal');\n return;\n }\n\n for (const observer of this.priorityObservers_) {\n this.executeObserver__(observer, value);\n }\n\n for (const observer of this.observers_) {\n this.executeObserver__(observer, value);\n }\n }\n\n /**\n * Executes a given observer's callback with the provided value, handling both synchronous and asynchronous callbacks.\n */\n private executeObserver__(observer: Observer_<T>, value: T): void {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\n try {\n const result = observer.callback(value);\n if (result instanceof Promise) {\n result.catch((err) => this.logger_.error('notify_', 'async_callback_failed', err, {observer}));\n }\n } catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\n }\n\n /**\n * Returns a Promise that resolves with the next value dispatched by the signal.\n * This provides an elegant way to wait for a single, future event using `async/await`.\n *\n * @returns A Promise that resolves with the next dispatched value.\n *\n * @example\n * async function onButtonClick() {\n * console.log('Waiting for the next signal...');\n * const nextValue = await mySignal.untilNext();\n * console.log('Signal received:', nextValue);\n * }\n */\n public untilNext(): Promise<T> {\n this.logger_.logMethod?.('untilNext');\n this.checkDestroyed_();\n return new Promise((resolve) => {\n this.subscribe(resolve, {\n once: true,\n priority: true, // Resolve the promise before other listeners are called.\n receivePrevious: false, // We only want the *next* value, not the current one.\n });\n });\n }\n\n /**\n * Destroys the signal, clearing all its listeners and making it inactive.\n *\n * After destruction, any interaction with the signal (like `subscribe` or `untilNext`)\n * will throw an error. This is crucial for preventing memory leaks by allowing\n * garbage collection of the signal and its observers.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy_', 'double_destroy_attempt');\n return;\n }\n this.isDestroyed__ = true;\n this.priorityObservers_.clear(); // Clear all priority observers.\n this.observers_.clear(); // Clear all normal observers.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as SignalConfig; // Help GC by breaking references.\n }\n\n /**\n * Throws an error if the signal has been destroyed.\n * This is a safeguard to prevent interaction with a defunct signal.\n * @protected\n */\n protected checkDestroyed_(): void {\n if (this.isDestroyed__) {\n this.logger_.accident('checkDestroyed_', 'attempt_to_use_destroyed_signal');\n throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`);\n }\n }\n}\n",
|
|
6
6
|
"import { delay } from '@alwatr/delay';\nimport { createLogger, type AlwatrLogger } from '@alwatr/logger';\n\nimport { SignalBase } from './signal-base.js';\n\nimport type { SignalConfig } from '../type.js';\n\n/**\n * A stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events. Defaults to `void` for events without a payload.\n *\n * @example\n * // Create a signal for user click events.\n * const onUserClick = new EventSignal<{ x: number, y: number }>({ name: 'on-user-click' });\n *\n * // Subscribe to the event.\n * onUserClick.subscribe(clickPosition => {\n * console.log(`User clicked at: ${clickPosition.x}, ${clickPosition.y}`);\n * });\n *\n * // Dispatch an event.\n * onUserClick.dispatch({ x: 100, y: 250 }); // Notifies the listener.\n *\n * // --- Example with no payload ---\n * const onAppReady = new EventSignal({ name: 'on-app-ready' });\n * onAppReady.subscribe(() => console.log('Application is ready!'));\n * onAppReady.dispatch(); // Notifies the listener.\n */\nexport class EventSignal<T = void> extends SignalBase<T> {\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_: AlwatrLogger;\n\n constructor(config: SignalConfig) {\n super(config);\n this.logger_ = createLogger(`event-signal:${this.name}`);\n this.logger_.logMethod?.('constructor');\n }\n\n /**\n * Dispatches an event with an optional payload to all active listeners.\n * The notification is scheduled as a microtask to prevent blocking and ensure\n * a consistent, non-blocking flow.\n *\n * @param payload The data to send with the event.\n */\n public dispatch(payload: T): void {\n this.logger_.logMethodArgs?.('dispatch', { payload });\n this.checkDestroyed_();\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(payload));\n }\n}\n",
|
|
7
7
|
"import { delay } from '@alwatr/delay';\nimport { createLogger, type AlwatrLogger } from '@alwatr/logger';\n\nimport { SignalBase } from './signal-base.js';\n\nimport type { StateSignalConfig, ListenerCallback, SubscribeOptions, SubscribeResult, IReadonlySignal } from '../type.js';\n\n/**\n * A stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n * @implements {IReadonlySignal<T>}\n *\n * @example\n * // Create a new state signal with an initial value.\n * const counter = new StateSignal<number>({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * // Get the current value.\n * console.log(counter.get()); // Outputs: 0\n *\n * // Subscribe to changes.\n * const subscription = counter.subscribe(newValue => {\n * console.log(`Counter changed to: ${newValue}`);\n * });\n *\n * // Set a new value, which triggers the notification.\n * counter.set(1); // Outputs: \"Counter changed to: 1\"\n *\n * // Update value based on the previous value.\n * counter.update(current => current + 1); // Outputs: \"Counter changed to: 2\"\n *\n * // Unsubscribe when no longer needed.\n * subscription.unsubscribe();\n */\nexport class StateSignal<T> extends SignalBase<T> implements IReadonlySignal<T> {\n /**\n * The current value of the signal.\n * @private\n */\n private value__: T;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_: AlwatrLogger;\n\n constructor(config: StateSignalConfig<T>) {\n super({\n name: config.name,\n onDestroy: config.onDestroy,\n });\n this.logger_ = createLogger(`state-signal:${this.name}`);\n this.value__ = config.initialValue;\n this.logger_.logMethodArgs?.('constructor', { initialValue: this.value__ });\n }\n\n /**\n * Retrieves the current value of the signal.\n *\n * @returns The current value.\n *\n * @example\n * console.log(mySignal.get());\n */\n public get(): T {\n this.checkDestroyed_();\n return this.value__;\n }\n\n /**\n * Updates the signal's value and notifies all active listeners.\n *\n * The notification is scheduled as a microtask, which means the update is deferred\n * slightly to batch multiple synchronous changes.\n *\n * @param newValue The new value to set.\n *\n * @example\n * // For primitive types\n * mySignal.set(42);\n *\n * // For object types, it's best practice to set an immutable new object.\n * mySignal.set({ ...mySignal.get(), property: 'new-value' });\n */\n public set(newValue: T): void {\n this.logger_.logMethodArgs?.('set', { newValue });\n this.checkDestroyed_();\n\n // For primitives (including null), do not notify if the value is the same.\n if (Object.is(this.value__, newValue) && (typeof newValue !== 'object' || newValue === null)) {\n return;\n }\n\n this.value__ = newValue;\n\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(newValue));\n }\n\n /**\n * Updates the signal's value based on its previous value.\n *\n * This method is particularly useful for state transitions that depend on the current value,\n * especially for objects or arrays, as it promotes an immutable update pattern.\n *\n * @param updater A function that receives the current value and returns the new value.\n *\n * @example\n * // For a counter\n * counterSignal.update(current => current + 1);\n *\n * // For an object state\n * userSignal.update(currentUser => ({ ...currentUser, loggedIn: true }));\n */\n public update(updater: (previousValue: T) => T): void {\n this.checkDestroyed_();\n const newValue = updater(this.value__);\n this.logger_.logMethodFull?.('update', this.value__, newValue);\n this.set(newValue);\n }\n\n /**\n * Subscribes a listener to this signal.\n *\n * By default, the listener is immediately called with the signal's current value (`receivePrevious: true`).\n * This behavior can be customized via the `options` parameter.\n *\n * @param callback The function to be called when the signal's value changes.\n * @param options Subscription options, including `receivePrevious` and `once`.\n * @returns An object with an `unsubscribe` method to remove the listener.\n */\n public override subscribe(callback: ListenerCallback<T>, options: SubscribeOptions = {}): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe', options);\n this.checkDestroyed_();\n\n // By default, new subscribers to a StateSignal should receive the current value.\n if (options.receivePrevious !== false) {\n // Immediately (but asynchronously) call the listener with the current value.\n // This is done in a microtask to ensure it happens after the subscription is fully registered.\n delay\n .nextMicrotask()\n .then(() => {\n this.logger_.logStep?.('subscribe', 'immediate_callback');\n callback(this.value__);\n })\n .catch((err) => this.logger_.error('subscribe', 'immediate_callback_failed', err));\n\n // If it's a 'once' subscription that receives the previous value, it's now fulfilled.\n // We don't need to add it to the observers list for future updates.\n if (options.once) {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return { unsubscribe: () => { } };\n }\n }\n\n return super.subscribe(callback, options);\n }\n\n /**\n * Destroys the signal, clearing its value and all listeners.\n * This is crucial for memory management to prevent leaks.\n */\n public override destroy(): void {\n this.value__ = null as T; // Clear the value to allow for garbage collection.\n super.destroy();\n }\n\n public asReadonly(): IReadonlySignal<T> {\n return this;\n }\n}\n",
|
|
8
8
|
"import { delay } from '@alwatr/delay';\nimport { createLogger, type AlwatrLogger } from '@alwatr/logger';\n\nimport { StateSignal } from './state-signal.js';\n\nimport type { ComputedSignalConfig, IReadonlySignal, SubscribeResult, SubscribeOptions } from '../type.js';\n\n/**\n * A read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @example\n * // --- Create dependency signals ---\n * const firstName = new StateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = new StateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * // --- Create a computed signal ---\n * const fullName = new ComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // Outputs: \"John Doe\"\n *\n * // --- Subscribe to the computed value ---\n * fullName.subscribe(newFullName => {\n * console.log(`Name changed to: ${newFullName}`);\n * });\n *\n * // --- Update a dependency ---\n * lastName.set('Smith'); // Recalculates and logs: \"Name changed to: John Smith\"\n * console.log(fullName.get()); // Outputs: \"John Smith\"\n *\n * // --- IMPORTANT: Clean up when done ---\n * fullName.destroy();\n */\nexport class ComputedSignal<T> implements IReadonlySignal<T> {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name: string;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_: AlwatrLogger;\n\n /**\n * The internal `StateSignal` that holds the computed value.\n * This is how the computed signal provides `.get()` and `.subscribe()` methods.\n * @protected\n */\n protected readonly internalSignal_: StateSignal<T>;\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent recalculations.\n * @private\n */\n private isRecalculating__ = false;\n\n constructor(protected config_: ComputedSignalConfig<T>) {\n this.name = config_.name;\n this.logger_ = createLogger(`computed-signal:${this.name}`);\n this.recalculate_ = this.recalculate_.bind(this);\n\n this.logger_.logMethod?.('constructor');\n\n this.internalSignal_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\n\n // Subscribe to all dependencies to trigger recalculation on change.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', { signal: signal.name });\n this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_, { receivePrevious: false }));\n }\n }\n\n /**\n * The current value of the computed signal.\n * Accessing this property returns the memoized value and does not trigger a recalculation.\n *\n * @returns The current computed value.\n * @throws {Error} If accessed after the signal has been destroyed.\n */\n public get(): T {\n return this.internalSignal_.get();\n }\n\n /**\n * Indicates whether the computed signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.internalSignal_.isDestroyed;\n }\n\n /**\n * Subscribes a listener to this signal.\n * The listener will be called whenever the computed value changes.\n *\n * @param callback The function to be called with the new value.\n * @param options Subscription options.\n * @returns A `SubscribeResult` object with an `unsubscribe` method.\n */\n public subscribe(callback: (value: T) => void, options?: SubscribeOptions): SubscribeResult {\n return this.internalSignal_.subscribe(callback, options);\n }\n\n /**\n * Returns a Promise that resolves with the next computed value.\n *\n * @returns A Promise that resolves with the next value.\n */\n public untilNext(): Promise<T> {\n return this.internalSignal_.untilNext();\n }\n\n /**\n * Permanently disposes of the computed signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping future recalculations and allowing the signal to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks.\n *\n * After `destroy()` is called, any attempt to access `.get()` or `.subscribe()` will throw an error.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n /**\n * If already destroyed, log an incident and return early.\n */\n if (this.isDestroyed) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.internalSignal_.destroy(); // Destroy the internal signal.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as ComputedSignalConfig<T>; // Release config closure.\n }\n\n /**\n * Schedules a recalculation of the signal's value.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `get` function runs only once per event loop tick, even if multiple dependencies\n * change in the same synchronous block of code.\n * @protected\n */\n protected async recalculate_(): Promise<void> {\n this.logger_.logMethod?.('recalculate_');\n\n if (this.internalSignal_.isDestroyed) {\n // This check is important in case a dependency fires after this signal is destroyed.\n this.logger_.incident?.('recalculate_', 'recalculate_on_destroyed_signal');\n return;\n }\n\n if (this.isRecalculating__) {\n // If a recalculation is already scheduled, do nothing.\n this.logger_.logStep?.('recalculate_', 'skipping_recalculation_already_scheduled');\n return;\n }\n\n this.isRecalculating__ = true;\n\n try {\n // Wait for the next macrotask to start the recalculation.\n // This batches all synchronous dependency updates in the current event loop.\n await delay.nextMacrotask();\n\n if (this.isDestroyed) {\n this.logger_.incident?.('recalculate_', 'destroyed_during_delay');\n this.isRecalculating__ = false;\n return;\n }\n\n this.logger_.logStep?.('recalculate_', 'recalculating_value');\n\n // Set the new value on the internal signal, which will notify our subscribers.\n this.internalSignal_.set(this.config_.get());\n }\n catch (err) {\n this.logger_.error('recalculate_', 'recalculation_failed', err);\n }\n\n // Allow the next recalculation to be scheduled.\n this.isRecalculating__ = false;\n }\n}\n",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"import {createComputedSignal} from '../creators/computed.js';\nimport {createStateSignal} from '../creators/state.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal} from '../type.js';\n\n/**\n * Creates a new computed signal that only emits values from a source signal\n * that satisfy a predicate function.\n *\n * This operator is analogous to `Array.prototype.filter`. It is particularly\n * useful for creating effects or other computed signals that should only react\n * to a specific subset of state changes.\n *\n * Note: The resulting signal's value will be `undefined` until the source\n * emits a value that passes the filter.\n *\n * @template T The type of the signal's value.\n *\n * @param sourceSignal The original signal to filter.\n * @param predicate A function that returns `true` if the value should be passed.\n * @param name An optional, unique identifier for the new signal for debugging. default: `${sourceSignal.name}-filtered`\n *\n * @returns A new computed signal that emits filtered values.\n *\n * @example\n * const numberSignal = createStateSignal({ name: 'number', initialValue: 0 });\n *\n * const evenNumberSignal = createFilteredSignal(\n * numberSignal,\n * (num) => num % 2 === 0,\n * );\n *\n * createEffect({\n * deps: [evenNumberSignal],\n * run: () => {\n * // This effect only runs for even numbers.\n * // The value can be `undefined` on the first run if initialValue is not even.\n * if (evenNumberSignal.get() !== undefined) {\n * console.log(`Even number detected: ${evenNumberSignal.get()}`);\n * }\n * },\n * runImmediately: true,\n * });\n * // Logs: \"Even number detected: 0\"\n *\n * numberSignal.set(1); // Effect does not run\n * numberSignal.set(2); // Logs: \"Even number detected: 2\"\n */\nexport function createFilteredSignal<T>(\n sourceSignal: IReadonlySignal<T>,\n predicate: (value: T) => boolean,\n name = `${sourceSignal.name}-filtered`,\n): ComputedSignal<T | undefined> {\n const sourceValue = sourceSignal.get();\n const initialValue = predicate(sourceValue) ? sourceValue : undefined;\n\n const internalSignal = createStateSignal({\n name: `${name}-internal`,\n initialValue,\n });\n\n const subscription = sourceSignal.subscribe((newValue) => {\n if (predicate(newValue)) {\n internalSignal.set(newValue);\n }\n });\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n subscription.unsubscribe();\n internalSignal.destroy();\n },\n });\n}\n",
|
|
20
20
|
"import {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal} from '../type.js';\n\n/**\n * Creates a new read-only computed signal that transforms the value of a source\n * signal using a projection function.\n *\n * This operator is analogous to `Array.prototype.map`. It applies a function to\n * each value emitted by the source signal and emits the result.\n *\n * @template T The type of the source signal's value.\n * @template R The type of the projected value.\n *\n * @param sourceSignal The original signal to transform.\n * @param projectFunction A function to apply to each value from the source signal.\n * @param [name] An optional, unique identifier for the new signal for debugging. default: `${sourceSignal.name}-mapped`\n *\n * @returns A new, read-only computed signal with the transformed values.\n *\n * @example\n * const userSignal = createStateSignal({\n * name: 'user',\n * initialValue: { name: 'John', age: 30 },\n * });\n *\n * const userNameSignal = createMappedSignal(\n * userSignal,\n * (user) => user.name,\n * );\n *\n * console.log(userNameSignal.get()); // Outputs: \"John\"\n * // in next macro-task ...\n * userSignal.set({ name: 'Jane', age: 32 });\n * console.log(userNameSignal.get()); // Outputs: \"Jane\"\n */\nexport function createMappedSignal<T, R>(\n sourceSignal: IReadonlySignal<T>,\n projectFunction: (value: T) => R,\n name = `${sourceSignal.name}-mapped`,\n): ComputedSignal<R> {\n return createComputedSignal({\n name: name,\n deps: [sourceSignal],\n get: () => projectFunction(sourceSignal.get()),\n });\n}\n"
|
|
21
21
|
],
|
|
22
|
-
"mappings": ";AASO,MAAe,CAAc,
|
|
23
|
-
"debugId": "
|
|
22
|
+
"mappings": ";AASO,MAAe,CAAc,CAoCZ,QA/BN,KAYG,mBAAqB,IAAI,IACzB,WAAa,IAAI,IAM5B,cAAgB,MAQb,YAAW,EAAY,CAChC,OAAO,KAAK,cAGd,WAAW,CAAW,EAAuB,CAAvB,eACpB,KAAK,KAAO,EAAQ,KASZ,eAAe,CAAC,EAA8B,CAGtD,GAFA,KAAK,QAAQ,YAAY,iBAAiB,EAEtC,KAAK,cAAe,CACtB,KAAK,QAAQ,WAAW,kBAAmB,qCAAqC,EAChF,OAGF,KAAK,mBAAmB,OAAO,CAAQ,EACvC,KAAK,WAAW,OAAO,CAAQ,EAY1B,SAAS,CAAC,EAA+B,EAA6C,CAC3F,KAAK,QAAQ,gBAAgB,iBAAkB,CAAO,EACtD,KAAK,gBAAgB,EAErB,IAAM,EAAyB,CAAC,WAAU,SAAO,EAEjD,GAAI,GAAS,SACX,KAAK,mBAAmB,IAAI,CAAQ,EAEpC,UAAK,WAAW,IAAI,CAAQ,EAI9B,MAAO,CACL,YAAa,IAAY,KAAK,gBAAgB,CAAQ,CACxD,EAYQ,OAAO,CAAC,EAAgB,CAGhC,GAFA,KAAK,QAAQ,gBAAgB,UAAW,CAAK,EAEzC,KAAK,cAAe,CACtB,KAAK,QAAQ,WAAW,UAAW,4BAA4B,EAC/D,OAGF,QAAW,KAAY,KAAK,mBAC1B,KAAK,kBAAkB,EAAU,CAAK,EAGxC,QAAW,KAAY,KAAK,WAC1B,KAAK,kBAAkB,EAAU,CAAK,EAOlC,iBAAiB,CAAC,EAAwB,EAAgB,CAChE,GAAI,EAAS,SAAS,KACpB,KAAK,gBAAgB,CAAQ,EAE/B,GAAI,CACF,IAAM,EA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B,IAAK,IAAM,EAAgB,EAAa,IAAI,CAAC,CAC/C,CAAC",
|
|
23
|
+
"debugId": "6E44E6DCC7E28F2164756E2164756E21",
|
|
24
24
|
"names": []
|
|
25
25
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/signal",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.4.0",
|
|
4
4
|
"description": "Alwatr Signal is a powerful, lightweight, and modern reactive programming library. It is inspired by the best concepts from major reactive libraries but engineered to be faster and more efficient than all of them. It provides a robust and elegant way to manage application state through a system of signals, offering fine-grained reactivity, predictability, and excellent performance.",
|
|
5
5
|
"license": "MPL-2.0",
|
|
6
6
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
|
|
@@ -21,15 +21,15 @@
|
|
|
21
21
|
},
|
|
22
22
|
"sideEffects": false,
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@alwatr/debounce": "9.
|
|
25
|
-
"@alwatr/delay": "9.
|
|
26
|
-
"@alwatr/local-storage": "9.
|
|
27
|
-
"@alwatr/logger": "9.
|
|
28
|
-
"@alwatr/session-storage": "9.
|
|
24
|
+
"@alwatr/debounce": "9.4.0",
|
|
25
|
+
"@alwatr/delay": "9.4.0",
|
|
26
|
+
"@alwatr/local-storage": "9.4.0",
|
|
27
|
+
"@alwatr/logger": "9.4.0",
|
|
28
|
+
"@alwatr/session-storage": "9.4.0"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@alwatr/nano-build": "9.3.0",
|
|
32
|
-
"@alwatr/standard": "9.
|
|
32
|
+
"@alwatr/standard": "9.4.0",
|
|
33
33
|
"@alwatr/type-helper": "9.1.1",
|
|
34
34
|
"typescript": "^6.0.2"
|
|
35
35
|
},
|
|
@@ -66,5 +66,5 @@
|
|
|
66
66
|
"signal",
|
|
67
67
|
"typescript"
|
|
68
68
|
],
|
|
69
|
-
"gitHead": "
|
|
69
|
+
"gitHead": "662f1047fc2a1b53a00902028d6cebfd04b52dd5"
|
|
70
70
|
}
|
package/src/core/signal-base.ts
CHANGED
|
@@ -24,7 +24,8 @@ export abstract class SignalBase<T> {
|
|
|
24
24
|
* The list of observers (listeners) subscribed to this signal.
|
|
25
25
|
* @protected
|
|
26
26
|
*/
|
|
27
|
-
protected readonly
|
|
27
|
+
protected readonly priorityObservers_ = new Set<Observer_<T>>();
|
|
28
|
+
protected readonly observers_ = new Set<Observer_<T>>();
|
|
28
29
|
|
|
29
30
|
/**
|
|
30
31
|
* A flag indicating whether the signal has been destroyed.
|
|
@@ -60,10 +61,8 @@ export abstract class SignalBase<T> {
|
|
|
60
61
|
return;
|
|
61
62
|
}
|
|
62
63
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
this.observers_.splice(index, 1);
|
|
66
|
-
}
|
|
64
|
+
this.priorityObservers_.delete(observer);
|
|
65
|
+
this.observers_.delete(observer);
|
|
67
66
|
}
|
|
68
67
|
|
|
69
68
|
/**
|
|
@@ -82,11 +81,9 @@ export abstract class SignalBase<T> {
|
|
|
82
81
|
const observer: Observer_<T> = {callback, options};
|
|
83
82
|
|
|
84
83
|
if (options?.priority) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
else {
|
|
89
|
-
this.observers_.push(observer);
|
|
84
|
+
this.priorityObservers_.add(observer);
|
|
85
|
+
} else {
|
|
86
|
+
this.observers_.add(observer);
|
|
90
87
|
}
|
|
91
88
|
|
|
92
89
|
// The returned unsubscribe function is a closure that calls the internal removal method.
|
|
@@ -112,24 +109,29 @@ export abstract class SignalBase<T> {
|
|
|
112
109
|
return;
|
|
113
110
|
}
|
|
114
111
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
112
|
+
for (const observer of this.priorityObservers_) {
|
|
113
|
+
this.executeObserver__(observer, value);
|
|
114
|
+
}
|
|
118
115
|
|
|
119
|
-
for (const observer of
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
116
|
+
for (const observer of this.observers_) {
|
|
117
|
+
this.executeObserver__(observer, value);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
123
120
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
121
|
+
/**
|
|
122
|
+
* Executes a given observer's callback with the provided value, handling both synchronous and asynchronous callbacks.
|
|
123
|
+
*/
|
|
124
|
+
private executeObserver__(observer: Observer_<T>, value: T): void {
|
|
125
|
+
if (observer.options?.once) {
|
|
126
|
+
this.removeObserver_(observer);
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
const result = observer.callback(value);
|
|
130
|
+
if (result instanceof Promise) {
|
|
131
|
+
result.catch((err) => this.logger_.error('notify_', 'async_callback_failed', err, {observer}));
|
|
132
132
|
}
|
|
133
|
+
} catch (err) {
|
|
134
|
+
this.logger_.error('notify_', 'sync_callback_failed', err);
|
|
133
135
|
}
|
|
134
136
|
}
|
|
135
137
|
|
|
@@ -172,7 +174,8 @@ export abstract class SignalBase<T> {
|
|
|
172
174
|
return;
|
|
173
175
|
}
|
|
174
176
|
this.isDestroyed__ = true;
|
|
175
|
-
this.
|
|
177
|
+
this.priorityObservers_.clear(); // Clear all priority observers.
|
|
178
|
+
this.observers_.clear(); // Clear all normal observers.
|
|
176
179
|
this.config_.onDestroy?.(); // Call the optional onDestroy callback.
|
|
177
180
|
this.config_ = null as unknown as SignalConfig; // Help GC by breaking references.
|
|
178
181
|
}
|