emittery 0.7.0 → 0.8.1

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.
Files changed (4) hide show
  1. package/index.d.ts +101 -83
  2. package/index.js +2 -9
  3. package/package.json +3 -4
  4. package/readme.md +27 -12
package/index.d.ts CHANGED
@@ -5,29 +5,51 @@ Symbol event names can be used to avoid name collisions when your classes are ex
5
5
  */
6
6
  type EventName = string | symbol;
7
7
 
8
+ // Helper type for turning the passed `EventData` type map into a list of string keys that don't require data alongside the event name when emitting. Uses the same trick that `Omit` does internally to filter keys by building a map of keys to keys we want to keep, and then accessing all the keys to return just the list of keys we want to keep.
9
+ type DatalessEventNames<EventData> = {
10
+ [Key in keyof EventData]: EventData[Key] extends undefined ? Key : never;
11
+ }[keyof EventData];
12
+
13
+ declare const listenerAdded: unique symbol;
14
+ declare const listenerRemoved: unique symbol;
15
+ type OmnipresentEventData = {[listenerAdded]: Emittery.ListenerChangedData; [listenerRemoved]: Emittery.ListenerChangedData};
16
+
8
17
  /**
9
- Emittery also accepts an array of strings and symbols as event names.
10
- */
11
- type EventNames = EventName | readonly EventName[];
18
+ Emittery is a strictly typed, fully async EventEmitter implementation. Event listeners can be registered with `on` or `once`, and events can be emitted with `emit`.
12
19
 
13
- declare class Emittery {
14
- /**
15
- In TypeScript, it returns a decorator which mixins `Emittery` as property `emitteryPropertyName` and `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the target class.
20
+ `Emittery` has a generic `EventData` type that can be provided by users to strongly type the list of events and the data passed to the listeners for those events. Pass an interface of {[eventName]: undefined | <eventArg>}, with all the event names as the keys and the values as the type of the argument passed to listeners if there is one, or `undefined` if there isn't.
16
21
 
17
- @example
18
- ```
19
- import Emittery = require('emittery');
22
+ @example
23
+ ```
24
+ import Emittery = require('emittery');
20
25
 
21
- @Emittery.mixin('emittery')
22
- class MyClass {}
26
+ const emitter = new Emittery<
27
+ // Pass `{[eventName: <string | symbol>]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
28
+ // A value of `undefined` in this map means the event listeners should expect no data, and a type other than `undefined` means the listeners will receive one argument of that type.
29
+ {
30
+ open: string,
31
+ close: undefined
32
+ }
33
+ >();
23
34
 
24
- const instance = new MyClass();
35
+ // Typechecks just fine because the data type for the `open` event is `string`.
36
+ emitter.emit('open', 'foo\n');
25
37
 
26
- instance.emit('event');
27
- ```
28
- */
29
- static mixin(emitteryPropertyName: string, methodNames?: readonly string[]): Function;
38
+ // Typechecks just fine because `close` is present but points to undefined in the event data type map.
39
+ emitter.emit('close');
40
+
41
+ // TS compilation error because `1` isn't assignable to `string`.
42
+ emitter.emit('open', 1);
30
43
 
44
+ // TS compilation error because `other` isn't defined in the event data type map.
45
+ emitter.emit('other');
46
+ ```
47
+ */
48
+ declare class Emittery<
49
+ EventData = Record<string, any>, // When https://github.com/microsoft/TypeScript/issues/1863 ships, we can switch this to have an index signature including Symbols. If you want to use symbol keys right now, you need to pass an interface with those symbol keys explicitly listed.
50
+ AllEventData = EventData & OmnipresentEventData,
51
+ DatalessEvents = DatalessEventNames<EventData>
52
+ > {
31
53
  /**
32
54
  Fires when an event listener was added.
33
55
 
@@ -52,7 +74,7 @@ declare class Emittery {
52
74
  });
53
75
  ```
54
76
  */
55
- static readonly listenerAdded: unique symbol;
77
+ static readonly listenerAdded: typeof listenerAdded;
56
78
 
57
79
  /**
58
80
  Fires when an event listener was removed.
@@ -80,7 +102,27 @@ declare class Emittery {
80
102
  off();
81
103
  ```
82
104
  */
83
- static readonly listenerRemoved: unique symbol;
105
+ static readonly listenerRemoved: typeof listenerRemoved;
106
+
107
+ /**
108
+ In TypeScript, it returns a decorator which mixins `Emittery` as property `emitteryPropertyName` and `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the target class.
109
+
110
+ @example
111
+ ```
112
+ import Emittery = require('emittery');
113
+
114
+ @Emittery.mixin('emittery')
115
+ class MyClass {}
116
+
117
+ const instance = new MyClass();
118
+
119
+ instance.emit('event');
120
+ ```
121
+ */
122
+ static mixin(
123
+ emitteryPropertyName: string | symbol,
124
+ methodNames?: readonly string[]
125
+ ): <T extends { new (): any }>(klass: T) => T; // eslint-disable-line @typescript-eslint/prefer-function-type
84
126
 
85
127
  /**
86
128
  Subscribe to one or more events.
@@ -106,8 +148,10 @@ declare class Emittery {
106
148
  emitter.emit('🐶', '🍖'); // log => '🍖'
107
149
  ```
108
150
  */
109
- on(eventName: typeof Emittery.listenerAdded | typeof Emittery.listenerRemoved, listener: (eventData: Emittery.ListenerChangedData) => void): Emittery.UnsubscribeFn
110
- on(eventName: EventNames, listener: (eventData?: unknown) => void): Emittery.UnsubscribeFn;
151
+ on<Name extends keyof AllEventData>(
152
+ eventName: Name,
153
+ listener: (eventData: AllEventData[Name]) => void | Promise<void>
154
+ ): Emittery.UnsubscribeFn;
111
155
 
112
156
  /**
113
157
  Get an async iterator which buffers data each time an event is emitted.
@@ -192,7 +236,9 @@ declare class Emittery {
192
236
  });
193
237
  ```
194
238
  */
195
- events(eventName: EventNames): AsyncIterableIterator<unknown>
239
+ events<Name extends keyof EventData>(
240
+ eventName: Name | Name[]
241
+ ): AsyncIterableIterator<EventData[Name]>;
196
242
 
197
243
  /**
198
244
  Remove one or more event subscriptions.
@@ -217,7 +263,10 @@ declare class Emittery {
217
263
  })();
218
264
  ```
219
265
  */
220
- off(eventName: EventNames, listener: (eventData?: unknown) => void): void;
266
+ off<Name extends keyof AllEventData>(
267
+ eventName: Name,
268
+ listener: (eventData: AllEventData[Name]) => void | Promise<void>
269
+ ): void;
221
270
 
222
271
  /**
223
272
  Subscribe to one or more events only once. It will be unsubscribed after the first
@@ -243,15 +292,18 @@ declare class Emittery {
243
292
  emitter.emit('🐶', '🍖'); // Nothing happens
244
293
  ```
245
294
  */
246
- once(eventName: typeof Emittery.listenerAdded | typeof Emittery.listenerRemoved): Promise<Emittery.ListenerChangedData>
247
- once(eventName: EventNames): Promise<unknown>;
295
+ once<Name extends keyof AllEventData>(eventName: Name): Promise<AllEventData[Name]>;
248
296
 
249
297
  /**
250
298
  Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.
251
299
 
252
300
  @returns A promise that resolves when all the event listeners are done. *Done* meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will be rejected with the error, but the other listeners will not be affected.
253
301
  */
254
- emit(eventName: EventName, eventData?: unknown): Promise<void>;
302
+ emit<Name extends DatalessEvents>(eventName: Name): Promise<void>;
303
+ emit<Name extends keyof EventData>(
304
+ eventName: Name,
305
+ eventData: EventData[Name]
306
+ ): Promise<void>;
255
307
 
256
308
  /**
257
309
  Same as `emit()`, but it waits for each listener to resolve before triggering the next one. This can be useful if your events depend on each other. Although ideally they should not. Prefer `emit()` whenever possible.
@@ -260,14 +312,23 @@ declare class Emittery {
260
312
 
261
313
  @returns A promise that resolves when all the event listeners are done.
262
314
  */
263
- emitSerial(eventName: EventName, eventData?: unknown): Promise<void>;
315
+ emitSerial<Name extends DatalessEvents>(eventName: Name): Promise<void>;
316
+ emitSerial<Name extends keyof EventData>(
317
+ eventName: Name,
318
+ eventData: EventData[Name]
319
+ ): Promise<void>;
264
320
 
265
321
  /**
266
322
  Subscribe to be notified about any event.
267
323
 
268
324
  @returns A method to unsubscribe.
269
325
  */
270
- onAny(listener: (eventName: EventName, eventData?: unknown) => unknown): Emittery.UnsubscribeFn;
326
+ onAny(
327
+ listener: (
328
+ eventName: keyof EventData,
329
+ eventData: EventData[keyof EventData]
330
+ ) => void | Promise<void>
331
+ ): Emittery.UnsubscribeFn;
271
332
 
272
333
  /**
273
334
  Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.
@@ -303,24 +364,31 @@ declare class Emittery {
303
364
  });
304
365
  ```
305
366
  */
306
- anyEvent(): AsyncIterableIterator<unknown>
367
+ anyEvent(): AsyncIterableIterator<
368
+ [keyof EventData, EventData[keyof EventData]]
369
+ >;
307
370
 
308
371
  /**
309
372
  Remove an `onAny` subscription.
310
373
  */
311
- offAny(listener: (eventName: EventName, eventData?: unknown) => void): void;
374
+ offAny(
375
+ listener: (
376
+ eventName: keyof EventData,
377
+ eventData: EventData[keyof EventData]
378
+ ) => void | Promise<void>
379
+ ): void;
312
380
 
313
381
  /**
314
382
  Clear all event listeners on the instance.
315
383
 
316
384
  If `eventName` is given, only the listeners for that event are cleared.
317
385
  */
318
- clearListeners(eventName?: EventNames): void;
386
+ clearListeners(eventName?: keyof EventData): void;
319
387
 
320
388
  /**
321
389
  The number of listeners for the `eventName` or all events if not specified.
322
390
  */
323
- listenerCount(eventName?: EventNames): number;
391
+ listenerCount(eventName?: keyof EventData): number;
324
392
 
325
393
  /**
326
394
  Bind the given `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the `target` object.
@@ -336,7 +404,7 @@ declare class Emittery {
336
404
  object.emit('event');
337
405
  ```
338
406
  */
339
- bindMethods(target: object, methodNames?: readonly string[]): void;
407
+ bindMethods(target: Record<string, unknown>, methodNames?: readonly string[]): void;
340
408
  }
341
409
 
342
410
  declare namespace Emittery {
@@ -344,15 +412,6 @@ declare namespace Emittery {
344
412
  Removes an event subscription.
345
413
  */
346
414
  type UnsubscribeFn = () => void;
347
- type EventNameFromDataMap<EventDataMap> = Extract<keyof EventDataMap, EventName>;
348
-
349
- /**
350
- Maps event names to their emitted data type.
351
- */
352
- interface Events {
353
- // Blocked by https://github.com/microsoft/TypeScript/issues/1863, should be
354
- // `[eventName: EventName]: unknown;`
355
- }
356
415
 
357
416
  /**
358
417
  The data provided as `eventData` when listening for `Emittery.listenerAdded` or `Emittery.listenerRemoved`.
@@ -361,54 +420,13 @@ declare namespace Emittery {
361
420
  /**
362
421
  The listener that was added or removed.
363
422
  */
364
- listener: (eventData?: unknown) => void;
423
+ listener: (eventData?: unknown) => void | Promise<void>;
365
424
 
366
425
  /**
367
426
  The name of the event that was added or removed if `.on()` or `.off()` was used, or `undefined` if `.onAny()` or `.offAny()` was used.
368
427
  */
369
428
  eventName?: EventName;
370
429
  }
371
-
372
- /**
373
- Async event emitter.
374
-
375
- You must list supported events and the data type they emit, if any.
376
-
377
- @example
378
- ```
379
- import Emittery = require('emittery');
380
-
381
- const emitter = new Emittery.Typed<{value: string}, 'open' | 'close'>();
382
-
383
- emitter.emit('open');
384
- emitter.emit('value', 'foo\n');
385
- emitter.emit('value', 1); // TS compilation error
386
- emitter.emit('end'); // TS compilation error
387
- ```
388
- */
389
- class Typed<EventDataMap extends Events, EmptyEvents extends EventName = never> extends Emittery {
390
- on<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name, listener: (eventData: EventDataMap[Name]) => void): Emittery.UnsubscribeFn;
391
- on<Name extends EmptyEvents>(eventName: Name, listener: () => void): Emittery.UnsubscribeFn;
392
-
393
- events<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name): AsyncIterableIterator<EventDataMap[Name]>;
394
-
395
- once<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name): Promise<EventDataMap[Name]>;
396
- once<Name extends EmptyEvents>(eventName: Name): Promise<void>;
397
-
398
- off<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name, listener: (eventData: EventDataMap[Name]) => void): void;
399
- off<Name extends EmptyEvents>(eventName: Name, listener: () => void): void;
400
-
401
- onAny(listener: (eventName: EventNameFromDataMap<EventDataMap> | EmptyEvents, eventData?: EventDataMap[EventNameFromDataMap<EventDataMap>]) => void): Emittery.UnsubscribeFn;
402
- anyEvent(): AsyncIterableIterator<[EventNameFromDataMap<EventDataMap>, EventDataMap[EventNameFromDataMap<EventDataMap>]]>;
403
-
404
- offAny(listener: (eventName: EventNameFromDataMap<EventDataMap> | EmptyEvents, eventData?: EventDataMap[EventNameFromDataMap<EventDataMap>]) => void): void;
405
-
406
- emit<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name, eventData: EventDataMap[Name]): Promise<void>;
407
- emit<Name extends EmptyEvents>(eventName: Name): Promise<void>;
408
-
409
- emitSerial<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name, eventData: EventDataMap[Name]): Promise<void>;
410
- emitSerial<Name extends EmptyEvents>(eventName: Name): Promise<void>;
411
- }
412
430
  }
413
431
 
414
432
  export = Emittery;
package/index.js CHANGED
@@ -31,7 +31,7 @@ function getListeners(instance, eventName) {
31
31
  }
32
32
 
33
33
  function getEventProducers(instance, eventName) {
34
- const key = typeof eventName === 'string' ? eventName : anyProducer;
34
+ const key = typeof eventName === 'string' || typeof eventName === 'symbol' ? eventName : anyProducer;
35
35
  const producers = producersMap.get(instance);
36
36
  if (!producers.has(key)) {
37
37
  producers.set(key, new Set());
@@ -313,7 +313,7 @@ class Emittery {
313
313
  eventNames = Array.isArray(eventNames) ? eventNames : [eventNames];
314
314
 
315
315
  for (const eventName of eventNames) {
316
- if (typeof eventName === 'string') {
316
+ if (typeof eventName === 'string' || typeof eventName === 'symbol') {
317
317
  getListeners(this, eventName).clear();
318
318
 
319
319
  const producers = getEventProducers(this, eventName);
@@ -392,13 +392,6 @@ class Emittery {
392
392
 
393
393
  const allEmitteryMethods = Object.getOwnPropertyNames(Emittery.prototype).filter(v => v !== 'constructor');
394
394
 
395
- // Subclass used to encourage TS users to type their events.
396
- Emittery.Typed = class extends Emittery {};
397
- Object.defineProperty(Emittery.Typed, 'Typed', {
398
- enumerable: false,
399
- value: undefined
400
- });
401
-
402
395
  Object.defineProperty(Emittery, 'listenerAdded', {
403
396
  value: listenerAdded,
404
397
  writable: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emittery",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Simple and modern async event emitter",
5
5
  "license": "MIT",
6
6
  "repository": "sindresorhus/emittery",
@@ -50,12 +50,11 @@
50
50
  "devDependencies": {
51
51
  "@types/node": "^13.7.5",
52
52
  "ava": "^2.4.0",
53
- "codecov": "^3.1.0",
54
53
  "delay": "^4.3.0",
55
54
  "nyc": "^15.0.0",
56
55
  "p-event": "^4.1.0",
57
- "tsd": "^0.11.0",
58
- "xo": "^0.25.4"
56
+ "tsd": "^0.14.0",
57
+ "xo": "^0.36.1"
59
58
  },
60
59
  "nyc": {
61
60
  "reporter": [
package/readme.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  > Simple and modern async event emitter
4
4
 
5
- [![Build Status](https://travis-ci.org/sindresorhus/emittery.svg?branch=master)](https://travis-ci.org/sindresorhus/emittery) [![codecov](https://codecov.io/gh/sindresorhus/emittery/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/emittery) [![](https://badgen.net/bundlephobia/minzip/emittery)](https://bundlephobia.com/result?p=emittery)
5
+ [![Coverage Status](https://codecov.io/gh/sindresorhus/emittery/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/emittery)
6
+ [![](https://badgen.net/bundlephobia/minzip/emittery)](https://bundlephobia.com/result?p=emittery)
6
7
 
7
8
  It works in Node.js and the browser (using a bundler).
8
9
 
@@ -120,9 +121,9 @@ const listener = data => console.log(data);
120
121
  await emitter.emit('🦊', 'c');
121
122
  emitter.off('🦄', listener);
122
123
  emitter.off(['🐶', '🦊'], listener);
123
- await emitter.emit('🦄', 'a'); // nothing happens
124
- await emitter.emit('🐶', 'b'); // nothing happens
125
- await emitter.emit('🦊', 'c'); // nothing happens
124
+ await emitter.emit('🦄', 'a'); // Nothing happens
125
+ await emitter.emit('🐶', 'b'); // Nothing happens
126
+ await emitter.emit('🦊', 'c'); // Nothing happens
126
127
  })();
127
128
  ```
128
129
 
@@ -147,8 +148,8 @@ emitter.once(['🦄', '🐶']).then(data => {
147
148
  console.log(data);
148
149
  });
149
150
 
150
- emitter.emit('🦄', '🌈'); // log => '🌈' x2
151
- emitter.emit('🐶', '🍖'); // nothing happens
151
+ emitter.emit('🦄', '🌈'); // Log => '🌈' x2
152
+ emitter.emit('🐶', '🍖'); // Nothing happens
152
153
  ```
153
154
 
154
155
  #### events(eventName)
@@ -316,17 +317,31 @@ object.emit('event');
316
317
 
317
318
  ## TypeScript
318
319
 
319
- The default `Emittery` class does not let you type allowed event names and their associated data. However, you can use `Emittery.Typed` with generics:
320
+ The default `Emittery` class has generic types that can be provided by TypeScript users to strongly type the list of events and the data passed to their event listeners.
320
321
 
321
322
  ```ts
322
323
  import Emittery = require('emittery');
323
324
 
324
- const emitter = new Emittery.Typed<{value: string}, 'open' | 'close'>();
325
+ const emitter = new Emittery<
326
+ // Pass `{[eventName]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
327
+ // A value of `undefined` in this map means the event listeners should expect no data, and a type other than `undefined` means the listeners will receive one argument of that type.
328
+ {
329
+ open: string,
330
+ close: undefined
331
+ }
332
+ >();
333
+
334
+ // Typechecks just fine because the data type for the `open` event is `string`.
335
+ emitter.emit('open', 'foo\n');
336
+
337
+ // Typechecks just fine because `close` is present but points to undefined in the event data type map.
338
+ emitter.emit('close');
339
+
340
+ // TS compilation error because `1` isn't assignable to `string`.
341
+ emitter.emit('open', 1);
325
342
 
326
- emitter.emit('open');
327
- emitter.emit('value', 'foo\n');
328
- emitter.emit('value', 1); // TS compilation error
329
- emitter.emit('end'); // TS compilation error
343
+ // TS compilation error because `other` isn't defined in the event data type map.
344
+ emitter.emit('other');
330
345
  ```
331
346
 
332
347
  ### Emittery.mixin(emitteryPropertyName, methodNames?)