@alwatr/signal 6.0.2 → 6.1.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/CHANGELOG.md +30 -0
- package/dist/core/persistent-state-signal.d.ts +45 -0
- package/dist/core/persistent-state-signal.d.ts.map +1 -0
- package/dist/core/state-signal.d.ts.map +1 -1
- package/dist/creators/persistent-state.d.ts +30 -0
- package/dist/creators/persistent-state.d.ts.map +1 -0
- package/dist/main.cjs +3 -3
- package/dist/main.cjs.map +4 -4
- package/dist/main.d.ts +4 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.mjs +3 -3
- package/dist/main.mjs.map +4 -4
- package/dist/type.d.ts +20 -2
- package/dist/type.d.ts.map +1 -1
- package/package.json +8 -7
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,36 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
## [6.1.0](https://github.com/Alwatr/flux/compare/v6.0.2...v6.1.0) (2025-09-22)
|
|
7
|
+
|
|
8
|
+
### ✨ Features
|
|
9
|
+
|
|
10
|
+
* add createPersistentStateSignal function for localStorage state management ([05c99bd](https://github.com/Alwatr/flux/commit/05c99bdef47fd285f0c1dc1017c511f411d0405b))
|
|
11
|
+
* add PersistentStateSignalConfig for local storage integration ([5dc1dfb](https://github.com/Alwatr/flux/commit/5dc1dfbc961d3820c2d765dedcb9d29909bbeab4))
|
|
12
|
+
* add saveDebounceDelay option to PersistentStateSignalConfig for optimized localStorage writes ([ebc542e](https://github.com/Alwatr/flux/commit/ebc542e496cfcdfe06d74abeb08a4e1c4f4ec8b6))
|
|
13
|
+
* implement debouncing for localStorage writes in PersistentStateSignal ([9644b37](https://github.com/Alwatr/flux/commit/9644b37f6d2c8b2b0cd8a27b0b4ce0ad4afa86a3))
|
|
14
|
+
* implement PersistentStateSignal for localStorage persistence ([0303a74](https://github.com/Alwatr/flux/commit/0303a744408d5e7188daf811bc3109c9c22fd156))
|
|
15
|
+
|
|
16
|
+
### 🐛 Bug Fixes
|
|
17
|
+
|
|
18
|
+
* enhance set method in PersistentStateSignal to support data type conversion ([3970fc1](https://github.com/Alwatr/flux/commit/3970fc17d90d72f124114b29b879b423934101a9))
|
|
19
|
+
* refine generic type constraint in PersistentStateSignalConfig to extend JsonValue ([d50a1fb](https://github.com/Alwatr/flux/commit/d50a1fb880d0816ccda13eaea1ddfa9b13e89f6d))
|
|
20
|
+
* refine generic type handling in PersistentStateSignal and syncStorage method ([30c50a8](https://github.com/Alwatr/flux/commit/30c50a8d3e24b742529aa3def0bfe0fde6561e4a))
|
|
21
|
+
* remove unnecessary comments from EffectSignalConfig and DebounceSignalConfig interfaces ([397692c](https://github.com/Alwatr/flux/commit/397692c361b8f0faa6443379c1bdefba74fb88a3))
|
|
22
|
+
* remove unnecessary constraint on generic type T in PersistentStateSignal ([83aab63](https://github.com/Alwatr/flux/commit/83aab637f4e7a9c976769b0bf64f89371da0b83a))
|
|
23
|
+
* update exports to include persistent state signal and related creators/operators ([2eb94fa](https://github.com/Alwatr/flux/commit/2eb94fa8683ee0d74b609b36415de3e039b364a5))
|
|
24
|
+
* update PersistentStateSignal to serialize values correctly and improve logging ([65947d4](https://github.com/Alwatr/flux/commit/65947d4a2b0c28b43fa3b0d15ea63e08d23d91c7))
|
|
25
|
+
* update StateSignal constructor to properly pass config parameters ([f1b4cf0](https://github.com/Alwatr/flux/commit/f1b4cf02103f97295eb7f76155012c27b9773a8a))
|
|
26
|
+
* update storageDebouncer to be readonly and adjust syncStorage method signature ([575b127](https://github.com/Alwatr/flux/commit/575b127e6367461cd3d6928ff73e395ed23bf459))
|
|
27
|
+
* update storageKey handling in PersistentStateSignal and createFsmService for improved state management ([42e764f](https://github.com/Alwatr/flux/commit/42e764f58a2f804c6082a46bfb96eb678a49c22a))
|
|
28
|
+
|
|
29
|
+
### 🔗 Dependencies update
|
|
30
|
+
|
|
31
|
+
* add @alwatr/local-storage as a dependency ([47b60fa](https://github.com/Alwatr/flux/commit/47b60fa3844fc49ccb85bc612e102c801a47ef1b))
|
|
32
|
+
* update @alwatr/local-storage to version 6.3.0 ([1b10f57](https://github.com/Alwatr/flux/commit/1b10f578d8c817da8472f18a8c9d8e7520a0a7f4))
|
|
33
|
+
* update dependencies to latest versions across packages ([97bd715](https://github.com/Alwatr/flux/commit/97bd71555912053f8b2ba6ad0578b74bf7f1c1d3))
|
|
34
|
+
* update package dependencies for @alwatr/yarn-upgrade, @alwatr/logger, and other packages ([96b56e7](https://github.com/Alwatr/flux/commit/96b56e75360411bed73ce84acb870db6153f8917))
|
|
35
|
+
|
|
6
36
|
## [6.0.2](https://github.com/Alwatr/flux/compare/v6.0.1...v6.0.2) (2025-09-21)
|
|
7
37
|
|
|
8
38
|
### 🔗 Dependencies update
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { StateSignal } from './state-signal.js';
|
|
2
|
+
import type { PersistentStateSignalConfig } from '../type.js';
|
|
3
|
+
/**
|
|
4
|
+
* A stateful signal that persists its value in the browser's localStorage.
|
|
5
|
+
*
|
|
6
|
+
* It extends the functionality of a standard `StateSignal` by automatically reading
|
|
7
|
+
* its initial value from localStorage and writing back any subsequent changes.
|
|
8
|
+
*
|
|
9
|
+
* @template T The type of the state it holds.
|
|
10
|
+
*/
|
|
11
|
+
export declare class PersistentStateSignal<T extends JsonValue> extends StateSignal<T> {
|
|
12
|
+
/**
|
|
13
|
+
* The underlying storage provider instance.
|
|
14
|
+
* @private
|
|
15
|
+
*/
|
|
16
|
+
private readonly storageProvider__;
|
|
17
|
+
/**
|
|
18
|
+
* Debouncer to limit how often we write to localStorage.
|
|
19
|
+
* @private
|
|
20
|
+
*/
|
|
21
|
+
private readonly storageDebouncer__;
|
|
22
|
+
/**
|
|
23
|
+
* The subscription to the signal's own changes to sync with storage.
|
|
24
|
+
* We subscribe to our own signal. When the value is set from anywhere,
|
|
25
|
+
* this listener will trigger and write it to localStorage.
|
|
26
|
+
* @private
|
|
27
|
+
*/
|
|
28
|
+
private readonly storageSyncSubscription__;
|
|
29
|
+
constructor(config: PersistentStateSignalConfig<T>);
|
|
30
|
+
/**
|
|
31
|
+
* Syncs the new value to storage.
|
|
32
|
+
* @param newValue The new value to sync to storage.
|
|
33
|
+
*/
|
|
34
|
+
private syncStorage__;
|
|
35
|
+
/**
|
|
36
|
+
* Removes the value from localStorage.
|
|
37
|
+
* This provides a clean way to clear persisted data.
|
|
38
|
+
*/
|
|
39
|
+
remove(): void;
|
|
40
|
+
/**
|
|
41
|
+
* Overrides the destroy method to also clean up the storage sync subscription.
|
|
42
|
+
*/
|
|
43
|
+
destroy(): void;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=persistent-state-signal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"persistent-state-signal.d.ts","sourceRoot":"","sources":["../../src/core/persistent-state-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,WAAW,EAAC,MAAM,mBAAmB,CAAC;AAE9C,OAAO,KAAK,EAAC,2BAA2B,EAAC,MAAM,YAAY,CAAC;AAG5D;;;;;;;GAOG;AACH,qBAAa,qBAAqB,CAAC,CAAC,SAAS,SAAS,CAAE,SAAQ,WAAW,CAAC,CAAC,CAAC;IAC5E;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAA0B;IAE5D;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAC;IAEpC;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAAC;gBAE/B,MAAM,EAAE,2BAA2B,CAAC,CAAC,CAAC;IAyClD;;;OAGG;IACH,OAAO,CAAC,aAAa;IAKrB;;;OAGG;IACI,MAAM,IAAI,IAAI;IAOrB;;OAEG;IACa,OAAO,IAAI,IAAI;CAQhC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state-signal.d.ts","sourceRoot":"","sources":["../../src/core/state-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAC,iBAAiB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAC,MAAM,YAAY,CAAC;AAExH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,WAAW,CAAC,CAAC,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAE,YAAW,eAAe,CAAC,CAAC,CAAC;IAC7E;;;OAGG;IACH,OAAO,CAAC,OAAO,CAAI;IAEnB;;;OAGG;IACH,SAAS,CAAC,OAAO,wCAA6C;gBAElD,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"state-signal.d.ts","sourceRoot":"","sources":["../../src/core/state-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAC,iBAAiB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAC,MAAM,YAAY,CAAC;AAExH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,WAAW,CAAC,CAAC,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAE,YAAW,eAAe,CAAC,CAAC,CAAC;IAC7E;;;OAGG;IACH,OAAO,CAAC,OAAO,CAAI;IAEnB;;;OAGG;IACH,SAAS,CAAC,OAAO,wCAA6C;gBAElD,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;IASxC;;;;;;;OAOG;IACI,GAAG,IAAI,CAAC;IAKf;;;;;;;;;;;;;;OAcG;IACI,GAAG,CAAC,QAAQ,EAAE,CAAC,GAAG,IAAI;IAe7B;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,OAAO,EAAE,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI;IAOrD;;;;;;;;;OASG;IACa,SAAS,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAAE,OAAO,GAAE,gBAAqB,GAAG,eAAe;IA2BzG;;;OAGG;IACa,OAAO,IAAI,IAAI;IAKxB,UAAU,IAAI,eAAe,CAAC,CAAC,CAAC;CAGxC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { PersistentStateSignal } from '../core/persistent-state-signal.js';
|
|
2
|
+
import type { PersistentStateSignalConfig } from '../type.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a stateful signal that persists its value in localStorage.
|
|
5
|
+
*
|
|
6
|
+
* This function provides a clean, declarative API for creating state that
|
|
7
|
+
* survives page reloads. It automatically handles reading the initial state
|
|
8
|
+
* from localStorage and saving subsequent updates.
|
|
9
|
+
*
|
|
10
|
+
* @template T The type of the state it holds.
|
|
11
|
+
*
|
|
12
|
+
* @param {PersistentStateSignalConfig<T>} config The configuration for the persistent state signal.
|
|
13
|
+
* @returns {PersistentStateSignal<T>} A new instance of PersistentStateSignal.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* // Create a signal to store user's preferred theme.
|
|
17
|
+
* const userThemeSignal = createPersistentStateSignal<string>({
|
|
18
|
+
* name: 'user-theme',
|
|
19
|
+
* schemaVersion: 1,
|
|
20
|
+
* defaultValue: 'light',
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* // The initial value is read from localStorage, or 'light' if not present.
|
|
24
|
+
* console.log(userThemeSignal.get());
|
|
25
|
+
*
|
|
26
|
+
* // Setting a new value updates the in-memory state and writes to localStorage.
|
|
27
|
+
* userThemeSignal.set('dark');
|
|
28
|
+
*/
|
|
29
|
+
export declare function createPersistentStateSignal<T extends JsonValue>(config: PersistentStateSignalConfig<T>): PersistentStateSignal<T>;
|
|
30
|
+
//# sourceMappingURL=persistent-state.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"persistent-state.d.ts","sourceRoot":"","sources":["../../src/creators/persistent-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,qBAAqB,EAAC,MAAM,oCAAoC,CAAC;AAEzE,OAAO,KAAK,EAAC,2BAA2B,EAAC,MAAM,YAAY,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,2BAA2B,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,2BAA2B,CAAC,CAAC,CAAC,GAAG,qBAAqB,CAAC,CAAC,CAAC,CAEjI"}
|
package/dist/main.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** 📦 @alwatr/signal v6.0
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/signal v6.0
|
|
3
|
-
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{ComputedSignal:()=>ComputedSignal,EffectSignal:()=>EffectSignal,EventSignal:()=>EventSignal,SignalBase:()=>SignalBase,StateSignal:()=>StateSignal,createComputedSignal:()=>createComputedSignal,createDebouncedSignal:()=>createDebouncedSignal,createEffect:()=>createEffect,createEventSignal:()=>createEventSignal,createStateSignal:()=>createStateSignal});module.exports=__toCommonJS(main_exports);var SignalBase=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.observers_=[];this.isDestroyed__=false}get isDestroyed(){return this.isDestroyed__}removeObserver_(observer){this.logger_.logMethod?.("removeObserver_");if(this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}const index=this.observers_.indexOf(observer);if(index!==-1){this.observers_.splice(index,1)}}subscribe(callback,options){this.logger_.logMethodArgs?.("subscribe.base",options);this.checkDestroyed_();const observer={callback,options};if(options?.priority){this.observers_.unshift(observer)}else{this.observers_.push(observer)}return{unsubscribe:()=>this.removeObserver_(observer)}}notify_(value){this.logger_.logMethodArgs?.("notify_",value);if(this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}const currentObservers=[...this.observers_];for(const observer of currentObservers){if(observer.options?.once){this.removeObserver_(observer)}try{const result=observer.callback(value);if(result instanceof Promise){result.catch(err=>this.logger_.error("notify_","async_callback_failed",err,{observer}))}}catch(err){this.logger_.error("notify_","sync_callback_failed",err)}}}untilNext(){this.logger_.logMethod?.("untilNext");this.checkDestroyed_();return new Promise(resolve=>{this.subscribe(resolve,{once:true,priority:true,receivePrevious:false})})}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}this.isDestroyed__=true;this.observers_.length=0;this.config_.onDestroy?.();this.config_=null}checkDestroyed_(){if(this.isDestroyed__){this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal");throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}};var import_delay=require("@alwatr/delay");var import_logger=require("@alwatr/logger");var EventSignal=class extends SignalBase{constructor(config){super(config);this.logger_=(0,import_logger.createLogger)(`event-signal:${this.name}`);this.logger_.logMethod?.("constructor")}dispatch(payload){this.logger_.logMethodArgs?.("dispatch",{payload});this.checkDestroyed_();import_delay.delay.nextMicrotask().then(()=>this.notify_(payload))}};var import_delay2=require("@alwatr/delay");var import_logger2=require("@alwatr/logger");var StateSignal=class extends SignalBase{constructor(config){super(config);this.logger_=(0,import_logger2.createLogger)(`state-signal:${this.name}`);this.value__=config.initialValue;this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){this.checkDestroyed_();return this.value__}set(newValue){this.logger_.logMethodArgs?.("set",{newValue});this.checkDestroyed_();if(Object.is(this.value__,newValue)&&(typeof newValue!=="object"||newValue===null)){return}this.value__=newValue;import_delay2.delay.nextMicrotask().then(()=>this.notify_(newValue))}update(updater){this.checkDestroyed_();const newValue=updater(this.value__);this.logger_.logMethodFull?.("update",this.value__,newValue);this.set(newValue)}subscribe(callback,options={}){this.logger_.logMethodArgs?.("subscribe",options);this.checkDestroyed_();if(options.receivePrevious!==false){import_delay2.delay.nextMicrotask().then(()=>{this.logger_.logStep?.("subscribe","immediate_callback");callback(this.value__)}).catch(err=>this.logger_.error("subscribe","immediate_callback_failed",err));if(options.once){return{unsubscribe:()=>{}}}}return super.subscribe(callback,options)}destroy(){this.value__=null;super.destroy()}asReadonly(){return this}};var import_delay3=require("@alwatr/delay");var import_logger3=require("@alwatr/logger");var ComputedSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.logger_=(0,import_logger3.createLogger)(`computed-signal:${this.name}`);this.internalSignal_=new StateSignal({name:`compute-${this.name}_`,initialValue:this.config_.get()});this.dependencySubscriptions__=[];this.isRecalculating__=false;this.logger_.logMethod?.("constructor");this.recalculate_=this.recalculate_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_,{receivePrevious:false}))}}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(callback,options){return this.internalSignal_.subscribe(callback,options)}untilNext(){return this.internalSignal_.untilNext()}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.internalSignal_.destroy();this.config_.onDestroy?.();this.config_=null}async recalculate_(){this.logger_.logMethod?.("recalculate_");if(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__=true;try{await import_delay3.delay.nextMacrotask();if(this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay");this.isRecalculating__=false;return}this.logger_.logStep?.("recalculate_","recalculating_value");this.internalSignal_.set(this.config_.get())}catch(err){this.logger_.error("recalculate_","recalculation_failed",err)}this.isRecalculating__=false}};var import_delay4=require("@alwatr/delay");var import_logger4=require("@alwatr/logger");var EffectSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name??`[${this.config_.deps.map(dep=>dep.name).join(", ")}]`;this.logger_=(0,import_logger4.createLogger)(`effect-signal:${this.name}`);this.dependencySubscriptions__=[];this.isRunning__=false;this.isDestroyed__=false;this.logger_.logMethod?.("constructor");this.scheduleExecution_=this.scheduleExecution_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_,{receivePrevious:false}))}if(config_.runImmediately===true){this.logger_.logStep?.("constructor","scheduling_initial_execution");void this.scheduleExecution_()}}get isDestroyed(){return this.isDestroyed__}async scheduleExecution_(){this.logger_.logMethod?.("scheduleExecution_");if(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__=true;try{await import_delay4.delay.nextMacrotask();if(this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay");this.isRunning__=false;return}this.logger_.logStep?.("scheduleExecution_","executing_effect");await this.config_.run()}catch(err){this.logger_.error("scheduleExecution_","effect_failed",err)}this.isRunning__=false}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=true;for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.config_.onDestroy?.();this.config_=null}};function createEventSignal(config){return new EventSignal(config)}function createStateSignal(config){return new StateSignal(config)}function createComputedSignal(config){return new ComputedSignal(config)}function createEffect(config){return new EffectSignal(config)}var import_debounce=require("@alwatr/debounce");function createDebouncedSignal(sourceSignal,config){const name=config.name??`${sourceSignal.name}-debounced`;const internalSignal=new StateSignal({name:`${name}-internal`,initialValue:sourceSignal.get()});const debouncer=(0,import_debounce.createDebouncer)({...config,func:value=>{internalSignal.set(value)}});const subscription=sourceSignal.subscribe(value=>debouncer.trigger(value),{receivePrevious:false});return createComputedSignal({name,deps:[internalSignal],get:()=>internalSignal.get(),onDestroy:()=>{if(internalSignal.isDestroyed)return;subscription.unsubscribe();debouncer.cancel();internalSignal.destroy();config.onDestroy?.();config=null}})}0&&(module.exports={ComputedSignal,EffectSignal,EventSignal,SignalBase,StateSignal,createComputedSignal,createDebouncedSignal,createEffect,createEventSignal,createStateSignal});
|
|
1
|
+
/** 📦 @alwatr/signal v6.1.0 */
|
|
2
|
+
__dev_mode__: console.debug("📦 @alwatr/signal v6.1.0");
|
|
3
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{ComputedSignal:()=>ComputedSignal,EffectSignal:()=>EffectSignal,EventSignal:()=>EventSignal,PersistentStateSignal:()=>PersistentStateSignal,SignalBase:()=>SignalBase,StateSignal:()=>StateSignal,createComputedSignal:()=>createComputedSignal,createDebouncedSignal:()=>createDebouncedSignal,createEffect:()=>createEffect,createEventSignal:()=>createEventSignal,createFilteredSignal:()=>createFilteredSignal,createMappedSignal:()=>createMappedSignal,createPersistentStateSignal:()=>createPersistentStateSignal,createStateSignal:()=>createStateSignal});module.exports=__toCommonJS(main_exports);var SignalBase=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.observers_=[];this.isDestroyed__=false}get isDestroyed(){return this.isDestroyed__}removeObserver_(observer){this.logger_.logMethod?.("removeObserver_");if(this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}const index=this.observers_.indexOf(observer);if(index!==-1){this.observers_.splice(index,1)}}subscribe(callback,options){this.logger_.logMethodArgs?.("subscribe.base",options);this.checkDestroyed_();const observer={callback,options};if(options?.priority){this.observers_.unshift(observer)}else{this.observers_.push(observer)}return{unsubscribe:()=>this.removeObserver_(observer)}}notify_(value){this.logger_.logMethodArgs?.("notify_",value);if(this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}const currentObservers=[...this.observers_];for(const observer of currentObservers){if(observer.options?.once){this.removeObserver_(observer)}try{const result=observer.callback(value);if(result instanceof Promise){result.catch(err=>this.logger_.error("notify_","async_callback_failed",err,{observer}))}}catch(err){this.logger_.error("notify_","sync_callback_failed",err)}}}untilNext(){this.logger_.logMethod?.("untilNext");this.checkDestroyed_();return new Promise(resolve=>{this.subscribe(resolve,{once:true,priority:true,receivePrevious:false})})}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}this.isDestroyed__=true;this.observers_.length=0;this.config_.onDestroy?.();this.config_=null}checkDestroyed_(){if(this.isDestroyed__){this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal");throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}};var import_delay=require("@alwatr/delay");var import_logger=require("@alwatr/logger");var EventSignal=class extends SignalBase{constructor(config){super(config);this.logger_=(0,import_logger.createLogger)(`event-signal:${this.name}`);this.logger_.logMethod?.("constructor")}dispatch(payload){this.logger_.logMethodArgs?.("dispatch",{payload});this.checkDestroyed_();import_delay.delay.nextMicrotask().then(()=>this.notify_(payload))}};var import_delay2=require("@alwatr/delay");var import_logger2=require("@alwatr/logger");var StateSignal=class extends SignalBase{constructor(config){super({name:config.name,onDestroy:config.onDestroy});this.logger_=(0,import_logger2.createLogger)(`state-signal:${this.name}`);this.value__=config.initialValue;this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){this.checkDestroyed_();return this.value__}set(newValue){this.logger_.logMethodArgs?.("set",{newValue});this.checkDestroyed_();if(Object.is(this.value__,newValue)&&(typeof newValue!=="object"||newValue===null)){return}this.value__=newValue;import_delay2.delay.nextMicrotask().then(()=>this.notify_(newValue))}update(updater){this.checkDestroyed_();const newValue=updater(this.value__);this.logger_.logMethodFull?.("update",this.value__,newValue);this.set(newValue)}subscribe(callback,options={}){this.logger_.logMethodArgs?.("subscribe",options);this.checkDestroyed_();if(options.receivePrevious!==false){import_delay2.delay.nextMicrotask().then(()=>{this.logger_.logStep?.("subscribe","immediate_callback");callback(this.value__)}).catch(err=>this.logger_.error("subscribe","immediate_callback_failed",err));if(options.once){return{unsubscribe:()=>{}}}}return super.subscribe(callback,options)}destroy(){this.value__=null;super.destroy()}asReadonly(){return this}};var import_delay3=require("@alwatr/delay");var import_logger3=require("@alwatr/logger");var ComputedSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.logger_=(0,import_logger3.createLogger)(`computed-signal:${this.name}`);this.internalSignal_=new StateSignal({name:`compute-${this.name}_`,initialValue:this.config_.get()});this.dependencySubscriptions__=[];this.isRecalculating__=false;this.logger_.logMethod?.("constructor");this.recalculate_=this.recalculate_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_,{receivePrevious:false}))}}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(callback,options){return this.internalSignal_.subscribe(callback,options)}untilNext(){return this.internalSignal_.untilNext()}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.internalSignal_.destroy();this.config_.onDestroy?.();this.config_=null}async recalculate_(){this.logger_.logMethod?.("recalculate_");if(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__=true;try{await import_delay3.delay.nextMacrotask();if(this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay");this.isRecalculating__=false;return}this.logger_.logStep?.("recalculate_","recalculating_value");this.internalSignal_.set(this.config_.get())}catch(err){this.logger_.error("recalculate_","recalculation_failed",err)}this.isRecalculating__=false}};var import_delay4=require("@alwatr/delay");var import_logger4=require("@alwatr/logger");var EffectSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name??`[${this.config_.deps.map(dep=>dep.name).join(", ")}]`;this.logger_=(0,import_logger4.createLogger)(`effect-signal:${this.name}`);this.dependencySubscriptions__=[];this.isRunning__=false;this.isDestroyed__=false;this.logger_.logMethod?.("constructor");this.scheduleExecution_=this.scheduleExecution_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_,{receivePrevious:false}))}if(config_.runImmediately===true){this.logger_.logStep?.("constructor","scheduling_initial_execution");void this.scheduleExecution_()}}get isDestroyed(){return this.isDestroyed__}async scheduleExecution_(){this.logger_.logMethod?.("scheduleExecution_");if(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__=true;try{await import_delay4.delay.nextMacrotask();if(this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay");this.isRunning__=false;return}this.logger_.logStep?.("scheduleExecution_","executing_effect");await this.config_.run()}catch(err){this.logger_.error("scheduleExecution_","effect_failed",err)}this.isRunning__=false}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=true;for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.config_.onDestroy?.();this.config_=null}};var import_debounce=require("@alwatr/debounce");var import_local_storage=require("@alwatr/local-storage");var PersistentStateSignal=class extends StateSignal{constructor(config){config.storageKey??=config.name;config.saveDebounceDelay??=500;const storageProvider=(0,import_local_storage.createLocalStorageProvider)({name:config.storageKey,schemaVersion:config.schemaVersion,defaultValue:config.defaultValue});const initialValue=storageProvider.read();super({name:config.name,initialValue,onDestroy:config.onDestroy});this.logger_.logMethodArgs?.("constructor",{name:config.name,schemaVersion:config.schemaVersion,initialValue});this.storageProvider__=storageProvider;this.storageDebouncer__=(0,import_debounce.createDebouncer)({delay:config.saveDebounceDelay,leading:false,trailing:true,thisContext:this,func:this.syncStorage__});this.storageSyncSubscription__=this.subscribe(this.storageDebouncer__.trigger,{receivePrevious:false})}syncStorage__(newValue){this.logger_.logMethodArgs?.("syncStorage__",newValue);this.storageProvider__.write(newValue)}remove(){this.checkDestroyed_();this.logger_.logMethod?.("remove");this.storageProvider__.remove()}destroy(){this.logger_.logMethod?.("destroy");this.storageDebouncer__.flush();this.storageSyncSubscription__.unsubscribe();super.destroy()}};function createEventSignal(config){return new EventSignal(config)}function createStateSignal(config){return new StateSignal(config)}function createComputedSignal(config){return new ComputedSignal(config)}function createEffect(config){return new EffectSignal(config)}function createPersistentStateSignal(config){return new PersistentStateSignal(config)}var import_debounce2=require("@alwatr/debounce");function createDebouncedSignal(sourceSignal,config){const name=config.name??`${sourceSignal.name}-debounced`;const internalSignal=new StateSignal({name:`${name}-internal`,initialValue:sourceSignal.get()});const debouncer=(0,import_debounce2.createDebouncer)({...config,func:value=>{internalSignal.set(value)}});const subscription=sourceSignal.subscribe(value=>debouncer.trigger(value),{receivePrevious:false});return createComputedSignal({name,deps:[internalSignal],get:()=>internalSignal.get(),onDestroy:()=>{if(internalSignal.isDestroyed)return;subscription.unsubscribe();debouncer.cancel();internalSignal.destroy();config.onDestroy?.();config=null}})}function createFilteredSignal(sourceSignal,predicate,name=`${sourceSignal.name}-filtered`){const sourceValue=sourceSignal.get();const initialValue=predicate(sourceValue)?sourceValue:void 0;const internalSignal=createStateSignal({name:`${name}-internal`,initialValue});const subscription=sourceSignal.subscribe(newValue=>{if(predicate(newValue)){internalSignal.set(newValue)}});return createComputedSignal({name,deps:[internalSignal],get:()=>internalSignal.get(),onDestroy:()=>{subscription.unsubscribe();internalSignal.destroy()}})}function createMappedSignal(sourceSignal,projectFunction,name=`${sourceSignal.name}-mapped`){return createComputedSignal({name,deps:[sourceSignal],get:()=>projectFunction(sourceSignal.get())})}0&&(module.exports={ComputedSignal,EffectSignal,EventSignal,PersistentStateSignal,SignalBase,StateSignal,createComputedSignal,createDebouncedSignal,createEffect,createEventSignal,createFilteredSignal,createMappedSignal,createPersistentStateSignal,createStateSignal});
|
|
4
4
|
//# sourceMappingURL=main.cjs.map
|
package/dist/main.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/main.ts", "../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/creators/event.ts", "../src/creators/state.ts", "../src/creators/computed.ts", "../src/creators/effect.ts", "../src/operators/debounce.ts"],
|
|
4
|
-
"sourcesContent": ["export * from './core/signal-base.js';\nexport * from './core/event-signal.js';\nexport * from './core/state-signal.js';\nexport * from './core/computed-signal.js';\nexport * from './core/effect-signal.js';\n\nexport * from './creators/event.js';\nexport * from './creators/state.js';\nexport * from './creators/computed.js';\nexport * from './creators/effect.js';\n\nexport * from './operators/debounce.js';\n\nexport type * from './type.js';\n", "import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\nimport type {} from '@alwatr/nano-build';\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 = this.config_.name;\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 observers_: 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\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 const index = this.observers_.indexOf(observer);\n if (index !== -1) {\n this.observers_.splice(index, 1);\n }\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 // High-priority observers are added to the front of the queue.\n this.observers_.unshift(observer);\n }\n else {\n this.observers_.push(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 // Create a snapshot of the observers array to iterate over.\n // This prevents issues if the observers_ array is modified during the loop.\n const currentObservers = [...this.observers_];\n\n for (const observer of currentObservers) {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\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 }\n catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\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.observers_.length = 0; // Clear all 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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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_ = createLogger(`event-signal:${this.name}`);\n\n constructor(config: SignalConfig) {\n super(config);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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_ = createLogger(`state-signal:${this.name}`);\n\n constructor(config: StateSignalConfig<T>) {\n super(config);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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 = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`computed-signal:${this.name}`);\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_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\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.logger_.logMethod?.('constructor');\n this.recalculate_ = this.recalculate_.bind(this);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport type {EffectSignalConfig, IEffectSignal, SubscribeResult} from '../type.js';\n\n/**\n * Manages a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @implements {IEffectSignal}\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = new StateSignal({ initialValue: 0, name: 'counter' });\n * const user = new StateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = new EffectSignal({\n * name: 'analytics-effect',\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport class EffectSignal implements IEffectSignal {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name ?? `[${this.config_.deps.map((dep) => dep.name).join(', ')}]`;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`effect-signal:${this.name}`);\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent executions of the effect.\n * @private\n */\n private isRunning__ = false;\n\n /**\n * A flag indicating whether the effect has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the effect signal has been destroyed.\n * A destroyed signal will no longer execute its effect and cannot be reused.\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_: EffectSignalConfig) {\n this.logger_.logMethod?.('constructor');\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n // Subscribe to all dependencies. We don't need the previous value,\n // as the `runImmediately` option controls the initial execution.\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.scheduleExecution_, {receivePrevious: false}));\n }\n\n // Run the effect immediately if requested.\n if (config_.runImmediately === true) {\n this.logger_.logStep?.('constructor', 'scheduling_initial_execution');\n // We don't need to await this, let it run in the background.\n void this.scheduleExecution_();\n }\n }\n\n /**\n * Schedules the execution of the effect's `run` function.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `run` function executes only once per event loop tick, even if multiple\n * dependencies change simultaneously.\n * @protected\n */\n protected async scheduleExecution_(): Promise<void> {\n this.logger_.logMethod?.('scheduleExecution_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'schedule_execution_on_destroyed_signal');\n return;\n }\n if (this.isRunning__) {\n // If an execution is already scheduled, do nothing.\n this.logger_.logStep?.('scheduleExecution_', 'skipped_because_already_running');\n return;\n }\n\n this.isRunning__ = true;\n\n try {\n // Wait for the next macrotask to batch simultaneous updates.\n await delay.nextMacrotask();\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'destroyed_during_delay');\n this.isRunning__ = false;\n return;\n }\n\n this.logger_.logStep?.('scheduleExecution_', 'executing_effect');\n await this.config_.run();\n }\n catch (err) {\n this.logger_.error('scheduleExecution_', 'effect_failed', err);\n }\n\n // Reset the flag after the current execution is complete.\n this.isRunning__ = false;\n }\n\n /**\n * Permanently disposes of the effect signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping any future executions of the effect and allowing it to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks and potentially unwanted side effects.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n this.isDestroyed__ = true;\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.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as EffectSignalConfig; // Release config closure.\n }\n}\n", "import {EventSignal} from '../core/event-signal.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * Creates 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.\n *\n * @param config The configuration for the event signal.\n * @returns A new instance of EventSignal.\n *\n * @example\n * const onUserClick = createEventSignal<{ x: number, y: number }>({\n * name: 'on-user-click'\n * });\n *\n * onUserClick.subscribe(pos => {\n * console.log(`User clicked at: ${pos.x}, ${pos.y}`);\n * });\n *\n * onUserClick.dispatch({ x: 100, y: 250 });\n */\nexport function createEventSignal<T = void>(config: SignalConfig): EventSignal<T> {\n return new EventSignal<T>(config);\n}\n", "import {StateSignal} from '../core/state-signal.js';\n\nimport type {StateSignalConfig} from '../type.js';\n\n/**\n * Creates 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 *\n * @param config The configuration for the state signal.\n * @returns A new instance of StateSignal.\n *\n * @example\n * const counter = createStateSignal({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * console.log(counter.get()); // Outputs: 0\n * counter.set(1);\n * console.log(counter.get()); // Outputs: 1\n */\nexport function createStateSignal<T>(config: StateSignalConfig<T>): StateSignal<T> {\n return new StateSignal(config);\n}\n", "import {ComputedSignal} from '../core/computed-signal.js';\n\nimport type {ComputedSignalConfig} from '../type.js';\n\n/**\n * Creates 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 * @param config The configuration for the computed signal.\n * @returns A new, read-only computed signal.\n *\n * @example\n * const firstName = createStateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = createStateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * const fullName = createComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // \"John Doe\"\n *\n * // IMPORTANT: Always destroy a computed signal when no longer needed.\n * // fullName.destroy();\n */\nexport function createComputedSignal<T>(config: ComputedSignalConfig<T>): ComputedSignal<T> {\n return new ComputedSignal(config);\n}\n", "import {EffectSignal} from '../core/effect-signal.js';\n\nimport type {EffectSignalConfig} from '../type.js';\n\n/**\n * Creates a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @param config The configuration for the effect.\n * @returns An object with a `destroy` method to stop the effect.\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = createStateSignal({ initialValue: 0, name: 'counter' });\n * const user = createStateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = createEffect({\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport function createEffect(config: EffectSignalConfig): EffectSignal {\n return new EffectSignal(config);\n}\n", "import {createDebouncer} from '@alwatr/debounce';\n\nimport {StateSignal} from '../core/state-signal.js';\nimport {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal, DebounceSignalConfig} from '../type.js';\n\n/**\n * Creates a new computed signal that debounces updates from a source signal.\n *\n * The returned signal is a `ComputedSignal`, meaning it is read-only and its value is\n * derived from the source. It only updates its value after a specified period of\n * inactivity from the source signal.\n *\n * This operator is essential for handling high-frequency events, such as user input\n * in a search box, resizing a window, or any other event that fires rapidly.\n * By debouncing, you can ensure that expensive operations (like API calls or heavy\n * computations) are only executed once the events have settled.\n *\n * @template T The type of the signal's value.\n *\n * @param {IReadonlySignal<T>} sourceSignal The original signal to debounce.\n * It can be a `StateSignal`, `ComputedSignal`, or any signal implementing `IReadonlySignal`.\n * @param {DebounceSignalConfig} config Configuration object for the debouncer,\n * including `delay`, `leading`, and `trailing` options from `@alwatr/debounce`.\n *\n * @returns {IComputedSignal<T>} A new, read-only computed signal that emits debounced values.\n * Crucially, you **must** call `.destroy()` on this signal when it's no longer\n * needed to prevent memory leaks by cleaning up internal subscriptions and timers.\n *\n * @example\n * ```typescript\n * // Create a source signal for user input.\n * const searchInput = createStateSignal({\n * name: 'search-input',\n * initialValue: '',\n * });\n *\n * // Create a debounced signal that waits 300ms after the user stops typing.\n * const debouncedSearch = createDebouncedSignal(searchInput, { delay: 300 });\n *\n * // Use an effect to react to the debounced value.\n * createEffect({\n * deps: [debouncedSearch],\n * run: () => {\n * if (debouncedSearch.get()) {\n * console.log(`🚀 Sending API request for: \"${debouncedSearch.get()}\"`);\n * }\n * },\n * });\n *\n * searchInput.set('Alwatr');\n * searchInput.set('Alwatr Signal');\n * // (after 300ms of inactivity)\n * // Logs: \"🚀 Sending API request for: \"Alwatr Signal\"\"\n *\n * // IMPORTANT: Clean up when the component unmounts.\n * // debouncedSearch.destroy();\n * ```\n */\nexport function createDebouncedSignal<T>(sourceSignal: IReadonlySignal<T>, config: DebounceSignalConfig): ComputedSignal<T> {\n const name = config.name ?? `${sourceSignal.name}-debounced`;\n\n const internalSignal = new StateSignal<T>({\n name: `${name}-internal`,\n initialValue: sourceSignal.get(),\n });\n\n const debouncer = createDebouncer({\n ...config,\n func: (value: T): void => {\n internalSignal.set(value);\n },\n });\n\n const subscription = sourceSignal.subscribe((value) => debouncer.trigger(value), {receivePrevious: false});\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n if (internalSignal.isDestroyed) return;\n subscription.unsubscribe();\n debouncer.cancel();\n internalSignal.destroy();\n config.onDestroy?.();\n config = null as unknown as DebounceSignalConfig;\n },\n });\n}\n"],
|
|
5
|
-
"mappings": ";;qqBAAA,
|
|
6
|
-
"names": ["import_delay", "import_logger", "import_delay", "import_logger", "import_delay", "import_logger"]
|
|
3
|
+
"sources": ["../src/main.ts", "../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/creators/event.ts", "../src/creators/state.ts", "../src/creators/computed.ts", "../src/creators/effect.ts", "../src/creators/persistent-state.ts", "../src/operators/debounce.ts", "../src/operators/filter.ts", "../src/operators/map.ts"],
|
|
4
|
+
"sourcesContent": ["export * from './core/signal-base.js';\nexport * from './core/event-signal.js';\nexport * from './core/state-signal.js';\nexport * from './core/computed-signal.js';\nexport * from './core/effect-signal.js';\nexport * from './core/persistent-state-signal.js';\n\nexport * from './creators/event.js';\nexport * from './creators/state.js';\nexport * from './creators/computed.js';\nexport * from './creators/effect.js';\nexport * from './creators/persistent-state.js';\n\nexport * from './operators/debounce.js';\nexport * from './operators/filter.js';\nexport * from './operators/map.js';\n\nexport type * from './type.js';\n", "import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\nimport type {} from '@alwatr/nano-build';\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 = this.config_.name;\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 observers_: 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\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 const index = this.observers_.indexOf(observer);\n if (index !== -1) {\n this.observers_.splice(index, 1);\n }\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 // High-priority observers are added to the front of the queue.\n this.observers_.unshift(observer);\n }\n else {\n this.observers_.push(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 // Create a snapshot of the observers array to iterate over.\n // This prevents issues if the observers_ array is modified during the loop.\n const currentObservers = [...this.observers_];\n\n for (const observer of currentObservers) {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\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 }\n catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\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.observers_.length = 0; // Clear all 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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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_ = createLogger(`event-signal:${this.name}`);\n\n constructor(config: SignalConfig) {\n super(config);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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_ = createLogger(`state-signal:${this.name}`);\n\n constructor(config: StateSignalConfig<T>) {\n super({\n name: config.name,\n onDestroy: config.onDestroy,\n });\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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 = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`computed-signal:${this.name}`);\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_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\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.logger_.logMethod?.('constructor');\n this.recalculate_ = this.recalculate_.bind(this);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport type {EffectSignalConfig, IEffectSignal, SubscribeResult} from '../type.js';\n\n/**\n * Manages a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @implements {IEffectSignal}\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = new StateSignal({ initialValue: 0, name: 'counter' });\n * const user = new StateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = new EffectSignal({\n * name: 'analytics-effect',\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport class EffectSignal implements IEffectSignal {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name ?? `[${this.config_.deps.map((dep) => dep.name).join(', ')}]`;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`effect-signal:${this.name}`);\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent executions of the effect.\n * @private\n */\n private isRunning__ = false;\n\n /**\n * A flag indicating whether the effect has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the effect signal has been destroyed.\n * A destroyed signal will no longer execute its effect and cannot be reused.\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_: EffectSignalConfig) {\n this.logger_.logMethod?.('constructor');\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n // Subscribe to all dependencies. We don't need the previous value,\n // as the `runImmediately` option controls the initial execution.\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.scheduleExecution_, {receivePrevious: false}));\n }\n\n // Run the effect immediately if requested.\n if (config_.runImmediately === true) {\n this.logger_.logStep?.('constructor', 'scheduling_initial_execution');\n // We don't need to await this, let it run in the background.\n void this.scheduleExecution_();\n }\n }\n\n /**\n * Schedules the execution of the effect's `run` function.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `run` function executes only once per event loop tick, even if multiple\n * dependencies change simultaneously.\n * @protected\n */\n protected async scheduleExecution_(): Promise<void> {\n this.logger_.logMethod?.('scheduleExecution_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'schedule_execution_on_destroyed_signal');\n return;\n }\n if (this.isRunning__) {\n // If an execution is already scheduled, do nothing.\n this.logger_.logStep?.('scheduleExecution_', 'skipped_because_already_running');\n return;\n }\n\n this.isRunning__ = true;\n\n try {\n // Wait for the next macrotask to batch simultaneous updates.\n await delay.nextMacrotask();\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'destroyed_during_delay');\n this.isRunning__ = false;\n return;\n }\n\n this.logger_.logStep?.('scheduleExecution_', 'executing_effect');\n await this.config_.run();\n }\n catch (err) {\n this.logger_.error('scheduleExecution_', 'effect_failed', err);\n }\n\n // Reset the flag after the current execution is complete.\n this.isRunning__ = false;\n }\n\n /**\n * Permanently disposes of the effect signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping any future executions of the effect and allowing it to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks and potentially unwanted side effects.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n this.isDestroyed__ = true;\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.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as EffectSignalConfig; // Release config closure.\n }\n}\n", "import {createDebouncer} from '@alwatr/debounce';\nimport {createLocalStorageProvider} from '@alwatr/local-storage';\n\nimport {StateSignal} from './state-signal.js';\n\nimport type {PersistentStateSignalConfig} from '../type.js';\nimport type {LocalStorageProvider} from '@alwatr/local-storage';\n\n/**\n * A stateful signal that persists its value in the browser's localStorage.\n *\n * It extends the functionality of a standard `StateSignal` by automatically reading\n * its initial value from localStorage and writing back any subsequent changes.\n *\n * @template T The type of the state it holds.\n */\nexport class PersistentStateSignal<T extends JsonValue> extends StateSignal<T> {\n /**\n * The underlying storage provider instance.\n * @private\n */\n private readonly storageProvider__: LocalStorageProvider<T>;\n\n /**\n * Debouncer to limit how often we write to localStorage.\n * @private\n */\n private readonly storageDebouncer__;\n\n /**\n * The subscription to the signal's own changes to sync with storage.\n * We subscribe to our own signal. When the value is set from anywhere,\n * this listener will trigger and write it to localStorage.\n * @private\n */\n private readonly storageSyncSubscription__;\n\n constructor(config: PersistentStateSignalConfig<T>) {\n config.storageKey ??= config.name;\n config.saveDebounceDelay ??= 500;\n\n // 1. Create the LocalStorageProvider instance.\n const storageProvider = createLocalStorageProvider<T>({\n name: config.storageKey,\n schemaVersion: config.schemaVersion,\n defaultValue: config.defaultValue,\n });\n\n // 2. Read the initial value from storage.\n // The .read() method guarantees a valid value is returned (either from storage or the default).\n const initialValue = storageProvider.read();\n\n // 3. Call the parent constructor with the correct initial value.\n super({\n name: config.name,\n initialValue,\n onDestroy: config.onDestroy,\n });\n\n this.logger_.logMethodArgs?.('constructor', {\n name: config.name,\n schemaVersion: config.schemaVersion,\n initialValue,\n });\n\n this.storageProvider__ = storageProvider;\n\n this.storageDebouncer__ = createDebouncer({\n delay: config.saveDebounceDelay,\n leading: false,\n trailing: true,\n thisContext: this,\n func: this.syncStorage__,\n });\n\n this.storageSyncSubscription__ = this.subscribe(this.storageDebouncer__.trigger, {receivePrevious: false});\n }\n\n /**\n * Syncs the new value to storage.\n * @param newValue The new value to sync to storage.\n */\n private syncStorage__(newValue: T): void {\n this.logger_.logMethodArgs?.('syncStorage__', newValue);\n this.storageProvider__.write(newValue);\n }\n\n /**\n * Removes the value from localStorage.\n * This provides a clean way to clear persisted data.\n */\n public remove(): void {\n this.checkDestroyed_();\n this.logger_.logMethod?.('remove');\n // Remove from storage.\n this.storageProvider__.remove();\n }\n\n /**\n * Overrides the destroy method to also clean up the storage sync subscription.\n */\n public override destroy(): void {\n this.logger_.logMethod?.('destroy');\n // Flush any pending storage writes before destroying.\n this.storageDebouncer__.flush();\n // Unsubscribe from the sync listener to prevent memory leaks.\n this.storageSyncSubscription__.unsubscribe();\n super.destroy();\n }\n}\n", "import {EventSignal} from '../core/event-signal.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * Creates 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.\n *\n * @param config The configuration for the event signal.\n * @returns A new instance of EventSignal.\n *\n * @example\n * const onUserClick = createEventSignal<{ x: number, y: number }>({\n * name: 'on-user-click'\n * });\n *\n * onUserClick.subscribe(pos => {\n * console.log(`User clicked at: ${pos.x}, ${pos.y}`);\n * });\n *\n * onUserClick.dispatch({ x: 100, y: 250 });\n */\nexport function createEventSignal<T = void>(config: SignalConfig): EventSignal<T> {\n return new EventSignal<T>(config);\n}\n", "import {StateSignal} from '../core/state-signal.js';\n\nimport type {StateSignalConfig} from '../type.js';\n\n/**\n * Creates 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 *\n * @param config The configuration for the state signal.\n * @returns A new instance of StateSignal.\n *\n * @example\n * const counter = createStateSignal({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * console.log(counter.get()); // Outputs: 0\n * counter.set(1);\n * console.log(counter.get()); // Outputs: 1\n */\nexport function createStateSignal<T>(config: StateSignalConfig<T>): StateSignal<T> {\n return new StateSignal(config);\n}\n", "import {ComputedSignal} from '../core/computed-signal.js';\n\nimport type {ComputedSignalConfig} from '../type.js';\n\n/**\n * Creates 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 * @param config The configuration for the computed signal.\n * @returns A new, read-only computed signal.\n *\n * @example\n * const firstName = createStateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = createStateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * const fullName = createComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // \"John Doe\"\n *\n * // IMPORTANT: Always destroy a computed signal when no longer needed.\n * // fullName.destroy();\n */\nexport function createComputedSignal<T>(config: ComputedSignalConfig<T>): ComputedSignal<T> {\n return new ComputedSignal(config);\n}\n", "import {EffectSignal} from '../core/effect-signal.js';\n\nimport type {EffectSignalConfig} from '../type.js';\n\n/**\n * Creates a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @param config The configuration for the effect.\n * @returns An object with a `destroy` method to stop the effect.\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = createStateSignal({ initialValue: 0, name: 'counter' });\n * const user = createStateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = createEffect({\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport function createEffect(config: EffectSignalConfig): EffectSignal {\n return new EffectSignal(config);\n}\n", "import {PersistentStateSignal} from '../core/persistent-state-signal.js';\n\nimport type {PersistentStateSignalConfig} from '../type.js';\n\n/**\n * Creates a stateful signal that persists its value in localStorage.\n *\n * This function provides a clean, declarative API for creating state that\n * survives page reloads. It automatically handles reading the initial state\n * from localStorage and saving subsequent updates.\n *\n * @template T The type of the state it holds.\n *\n * @param {PersistentStateSignalConfig<T>} config The configuration for the persistent state signal.\n * @returns {PersistentStateSignal<T>} A new instance of PersistentStateSignal.\n *\n * @example\n * // Create a signal to store user's preferred theme.\n * const userThemeSignal = createPersistentStateSignal<string>({\n * name: 'user-theme',\n * schemaVersion: 1,\n * defaultValue: 'light',\n * });\n *\n * // The initial value is read from localStorage, or 'light' if not present.\n * console.log(userThemeSignal.get());\n *\n * // Setting a new value updates the in-memory state and writes to localStorage.\n * userThemeSignal.set('dark');\n */\nexport function createPersistentStateSignal<T extends JsonValue>(config: PersistentStateSignalConfig<T>): PersistentStateSignal<T> {\n return new PersistentStateSignal(config);\n}\n", "import {createDebouncer} from '@alwatr/debounce';\n\nimport {StateSignal} from '../core/state-signal.js';\nimport {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal, DebounceSignalConfig} from '../type.js';\n\n/**\n * Creates a new computed signal that debounces updates from a source signal.\n *\n * The returned signal is a `ComputedSignal`, meaning it is read-only and its value is\n * derived from the source. It only updates its value after a specified period of\n * inactivity from the source signal.\n *\n * This operator is essential for handling high-frequency events, such as user input\n * in a search box, resizing a window, or any other event that fires rapidly.\n * By debouncing, you can ensure that expensive operations (like API calls or heavy\n * computations) are only executed once the events have settled.\n *\n * @template T The type of the signal's value.\n *\n * @param {IReadonlySignal<T>} sourceSignal The original signal to debounce.\n * It can be a `StateSignal`, `ComputedSignal`, or any signal implementing `IReadonlySignal`.\n * @param {DebounceSignalConfig} config Configuration object for the debouncer,\n * including `delay`, `leading`, and `trailing` options from `@alwatr/debounce`.\n *\n * @returns {IComputedSignal<T>} A new, read-only computed signal that emits debounced values.\n * Crucially, you **must** call `.destroy()` on this signal when it's no longer\n * needed to prevent memory leaks by cleaning up internal subscriptions and timers.\n *\n * @example\n * ```typescript\n * // Create a source signal for user input.\n * const searchInput = createStateSignal({\n * name: 'search-input',\n * initialValue: '',\n * });\n *\n * // Create a debounced signal that waits 300ms after the user stops typing.\n * const debouncedSearch = createDebouncedSignal(searchInput, { delay: 300 });\n *\n * // Use an effect to react to the debounced value.\n * createEffect({\n * deps: [debouncedSearch],\n * run: () => {\n * if (debouncedSearch.get()) {\n * console.log(`🚀 Sending API request for: \"${debouncedSearch.get()}\"`);\n * }\n * },\n * });\n *\n * searchInput.set('Alwatr');\n * searchInput.set('Alwatr Signal');\n * // (after 300ms of inactivity)\n * // Logs: \"🚀 Sending API request for: \"Alwatr Signal\"\"\n *\n * // IMPORTANT: Clean up when the component unmounts.\n * // debouncedSearch.destroy();\n * ```\n */\nexport function createDebouncedSignal<T>(sourceSignal: IReadonlySignal<T>, config: DebounceSignalConfig): ComputedSignal<T> {\n const name = config.name ?? `${sourceSignal.name}-debounced`;\n\n const internalSignal = new StateSignal<T>({\n name: `${name}-internal`,\n initialValue: sourceSignal.get(),\n });\n\n const debouncer = createDebouncer({\n ...config,\n func: (value: T): void => {\n internalSignal.set(value);\n },\n });\n\n const subscription = sourceSignal.subscribe((value) => debouncer.trigger(value), {receivePrevious: false});\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n if (internalSignal.isDestroyed) return;\n subscription.unsubscribe();\n debouncer.cancel();\n internalSignal.destroy();\n config.onDestroy?.();\n config = null as unknown as DebounceSignalConfig;\n },\n });\n}\n", "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", "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"],
|
|
5
|
+
"mappings": ";;qqBAAA,ynBCUO,IAAe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,EACvB,OAAO,YAAY,EACnB,OAAS,IACX,CACF,CAAC,CACH,CC1CO,SAAS,qBACd,aACA,UACA,KAAO,GAAG,aAAa,IAAI,YACI,CAC/B,MAAM,YAAc,aAAa,IAAI,EACrC,MAAM,aAAe,UAAU,WAAW,EAAI,YAAc,OAE5D,MAAM,eAAiB,kBAAkB,CACvC,KAAM,GAAG,IAAI,YACb,YACF,CAAC,EAED,MAAM,aAAe,aAAa,UAAW,UAAa,CACxD,GAAI,UAAU,QAAQ,EAAG,CACvB,eAAe,IAAI,QAAQ,CAC7B,CACF,CAAC,EAED,OAAO,qBAAqB,CAC1B,KACA,KAAM,CAAC,cAAc,EACrB,IAAK,IAAM,eAAe,IAAI,EAC9B,UAAW,IAAM,CACf,aAAa,YAAY,EACzB,eAAe,QAAQ,CACzB,CACF,CAAC,CACH,CCxCO,SAAS,mBACd,aACA,gBACA,KAAO,GAAG,aAAa,IAAI,UACR,CACnB,OAAO,qBAAqB,CAC1B,KACA,KAAM,CAAC,YAAY,EACnB,IAAK,IAAM,gBAAgB,aAAa,IAAI,CAAC,CAC/C,CAAC,CACH",
|
|
6
|
+
"names": ["import_delay", "import_logger", "import_delay", "import_logger", "import_delay", "import_logger", "import_debounce"]
|
|
7
7
|
}
|
package/dist/main.d.ts
CHANGED
|
@@ -3,10 +3,14 @@ export * from './core/event-signal.js';
|
|
|
3
3
|
export * from './core/state-signal.js';
|
|
4
4
|
export * from './core/computed-signal.js';
|
|
5
5
|
export * from './core/effect-signal.js';
|
|
6
|
+
export * from './core/persistent-state-signal.js';
|
|
6
7
|
export * from './creators/event.js';
|
|
7
8
|
export * from './creators/state.js';
|
|
8
9
|
export * from './creators/computed.js';
|
|
9
10
|
export * from './creators/effect.js';
|
|
11
|
+
export * from './creators/persistent-state.js';
|
|
10
12
|
export * from './operators/debounce.js';
|
|
13
|
+
export * from './operators/filter.js';
|
|
14
|
+
export * from './operators/map.js';
|
|
11
15
|
export type * from './type.js';
|
|
12
16
|
//# sourceMappingURL=main.d.ts.map
|
package/dist/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,wBAAwB,CAAC;AACvC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,wBAAwB,CAAC;AACvC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,yBAAyB,CAAC;AACxC,cAAc,mCAAmC,CAAC;AAElD,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,gCAAgC,CAAC;AAE/C,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AAEnC,mBAAmB,WAAW,CAAC"}
|
package/dist/main.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** 📦 @alwatr/signal v6.0
|
|
2
|
-
__dev_mode__: console.debug("📦 @alwatr/signal v6.0
|
|
3
|
-
var SignalBase=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.observers_=[];this.isDestroyed__=false}get isDestroyed(){return this.isDestroyed__}removeObserver_(observer){this.logger_.logMethod?.("removeObserver_");if(this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}const index=this.observers_.indexOf(observer);if(index!==-1){this.observers_.splice(index,1)}}subscribe(callback,options){this.logger_.logMethodArgs?.("subscribe.base",options);this.checkDestroyed_();const observer={callback,options};if(options?.priority){this.observers_.unshift(observer)}else{this.observers_.push(observer)}return{unsubscribe:()=>this.removeObserver_(observer)}}notify_(value){this.logger_.logMethodArgs?.("notify_",value);if(this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}const currentObservers=[...this.observers_];for(const observer of currentObservers){if(observer.options?.once){this.removeObserver_(observer)}try{const result=observer.callback(value);if(result instanceof Promise){result.catch(err=>this.logger_.error("notify_","async_callback_failed",err,{observer}))}}catch(err){this.logger_.error("notify_","sync_callback_failed",err)}}}untilNext(){this.logger_.logMethod?.("untilNext");this.checkDestroyed_();return new Promise(resolve=>{this.subscribe(resolve,{once:true,priority:true,receivePrevious:false})})}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}this.isDestroyed__=true;this.observers_.length=0;this.config_.onDestroy?.();this.config_=null}checkDestroyed_(){if(this.isDestroyed__){this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal");throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}};import{delay}from"@alwatr/delay";import{createLogger}from"@alwatr/logger";var EventSignal=class extends SignalBase{constructor(config){super(config);this.logger_=createLogger(`event-signal:${this.name}`);this.logger_.logMethod?.("constructor")}dispatch(payload){this.logger_.logMethodArgs?.("dispatch",{payload});this.checkDestroyed_();delay.nextMicrotask().then(()=>this.notify_(payload))}};import{delay as delay2}from"@alwatr/delay";import{createLogger as createLogger2}from"@alwatr/logger";var StateSignal=class extends SignalBase{constructor(config){super(config);this.logger_=createLogger2(`state-signal:${this.name}`);this.value__=config.initialValue;this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){this.checkDestroyed_();return this.value__}set(newValue){this.logger_.logMethodArgs?.("set",{newValue});this.checkDestroyed_();if(Object.is(this.value__,newValue)&&(typeof newValue!=="object"||newValue===null)){return}this.value__=newValue;delay2.nextMicrotask().then(()=>this.notify_(newValue))}update(updater){this.checkDestroyed_();const newValue=updater(this.value__);this.logger_.logMethodFull?.("update",this.value__,newValue);this.set(newValue)}subscribe(callback,options={}){this.logger_.logMethodArgs?.("subscribe",options);this.checkDestroyed_();if(options.receivePrevious!==false){delay2.nextMicrotask().then(()=>{this.logger_.logStep?.("subscribe","immediate_callback");callback(this.value__)}).catch(err=>this.logger_.error("subscribe","immediate_callback_failed",err));if(options.once){return{unsubscribe:()=>{}}}}return super.subscribe(callback,options)}destroy(){this.value__=null;super.destroy()}asReadonly(){return this}};import{delay as delay3}from"@alwatr/delay";import{createLogger as createLogger3}from"@alwatr/logger";var ComputedSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.logger_=createLogger3(`computed-signal:${this.name}`);this.internalSignal_=new StateSignal({name:`compute-${this.name}_`,initialValue:this.config_.get()});this.dependencySubscriptions__=[];this.isRecalculating__=false;this.logger_.logMethod?.("constructor");this.recalculate_=this.recalculate_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_,{receivePrevious:false}))}}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(callback,options){return this.internalSignal_.subscribe(callback,options)}untilNext(){return this.internalSignal_.untilNext()}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.internalSignal_.destroy();this.config_.onDestroy?.();this.config_=null}async recalculate_(){this.logger_.logMethod?.("recalculate_");if(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__=true;try{await delay3.nextMacrotask();if(this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay");this.isRecalculating__=false;return}this.logger_.logStep?.("recalculate_","recalculating_value");this.internalSignal_.set(this.config_.get())}catch(err){this.logger_.error("recalculate_","recalculation_failed",err)}this.isRecalculating__=false}};import{delay as delay4}from"@alwatr/delay";import{createLogger as createLogger4}from"@alwatr/logger";var EffectSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name??`[${this.config_.deps.map(dep=>dep.name).join(", ")}]`;this.logger_=createLogger4(`effect-signal:${this.name}`);this.dependencySubscriptions__=[];this.isRunning__=false;this.isDestroyed__=false;this.logger_.logMethod?.("constructor");this.scheduleExecution_=this.scheduleExecution_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_,{receivePrevious:false}))}if(config_.runImmediately===true){this.logger_.logStep?.("constructor","scheduling_initial_execution");void this.scheduleExecution_()}}get isDestroyed(){return this.isDestroyed__}async scheduleExecution_(){this.logger_.logMethod?.("scheduleExecution_");if(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__=true;try{await delay4.nextMacrotask();if(this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay");this.isRunning__=false;return}this.logger_.logStep?.("scheduleExecution_","executing_effect");await this.config_.run()}catch(err){this.logger_.error("scheduleExecution_","effect_failed",err)}this.isRunning__=false}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=true;for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.config_.onDestroy?.();this.config_=null}};function createEventSignal(config){return new EventSignal(config)}function createStateSignal(config){return new StateSignal(config)}function createComputedSignal(config){return new ComputedSignal(config)}function createEffect(config){return new EffectSignal(config)}import{createDebouncer}from"@alwatr/debounce";function createDebouncedSignal(sourceSignal,config){const name=config.name??`${sourceSignal.name}-debounced`;const internalSignal=new StateSignal({name:`${name}-internal`,initialValue:sourceSignal.get()});const debouncer=createDebouncer({...config,func:value=>{internalSignal.set(value)}});const subscription=sourceSignal.subscribe(value=>debouncer.trigger(value),{receivePrevious:false});return createComputedSignal({name,deps:[internalSignal],get:()=>internalSignal.get(),onDestroy:()=>{if(internalSignal.isDestroyed)return;subscription.unsubscribe();debouncer.cancel();internalSignal.destroy();config.onDestroy?.();config=null}})}export{ComputedSignal,EffectSignal,EventSignal,SignalBase,StateSignal,createComputedSignal,createDebouncedSignal,createEffect,createEventSignal,createStateSignal};
|
|
1
|
+
/** 📦 @alwatr/signal v6.1.0 */
|
|
2
|
+
__dev_mode__: console.debug("📦 @alwatr/signal v6.1.0");
|
|
3
|
+
var SignalBase=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.observers_=[];this.isDestroyed__=false}get isDestroyed(){return this.isDestroyed__}removeObserver_(observer){this.logger_.logMethod?.("removeObserver_");if(this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}const index=this.observers_.indexOf(observer);if(index!==-1){this.observers_.splice(index,1)}}subscribe(callback,options){this.logger_.logMethodArgs?.("subscribe.base",options);this.checkDestroyed_();const observer={callback,options};if(options?.priority){this.observers_.unshift(observer)}else{this.observers_.push(observer)}return{unsubscribe:()=>this.removeObserver_(observer)}}notify_(value){this.logger_.logMethodArgs?.("notify_",value);if(this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}const currentObservers=[...this.observers_];for(const observer of currentObservers){if(observer.options?.once){this.removeObserver_(observer)}try{const result=observer.callback(value);if(result instanceof Promise){result.catch(err=>this.logger_.error("notify_","async_callback_failed",err,{observer}))}}catch(err){this.logger_.error("notify_","sync_callback_failed",err)}}}untilNext(){this.logger_.logMethod?.("untilNext");this.checkDestroyed_();return new Promise(resolve=>{this.subscribe(resolve,{once:true,priority:true,receivePrevious:false})})}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}this.isDestroyed__=true;this.observers_.length=0;this.config_.onDestroy?.();this.config_=null}checkDestroyed_(){if(this.isDestroyed__){this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal");throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}};import{delay}from"@alwatr/delay";import{createLogger}from"@alwatr/logger";var EventSignal=class extends SignalBase{constructor(config){super(config);this.logger_=createLogger(`event-signal:${this.name}`);this.logger_.logMethod?.("constructor")}dispatch(payload){this.logger_.logMethodArgs?.("dispatch",{payload});this.checkDestroyed_();delay.nextMicrotask().then(()=>this.notify_(payload))}};import{delay as delay2}from"@alwatr/delay";import{createLogger as createLogger2}from"@alwatr/logger";var StateSignal=class extends SignalBase{constructor(config){super({name:config.name,onDestroy:config.onDestroy});this.logger_=createLogger2(`state-signal:${this.name}`);this.value__=config.initialValue;this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){this.checkDestroyed_();return this.value__}set(newValue){this.logger_.logMethodArgs?.("set",{newValue});this.checkDestroyed_();if(Object.is(this.value__,newValue)&&(typeof newValue!=="object"||newValue===null)){return}this.value__=newValue;delay2.nextMicrotask().then(()=>this.notify_(newValue))}update(updater){this.checkDestroyed_();const newValue=updater(this.value__);this.logger_.logMethodFull?.("update",this.value__,newValue);this.set(newValue)}subscribe(callback,options={}){this.logger_.logMethodArgs?.("subscribe",options);this.checkDestroyed_();if(options.receivePrevious!==false){delay2.nextMicrotask().then(()=>{this.logger_.logStep?.("subscribe","immediate_callback");callback(this.value__)}).catch(err=>this.logger_.error("subscribe","immediate_callback_failed",err));if(options.once){return{unsubscribe:()=>{}}}}return super.subscribe(callback,options)}destroy(){this.value__=null;super.destroy()}asReadonly(){return this}};import{delay as delay3}from"@alwatr/delay";import{createLogger as createLogger3}from"@alwatr/logger";var ComputedSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.logger_=createLogger3(`computed-signal:${this.name}`);this.internalSignal_=new StateSignal({name:`compute-${this.name}_`,initialValue:this.config_.get()});this.dependencySubscriptions__=[];this.isRecalculating__=false;this.logger_.logMethod?.("constructor");this.recalculate_=this.recalculate_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_,{receivePrevious:false}))}}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(callback,options){return this.internalSignal_.subscribe(callback,options)}untilNext(){return this.internalSignal_.untilNext()}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.internalSignal_.destroy();this.config_.onDestroy?.();this.config_=null}async recalculate_(){this.logger_.logMethod?.("recalculate_");if(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__=true;try{await delay3.nextMacrotask();if(this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay");this.isRecalculating__=false;return}this.logger_.logStep?.("recalculate_","recalculating_value");this.internalSignal_.set(this.config_.get())}catch(err){this.logger_.error("recalculate_","recalculation_failed",err)}this.isRecalculating__=false}};import{delay as delay4}from"@alwatr/delay";import{createLogger as createLogger4}from"@alwatr/logger";var EffectSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name??`[${this.config_.deps.map(dep=>dep.name).join(", ")}]`;this.logger_=createLogger4(`effect-signal:${this.name}`);this.dependencySubscriptions__=[];this.isRunning__=false;this.isDestroyed__=false;this.logger_.logMethod?.("constructor");this.scheduleExecution_=this.scheduleExecution_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_,{receivePrevious:false}))}if(config_.runImmediately===true){this.logger_.logStep?.("constructor","scheduling_initial_execution");void this.scheduleExecution_()}}get isDestroyed(){return this.isDestroyed__}async scheduleExecution_(){this.logger_.logMethod?.("scheduleExecution_");if(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__=true;try{await delay4.nextMacrotask();if(this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay");this.isRunning__=false;return}this.logger_.logStep?.("scheduleExecution_","executing_effect");await this.config_.run()}catch(err){this.logger_.error("scheduleExecution_","effect_failed",err)}this.isRunning__=false}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=true;for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.config_.onDestroy?.();this.config_=null}};import{createDebouncer}from"@alwatr/debounce";import{createLocalStorageProvider}from"@alwatr/local-storage";var PersistentStateSignal=class extends StateSignal{constructor(config){config.storageKey??=config.name;config.saveDebounceDelay??=500;const storageProvider=createLocalStorageProvider({name:config.storageKey,schemaVersion:config.schemaVersion,defaultValue:config.defaultValue});const initialValue=storageProvider.read();super({name:config.name,initialValue,onDestroy:config.onDestroy});this.logger_.logMethodArgs?.("constructor",{name:config.name,schemaVersion:config.schemaVersion,initialValue});this.storageProvider__=storageProvider;this.storageDebouncer__=createDebouncer({delay:config.saveDebounceDelay,leading:false,trailing:true,thisContext:this,func:this.syncStorage__});this.storageSyncSubscription__=this.subscribe(this.storageDebouncer__.trigger,{receivePrevious:false})}syncStorage__(newValue){this.logger_.logMethodArgs?.("syncStorage__",newValue);this.storageProvider__.write(newValue)}remove(){this.checkDestroyed_();this.logger_.logMethod?.("remove");this.storageProvider__.remove()}destroy(){this.logger_.logMethod?.("destroy");this.storageDebouncer__.flush();this.storageSyncSubscription__.unsubscribe();super.destroy()}};function createEventSignal(config){return new EventSignal(config)}function createStateSignal(config){return new StateSignal(config)}function createComputedSignal(config){return new ComputedSignal(config)}function createEffect(config){return new EffectSignal(config)}function createPersistentStateSignal(config){return new PersistentStateSignal(config)}import{createDebouncer as createDebouncer2}from"@alwatr/debounce";function createDebouncedSignal(sourceSignal,config){const name=config.name??`${sourceSignal.name}-debounced`;const internalSignal=new StateSignal({name:`${name}-internal`,initialValue:sourceSignal.get()});const debouncer=createDebouncer2({...config,func:value=>{internalSignal.set(value)}});const subscription=sourceSignal.subscribe(value=>debouncer.trigger(value),{receivePrevious:false});return createComputedSignal({name,deps:[internalSignal],get:()=>internalSignal.get(),onDestroy:()=>{if(internalSignal.isDestroyed)return;subscription.unsubscribe();debouncer.cancel();internalSignal.destroy();config.onDestroy?.();config=null}})}function createFilteredSignal(sourceSignal,predicate,name=`${sourceSignal.name}-filtered`){const sourceValue=sourceSignal.get();const initialValue=predicate(sourceValue)?sourceValue:void 0;const internalSignal=createStateSignal({name:`${name}-internal`,initialValue});const subscription=sourceSignal.subscribe(newValue=>{if(predicate(newValue)){internalSignal.set(newValue)}});return createComputedSignal({name,deps:[internalSignal],get:()=>internalSignal.get(),onDestroy:()=>{subscription.unsubscribe();internalSignal.destroy()}})}function createMappedSignal(sourceSignal,projectFunction,name=`${sourceSignal.name}-mapped`){return createComputedSignal({name,deps:[sourceSignal],get:()=>projectFunction(sourceSignal.get())})}export{ComputedSignal,EffectSignal,EventSignal,PersistentStateSignal,SignalBase,StateSignal,createComputedSignal,createDebouncedSignal,createEffect,createEventSignal,createFilteredSignal,createMappedSignal,createPersistentStateSignal,createStateSignal};
|
|
4
4
|
//# sourceMappingURL=main.mjs.map
|
package/dist/main.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 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/creators/event.ts", "../src/creators/state.ts", "../src/creators/computed.ts", "../src/creators/effect.ts", "../src/operators/debounce.ts"],
|
|
4
|
-
"sourcesContent": ["import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\nimport type {} from '@alwatr/nano-build';\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 = this.config_.name;\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 observers_: 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\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 const index = this.observers_.indexOf(observer);\n if (index !== -1) {\n this.observers_.splice(index, 1);\n }\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 // High-priority observers are added to the front of the queue.\n this.observers_.unshift(observer);\n }\n else {\n this.observers_.push(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 // Create a snapshot of the observers array to iterate over.\n // This prevents issues if the observers_ array is modified during the loop.\n const currentObservers = [...this.observers_];\n\n for (const observer of currentObservers) {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\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 }\n catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\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.observers_.length = 0; // Clear all 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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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_ = createLogger(`event-signal:${this.name}`);\n\n constructor(config: SignalConfig) {\n super(config);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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_ = createLogger(`state-signal:${this.name}`);\n\n constructor(config: StateSignalConfig<T>) {\n super(config);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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 = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`computed-signal:${this.name}`);\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_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\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.logger_.logMethod?.('constructor');\n this.recalculate_ = this.recalculate_.bind(this);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport type {EffectSignalConfig, IEffectSignal, SubscribeResult} from '../type.js';\n\n/**\n * Manages a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @implements {IEffectSignal}\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = new StateSignal({ initialValue: 0, name: 'counter' });\n * const user = new StateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = new EffectSignal({\n * name: 'analytics-effect',\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport class EffectSignal implements IEffectSignal {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name ?? `[${this.config_.deps.map((dep) => dep.name).join(', ')}]`;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`effect-signal:${this.name}`);\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent executions of the effect.\n * @private\n */\n private isRunning__ = false;\n\n /**\n * A flag indicating whether the effect has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the effect signal has been destroyed.\n * A destroyed signal will no longer execute its effect and cannot be reused.\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_: EffectSignalConfig) {\n this.logger_.logMethod?.('constructor');\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n // Subscribe to all dependencies. We don't need the previous value,\n // as the `runImmediately` option controls the initial execution.\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.scheduleExecution_, {receivePrevious: false}));\n }\n\n // Run the effect immediately if requested.\n if (config_.runImmediately === true) {\n this.logger_.logStep?.('constructor', 'scheduling_initial_execution');\n // We don't need to await this, let it run in the background.\n void this.scheduleExecution_();\n }\n }\n\n /**\n * Schedules the execution of the effect's `run` function.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `run` function executes only once per event loop tick, even if multiple\n * dependencies change simultaneously.\n * @protected\n */\n protected async scheduleExecution_(): Promise<void> {\n this.logger_.logMethod?.('scheduleExecution_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'schedule_execution_on_destroyed_signal');\n return;\n }\n if (this.isRunning__) {\n // If an execution is already scheduled, do nothing.\n this.logger_.logStep?.('scheduleExecution_', 'skipped_because_already_running');\n return;\n }\n\n this.isRunning__ = true;\n\n try {\n // Wait for the next macrotask to batch simultaneous updates.\n await delay.nextMacrotask();\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'destroyed_during_delay');\n this.isRunning__ = false;\n return;\n }\n\n this.logger_.logStep?.('scheduleExecution_', 'executing_effect');\n await this.config_.run();\n }\n catch (err) {\n this.logger_.error('scheduleExecution_', 'effect_failed', err);\n }\n\n // Reset the flag after the current execution is complete.\n this.isRunning__ = false;\n }\n\n /**\n * Permanently disposes of the effect signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping any future executions of the effect and allowing it to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks and potentially unwanted side effects.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n this.isDestroyed__ = true;\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.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as EffectSignalConfig; // Release config closure.\n }\n}\n", "import {EventSignal} from '../core/event-signal.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * Creates 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.\n *\n * @param config The configuration for the event signal.\n * @returns A new instance of EventSignal.\n *\n * @example\n * const onUserClick = createEventSignal<{ x: number, y: number }>({\n * name: 'on-user-click'\n * });\n *\n * onUserClick.subscribe(pos => {\n * console.log(`User clicked at: ${pos.x}, ${pos.y}`);\n * });\n *\n * onUserClick.dispatch({ x: 100, y: 250 });\n */\nexport function createEventSignal<T = void>(config: SignalConfig): EventSignal<T> {\n return new EventSignal<T>(config);\n}\n", "import {StateSignal} from '../core/state-signal.js';\n\nimport type {StateSignalConfig} from '../type.js';\n\n/**\n * Creates 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 *\n * @param config The configuration for the state signal.\n * @returns A new instance of StateSignal.\n *\n * @example\n * const counter = createStateSignal({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * console.log(counter.get()); // Outputs: 0\n * counter.set(1);\n * console.log(counter.get()); // Outputs: 1\n */\nexport function createStateSignal<T>(config: StateSignalConfig<T>): StateSignal<T> {\n return new StateSignal(config);\n}\n", "import {ComputedSignal} from '../core/computed-signal.js';\n\nimport type {ComputedSignalConfig} from '../type.js';\n\n/**\n * Creates 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 * @param config The configuration for the computed signal.\n * @returns A new, read-only computed signal.\n *\n * @example\n * const firstName = createStateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = createStateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * const fullName = createComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // \"John Doe\"\n *\n * // IMPORTANT: Always destroy a computed signal when no longer needed.\n * // fullName.destroy();\n */\nexport function createComputedSignal<T>(config: ComputedSignalConfig<T>): ComputedSignal<T> {\n return new ComputedSignal(config);\n}\n", "import {EffectSignal} from '../core/effect-signal.js';\n\nimport type {EffectSignalConfig} from '../type.js';\n\n/**\n * Creates a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @param config The configuration for the effect.\n * @returns An object with a `destroy` method to stop the effect.\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = createStateSignal({ initialValue: 0, name: 'counter' });\n * const user = createStateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = createEffect({\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport function createEffect(config: EffectSignalConfig): EffectSignal {\n return new EffectSignal(config);\n}\n", "import {createDebouncer} from '@alwatr/debounce';\n\nimport {StateSignal} from '../core/state-signal.js';\nimport {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal, DebounceSignalConfig} from '../type.js';\n\n/**\n * Creates a new computed signal that debounces updates from a source signal.\n *\n * The returned signal is a `ComputedSignal`, meaning it is read-only and its value is\n * derived from the source. It only updates its value after a specified period of\n * inactivity from the source signal.\n *\n * This operator is essential for handling high-frequency events, such as user input\n * in a search box, resizing a window, or any other event that fires rapidly.\n * By debouncing, you can ensure that expensive operations (like API calls or heavy\n * computations) are only executed once the events have settled.\n *\n * @template T The type of the signal's value.\n *\n * @param {IReadonlySignal<T>} sourceSignal The original signal to debounce.\n * It can be a `StateSignal`, `ComputedSignal`, or any signal implementing `IReadonlySignal`.\n * @param {DebounceSignalConfig} config Configuration object for the debouncer,\n * including `delay`, `leading`, and `trailing` options from `@alwatr/debounce`.\n *\n * @returns {IComputedSignal<T>} A new, read-only computed signal that emits debounced values.\n * Crucially, you **must** call `.destroy()` on this signal when it's no longer\n * needed to prevent memory leaks by cleaning up internal subscriptions and timers.\n *\n * @example\n * ```typescript\n * // Create a source signal for user input.\n * const searchInput = createStateSignal({\n * name: 'search-input',\n * initialValue: '',\n * });\n *\n * // Create a debounced signal that waits 300ms after the user stops typing.\n * const debouncedSearch = createDebouncedSignal(searchInput, { delay: 300 });\n *\n * // Use an effect to react to the debounced value.\n * createEffect({\n * deps: [debouncedSearch],\n * run: () => {\n * if (debouncedSearch.get()) {\n * console.log(`🚀 Sending API request for: \"${debouncedSearch.get()}\"`);\n * }\n * },\n * });\n *\n * searchInput.set('Alwatr');\n * searchInput.set('Alwatr Signal');\n * // (after 300ms of inactivity)\n * // Logs: \"🚀 Sending API request for: \"Alwatr Signal\"\"\n *\n * // IMPORTANT: Clean up when the component unmounts.\n * // debouncedSearch.destroy();\n * ```\n */\nexport function createDebouncedSignal<T>(sourceSignal: IReadonlySignal<T>, config: DebounceSignalConfig): ComputedSignal<T> {\n const name = config.name ?? `${sourceSignal.name}-debounced`;\n\n const internalSignal = new StateSignal<T>({\n name: `${name}-internal`,\n initialValue: sourceSignal.get(),\n });\n\n const debouncer = createDebouncer({\n ...config,\n func: (value: T): void => {\n internalSignal.set(value);\n },\n });\n\n const subscription = sourceSignal.subscribe((value) => debouncer.trigger(value), {receivePrevious: false});\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n if (internalSignal.isDestroyed) return;\n subscription.unsubscribe();\n debouncer.cancel();\n internalSignal.destroy();\n config.onDestroy?.();\n config = null as unknown as DebounceSignalConfig;\n },\n });\n}\n"],
|
|
5
|
-
"mappings": ";;AAUO,IAAe,WAAf,KAA6B,CAmClC,YAAsB,QAAuB,CAAvB,qBA9BtB,KAAgB,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AAW,EACpC,KAAK,gBAAgB,EACrB,OAAO,IAAI,QAAS,SAAY,CAC9B,KAAK,UAAU,QAAS,CACtB,KAAM,KACN,SAAU,KACV,gBAAiB,KACnB,CAAC,CACH,CAAC,CACH,CASO,SAAgB,CACrB,KAAK,QAAQ,YAAY,SAAS,EAClC,GAAI,KAAK,cAAe,CACtB,KAAK,QAAQ,WAAW,WAAY,wBAAwB,EAC5D,MACF,CACA,KAAK,cAAgB,KACrB,KAAK,WAAW,OAAS,EACzB,KAAK,QAAQ,YAAY,EACzB,KAAK,QAAU,IACjB,CAOU,iBAAwB,CAChC,GAAI,KAAK,cAAe,CACtB,KAAK,QAAQ,SAAS,kBAAmB,iCAAiC,EAC1E,MAAM,IAAI,MAAM,gDAAgD,KAAK,IAAI,GAAG,CAC9E,CACF,CACF,EC7LA,OAAQ,UAAY,gBACpB,OAAQ,iBAAmB,iBAiCpB,IAAM,YAAN,cAAoC,UAAc,CAOvD,YAAY,OAAsB,CAChC,MAAM,MAAM,EAHd,KAAU,QAAU,aAAa,gBAAgB,KAAK,IAAI,EAAE,EAI1D,KAAK,QAAQ,YAAY,aAAa,CACxC,CASO,SAAS,QAAkB,CAChC,KAAK,QAAQ,gBAAgB,WAAY,CAAC,OAAO,CAAC,EAClD,KAAK,gBAAgB,EAErB,MAAM,cAAc,EAAE,KAAK,IAAM,KAAK,QAAQ,OAAO,CAAC,CACxD,CACF,EC3DA,OAAQ,SAAAA,WAAY,gBACpB,OAAQ,gBAAAC,kBAAmB,iBAuCpB,IAAM,YAAN,cAA6B,UAA4C,CAa9E,YAAY,OAA8B,CACxC,MAAM,
|
|
6
|
-
"names": ["delay", "createLogger", "createLogger", "delay", "delay", "createLogger", "createLogger", "delay", "delay", "createLogger"]
|
|
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/creators/event.ts", "../src/creators/state.ts", "../src/creators/computed.ts", "../src/creators/effect.ts", "../src/creators/persistent-state.ts", "../src/operators/debounce.ts", "../src/operators/filter.ts", "../src/operators/map.ts"],
|
|
4
|
+
"sourcesContent": ["import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\nimport type {} from '@alwatr/nano-build';\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 = this.config_.name;\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 observers_: 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\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 const index = this.observers_.indexOf(observer);\n if (index !== -1) {\n this.observers_.splice(index, 1);\n }\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 // High-priority observers are added to the front of the queue.\n this.observers_.unshift(observer);\n }\n else {\n this.observers_.push(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 // Create a snapshot of the observers array to iterate over.\n // This prevents issues if the observers_ array is modified during the loop.\n const currentObservers = [...this.observers_];\n\n for (const observer of currentObservers) {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\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 }\n catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\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.observers_.length = 0; // Clear all 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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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_ = createLogger(`event-signal:${this.name}`);\n\n constructor(config: SignalConfig) {\n super(config);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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_ = createLogger(`state-signal:${this.name}`);\n\n constructor(config: StateSignalConfig<T>) {\n super({\n name: config.name,\n onDestroy: config.onDestroy,\n });\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} 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 = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`computed-signal:${this.name}`);\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_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\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.logger_.logMethod?.('constructor');\n this.recalculate_ = this.recalculate_.bind(this);\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", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport type {EffectSignalConfig, IEffectSignal, SubscribeResult} from '../type.js';\n\n/**\n * Manages a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @implements {IEffectSignal}\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = new StateSignal({ initialValue: 0, name: 'counter' });\n * const user = new StateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = new EffectSignal({\n * name: 'analytics-effect',\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport class EffectSignal implements IEffectSignal {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name ?? `[${this.config_.deps.map((dep) => dep.name).join(', ')}]`;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`effect-signal:${this.name}`);\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent executions of the effect.\n * @private\n */\n private isRunning__ = false;\n\n /**\n * A flag indicating whether the effect has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the effect signal has been destroyed.\n * A destroyed signal will no longer execute its effect and cannot be reused.\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_: EffectSignalConfig) {\n this.logger_.logMethod?.('constructor');\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n // Subscribe to all dependencies. We don't need the previous value,\n // as the `runImmediately` option controls the initial execution.\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.scheduleExecution_, {receivePrevious: false}));\n }\n\n // Run the effect immediately if requested.\n if (config_.runImmediately === true) {\n this.logger_.logStep?.('constructor', 'scheduling_initial_execution');\n // We don't need to await this, let it run in the background.\n void this.scheduleExecution_();\n }\n }\n\n /**\n * Schedules the execution of the effect's `run` function.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `run` function executes only once per event loop tick, even if multiple\n * dependencies change simultaneously.\n * @protected\n */\n protected async scheduleExecution_(): Promise<void> {\n this.logger_.logMethod?.('scheduleExecution_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'schedule_execution_on_destroyed_signal');\n return;\n }\n if (this.isRunning__) {\n // If an execution is already scheduled, do nothing.\n this.logger_.logStep?.('scheduleExecution_', 'skipped_because_already_running');\n return;\n }\n\n this.isRunning__ = true;\n\n try {\n // Wait for the next macrotask to batch simultaneous updates.\n await delay.nextMacrotask();\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'destroyed_during_delay');\n this.isRunning__ = false;\n return;\n }\n\n this.logger_.logStep?.('scheduleExecution_', 'executing_effect');\n await this.config_.run();\n }\n catch (err) {\n this.logger_.error('scheduleExecution_', 'effect_failed', err);\n }\n\n // Reset the flag after the current execution is complete.\n this.isRunning__ = false;\n }\n\n /**\n * Permanently disposes of the effect signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping any future executions of the effect and allowing it to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks and potentially unwanted side effects.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n this.isDestroyed__ = true;\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.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as EffectSignalConfig; // Release config closure.\n }\n}\n", "import {createDebouncer} from '@alwatr/debounce';\nimport {createLocalStorageProvider} from '@alwatr/local-storage';\n\nimport {StateSignal} from './state-signal.js';\n\nimport type {PersistentStateSignalConfig} from '../type.js';\nimport type {LocalStorageProvider} from '@alwatr/local-storage';\n\n/**\n * A stateful signal that persists its value in the browser's localStorage.\n *\n * It extends the functionality of a standard `StateSignal` by automatically reading\n * its initial value from localStorage and writing back any subsequent changes.\n *\n * @template T The type of the state it holds.\n */\nexport class PersistentStateSignal<T extends JsonValue> extends StateSignal<T> {\n /**\n * The underlying storage provider instance.\n * @private\n */\n private readonly storageProvider__: LocalStorageProvider<T>;\n\n /**\n * Debouncer to limit how often we write to localStorage.\n * @private\n */\n private readonly storageDebouncer__;\n\n /**\n * The subscription to the signal's own changes to sync with storage.\n * We subscribe to our own signal. When the value is set from anywhere,\n * this listener will trigger and write it to localStorage.\n * @private\n */\n private readonly storageSyncSubscription__;\n\n constructor(config: PersistentStateSignalConfig<T>) {\n config.storageKey ??= config.name;\n config.saveDebounceDelay ??= 500;\n\n // 1. Create the LocalStorageProvider instance.\n const storageProvider = createLocalStorageProvider<T>({\n name: config.storageKey,\n schemaVersion: config.schemaVersion,\n defaultValue: config.defaultValue,\n });\n\n // 2. Read the initial value from storage.\n // The .read() method guarantees a valid value is returned (either from storage or the default).\n const initialValue = storageProvider.read();\n\n // 3. Call the parent constructor with the correct initial value.\n super({\n name: config.name,\n initialValue,\n onDestroy: config.onDestroy,\n });\n\n this.logger_.logMethodArgs?.('constructor', {\n name: config.name,\n schemaVersion: config.schemaVersion,\n initialValue,\n });\n\n this.storageProvider__ = storageProvider;\n\n this.storageDebouncer__ = createDebouncer({\n delay: config.saveDebounceDelay,\n leading: false,\n trailing: true,\n thisContext: this,\n func: this.syncStorage__,\n });\n\n this.storageSyncSubscription__ = this.subscribe(this.storageDebouncer__.trigger, {receivePrevious: false});\n }\n\n /**\n * Syncs the new value to storage.\n * @param newValue The new value to sync to storage.\n */\n private syncStorage__(newValue: T): void {\n this.logger_.logMethodArgs?.('syncStorage__', newValue);\n this.storageProvider__.write(newValue);\n }\n\n /**\n * Removes the value from localStorage.\n * This provides a clean way to clear persisted data.\n */\n public remove(): void {\n this.checkDestroyed_();\n this.logger_.logMethod?.('remove');\n // Remove from storage.\n this.storageProvider__.remove();\n }\n\n /**\n * Overrides the destroy method to also clean up the storage sync subscription.\n */\n public override destroy(): void {\n this.logger_.logMethod?.('destroy');\n // Flush any pending storage writes before destroying.\n this.storageDebouncer__.flush();\n // Unsubscribe from the sync listener to prevent memory leaks.\n this.storageSyncSubscription__.unsubscribe();\n super.destroy();\n }\n}\n", "import {EventSignal} from '../core/event-signal.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * Creates 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.\n *\n * @param config The configuration for the event signal.\n * @returns A new instance of EventSignal.\n *\n * @example\n * const onUserClick = createEventSignal<{ x: number, y: number }>({\n * name: 'on-user-click'\n * });\n *\n * onUserClick.subscribe(pos => {\n * console.log(`User clicked at: ${pos.x}, ${pos.y}`);\n * });\n *\n * onUserClick.dispatch({ x: 100, y: 250 });\n */\nexport function createEventSignal<T = void>(config: SignalConfig): EventSignal<T> {\n return new EventSignal<T>(config);\n}\n", "import {StateSignal} from '../core/state-signal.js';\n\nimport type {StateSignalConfig} from '../type.js';\n\n/**\n * Creates 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 *\n * @param config The configuration for the state signal.\n * @returns A new instance of StateSignal.\n *\n * @example\n * const counter = createStateSignal({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * console.log(counter.get()); // Outputs: 0\n * counter.set(1);\n * console.log(counter.get()); // Outputs: 1\n */\nexport function createStateSignal<T>(config: StateSignalConfig<T>): StateSignal<T> {\n return new StateSignal(config);\n}\n", "import {ComputedSignal} from '../core/computed-signal.js';\n\nimport type {ComputedSignalConfig} from '../type.js';\n\n/**\n * Creates 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 * @param config The configuration for the computed signal.\n * @returns A new, read-only computed signal.\n *\n * @example\n * const firstName = createStateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = createStateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * const fullName = createComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // \"John Doe\"\n *\n * // IMPORTANT: Always destroy a computed signal when no longer needed.\n * // fullName.destroy();\n */\nexport function createComputedSignal<T>(config: ComputedSignalConfig<T>): ComputedSignal<T> {\n return new ComputedSignal(config);\n}\n", "import {EffectSignal} from '../core/effect-signal.js';\n\nimport type {EffectSignalConfig} from '../type.js';\n\n/**\n * Creates a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @param config The configuration for the effect.\n * @returns An object with a `destroy` method to stop the effect.\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = createStateSignal({ initialValue: 0, name: 'counter' });\n * const user = createStateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = createEffect({\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport function createEffect(config: EffectSignalConfig): EffectSignal {\n return new EffectSignal(config);\n}\n", "import {PersistentStateSignal} from '../core/persistent-state-signal.js';\n\nimport type {PersistentStateSignalConfig} from '../type.js';\n\n/**\n * Creates a stateful signal that persists its value in localStorage.\n *\n * This function provides a clean, declarative API for creating state that\n * survives page reloads. It automatically handles reading the initial state\n * from localStorage and saving subsequent updates.\n *\n * @template T The type of the state it holds.\n *\n * @param {PersistentStateSignalConfig<T>} config The configuration for the persistent state signal.\n * @returns {PersistentStateSignal<T>} A new instance of PersistentStateSignal.\n *\n * @example\n * // Create a signal to store user's preferred theme.\n * const userThemeSignal = createPersistentStateSignal<string>({\n * name: 'user-theme',\n * schemaVersion: 1,\n * defaultValue: 'light',\n * });\n *\n * // The initial value is read from localStorage, or 'light' if not present.\n * console.log(userThemeSignal.get());\n *\n * // Setting a new value updates the in-memory state and writes to localStorage.\n * userThemeSignal.set('dark');\n */\nexport function createPersistentStateSignal<T extends JsonValue>(config: PersistentStateSignalConfig<T>): PersistentStateSignal<T> {\n return new PersistentStateSignal(config);\n}\n", "import {createDebouncer} from '@alwatr/debounce';\n\nimport {StateSignal} from '../core/state-signal.js';\nimport {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal, DebounceSignalConfig} from '../type.js';\n\n/**\n * Creates a new computed signal that debounces updates from a source signal.\n *\n * The returned signal is a `ComputedSignal`, meaning it is read-only and its value is\n * derived from the source. It only updates its value after a specified period of\n * inactivity from the source signal.\n *\n * This operator is essential for handling high-frequency events, such as user input\n * in a search box, resizing a window, or any other event that fires rapidly.\n * By debouncing, you can ensure that expensive operations (like API calls or heavy\n * computations) are only executed once the events have settled.\n *\n * @template T The type of the signal's value.\n *\n * @param {IReadonlySignal<T>} sourceSignal The original signal to debounce.\n * It can be a `StateSignal`, `ComputedSignal`, or any signal implementing `IReadonlySignal`.\n * @param {DebounceSignalConfig} config Configuration object for the debouncer,\n * including `delay`, `leading`, and `trailing` options from `@alwatr/debounce`.\n *\n * @returns {IComputedSignal<T>} A new, read-only computed signal that emits debounced values.\n * Crucially, you **must** call `.destroy()` on this signal when it's no longer\n * needed to prevent memory leaks by cleaning up internal subscriptions and timers.\n *\n * @example\n * ```typescript\n * // Create a source signal for user input.\n * const searchInput = createStateSignal({\n * name: 'search-input',\n * initialValue: '',\n * });\n *\n * // Create a debounced signal that waits 300ms after the user stops typing.\n * const debouncedSearch = createDebouncedSignal(searchInput, { delay: 300 });\n *\n * // Use an effect to react to the debounced value.\n * createEffect({\n * deps: [debouncedSearch],\n * run: () => {\n * if (debouncedSearch.get()) {\n * console.log(`🚀 Sending API request for: \"${debouncedSearch.get()}\"`);\n * }\n * },\n * });\n *\n * searchInput.set('Alwatr');\n * searchInput.set('Alwatr Signal');\n * // (after 300ms of inactivity)\n * // Logs: \"🚀 Sending API request for: \"Alwatr Signal\"\"\n *\n * // IMPORTANT: Clean up when the component unmounts.\n * // debouncedSearch.destroy();\n * ```\n */\nexport function createDebouncedSignal<T>(sourceSignal: IReadonlySignal<T>, config: DebounceSignalConfig): ComputedSignal<T> {\n const name = config.name ?? `${sourceSignal.name}-debounced`;\n\n const internalSignal = new StateSignal<T>({\n name: `${name}-internal`,\n initialValue: sourceSignal.get(),\n });\n\n const debouncer = createDebouncer({\n ...config,\n func: (value: T): void => {\n internalSignal.set(value);\n },\n });\n\n const subscription = sourceSignal.subscribe((value) => debouncer.trigger(value), {receivePrevious: false});\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n if (internalSignal.isDestroyed) return;\n subscription.unsubscribe();\n debouncer.cancel();\n internalSignal.destroy();\n config.onDestroy?.();\n config = null as unknown as DebounceSignalConfig;\n },\n });\n}\n", "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", "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"],
|
|
5
|
+
"mappings": ";;AAUO,IAAe,WAAf,KAA6B,CAmClC,YAAsB,QAAuB,CAAvB,qBA9BtB,KAAgB,KAAO,KAAK,QAAQ,KAYpC,KAAmB,WAA6B,CAAC,EAMjD,KAAQ,cAAgB,KAYsB,CAJ9C,IAAW,aAAuB,CAChC,OAAO,KAAK,aACd,CAUU,gBAAgB,SAA8B,CACtD,KAAK,QAAQ,YAAY,iBAAiB,EAE1C,GAAI,KAAK,cAAe,CACtB,KAAK,QAAQ,WAAW,kBAAmB,qCAAqC,EAChF,MACF,CAEA,MAAM,MAAQ,KAAK,WAAW,QAAQ,QAAQ,EAC9C,GAAI,QAAU,GAAI,CAChB,KAAK,WAAW,OAAO,MAAO,CAAC,CACjC,CACF,CAWO,UAAU,SAA+B,QAA6C,CAC3F,KAAK,QAAQ,gBAAgB,iBAAkB,OAAO,EACtD,KAAK,gBAAgB,EAErB,MAAM,SAAyB,CAAC,SAAU,OAAO,EAEjD,GAAI,SAAS,SAAU,CAErB,KAA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ACH,CCxCO,SAAS,mBACd,aACA,gBACA,KAAO,GAAG,aAAa,IAAI,UACR,CACnB,OAAO,qBAAqB,CAC1B,KACA,KAAM,CAAC,YAAY,EACnB,IAAK,IAAM,gBAAgB,aAAa,IAAI,CAAC,CAC/C,CAAC,CACH",
|
|
6
|
+
"names": ["delay", "createLogger", "createLogger", "delay", "delay", "createLogger", "createLogger", "delay", "delay", "createLogger", "createDebouncer", "createDebouncer"]
|
|
7
7
|
}
|
package/dist/type.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DebouncerConfig } from '@alwatr/debounce';
|
|
2
|
+
import type { LocalStorageProviderConfig } from '@alwatr/local-storage';
|
|
2
3
|
/**
|
|
3
4
|
* @package @alwatr/signal
|
|
4
5
|
*
|
|
@@ -228,7 +229,6 @@ export interface EffectSignalConfig {
|
|
|
228
229
|
run: () => Awaitable<void>;
|
|
229
230
|
/**
|
|
230
231
|
* If `true`, the effect's `run` function will be executed once immediately upon initialization.
|
|
231
|
-
*
|
|
232
232
|
* @default false
|
|
233
233
|
*/
|
|
234
234
|
runImmediately?: boolean;
|
|
@@ -269,7 +269,6 @@ export interface IEffectSignal {
|
|
|
269
269
|
export interface DebounceSignalConfig extends Omit<DebouncerConfig<never>, 'func' | 'thisContext'> {
|
|
270
270
|
/**
|
|
271
271
|
* A unique identifier for the signal. This is crucial for debugging and differentiating signals.
|
|
272
|
-
*
|
|
273
272
|
* @default `${sourceSignal.name}-debounced`
|
|
274
273
|
*/
|
|
275
274
|
name?: string;
|
|
@@ -279,4 +278,23 @@ export interface DebounceSignalConfig extends Omit<DebouncerConfig<never>, 'func
|
|
|
279
278
|
*/
|
|
280
279
|
onDestroy?: () => void;
|
|
281
280
|
}
|
|
281
|
+
/**
|
|
282
|
+
* Configuration for a persistent state signal.
|
|
283
|
+
* It combines the core signal configuration with the necessary options for local storage persistence.
|
|
284
|
+
*
|
|
285
|
+
* @template T The type of the state it holds.
|
|
286
|
+
*/
|
|
287
|
+
export interface PersistentStateSignalConfig<T extends JsonValue> extends SignalConfig, LocalStorageProviderConfig<T> {
|
|
288
|
+
/**
|
|
289
|
+
* The key under which to store the signal's state in localStorage.
|
|
290
|
+
* @default `signal-name`
|
|
291
|
+
*/
|
|
292
|
+
storageKey?: string;
|
|
293
|
+
/**
|
|
294
|
+
* The debounce delay (in milliseconds) for saving changes to localStorage.
|
|
295
|
+
* This helps to reduce the frequency of write operations, which can be costly in terms of performance.
|
|
296
|
+
* @default 500
|
|
297
|
+
*/
|
|
298
|
+
saveDebounceDelay?: number;
|
|
299
|
+
}
|
|
282
300
|
//# sourceMappingURL=type.d.ts.map
|
package/dist/type.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,uBAAuB,CAAC;AAGtE;;;;;;;GAOG;AACH,MAAM,MAAM,gBAAgB,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,SAAS,CAAC,IAAI,CAAC,CAAC;AAEhE;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;;;;;;OASG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;IAEf;;;;;;;;;OASG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;;;;;;;;;;;;OAcG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;;OAQG;IACH,WAAW,EAAE,MAAM,IAAI,CAAC;CACzB;AAED;;;GAGG;AACH,MA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CAAC,EAAE,MAAM,CAAC;IAEd;;;OAGG;IACH,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAE9B;;;;;;;;;;;OAWG;IACH,GAAG,EAAE,MAAM,SAAS,CAAC,IAAI,CAAC,CAAC;IAE3B;;;OAGG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;;OAIG;IACH,OAAO,EAAE,MAAM,IAAI,CAAC;IAEpB;;;;OAIG;IACH,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;CAC/B;AAED;;;;;GAKG;AACH,MAAM,WAAW,oBAAqB,SAAQ,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,aAAa,CAAC;IAChG;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;CACxB;AAED;;;;;GAKG;AACH,MAAM,WAAW,2BAA2B,CAAC,CAAC,SAAS,SAAS,CAAE,SAAQ,YAAY,EAAE,0BAA0B,CAAC,CAAC,CAAC;IACnH;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B"}
|
package/package.json
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/signal",
|
|
3
3
|
"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.",
|
|
4
|
-
"version": "6.0
|
|
4
|
+
"version": "6.1.0",
|
|
5
5
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
|
|
6
6
|
"bugs": "https://github.com/Alwatr/flux/issues",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@alwatr/debounce": "^1.1.
|
|
9
|
-
"@alwatr/delay": "^6.0.
|
|
10
|
-
"@alwatr/
|
|
8
|
+
"@alwatr/debounce": "^1.1.8",
|
|
9
|
+
"@alwatr/delay": "^6.0.10",
|
|
10
|
+
"@alwatr/local-storage": "^6.3.3",
|
|
11
|
+
"@alwatr/logger": "^6.0.7"
|
|
11
12
|
},
|
|
12
13
|
"devDependencies": {
|
|
13
|
-
"@alwatr/nano-build": "^6.3.
|
|
14
|
+
"@alwatr/nano-build": "^6.3.2",
|
|
14
15
|
"@alwatr/prettier-config": "^5.0.4",
|
|
15
16
|
"@alwatr/tsconfig-base": "^6.0.2",
|
|
16
|
-
"@alwatr/type-helper": "^6.1.
|
|
17
|
+
"@alwatr/type-helper": "^6.1.2",
|
|
17
18
|
"@jest/globals": "^30.1.2",
|
|
18
19
|
"@types/node": "^22.18.6",
|
|
19
20
|
"jest": "^30.1.3",
|
|
@@ -69,5 +70,5 @@
|
|
|
69
70
|
"sideEffects": false,
|
|
70
71
|
"type": "module",
|
|
71
72
|
"types": "./dist/main.d.ts",
|
|
72
|
-
"gitHead": "
|
|
73
|
+
"gitHead": "612960b22abc85db7da2bdbfc815e685edb69c2f"
|
|
73
74
|
}
|