@alwatr/signal 9.23.2 → 9.23.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/event-signal.d.ts +2 -2
- package/dist/core/event-signal.d.ts.map +1 -1
- package/dist/main.js +2 -2
- package/dist/main.js.map +3 -3
- package/dist/type.d.ts +16 -8
- package/dist/type.d.ts.map +1 -1
- package/package.json +7 -7
- package/src/core/event-signal.ts +6 -6
- package/src/type.ts +17 -9
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type AlwatrLogger } from '@alwatr/logger';
|
|
2
2
|
import { SignalBase } from './signal-base.js';
|
|
3
|
-
import type { SignalConfig } from '../type.js';
|
|
3
|
+
import type { IBaseSignal, SignalConfig } from '../type.js';
|
|
4
4
|
/**
|
|
5
5
|
* A stateless signal for dispatching transient events.
|
|
6
6
|
*
|
|
@@ -28,7 +28,7 @@ import type { SignalConfig } from '../type.js';
|
|
|
28
28
|
* onAppReady.subscribe(() => console.log('Application is ready!'));
|
|
29
29
|
* onAppReady.dispatch(); // Notifies the listener.
|
|
30
30
|
*/
|
|
31
|
-
export declare class EventSignal<T = void> extends SignalBase<T> {
|
|
31
|
+
export declare class EventSignal<T = void> extends SignalBase<T> implements IBaseSignal<T> {
|
|
32
32
|
/**
|
|
33
33
|
* The logger instance for this signal.
|
|
34
34
|
* @protected
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-signal.d.ts","sourceRoot":"","sources":["../../src/core/event-signal.ts"],"names":[],"mappings":"AACA,OAAO,
|
|
1
|
+
{"version":3,"file":"event-signal.d.ts","sourceRoot":"","sources":["../../src/core/event-signal.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,KAAK,YAAY,EAAC,MAAM,gBAAgB,CAAC;AAE/D,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAC,WAAW,EAAE,YAAY,EAAC,MAAM,YAAY,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,WAAW,CAAC,CAAC,GAAG,IAAI,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAE,YAAW,WAAW,CAAC,CAAC,CAAC;IAChF;;;OAGG;IACH,SAAS,CAAC,OAAO,EAAE,YAAY,CAAC;gBAEpB,MAAM,EAAE,YAAY;IAMhC;;;;;;OAMG;IACI,QAAQ,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI;CAMlC"}
|
package/dist/main.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/* 📦 @alwatr/signal v9.23.
|
|
1
|
+
/* 📦 @alwatr/signal v9.23.3 */
|
|
2
2
|
class B{config_;name;priorityObservers_=new Set;observers_=new Set;isDestroyed__=!1;get isDestroyed(){return this.isDestroyed__}constructor(G){this.config_=G;this.name=G.name}removeObserver_(G){if(this.logger_.logMethod?.("removeObserver_"),this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}this.priorityObservers_.delete(G),this.observers_.delete(G)}subscribe(G,H){this.logger_.logMethodArgs?.("subscribe.base",H),this.checkDestroyed_();let Q={callback:G,options:H};if(H?.priority)this.priorityObservers_.add(Q);else this.observers_.add(Q);return{unsubscribe:()=>this.removeObserver_(Q)}}notify_(G){if(this.logger_.logMethodArgs?.("notify_",G),this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}for(let H of this.priorityObservers_)this.executeObserver__(H,G);for(let H of this.observers_)this.executeObserver__(H,G)}executeObserver__(G,H){if(G.options?.once)this.removeObserver_(G);try{let Q=G.callback(H);if(Q instanceof Promise)Q.catch((X)=>this.logger_.error("notify_","async_callback_failed",X,{observer:G}))}catch(Q){this.logger_.error("notify_","sync_callback_failed",Q)}}pendingRejects__=new Set;untilNext(){return this.logger_.logMethod?.("untilNext"),this.checkDestroyed_(),new Promise((G,H)=>{this.pendingRejects__.add(H),this.subscribe((Q)=>{this.pendingRejects__.delete(H),G(Q)},{once:!0,priority:!0,receivePrevious:!1})})}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}if(this.isDestroyed__=!0,this.pendingRejects__.size){let G=Error("signal_destroyed");for(let H of this.pendingRejects__)H(G);this.pendingRejects__.clear()}this.priorityObservers_.clear(),this.observers_.clear(),this.config_.onDestroy?.(),this.config_=null}checkDestroyed_(){if(this.isDestroyed__)throw this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal"),Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}import{delay as _}from"@alwatr/delay";import{createLogger as U}from"@alwatr/logger";class J extends B{logger_;constructor(G){super(G);this.logger_=U(`event-signal:${this.name}`),this.logger_.logMethod?.("constructor")}dispatch(G){this.logger_.logMethodArgs?.("dispatch",{payload:G}),this.checkDestroyed_(),_.nextMicrotask().then(()=>this.notify_(G))}}import{delay as M}from"@alwatr/delay";import{createLogger as E}from"@alwatr/logger";class K extends B{value__;logger_;notifyPending__=!1;notifyVersion__=0;constructor(G){super({name:G.name,onDestroy:G.onDestroy});this.logger_=E(`state-signal:${this.name}`),this.value__=G.initialValue,this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){return this.checkDestroyed_(),this.value__}set(G){if(this.logger_.logMethodArgs?.("set",{newValue:G}),Object.is(this.value__,G)&&(typeof G!=="object"||G===null))return;this.value__=G,this.notifyChange()}notifyChange(){if(this.logger_.logMethod?.("notifyChange"),this.checkDestroyed_(),this.notifyVersion__++,this.notifyPending__)return;this.notifyPending__=!0,M.nextMicrotask().then(()=>{this.notifyPending__=!1,this.notify_(this.value__)})}update(G){this.checkDestroyed_();let H=G(this.value__);this.logger_.logMethodFull?.("update",this.value__,H),this.set(H)}subscribe(G,H={}){this.logger_.logMethodArgs?.("subscribe",H),this.checkDestroyed_();let Q=super.subscribe(G,H);if(H.receivePrevious===!1)return Q;if(this.notifyPending__)return Q;let X=this.notifyVersion__;return M.nextMicrotask().then(()=>{if(this.logger_.logStep?.("subscribe","immediate_callback"),this.notifyVersion__!==X)return;if(H.once)Q.unsubscribe();G(this.value__)}).catch((Y)=>this.logger_.error("subscribe","immediate_callback_failed",Y)),Q}destroy(){this.value__=null,super.destroy()}asReadonly(){return this}}import{delay as x}from"@alwatr/delay";import{createLogger as D}from"@alwatr/logger";class R{config_;name;logger_;internalSignal_;dependencySubscriptions__=[];isRecalculating__=!1;constructor(G){this.config_=G;this.name=G.name,this.logger_=D(`computed-signal:${this.name}`),this.recalculate_=this.recalculate_.bind(this),this.logger_.logMethod?.("constructor"),this.internalSignal_=new K({name:`compute-${this.name}_`,initialValue:this.config_.get()});for(let H of G.deps)this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:H.name}),this.dependencySubscriptions__.push(H.subscribe(this.recalculate_,{receivePrevious:!1}))}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(G,H){return this.internalSignal_.subscribe(G,H)}untilNext(){return this.internalSignal_.untilNext()}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(let G of this.dependencySubscriptions__)G.unsubscribe();this.dependencySubscriptions__.length=0,this.internalSignal_.destroy(),this.config_.onDestroy?.(),this.config_=null}async recalculate_(){if(this.logger_.logMethod?.("recalculate_"),this.internalSignal_.isDestroyed){this.logger_.incident?.("recalculate_","recalculate_on_destroyed_signal");return}if(this.isRecalculating__){this.logger_.logStep?.("recalculate_","skipping_recalculation_already_scheduled");return}this.isRecalculating__=!0;try{if(await x.nextMacrotask(),this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay"),this.isRecalculating__=!1;return}this.logger_.logStep?.("recalculate_","recalculating_value"),this.internalSignal_.set(this.config_.get())}catch(G){this.logger_.error("recalculate_","recalculation_failed",G)}this.isRecalculating__=!1}}import{delay as I}from"@alwatr/delay";import{createLogger as N}from"@alwatr/logger";class z{config_;name;logger_;dependencySubscriptions__=[];isRunning__=!1;isDestroyed__=!1;get isDestroyed(){return this.isDestroyed__}constructor(G){this.config_=G;this.name=G.name??`[${G.deps.map((H)=>H.name).join(", ")}]`,this.logger_=N(`effect-signal:${this.name}`),this.scheduleExecution_=this.scheduleExecution_.bind(this),this.logger_.logMethod?.("constructor");for(let H of G.deps)this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:H.name}),this.dependencySubscriptions__.push(H.subscribe(this.scheduleExecution_,{receivePrevious:!1}));if(G.runImmediately===!0)this.logger_.logStep?.("constructor","scheduling_initial_execution"),this.scheduleExecution_()}async scheduleExecution_(){if(this.logger_.logMethod?.("scheduleExecution_"),this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","schedule_execution_on_destroyed_signal");return}if(this.isRunning__){this.logger_.logStep?.("scheduleExecution_","skipped_because_already_running");return}this.isRunning__=!0;try{if(await I.nextMacrotask(),this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay"),this.isRunning__=!1;return}this.logger_.logStep?.("scheduleExecution_","executing_effect"),await this.config_.run()}catch(G){this.logger_.error("scheduleExecution_","effect_failed",G)}this.isRunning__=!1}destroy(){if(this.logger_.logMethod?.("destroy"),this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=!0;for(let G of this.dependencySubscriptions__)G.unsubscribe();this.dependencySubscriptions__.length=0,this.config_.onDestroy?.(),this.config_=null}}import{createDebouncer as A}from"@alwatr/debounce";import{createLocalStorageProvider as k}from"@alwatr/local-storage";class L extends K{storageProvider__;storageDebouncer__;storageSyncSubscription__;constructor(G){let{name:H,storageKey:Q=H,saveDebounceDelay:X=500,initialValue:Y,onDestroy:Z,schemaVersion:W}=G,q=k({name:Q,schemaVersion:W});super({name:H,initialValue:q.read()??Y,onDestroy:Z});this.logger_.logMethodArgs?.("constructor",G),this.storageProvider__=q,this.storageDebouncer__=A({delay:X,leading:!1,trailing:!0,thisContext:this,func:this.syncStorage__}),this.storageSyncSubscription__=this.subscribe(this.storageDebouncer__.trigger,{receivePrevious:!1})}syncStorage__(G){this.logger_.logMethodArgs?.("syncStorage__",G),this.storageProvider__.write(G)}remove(){this.checkDestroyed_(),this.logger_.logMethod?.("remove"),this.storageProvider__.remove()}destroy(){this.logger_.logMethod?.("destroy"),this.storageDebouncer__.flush(),this.storageSyncSubscription__.unsubscribe(),super.destroy()}}import{createDebouncer as V}from"@alwatr/debounce";import{createSessionStorageProvider as j}from"@alwatr/session-storage";class O extends K{storageProvider__;storageDebouncer__;storageSyncSubscription__;constructor(G){let{name:H,storageKey:Q=H,saveDebounceDelay:X=500,initialValue:Y,onDestroy:Z}=G,W=j({name:Q});super({name:H,initialValue:W.read()??Y,onDestroy:Z});this.logger_.logMethodArgs?.("constructor",G),this.storageProvider__=W,this.storageDebouncer__=V({delay:X,leading:!1,trailing:!0,thisContext:this,func:this.syncStorage__}),this.storageSyncSubscription__=this.subscribe(this.storageDebouncer__.trigger,{receivePrevious:!1})}syncStorage__(G){this.logger_.logMethodArgs?.("syncStorage__",G),this.storageProvider__.write(G)}remove(){this.checkDestroyed_(),this.logger_.logMethod?.("remove"),this.storageProvider__.remove()}destroy(){this.logger_.logMethod?.("destroy"),this.storageDebouncer__.flush(),this.storageSyncSubscription__.unsubscribe(),super.destroy()}}import{delay as C}from"@alwatr/delay";import{createLogger as T}from"@alwatr/logger";class $ extends B{logger_;namedHandlers__=new Map;constructor(G){super(G);this.logger_=T(`channel-signal:${this.name}`),this.logger_.logMethod?.("constructor")}dispatch(...G){let[H,Q]=G;this.logger_.logMethodArgs?.("dispatch",{name:H,payload:Q}),this.checkDestroyed_(),C.nextMicrotask().then(()=>this.route__(H,Q))}on(G,H,Q){this.logger_.logMethodArgs?.("on",{name:G}),this.checkDestroyed_();let X=this.namedHandlers__.get(G);if(!X)X=new Set,this.namedHandlers__.set(G,X);let Y={handler:H,once:Q?.once??!1};return X.add(Y),{unsubscribe:()=>{if(X.delete(Y),X.size===0)this.namedHandlers__.delete(G)}}}subscribe(G,H){return this.logger_.logMethodArgs?.("subscribe",H),super.subscribe(G,H)}route__(G,H){if(this.isDestroyed)return;let Q=this.namedHandlers__.get(G);if(Q?.size)for(let X of Q){if(X.once){if(Q.delete(X),Q.size===0)this.namedHandlers__.delete(G)}try{let Y=X.handler(H);if(Y instanceof Promise)Y.catch((Z)=>this.logger_.error("route__","async_named_handler_failed",Z))}catch(Y){this.logger_.error("route__","sync_named_handler_failed",Y)}}this.notify_({name:G,payload:H})}destroy(){this.namedHandlers__.clear(),super.destroy()}}function WG(G){return new J(G)}function P(G){return new K(G)}function F(G){return new R(G)}function OG(G){return new z(G)}function PG(G){return new L(G)}function EG(G){return new O(G)}function IG(G){return new $(G)}import{createDebouncer as w}from"@alwatr/debounce";function jG(G,H){let Q=H.name??`${G.name}-debounced`,X=new K({name:`${Q}-internal`,initialValue:G.get()}),Y=w({...H,thisContext:X,func:X.set}),Z=G.subscribe(Y.trigger,{receivePrevious:!1});return F({name:Q,deps:[X],get:()=>X.get(),onDestroy:()=>{if(X.isDestroyed)return;Z.unsubscribe(),Y.cancel(),X.destroy(),H.onDestroy?.(),H=null}})}function vG(G,H,Q=`${G.name}-filtered`){let X=G.get(),Y=H(X)?X:void 0,Z=P({name:`${Q}-internal`,initialValue:Y}),W=G.subscribe((q)=>{if(H(q))Z.set(q)});return F({name:Q,deps:[Z],get:()=>Z.get(),onDestroy:()=>{W.unsubscribe(),Z.destroy()}})}function SG(G,H,Q=`${G.name}-mapped`){return F({name:Q,deps:[G],get:()=>H(G.get())})}export{P as createStateSignal,EG as createSessionStateSignal,PG as createPersistentStateSignal,SG as createMappedSignal,vG as createFilteredSignal,WG as createEventSignal,OG as createEffect,jG as createDebouncedSignal,F as createComputedSignal,IG as createChannelSignal,K as StateSignal,B as SignalBase,O as SessionStateSignal,L as PersistentStateSignal,J as EventSignal,z as EffectSignal,R as ComputedSignal,$ as ChannelSignal};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=2A6AFA49C59E6EB664756E2164756E21
|
|
5
5
|
//# sourceMappingURL=main.js.map
|
package/dist/main.js.map
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"sources": ["../src/core/signal-base.ts", "../src/core/event-signal.ts", "../src/core/state-signal.ts", "../src/core/computed-signal.ts", "../src/core/effect-signal.ts", "../src/core/persistent-state-signal.ts", "../src/core/session-state-signal.ts", "../src/core/channel-signal.ts", "../src/creators/event.ts", "../src/creators/state.ts", "../src/creators/computed.ts", "../src/creators/effect.ts", "../src/creators/persistent-state.ts", "../src/creators/session-state.ts", "../src/creators/channel.ts", "../src/operators/debounce.ts", "../src/operators/filter.ts", "../src/operators/map.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\n\n/**\n * An abstract base class for signal implementations.\n * It provides the core functionality for managing subscriptions (observers).\n *\n * @template T The type of data that the signal holds or dispatches.\n */\nexport abstract class SignalBase<T> {\n /**\n * The unique identifier for this signal instance.\n * Useful for debugging and logging.\n */\n public readonly name: string;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected abstract logger_: AlwatrLogger;\n\n /**\n * The list of observers (listeners) subscribed to this signal.\n * @protected\n */\n protected readonly priorityObservers_ = new Set<Observer_<T>>();\n protected readonly observers_ = new Set<Observer_<T>>();\n\n /**\n * A flag indicating whether the signal has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n constructor(protected config_: SignalConfig) {\n this.name = config_.name;\n }\n\n /**\n * Removes a specific observer from the observers list.\n *\n * @param observer The observer instance to remove.\n * @protected\n */\n protected removeObserver_(observer: Observer_<T>): void {\n this.logger_.logMethod?.('removeObserver_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('removeObserver_', 'remove_observer_on_destroyed_signal');\n return;\n }\n\n this.priorityObservers_.delete(observer);\n this.observers_.delete(observer);\n }\n\n /**\n * Subscribes a listener function to this signal.\n *\n * The listener will be called whenever the signal is notified (e.g., when `dispatch` or `set` is called).\n *\n * @param callback The function to be called when the signal is dispatched.\n * @param options Subscription options to customize the behavior (e.g., `once`, `priority`).\n * @returns A `SubscribeResult` object with an `unsubscribe` method to remove the listener.\n */\n public subscribe(callback: ListenerCallback<T>, options?: SubscribeOptions): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe.base', options);\n this.checkDestroyed_();\n\n const observer: Observer_<T> = {callback, options};\n\n if (options?.priority) {\n this.priorityObservers_.add(observer);\n } else {\n this.observers_.add(observer);\n }\n\n // The returned unsubscribe function is a closure that calls the internal removal method.\n return {\n unsubscribe: (): void => this.removeObserver_(observer),\n };\n }\n\n /**\n * Notifies all registered observers about a new value.\n *\n * This method iterates through a snapshot of the current observers to prevent issues\n * with subscriptions changing during notification (e.g., an observer unsubscribing itself).\n *\n * @param value The new value to notify observers about.\n * @protected\n */\n protected notify_(value: T): void {\n this.logger_.logMethodArgs?.('notify_', value);\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('notify_', 'notify_on_destroyed_signal');\n return;\n }\n\n for (const observer of this.priorityObservers_) {\n this.executeObserver__(observer, value);\n }\n\n for (const observer of this.observers_) {\n this.executeObserver__(observer, value);\n }\n }\n\n /**\n * Executes a given observer's callback with the provided value, handling both synchronous and asynchronous callbacks.\n */\n private executeObserver__(observer: Observer_<T>, value: T): void {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\n try {\n const result = observer.callback(value);\n if (result instanceof Promise) {\n result.catch((err) => this.logger_.error('notify_', 'async_callback_failed', err, {observer}));\n }\n } catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\n }\n\n private pendingRejects__ = new Set<(reason?: any) => void>();\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, reject) => {\n this.pendingRejects__.add(reject);\n this.subscribe(\n (value) => {\n this.pendingRejects__.delete(reject);\n resolve(value);\n },\n {\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 /**\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; // Mark the signal as destroyed.\n // Reject all pending promises.\n if (this.pendingRejects__.size) {\n const error = new Error('signal_destroyed');\n for (const reject of this.pendingRejects__) {\n reject(error);\n }\n this.pendingRejects__.clear(); // Clear all pending rejects.\n }\n this.priorityObservers_.clear(); // Clear all priority observers.\n this.observers_.clear(); // Clear all normal observers.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as SignalConfig; // Help GC by breaking references.\n }\n\n /**\n * Throws an error if the signal has been destroyed.\n * This is a safeguard to prevent interaction with a defunct signal.\n * @protected\n */\n protected checkDestroyed_(): void {\n if (this.isDestroyed__) {\n this.logger_.accident('checkDestroyed_', 'attempt_to_use_destroyed_signal');\n throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`);\n }\n }\n}\n",
|
|
6
|
-
"import {
|
|
6
|
+
"import {delay} from '@alwatr/delay';\nimport {createLogger, type AlwatrLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {IBaseSignal, 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> implements IBaseSignal<T> {\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_: AlwatrLogger;\n\n constructor(config: SignalConfig) {\n super(config);\n this.logger_ = createLogger(`event-signal:${this.name}`);\n this.logger_.logMethod?.('constructor');\n }\n\n /**\n * Dispatches an event with an optional payload to all active listeners.\n * The notification is scheduled as a microtask to prevent blocking and ensure\n * a consistent, non-blocking flow.\n *\n * @param payload The data to send with the event.\n */\n public dispatch(payload: T): void {\n this.logger_.logMethodArgs?.('dispatch', {payload});\n this.checkDestroyed_();\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(payload));\n }\n}\n",
|
|
7
7
|
"import {delay} from '@alwatr/delay';\nimport {createLogger, type AlwatrLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {StateSignalConfig, ListenerCallback, SubscribeOptions, SubscribeResult, IReadonlySignal} from '../type.js';\n\n/**\n * A stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n * @implements {IReadonlySignal<T>}\n *\n * @example\n * // Create a new state signal with an initial value.\n * const counter = new StateSignal<number>({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * // Get the current value.\n * console.log(counter.get()); // Outputs: 0\n *\n * // Subscribe to changes.\n * const subscription = counter.subscribe(newValue => {\n * console.log(`Counter changed to: ${newValue}`);\n * });\n *\n * // Set a new value, which triggers the notification.\n * counter.set(1); // Outputs: \"Counter changed to: 1\"\n *\n * // Update value based on the previous value.\n * counter.update(current => current + 1); // Outputs: \"Counter changed to: 2\"\n *\n * // Unsubscribe when no longer needed.\n * subscription.unsubscribe();\n */\nexport class StateSignal<T> extends SignalBase<T> implements IReadonlySignal<T> {\n /**\n * The current value of the signal.\n * @private\n */\n private value__: T;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_: AlwatrLogger;\n\n /**\n * Indicates if a notification is already scheduled.\n * @private\n */\n private notifyPending__ = false;\n\n /**\n * The version of the last notification.\n * @private\n */\n private notifyVersion__ = 0;\n\n constructor(config: StateSignalConfig<T>) {\n super({\n name: config.name,\n onDestroy: config.onDestroy,\n });\n this.logger_ = createLogger(`state-signal:${this.name}`);\n this.value__ = config.initialValue;\n this.logger_.logMethodArgs?.('constructor', {initialValue: this.value__});\n }\n\n /**\n * Retrieves the current value of the signal.\n *\n * @returns The current value.\n *\n * @example\n * console.log(mySignal.get());\n */\n public get(): T {\n this.checkDestroyed_();\n return this.value__;\n }\n\n /**\n * Updates the signal's value and notifies all active listeners.\n *\n * The notification is scheduled as a microtask, which means the update is deferred\n * slightly to batch multiple synchronous changes.\n *\n * @param newValue The new value to set.\n *\n * @example\n * // For primitive types\n * mySignal.set(42);\n *\n * // For object types, it's best practice to set an immutable new object.\n * mySignal.set({ ...mySignal.get(), property: 'new-value' });\n */\n public set(newValue: T): void {\n this.logger_.logMethodArgs?.('set', {newValue});\n\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 this.notifyChange();\n }\n\n /**\n * Notifies all listeners about the current value, even if it hasn't changed.\n *\n * This method is useful when you change the value instance directly (e.g., mutating an object) and want to inform listeners about the change.\n */\n public notifyChange(): void {\n this.logger_.logMethod?.('notifyChange');\n this.checkDestroyed_();\n\n this.notifyVersion__++;\n if (this.notifyPending__) return;\n this.notifyPending__ = true;\n\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => {\n this.notifyPending__ = false;\n this.notify_(this.value__);\n });\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 const result = super.subscribe(callback, options);\n\n if (options.receivePrevious === false) return result; // If the subscriber opts out of receiving the current value, skip the immediate callback.\n if (this.notifyPending__) return result; // If a notification is already pending, the callback will be called with the latest value when the notification is processed.\n\n const subscribeVersion = this.notifyVersion__;\n delay\n .nextMicrotask()\n .then((): void => {\n this.logger_.logStep?.('subscribe', 'immediate_callback');\n if (this.notifyVersion__ !== subscribeVersion) return; // A notification occurred after subscribing, so skip the immediate callback.\n if (options.once) {\n result.unsubscribe();\n }\n callback(this.value__);\n })\n .catch((err) => this.logger_.error('subscribe', 'immediate_callback_failed', err));\n\n return result;\n }\n\n /**\n * Destroys the signal, clearing its value and all listeners.\n * This is crucial for memory management to prevent leaks.\n */\n public override destroy(): void {\n this.value__ = null as T; // Clear the value to allow for garbage collection.\n super.destroy();\n }\n\n public asReadonly(): IReadonlySignal<T> {\n return this;\n }\n}\n",
|
|
8
8
|
"import { delay } from '@alwatr/delay';\nimport { createLogger, type AlwatrLogger } from '@alwatr/logger';\n\nimport { StateSignal } from './state-signal.js';\n\nimport type { ComputedSignalConfig, IReadonlySignal, SubscribeResult, SubscribeOptions } from '../type.js';\n\n/**\n * A read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @example\n * // --- Create dependency signals ---\n * const firstName = new StateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = new StateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * // --- Create a computed signal ---\n * const fullName = new ComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // Outputs: \"John Doe\"\n *\n * // --- Subscribe to the computed value ---\n * fullName.subscribe(newFullName => {\n * console.log(`Name changed to: ${newFullName}`);\n * });\n *\n * // --- Update a dependency ---\n * lastName.set('Smith'); // Recalculates and logs: \"Name changed to: John Smith\"\n * console.log(fullName.get()); // Outputs: \"John Smith\"\n *\n * // --- IMPORTANT: Clean up when done ---\n * fullName.destroy();\n */\nexport class ComputedSignal<T> implements IReadonlySignal<T> {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name: string;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_: AlwatrLogger;\n\n /**\n * The internal `StateSignal` that holds the computed value.\n * This is how the computed signal provides `.get()` and `.subscribe()` methods.\n * @protected\n */\n protected readonly internalSignal_: StateSignal<T>;\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent recalculations.\n * @private\n */\n private isRecalculating__ = false;\n\n constructor(protected config_: ComputedSignalConfig<T>) {\n this.name = config_.name;\n this.logger_ = createLogger(`computed-signal:${this.name}`);\n this.recalculate_ = this.recalculate_.bind(this);\n\n this.logger_.logMethod?.('constructor');\n\n this.internalSignal_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\n\n // Subscribe to all dependencies to trigger recalculation on change.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', { signal: signal.name });\n this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_, { receivePrevious: false }));\n }\n }\n\n /**\n * The current value of the computed signal.\n * Accessing this property returns the memoized value and does not trigger a recalculation.\n *\n * @returns The current computed value.\n * @throws {Error} If accessed after the signal has been destroyed.\n */\n public get(): T {\n return this.internalSignal_.get();\n }\n\n /**\n * Indicates whether the computed signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.internalSignal_.isDestroyed;\n }\n\n /**\n * Subscribes a listener to this signal.\n * The listener will be called whenever the computed value changes.\n *\n * @param callback The function to be called with the new value.\n * @param options Subscription options.\n * @returns A `SubscribeResult` object with an `unsubscribe` method.\n */\n public subscribe(callback: (value: T) => void, options?: SubscribeOptions): SubscribeResult {\n return this.internalSignal_.subscribe(callback, options);\n }\n\n /**\n * Returns a Promise that resolves with the next computed value.\n *\n * @returns A Promise that resolves with the next value.\n */\n public untilNext(): Promise<T> {\n return this.internalSignal_.untilNext();\n }\n\n /**\n * Permanently disposes of the computed signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping future recalculations and allowing the signal to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks.\n *\n * After `destroy()` is called, any attempt to access `.get()` or `.subscribe()` will throw an error.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n /**\n * If already destroyed, log an incident and return early.\n */\n if (this.isDestroyed) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.internalSignal_.destroy(); // Destroy the internal signal.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as ComputedSignalConfig<T>; // Release config closure.\n }\n\n /**\n * Schedules a recalculation of the signal's value.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `get` function runs only once per event loop tick, even if multiple dependencies\n * change in the same synchronous block of code.\n * @protected\n */\n protected async recalculate_(): Promise<void> {\n this.logger_.logMethod?.('recalculate_');\n\n if (this.internalSignal_.isDestroyed) {\n // This check is important in case a dependency fires after this signal is destroyed.\n this.logger_.incident?.('recalculate_', 'recalculate_on_destroyed_signal');\n return;\n }\n\n if (this.isRecalculating__) {\n // If a recalculation is already scheduled, do nothing.\n this.logger_.logStep?.('recalculate_', 'skipping_recalculation_already_scheduled');\n return;\n }\n\n this.isRecalculating__ = true;\n\n try {\n // Wait for the next macrotask to start the recalculation.\n // This batches all synchronous dependency updates in the current event loop.\n await delay.nextMacrotask();\n\n if (this.isDestroyed) {\n this.logger_.incident?.('recalculate_', 'destroyed_during_delay');\n this.isRecalculating__ = false;\n return;\n }\n\n this.logger_.logStep?.('recalculate_', 'recalculating_value');\n\n // Set the new value on the internal signal, which will notify our subscribers.\n this.internalSignal_.set(this.config_.get());\n }\n catch (err) {\n this.logger_.error('recalculate_', 'recalculation_failed', err);\n }\n\n // Allow the next recalculation to be scheduled.\n this.isRecalculating__ = false;\n }\n}\n",
|
|
9
9
|
"import { delay } from '@alwatr/delay';\nimport { createLogger, type AlwatrLogger } 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: string;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_: AlwatrLogger;\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.name = config_.name ?? `[${config_.deps.map((dep) => dep.name).join(', ')}]`;\n this.logger_ = createLogger(`effect-signal:${this.name}`);\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n this.logger_.logMethod?.('constructor');\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",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"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",
|
|
22
22
|
"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"
|
|
23
23
|
],
|
|
24
|
-
"mappings": ";AASO,MAAe,CAAc,CAoCZ,QA/BN,KAYG,mBAAqB,IAAI,IACzB,WAAa,IAAI,IAM5B,cAAgB,MAQb,YAAW,EAAY,CAChC,OAAO,KAAK,cAGd,WAAW,CAAW,EAAuB,CAAvB,eACpB,KAAK,KAAO,EAAQ,KASZ,eAAe,CAAC,EAA8B,CAGtD,GAFA,KAAK,QAAQ,YAAY,iBAAiB,EAEtC,KAAK,cAAe,CACtB,KAAK,QAAQ,WAAW,kBAAmB,qCAAqC,EAChF,OAGF,KAAK,mBAAmB,OAAO,CAAQ,EACvC,KAAK,WAAW,OAAO,CAAQ,EAY1B,SAAS,CAAC,EAA+B,EAA6C,CAC3F,KAAK,QAAQ,gBAAgB,iBAAkB,CAAO,EACtD,KAAK,gBAAgB,EAErB,IAAM,EAAyB,CAAC,WAAU,SAAO,EAEjD,GAAI,GAAS,SACX,KAAK,mBAAmB,IAAI,CAAQ,EAEpC,UAAK,WAAW,IAAI,CAAQ,EAI9B,MAAO,CACL,YAAa,IAAY,KAAK,gBAAgB,CAAQ,CACxD,EAYQ,OAAO,CAAC,EAAgB,CAGhC,GAFA,KAAK,QAAQ,gBAAgB,UAAW,CAAK,EAEzC,KAAK,cAAe,CACtB,KAAK,QAAQ,WAAW,UAAW,4BAA4B,EAC/D,OAGF,QAAW,KA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AM,EACN,KAAM,CAAC,CAAc,EACrB,IAAK,IAAM,EAAe,IAAI,EAC9B,UAAW,IAAM,CACf,GAAI,EAAe,YAAa,OAChC,EAAa,YAAY,EACzB,EAAU,OAAO,EACjB,EAAe,QAAQ,EACvB,EAAO,YAAY,EACnB,EAAS,KAEb,CAAC,ECxCI,SAAS,EAAuB,CACrC,EACA,EACA,EAAO,GAAG,EAAa,gBACQ,CAC/B,IAAM,EAAc,EAAa,IAAI,EAC/B,EAAe,EAAU,CAAW,EAAI,EAAc,OAEtD,EAAiB,EAAkB,CACvC,KAAM,GAAG,aACT,cACF,CAAC,EAEK,EAAe,EAAa,UAAU,CAAC,IAAa,CACxD,GAAI,EAAU,CAAQ,EACpB,EAAe,IAAI,CAAQ,EAE9B,EAED,OAAO,EAAqB,CAC1B,KAAM,EACN,KAAM,CAAC,CAAc,EACrB,IAAK,IAAM,EAAe,IAAI,EAC9B,UAAW,IAAM,CACf,EAAa,YAAY,EACzB,EAAe,QAAQ,EAE3B,CAAC,ECvCI,SAAS,EAAwB,CACtC,EACA,EACA,EAAO,GAAG,EAAa,cACJ,CACnB,OAAO,EAAqB,CAC1B,KAAM,EACN,KAAM,CAAC,CAAY,EACnB,IAAK,IAAM,EAAgB,EAAa,IAAI,CAAC,CAC/C,CAAC",
|
|
25
|
+
"debugId": "2A6AFA49C59E6EB664756E2164756E21",
|
|
26
26
|
"names": []
|
|
27
27
|
}
|
package/dist/type.d.ts
CHANGED
|
@@ -114,21 +114,16 @@ export interface StateSignalConfig<T> extends SignalConfig {
|
|
|
114
114
|
readonly initialValue: T;
|
|
115
115
|
}
|
|
116
116
|
/**
|
|
117
|
-
* Represents a signal that can be
|
|
118
|
-
*
|
|
119
|
-
* as dependencies in other signals without exposing their `set` or `dispatch` methods.
|
|
117
|
+
* Represents a signal that can be subscribed to for changes, but does not allow direct modification of its value.
|
|
118
|
+
* This is the base interface for both `StateSignal` and `ComputedSignal`, allowing them to be used as dependencies
|
|
120
119
|
*
|
|
121
120
|
* @template T The type of the signal's value.
|
|
122
121
|
*/
|
|
123
|
-
export interface
|
|
122
|
+
export interface IBaseSignal<T> {
|
|
124
123
|
/**
|
|
125
124
|
* The unique identifier for this signal instance. Useful for debugging.
|
|
126
125
|
*/
|
|
127
126
|
readonly name: string;
|
|
128
|
-
/**
|
|
129
|
-
* The current value of the signal.
|
|
130
|
-
*/
|
|
131
|
-
get: () => T;
|
|
132
127
|
/**
|
|
133
128
|
* Indicates whether the signal has been destroyed.
|
|
134
129
|
* A destroyed signal cannot be used and will throw an error if interacted with.
|
|
@@ -166,6 +161,19 @@ export interface IReadonlySignal<T> {
|
|
|
166
161
|
*/
|
|
167
162
|
destroy(): void;
|
|
168
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* Represents a signal that can be read from but not written to.
|
|
166
|
+
* Both `StateSignal` and `ComputedSignal` implement this interface, allowing them to be used
|
|
167
|
+
* as dependencies in other signals without exposing their `set` or `dispatch` methods.
|
|
168
|
+
*
|
|
169
|
+
* @template T The type of the signal's value.
|
|
170
|
+
*/
|
|
171
|
+
export interface IReadonlySignal<T> extends IBaseSignal<T> {
|
|
172
|
+
/**
|
|
173
|
+
* The current value of the signal.
|
|
174
|
+
*/
|
|
175
|
+
get: () => T;
|
|
176
|
+
}
|
|
169
177
|
/**
|
|
170
178
|
* A list of `IReadonlySignal` instances that a computed or effect signal depends on.
|
|
171
179
|
* This ensures that dependencies can be read from but not modified by the dependent signal.
|
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,SAAS,EAAC,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,uBAAuB,CAAC;AAEtE;;;;;;;GAOG;AACH,MAAM,MAAM,gBAAgB,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tG;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;GAKG;AACH,MAAM,WAAW,wBAAwB,CAAC,CAAC,CAAE,SAAQ,iBAAiB,CAAC,CAAC,CAAC;IACvE;;;;;;;;OAQG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/signal",
|
|
3
|
-
"version": "9.23.
|
|
3
|
+
"version": "9.23.3",
|
|
4
4
|
"description": "Alwatr Signal is a powerful, lightweight, and modern reactive programming library. It is inspired by the best concepts from major reactive libraries but engineered to be faster and more efficient than all of them. It provides a robust and elegant way to manage application state through a system of signals, offering fine-grained reactivity, predictability, and excellent performance.",
|
|
5
5
|
"license": "MPL-2.0",
|
|
6
6
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
|
|
@@ -21,11 +21,11 @@
|
|
|
21
21
|
},
|
|
22
22
|
"sideEffects": false,
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@alwatr/debounce": "9.
|
|
25
|
-
"@alwatr/delay": "9.
|
|
26
|
-
"@alwatr/local-storage": "9.
|
|
27
|
-
"@alwatr/logger": "9.
|
|
28
|
-
"@alwatr/session-storage": "9.
|
|
24
|
+
"@alwatr/debounce": "9.23.3",
|
|
25
|
+
"@alwatr/delay": "9.23.3",
|
|
26
|
+
"@alwatr/local-storage": "9.23.3",
|
|
27
|
+
"@alwatr/logger": "9.23.3",
|
|
28
|
+
"@alwatr/session-storage": "9.23.3"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@alwatr/nano-build": "9.14.0",
|
|
@@ -66,5 +66,5 @@
|
|
|
66
66
|
"signal",
|
|
67
67
|
"typescript"
|
|
68
68
|
],
|
|
69
|
-
"gitHead": "
|
|
69
|
+
"gitHead": "e38ea606b08ee85402fe112d4e32e741a446dcad"
|
|
70
70
|
}
|
package/src/core/event-signal.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import {delay} from '@alwatr/delay';
|
|
2
|
+
import {createLogger, type AlwatrLogger} from '@alwatr/logger';
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import {SignalBase} from './signal-base.js';
|
|
5
5
|
|
|
6
|
-
import type { SignalConfig
|
|
6
|
+
import type {IBaseSignal, SignalConfig} from '../type.js';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* A stateless signal for dispatching transient events.
|
|
@@ -32,7 +32,7 @@ import type { SignalConfig } from '../type.js';
|
|
|
32
32
|
* onAppReady.subscribe(() => console.log('Application is ready!'));
|
|
33
33
|
* onAppReady.dispatch(); // Notifies the listener.
|
|
34
34
|
*/
|
|
35
|
-
export class EventSignal<T = void> extends SignalBase<T> {
|
|
35
|
+
export class EventSignal<T = void> extends SignalBase<T> implements IBaseSignal<T> {
|
|
36
36
|
/**
|
|
37
37
|
* The logger instance for this signal.
|
|
38
38
|
* @protected
|
|
@@ -53,7 +53,7 @@ export class EventSignal<T = void> extends SignalBase<T> {
|
|
|
53
53
|
* @param payload The data to send with the event.
|
|
54
54
|
*/
|
|
55
55
|
public dispatch(payload: T): void {
|
|
56
|
-
this.logger_.logMethodArgs?.('dispatch', {
|
|
56
|
+
this.logger_.logMethodArgs?.('dispatch', {payload});
|
|
57
57
|
this.checkDestroyed_();
|
|
58
58
|
// Dispatch as a microtask to ensure consistent, non-blocking behavior.
|
|
59
59
|
delay.nextMicrotask().then(() => this.notify_(payload));
|
package/src/type.ts
CHANGED
|
@@ -125,23 +125,17 @@ export interface StateSignalConfig<T> extends SignalConfig {
|
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
/**
|
|
128
|
-
* Represents a signal that can be
|
|
129
|
-
*
|
|
130
|
-
* as dependencies in other signals without exposing their `set` or `dispatch` methods.
|
|
128
|
+
* Represents a signal that can be subscribed to for changes, but does not allow direct modification of its value.
|
|
129
|
+
* This is the base interface for both `StateSignal` and `ComputedSignal`, allowing them to be used as dependencies
|
|
131
130
|
*
|
|
132
131
|
* @template T The type of the signal's value.
|
|
133
132
|
*/
|
|
134
|
-
export interface
|
|
133
|
+
export interface IBaseSignal<T> {
|
|
135
134
|
/**
|
|
136
135
|
* The unique identifier for this signal instance. Useful for debugging.
|
|
137
136
|
*/
|
|
138
137
|
readonly name: string;
|
|
139
138
|
|
|
140
|
-
/**
|
|
141
|
-
* The current value of the signal.
|
|
142
|
-
*/
|
|
143
|
-
get: () => T;
|
|
144
|
-
|
|
145
139
|
/**
|
|
146
140
|
* Indicates whether the signal has been destroyed.
|
|
147
141
|
* A destroyed signal cannot be used and will throw an error if interacted with.
|
|
@@ -183,6 +177,20 @@ export interface IReadonlySignal<T> {
|
|
|
183
177
|
destroy(): void;
|
|
184
178
|
}
|
|
185
179
|
|
|
180
|
+
/**
|
|
181
|
+
* Represents a signal that can be read from but not written to.
|
|
182
|
+
* Both `StateSignal` and `ComputedSignal` implement this interface, allowing them to be used
|
|
183
|
+
* as dependencies in other signals without exposing their `set` or `dispatch` methods.
|
|
184
|
+
*
|
|
185
|
+
* @template T The type of the signal's value.
|
|
186
|
+
*/
|
|
187
|
+
export interface IReadonlySignal<T> extends IBaseSignal<T> {
|
|
188
|
+
/**
|
|
189
|
+
* The current value of the signal.
|
|
190
|
+
*/
|
|
191
|
+
get: () => T;
|
|
192
|
+
}
|
|
193
|
+
|
|
186
194
|
/**
|
|
187
195
|
* A list of `IReadonlySignal` instances that a computed or effect signal depends on.
|
|
188
196
|
* This ensures that dependencies can be read from but not modified by the dependent signal.
|