index.d.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /**
  2. Emittery accepts strings and symbols as event names.
  3. Symbol event names can be used to avoid name collisions when your classes are extended, especially for internal events.
  4. */
  5. type EventName = string | symbol;
  6. // 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.
  7. type DatalessEventNames<EventData> = {
  8. [Key in keyof EventData]: EventData[Key] extends undefined ? Key : never;
  9. }[keyof EventData];
  10. declare const listenerAdded: unique symbol;
  11. declare const listenerRemoved: unique symbol;
  12. type OmnipresentEventData = {[listenerAdded]: Emittery.ListenerChangedData; [listenerRemoved]: Emittery.ListenerChangedData};
  13. /**
  14. 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`.
  15. `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. @example
  17. ```
  18. import Emittery = require('emittery');
  19. const emitter = new Emittery<
  20. // Pass `{[eventName: <string | symbol>]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
  21. // 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.
  22. {
  23. open: string,
  24. close: undefined
  25. }
  26. >();
  27. // Typechecks just fine because the data type for the `open` event is `string`.
  28. emitter.emit('open', 'foo\n');
  29. // Typechecks just fine because `close` is present but points to undefined in the event data type map.
  30. emitter.emit('close');
  31. // TS compilation error because `1` isn't assignable to `string`.
  32. emitter.emit('open', 1);
  33. // TS compilation error because `other` isn't defined in the event data type map.
  34. emitter.emit('other');
  35. ```
  36. */
  37. declare class Emittery<
  38. 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.
  39. AllEventData = EventData & OmnipresentEventData,
  40. DatalessEvents = DatalessEventNames<EventData>
  41. > {
  42. /**
  43. Fires when an event listener was added.
  44. An object with `listener` and `eventName` (if `on` or `off` was used) is provided as event data.
  45. @example
  46. ```
  47. import Emittery = require('emittery');
  48. const emitter = new Emittery();
  49. emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
  50. console.log(listener);
  51. //=> data => {}
  52. console.log(eventName);
  53. //=> '🦄'
  54. });
  55. emitter.on('🦄', data => {
  56. // Handle data
  57. });
  58. ```
  59. */
  60. static readonly listenerAdded: typeof listenerAdded;
  61. /**
  62. Fires when an event listener was removed.
  63. An object with `listener` and `eventName` (if `on` or `off` was used) is provided as event data.
  64. @example
  65. ```
  66. import Emittery = require('emittery');
  67. const emitter = new Emittery();
  68. const off = emitter.on('🦄', data => {
  69. // Handle data
  70. });
  71. emitter.on(Emittery.listenerRemoved, ({listener, eventName}) => {
  72. console.log(listener);
  73. //=> data => {}
  74. console.log(eventName);
  75. //=> '🦄'
  76. });
  77. off();
  78. ```
  79. */
  80. static readonly listenerRemoved: typeof listenerRemoved;
  81. /**
  82. 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.
  83. @example
  84. ```
  85. import Emittery = require('emittery');
  86. @Emittery.mixin('emittery')
  87. class MyClass {}
  88. const instance = new MyClass();
  89. instance.emit('event');
  90. ```
  91. */
  92. static mixin(
  93. emitteryPropertyName: string | symbol,
  94. methodNames?: readonly string[]
  95. ): <T extends { new (): any }>(klass: T) => T; // eslint-disable-line @typescript-eslint/prefer-function-type
  96. /**
  97. Subscribe to one or more events.
  98. Using the same listener multiple times for the same event will result in only one method call per emitted event.
  99. @returns An unsubscribe method.
  100. @example
  101. ```
  102. import Emittery = require('emittery');
  103. const emitter = new Emittery();
  104. emitter.on('🦄', data => {
  105. console.log(data);
  106. });
  107. emitter.on(['🦄', '🐶'], data => {
  108. console.log(data);
  109. });
  110. emitter.emit('🦄', '🌈'); // log => '🌈' x2
  111. emitter.emit('🐶', '🍖'); // log => '🍖'
  112. ```
  113. */
  114. on<Name extends keyof AllEventData>(
  115. eventName: Name,
  116. listener: (eventData: AllEventData[Name]) => void | Promise<void>
  117. ): Emittery.UnsubscribeFn;
  118. /**
  119. Get an async iterator which buffers data each time an event is emitted.
  120. Call `return()` on the iterator to remove the subscription.
  121. @example
  122. ```
  123. import Emittery = require('emittery');
  124. const emitter = new Emittery();
  125. const iterator = emitter.events('🦄');
  126. emitter.emit('🦄', '🌈1'); // Buffered
  127. emitter.emit('🦄', '🌈2'); // Buffered
  128. iterator
  129. .next()
  130. .then(({value, done}) => {
  131. // done === false
  132. // value === '🌈1'
  133. return iterator.next();
  134. })
  135. .then(({value, done}) => {
  136. // done === false
  137. // value === '🌈2'
  138. // Revoke subscription
  139. return iterator.return();
  140. })
  141. .then(({done}) => {
  142. // done === true
  143. });
  144. ```
  145. In practice you would usually consume the events using the [for await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) statement. In that case, to revoke the subscription simply break the loop.
  146. @example
  147. ```
  148. import Emittery = require('emittery');
  149. const emitter = new Emittery();
  150. const iterator = emitter.events('🦄');
  151. emitter.emit('🦄', '🌈1'); // Buffered
  152. emitter.emit('🦄', '🌈2'); // Buffered
  153. // In an async context.
  154. for await (const data of iterator) {
  155. if (data === '🌈2') {
  156. break; // Revoke the subscription when we see the value `🌈2`.
  157. }
  158. }
  159. ```
  160. It accepts multiple event names.
  161. @example
  162. ```
  163. import Emittery = require('emittery');
  164. const emitter = new Emittery();
  165. const iterator = emitter.events(['🦄', '🦊']);
  166. emitter.emit('🦄', '🌈1'); // Buffered
  167. emitter.emit('🦊', '🌈2'); // Buffered
  168. iterator
  169. .next()
  170. .then(({value, done}) => {
  171. // done === false
  172. // value === '🌈1'
  173. return iterator.next();
  174. })
  175. .then(({value, done}) => {
  176. // done === false
  177. // value === '🌈2'
  178. // Revoke subscription
  179. return iterator.return();
  180. })
  181. .then(({done}) => {
  182. // done === true
  183. });
  184. ```
  185. */
  186. events<Name extends keyof EventData>(
  187. eventName: Name | Name[]
  188. ): AsyncIterableIterator<EventData[Name]>;
  189. /**
  190. Remove one or more event subscriptions.
  191. @example
  192. ```
  193. import Emittery = require('emittery');
  194. const emitter = new Emittery();
  195. const listener = data => console.log(data);
  196. (async () => {
  197. emitter.on(['🦄', '🐶', '🦊'], listener);
  198. await emitter.emit('🦄', 'a');
  199. await emitter.emit('🐶', 'b');
  200. await emitter.emit('🦊', 'c');
  201. emitter.off('🦄', listener);
  202. emitter.off(['🐶', '🦊'], listener);
  203. await emitter.emit('🦄', 'a'); // nothing happens
  204. await emitter.emit('🐶', 'b'); // nothing happens
  205. await emitter.emit('🦊', 'c'); // nothing happens
  206. })();
  207. ```
  208. */
  209. off<Name extends keyof AllEventData>(
  210. eventName: Name,
  211. listener: (eventData: AllEventData[Name]) => void | Promise<void>
  212. ): void;
  213. /**
  214. Subscribe to one or more events only once. It will be unsubscribed after the first
  215. event.
  216. @returns The event data when `eventName` is emitted.
  217. @example
  218. ```
  219. import Emittery = require('emittery');
  220. const emitter = new Emittery();
  221. emitter.once('🦄').then(data => {
  222. console.log(data);
  223. //=> '🌈'
  224. });
  225. emitter.once(['🦄', '🐶']).then(data => {
  226. console.log(data);
  227. });
  228. emitter.emit('🦄', '🌈'); // Logs `🌈` twice
  229. emitter.emit('🐶', '🍖'); // Nothing happens
  230. ```
  231. */
  232. once<Name extends keyof AllEventData>(eventName: Name): Promise<AllEventData[Name]>;
  233. /**
  234. Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.
  235. @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.
  236. */
  237. emit<Name extends DatalessEvents>(eventName: Name): Promise<void>;
  238. emit<Name extends keyof EventData>(
  239. eventName: Name,
  240. eventData: EventData[Name]
  241. ): Promise<void>;
  242. /**
  243. 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.
  244. If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will *not* be called.
  245. @returns A promise that resolves when all the event listeners are done.
  246. */
  247. emitSerial<Name extends DatalessEvents>(eventName: Name): Promise<void>;
  248. emitSerial<Name extends keyof EventData>(
  249. eventName: Name,
  250. eventData: EventData[Name]
  251. ): Promise<void>;
  252. /**
  253. Subscribe to be notified about any event.
  254. @returns A method to unsubscribe.
  255. */
  256. onAny(
  257. listener: (
  258. eventName: keyof EventData,
  259. eventData: EventData[keyof EventData]
  260. ) => void | Promise<void>
  261. ): Emittery.UnsubscribeFn;
  262. /**
  263. Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.
  264. Call `return()` on the iterator to remove the subscription.
  265. In the same way as for `events`, you can subscribe by using the `for await` statement.
  266. @example
  267. ```
  268. import Emittery = require('emittery');
  269. const emitter = new Emittery();
  270. const iterator = emitter.anyEvent();
  271. emitter.emit('🦄', '🌈1'); // Buffered
  272. emitter.emit('🌟', '🌈2'); // Buffered
  273. iterator.next()
  274. .then(({value, done}) => {
  275. // done is false
  276. // value is ['🦄', '🌈1']
  277. return iterator.next();
  278. })
  279. .then(({value, done}) => {
  280. // done is false
  281. // value is ['🌟', '🌈2']
  282. // revoke subscription
  283. return iterator.return();
  284. })
  285. .then(({done}) => {
  286. // done is true
  287. });
  288. ```
  289. */
  290. anyEvent(): AsyncIterableIterator<
  291. [keyof EventData, EventData[keyof EventData]]
  292. >;
  293. /**
  294. Remove an `onAny` subscription.
  295. */
  296. offAny(
  297. listener: (
  298. eventName: keyof EventData,
  299. eventData: EventData[keyof EventData]
  300. ) => void | Promise<void>
  301. ): void;
  302. /**
  303. Clear all event listeners on the instance.
  304. If `eventName` is given, only the listeners for that event are cleared.
  305. */
  306. clearListeners(eventName?: keyof EventData): void;
  307. /**
  308. The number of listeners for the `eventName` or all events if not specified.
  309. */
  310. listenerCount(eventName?: keyof EventData): number;
  311. /**
  312. Bind the given `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the `target` object.
  313. @example
  314. ```
  315. import Emittery = require('emittery');
  316. const object = {};
  317. new Emittery().bindMethods(object);
  318. object.emit('event');
  319. ```
  320. */
  321. bindMethods(target: Record<string, unknown>, methodNames?: readonly string[]): void;
  322. }
  323. declare namespace Emittery {
  324. /**
  325. Removes an event subscription.
  326. */
  327. type UnsubscribeFn = () => void;
  328. /**
  329. The data provided as `eventData` when listening for `Emittery.listenerAdded` or `Emittery.listenerRemoved`.
  330. */
  331. interface ListenerChangedData {
  332. /**
  333. The listener that was added or removed.
  334. */
  335. listener: (eventData?: unknown) => void | Promise<void>;
  336. /**
  337. The name of the event that was added or removed if `.on()` or `.off()` was used, or `undefined` if `.onAny()` or `.offAny()` was used.
  338. */
  339. eventName?: EventName;
  340. }
  341. }
  342. export = Emittery;