All files / src/notifier implementation.ts

100% Statements 48/48
86.66% Branches 26/30
100% Functions 9/9
100% Lines 48/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235                                                                                                                                                                                                          12x                                                           445x     445x 445x   6x 6x             445x 591x 376x     215x   591x 213x 213x 213x 1x 1x 1x 1x               4x 4x 4x               215x 16x 16x 16x       445x 445x   13x       445x   275x 275x   275x 2x 2x     275x       116x 116x 116x 116x   116x   9x 9x 9x 9x             21x 18x 18x   21x                
import { debounce } from '../utils/async/debounce.ts';
import type { DeferredValue } from '../utils/async/deferred-value.ts';
import { createDeferredValue } from '../utils/async/deferred-value.ts';
import { ClosedError } from '../utils/common/closed-error.ts';
import type { EventNotifier } from './definition.ts';
 
/**
 * Creates a type-safe event notifier.
 *
 * This utility helps you implement observable patterns in a lightweight way.
 *
 * The typical usage pattern is:
 *
 * - Create a private notifier using `createEventNotifier()`
 * - Expose a public `onEvent` method so clients can register listeners
 * - Use notify to emit events when something happens and listeners are registered.
 * - Optionally handle listener errors using `onError`
 * - Optionally observe lifecycle changes (listener/waiter activity or closure) using `onChange`
 *
 * All listeners are automatically cleaned up via the returned `close()` methods.
 *
 * When `debounceDelay` is specified, rapid successive calls to `notify()` will be debounced, ensuring that all
 * listeners (and `waitForEvent()`) receive only the final event after the delay period. This is useful for scenarios
 * like file watching, user input handling, or batching rapid state changes. For more complex debouncing needs (argument
 * accumulation, leading edge execution, etc.), consider using the `debounce` utility directly on your notification
 * logic.
 *
 * @example Basic usage
 *
 * ```ts
 * import { createEventNotifier } from 'emitnlog/notifier';
 *
 * class Car {
 *   private _onStartNotifier = createEventNotifier<{ mileage: number }>();
 *   public onStart = this._onStartNotifier.onEvent;
 *
 *   private _onStopNotifier = createEventNotifier<{ engineOn: boolean }>();
 *   public onStop = this._onStopNotifier.onEvent;
 *
 *   public start() {
 *     // Use lazy evaluation: compute only if someone is listening
 *     this._onStartNotifier.notify(() => ({ mileage: this.computeMileage() }));
 *   }
 *
 *   public stop() {
 *     this._onStopNotifier.notify({ engineOn: this.isRunning() });
 *   }
 *
 *   private computeMileage(): number {
 *     // expensive computation
 *     return 42;
 *   }
 *
 *   private isRunning(): boolean {
 *     return true;
 *   }
 * }
 *
 * const car = new Car();
 *
 * const startListener = car.onStart((event) => {
 *   console.log(`Car started with mileage ${event.mileage}`);
 * });
 *
 * const stopListener = car.onStop((event) => {
 *   console.log(`Car stopped. Engine on? ${event.engineOn}`);
 * });
 *
 * car.start();
 * car.stop();
 *
 * // Unsubscribe later
 * startListener.close();
 * stopListener.close();
 * ```
 *
 * @example With debounced notifications
 *
 * ```ts
 * import { createEventNotifier } from 'emitnlog/notifier';
 *
 * const fileWatcher = createEventNotifier<{ path: string }>({ debounceDelay: 300 });
 *
 * fileWatcher.onEvent(({ path }) => {
 *   console.log(`File changed: ${path}`);
 * });
 *
 * // Rapid file changes - only the last one triggers listeners
 * fileWatcher.notify({ path: 'file1.txt' });
 * fileWatcher.notify({ path: 'file2.txt' });
 * fileWatcher.notify({ path: 'file3.txt' });
 * // After 300ms: logs "File changed: file3.txt"
 *
 * // waitForEvent also gets the debounced result
 * const finalEvent = await fileWatcher.waitForEvent(); // { path: 'file3.txt' }
 * ```
 *
 * @template T The shape of the event data.
 * @param options Optional configuration including debounce delay.
 * @returns An EventNotifier that supports listener registration, notification, and error handling.
 */
export const createEventNotifier = <T = void>(options?: {
  /**
   * The debounce delay for notifications in milliseconds.
   */
  readonly debounceDelay?: number;
 
  /**
   * Sets an error handler for the notifier, to be called whenever a listener throws an error.
   *
   * Errors throw by the handler are ignored.
   */
  readonly onError?: (error: unknown) => void;
 
  /**
   * Sets a handler for the notifier, to be called whenever the notifier state changes.
   *
   * Errors throw by the handler are ignored.
   */
  readonly onChange?: (event: {
    /**
     * Whether the notifier is active, i.e., if there is at least one listener or one wait event.
     */
    readonly active?: boolean;
 
    /**
     * The reason for the state change.
     */
    readonly reason: ChangeReason;
  }) => void;
}): EventNotifier<T> => {
  const listeners = new Set<(event: T) => unknown>();
  let deferredEvent: DeferredValue<T> | undefined;
 
  const onChange = options?.onChange;
  const notifyOnChange = onChange
    ? (reason: ChangeReason) => {
        try {
          onChange({ active: Boolean(listeners.size || deferredEvent), reason });
        } catch {
          // ignore
        }
      }
    : undefined;
 
  const basicNotify = (event?: T | (() => T)) => {
    if (!listeners.size && !deferredEvent) {
      return;
    }
 
    const value: T = typeof event === 'function' ? (event as () => T)() : (event as T);
 
    for (const listener of listeners) {
      try {
        const result = listener(value);
        if (result instanceof Promise) {
          void result.catch((error: unknown) => {
            Eif (options?.onError) {
              try {
                options.onError(error);
              } catch {
                // ignore
              }
            }
          });
        }
      } catch (error) {
        Eif (options?.onError) {
          try {
            options.onError(error);
          } catch {
            // ignore
          }
        }
      }
    }
 
    if (deferredEvent) {
      deferredEvent.resolve(value);
      deferredEvent = undefined;
      notifyOnChange?.('waiter-resolved');
    }
  };
 
  const debounced = options?.debounceDelay !== undefined ? debounce(basicNotify, options.debounceDelay) : undefined;
  const notify: (event?: T | (() => T)) => void = debounced
    ? (event?: T | (() => T)) => {
        void debounced(event);
      }
    : basicNotify;
 
  return {
    close: () => {
      debounced?.cancel(true);
      listeners.clear();
 
      if (deferredEvent) {
        deferredEvent.reject(new ClosedError('EventNotifier closed'));
        deferredEvent = undefined;
      }
 
      notifyOnChange?.('closed');
    },
 
    onEvent: (listener) => {
      const beforeAddSize = listeners.size;
      listeners.add(listener);
      Eif (beforeAddSize !== listeners.size) {
        notifyOnChange?.('listener-added');
      }
      return {
        close: () => {
          const beforeDeleteSize = listeners.size;
          listeners.delete(listener);
          Eif (beforeDeleteSize !== listeners.size) {
            notifyOnChange?.('listener-removed');
          }
        },
      };
    },
 
    waitForEvent: () => {
      if (!deferredEvent) {
        deferredEvent = createDeferredValue<T>();
        notifyOnChange?.('waiter-added');
      }
      return deferredEvent.promise;
    },
 
    notify,
  };
};
 
type ChangeReason = 'listener-added' | 'listener-removed' | 'waiter-added' | 'waiter-resolved' | 'closed';