All files / notifier implementation.ts

100% Statements 26/26
100% Branches 14/14
100% Functions 7/7
100% Lines 25/25

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 1518x   8x                                                                                                                                                                                           8x 359x       359x 462x 271x     191x 12x     191x 189x 189x   6x 4x         191x 15x 15x       359x   68x 68x       103x 103x   8x         18x         7x        
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 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`
 *
 * 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
 * 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
 * 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.
 * @template E Optional error type (defaults to Error).
 * @param options Optional configuration including debounce delay.
 * @returns An EventNotifier that supports listener registration, notification, and error handling.
 */
export const createEventNotifier = <T = void, E = Error>(options?: { debounceDelay?: number }): EventNotifier<T, E> => {
  const listeners = new Set<(event: T) => unknown>();
  let errorHandler: ((error: E) => void) | undefined;
  let deferredEvent: DeferredValue<T> | undefined;
 
  const notify = (event: T | (() => T)) => {
    if (!listeners.size && !deferredEvent) {
      return;
    }
 
    if (typeof event === 'function') {
      event = (event as () => T)();
    }
 
    for (const listener of listeners) {
      try {
        void listener(event);
      } catch (error) {
        if (errorHandler) {
          errorHandler(error as E);
        }
      }
    }
 
    if (deferredEvent) {
      deferredEvent.resolve(event);
      deferredEvent = undefined;
    }
  };
 
  return {
    close: () => {
      listeners.clear();
      errorHandler = undefined;
    },
 
    onEvent: (listener) => {
      listeners.add(listener);
      return {
        close: () => {
          listeners.delete(listener);
        },
      };
    },
 
    waitForEvent: () => (deferredEvent || (deferredEvent = createDeferredValue<T>())).promise,
 
    notify: options?.debounceDelay !== undefined ? debounce(notify, options.debounceDelay) : notify,
 
    onError: (handler) => {
      errorHandler = handler;
    },
  };
};