evnty 4.0.0-rc-1 → 4.0.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
@@ -47,10 +47,10 @@ const removeListener = (listeners, listener)=>{
47
47
  return wasRemoved;
48
48
  };
49
49
  const setTimeoutAsync = (timeout, signal)=>new Promise((resolve)=>{
50
- const timerId = setTimeout(resolve, timeout);
50
+ const timerId = setTimeout(resolve, timeout, true);
51
51
  signal?.addEventListener('abort', ()=>{
52
52
  clearTimeout(timerId);
53
- resolve();
53
+ resolve(false);
54
54
  });
55
55
  });
56
56
  class Callable extends Function {
@@ -92,7 +92,7 @@ class Event extends Callable {
92
92
  super(async (value)=>Promise.all(listeners.map(async (listener)=>listener(await value))));
93
93
  this.listeners = listeners;
94
94
  this.dispose = async ()=>{
95
- this.clear();
95
+ void this.clear();
96
96
  await this._error?.dispose();
97
97
  await dispose?.();
98
98
  };
@@ -121,12 +121,12 @@ class Event extends Callable {
121
121
  on(listener) {
122
122
  this.listeners.push(listener);
123
123
  return new Unsubscribe(()=>{
124
- this.off(listener);
124
+ void this.off(listener);
125
125
  });
126
126
  }
127
127
  once(listener) {
128
128
  const oneTimeListener = (event)=>{
129
- this.off(oneTimeListener);
129
+ void this.off(oneTimeListener);
130
130
  return listener(event);
131
131
  };
132
132
  return this.on(oneTimeListener);
@@ -141,7 +141,7 @@ class Event extends Callable {
141
141
  return this;
142
142
  }
143
143
  then(onfulfilled, onrejected) {
144
- const promise = new Promise((resolve)=>this.once((event)=>resolve(event)));
144
+ const promise = new Promise((resolve)=>this.once(resolve));
145
145
  return promise.then(onfulfilled, onrejected);
146
146
  }
147
147
  get promise() {
@@ -154,15 +154,15 @@ class Event extends Callable {
154
154
  queue.push(value);
155
155
  await doneEvent(false);
156
156
  };
157
- const unsubscribe = this.on(emitEvent).pre(()=>{
157
+ const unsubscribe = this.on(emitEvent).pre(async ()=>{
158
158
  removeListener(this.spies, spy);
159
159
  queue.splice(0);
160
- doneEvent.dispose();
160
+ await doneEvent.dispose();
161
161
  });
162
162
  const spy = (target = emitEvent)=>{
163
163
  if (target === emitEvent) {
164
- doneEvent(true);
165
- unsubscribe();
164
+ void doneEvent(true);
165
+ void unsubscribe();
166
166
  }
167
167
  };
168
168
  this.spies.push(spy);
@@ -186,7 +186,7 @@ class Event extends Callable {
186
186
  };
187
187
  },
188
188
  async return (value) {
189
- unsubscribe();
189
+ await unsubscribe();
190
190
  return {
191
191
  done: true,
192
192
  value
@@ -209,7 +209,7 @@ class Event extends Callable {
209
209
  });
210
210
  const spy = (target = emitEvent)=>{
211
211
  if (target === emitEvent) {
212
- unsubscribe();
212
+ void unsubscribe();
213
213
  }
214
214
  };
215
215
  this.spies.push(spy);
@@ -242,11 +242,17 @@ class Event extends Callable {
242
242
  yield await mapper(value);
243
243
  });
244
244
  }
245
- reduce(reducer, init) {
246
- let result = init;
245
+ reduce(reducer, ...init) {
246
+ let hasInit = init.length === 1;
247
+ let result = init[0];
247
248
  return this.pipe(async function*(value) {
248
- result = await reducer(result, value);
249
- yield result;
249
+ if (hasInit) {
250
+ result = await reducer(result, value);
251
+ yield result;
252
+ } else {
253
+ result = value;
254
+ hasInit = true;
255
+ }
250
256
  });
251
257
  }
252
258
  expand(expander) {
@@ -260,71 +266,64 @@ class Event extends Callable {
260
266
  orchestrate(conductor) {
261
267
  let initialized = false;
262
268
  let lastValue;
263
- const emitEvent = async (value)=>{
269
+ const unsubscribe = this.on(async (event)=>{
264
270
  initialized = true;
265
- lastValue = value;
266
- };
267
- const unsubscribe = this.on(emitEvent).pre(()=>{
268
- removeListener(this.spies, spy);
271
+ lastValue = event;
269
272
  });
270
- const spy = (target = emitEvent)=>{
271
- if (target === emitEvent) {
272
- unsubscribe();
273
- }
274
- };
275
- conductor.spies.push(spy);
276
- return conductor.pipe(async function*() {
273
+ const unsubscribeConductor = conductor.on(async ()=>{
277
274
  if (initialized) {
275
+ await orchestratedEvent(lastValue);
278
276
  initialized = false;
279
- yield lastValue;
280
277
  }
281
278
  });
279
+ const orchestratedEvent = new Event(unsubscribe.post(unsubscribeConductor));
280
+ return orchestratedEvent;
282
281
  }
283
282
  debounce(interval) {
284
- let timer;
285
- const unsubscribe = this.on((event)=>{
286
- clearTimeout(timer);
287
- timer = setTimeout(()=>{
288
- result(event).catch(result.error);
289
- }, interval);
283
+ let controller = new AbortController();
284
+ return this.pipe(async function*(value) {
285
+ controller.abort();
286
+ controller = new AbortController();
287
+ const complete = await setTimeoutAsync(interval, controller.signal);
288
+ if (complete) {
289
+ yield value;
290
+ }
290
291
  });
291
- const result = new Event(unsubscribe);
292
- return result;
293
292
  }
294
- throttle(duration) {
293
+ throttle(interval) {
295
294
  let timeout = 0;
296
295
  let pendingValue;
297
296
  let hasPendingValue = false;
298
297
  return this.pipe(async function*(value) {
299
298
  const now = Date.now();
300
299
  if (timeout <= now) {
301
- timeout = now + duration;
300
+ timeout = now + interval;
302
301
  yield value;
303
302
  } else {
304
303
  pendingValue = value;
305
304
  if (!hasPendingValue) {
306
305
  hasPendingValue = true;
307
306
  await setTimeoutAsync(timeout - now);
308
- yield pendingValue;
309
- timeout = now + duration;
307
+ timeout = now + interval;
310
308
  hasPendingValue = false;
309
+ yield pendingValue;
311
310
  }
312
311
  }
313
312
  });
314
313
  }
315
314
  batch(interval, size) {
316
- let abort = new AbortController();
315
+ let controller = new AbortController();
317
316
  const batch = [];
318
317
  return this.pipe(async function*(value) {
319
318
  batch.push(value);
320
319
  if (size !== undefined && batch.length >= size) {
321
- abort.abort();
320
+ controller.abort();
322
321
  yield batch.splice(0);
323
322
  }
324
323
  if (batch.length === 1) {
325
- abort = new AbortController();
326
- await setTimeoutAsync(interval, abort.signal);
327
- if (!abort.signal.aborted) {
324
+ controller = new AbortController();
325
+ const complete = await setTimeoutAsync(interval, controller.signal);
326
+ if (complete) {
328
327
  yield batch.splice(0);
329
328
  }
330
329
  }
@@ -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 * @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\nexport const setTimeoutAsync = (timeout: number, signal?: AbortSignal) => new Promise<void>(resolve => {\n const timerId = setTimeout(resolve, timeout);\n signal?.addEventListener('abort', () => {\n clearTimeout(timerId);\n resolve();\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 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> {\n pop(): MaybePromise<T>;\n stop(): MaybePromise<void>;\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 * ```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 * @param dispose - A function to call on the event disposal.\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.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 * ```typescript\n * // Check if a listener is not already added\n * if (event.lacks(myListener)) {\n * event.on(myListener);\n * }\n * ```\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 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 * ```typescript\n * // Verify if a listener is registered\n * if (event.has(myListener)) {\n * console.log('Listener is already registered');\n * }\n * ```\n *\n * @param listener - The listener function to check.\n * @returns `true` if the listener is currently registered; otherwise, `false`.\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 * ```typescript\n * // Remove a listener\n * event.off(myListener);\n * ```\n *\n * @param listener - The listener to remove.\n * @returns The event instance, allowing for method chaining.\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 * ```typescript\n * // Add a listener to an event\n * const unsubscribe = event.on((data) => {\n * console.log('Event data:', data);\n * });\n * ```\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 on(listener: Listener<T, R>): Unsubscribe {\n this.listeners.push(listener);\n return new Unsubscribe(() => {\n 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 * ```typescript\n * // Register a one-time listener\n * const onceUnsubscribe = event.once((data) => {\n * console.log('Received data once:', data);\n * });\n * ```\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 once(listener: Listener<T, R>): Unsubscribe {\n const oneTimeListener = (event: T) => {\n 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 * ```typescript\n * const myEvent = new Event();\n * myEvent.on(data => console.log(data));\n * myEvent.clear(); // Clears all listeners\n * ```\n *\n * @returns {this} The instance of the event, allowing for method chaining.\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 * ```typescript\n * const clickEvent = new Event<[number, number]>();\n * await clickEvent;\n * ```\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\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((event) => resolve(event)));\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 * ```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 * @returns An async iterator that yields values as they are emitted by this event.\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(() => {\n removeListener(this.spies, spy);\n queue.splice(0);\n doneEvent.dispose();\n });\n\n const spy: (typeof this.spies)[number] = (target = emitEvent) => {\n if (target === emitEvent) {\n doneEvent(true);\n 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 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 * ```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 * @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 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 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 * ```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 * @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 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 * ```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 * @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 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 * ```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 * @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 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 * ```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 * @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 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 * ```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 * @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 */\n reduce<A, AR = R>(reducer: Reducer<T, A>, init: A): Event<Awaited<A>, AR> {\n let result = init;\n return this.pipe(async function* (value) {\n result = await reducer(result, value);\n yield result;\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 * ```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 * @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 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 * ```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 * @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 orchestrate(conductor: Event<any, any>): Event<Awaited<T>, unknown> {\n let initialized = false;\n let lastValue: T;\n\n const emitEvent = async (value: T) => {\n initialized = true;\n lastValue = value;\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 unsubscribe();\n }\n };\n conductor.spies.push(spy);\n\n return conductor.pipe(async function* () {\n if (initialized) {\n initialized = false;\n yield lastValue\n }\n });\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 * ```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 * @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 debounce(interval: number): Event<T, R> {\n let timer: ReturnType<typeof setTimeout>;\n\n const unsubscribe = this.on((event) => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n result(event).catch(result.error);\n }, interval);\n });\n const result = new Event<T, R>(unsubscribe);\n return result;\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 * ```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 * @param interval - The time interval (in milliseconds) between allowed emissions.\n * @returns A new Event that emits throttled values.\n */\n throttle(duration: 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 + duration;\n yield value;\n } else {\n pendingValue = value;\n if (!hasPendingValue) {\n hasPendingValue = true;\n await setTimeoutAsync(timeout - now);\n yield pendingValue;\n timeout = now + duration;\n hasPendingValue = false;\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 * ```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 * @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 batch(interval: number, size?: number): Event<T[], R> {\n let abort = new AbortController();\n const batch: T[] = [];\n\n return this\n .pipe(async function* (value) {\n batch.push(value);\n if (size !== undefined && batch.length >= size) {\n abort.abort();\n yield batch.splice(0);\n }\n if (batch.length === 1) {\n abort = new AbortController();\n await setTimeoutAsync(interval, abort.signal);\n if (!abort.signal.aborted) {\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 * ```typescript\n * // Queueing tasks for sequential execution\n * const taskEvent = new Event<string>();\n * const taskQueue = taskEvent.queue();\n * await taskEvent('Task 1');\n * await taskEvent('Task 2');\n * (async () => {\n * console.log('Processing:', await taskQueue.pop()); // Processing: Task 1\n * console.log('Processing:', await taskQueue.pop()); // Processing: Task 2\n * })();\n * ```\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 queue(): Queue<T> {\n const queue: T[] = [];\n const valueEvent = new Event<void>();\n const unsubscribe = this.on(async (value) => {\n queue.push(value);\n await valueEvent();\n });\n\n return {\n async pop() {\n if (!queue.length) {\n await valueEvent;\n }\n return queue.shift()!;\n },\n async stop() {\n await unsubscribe();\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 * ```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 *\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 */\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 * ```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 *\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 */\nexport const createInterval = <R = void>(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 * ```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 *\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 */\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","expand","expander","values","orchestrate","conductor","initialized","lastValue","debounce","interval","timer","throttle","duration","pendingValue","hasPendingValue","now","Date","batch","abort","AbortController","aborted","valueEvent","pop","stop","events","mergedEvent","counter","intervalEvent","clearInterval","setInterval"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;;;;IA0EsBA,QAAQ;eAARA;;IAyDTC,KAAK;eAALA;;IA3CAC,WAAW;eAAXA;;IA4wBAC,WAAW;eAAXA;;IAtBAC,cAAc;eAAdA;;IAwBb,OAA2B;eAA3B;;IA/CaC,KAAK;eAALA;;IArwB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6F,YAAY,IAAMF,cAAcD,YAAYjB;IAC5F,OAAOkB;AACT;AAiBO,MAAM1G,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 = <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 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> {\n pop(): MaybePromise<T>;\n stop(): MaybePromise<void>;\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 const valueEvent = new Event<void>();\n const unsubscribe = this.on(async (value) => {\n queue.push(value);\n await valueEvent();\n });\n\n return {\n async pop() {\n if (!queue.length) {\n await valueEvent;\n }\n return queue.shift()!;\n },\n async stop() {\n await unsubscribe();\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 = void>(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","events","mergedEvent","counter","intervalEvent","clearInterval","setInterval"],"mappings":";;;;;;;;;;;IAkFsBA,QAAQ;eAARA;;IAyDTC,KAAK;eAALA;;IA3CAC,WAAW;eAAXA;;IAswBAC,WAAW;eAAXA;;IAtBAC,cAAc;eAAdA;;IAwBb,OAA2B;eAA3B;;IA/CaC,KAAK;eAALA;;IAtwBAC,cAAc;eAAdA;;IAgBAC,eAAe;eAAfA;;;AAhBN,MAAMD,iBAAiB,CAAOE,WAA6BC;IAChE,IAAIC,QAAQF,UAAUG,OAAO,CAACF;IAC9B,MAAMG,aAAaF,UAAU,CAAC;IAC9B,MAAO,CAACA,M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