evnty 4.1.0 → 4.2.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/build/index.cjs CHANGED
@@ -60,8 +60,15 @@ class Callable extends Function {
60
60
  }
61
61
  }
62
62
  class Unsubscribe extends Callable {
63
+ _done = false;
63
64
  constructor(callback){
64
- super(callback);
65
+ super(()=>{
66
+ this._done = true;
67
+ callback();
68
+ });
69
+ }
70
+ get done() {
71
+ return this._done;
65
72
  }
66
73
  pre(callback) {
67
74
  return new Unsubscribe(async ()=>{
@@ -83,15 +90,22 @@ class Unsubscribe extends Callable {
83
90
  });
84
91
  }
85
92
  }
93
+ var SpyType;
94
+ (function(SpyType) {
95
+ SpyType[SpyType["Add"] = 0] = "Add";
96
+ SpyType[SpyType["Remove"] = 1] = "Remove";
97
+ })(SpyType || (SpyType = {}));
86
98
  class Event extends Callable {
87
99
  listeners;
88
100
  spies = [];
101
+ _disposed = false;
89
102
  dispose;
90
103
  constructor(dispose){
91
104
  const listeners = [];
92
105
  super(async (value)=>Promise.all(listeners.map(async (listener)=>listener(await value))));
93
106
  this.listeners = listeners;
94
107
  this.dispose = async ()=>{
108
+ this._disposed = true;
95
109
  void this.clear();
96
110
  await this._error?.dispose();
97
111
  await dispose?.();
@@ -104,6 +118,9 @@ class Event extends Callable {
104
118
  get size() {
105
119
  return this.listeners.length;
106
120
  }
121
+ get disposed() {
122
+ return this._disposed;
123
+ }
107
124
  lacks(listener) {
108
125
  return this.listeners.indexOf(listener) === -1;
109
126
  }
@@ -114,12 +131,17 @@ class Event extends Callable {
114
131
  if (removeListener(this.listeners, listener) && this.spies.length) {
115
132
  [
116
133
  ...this.spies
117
- ].forEach((spy)=>spy(listener));
134
+ ].forEach((spy)=>spy(listener, 1));
118
135
  }
119
136
  return this;
120
137
  }
121
138
  on(listener) {
122
139
  this.listeners.push(listener);
140
+ if (this.spies.length) {
141
+ [
142
+ ...this.spies
143
+ ].forEach((spy)=>spy(listener, 0));
144
+ }
123
145
  return new Unsubscribe(()=>{
124
146
  void this.off(listener);
125
147
  });
@@ -136,7 +158,7 @@ class Event extends Callable {
136
158
  if (this.spies.length) {
137
159
  [
138
160
  ...this.spies
139
- ].forEach((spy)=>spy());
161
+ ].forEach((spy)=>spy(undefined, 1));
140
162
  }
141
163
  return this;
142
164
  }
@@ -159,8 +181,8 @@ class Event extends Callable {
159
181
  queue.splice(0);
160
182
  await doneEvent.dispose();
161
183
  });
162
- const spy = (target = emitEvent)=>{
163
- if (target === emitEvent) {
184
+ const spy = (target = emitEvent, action)=>{
185
+ if (target === emitEvent && action === 1) {
164
186
  void doneEvent(true);
165
187
  void unsubscribe();
166
188
  }
@@ -207,8 +229,8 @@ class Event extends Callable {
207
229
  const unsubscribe = this.on(emitEvent).pre(()=>{
208
230
  removeListener(this.spies, spy);
209
231
  });
210
- const spy = (target = emitEvent)=>{
211
- if (target === emitEvent) {
232
+ const spy = (target = emitEvent, action)=>{
233
+ if (target === emitEvent && action === 1) {
212
234
  void unsubscribe();
213
235
  }
214
236
  };
@@ -354,6 +376,9 @@ class Event extends Callable {
354
376
  get stopped () {
355
377
  return done;
356
378
  },
379
+ then (onfulfilled, onrejected) {
380
+ return this.pop().then(onfulfilled, onrejected);
381
+ },
357
382
  [Symbol.asyncIterator] () {
358
383
  return {
359
384
  next: async ()=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type MaybePromise<T> = Promise<T> | PromiseLike<T> | T;\n\nexport interface Callback<R = void> {\n (): MaybePromise<R>;\n}\n\nexport interface Listener<T, R = unknown> {\n (event: T): MaybePromise<R | void>;\n}\n\nexport interface FilterFunction<T> {\n (event: T): MaybePromise<boolean>;\n}\n\nexport interface Predicate<T, P extends T> {\n (event: T): event is P;\n}\n\nexport type Filter<T, P extends T> = Predicate<T, P> | FilterFunction<T>;\n\nexport interface Mapper<T, R> {\n (event: T): MaybePromise<R>;\n}\n\nexport interface Reducer<T, R> {\n (result: R, event: T): MaybePromise<R>;\n}\n\nexport interface Expander<T, R> {\n (event: T): MaybePromise<R>;\n}\n\n/**\n * Removes a listener from the provided array of listeners. It searches for the listener and removes all instances of it from the array.\n * This method ensures that the listener is fully unregistered, preventing any residual calls to a potentially deprecated handler.\n *\n * @internal\n * @param {Listener<T, R>[]} listeners - The array of listeners from which to remove the listener.\n * @param {Listener<T, R>} listener - The listener function to remove from the list of listeners.\n * @returns {boolean} - Returns `true` if the listener was found and removed, `false` otherwise.\n *\n * @template T - The type of the event that listeners are associated with.\n * @template R - The type of the return value that listeners are expected to return.\n *\n * ```typescript\n * // Assuming an array of listeners for click events\n * const listeners = [onClickHandler1, onClickHandler2];\n * const wasRemoved = removeListener(listeners, onClickHandler1);\n * console.log(wasRemoved); // Output: true\n * ```\n */\nexport const removeListener = <T, R>(listeners: Listener<T, R>[], listener: Listener<T, R>): boolean => {\n let index = listeners.indexOf(listener);\n const wasRemoved = index !== -1;\n while (~index) {\n listeners.splice(index, 1);\n index = listeners.indexOf(listener);\n }\n return wasRemoved;\n};\n\n/**\n * @internal\n * @param timeout\n * @param signal\n * @returns\n */\nexport const setTimeoutAsync = (timeout: number, signal?: AbortSignal) =>\n new Promise<boolean>((resolve) => {\n const timerId = setTimeout(resolve, timeout, true);\n signal?.addEventListener('abort', () => {\n clearTimeout(timerId);\n resolve(false);\n });\n });\n\n/**\n * An abstract class that extends the built-in Function class. It allows instances of the class\n * to be called as functions. When an instance of Callable is called as a function, it will\n * call the function passed to its constructor with the same arguments.\n * @internal\n */\nexport abstract class Callable extends Function {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n constructor(func: Function) {\n super();\n return Object.setPrototypeOf(func, new.target.prototype);\n }\n}\n\nexport interface Unsubscribe {\n (): MaybePromise<void>;\n}\n\n/**\n * @internal\n */\nexport class Unsubscribe extends Callable {\n constructor(callback: Callback) {\n super(callback);\n }\n\n pre(callback: Callback): Unsubscribe {\n return new Unsubscribe(async () => {\n await callback();\n await this();\n });\n }\n\n post(callback: Callback): Unsubscribe {\n return new Unsubscribe(async () => {\n await this();\n await callback();\n });\n }\n\n countdown(count: number): Unsubscribe {\n return new Unsubscribe(async () => {\n if (!--count) {\n await this();\n }\n });\n }\n}\n\nexport interface Queue<T> extends AsyncIterable<T> {\n pop(): MaybePromise<T>;\n stop(): MaybePromise<void>;\n stopped: boolean;\n}\n\nexport interface Event<T = any, R = any> {\n (event: T): Promise<(void | Awaited<R>)[]>;\n}\n\n/**\n * A class representing an anonymous event that can be listened to or triggered.\n *\n * @template T - The event type.\n * @template R - The return type of the event.\n */\nexport class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLike<T> {\n /**\n * The array of listeners for the event.\n */\n private listeners: Listener<T, R>[];\n\n private spies: Array<(listener: Listener<T, R> | void) => void> = [];\n\n /**\n * A function that disposes of the event and its listeners.\n */\n readonly dispose: Callback;\n\n /**\n * Creates a new event.\n *\n * @param dispose - A function to call on the event disposal.\n *\n * ```typescript\n * // Create a click event.\n * const clickEvent = new Event<[x: number, y: number], void>();\n * clickEvent.on(([x, y]) => console.log(`Clicked at ${x}, ${y}`));\n * ```\n */\n constructor(dispose?: Callback) {\n const listeners: Listener<T, R>[] = [];\n // passes listeners exceptions to catch method\n super(async (value: T): Promise<(void | Awaited<R>)[]> => Promise.all(listeners.map(async (listener) => listener(await value))));\n this.listeners = listeners;\n\n this.dispose = async () => {\n void this.clear();\n await this._error?.dispose();\n await dispose?.();\n };\n }\n\n private _error?: Event<unknown>;\n\n /**\n * Error event that emits errors.\n *\n * @returns {Event<unknown>} The error event.\n */\n get error(): Event<unknown> {\n return (this._error ??= new Event<unknown>());\n }\n\n /**\n * The number of listeners for the event.\n *\n * @readonly\n * @type {number}\n */\n get size(): number {\n return this.listeners.length;\n }\n\n /**\n * Checks if the given listener is NOT registered for this event.\n *\n * @param listener - The listener function to check against the registered listeners.\n * @returns `true` if the listener is not already registered; otherwise, `false`.\n *\n * ```typescript\n * // Check if a listener is not already added\n * if (event.lacks(myListener)) {\n * event.on(myListener);\n * }\n * ```\n */\n lacks(listener: Listener<T, R>): boolean {\n return this.listeners.indexOf(listener) === -1;\n }\n\n /**\n * Checks if the given listener is registered for this event.\n *\n * @param listener - The listener function to check.\n * @returns `true` if the listener is currently registered; otherwise, `false`.\n *\n * ```typescript\n * // Verify if a listener is registered\n * if (event.has(myListener)) {\n * console.log('Listener is already registered');\n * }\n * ```\n */\n has(listener: Listener<T, R>): boolean {\n return this.listeners.indexOf(listener) !== -1;\n }\n\n /**\n * Removes a specific listener from this event.\n *\n * @param listener - The listener to remove.\n * @returns The event instance, allowing for method chaining.\n *\n * ```typescript\n * // Remove a listener\n * event.off(myListener);\n * ```\n */\n off(listener: Listener<T, R>): this {\n if (removeListener(this.listeners, listener) && this.spies.length) {\n [...this.spies].forEach((spy) => spy(listener));\n }\n return this;\n }\n\n /**\n * Registers a listener that gets triggered whenever the event is emitted.\n * This is the primary method for adding event handlers that will react to the event being triggered.\n *\n * @param listener - The function to call when the event occurs.\n * @returns An object that can be used to unsubscribe the listener, ensuring easy cleanup.\n *\n * ```typescript\n * // Add a listener to an event\n * const unsubscribe = event.on((data) => {\n * console.log('Event data:', data);\n * });\n * ```\n */\n on(listener: Listener<T, R>): Unsubscribe {\n this.listeners.push(listener);\n return new Unsubscribe(() => {\n void this.off(listener);\n });\n }\n\n /**\n * Adds a listener that will be called only once the next time the event is emitted.\n * This method is useful for one-time notifications or single-trigger scenarios.\n *\n * @param listener - The listener to trigger once.\n * @returns An object that can be used to remove the listener if the event has not yet occurred.\n *\n * ```typescript\n * // Register a one-time listener\n * const onceUnsubscribe = event.once((data) => {\n * console.log('Received data once:', data);\n * });\n * ```\n */\n once(listener: Listener<T, R>): Unsubscribe {\n const oneTimeListener = (event: T) => {\n void this.off(oneTimeListener);\n return listener(event);\n };\n return this.on(oneTimeListener);\n }\n\n /**\n * Removes all listeners from the event, effectively resetting it. This is useful when you need to\n * cleanly dispose of all event handlers to prevent memory leaks or unwanted triggerings after certain conditions.\n *\n * @returns {this} The instance of the event, allowing for method chaining.\n *\n * ```typescript\n * const myEvent = new Event();\n * myEvent.on(data => console.log(data));\n * myEvent.clear(); // Clears all listeners\n * ```\n */\n clear(): this {\n this.listeners.splice(0);\n if (this.spies.length) {\n [...this.spies].forEach((spy) => spy());\n }\n return this;\n }\n\n /**\n * Enables the `Event` to be used in a Promise chain, resolving with the first emitted value.\n *\n * @template TResult1 - The type of the fulfilled value returned by `onfulfilled` (defaults to the event's type).\n * @template TResult2 - The type of the rejected value returned by `onrejected` (defaults to `never`).\n * @param onfulfilled - A function called when the event emits its first value.\n * @param onrejected - A function called if an error occurs before the event emits.\n * @returns A Promise that resolves with the result of `onfulfilled` or `onrejected`.\n *\n * ```typescript\n * const clickEvent = new Event<[number, number]>();\n * await clickEvent;\n * ```\n */\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n const promise = new Promise<T>((resolve) => this.once(resolve));\n\n return promise.then(onfulfilled, onrejected);\n }\n\n /**\n * A promise that resolves with the first emitted value from this event.\n *\n * @returns {Promise<T>} The promise value.\n */\n get promise(): Promise<T> {\n return this.then((v) => v);\n }\n\n /**\n * Makes this event iterable using `for await...of` loops.\n *\n * @returns An async iterator that yields values as they are emitted by this event.\n *\n * ```typescript\n * // Assuming an event that emits numbers\n * const numberEvent = new Event<number>();\n * (async () => {\n * for await (const num of numberEvent) {\n * console.log('Number:', num);\n * }\n * })();\n * await numberEvent(1);\n * await numberEvent(2);\n * await numberEvent(3);\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n const queue: T[] = [];\n const doneEvent = new Event<boolean>();\n const emitEvent = async (value: T) => {\n queue.push(value);\n await doneEvent(false);\n };\n const unsubscribe = this.on(emitEvent).pre(async () => {\n removeListener(this.spies, spy);\n queue.splice(0);\n await doneEvent.dispose();\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent) => {\n if (target === emitEvent) {\n void doneEvent(true);\n void unsubscribe();\n }\n };\n\n this.spies.push(spy);\n return {\n async next() {\n if (queue.length) {\n return { value: queue.shift()!, done: false };\n }\n if (!(await doneEvent)) {\n return { value: queue.shift()!, done: false };\n }\n return { value: undefined, done: true };\n },\n async return(value: unknown) {\n await unsubscribe();\n return { done: true, value };\n },\n };\n }\n\n /**\n * Transforms the event's values using a generator function, creating a new `Event` that emits the transformed values.\n *\n * @template PT - The type of values emitted by the transformed `Event`.\n * @template PR - The return type of the listeners of the transformed `Event`.\n * @param generator - A function that takes the original event's value and returns a generator (sync or async) that yields the transformed values.\n * @returns A new `Event` instance that emits the transformed values.\n *\n * ```typescript\n * const numbersEvent = new Event<number>();\n * const evenNumbersEvent = numbersEvent.pipe(function*(value) {\n * if (value % 2 === 0) {\n * yield value;\n * }\n * });\n * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));\n * await numbersEvent(1);\n * await numbersEvent(2);\n * await numbersEvent(3);\n * ```\n */\n pipe<PT, R>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): Event<PT, R> {\n const emitEvent = async (value: T) => {\n try {\n for await (const generatedValue of generator(value)) {\n await result(generatedValue).catch((e) => result.error(e));\n }\n } catch (e) {\n await result.error(e);\n }\n };\n\n const unsubscribe = this.on(emitEvent).pre(() => {\n removeListener(this.spies, spy);\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent) => {\n if (target === emitEvent) {\n void unsubscribe();\n }\n };\n this.spies.push(spy);\n\n const result = new Event<PT, R>(unsubscribe);\n return result;\n }\n\n /**\n * Creates an async generator that yields values as they are emitted by this event.\n *\n * @template PT - The type of values yielded by the async generator.\n * @param generator - An optional function that takes the original event's value and returns a generator (sync or async)\n * that yields values to include in the async generator.\n * @returns An async generator that yields values from this event as they occur.\n *\n * ```typescript\n * const numbersEvent = new Event<number>();\n * const evenNumbersEvent = numbersEvent.pipe(function*(value) {\n * if (value % 2 === 0) {\n * yield value;\n * }\n * });\n * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));\n * await numbersEvent(1);\n * await numbersEvent(2);\n * await numbersEvent(3);\n * ```\n */\n async *generator<PT>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): AsyncGenerator<Awaited<PT>, void, unknown> {\n for await (const value of this.pipe(generator)) {\n yield value;\n }\n }\n\n /**\n * Filters events, creating a new event that only triggers when the provided filter function returns `true`.\n * This method can be used to selectively process events that meet certain criteria.\n *\n * @param {Filter<T, P>} predicate The filter function or predicate to apply to each event.\n * @returns {Event<P, R>} A new event that only triggers for filtered events.\n *\n * ```typescript\n * const keyPressedEvent = new Event<string>();\n * const enterPressedEvent = keyPressedEvent.filter(key => key === 'Enter');\n * enterPressedEvent.on(() => console.log('Enter key was pressed.'));\n * ```\n */\n filter<P extends T>(predicate: Predicate<T, P>): Event<P, R>;\n filter<P extends T>(filter: FilterFunction<T>): Event<P, R>;\n filter<P extends T>(filter: Filter<T, P>): Event<P, R> {\n return this.pipe<P, R>(async function* (value: T) {\n if (await filter(value)) {\n yield value as P;\n }\n });\n }\n\n /**\n * Creates a new event that will only be triggered once when the provided filter function returns `true`.\n * This method is useful for handling one-time conditions in a stream of events.\n *\n * @param {Filter<T, P>} predicate - The filter function or predicate.\n * @returns {Event<P, R>} A new event that will be triggered only once when the filter condition is met.\n *\n * ```typescript\n * const sizeChangeEvent = new Event<number>();\n * const sizeReachedEvent = sizeChangeEvent.first(size => size > 1024);\n * sizeReachedEvent.on(() => console.log('Size threshold exceeded.'));\n * ```\n */\n first<P extends T>(predicate: Predicate<T, P>): Event<P, R>;\n first<P extends T>(filter: FilterFunction<T>): Event<P, R>;\n first<P extends T>(filter: Filter<T, P>): Event<P, R> {\n const filteredEvent = this.pipe<P, R>(async function* (value: T) {\n if (await filter(value)) {\n yield value as P;\n await filteredEvent.dispose();\n }\n });\n return filteredEvent;\n }\n\n /**\n * Transforms the data emitted by this event using a mapping function. Each emitted event is processed by the `mapper`\n * function, which returns a new value that is then emitted by the returned `Event` instance. This is useful for data transformation\n * or adapting the event's data structure.\n *\n * @template M The type of data that the mapper function will produce.\n * @template MR The type of data emitted by the mapped event, usually related to or the same as `M`.\n * @param {Mapper<T, M>} mapper A function that takes the original event data and returns the transformed data.\n * @returns {Event<M, MR>} A new `Event` instance that emits the mapped values.\n *\n * ```typescript\n * // Assuming an event that emits numbers, create a new event that emits their squares.\n * const numberEvent = new Event<number>();\n * const squaredEvent = numberEvent.map(num => num * num);\n * squaredEvent.on(squared => console.log('Squared number:', squared));\n * await numberEvent(5); // Logs: \"Squared number: 25\"\n * ```\n */\n map<M, MR = R>(mapper: Mapper<T, M>): Event<Awaited<M>, MR> {\n return this.pipe(async function* (value) {\n yield await mapper(value);\n });\n }\n\n /**\n * Accumulates the values emitted by this event using a reducer function, starting from an initial value. The reducer\n * function takes the accumulated value and the latest emitted event data, then returns a new accumulated value. This\n * new value is then emitted by the returned `Event` instance. This is particularly useful for accumulating state over time.\n *\n * @template A The type of the accumulator value.\n * @template AR The type of data emitted by the reduced event, usually the same as `A`.\n * @param {Reducer<T, A>} reducer A function that takes the current accumulated value and the new event data, returning the new accumulated value.\n * @param {A} init The initial value of the accumulator.\n * @returns {Event<A, AR>} A new `Event` instance that emits the reduced value.\n *\n * ```typescript\n * const sumEvent = numberEvent.reduce((a, b) => a + b, 0);\n * sumEvent.on((sum) => console.log(sum)); // 1, 3, 6\n * await sumEvent(1);\n * await sumEvent(2);\n * await sumEvent(3);\n * ```\n */\n reduce<A, AR = R>(reducer: Reducer<T, A>, init?: A): Event<Awaited<A>, AR>;\n reduce<A, AR = R>(reducer: Reducer<T, A>, ...init: unknown[]): Event<Awaited<A>, AR> {\n let hasInit = init.length === 1;\n let result = init[0] as A | undefined;\n\n return this.pipe(async function* (value) {\n if (hasInit) {\n result = await reducer(result!, value);\n yield result;\n } else {\n result = value as unknown as A;\n hasInit = true;\n }\n });\n }\n\n /**\n * Transforms each event's data into multiple events using an expander function. The expander function takes\n * the original event's data and returns an array of new data elements, each of which will be emitted individually\n * by the returned `Event` instance. This method is useful for scenarios where an event's data can naturally\n * be expanded into multiple, separate pieces of data which should each trigger further processing independently.\n *\n * @template ET - The type of data elements in the array returned by the expander function.\n * @template ER - The type of responses emitted by the expanded event, usually related to or the same as `ET`.\n * @param {Expander<T, ET[]>} expander - A function that takes the original event data and returns an array of new data elements.\n * @returns {Event<ET, ER>} - A new `Event` instance that emits each value from the array returned by the expander function.\n *\n * ```typescript\n * // Assuming an event that emits a sentence, create a new event that emits each word from the sentence separately.\n * const sentenceEvent = new Event<string>();\n * const wordEvent = sentenceEvent.expand(sentence => sentence.split(' '));\n * wordEvent.on(word => console.log('Word:', word));\n * await sentenceEvent('Hello world'); // Logs: \"Word: Hello\", \"Word: world\"\n * ```\n */\n expand<ET, ER>(expander: Expander<T, ET[]>): Event<Awaited<ET>, ER> {\n return this.pipe(async function* (value) {\n const values = await expander(value);\n for (const value of values) {\n yield value;\n }\n });\n }\n\n /**\n * Creates a new event that emits values based on a conductor event. The orchestrated event will emit the last value\n * captured from the original event each time the conductor event is triggered. This method is useful for synchronizing\n * events, where the emission of one event controls the timing of another.\n *\n * @template T The type of data emitted by the original event.\n * @template R The type of data emitted by the orchestrated event, usually the same as `T`.\n * @param {Event<unknown, unknown>} conductor An event that signals when the orchestrated event should emit.\n * @returns {Event<T, R>} An orchestrated event that emits values based on the conductor's trigger.\n *\n * ```typescript\n * const rightClickPositionEvent = mouseMoveEvent.orchestrate(mouseRightClickEvent);\n * ```\n *\n * ```typescript\n * // An event that emits whenever a \"tick\" event occurs.\n * const tickEvent = new Event<void>();\n * const dataEvent = new Event<string>();\n * const synchronizedEvent = dataEvent.orchestrate(tickEvent);\n * synchronizedEvent.on(data => console.log('Data on tick:', data));\n * await dataEvent('Hello');\n * await dataEvent('World!');\n * await tickEvent(); // Logs: \"Data on tick: World!\"\n * ```\n */\n orchestrate(conductor: Event<any, any>): Event<T, R> {\n let initialized = false;\n let lastValue: T;\n const unsubscribe = this.on(async (event) => {\n initialized = true;\n lastValue = event;\n });\n const unsubscribeConductor = conductor.on(async () => {\n if (initialized) {\n await orchestratedEvent(lastValue);\n initialized = false;\n }\n });\n\n const orchestratedEvent = new Event<T, R>(unsubscribe.post(unsubscribeConductor));\n return orchestratedEvent;\n }\n /**\n * Creates a debounced event that delays triggering until after a specified interval has elapsed\n * following the last time it was invoked. This method is particularly useful for limiting the rate\n * at which a function is executed. Common use cases include handling rapid user inputs, window resizing,\n * or scroll events.\n *\n * @param {number} interval - The amount of time to wait (in milliseconds) before firing the debounced event.\n * @returns {Event<T, R>} An event of debounced events.\n *\n * ```typescript\n * const debouncedEvent = textInputEvent.debounce(100);\n * debouncedEvent.on((str) => console.log(str)); // only 'text' is emitted\n * await event('t');\n * await event('te');\n * await event('tex');\n * await event('text');\n * ```\n */\n debounce(interval: number): Event<Awaited<T>, unknown> {\n let controller = new AbortController();\n\n return this.pipe(async function* (value) {\n controller.abort();\n controller = new AbortController();\n const complete = await setTimeoutAsync(interval, controller.signal);\n if (complete) {\n yield value;\n }\n });\n }\n\n /**\n * Creates a throttled event that emits values at most once per specified interval.\n *\n * This is useful for controlling the rate of event emissions, especially for high-frequency events.\n * The throttled event will immediately emit the first value, and then only emit subsequent values\n * if the specified interval has passed since the last emission.\n *\n * @param interval - The time interval (in milliseconds) between allowed emissions.\n * @returns A new Event that emits throttled values.\n *\n * ```typescript\n * const scrollEvent = new Event();\n * const throttledScroll = scrollEvent.throttle(100); // Emit at most every 100ms\n * throttledScroll.on(() => console.log(\"Throttled scroll event\"));\n * ```\n */\n throttle(interval: number): Event<Awaited<T>, unknown> {\n let timeout = 0;\n let pendingValue: T;\n let hasPendingValue = false;\n\n return this.pipe(async function* (value) {\n const now = Date.now();\n if (timeout <= now) {\n timeout = now + interval;\n yield value;\n } else {\n pendingValue = value;\n if (!hasPendingValue) {\n hasPendingValue = true;\n await setTimeoutAsync(timeout - now);\n timeout = now + interval;\n hasPendingValue = false;\n yield pendingValue;\n }\n }\n });\n }\n\n /**\n * Aggregates multiple event emissions into batches and emits the batched events either at specified\n * time intervals or when the batch reaches a predefined size. This method is useful for grouping\n * a high volume of events into manageable chunks, such as logging or processing data in bulk.\n *\n * @param {number} interval - The time in milliseconds between batch emissions.\n * @param {number} [size] - Optional. The maximum size of each batch. If specified, triggers a batch emission\n * once the batch reaches this size, regardless of the interval.\n * @returns {Event<T[], R>} An event of the batched results.\n *\n * ```typescript\n * // Batch messages for bulk processing every 1 second or when 10 messages are collected\n * const messageEvent = createEvent<string, void>();\n * const batchedMessageEvent = messageEvent.batch(1000, 10);\n * batchedMessageEvent.on((messages) => console.log('Batched Messages:', messages));\n * ```\n */\n batch(interval: number, size?: number): Event<T[], R> {\n let controller = new AbortController();\n const batch: T[] = [];\n\n return this.pipe(async function* (value) {\n batch.push(value);\n if (size !== undefined && batch.length >= size) {\n controller.abort();\n yield batch.splice(0);\n }\n if (batch.length === 1) {\n controller = new AbortController();\n const complete = await setTimeoutAsync(interval, controller.signal);\n if (complete) {\n yield batch.splice(0);\n }\n }\n });\n }\n\n /**\n * Creates a queue from the event, where each emitted value is sequentially processed. The returned object allows popping elements\n * from the queue, ensuring that elements are handled one at a time. This method is ideal for scenarios where order and sequential processing are critical.\n *\n * @returns {Queue<T>} An object representing the queue. The 'pop' method retrieves the next element from the queue, while 'stop' halts further processing.\n *\n * ```typescript\n * // Queueing tasks for sequential execution\n * const taskEvent = new Event<string>();\n * const taskQueue = taskEvent.queue();\n * (async () => {\n * console.log('Processing:', await taskQueue.pop()); // Processing: Task 1\n * console.log('Processing:', await taskQueue.pop()); // Processing: Task 2\n * })();\n * await taskEvent('Task 1');\n * await taskEvent('Task 2');\n * ```\n */\n queue(): Queue<T> {\n const queue: T[] = [];\n let done = false;\n const valueEvent = new Event<void>();\n const unsubscribe = this.on(async (value) => {\n queue.push(value);\n await valueEvent();\n });\n\n const pop = async () => {\n if (!queue.length) {\n await valueEvent;\n }\n return queue.shift()!;\n };\n const stop = async () => {\n await unsubscribe();\n done = true;\n await valueEvent();\n };\n\n return {\n pop,\n stop,\n get stopped() {\n return done;\n },\n [Symbol.asyncIterator]() {\n return {\n next: async () => {\n return { value: await pop(), done };\n },\n };\n },\n };\n }\n}\n\nexport type EventParameters<T> = T extends Event<infer P, any> ? P : never;\n\nexport type EventResult<T> = T extends Event<any, infer R> ? R : never;\n\nexport type AllEventsParameters<T extends Event<any, any>[]> = { [K in keyof T]: EventParameters<T[K]> }[number];\n\nexport type AllEventsResults<T extends Event<any, any>[]> = { [K in keyof T]: EventResult<T[K]> }[number];\n\n/**\n * Merges multiple events into a single event. This function takes any number of `Event` instances\n * and returns a new `Event` that triggers whenever any of the input events trigger. The parameters\n * and results of the merged event are derived from the input events, providing a flexible way to\n * handle multiple sources of events in a unified manner.\n *\n * @template Events - An array of `Event` instances.\n * @param {...Events} events - A rest parameter that takes multiple events to be merged.\n * @returns {Event<AllEventsParameters<Events>, AllEventsResults<Events>>} - Returns a new `Event` instance\n * that triggers with the parameters and results of any of the merged input events.\n *\n * ```typescript\n * // Merging mouse and keyboard events into a single event\n * const mouseEvent = createEvent<MouseEvent>();\n * const keyboardEvent = createEvent<KeyboardEvent>();\n * const inputEvent = merge(mouseEvent, keyboardEvent);\n * inputEvent.on(event => console.log('Input event:', event));\n * ```\n */\nexport const merge = <Events extends Event<any, any>[]>(...events: Events): Event<AllEventsParameters<Events>, AllEventsResults<Events>> => {\n const mergedEvent = new Event<AllEventsParameters<Events>, AllEventsResults<Events>>();\n events.forEach((event) => event.on(mergedEvent));\n return mergedEvent;\n};\n\n/**\n * Creates a periodic event that triggers at a specified interval. The event will automatically emit\n * an incrementing counter value each time it triggers, starting from zero. This function is useful\n * for creating time-based triggers within an application, such as updating UI elements, polling,\n * or any other timed operation.\n *\n * @template R - The return type of the event handler function, defaulting to `void`.\n * @param {number} interval - The interval in milliseconds at which the event should trigger.\n * @returns {Event<number, R>} - An `Event` instance that triggers at the specified interval,\n * emitting an incrementing counter value.\n *\n * ```typescript\n * // Creating an interval event that logs a message every second\n * const tickEvent = createInterval(1000);\n * tickEvent.on(tickNumber => console.log('Tick:', tickNumber));\n * ```\n */\nexport const createInterval = <R = unknown>(interval: number): Event<number, R> => {\n let counter = 0;\n const intervalEvent = new Event<number, R>(() => clearInterval(timerId));\n const timerId: ReturnType<typeof setInterval> = setInterval(() => intervalEvent(counter++), interval);\n return intervalEvent;\n};\n\n/**\n * Creates a new instance of the `Event` class, which allows for the registration of event handlers that get called when the event is emitted.\n * This factory function simplifies the creation of events by encapsulating the instantiation logic, providing a clean and simple API for event creation.\n *\n * @typeParam T - The tuple of argument types that the event will accept.\n * @typeParam R - The return type of the event handler function, which is emitted after processing the event data.\n * @returns {Event<T, R>} - A new instance of the `Event` class, ready to have listeners added to it.\n *\n * ```typescript\n * // Create a new event that accepts a string and returns the string length\n * const myEvent = createEvent<string, number>();\n * myEvent.on((str: string) => str.length);\n * myEvent('hello').then(results => console.log(results)); // Logs: [5]\n * ```\n */\nexport const createEvent = <T = unknown, R = unknown>(): Event<T, R> => new Event<T, R>();\n\nexport default createEvent;\n\n/**\n * A type helper that extracts the event listener type\n *\n * @typeParam E - The event type.\n */\nexport type EventHandler<E> = E extends Event<infer T, infer R> ? Listener<T, R> : never;\n\n/**\n * A type helper that extracts the event filter type\n *\n * @typeParam E The event type to filter.\n */\nexport type EventFilter<E> = FilterFunction<EventParameters<E>>;\n\n/**\n * A type helper that extracts the event predicate type\n *\n * @typeParam E The event type to predicate.\n */\nexport type EventPredicate<E, P extends EventParameters<E>> = Predicate<EventParameters<E>, P>;\n\n/**\n * A type helper that extracts the event mapper type\n *\n * @typeParam E The event type to map.\n * @typeParam M The new type to map `E` to.\n */\nexport type EventMapper<E, M> = Mapper<EventParameters<E>, M>;\n\n/**\n * A type helper that extracts the event mapper type\n *\n * @typeParam E The type of event to reduce.\n * @typeParam M The type of reduced event.\n */\nexport type EventReducer<E, R> = Reducer<EventParameters<E>, R>;\n"],"names":["Callable","Event","Unsubscribe","createEvent","createInterval","merge","removeListener","setTimeoutAsync","listeners","listener","index","indexOf","wasRemoved","splice","timeout","signal","Promise","resolve","timerId","setTimeout","addEventListener","clearTimeout","Function","constructor","func","Object","setPrototypeOf","prototype","callback","pre","post","countdown","count","spies","dispose","value","all","map","clear","_error","error","size","length","lacks","has","off","forEach","spy","on","push","once","oneTimeListener","event","then","onfulfilled","onrejected","promise","v","Symbol","asyncIterator","queue","doneEvent","emitEvent","unsubscribe","target","next","shift","done","undefined","return","pipe","generator","generatedValue","result","catch","e","filter","first","filteredEvent","mapper","reduce","reducer","init","hasInit","expand","expander","values","orchestrate","conductor","initialized","lastValue","unsubscribeConductor","orchestratedEvent","debounce","interval","controller","AbortController","abort","complete","throttle","pendingValue","hasPendingValue","now","Date","batch","valueEvent","pop","stop","stopped","events","mergedEvent","counter","intervalEvent","clearInterval","setInterval"],"mappings":";;;;;;;;;;;IAkFsBA,QAAQ;eAARA;;IA2DTC,KAAK;eAALA;;IA5CAC,WAAW;eAAXA;;IAuxBAC,WAAW;eAAXA;;IAtBAC,cAAc;eAAdA;;IAwBb,OAA2B;eAA3B;;IA/CaC,KAAK;eAALA;;IAxxBAC,cAAc;eAAdA;;IAgBAC,eAAe;eAAfA;;;AAhBN,MAAMD,iBAAiB,CAAOE,WAA6BC;IAChE,IAAIC,QAAQF,UAAUG,OAAO,CAACF;IAC9B,MAAMG,aAAaF,UAAU,CAAC;IAC9B,MAAO,CAACA,MAAO;QACbF,UAAUK,MAAM,CAACH,OAAO;QACxBA,QAAQF,UAAUG,OAAO,CAACF;IAC5B;IACA,OAAOG;AACT;AAQO,MAAML,kBAAkB,CAACO,SAAiBC,SAC/C,IAAIC,QAAiB,CAACC;QACpB,MAAMC,UAAUC,WAAWF,SAASH,SAAS;QAC7CC,QAAQK,iBAAiB,SAAS;YAChCC,aAAaH;YACbD,QAAQ;QACV;IACF;AAQK,MAAejB,iBAAi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AAI2F,MAAM9D,MAAM,KAAK,GAAG;gBACtBqD,aAAa,IAAIC;gBACjB,MAAME,WAAW,MAAM3F,gBAAgBuF,UAAUC,WAAWhF,MAAM;gBAClE,IAAImF,UAAU;oBACZ,MAAMM,MAAM3F,MAAM,CAAC;gBACrB;YACF;QACF;IACF;IAoBA+C,QAAkB;QAChB,MAAMA,QAAa,EAAE;QACrB,IAAIO,OAAO;QACX,MAAMsC,aAAa,IAAIxG;QACvB,MAAM8D,cAAc,IAAI,CAACf,EAAE,CAAC,OAAOb;YACjCyB,MAAMX,IAAI,CAACd;YACX,MAAMsE;QACR;QAEA,MAAMC,MAAM;YACV,IAAI,CAAC9C,MAAMlB,MAAM,EAAE;gBACjB,MAAM+D;YACR;YACA,OAAO7C,MAAMM,KAAK;QACpB;QACA,MAAMyC,OAAO;YACX,MAAM5C;YACNI,OAAO;YACP,MAAMsC;QACR;QAEA,OAAO;YACLC;YACAC;YACA,IAAIC,WAAU;gBACZ,OAAOzC;YACT;YACA,CAACT,OAAOC,aAAa,CAAC;gBACpB,OAAO;oBACLM,MAAM;wBACJ,OAAO;4BAAE9B,OAAO,MAAMuE;4BAAOvC;wBAAK;oBACpC;gBACF;YACF;QACF;IACF;AACF;AA6BO,MAAM9D,QAAQ,CAAmC,GAAGwG;IACzD,MAAMC,cAAc,IAAI7G;IACxB4G,OAAO/D,OAAO,CAAC,CAACM,QAAUA,MAAMJ,EAAE,CAAC8D;IACnC,OAAOA;AACT;AAmBO,MAAM1G,iBAAiB,CAAc0F;IAC1C,IAAIiB,UAAU;IACd,MAAMC,gBAAgB,IAAI/G,MAAiB,IAAMgH,cAAc/F;IAC/D,MAAMA,UAA0CgG,YAAY,IAAMF,cAAcD,YAAYjB;IAC5F,OAAOkB;AACT;AAiBO,MAAM7G,cAAc,IAA6C,IAAIF;MAE5E,WAAeE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type MaybePromise<T> = Promise<T> | PromiseLike<T> | T;\n\nexport interface Callback<R = void> {\n (): MaybePromise<R>;\n}\n\nexport interface Listener<T, R = unknown> {\n (event: T): MaybePromise<R | void>;\n}\n\nexport interface FilterFunction<T> {\n (event: T): MaybePromise<boolean>;\n}\n\nexport interface Predicate<T, P extends T> {\n (event: T): event is P;\n}\n\nexport type Filter<T, P extends T> = Predicate<T, P> | FilterFunction<T>;\n\nexport interface Mapper<T, R> {\n (event: T): MaybePromise<R>;\n}\n\nexport interface Reducer<T, R> {\n (result: R, event: T): MaybePromise<R>;\n}\n\nexport interface Expander<T, R> {\n (event: T): MaybePromise<R>;\n}\n\n/**\n * Removes a listener from the provided array of listeners. It searches for the listener and removes all instances of it from the array.\n * This method ensures that the listener is fully unregistered, preventing any residual calls to a potentially deprecated handler.\n *\n * @internal\n * @param {Listener<T, R>[]} listeners - The array of listeners from which to remove the listener.\n * @param {Listener<T, R>} listener - The listener function to remove from the list of listeners.\n * @returns {boolean} - Returns `true` if the listener was found and removed, `false` otherwise.\n *\n * @template T - The type of the event that listeners are associated with.\n * @template R - The type of the return value that listeners are expected to return.\n *\n * ```typescript\n * // Assuming an array of listeners for click events\n * const listeners = [onClickHandler1, onClickHandler2];\n * const wasRemoved = removeListener(listeners, onClickHandler1);\n * console.log(wasRemoved); // Output: true\n * ```\n */\nexport const removeListener = (listeners: unknown[], listener: unknown): boolean => {\n let index = listeners.indexOf(listener);\n const wasRemoved = index !== -1;\n while (~index) {\n listeners.splice(index, 1);\n index = listeners.indexOf(listener);\n }\n return wasRemoved;\n};\n\n/**\n * @internal\n * @param timeout\n * @param signal\n * @returns\n */\nexport const setTimeoutAsync = (timeout: number, signal?: AbortSignal) =>\n new Promise<boolean>((resolve) => {\n const timerId = setTimeout(resolve, timeout, true);\n signal?.addEventListener('abort', () => {\n clearTimeout(timerId);\n resolve(false);\n });\n });\n\n/**\n * An abstract class that extends the built-in Function class. It allows instances of the class\n * to be called as functions. When an instance of Callable is called as a function, it will\n * call the function passed to its constructor with the same arguments.\n * @internal\n */\nexport abstract class Callable extends Function {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n constructor(func: Function) {\n super();\n return Object.setPrototypeOf(func, new.target.prototype);\n }\n}\n\nexport interface Unsubscribe {\n (): MaybePromise<void>;\n}\n\n/**\n * @internal\n */\nexport class Unsubscribe extends Callable {\n private _done = false;\n\n constructor(callback: Callback) {\n super(() => {\n this._done = true;\n callback();\n });\n }\n\n get done() {\n return this._done;\n }\n\n pre(callback: Callback): Unsubscribe {\n return new Unsubscribe(async () => {\n await callback();\n await this();\n });\n }\n\n post(callback: Callback): Unsubscribe {\n return new Unsubscribe(async () => {\n await this();\n await callback();\n });\n }\n\n countdown(count: number): Unsubscribe {\n return new Unsubscribe(async () => {\n if (!--count) {\n await this();\n }\n });\n }\n}\n\nexport interface Event<T = any, R = any> {\n (event: T): Promise<(void | Awaited<R>)[]>;\n}\n\nenum SpyType {\n Add,\n Remove,\n}\n\n/**\n * A class representing an anonymous event that can be listened to or triggered.\n *\n * @template T - The event type.\n * @template R - The return type of the event.\n */\nexport class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLike<T> {\n /**\n * The array of listeners for the event.\n */\n private listeners: Listener<T, R>[];\n\n private spies: Array<(listener: Listener<T, R> | void, type: SpyType) => void> = [];\n\n private _disposed = false;\n\n /**\n * A function that disposes of the event and its listeners.\n */\n readonly dispose: Callback;\n\n /**\n * Creates a new event.\n *\n * @param dispose - A function to call on the event disposal.\n *\n * ```typescript\n * // Create a click event.\n * const clickEvent = new Event<[x: number, y: number], void>();\n * clickEvent.on(([x, y]) => console.log(`Clicked at ${x}, ${y}`));\n * ```\n */\n constructor(dispose?: Callback) {\n const listeners: Listener<T, R>[] = [];\n // passes listeners exceptions to catch method\n super(async (value: T): Promise<(void | Awaited<R>)[]> => Promise.all(listeners.map(async (listener) => listener(await value))));\n this.listeners = listeners;\n\n this.dispose = async () => {\n this._disposed = true;\n void this.clear();\n await this._error?.dispose();\n await dispose?.();\n };\n }\n\n private _error?: Event<unknown>;\n\n /**\n * Error event that emits errors.\n *\n * @returns {Event<unknown>} The error event.\n */\n get error(): Event<unknown> {\n return (this._error ??= new Event<unknown>());\n }\n\n /**\n * The number of listeners for the event.\n *\n * @readonly\n * @type {number}\n */\n get size(): number {\n return this.listeners.length;\n }\n\n /**\n * Checks if the event has been disposed.\n * @returns {boolean} `true` if the event has been disposed; otherwise, `false`.\n */\n get disposed(): boolean {\n return this._disposed;\n }\n\n /**\n * Checks if the given listener is NOT registered for this event.\n *\n * @param listener - The listener function to check against the registered listeners.\n * @returns `true` if the listener is not already registered; otherwise, `false`.\n *\n * ```typescript\n * // Check if a listener is not already added\n * if (event.lacks(myListener)) {\n * event.on(myListener);\n * }\n * ```\n */\n lacks(listener: Listener<T, R>): boolean {\n return this.listeners.indexOf(listener) === -1;\n }\n\n /**\n * Checks if the given listener is registered for this event.\n *\n * @param listener - The listener function to check.\n * @returns `true` if the listener is currently registered; otherwise, `false`.\n *\n * ```typescript\n * // Verify if a listener is registered\n * if (event.has(myListener)) {\n * console.log('Listener is already registered');\n * }\n * ```\n */\n has(listener: Listener<T, R>): boolean {\n return this.listeners.indexOf(listener) !== -1;\n }\n\n /**\n * Removes a specific listener from this event.\n *\n * @param listener - The listener to remove.\n * @returns The event instance, allowing for method chaining.\n *\n * ```typescript\n * // Remove a listener\n * event.off(myListener);\n * ```\n */\n off(listener: Listener<T, R>): this {\n if (removeListener(this.listeners, listener) && this.spies.length) {\n [...this.spies].forEach((spy) => spy(listener, SpyType.Remove));\n }\n return this;\n }\n\n /**\n * Registers a listener that gets triggered whenever the event is emitted.\n * This is the primary method for adding event handlers that will react to the event being triggered.\n *\n * @param listener - The function to call when the event occurs.\n * @returns An object that can be used to unsubscribe the listener, ensuring easy cleanup.\n *\n * ```typescript\n * // Add a listener to an event\n * const unsubscribe = event.on((data) => {\n * console.log('Event data:', data);\n * });\n * ```\n */\n on(listener: Listener<T, R>): Unsubscribe {\n this.listeners.push(listener);\n if (this.spies.length) {\n [...this.spies].forEach((spy) => spy(listener, SpyType.Add));\n }\n return new Unsubscribe(() => {\n void this.off(listener);\n });\n }\n\n /**\n * Adds a listener that will be called only once the next time the event is emitted.\n * This method is useful for one-time notifications or single-trigger scenarios.\n *\n * @param listener - The listener to trigger once.\n * @returns An object that can be used to remove the listener if the event has not yet occurred.\n *\n * ```typescript\n * // Register a one-time listener\n * const onceUnsubscribe = event.once((data) => {\n * console.log('Received data once:', data);\n * });\n * ```\n */\n once(listener: Listener<T, R>): Unsubscribe {\n const oneTimeListener = (event: T) => {\n void this.off(oneTimeListener);\n return listener(event);\n };\n return this.on(oneTimeListener);\n }\n\n /**\n * Removes all listeners from the event, effectively resetting it. This is useful when you need to\n * cleanly dispose of all event handlers to prevent memory leaks or unwanted triggerings after certain conditions.\n *\n * @returns {this} The instance of the event, allowing for method chaining.\n *\n * ```typescript\n * const myEvent = new Event();\n * myEvent.on(data => console.log(data));\n * myEvent.clear(); // Clears all listeners\n * ```\n */\n clear(): this {\n this.listeners.splice(0);\n if (this.spies.length) {\n [...this.spies].forEach((spy) => spy(undefined, SpyType.Remove));\n }\n return this;\n }\n\n /**\n * Enables the `Event` to be used in a Promise chain, resolving with the first emitted value.\n *\n * @template TResult1 - The type of the fulfilled value returned by `onfulfilled` (defaults to the event's type).\n * @template TResult2 - The type of the rejected value returned by `onrejected` (defaults to `never`).\n * @param onfulfilled - A function called when the event emits its first value.\n * @param onrejected - A function called if an error occurs before the event emits.\n * @returns A Promise that resolves with the result of `onfulfilled` or `onrejected`.\n *\n * ```typescript\n * const clickEvent = new Event<[number, number]>();\n * await clickEvent;\n * ```\n */\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n const promise = new Promise<T>((resolve) => this.once(resolve));\n\n return promise.then(onfulfilled, onrejected);\n }\n\n /**\n * A promise that resolves with the first emitted value from this event.\n *\n * @returns {Promise<T>} The promise value.\n */\n get promise(): Promise<T> {\n return this.then((v) => v);\n }\n\n /**\n * Makes this event iterable using `for await...of` loops.\n *\n * @returns An async iterator that yields values as they are emitted by this event.\n *\n * ```typescript\n * // Assuming an event that emits numbers\n * const numberEvent = new Event<number>();\n * (async () => {\n * for await (const num of numberEvent) {\n * console.log('Number:', num);\n * }\n * })();\n * await numberEvent(1);\n * await numberEvent(2);\n * await numberEvent(3);\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n const queue: T[] = [];\n const doneEvent = new Event<boolean>();\n const emitEvent = async (value: T) => {\n queue.push(value);\n await doneEvent(false);\n };\n const unsubscribe = this.on(emitEvent).pre(async () => {\n removeListener(this.spies, spy);\n queue.splice(0);\n await doneEvent.dispose();\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent, action) => {\n if (target === emitEvent && action === SpyType.Remove) {\n void doneEvent(true);\n void unsubscribe();\n }\n };\n\n this.spies.push(spy);\n return {\n async next() {\n if (queue.length) {\n return { value: queue.shift()!, done: false };\n }\n if (!(await doneEvent)) {\n return { value: queue.shift()!, done: false };\n }\n return { value: undefined, done: true };\n },\n async return(value: unknown) {\n await unsubscribe();\n return { done: true, value };\n },\n };\n }\n\n /**\n * Transforms the event's values using a generator function, creating a new `Event` that emits the transformed values.\n *\n * @template PT - The type of values emitted by the transformed `Event`.\n * @template PR - The return type of the listeners of the transformed `Event`.\n * @param generator - A function that takes the original event's value and returns a generator (sync or async) that yields the transformed values.\n * @returns A new `Event` instance that emits the transformed values.\n *\n * ```typescript\n * const numbersEvent = new Event<number>();\n * const evenNumbersEvent = numbersEvent.pipe(function*(value) {\n * if (value % 2 === 0) {\n * yield value;\n * }\n * });\n * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));\n * await numbersEvent(1);\n * await numbersEvent(2);\n * await numbersEvent(3);\n * ```\n */\n pipe<PT, R>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): Event<PT, R> {\n const emitEvent = async (value: T) => {\n try {\n for await (const generatedValue of generator(value)) {\n await result(generatedValue).catch((e) => result.error(e));\n }\n } catch (e) {\n await result.error(e);\n }\n };\n\n const unsubscribe = this.on(emitEvent).pre(() => {\n removeListener(this.spies, spy);\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent, action) => {\n if (target === emitEvent && action === SpyType.Remove) {\n void unsubscribe();\n }\n };\n this.spies.push(spy);\n\n const result = new Event<PT, R>(unsubscribe);\n return result;\n }\n\n /**\n * Creates an async generator that yields values as they are emitted by this event.\n *\n * @template PT - The type of values yielded by the async generator.\n * @param generator - An optional function that takes the original event's value and returns a generator (sync or async)\n * that yields values to include in the async generator.\n * @returns An async generator that yields values from this event as they occur.\n *\n * ```typescript\n * const numbersEvent = new Event<number>();\n * const evenNumbersEvent = numbersEvent.pipe(function*(value) {\n * if (value % 2 === 0) {\n * yield value;\n * }\n * });\n * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));\n * await numbersEvent(1);\n * await numbersEvent(2);\n * await numbersEvent(3);\n * ```\n */\n async *generator<PT>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): AsyncGenerator<Awaited<PT>, void, unknown> {\n for await (const value of this.pipe(generator)) {\n yield value;\n }\n }\n\n /**\n * Filters events, creating a new event that only triggers when the provided filter function returns `true`.\n * This method can be used to selectively process events that meet certain criteria.\n *\n * @param {Filter<T, P>} predicate The filter function or predicate to apply to each event.\n * @returns {Event<P, R>} A new event that only triggers for filtered events.\n *\n * ```typescript\n * const keyPressedEvent = new Event<string>();\n * const enterPressedEvent = keyPressedEvent.filter(key => key === 'Enter');\n * enterPressedEvent.on(() => console.log('Enter key was pressed.'));\n * ```\n */\n filter<P extends T>(predicate: Predicate<T, P>): Event<P, R>;\n filter<P extends T>(filter: FilterFunction<T>): Event<P, R>;\n filter<P extends T>(filter: Filter<T, P>): Event<P, R> {\n return this.pipe<P, R>(async function* (value: T) {\n if (await filter(value)) {\n yield value as P;\n }\n });\n }\n\n /**\n * Creates a new event that will only be triggered once when the provided filter function returns `true`.\n * This method is useful for handling one-time conditions in a stream of events.\n *\n * @param {Filter<T, P>} predicate - The filter function or predicate.\n * @returns {Event<P, R>} A new event that will be triggered only once when the filter condition is met.\n *\n * ```typescript\n * const sizeChangeEvent = new Event<number>();\n * const sizeReachedEvent = sizeChangeEvent.first(size => size > 1024);\n * sizeReachedEvent.on(() => console.log('Size threshold exceeded.'));\n * ```\n */\n first<P extends T>(predicate: Predicate<T, P>): Event<P, R>;\n first<P extends T>(filter: FilterFunction<T>): Event<P, R>;\n first<P extends T>(filter: Filter<T, P>): Event<P, R> {\n const filteredEvent = this.pipe<P, R>(async function* (value: T) {\n if (await filter(value)) {\n yield value as P;\n await filteredEvent.dispose();\n }\n });\n return filteredEvent;\n }\n\n /**\n * Transforms the data emitted by this event using a mapping function. Each emitted event is processed by the `mapper`\n * function, which returns a new value that is then emitted by the returned `Event` instance. This is useful for data transformation\n * or adapting the event's data structure.\n *\n * @template M The type of data that the mapper function will produce.\n * @template MR The type of data emitted by the mapped event, usually related to or the same as `M`.\n * @param {Mapper<T, M>} mapper A function that takes the original event data and returns the transformed data.\n * @returns {Event<M, MR>} A new `Event` instance that emits the mapped values.\n *\n * ```typescript\n * // Assuming an event that emits numbers, create a new event that emits their squares.\n * const numberEvent = new Event<number>();\n * const squaredEvent = numberEvent.map(num => num * num);\n * squaredEvent.on(squared => console.log('Squared number:', squared));\n * await numberEvent(5); // Logs: \"Squared number: 25\"\n * ```\n */\n map<M, MR = R>(mapper: Mapper<T, M>): Event<Awaited<M>, MR> {\n return this.pipe(async function* (value) {\n yield await mapper(value);\n });\n }\n\n /**\n * Accumulates the values emitted by this event using a reducer function, starting from an initial value. The reducer\n * function takes the accumulated value and the latest emitted event data, then returns a new accumulated value. This\n * new value is then emitted by the returned `Event` instance. This is particularly useful for accumulating state over time.\n *\n * @template A The type of the accumulator value.\n * @template AR The type of data emitted by the reduced event, usually the same as `A`.\n * @param {Reducer<T, A>} reducer A function that takes the current accumulated value and the new event data, returning the new accumulated value.\n * @param {A} init The initial value of the accumulator.\n * @returns {Event<A, AR>} A new `Event` instance that emits the reduced value.\n *\n * ```typescript\n * const sumEvent = numberEvent.reduce((a, b) => a + b, 0);\n * sumEvent.on((sum) => console.log(sum)); // 1, 3, 6\n * await sumEvent(1);\n * await sumEvent(2);\n * await sumEvent(3);\n * ```\n */\n reduce<A, AR = R>(reducer: Reducer<T, A>, init?: A): Event<Awaited<A>, AR>;\n reduce<A, AR = R>(reducer: Reducer<T, A>, ...init: unknown[]): Event<Awaited<A>, AR> {\n let hasInit = init.length === 1;\n let result = init[0] as A | undefined;\n\n return this.pipe(async function* (value) {\n if (hasInit) {\n result = await reducer(result!, value);\n yield result;\n } else {\n result = value as unknown as A;\n hasInit = true;\n }\n });\n }\n\n /**\n * Transforms each event's data into multiple events using an expander function. The expander function takes\n * the original event's data and returns an array of new data elements, each of which will be emitted individually\n * by the returned `Event` instance. This method is useful for scenarios where an event's data can naturally\n * be expanded into multiple, separate pieces of data which should each trigger further processing independently.\n *\n * @template ET - The type of data elements in the array returned by the expander function.\n * @template ER - The type of responses emitted by the expanded event, usually related to or the same as `ET`.\n * @param {Expander<T, ET[]>} expander - A function that takes the original event data and returns an array of new data elements.\n * @returns {Event<ET, ER>} - A new `Event` instance that emits each value from the array returned by the expander function.\n *\n * ```typescript\n * // Assuming an event that emits a sentence, create a new event that emits each word from the sentence separately.\n * const sentenceEvent = new Event<string>();\n * const wordEvent = sentenceEvent.expand(sentence => sentence.split(' '));\n * wordEvent.on(word => console.log('Word:', word));\n * await sentenceEvent('Hello world'); // Logs: \"Word: Hello\", \"Word: world\"\n * ```\n */\n expand<ET, ER>(expander: Expander<T, ET[]>): Event<Awaited<ET>, ER> {\n return this.pipe(async function* (value) {\n const values = await expander(value);\n for (const value of values) {\n yield value;\n }\n });\n }\n\n /**\n * Creates a new event that emits values based on a conductor event. The orchestrated event will emit the last value\n * captured from the original event each time the conductor event is triggered. This method is useful for synchronizing\n * events, where the emission of one event controls the timing of another.\n *\n * @template T The type of data emitted by the original event.\n * @template R The type of data emitted by the orchestrated event, usually the same as `T`.\n * @param {Event<unknown, unknown>} conductor An event that signals when the orchestrated event should emit.\n * @returns {Event<T, R>} An orchestrated event that emits values based on the conductor's trigger.\n *\n * ```typescript\n * const rightClickPositionEvent = mouseMoveEvent.orchestrate(mouseRightClickEvent);\n * ```\n *\n * ```typescript\n * // An event that emits whenever a \"tick\" event occurs.\n * const tickEvent = new Event<void>();\n * const dataEvent = new Event<string>();\n * const synchronizedEvent = dataEvent.orchestrate(tickEvent);\n * synchronizedEvent.on(data => console.log('Data on tick:', data));\n * await dataEvent('Hello');\n * await dataEvent('World!');\n * await tickEvent(); // Logs: \"Data on tick: World!\"\n * ```\n */\n orchestrate(conductor: Event<any, any>): Event<T, R> {\n let initialized = false;\n let lastValue: T;\n const unsubscribe = this.on(async (event) => {\n initialized = true;\n lastValue = event;\n });\n const unsubscribeConductor = conductor.on(async () => {\n if (initialized) {\n await orchestratedEvent(lastValue);\n initialized = false;\n }\n });\n\n const orchestratedEvent = new Event<T, R>(unsubscribe.post(unsubscribeConductor));\n return orchestratedEvent;\n }\n /**\n * Creates a debounced event that delays triggering until after a specified interval has elapsed\n * following the last time it was invoked. This method is particularly useful for limiting the rate\n * at which a function is executed. Common use cases include handling rapid user inputs, window resizing,\n * or scroll events.\n *\n * @param {number} interval - The amount of time to wait (in milliseconds) before firing the debounced event.\n * @returns {Event<T, R>} An event of debounced events.\n *\n * ```typescript\n * const debouncedEvent = textInputEvent.debounce(100);\n * debouncedEvent.on((str) => console.log(str)); // only 'text' is emitted\n * await event('t');\n * await event('te');\n * await event('tex');\n * await event('text');\n * ```\n */\n debounce(interval: number): Event<Awaited<T>, unknown> {\n let controller = new AbortController();\n\n return this.pipe(async function* (value) {\n controller.abort();\n controller = new AbortController();\n const complete = await setTimeoutAsync(interval, controller.signal);\n if (complete) {\n yield value;\n }\n });\n }\n\n /**\n * Creates a throttled event that emits values at most once per specified interval.\n *\n * This is useful for controlling the rate of event emissions, especially for high-frequency events.\n * The throttled event will immediately emit the first value, and then only emit subsequent values\n * if the specified interval has passed since the last emission.\n *\n * @param interval - The time interval (in milliseconds) between allowed emissions.\n * @returns A new Event that emits throttled values.\n *\n * ```typescript\n * const scrollEvent = new Event();\n * const throttledScroll = scrollEvent.throttle(100); // Emit at most every 100ms\n * throttledScroll.on(() => console.log(\"Throttled scroll event\"));\n * ```\n */\n throttle(interval: number): Event<Awaited<T>, unknown> {\n let timeout = 0;\n let pendingValue: T;\n let hasPendingValue = false;\n\n return this.pipe(async function* (value) {\n const now = Date.now();\n if (timeout <= now) {\n timeout = now + interval;\n yield value;\n } else {\n pendingValue = value;\n if (!hasPendingValue) {\n hasPendingValue = true;\n await setTimeoutAsync(timeout - now);\n timeout = now + interval;\n hasPendingValue = false;\n yield pendingValue;\n }\n }\n });\n }\n\n /**\n * Aggregates multiple event emissions into batches and emits the batched events either at specified\n * time intervals or when the batch reaches a predefined size. This method is useful for grouping\n * a high volume of events into manageable chunks, such as logging or processing data in bulk.\n *\n * @param {number} interval - The time in milliseconds between batch emissions.\n * @param {number} [size] - Optional. The maximum size of each batch. If specified, triggers a batch emission\n * once the batch reaches this size, regardless of the interval.\n * @returns {Event<T[], R>} An event of the batched results.\n *\n * ```typescript\n * // Batch messages for bulk processing every 1 second or when 10 messages are collected\n * const messageEvent = createEvent<string, void>();\n * const batchedMessageEvent = messageEvent.batch(1000, 10);\n * batchedMessageEvent.on((messages) => console.log('Batched Messages:', messages));\n * ```\n */\n batch(interval: number, size?: number): Event<T[], R> {\n let controller = new AbortController();\n const batch: T[] = [];\n\n return this.pipe(async function* (value) {\n batch.push(value);\n if (size !== undefined && batch.length >= size) {\n controller.abort();\n yield batch.splice(0);\n }\n if (batch.length === 1) {\n controller = new AbortController();\n const complete = await setTimeoutAsync(interval, controller.signal);\n if (complete) {\n yield batch.splice(0);\n }\n }\n });\n }\n\n /**\n * Creates a queue from the event, where each emitted value is sequentially processed. The returned object allows popping elements\n * from the queue, ensuring that elements are handled one at a time. This method is ideal for scenarios where order and sequential processing are critical.\n *\n * @returns {Queue<T>} An object representing the queue. The 'pop' method retrieves the next element from the queue, while 'stop' halts further processing.\n *\n * ```typescript\n * // Queueing tasks for sequential execution\n * const taskEvent = new Event<string>();\n * const taskQueue = taskEvent.queue();\n * (async () => {\n * console.log('Processing:', await taskQueue.pop()); // Processing: Task 1\n * // Queue also can be used as a Promise\n * console.log('Processing:', await taskQueue); // Processing: Task 2\n * })();\n * await taskEvent('Task 1');\n * await taskEvent('Task 2');\n *```\n *\n *```typescript\n * // Additionally, the queue can be used as an async iterator\n * const taskEvent = new Event<string>();\n * const taskQueue = taskEvent.queue();\n * (async () => {\n * for await (const task of taskQueue) {\n * console.log('Processing:', task);\n * }\n * })();\n * await taskEvent('Task 1');\n * await taskEvent('Task 2');\n * ```\n *\n */\n queue(): Queue<T> {\n const queue: T[] = [];\n let done = false;\n const valueEvent = new Event<void>();\n\n const unsubscribe = this.on(async (value) => {\n queue.push(value);\n await valueEvent();\n });\n\n const pop = async () => {\n if (!queue.length) {\n await valueEvent;\n }\n return queue.shift()!;\n };\n const stop = async () => {\n await unsubscribe();\n done = true;\n await valueEvent();\n };\n\n return {\n pop,\n stop,\n get stopped() {\n return done;\n },\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n return this.pop().then(onfulfilled, onrejected);\n },\n [Symbol.asyncIterator]() {\n return {\n next: async () => {\n return { value: await pop(), done };\n },\n };\n },\n };\n }\n}\n\nexport interface Queue<T> extends AsyncIterable<T>, PromiseLike<T> {\n pop(): Promise<T>;\n stop(): Promise<void>;\n stopped: boolean;\n}\n\nexport type EventParameters<T> = T extends Event<infer P, any> ? P : never;\n\nexport type EventResult<T> = T extends Event<any, infer R> ? R : never;\n\nexport type AllEventsParameters<T extends Event<any, any>[]> = { [K in keyof T]: EventParameters<T[K]> }[number];\n\nexport type AllEventsResults<T extends Event<any, any>[]> = { [K in keyof T]: EventResult<T[K]> }[number];\n\n/**\n * Merges multiple events into a single event. This function takes any number of `Event` instances\n * and returns a new `Event` that triggers whenever any of the input events trigger. The parameters\n * and results of the merged event are derived from the input events, providing a flexible way to\n * handle multiple sources of events in a unified manner.\n *\n * @template Events - An array of `Event` instances.\n * @param {...Events} events - A rest parameter that takes multiple events to be merged.\n * @returns {Event<AllEventsParameters<Events>, AllEventsResults<Events>>} - Returns a new `Event` instance\n * that triggers with the parameters and results of any of the merged input events.\n *\n * ```typescript\n * // Merging mouse and keyboard events into a single event\n * const mouseEvent = createEvent<MouseEvent>();\n * const keyboardEvent = createEvent<KeyboardEvent>();\n * const inputEvent = merge(mouseEvent, keyboardEvent);\n * inputEvent.on(event => console.log('Input event:', event));\n * ```\n */\nexport const merge = <Events extends Event<any, any>[]>(...events: Events): Event<AllEventsParameters<Events>, AllEventsResults<Events>> => {\n const mergedEvent = new Event<AllEventsParameters<Events>, AllEventsResults<Events>>();\n events.forEach((event) => event.on(mergedEvent));\n return mergedEvent;\n};\n\n/**\n * Creates a periodic event that triggers at a specified interval. The event will automatically emit\n * an incrementing counter value each time it triggers, starting from zero. This function is useful\n * for creating time-based triggers within an application, such as updating UI elements, polling,\n * or any other timed operation.\n *\n * @template R - The return type of the event handler function, defaulting to `void`.\n * @param {number} interval - The interval in milliseconds at which the event should trigger.\n * @returns {Event<number, R>} - An `Event` instance that triggers at the specified interval,\n * emitting an incrementing counter value.\n *\n * ```typescript\n * // Creating an interval event that logs a message every second\n * const tickEvent = createInterval(1000);\n * tickEvent.on(tickNumber => console.log('Tick:', tickNumber));\n * ```\n */\nexport const createInterval = <R = unknown>(interval: number): Event<number, R> => {\n let counter = 0;\n const intervalEvent = new Event<number, R>(() => clearInterval(timerId));\n const timerId: ReturnType<typeof setInterval> = setInterval(() => intervalEvent(counter++), interval);\n return intervalEvent;\n};\n\n/**\n * Creates a new instance of the `Event` class, which allows for the registration of event handlers that get called when the event is emitted.\n * This factory function simplifies the creation of events by encapsulating the instantiation logic, providing a clean and simple API for event creation.\n *\n * @typeParam T - The tuple of argument types that the event will accept.\n * @typeParam R - The return type of the event handler function, which is emitted after processing the event data.\n * @returns {Event<T, R>} - A new instance of the `Event` class, ready to have listeners added to it.\n *\n * ```typescript\n * // Create a new event that accepts a string and returns the string length\n * const myEvent = createEvent<string, number>();\n * myEvent.on((str: string) => str.length);\n * myEvent('hello').then(results => console.log(results)); // Logs: [5]\n * ```\n */\nexport const createEvent = <T = unknown, R = unknown>(): Event<T, R> => new Event<T, R>();\n\nexport default createEvent;\n\n/**\n * A type helper that extracts the event listener type\n *\n * @typeParam E - The event type.\n */\nexport type EventHandler<E> = E extends Event<infer T, infer R> ? Listener<T, R> : never;\n\n/**\n * A type helper that extracts the event filter type\n *\n * @typeParam E The event type to filter.\n */\nexport type EventFilter<E> = FilterFunction<EventParameters<E>>;\n\n/**\n * A type helper that extracts the event predicate type\n *\n * @typeParam E The event type to predicate.\n */\nexport type EventPredicate<E, P extends EventParameters<E>> = Predicate<EventParameters<E>, P>;\n\n/**\n * A type helper that extracts the event mapper type\n *\n * @typeParam E The event type to map.\n * @typeParam M The new type to map `E` to.\n */\nexport type EventMapper<E, M> = Mapper<EventParameters<E>, M>;\n\n/**\n * A type helper that extracts the event mapper type\n *\n * @typeParam E The type of event to reduce.\n * @typeParam M The type of reduced event.\n */\nexport type EventReducer<E, R> = Reducer<EventParameters<E>, R>;\n"],"names":["Callable","Event","Unsubscribe","createEvent","createInterval","merge","removeListener","setTimeoutAsync","listeners","listener","index","indexOf","wasRemoved","splice","timeout","signal","Promise","resolve","timerId","setTimeout","addEventListener","clearTimeout","Function","constructor","func","Object","setPrototypeOf","prototype","_done","callback","done","pre","post","countdown","count","SpyType","spies","_disposed","dispose","value","all","map","clear","_error","error","size","length","disposed","lacks","has","off","forEach","spy","on","push","once","oneTimeListener","event","undefined","then","onfulfilled","onrejected","promise","v","Symbol","asyncIterator","queue","doneEvent","emitEvent","unsubscribe","target","action","next","shift","return","pipe","generator","generatedValue","result","catch","e","filter","first","filteredEvent","mapper","reduce","reducer","init","hasInit","expand","expander","values","orchestrate","conductor","initialized","lastValue","unsubscribeConductor","orchestratedEvent","debounce","interval","controller","AbortController","abort","complete","throttle","pendingValue","hasPendingValue","now","Date","batch","valueEvent","pop","stop","stopped","events","mergedEvent","counter","intervalEvent","clearInterval","setInterval"],"mappings":";;;;;;;;;;;IAkFsBA,QAAQ;eAARA;;IAmETC,KAAK;eAALA;;IApDAC,WAAW;eAAXA;;IAy0BAC,WAAW;eAAXA;;IAtBAC,cAAc;eAAdA;;IAwBb,OAA2B;eAA3B;;IA/CaC,KAAK;eAALA;;IA10BAC,cAAc;eAAdA;;IAgBAC,eAAe;eAAfA;;;AAhBN,MAAMD,iBAAiB,CAACE,WAAsBC;IACnD,IAAIC,QAAQF,UAAUG,OAAO,CAACF;IAC9B,MAAMG,aAAaF,UAAU,CAAC;IAC9B,MAAO,CAACA,MAAO;QACbF,UAAUK,MAAM,CAACH,OAAO;QACxBA,QAAQF,UAAUG,OAAO,CAACF;IAC5B;IACA,OAAOG;AACT;AAQO,MAAML,kBAAkB,CAACO,SAAiBC,SAC/C,IAAIC,QAAiB,CAACC;QACpB,MAAMC,UAAUC,WAAWF,SAASH,SAAS;QAC7CC,QAAQK,iBAAiB,SAAS;YAChCC,aAAaH;YACbD,QAAQ;QACV;IACF;AAQK,MAAejB,iBAAiBsB;IAErCC,YAAYC,IAAc,CAAE;QAC1B,KAAK;QACL,OAAOC,OAAOC,cAAc,CAACF,MAAM,WAAWG,SAAS;IACzD;AACF;AASO,MAAMzB,oBAAoBF;IACvB4B,QAAQ,MAAM;IAEtBL,YAAYM,QAAkB,CAAE;QAC9B,KAAK,CAAC;YACJ,IAAI,CAACD,KAAK,GAAG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/G,iBAAiB,CAAc+F;IAC1C,IAAIiB,UAAU;IACd,MAAMC,gBAAgB,IAAIpH,MAAiB,IAAMqH,cAAcpG;IAC/D,MAAMA,UAA0CqG,YAAY,IAAMF,cAAcD,YAAYjB;IAC5F,OAAOkB;AACT;AAiBO,MAAMlH,cAAc,IAA6C,IAAIF;MAE5E,WAAeE"}
package/build/index.d.ts CHANGED
@@ -40,7 +40,7 @@ export interface Expander<T, R> {
40
40
  * console.log(wasRemoved); // Output: true
41
41
  * ```
42
42
  */
43
- export declare const removeListener: <T, R>(listeners: Listener<T, R>[], listener: Listener<T, R>) => boolean;
43
+ export declare const removeListener: (listeners: unknown[], listener: unknown) => boolean;
44
44
  /**
45
45
  * @internal
46
46
  * @param timeout
@@ -64,16 +64,13 @@ export interface Unsubscribe {
64
64
  * @internal
65
65
  */
66
66
  export declare class Unsubscribe extends Callable {
67
+ private _done;
67
68
  constructor(callback: Callback);
69
+ get done(): boolean;
68
70
  pre(callback: Callback): Unsubscribe;
69
71
  post(callback: Callback): Unsubscribe;
70
72
  countdown(count: number): Unsubscribe;
71
73
  }
72
- export interface Queue<T> extends AsyncIterable<T> {
73
- pop(): MaybePromise<T>;
74
- stop(): MaybePromise<void>;
75
- stopped: boolean;
76
- }
77
74
  export interface Event<T = any, R = any> {
78
75
  (event: T): Promise<(void | Awaited<R>)[]>;
79
76
  }
@@ -89,6 +86,7 @@ export declare class Event<T, R> extends Callable implements AsyncIterable<T>, P
89
86
  */
90
87
  private listeners;
91
88
  private spies;
89
+ private _disposed;
92
90
  /**
93
91
  * A function that disposes of the event and its listeners.
94
92
  */
@@ -119,6 +117,11 @@ export declare class Event<T, R> extends Callable implements AsyncIterable<T>, P
119
117
  * @type {number}
120
118
  */
121
119
  get size(): number;
120
+ /**
121
+ * Checks if the event has been disposed.
122
+ * @returns {boolean} `true` if the event has been disposed; otherwise, `false`.
123
+ */
124
+ get disposed(): boolean;
122
125
  /**
123
126
  * Checks if the given listener is NOT registered for this event.
124
127
  *
@@ -467,14 +470,34 @@ export declare class Event<T, R> extends Callable implements AsyncIterable<T>, P
467
470
  * const taskQueue = taskEvent.queue();
468
471
  * (async () => {
469
472
  * console.log('Processing:', await taskQueue.pop()); // Processing: Task 1
470
- * console.log('Processing:', await taskQueue.pop()); // Processing: Task 2
473
+ * // Queue also can be used as a Promise
474
+ * console.log('Processing:', await taskQueue); // Processing: Task 2
475
+ * })();
476
+ * await taskEvent('Task 1');
477
+ * await taskEvent('Task 2');
478
+ *```
479
+ *
480
+ *```typescript
481
+ * // Additionally, the queue can be used as an async iterator
482
+ * const taskEvent = new Event<string>();
483
+ * const taskQueue = taskEvent.queue();
484
+ * (async () => {
485
+ * for await (const task of taskQueue) {
486
+ * console.log('Processing:', task);
487
+ * }
471
488
  * })();
472
489
  * await taskEvent('Task 1');
473
490
  * await taskEvent('Task 2');
474
491
  * ```
492
+ *
475
493
  */
476
494
  queue(): Queue<T>;
477
495
  }
496
+ export interface Queue<T> extends AsyncIterable<T>, PromiseLike<T> {
497
+ pop(): Promise<T>;
498
+ stop(): Promise<void>;
499
+ stopped: boolean;
500
+ }
478
501
  export type EventParameters<T> = T extends Event<infer P, any> ? P : never;
479
502
  export type EventResult<T> = T extends Event<any, infer R> ? R : never;
480
503
  export type AllEventsParameters<T extends Event<any, any>[]> = {
package/build/index.js CHANGED
@@ -21,8 +21,15 @@ export class Callable extends Function {
21
21
  }
22
22
  }
23
23
  export class Unsubscribe extends Callable {
24
+ _done = false;
24
25
  constructor(callback){
25
- super(callback);
26
+ super(()=>{
27
+ this._done = true;
28
+ callback();
29
+ });
30
+ }
31
+ get done() {
32
+ return this._done;
26
33
  }
27
34
  pre(callback) {
28
35
  return new Unsubscribe(async ()=>{
@@ -44,15 +51,22 @@ export class Unsubscribe extends Callable {
44
51
  });
45
52
  }
46
53
  }
54
+ var SpyType;
55
+ (function(SpyType) {
56
+ SpyType[SpyType["Add"] = 0] = "Add";
57
+ SpyType[SpyType["Remove"] = 1] = "Remove";
58
+ })(SpyType || (SpyType = {}));
47
59
  export class Event extends Callable {
48
60
  listeners;
49
61
  spies = [];
62
+ _disposed = false;
50
63
  dispose;
51
64
  constructor(dispose){
52
65
  const listeners = [];
53
66
  super(async (value)=>Promise.all(listeners.map(async (listener)=>listener(await value))));
54
67
  this.listeners = listeners;
55
68
  this.dispose = async ()=>{
69
+ this._disposed = true;
56
70
  void this.clear();
57
71
  await this._error?.dispose();
58
72
  await dispose?.();
@@ -65,6 +79,9 @@ export class Event extends Callable {
65
79
  get size() {
66
80
  return this.listeners.length;
67
81
  }
82
+ get disposed() {
83
+ return this._disposed;
84
+ }
68
85
  lacks(listener) {
69
86
  return this.listeners.indexOf(listener) === -1;
70
87
  }
@@ -75,12 +92,17 @@ export class Event extends Callable {
75
92
  if (removeListener(this.listeners, listener) && this.spies.length) {
76
93
  [
77
94
  ...this.spies
78
- ].forEach((spy)=>spy(listener));
95
+ ].forEach((spy)=>spy(listener, 1));
79
96
  }
80
97
  return this;
81
98
  }
82
99
  on(listener) {
83
100
  this.listeners.push(listener);
101
+ if (this.spies.length) {
102
+ [
103
+ ...this.spies
104
+ ].forEach((spy)=>spy(listener, 0));
105
+ }
84
106
  return new Unsubscribe(()=>{
85
107
  void this.off(listener);
86
108
  });
@@ -97,7 +119,7 @@ export class Event extends Callable {
97
119
  if (this.spies.length) {
98
120
  [
99
121
  ...this.spies
100
- ].forEach((spy)=>spy());
122
+ ].forEach((spy)=>spy(undefined, 1));
101
123
  }
102
124
  return this;
103
125
  }
@@ -120,8 +142,8 @@ export class Event extends Callable {
120
142
  queue.splice(0);
121
143
  await doneEvent.dispose();
122
144
  });
123
- const spy = (target = emitEvent)=>{
124
- if (target === emitEvent) {
145
+ const spy = (target = emitEvent, action)=>{
146
+ if (target === emitEvent && action === 1) {
125
147
  void doneEvent(true);
126
148
  void unsubscribe();
127
149
  }
@@ -168,8 +190,8 @@ export class Event extends Callable {
168
190
  const unsubscribe = this.on(emitEvent).pre(()=>{
169
191
  removeListener(this.spies, spy);
170
192
  });
171
- const spy = (target = emitEvent)=>{
172
- if (target === emitEvent) {
193
+ const spy = (target = emitEvent, action)=>{
194
+ if (target === emitEvent && action === 1) {
173
195
  void unsubscribe();
174
196
  }
175
197
  };
@@ -315,6 +337,9 @@ export class Event extends Callable {
315
337
  get stopped () {
316
338
  return done;
317
339
  },
340
+ then (onfulfilled, onrejected) {
341
+ return this.pop().then(onfulfilled, onrejected);
342
+ },
318
343
  [Symbol.asyncIterator] () {
319
344
  return {
320
345
  next: async ()=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type MaybePromise<T> = Promise<T> | PromiseLike<T> | T;\n\nexport interface Callback<R = void> {\n (): MaybePromise<R>;\n}\n\nexport interface Listener<T, R = unknown> {\n (event: T): MaybePromise<R | void>;\n}\n\nexport interface FilterFunction<T> {\n (event: T): MaybePromise<boolean>;\n}\n\nexport interface Predicate<T, P extends T> {\n (event: T): event is P;\n}\n\nexport type Filter<T, P extends T> = Predicate<T, P> | FilterFunction<T>;\n\nexport interface Mapper<T, R> {\n (event: T): MaybePromise<R>;\n}\n\nexport interface Reducer<T, R> {\n (result: R, event: T): MaybePromise<R>;\n}\n\nexport interface Expander<T, R> {\n (event: T): MaybePromise<R>;\n}\n\n/**\n * Removes a listener from the provided array of listeners. It searches for the listener and removes all instances of it from the array.\n * This method ensures that the listener is fully unregistered, preventing any residual calls to a potentially deprecated handler.\n *\n * @internal\n * @param {Listener<T, R>[]} listeners - The array of listeners from which to remove the listener.\n * @param {Listener<T, R>} listener - The listener function to remove from the list of listeners.\n * @returns {boolean} - Returns `true` if the listener was found and removed, `false` otherwise.\n *\n * @template T - The type of the event that listeners are associated with.\n * @template R - The type of the return value that listeners are expected to return.\n *\n * ```typescript\n * // Assuming an array of listeners for click events\n * const listeners = [onClickHandler1, onClickHandler2];\n * const wasRemoved = removeListener(listeners, onClickHandler1);\n * console.log(wasRemoved); // Output: true\n * ```\n */\nexport const removeListener = <T, R>(listeners: Listener<T, R>[], listener: Listener<T, R>): boolean => {\n let index = listeners.indexOf(listener);\n const wasRemoved = index !== -1;\n while (~index) {\n listeners.splice(index, 1);\n index = listeners.indexOf(listener);\n }\n return wasRemoved;\n};\n\n/**\n * @internal\n * @param timeout\n * @param signal\n * @returns\n */\nexport const setTimeoutAsync = (timeout: number, signal?: AbortSignal) =>\n new Promise<boolean>((resolve) => {\n const timerId = setTimeout(resolve, timeout, true);\n signal?.addEventListener('abort', () => {\n clearTimeout(timerId);\n resolve(false);\n });\n });\n\n/**\n * An abstract class that extends the built-in Function class. It allows instances of the class\n * to be called as functions. When an instance of Callable is called as a function, it will\n * call the function passed to its constructor with the same arguments.\n * @internal\n */\nexport abstract class Callable extends Function {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n constructor(func: Function) {\n super();\n return Object.setPrototypeOf(func, new.target.prototype);\n }\n}\n\nexport interface Unsubscribe {\n (): MaybePromise<void>;\n}\n\n/**\n * @internal\n */\nexport class Unsubscribe extends Callable {\n constructor(callback: Callback) {\n super(callback);\n }\n\n pre(callback: Callback): Unsubscribe {\n return new Unsubscribe(async () => {\n await callback();\n await this();\n });\n }\n\n post(callback: Callback): Unsubscribe {\n return new Unsubscribe(async () => {\n await this();\n await callback();\n });\n }\n\n countdown(count: number): Unsubscribe {\n return new Unsubscribe(async () => {\n if (!--count) {\n await this();\n }\n });\n }\n}\n\nexport interface Queue<T> extends AsyncIterable<T> {\n pop(): MaybePromise<T>;\n stop(): MaybePromise<void>;\n stopped: boolean;\n}\n\nexport interface Event<T = any, R = any> {\n (event: T): Promise<(void | Awaited<R>)[]>;\n}\n\n/**\n * A class representing an anonymous event that can be listened to or triggered.\n *\n * @template T - The event type.\n * @template R - The return type of the event.\n */\nexport class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLike<T> {\n /**\n * The array of listeners for the event.\n */\n private listeners: Listener<T, R>[];\n\n private spies: Array<(listener: Listener<T, R> | void) => void> = [];\n\n /**\n * A function that disposes of the event and its listeners.\n */\n readonly dispose: Callback;\n\n /**\n * Creates a new event.\n *\n * @param dispose - A function to call on the event disposal.\n *\n * ```typescript\n * // Create a click event.\n * const clickEvent = new Event<[x: number, y: number], void>();\n * clickEvent.on(([x, y]) => console.log(`Clicked at ${x}, ${y}`));\n * ```\n */\n constructor(dispose?: Callback) {\n const listeners: Listener<T, R>[] = [];\n // passes listeners exceptions to catch method\n super(async (value: T): Promise<(void | Awaited<R>)[]> => Promise.all(listeners.map(async (listener) => listener(await value))));\n this.listeners = listeners;\n\n this.dispose = async () => {\n void this.clear();\n await this._error?.dispose();\n await dispose?.();\n };\n }\n\n private _error?: Event<unknown>;\n\n /**\n * Error event that emits errors.\n *\n * @returns {Event<unknown>} The error event.\n */\n get error(): Event<unknown> {\n return (this._error ??= new Event<unknown>());\n }\n\n /**\n * The number of listeners for the event.\n *\n * @readonly\n * @type {number}\n */\n get size(): number {\n return this.listeners.length;\n }\n\n /**\n * Checks if the given listener is NOT registered for this event.\n *\n * @param listener - The listener function to check against the registered listeners.\n * @returns `true` if the listener is not already registered; otherwise, `false`.\n *\n * ```typescript\n * // Check if a listener is not already added\n * if (event.lacks(myListener)) {\n * event.on(myListener);\n * }\n * ```\n */\n lacks(listener: Listener<T, R>): boolean {\n return this.listeners.indexOf(listener) === -1;\n }\n\n /**\n * Checks if the given listener is registered for this event.\n *\n * @param listener - The listener function to check.\n * @returns `true` if the listener is currently registered; otherwise, `false`.\n *\n * ```typescript\n * // Verify if a listener is registered\n * if (event.has(myListener)) {\n * console.log('Listener is already registered');\n * }\n * ```\n */\n has(listener: Listener<T, R>): boolean {\n return this.listeners.indexOf(listener) !== -1;\n }\n\n /**\n * Removes a specific listener from this event.\n *\n * @param listener - The listener to remove.\n * @returns The event instance, allowing for method chaining.\n *\n * ```typescript\n * // Remove a listener\n * event.off(myListener);\n * ```\n */\n off(listener: Listener<T, R>): this {\n if (removeListener(this.listeners, listener) && this.spies.length) {\n [...this.spies].forEach((spy) => spy(listener));\n }\n return this;\n }\n\n /**\n * Registers a listener that gets triggered whenever the event is emitted.\n * This is the primary method for adding event handlers that will react to the event being triggered.\n *\n * @param listener - The function to call when the event occurs.\n * @returns An object that can be used to unsubscribe the listener, ensuring easy cleanup.\n *\n * ```typescript\n * // Add a listener to an event\n * const unsubscribe = event.on((data) => {\n * console.log('Event data:', data);\n * });\n * ```\n */\n on(listener: Listener<T, R>): Unsubscribe {\n this.listeners.push(listener);\n return new Unsubscribe(() => {\n void this.off(listener);\n });\n }\n\n /**\n * Adds a listener that will be called only once the next time the event is emitted.\n * This method is useful for one-time notifications or single-trigger scenarios.\n *\n * @param listener - The listener to trigger once.\n * @returns An object that can be used to remove the listener if the event has not yet occurred.\n *\n * ```typescript\n * // Register a one-time listener\n * const onceUnsubscribe = event.once((data) => {\n * console.log('Received data once:', data);\n * });\n * ```\n */\n once(listener: Listener<T, R>): Unsubscribe {\n const oneTimeListener = (event: T) => {\n void this.off(oneTimeListener);\n return listener(event);\n };\n return this.on(oneTimeListener);\n }\n\n /**\n * Removes all listeners from the event, effectively resetting it. This is useful when you need to\n * cleanly dispose of all event handlers to prevent memory leaks or unwanted triggerings after certain conditions.\n *\n * @returns {this} The instance of the event, allowing for method chaining.\n *\n * ```typescript\n * const myEvent = new Event();\n * myEvent.on(data => console.log(data));\n * myEvent.clear(); // Clears all listeners\n * ```\n */\n clear(): this {\n this.listeners.splice(0);\n if (this.spies.length) {\n [...this.spies].forEach((spy) => spy());\n }\n return this;\n }\n\n /**\n * Enables the `Event` to be used in a Promise chain, resolving with the first emitted value.\n *\n * @template TResult1 - The type of the fulfilled value returned by `onfulfilled` (defaults to the event's type).\n * @template TResult2 - The type of the rejected value returned by `onrejected` (defaults to `never`).\n * @param onfulfilled - A function called when the event emits its first value.\n * @param onrejected - A function called if an error occurs before the event emits.\n * @returns A Promise that resolves with the result of `onfulfilled` or `onrejected`.\n *\n * ```typescript\n * const clickEvent = new Event<[number, number]>();\n * await clickEvent;\n * ```\n */\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n const promise = new Promise<T>((resolve) => this.once(resolve));\n\n return promise.then(onfulfilled, onrejected);\n }\n\n /**\n * A promise that resolves with the first emitted value from this event.\n *\n * @returns {Promise<T>} The promise value.\n */\n get promise(): Promise<T> {\n return this.then((v) => v);\n }\n\n /**\n * Makes this event iterable using `for await...of` loops.\n *\n * @returns An async iterator that yields values as they are emitted by this event.\n *\n * ```typescript\n * // Assuming an event that emits numbers\n * const numberEvent = new Event<number>();\n * (async () => {\n * for await (const num of numberEvent) {\n * console.log('Number:', num);\n * }\n * })();\n * await numberEvent(1);\n * await numberEvent(2);\n * await numberEvent(3);\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n const queue: T[] = [];\n const doneEvent = new Event<boolean>();\n const emitEvent = async (value: T) => {\n queue.push(value);\n await doneEvent(false);\n };\n const unsubscribe = this.on(emitEvent).pre(async () => {\n removeListener(this.spies, spy);\n queue.splice(0);\n await doneEvent.dispose();\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent) => {\n if (target === emitEvent) {\n void doneEvent(true);\n void unsubscribe();\n }\n };\n\n this.spies.push(spy);\n return {\n async next() {\n if (queue.length) {\n return { value: queue.shift()!, done: false };\n }\n if (!(await doneEvent)) {\n return { value: queue.shift()!, done: false };\n }\n return { value: undefined, done: true };\n },\n async return(value: unknown) {\n await unsubscribe();\n return { done: true, value };\n },\n };\n }\n\n /**\n * Transforms the event's values using a generator function, creating a new `Event` that emits the transformed values.\n *\n * @template PT - The type of values emitted by the transformed `Event`.\n * @template PR - The return type of the listeners of the transformed `Event`.\n * @param generator - A function that takes the original event's value and returns a generator (sync or async) that yields the transformed values.\n * @returns A new `Event` instance that emits the transformed values.\n *\n * ```typescript\n * const numbersEvent = new Event<number>();\n * const evenNumbersEvent = numbersEvent.pipe(function*(value) {\n * if (value % 2 === 0) {\n * yield value;\n * }\n * });\n * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));\n * await numbersEvent(1);\n * await numbersEvent(2);\n * await numbersEvent(3);\n * ```\n */\n pipe<PT, R>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): Event<PT, R> {\n const emitEvent = async (value: T) => {\n try {\n for await (const generatedValue of generator(value)) {\n await result(generatedValue).catch((e) => result.error(e));\n }\n } catch (e) {\n await result.error(e);\n }\n };\n\n const unsubscribe = this.on(emitEvent).pre(() => {\n removeListener(this.spies, spy);\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent) => {\n if (target === emitEvent) {\n void unsubscribe();\n }\n };\n this.spies.push(spy);\n\n const result = new Event<PT, R>(unsubscribe);\n return result;\n }\n\n /**\n * Creates an async generator that yields values as they are emitted by this event.\n *\n * @template PT - The type of values yielded by the async generator.\n * @param generator - An optional function that takes the original event's value and returns a generator (sync or async)\n * that yields values to include in the async generator.\n * @returns An async generator that yields values from this event as they occur.\n *\n * ```typescript\n * const numbersEvent = new Event<number>();\n * const evenNumbersEvent = numbersEvent.pipe(function*(value) {\n * if (value % 2 === 0) {\n * yield value;\n * }\n * });\n * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));\n * await numbersEvent(1);\n * await numbersEvent(2);\n * await numbersEvent(3);\n * ```\n */\n async *generator<PT>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): AsyncGenerator<Awaited<PT>, void, unknown> {\n for await (const value of this.pipe(generator)) {\n yield value;\n }\n }\n\n /**\n * Filters events, creating a new event that only triggers when the provided filter function returns `true`.\n * This method can be used to selectively process events that meet certain criteria.\n *\n * @param {Filter<T, P>} predicate The filter function or predicate to apply to each event.\n * @returns {Event<P, R>} A new event that only triggers for filtered events.\n *\n * ```typescript\n * const keyPressedEvent = new Event<string>();\n * const enterPressedEvent = keyPressedEvent.filter(key => key === 'Enter');\n * enterPressedEvent.on(() => console.log('Enter key was pressed.'));\n * ```\n */\n filter<P extends T>(predicate: Predicate<T, P>): Event<P, R>;\n filter<P extends T>(filter: FilterFunction<T>): Event<P, R>;\n filter<P extends T>(filter: Filter<T, P>): Event<P, R> {\n return this.pipe<P, R>(async function* (value: T) {\n if (await filter(value)) {\n yield value as P;\n }\n });\n }\n\n /**\n * Creates a new event that will only be triggered once when the provided filter function returns `true`.\n * This method is useful for handling one-time conditions in a stream of events.\n *\n * @param {Filter<T, P>} predicate - The filter function or predicate.\n * @returns {Event<P, R>} A new event that will be triggered only once when the filter condition is met.\n *\n * ```typescript\n * const sizeChangeEvent = new Event<number>();\n * const sizeReachedEvent = sizeChangeEvent.first(size => size > 1024);\n * sizeReachedEvent.on(() => console.log('Size threshold exceeded.'));\n * ```\n */\n first<P extends T>(predicate: Predicate<T, P>): Event<P, R>;\n first<P extends T>(filter: FilterFunction<T>): Event<P, R>;\n first<P extends T>(filter: Filter<T, P>): Event<P, R> {\n const filteredEvent = this.pipe<P, R>(async function* (value: T) {\n if (await filter(value)) {\n yield value as P;\n await filteredEvent.dispose();\n }\n });\n return filteredEvent;\n }\n\n /**\n * Transforms the data emitted by this event using a mapping function. Each emitted event is processed by the `mapper`\n * function, which returns a new value that is then emitted by the returned `Event` instance. This is useful for data transformation\n * or adapting the event's data structure.\n *\n * @template M The type of data that the mapper function will produce.\n * @template MR The type of data emitted by the mapped event, usually related to or the same as `M`.\n * @param {Mapper<T, M>} mapper A function that takes the original event data and returns the transformed data.\n * @returns {Event<M, MR>} A new `Event` instance that emits the mapped values.\n *\n * ```typescript\n * // Assuming an event that emits numbers, create a new event that emits their squares.\n * const numberEvent = new Event<number>();\n * const squaredEvent = numberEvent.map(num => num * num);\n * squaredEvent.on(squared => console.log('Squared number:', squared));\n * await numberEvent(5); // Logs: \"Squared number: 25\"\n * ```\n */\n map<M, MR = R>(mapper: Mapper<T, M>): Event<Awaited<M>, MR> {\n return this.pipe(async function* (value) {\n yield await mapper(value);\n });\n }\n\n /**\n * Accumulates the values emitted by this event using a reducer function, starting from an initial value. The reducer\n * function takes the accumulated value and the latest emitted event data, then returns a new accumulated value. This\n * new value is then emitted by the returned `Event` instance. This is particularly useful for accumulating state over time.\n *\n * @template A The type of the accumulator value.\n * @template AR The type of data emitted by the reduced event, usually the same as `A`.\n * @param {Reducer<T, A>} reducer A function that takes the current accumulated value and the new event data, returning the new accumulated value.\n * @param {A} init The initial value of the accumulator.\n * @returns {Event<A, AR>} A new `Event` instance that emits the reduced value.\n *\n * ```typescript\n * const sumEvent = numberEvent.reduce((a, b) => a + b, 0);\n * sumEvent.on((sum) => console.log(sum)); // 1, 3, 6\n * await sumEvent(1);\n * await sumEvent(2);\n * await sumEvent(3);\n * ```\n */\n reduce<A, AR = R>(reducer: Reducer<T, A>, init?: A): Event<Awaited<A>, AR>;\n reduce<A, AR = R>(reducer: Reducer<T, A>, ...init: unknown[]): Event<Awaited<A>, AR> {\n let hasInit = init.length === 1;\n let result = init[0] as A | undefined;\n\n return this.pipe(async function* (value) {\n if (hasInit) {\n result = await reducer(result!, value);\n yield result;\n } else {\n result = value as unknown as A;\n hasInit = true;\n }\n });\n }\n\n /**\n * Transforms each event's data into multiple events using an expander function. The expander function takes\n * the original event's data and returns an array of new data elements, each of which will be emitted individually\n * by the returned `Event` instance. This method is useful for scenarios where an event's data can naturally\n * be expanded into multiple, separate pieces of data which should each trigger further processing independently.\n *\n * @template ET - The type of data elements in the array returned by the expander function.\n * @template ER - The type of responses emitted by the expanded event, usually related to or the same as `ET`.\n * @param {Expander<T, ET[]>} expander - A function that takes the original event data and returns an array of new data elements.\n * @returns {Event<ET, ER>} - A new `Event` instance that emits each value from the array returned by the expander function.\n *\n * ```typescript\n * // Assuming an event that emits a sentence, create a new event that emits each word from the sentence separately.\n * const sentenceEvent = new Event<string>();\n * const wordEvent = sentenceEvent.expand(sentence => sentence.split(' '));\n * wordEvent.on(word => console.log('Word:', word));\n * await sentenceEvent('Hello world'); // Logs: \"Word: Hello\", \"Word: world\"\n * ```\n */\n expand<ET, ER>(expander: Expander<T, ET[]>): Event<Awaited<ET>, ER> {\n return this.pipe(async function* (value) {\n const values = await expander(value);\n for (const value of values) {\n yield value;\n }\n });\n }\n\n /**\n * Creates a new event that emits values based on a conductor event. The orchestrated event will emit the last value\n * captured from the original event each time the conductor event is triggered. This method is useful for synchronizing\n * events, where the emission of one event controls the timing of another.\n *\n * @template T The type of data emitted by the original event.\n * @template R The type of data emitted by the orchestrated event, usually the same as `T`.\n * @param {Event<unknown, unknown>} conductor An event that signals when the orchestrated event should emit.\n * @returns {Event<T, R>} An orchestrated event that emits values based on the conductor's trigger.\n *\n * ```typescript\n * const rightClickPositionEvent = mouseMoveEvent.orchestrate(mouseRightClickEvent);\n * ```\n *\n * ```typescript\n * // An event that emits whenever a \"tick\" event occurs.\n * const tickEvent = new Event<void>();\n * const dataEvent = new Event<string>();\n * const synchronizedEvent = dataEvent.orchestrate(tickEvent);\n * synchronizedEvent.on(data => console.log('Data on tick:', data));\n * await dataEvent('Hello');\n * await dataEvent('World!');\n * await tickEvent(); // Logs: \"Data on tick: World!\"\n * ```\n */\n orchestrate(conductor: Event<any, any>): Event<T, R> {\n let initialized = false;\n let lastValue: T;\n const unsubscribe = this.on(async (event) => {\n initialized = true;\n lastValue = event;\n });\n const unsubscribeConductor = conductor.on(async () => {\n if (initialized) {\n await orchestratedEvent(lastValue);\n initialized = false;\n }\n });\n\n const orchestratedEvent = new Event<T, R>(unsubscribe.post(unsubscribeConductor));\n return orchestratedEvent;\n }\n /**\n * Creates a debounced event that delays triggering until after a specified interval has elapsed\n * following the last time it was invoked. This method is particularly useful for limiting the rate\n * at which a function is executed. Common use cases include handling rapid user inputs, window resizing,\n * or scroll events.\n *\n * @param {number} interval - The amount of time to wait (in milliseconds) before firing the debounced event.\n * @returns {Event<T, R>} An event of debounced events.\n *\n * ```typescript\n * const debouncedEvent = textInputEvent.debounce(100);\n * debouncedEvent.on((str) => console.log(str)); // only 'text' is emitted\n * await event('t');\n * await event('te');\n * await event('tex');\n * await event('text');\n * ```\n */\n debounce(interval: number): Event<Awaited<T>, unknown> {\n let controller = new AbortController();\n\n return this.pipe(async function* (value) {\n controller.abort();\n controller = new AbortController();\n const complete = await setTimeoutAsync(interval, controller.signal);\n if (complete) {\n yield value;\n }\n });\n }\n\n /**\n * Creates a throttled event that emits values at most once per specified interval.\n *\n * This is useful for controlling the rate of event emissions, especially for high-frequency events.\n * The throttled event will immediately emit the first value, and then only emit subsequent values\n * if the specified interval has passed since the last emission.\n *\n * @param interval - The time interval (in milliseconds) between allowed emissions.\n * @returns A new Event that emits throttled values.\n *\n * ```typescript\n * const scrollEvent = new Event();\n * const throttledScroll = scrollEvent.throttle(100); // Emit at most every 100ms\n * throttledScroll.on(() => console.log(\"Throttled scroll event\"));\n * ```\n */\n throttle(interval: number): Event<Awaited<T>, unknown> {\n let timeout = 0;\n let pendingValue: T;\n let hasPendingValue = false;\n\n return this.pipe(async function* (value) {\n const now = Date.now();\n if (timeout <= now) {\n timeout = now + interval;\n yield value;\n } else {\n pendingValue = value;\n if (!hasPendingValue) {\n hasPendingValue = true;\n await setTimeoutAsync(timeout - now);\n timeout = now + interval;\n hasPendingValue = false;\n yield pendingValue;\n }\n }\n });\n }\n\n /**\n * Aggregates multiple event emissions into batches and emits the batched events either at specified\n * time intervals or when the batch reaches a predefined size. This method is useful for grouping\n * a high volume of events into manageable chunks, such as logging or processing data in bulk.\n *\n * @param {number} interval - The time in milliseconds between batch emissions.\n * @param {number} [size] - Optional. The maximum size of each batch. If specified, triggers a batch emission\n * once the batch reaches this size, regardless of the interval.\n * @returns {Event<T[], R>} An event of the batched results.\n *\n * ```typescript\n * // Batch messages for bulk processing every 1 second or when 10 messages are collected\n * const messageEvent = createEvent<string, void>();\n * const batchedMessageEvent = messageEvent.batch(1000, 10);\n * batchedMessageEvent.on((messages) => console.log('Batched Messages:', messages));\n * ```\n */\n batch(interval: number, size?: number): Event<T[], R> {\n let controller = new AbortController();\n const batch: T[] = [];\n\n return this.pipe(async function* (value) {\n batch.push(value);\n if (size !== undefined && batch.length >= size) {\n controller.abort();\n yield batch.splice(0);\n }\n if (batch.length === 1) {\n controller = new AbortController();\n const complete = await setTimeoutAsync(interval, controller.signal);\n if (complete) {\n yield batch.splice(0);\n }\n }\n });\n }\n\n /**\n * Creates a queue from the event, where each emitted value is sequentially processed. The returned object allows popping elements\n * from the queue, ensuring that elements are handled one at a time. This method is ideal for scenarios where order and sequential processing are critical.\n *\n * @returns {Queue<T>} An object representing the queue. The 'pop' method retrieves the next element from the queue, while 'stop' halts further processing.\n *\n * ```typescript\n * // Queueing tasks for sequential execution\n * const taskEvent = new Event<string>();\n * const taskQueue = taskEvent.queue();\n * (async () => {\n * console.log('Processing:', await taskQueue.pop()); // Processing: Task 1\n * console.log('Processing:', await taskQueue.pop()); // Processing: Task 2\n * })();\n * await taskEvent('Task 1');\n * await taskEvent('Task 2');\n * ```\n */\n queue(): Queue<T> {\n const queue: T[] = [];\n let done = false;\n const valueEvent = new Event<void>();\n const unsubscribe = this.on(async (value) => {\n queue.push(value);\n await valueEvent();\n });\n\n const pop = async () => {\n if (!queue.length) {\n await valueEvent;\n }\n return queue.shift()!;\n };\n const stop = async () => {\n await unsubscribe();\n done = true;\n await valueEvent();\n };\n\n return {\n pop,\n stop,\n get stopped() {\n return done;\n },\n [Symbol.asyncIterator]() {\n return {\n next: async () => {\n return { value: await pop(), done };\n },\n };\n },\n };\n }\n}\n\nexport type EventParameters<T> = T extends Event<infer P, any> ? P : never;\n\nexport type EventResult<T> = T extends Event<any, infer R> ? R : never;\n\nexport type AllEventsParameters<T extends Event<any, any>[]> = { [K in keyof T]: EventParameters<T[K]> }[number];\n\nexport type AllEventsResults<T extends Event<any, any>[]> = { [K in keyof T]: EventResult<T[K]> }[number];\n\n/**\n * Merges multiple events into a single event. This function takes any number of `Event` instances\n * and returns a new `Event` that triggers whenever any of the input events trigger. The parameters\n * and results of the merged event are derived from the input events, providing a flexible way to\n * handle multiple sources of events in a unified manner.\n *\n * @template Events - An array of `Event` instances.\n * @param {...Events} events - A rest parameter that takes multiple events to be merged.\n * @returns {Event<AllEventsParameters<Events>, AllEventsResults<Events>>} - Returns a new `Event` instance\n * that triggers with the parameters and results of any of the merged input events.\n *\n * ```typescript\n * // Merging mouse and keyboard events into a single event\n * const mouseEvent = createEvent<MouseEvent>();\n * const keyboardEvent = createEvent<KeyboardEvent>();\n * const inputEvent = merge(mouseEvent, keyboardEvent);\n * inputEvent.on(event => console.log('Input event:', event));\n * ```\n */\nexport const merge = <Events extends Event<any, any>[]>(...events: Events): Event<AllEventsParameters<Events>, AllEventsResults<Events>> => {\n const mergedEvent = new Event<AllEventsParameters<Events>, AllEventsResults<Events>>();\n events.forEach((event) => event.on(mergedEvent));\n return mergedEvent;\n};\n\n/**\n * Creates a periodic event that triggers at a specified interval. The event will automatically emit\n * an incrementing counter value each time it triggers, starting from zero. This function is useful\n * for creating time-based triggers within an application, such as updating UI elements, polling,\n * or any other timed operation.\n *\n * @template R - The return type of the event handler function, defaulting to `void`.\n * @param {number} interval - The interval in milliseconds at which the event should trigger.\n * @returns {Event<number, R>} - An `Event` instance that triggers at the specified interval,\n * emitting an incrementing counter value.\n *\n * ```typescript\n * // Creating an interval event that logs a message every second\n * const tickEvent = createInterval(1000);\n * tickEvent.on(tickNumber => console.log('Tick:', tickNumber));\n * ```\n */\nexport const createInterval = <R = unknown>(interval: number): Event<number, R> => {\n let counter = 0;\n const intervalEvent = new Event<number, R>(() => clearInterval(timerId));\n const timerId: ReturnType<typeof setInterval> = setInterval(() => intervalEvent(counter++), interval);\n return intervalEvent;\n};\n\n/**\n * Creates a new instance of the `Event` class, which allows for the registration of event handlers that get called when the event is emitted.\n * This factory function simplifies the creation of events by encapsulating the instantiation logic, providing a clean and simple API for event creation.\n *\n * @typeParam T - The tuple of argument types that the event will accept.\n * @typeParam R - The return type of the event handler function, which is emitted after processing the event data.\n * @returns {Event<T, R>} - A new instance of the `Event` class, ready to have listeners added to it.\n *\n * ```typescript\n * // Create a new event that accepts a string and returns the string length\n * const myEvent = createEvent<string, number>();\n * myEvent.on((str: string) => str.length);\n * myEvent('hello').then(results => console.log(results)); // Logs: [5]\n * ```\n */\nexport const createEvent = <T = unknown, R = unknown>(): Event<T, R> => new Event<T, R>();\n\nexport default createEvent;\n\n/**\n * A type helper that extracts the event listener type\n *\n * @typeParam E - The event type.\n */\nexport type EventHandler<E> = E extends Event<infer T, infer R> ? Listener<T, R> : never;\n\n/**\n * A type helper that extracts the event filter type\n *\n * @typeParam E The event type to filter.\n */\nexport type EventFilter<E> = FilterFunction<EventParameters<E>>;\n\n/**\n * A type helper that extracts the event predicate type\n *\n * @typeParam E The event type to predicate.\n */\nexport type EventPredicate<E, P extends EventParameters<E>> = Predicate<EventParameters<E>, P>;\n\n/**\n * A type helper that extracts the event mapper type\n *\n * @typeParam E The event type to map.\n * @typeParam M The new type to map `E` to.\n */\nexport type EventMapper<E, M> = Mapper<EventParameters<E>, M>;\n\n/**\n * A type helper that extracts the event mapper type\n *\n * @typeParam E The type of event to reduce.\n * @typeParam M The type of reduced event.\n */\nexport type EventReducer<E, R> = Reducer<EventParameters<E>, R>;\n"],"names":["removeListener","listeners","listener","index","indexOf","wasRemoved","splice","setTimeoutAsync","timeout","signal","Promise","resolve","timerId","setTimeout","addEventListener","clearTimeout","Callable","Function","constructor","func","Object","setPrototypeOf","prototype","Unsubscribe","callback","pre","post","countdown","count","Event","spies","dispose","value","all","map","clear","_error","error","size","length","lacks","has","off","forEach","spy","on","push","once","oneTimeListener","event","then","onfulfilled","onrejected","promise","v","Symbol","asyncIterator","queue","doneEvent","emitEvent","unsubscribe","target","next","shift","done","undefined","return","pipe","generator","generatedValue","result","catch","e","filter","first","filteredEvent","mapper","reduce","reducer","init","hasInit","expand","expander","values","orchestrate","conductor","initialized","lastValue","unsubscribeConductor","orchestratedEvent","debounce","interval","controller","AbortController","abort","complete","throttle","pendingValue","hasPendingValue","now","Date","batch","valueEvent","pop","stop","stopped","merge","events","mergedEvent","createInterval","counter","intervalEvent","clearInterval","setInterval","createEvent"],"mappings":"AAmDA,OAAO,MAAMA,iBAAiB,CAAOC,WAA6BC;IAChE,IAAIC,QAAQF,UAAUG,OAAO,CAACF;IAC9B,MAAMG,aAAaF,UAAU,CAAC;IAC9B,MAAO,CAACA,MAAO;QACbF,UAAUK,MAAM,CAACH,OAAO;QACxBA,QAAQF,UAAUG,OAAO,CAACF;IAC5B;IACA,OAAOG;AACT,EAAE;AAQF,OAAO,MAAME,kBAAkB,CAACC,SAAiBC,SAC/C,IAAIC,QAAiB,CAACC;QACpB,MAAMC,UAAUC,WAAWF,SAASH,SAAS;QAC7CC,QAAQK,iBAAiB,SAAS;YAChCC,aAAaH;YACbD,QAAQ;QACV;IACF,GAAG;AAQL,OAAO,MAAeK,iBAAiBC;IAErCC,YAAYC,IAAc,CAAE;QAC1B,KAAK;QACL,OAAOC,OAAOC,cAAc,CAACF,MAAM,WAAWG,SAAS;IACzD;AACF;AASA,OAAO,MAAMC,oBAAoBP;IAC/BE,YAAYM,QAAkB,CAAE;QAC9B,KAAK,CAACA;IACR;IAEAC,IAAID,QAAkB,EAAe;QACnC,OAAO,IAAID,YAAY;YACrB,MAAMC;YACN,MAAM,IAAI;QACZ;IACF;IAEAE,KAAKF,QAAkB,EAAe;QACpC,OAAO,IAAID,YAAY;YACrB,MAAM,IAAI;YACV,MAAMC;QACR;IACF;IAEAG,UAAUC,KAAa,EAAe;QACpC,OAAO,IAAIL,YAAY;YACrB,IAAI,CAAC,EAAEK,OAAO;gBACZ,MAAM,IAAI;YACZ;QACF;IACF;AACF;AAkBA,OAAO,MAAMC,cAAoBb;IAIvBf,UAA4B;IAE5B6B,QAA0D,EAAE,CAAC;IAK5DC,QAAkB;IAa3Bb,YAAYa,OAAkB,CAAE;QAC9B,MAAM9B,YAA8B,EAAE;QAEtC,KAAK,CAAC,OAAO+B,QAA6CtB,QAAQuB,GAAG,CAAChC,UAAUiC,G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MuE;4BAAOvC;wBAAK;oBACpC;gBACF;YACF;QACF;IACF;AACF;AA6BA,OAAO,MAAM0C,QAAQ,CAAmC,GAAGC;IACzD,MAAMC,cAAc,IAAI/E;IACxB8E,OAAOhE,OAAO,CAAC,CAACM,QAAUA,MAAMJ,EAAE,CAAC+D;IACnC,OAAOA;AACT,EAAE;AAmBF,OAAO,MAAMC,iBAAiB,CAAclB;IAC1C,IAAImB,UAAU;IACd,MAAMC,gBAAgB,IAAIlF,MAAiB,IAAMmF,cAAcpG;IAC/D,MAAMA,UAA0CqG,YAAY,IAAMF,cAAcD,YAAYnB;IAC5F,OAAOoB;AACT,EAAE;AAiBF,OAAO,MAAMG,cAAc,IAA6C,IAAIrF,QAAc;AAE1F,eAAeqF,YAAY"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type MaybePromise<T> = Promise<T> | PromiseLike<T> | T;\n\nexport interface Callback<R = void> {\n (): MaybePromise<R>;\n}\n\nexport interface Listener<T, R = unknown> {\n (event: T): MaybePromise<R | void>;\n}\n\nexport interface FilterFunction<T> {\n (event: T): MaybePromise<boolean>;\n}\n\nexport interface Predicate<T, P extends T> {\n (event: T): event is P;\n}\n\nexport type Filter<T, P extends T> = Predicate<T, P> | FilterFunction<T>;\n\nexport interface Mapper<T, R> {\n (event: T): MaybePromise<R>;\n}\n\nexport interface Reducer<T, R> {\n (result: R, event: T): MaybePromise<R>;\n}\n\nexport interface Expander<T, R> {\n (event: T): MaybePromise<R>;\n}\n\n/**\n * Removes a listener from the provided array of listeners. It searches for the listener and removes all instances of it from the array.\n * This method ensures that the listener is fully unregistered, preventing any residual calls to a potentially deprecated handler.\n *\n * @internal\n * @param {Listener<T, R>[]} listeners - The array of listeners from which to remove the listener.\n * @param {Listener<T, R>} listener - The listener function to remove from the list of listeners.\n * @returns {boolean} - Returns `true` if the listener was found and removed, `false` otherwise.\n *\n * @template T - The type of the event that listeners are associated with.\n * @template R - The type of the return value that listeners are expected to return.\n *\n * ```typescript\n * // Assuming an array of listeners for click events\n * const listeners = [onClickHandler1, onClickHandler2];\n * const wasRemoved = removeListener(listeners, onClickHandler1);\n * console.log(wasRemoved); // Output: true\n * ```\n */\nexport const removeListener = (listeners: unknown[], listener: unknown): boolean => {\n let index = listeners.indexOf(listener);\n const wasRemoved = index !== -1;\n while (~index) {\n listeners.splice(index, 1);\n index = listeners.indexOf(listener);\n }\n return wasRemoved;\n};\n\n/**\n * @internal\n * @param timeout\n * @param signal\n * @returns\n */\nexport const setTimeoutAsync = (timeout: number, signal?: AbortSignal) =>\n new Promise<boolean>((resolve) => {\n const timerId = setTimeout(resolve, timeout, true);\n signal?.addEventListener('abort', () => {\n clearTimeout(timerId);\n resolve(false);\n });\n });\n\n/**\n * An abstract class that extends the built-in Function class. It allows instances of the class\n * to be called as functions. When an instance of Callable is called as a function, it will\n * call the function passed to its constructor with the same arguments.\n * @internal\n */\nexport abstract class Callable extends Function {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n constructor(func: Function) {\n super();\n return Object.setPrototypeOf(func, new.target.prototype);\n }\n}\n\nexport interface Unsubscribe {\n (): MaybePromise<void>;\n}\n\n/**\n * @internal\n */\nexport class Unsubscribe extends Callable {\n private _done = false;\n\n constructor(callback: Callback) {\n super(() => {\n this._done = true;\n callback();\n });\n }\n\n get done() {\n return this._done;\n }\n\n pre(callback: Callback): Unsubscribe {\n return new Unsubscribe(async () => {\n await callback();\n await this();\n });\n }\n\n post(callback: Callback): Unsubscribe {\n return new Unsubscribe(async () => {\n await this();\n await callback();\n });\n }\n\n countdown(count: number): Unsubscribe {\n return new Unsubscribe(async () => {\n if (!--count) {\n await this();\n }\n });\n }\n}\n\nexport interface Event<T = any, R = any> {\n (event: T): Promise<(void | Awaited<R>)[]>;\n}\n\nenum SpyType {\n Add,\n Remove,\n}\n\n/**\n * A class representing an anonymous event that can be listened to or triggered.\n *\n * @template T - The event type.\n * @template R - The return type of the event.\n */\nexport class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLike<T> {\n /**\n * The array of listeners for the event.\n */\n private listeners: Listener<T, R>[];\n\n private spies: Array<(listener: Listener<T, R> | void, type: SpyType) => void> = [];\n\n private _disposed = false;\n\n /**\n * A function that disposes of the event and its listeners.\n */\n readonly dispose: Callback;\n\n /**\n * Creates a new event.\n *\n * @param dispose - A function to call on the event disposal.\n *\n * ```typescript\n * // Create a click event.\n * const clickEvent = new Event<[x: number, y: number], void>();\n * clickEvent.on(([x, y]) => console.log(`Clicked at ${x}, ${y}`));\n * ```\n */\n constructor(dispose?: Callback) {\n const listeners: Listener<T, R>[] = [];\n // passes listeners exceptions to catch method\n super(async (value: T): Promise<(void | Awaited<R>)[]> => Promise.all(listeners.map(async (listener) => listener(await value))));\n this.listeners = listeners;\n\n this.dispose = async () => {\n this._disposed = true;\n void this.clear();\n await this._error?.dispose();\n await dispose?.();\n };\n }\n\n private _error?: Event<unknown>;\n\n /**\n * Error event that emits errors.\n *\n * @returns {Event<unknown>} The error event.\n */\n get error(): Event<unknown> {\n return (this._error ??= new Event<unknown>());\n }\n\n /**\n * The number of listeners for the event.\n *\n * @readonly\n * @type {number}\n */\n get size(): number {\n return this.listeners.length;\n }\n\n /**\n * Checks if the event has been disposed.\n * @returns {boolean} `true` if the event has been disposed; otherwise, `false`.\n */\n get disposed(): boolean {\n return this._disposed;\n }\n\n /**\n * Checks if the given listener is NOT registered for this event.\n *\n * @param listener - The listener function to check against the registered listeners.\n * @returns `true` if the listener is not already registered; otherwise, `false`.\n *\n * ```typescript\n * // Check if a listener is not already added\n * if (event.lacks(myListener)) {\n * event.on(myListener);\n * }\n * ```\n */\n lacks(listener: Listener<T, R>): boolean {\n return this.listeners.indexOf(listener) === -1;\n }\n\n /**\n * Checks if the given listener is registered for this event.\n *\n * @param listener - The listener function to check.\n * @returns `true` if the listener is currently registered; otherwise, `false`.\n *\n * ```typescript\n * // Verify if a listener is registered\n * if (event.has(myListener)) {\n * console.log('Listener is already registered');\n * }\n * ```\n */\n has(listener: Listener<T, R>): boolean {\n return this.listeners.indexOf(listener) !== -1;\n }\n\n /**\n * Removes a specific listener from this event.\n *\n * @param listener - The listener to remove.\n * @returns The event instance, allowing for method chaining.\n *\n * ```typescript\n * // Remove a listener\n * event.off(myListener);\n * ```\n */\n off(listener: Listener<T, R>): this {\n if (removeListener(this.listeners, listener) && this.spies.length) {\n [...this.spies].forEach((spy) => spy(listener, SpyType.Remove));\n }\n return this;\n }\n\n /**\n * Registers a listener that gets triggered whenever the event is emitted.\n * This is the primary method for adding event handlers that will react to the event being triggered.\n *\n * @param listener - The function to call when the event occurs.\n * @returns An object that can be used to unsubscribe the listener, ensuring easy cleanup.\n *\n * ```typescript\n * // Add a listener to an event\n * const unsubscribe = event.on((data) => {\n * console.log('Event data:', data);\n * });\n * ```\n */\n on(listener: Listener<T, R>): Unsubscribe {\n this.listeners.push(listener);\n if (this.spies.length) {\n [...this.spies].forEach((spy) => spy(listener, SpyType.Add));\n }\n return new Unsubscribe(() => {\n void this.off(listener);\n });\n }\n\n /**\n * Adds a listener that will be called only once the next time the event is emitted.\n * This method is useful for one-time notifications or single-trigger scenarios.\n *\n * @param listener - The listener to trigger once.\n * @returns An object that can be used to remove the listener if the event has not yet occurred.\n *\n * ```typescript\n * // Register a one-time listener\n * const onceUnsubscribe = event.once((data) => {\n * console.log('Received data once:', data);\n * });\n * ```\n */\n once(listener: Listener<T, R>): Unsubscribe {\n const oneTimeListener = (event: T) => {\n void this.off(oneTimeListener);\n return listener(event);\n };\n return this.on(oneTimeListener);\n }\n\n /**\n * Removes all listeners from the event, effectively resetting it. This is useful when you need to\n * cleanly dispose of all event handlers to prevent memory leaks or unwanted triggerings after certain conditions.\n *\n * @returns {this} The instance of the event, allowing for method chaining.\n *\n * ```typescript\n * const myEvent = new Event();\n * myEvent.on(data => console.log(data));\n * myEvent.clear(); // Clears all listeners\n * ```\n */\n clear(): this {\n this.listeners.splice(0);\n if (this.spies.length) {\n [...this.spies].forEach((spy) => spy(undefined, SpyType.Remove));\n }\n return this;\n }\n\n /**\n * Enables the `Event` to be used in a Promise chain, resolving with the first emitted value.\n *\n * @template TResult1 - The type of the fulfilled value returned by `onfulfilled` (defaults to the event's type).\n * @template TResult2 - The type of the rejected value returned by `onrejected` (defaults to `never`).\n * @param onfulfilled - A function called when the event emits its first value.\n * @param onrejected - A function called if an error occurs before the event emits.\n * @returns A Promise that resolves with the result of `onfulfilled` or `onrejected`.\n *\n * ```typescript\n * const clickEvent = new Event<[number, number]>();\n * await clickEvent;\n * ```\n */\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n const promise = new Promise<T>((resolve) => this.once(resolve));\n\n return promise.then(onfulfilled, onrejected);\n }\n\n /**\n * A promise that resolves with the first emitted value from this event.\n *\n * @returns {Promise<T>} The promise value.\n */\n get promise(): Promise<T> {\n return this.then((v) => v);\n }\n\n /**\n * Makes this event iterable using `for await...of` loops.\n *\n * @returns An async iterator that yields values as they are emitted by this event.\n *\n * ```typescript\n * // Assuming an event that emits numbers\n * const numberEvent = new Event<number>();\n * (async () => {\n * for await (const num of numberEvent) {\n * console.log('Number:', num);\n * }\n * })();\n * await numberEvent(1);\n * await numberEvent(2);\n * await numberEvent(3);\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n const queue: T[] = [];\n const doneEvent = new Event<boolean>();\n const emitEvent = async (value: T) => {\n queue.push(value);\n await doneEvent(false);\n };\n const unsubscribe = this.on(emitEvent).pre(async () => {\n removeListener(this.spies, spy);\n queue.splice(0);\n await doneEvent.dispose();\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent, action) => {\n if (target === emitEvent && action === SpyType.Remove) {\n void doneEvent(true);\n void unsubscribe();\n }\n };\n\n this.spies.push(spy);\n return {\n async next() {\n if (queue.length) {\n return { value: queue.shift()!, done: false };\n }\n if (!(await doneEvent)) {\n return { value: queue.shift()!, done: false };\n }\n return { value: undefined, done: true };\n },\n async return(value: unknown) {\n await unsubscribe();\n return { done: true, value };\n },\n };\n }\n\n /**\n * Transforms the event's values using a generator function, creating a new `Event` that emits the transformed values.\n *\n * @template PT - The type of values emitted by the transformed `Event`.\n * @template PR - The return type of the listeners of the transformed `Event`.\n * @param generator - A function that takes the original event's value and returns a generator (sync or async) that yields the transformed values.\n * @returns A new `Event` instance that emits the transformed values.\n *\n * ```typescript\n * const numbersEvent = new Event<number>();\n * const evenNumbersEvent = numbersEvent.pipe(function*(value) {\n * if (value % 2 === 0) {\n * yield value;\n * }\n * });\n * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));\n * await numbersEvent(1);\n * await numbersEvent(2);\n * await numbersEvent(3);\n * ```\n */\n pipe<PT, R>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): Event<PT, R> {\n const emitEvent = async (value: T) => {\n try {\n for await (const generatedValue of generator(value)) {\n await result(generatedValue).catch((e) => result.error(e));\n }\n } catch (e) {\n await result.error(e);\n }\n };\n\n const unsubscribe = this.on(emitEvent).pre(() => {\n removeListener(this.spies, spy);\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent, action) => {\n if (target === emitEvent && action === SpyType.Remove) {\n void unsubscribe();\n }\n };\n this.spies.push(spy);\n\n const result = new Event<PT, R>(unsubscribe);\n return result;\n }\n\n /**\n * Creates an async generator that yields values as they are emitted by this event.\n *\n * @template PT - The type of values yielded by the async generator.\n * @param generator - An optional function that takes the original event's value and returns a generator (sync or async)\n * that yields values to include in the async generator.\n * @returns An async generator that yields values from this event as they occur.\n *\n * ```typescript\n * const numbersEvent = new Event<number>();\n * const evenNumbersEvent = numbersEvent.pipe(function*(value) {\n * if (value % 2 === 0) {\n * yield value;\n * }\n * });\n * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));\n * await numbersEvent(1);\n * await numbersEvent(2);\n * await numbersEvent(3);\n * ```\n */\n async *generator<PT>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): AsyncGenerator<Awaited<PT>, void, unknown> {\n for await (const value of this.pipe(generator)) {\n yield value;\n }\n }\n\n /**\n * Filters events, creating a new event that only triggers when the provided filter function returns `true`.\n * This method can be used to selectively process events that meet certain criteria.\n *\n * @param {Filter<T, P>} predicate The filter function or predicate to apply to each event.\n * @returns {Event<P, R>} A new event that only triggers for filtered events.\n *\n * ```typescript\n * const keyPressedEvent = new Event<string>();\n * const enterPressedEvent = keyPressedEvent.filter(key => key === 'Enter');\n * enterPressedEvent.on(() => console.log('Enter key was pressed.'));\n * ```\n */\n filter<P extends T>(predicate: Predicate<T, P>): Event<P, R>;\n filter<P extends T>(filter: FilterFunction<T>): Event<P, R>;\n filter<P extends T>(filter: Filter<T, P>): Event<P, R> {\n return this.pipe<P, R>(async function* (value: T) {\n if (await filter(value)) {\n yield value as P;\n }\n });\n }\n\n /**\n * Creates a new event that will only be triggered once when the provided filter function returns `true`.\n * This method is useful for handling one-time conditions in a stream of events.\n *\n * @param {Filter<T, P>} predicate - The filter function or predicate.\n * @returns {Event<P, R>} A new event that will be triggered only once when the filter condition is met.\n *\n * ```typescript\n * const sizeChangeEvent = new Event<number>();\n * const sizeReachedEvent = sizeChangeEvent.first(size => size > 1024);\n * sizeReachedEvent.on(() => console.log('Size threshold exceeded.'));\n * ```\n */\n first<P extends T>(predicate: Predicate<T, P>): Event<P, R>;\n first<P extends T>(filter: FilterFunction<T>): Event<P, R>;\n first<P extends T>(filter: Filter<T, P>): Event<P, R> {\n const filteredEvent = this.pipe<P, R>(async function* (value: T) {\n if (await filter(value)) {\n yield value as P;\n await filteredEvent.dispose();\n }\n });\n return filteredEvent;\n }\n\n /**\n * Transforms the data emitted by this event using a mapping function. Each emitted event is processed by the `mapper`\n * function, which returns a new value that is then emitted by the returned `Event` instance. This is useful for data transformation\n * or adapting the event's data structure.\n *\n * @template M The type of data that the mapper function will produce.\n * @template MR The type of data emitted by the mapped event, usually related to or the same as `M`.\n * @param {Mapper<T, M>} mapper A function that takes the original event data and returns the transformed data.\n * @returns {Event<M, MR>} A new `Event` instance that emits the mapped values.\n *\n * ```typescript\n * // Assuming an event that emits numbers, create a new event that emits their squares.\n * const numberEvent = new Event<number>();\n * const squaredEvent = numberEvent.map(num => num * num);\n * squaredEvent.on(squared => console.log('Squared number:', squared));\n * await numberEvent(5); // Logs: \"Squared number: 25\"\n * ```\n */\n map<M, MR = R>(mapper: Mapper<T, M>): Event<Awaited<M>, MR> {\n return this.pipe(async function* (value) {\n yield await mapper(value);\n });\n }\n\n /**\n * Accumulates the values emitted by this event using a reducer function, starting from an initial value. The reducer\n * function takes the accumulated value and the latest emitted event data, then returns a new accumulated value. This\n * new value is then emitted by the returned `Event` instance. This is particularly useful for accumulating state over time.\n *\n * @template A The type of the accumulator value.\n * @template AR The type of data emitted by the reduced event, usually the same as `A`.\n * @param {Reducer<T, A>} reducer A function that takes the current accumulated value and the new event data, returning the new accumulated value.\n * @param {A} init The initial value of the accumulator.\n * @returns {Event<A, AR>} A new `Event` instance that emits the reduced value.\n *\n * ```typescript\n * const sumEvent = numberEvent.reduce((a, b) => a + b, 0);\n * sumEvent.on((sum) => console.log(sum)); // 1, 3, 6\n * await sumEvent(1);\n * await sumEvent(2);\n * await sumEvent(3);\n * ```\n */\n reduce<A, AR = R>(reducer: Reducer<T, A>, init?: A): Event<Awaited<A>, AR>;\n reduce<A, AR = R>(reducer: Reducer<T, A>, ...init: unknown[]): Event<Awaited<A>, AR> {\n let hasInit = init.length === 1;\n let result = init[0] as A | undefined;\n\n return this.pipe(async function* (value) {\n if (hasInit) {\n result = await reducer(result!, value);\n yield result;\n } else {\n result = value as unknown as A;\n hasInit = true;\n }\n });\n }\n\n /**\n * Transforms each event's data into multiple events using an expander function. The expander function takes\n * the original event's data and returns an array of new data elements, each of which will be emitted individually\n * by the returned `Event` instance. This method is useful for scenarios where an event's data can naturally\n * be expanded into multiple, separate pieces of data which should each trigger further processing independently.\n *\n * @template ET - The type of data elements in the array returned by the expander function.\n * @template ER - The type of responses emitted by the expanded event, usually related to or the same as `ET`.\n * @param {Expander<T, ET[]>} expander - A function that takes the original event data and returns an array of new data elements.\n * @returns {Event<ET, ER>} - A new `Event` instance that emits each value from the array returned by the expander function.\n *\n * ```typescript\n * // Assuming an event that emits a sentence, create a new event that emits each word from the sentence separately.\n * const sentenceEvent = new Event<string>();\n * const wordEvent = sentenceEvent.expand(sentence => sentence.split(' '));\n * wordEvent.on(word => console.log('Word:', word));\n * await sentenceEvent('Hello world'); // Logs: \"Word: Hello\", \"Word: world\"\n * ```\n */\n expand<ET, ER>(expander: Expander<T, ET[]>): Event<Awaited<ET>, ER> {\n return this.pipe(async function* (value) {\n const values = await expander(value);\n for (const value of values) {\n yield value;\n }\n });\n }\n\n /**\n * Creates a new event that emits values based on a conductor event. The orchestrated event will emit the last value\n * captured from the original event each time the conductor event is triggered. This method is useful for synchronizing\n * events, where the emission of one event controls the timing of another.\n *\n * @template T The type of data emitted by the original event.\n * @template R The type of data emitted by the orchestrated event, usually the same as `T`.\n * @param {Event<unknown, unknown>} conductor An event that signals when the orchestrated event should emit.\n * @returns {Event<T, R>} An orchestrated event that emits values based on the conductor's trigger.\n *\n * ```typescript\n * const rightClickPositionEvent = mouseMoveEvent.orchestrate(mouseRightClickEvent);\n * ```\n *\n * ```typescript\n * // An event that emits whenever a \"tick\" event occurs.\n * const tickEvent = new Event<void>();\n * const dataEvent = new Event<string>();\n * const synchronizedEvent = dataEvent.orchestrate(tickEvent);\n * synchronizedEvent.on(data => console.log('Data on tick:', data));\n * await dataEvent('Hello');\n * await dataEvent('World!');\n * await tickEvent(); // Logs: \"Data on tick: World!\"\n * ```\n */\n orchestrate(conductor: Event<any, any>): Event<T, R> {\n let initialized = false;\n let lastValue: T;\n const unsubscribe = this.on(async (event) => {\n initialized = true;\n lastValue = event;\n });\n const unsubscribeConductor = conductor.on(async () => {\n if (initialized) {\n await orchestratedEvent(lastValue);\n initialized = false;\n }\n });\n\n const orchestratedEvent = new Event<T, R>(unsubscribe.post(unsubscribeConductor));\n return orchestratedEvent;\n }\n /**\n * Creates a debounced event that delays triggering until after a specified interval has elapsed\n * following the last time it was invoked. This method is particularly useful for limiting the rate\n * at which a function is executed. Common use cases include handling rapid user inputs, window resizing,\n * or scroll events.\n *\n * @param {number} interval - The amount of time to wait (in milliseconds) before firing the debounced event.\n * @returns {Event<T, R>} An event of debounced events.\n *\n * ```typescript\n * const debouncedEvent = textInputEvent.debounce(100);\n * debouncedEvent.on((str) => console.log(str)); // only 'text' is emitted\n * await event('t');\n * await event('te');\n * await event('tex');\n * await event('text');\n * ```\n */\n debounce(interval: number): Event<Awaited<T>, unknown> {\n let controller = new AbortController();\n\n return this.pipe(async function* (value) {\n controller.abort();\n controller = new AbortController();\n const complete = await setTimeoutAsync(interval, controller.signal);\n if (complete) {\n yield value;\n }\n });\n }\n\n /**\n * Creates a throttled event that emits values at most once per specified interval.\n *\n * This is useful for controlling the rate of event emissions, especially for high-frequency events.\n * The throttled event will immediately emit the first value, and then only emit subsequent values\n * if the specified interval has passed since the last emission.\n *\n * @param interval - The time interval (in milliseconds) between allowed emissions.\n * @returns A new Event that emits throttled values.\n *\n * ```typescript\n * const scrollEvent = new Event();\n * const throttledScroll = scrollEvent.throttle(100); // Emit at most every 100ms\n * throttledScroll.on(() => console.log(\"Throttled scroll event\"));\n * ```\n */\n throttle(interval: number): Event<Awaited<T>, unknown> {\n let timeout = 0;\n let pendingValue: T;\n let hasPendingValue = false;\n\n return this.pipe(async function* (value) {\n const now = Date.now();\n if (timeout <= now) {\n timeout = now + interval;\n yield value;\n } else {\n pendingValue = value;\n if (!hasPendingValue) {\n hasPendingValue = true;\n await setTimeoutAsync(timeout - now);\n timeout = now + interval;\n hasPendingValue = false;\n yield pendingValue;\n }\n }\n });\n }\n\n /**\n * Aggregates multiple event emissions into batches and emits the batched events either at specified\n * time intervals or when the batch reaches a predefined size. This method is useful for grouping\n * a high volume of events into manageable chunks, such as logging or processing data in bulk.\n *\n * @param {number} interval - The time in milliseconds between batch emissions.\n * @param {number} [size] - Optional. The maximum size of each batch. If specified, triggers a batch emission\n * once the batch reaches this size, regardless of the interval.\n * @returns {Event<T[], R>} An event of the batched results.\n *\n * ```typescript\n * // Batch messages for bulk processing every 1 second or when 10 messages are collected\n * const messageEvent = createEvent<string, void>();\n * const batchedMessageEvent = messageEvent.batch(1000, 10);\n * batchedMessageEvent.on((messages) => console.log('Batched Messages:', messages));\n * ```\n */\n batch(interval: number, size?: number): Event<T[], R> {\n let controller = new AbortController();\n const batch: T[] = [];\n\n return this.pipe(async function* (value) {\n batch.push(value);\n if (size !== undefined && batch.length >= size) {\n controller.abort();\n yield batch.splice(0);\n }\n if (batch.length === 1) {\n controller = new AbortController();\n const complete = await setTimeoutAsync(interval, controller.signal);\n if (complete) {\n yield batch.splice(0);\n }\n }\n });\n }\n\n /**\n * Creates a queue from the event, where each emitted value is sequentially processed. The returned object allows popping elements\n * from the queue, ensuring that elements are handled one at a time. This method is ideal for scenarios where order and sequential processing are critical.\n *\n * @returns {Queue<T>} An object representing the queue. The 'pop' method retrieves the next element from the queue, while 'stop' halts further processing.\n *\n * ```typescript\n * // Queueing tasks for sequential execution\n * const taskEvent = new Event<string>();\n * const taskQueue = taskEvent.queue();\n * (async () => {\n * console.log('Processing:', await taskQueue.pop()); // Processing: Task 1\n * // Queue also can be used as a Promise\n * console.log('Processing:', await taskQueue); // Processing: Task 2\n * })();\n * await taskEvent('Task 1');\n * await taskEvent('Task 2');\n *```\n *\n *```typescript\n * // Additionally, the queue can be used as an async iterator\n * const taskEvent = new Event<string>();\n * const taskQueue = taskEvent.queue();\n * (async () => {\n * for await (const task of taskQueue) {\n * console.log('Processing:', task);\n * }\n * })();\n * await taskEvent('Task 1');\n * await taskEvent('Task 2');\n * ```\n *\n */\n queue(): Queue<T> {\n const queue: T[] = [];\n let done = false;\n const valueEvent = new Event<void>();\n\n const unsubscribe = this.on(async (value) => {\n queue.push(value);\n await valueEvent();\n });\n\n const pop = async () => {\n if (!queue.length) {\n await valueEvent;\n }\n return queue.shift()!;\n };\n const stop = async () => {\n await unsubscribe();\n done = true;\n await valueEvent();\n };\n\n return {\n pop,\n stop,\n get stopped() {\n return done;\n },\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n return this.pop().then(onfulfilled, onrejected);\n },\n [Symbol.asyncIterator]() {\n return {\n next: async () => {\n return { value: await pop(), done };\n },\n };\n },\n };\n }\n}\n\nexport interface Queue<T> extends AsyncIterable<T>, PromiseLike<T> {\n pop(): Promise<T>;\n stop(): Promise<void>;\n stopped: boolean;\n}\n\nexport type EventParameters<T> = T extends Event<infer P, any> ? P : never;\n\nexport type EventResult<T> = T extends Event<any, infer R> ? R : never;\n\nexport type AllEventsParameters<T extends Event<any, any>[]> = { [K in keyof T]: EventParameters<T[K]> }[number];\n\nexport type AllEventsResults<T extends Event<any, any>[]> = { [K in keyof T]: EventResult<T[K]> }[number];\n\n/**\n * Merges multiple events into a single event. This function takes any number of `Event` instances\n * and returns a new `Event` that triggers whenever any of the input events trigger. The parameters\n * and results of the merged event are derived from the input events, providing a flexible way to\n * handle multiple sources of events in a unified manner.\n *\n * @template Events - An array of `Event` instances.\n * @param {...Events} events - A rest parameter that takes multiple events to be merged.\n * @returns {Event<AllEventsParameters<Events>, AllEventsResults<Events>>} - Returns a new `Event` instance\n * that triggers with the parameters and results of any of the merged input events.\n *\n * ```typescript\n * // Merging mouse and keyboard events into a single event\n * const mouseEvent = createEvent<MouseEvent>();\n * const keyboardEvent = createEvent<KeyboardEvent>();\n * const inputEvent = merge(mouseEvent, keyboardEvent);\n * inputEvent.on(event => console.log('Input event:', event));\n * ```\n */\nexport const merge = <Events extends Event<any, any>[]>(...events: Events): Event<AllEventsParameters<Events>, AllEventsResults<Events>> => {\n const mergedEvent = new Event<AllEventsParameters<Events>, AllEventsResults<Events>>();\n events.forEach((event) => event.on(mergedEvent));\n return mergedEvent;\n};\n\n/**\n * Creates a periodic event that triggers at a specified interval. The event will automatically emit\n * an incrementing counter value each time it triggers, starting from zero. This function is useful\n * for creating time-based triggers within an application, such as updating UI elements, polling,\n * or any other timed operation.\n *\n * @template R - The return type of the event handler function, defaulting to `void`.\n * @param {number} interval - The interval in milliseconds at which the event should trigger.\n * @returns {Event<number, R>} - An `Event` instance that triggers at the specified interval,\n * emitting an incrementing counter value.\n *\n * ```typescript\n * // Creating an interval event that logs a message every second\n * const tickEvent = createInterval(1000);\n * tickEvent.on(tickNumber => console.log('Tick:', tickNumber));\n * ```\n */\nexport const createInterval = <R = unknown>(interval: number): Event<number, R> => {\n let counter = 0;\n const intervalEvent = new Event<number, R>(() => clearInterval(timerId));\n const timerId: ReturnType<typeof setInterval> = setInterval(() => intervalEvent(counter++), interval);\n return intervalEvent;\n};\n\n/**\n * Creates a new instance of the `Event` class, which allows for the registration of event handlers that get called when the event is emitted.\n * This factory function simplifies the creation of events by encapsulating the instantiation logic, providing a clean and simple API for event creation.\n *\n * @typeParam T - The tuple of argument types that the event will accept.\n * @typeParam R - The return type of the event handler function, which is emitted after processing the event data.\n * @returns {Event<T, R>} - A new instance of the `Event` class, ready to have listeners added to it.\n *\n * ```typescript\n * // Create a new event that accepts a string and returns the string length\n * const myEvent = createEvent<string, number>();\n * myEvent.on((str: string) => str.length);\n * myEvent('hello').then(results => console.log(results)); // Logs: [5]\n * ```\n */\nexport const createEvent = <T = unknown, R = unknown>(): Event<T, R> => new Event<T, R>();\n\nexport default createEvent;\n\n/**\n * A type helper that extracts the event listener type\n *\n * @typeParam E - The event type.\n */\nexport type EventHandler<E> = E extends Event<infer T, infer R> ? Listener<T, R> : never;\n\n/**\n * A type helper that extracts the event filter type\n *\n * @typeParam E The event type to filter.\n */\nexport type EventFilter<E> = FilterFunction<EventParameters<E>>;\n\n/**\n * A type helper that extracts the event predicate type\n *\n * @typeParam E The event type to predicate.\n */\nexport type EventPredicate<E, P extends EventParameters<E>> = Predicate<EventParameters<E>, P>;\n\n/**\n * A type helper that extracts the event mapper type\n *\n * @typeParam E The event type to map.\n * @typeParam M The new type to map `E` to.\n */\nexport type EventMapper<E, M> = Mapper<EventParameters<E>, M>;\n\n/**\n * A type helper that extracts the event mapper type\n *\n * @typeParam E The type of event to reduce.\n * @typeParam M The type of reduced event.\n */\nexport type EventReducer<E, R> = Reducer<EventParameters<E>, R>;\n"],"names":["removeListener","listeners","listener","index","indexOf","wasRemoved","splice","setTimeoutAsync","timeout","signal","Promise","resolve","timerId","setTimeout","addEventListener","clearTimeout","Callable","Function","constructor","func","Object","setPrototypeOf","prototype","Unsubscribe","_done","callback","done","pre","post","countdown","count","SpyType","Event","spies","_disposed","dispose","value","all","map","clear","_error","error","size","length","disposed","lacks","has","off","forEach","spy","on","push","once","oneTimeListener","event","undefined","then","onfulfilled","onrejected","promise","v","Symbol","asyncIterator","queue","doneEvent","emitEvent","unsubscribe","target","action","next","shift","return","pipe","generator","generatedValue","result","catch","e","filter","first","filteredEvent","mapper","reduce","reducer","init","hasInit","expand","expander","values","orchestrate","conductor","initialized","lastValue","unsubscribeConductor","orchestratedEvent","debounce","interval","controller","AbortController","abort","complete","throttle","pendingValue","hasPendingValue","now","Date","batch","valueEvent","pop","stop","stopped","merge","events","mergedEvent","createInterval","counter","intervalEvent","clearInterval","setInterval","createEvent"],"mappings":"AAmDA,OAAO,MAAMA,iBAAiB,CAACC,WAAsBC;IACnD,IAAIC,QAAQF,UAAUG,OAAO,CAACF;IAC9B,MAAMG,aAAaF,UAAU,CAAC;IAC9B,MAAO,CAACA,MAAO;QACbF,UAAUK,MAAM,CAACH,OAAO;QACxBA,QAAQF,UAAUG,OAAO,CAACF;IAC5B;IACA,OAAOG;AACT,EAAE;AAQF,OAAO,MAAME,kBAAkB,CAACC,SAAiBC,SAC/C,IAAIC,Q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AEvF,OAAO,IAAI,CAACkD,GAAG,GAAGpD,IAAI,CAACC,aAAaC;YACtC;YACA,CAACG,OAAOC,aAAa,CAAC;gBACpB,OAAO;oBACLO,MAAM;wBACJ,OAAO;4BAAEjC,OAAO,MAAMwE;4BAAOlF;wBAAK;oBACpC;gBACF;YACF;QACF;IACF;AACF;AAmCA,OAAO,MAAMqF,QAAQ,CAAmC,GAAGC;IACzD,MAAMC,cAAc,IAAIjF;IACxBgF,OAAOhE,OAAO,CAAC,CAACM,QAAUA,MAAMJ,EAAE,CAAC+D;IACnC,OAAOA;AACT,EAAE;AAmBF,OAAO,MAAMC,iBAAiB,CAAclB;IAC1C,IAAImB,UAAU;IACd,MAAMC,gBAAgB,IAAIpF,MAAiB,IAAMqF,cAAczG;IAC/D,MAAMA,UAA0C0G,YAAY,IAAMF,cAAcD,YAAYnB;IAC5F,OAAOoB;AACT,EAAE;AAiBF,OAAO,MAAMG,cAAc,IAA6C,IAAIvF,QAAc;AAE1F,eAAeuF,YAAY"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "evnty",
3
3
  "description": "0-Deps, simple, fast, for browser and node js reactive anonymous event library",
4
- "version": "4.1.0",
4
+ "version": "4.2.0",
5
5
  "type": "module",
6
6
  "types": "build/index.d.ts",
7
7
  "main": "build/index.cjs",
package/src/index.ts CHANGED
@@ -49,7 +49,7 @@ export interface Expander<T, R> {
49
49
  * console.log(wasRemoved); // Output: true
50
50
  * ```
51
51
  */
52
- export const removeListener = <T, R>(listeners: Listener<T, R>[], listener: Listener<T, R>): boolean => {
52
+ export const removeListener = (listeners: unknown[], listener: unknown): boolean => {
53
53
  let index = listeners.indexOf(listener);
54
54
  const wasRemoved = index !== -1;
55
55
  while (~index) {
@@ -96,8 +96,17 @@ export interface Unsubscribe {
96
96
  * @internal
97
97
  */
98
98
  export class Unsubscribe extends Callable {
99
+ private _done = false;
100
+
99
101
  constructor(callback: Callback) {
100
- super(callback);
102
+ super(() => {
103
+ this._done = true;
104
+ callback();
105
+ });
106
+ }
107
+
108
+ get done() {
109
+ return this._done;
101
110
  }
102
111
 
103
112
  pre(callback: Callback): Unsubscribe {
@@ -123,16 +132,15 @@ export class Unsubscribe extends Callable {
123
132
  }
124
133
  }
125
134
 
126
- export interface Queue<T> extends AsyncIterable<T> {
127
- pop(): MaybePromise<T>;
128
- stop(): MaybePromise<void>;
129
- stopped: boolean;
130
- }
131
-
132
135
  export interface Event<T = any, R = any> {
133
136
  (event: T): Promise<(void | Awaited<R>)[]>;
134
137
  }
135
138
 
139
+ enum SpyType {
140
+ Add,
141
+ Remove,
142
+ }
143
+
136
144
  /**
137
145
  * A class representing an anonymous event that can be listened to or triggered.
138
146
  *
@@ -145,7 +153,9 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
145
153
  */
146
154
  private listeners: Listener<T, R>[];
147
155
 
148
- private spies: Array<(listener: Listener<T, R> | void) => void> = [];
156
+ private spies: Array<(listener: Listener<T, R> | void, type: SpyType) => void> = [];
157
+
158
+ private _disposed = false;
149
159
 
150
160
  /**
151
161
  * A function that disposes of the event and its listeners.
@@ -170,6 +180,7 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
170
180
  this.listeners = listeners;
171
181
 
172
182
  this.dispose = async () => {
183
+ this._disposed = true;
173
184
  void this.clear();
174
185
  await this._error?.dispose();
175
186
  await dispose?.();
@@ -197,6 +208,14 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
197
208
  return this.listeners.length;
198
209
  }
199
210
 
211
+ /**
212
+ * Checks if the event has been disposed.
213
+ * @returns {boolean} `true` if the event has been disposed; otherwise, `false`.
214
+ */
215
+ get disposed(): boolean {
216
+ return this._disposed;
217
+ }
218
+
200
219
  /**
201
220
  * Checks if the given listener is NOT registered for this event.
202
221
  *
@@ -244,7 +263,7 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
244
263
  */
245
264
  off(listener: Listener<T, R>): this {
246
265
  if (removeListener(this.listeners, listener) && this.spies.length) {
247
- [...this.spies].forEach((spy) => spy(listener));
266
+ [...this.spies].forEach((spy) => spy(listener, SpyType.Remove));
248
267
  }
249
268
  return this;
250
269
  }
@@ -265,6 +284,9 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
265
284
  */
266
285
  on(listener: Listener<T, R>): Unsubscribe {
267
286
  this.listeners.push(listener);
287
+ if (this.spies.length) {
288
+ [...this.spies].forEach((spy) => spy(listener, SpyType.Add));
289
+ }
268
290
  return new Unsubscribe(() => {
269
291
  void this.off(listener);
270
292
  });
@@ -307,7 +329,7 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
307
329
  clear(): this {
308
330
  this.listeners.splice(0);
309
331
  if (this.spies.length) {
310
- [...this.spies].forEach((spy) => spy());
332
+ [...this.spies].forEach((spy) => spy(undefined, SpyType.Remove));
311
333
  }
312
334
  return this;
313
335
  }
@@ -375,8 +397,8 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
375
397
  await doneEvent.dispose();
376
398
  });
377
399
 
378
- const spy: (typeof this.spies)[number] = (target = emitEvent) => {
379
- if (target === emitEvent) {
400
+ const spy: (typeof this.spies)[number] = (target = emitEvent, action) => {
401
+ if (target === emitEvent && action === SpyType.Remove) {
380
402
  void doneEvent(true);
381
403
  void unsubscribe();
382
404
  }
@@ -436,8 +458,8 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
436
458
  removeListener(this.spies, spy);
437
459
  });
438
460
 
439
- const spy: (typeof this.spies)[number] = (target = emitEvent) => {
440
- if (target === emitEvent) {
461
+ const spy: (typeof this.spies)[number] = (target = emitEvent, action) => {
462
+ if (target === emitEvent && action === SpyType.Remove) {
441
463
  void unsubscribe();
442
464
  }
443
465
  };
@@ -770,16 +792,32 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
770
792
  * const taskQueue = taskEvent.queue();
771
793
  * (async () => {
772
794
  * console.log('Processing:', await taskQueue.pop()); // Processing: Task 1
773
- * console.log('Processing:', await taskQueue.pop()); // Processing: Task 2
795
+ * // Queue also can be used as a Promise
796
+ * console.log('Processing:', await taskQueue); // Processing: Task 2
797
+ * })();
798
+ * await taskEvent('Task 1');
799
+ * await taskEvent('Task 2');
800
+ *```
801
+ *
802
+ *```typescript
803
+ * // Additionally, the queue can be used as an async iterator
804
+ * const taskEvent = new Event<string>();
805
+ * const taskQueue = taskEvent.queue();
806
+ * (async () => {
807
+ * for await (const task of taskQueue) {
808
+ * console.log('Processing:', task);
809
+ * }
774
810
  * })();
775
811
  * await taskEvent('Task 1');
776
812
  * await taskEvent('Task 2');
777
813
  * ```
814
+ *
778
815
  */
779
816
  queue(): Queue<T> {
780
817
  const queue: T[] = [];
781
818
  let done = false;
782
819
  const valueEvent = new Event<void>();
820
+
783
821
  const unsubscribe = this.on(async (value) => {
784
822
  queue.push(value);
785
823
  await valueEvent();
@@ -803,6 +841,12 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
803
841
  get stopped() {
804
842
  return done;
805
843
  },
844
+ then<TResult1 = T, TResult2 = never>(
845
+ onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined,
846
+ onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,
847
+ ): Promise<TResult1 | TResult2> {
848
+ return this.pop().then(onfulfilled, onrejected);
849
+ },
806
850
  [Symbol.asyncIterator]() {
807
851
  return {
808
852
  next: async () => {
@@ -814,6 +858,12 @@ export class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLi
814
858
  }
815
859
  }
816
860
 
861
+ export interface Queue<T> extends AsyncIterable<T>, PromiseLike<T> {
862
+ pop(): Promise<T>;
863
+ stop(): Promise<void>;
864
+ stopped: boolean;
865
+ }
866
+
817
867
  export type EventParameters<T> = T extends Event<infer P, any> ? P : never;
818
868
 
819
869
  export type EventResult<T> = T extends Event<any, infer R> ? R : never;