index.d.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /* eslint-disable no-redeclare */
  2. /**
  3. Emittery accepts strings, symbols, and numbers as event names.
  4. Symbol event names are preferred given that they can be used to avoid name collisions when your classes are extended, especially for internal events.
  5. */
  6. type EventName = PropertyKey;
  7. // 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.
  8. type DatalessEventNames<EventData> = {
  9. [Key in keyof EventData]: EventData[Key] extends undefined ? Key : never;
  10. }[keyof EventData];
  11. declare const listenerAdded: unique symbol;
  12. declare const listenerRemoved: unique symbol;
  13. type _OmnipresentEventData = {[listenerAdded]: Emittery.ListenerChangedData; [listenerRemoved]: Emittery.ListenerChangedData};
  14. /**
  15. Emittery can collect and log debug information.
  16. To enable this feature set the `DEBUG` environment variable to `emittery` or `*`. Additionally, you can set the static `isDebugEnabled` variable to true on the Emittery class, or `myEmitter.debug.enabled` on an instance of it for debugging a single instance.
  17. See API for more information on how debugging works.
  18. */
  19. type DebugLogger<EventData, Name extends keyof EventData> = (type: string, debugName: string, eventName?: Name, eventData?: EventData[Name]) => void;
  20. /**
  21. Configure debug options of an instance.
  22. */
  23. interface DebugOptions<EventData> {
  24. /**
  25. Define a name for the instance of Emittery to use when outputting debug data.
  26. @default undefined
  27. @example
  28. ```
  29. import Emittery = require('emittery');
  30. Emittery.isDebugEnabled = true;
  31. const emitter = new Emittery({debug: {name: 'myEmitter'}});
  32. emitter.on('test', data => {
  33. // …
  34. });
  35. emitter.emit('test');
  36. //=> [16:43:20.417][emittery:subscribe][myEmitter] Event Name: test
  37. // data: undefined
  38. ```
  39. */
  40. readonly name: string;
  41. /**
  42. Toggle debug logging just for this instance.
  43. @default false
  44. @example
  45. ```
  46. import Emittery = require('emittery');
  47. const emitter1 = new Emittery({debug: {name: 'emitter1', enabled: true}});
  48. const emitter2 = new Emittery({debug: {name: 'emitter2'}});
  49. emitter1.on('test', data => {
  50. // …
  51. });
  52. emitter2.on('test', data => {
  53. // …
  54. });
  55. emitter1.emit('test');
  56. //=> [16:43:20.417][emittery:subscribe][emitter1] Event Name: test
  57. // data: undefined
  58. emitter2.emit('test');
  59. ```
  60. */
  61. enabled?: boolean;
  62. /**
  63. Function that handles debug data.
  64. @default
  65. ```
  66. (type, debugName, eventName, eventData) => {
  67. eventData = JSON.stringify(eventData);
  68. if (typeof eventName === 'symbol' || typeof eventName === 'number') {
  69. eventName = eventName.toString();
  70. }
  71. const currentTime = new Date();
  72. const logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;
  73. console.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\n\tdata: ${eventData}`);
  74. }
  75. ```
  76. @example
  77. ```
  78. import Emittery = require('emittery');
  79. const myLogger = (type, debugName, eventName, eventData) => console.log(`[${type}]: ${eventName}`);
  80. const emitter = new Emittery({
  81. debug: {
  82. name: 'myEmitter',
  83. enabled: true,
  84. logger: myLogger
  85. }
  86. });
  87. emitter.on('test', data => {
  88. // …
  89. });
  90. emitter.emit('test');
  91. //=> [subscribe]: test
  92. ```
  93. */
  94. logger?: DebugLogger<EventData, keyof EventData>;
  95. }
  96. /**
  97. Configuration options for Emittery.
  98. */
  99. interface Options<EventData> {
  100. debug?: DebugOptions<EventData>;
  101. }
  102. /**
  103. A promise returned from `emittery.once` with an extra `off` method to cancel your subscription.
  104. */
  105. interface EmitteryOncePromise<T> extends Promise<T> {
  106. off(): void;
  107. }
  108. /**
  109. 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`.
  110. `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.
  111. @example
  112. ```
  113. import Emittery = require('emittery');
  114. const emitter = new Emittery<
  115. // Pass `{[eventName: <string | symbol | number>]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
  116. // 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.
  117. {
  118. open: string,
  119. close: undefined
  120. }
  121. >();
  122. // Typechecks just fine because the data type for the `open` event is `string`.
  123. emitter.emit('open', 'foo\n');
  124. // Typechecks just fine because `close` is present but points to undefined in the event data type map.
  125. emitter.emit('close');
  126. // TS compilation error because `1` isn't assignable to `string`.
  127. emitter.emit('open', 1);
  128. // TS compilation error because `other` isn't defined in the event data type map.
  129. emitter.emit('other');
  130. ```
  131. */
  132. declare class Emittery<
  133. EventData = Record<EventName, any>,
  134. AllEventData = EventData & _OmnipresentEventData,
  135. DatalessEvents = DatalessEventNames<EventData>
  136. > {
  137. /**
  138. Toggle debug mode for all instances.
  139. Default: `true` if the `DEBUG` environment variable is set to `emittery` or `*`, otherwise `false`.
  140. @example
  141. ```
  142. import Emittery = require('emittery');
  143. Emittery.isDebugEnabled = true;
  144. const emitter1 = new Emittery({debug: {name: 'myEmitter1'}});
  145. const emitter2 = new Emittery({debug: {name: 'myEmitter2'}});
  146. emitter1.on('test', data => {
  147. // …
  148. });
  149. emitter2.on('otherTest', data => {
  150. // …
  151. });
  152. emitter1.emit('test');
  153. //=> [16:43:20.417][emittery:subscribe][myEmitter1] Event Name: test
  154. // data: undefined
  155. emitter2.emit('otherTest');
  156. //=> [16:43:20.417][emittery:subscribe][myEmitter2] Event Name: otherTest
  157. // data: undefined
  158. ```
  159. */
  160. static isDebugEnabled: boolean;
  161. /**
  162. Fires when an event listener was added.
  163. An object with `listener` and `eventName` (if `on` or `off` was used) is provided as event data.
  164. @example
  165. ```
  166. import Emittery = require('emittery');
  167. const emitter = new Emittery();
  168. emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
  169. console.log(listener);
  170. //=> data => {}
  171. console.log(eventName);
  172. //=> '🦄'
  173. });
  174. emitter.on('🦄', data => {
  175. // Handle data
  176. });
  177. ```
  178. */
  179. static readonly listenerAdded: typeof listenerAdded;
  180. /**
  181. Fires when an event listener was removed.
  182. An object with `listener` and `eventName` (if `on` or `off` was used) is provided as event data.
  183. @example
  184. ```
  185. import Emittery = require('emittery');
  186. const emitter = new Emittery();
  187. const off = emitter.on('🦄', data => {
  188. // Handle data
  189. });
  190. emitter.on(Emittery.listenerRemoved, ({listener, eventName}) => {
  191. console.log(listener);
  192. //=> data => {}
  193. console.log(eventName);
  194. //=> '🦄'
  195. });
  196. off();
  197. ```
  198. */
  199. static readonly listenerRemoved: typeof listenerRemoved;
  200. /**
  201. Debugging options for the current instance.
  202. */
  203. debug: DebugOptions<EventData>;
  204. /**
  205. Create a new Emittery instance with the specified options.
  206. @returns An instance of Emittery that you can use to listen for and emit events.
  207. */
  208. constructor(options?: Options<EventData>);
  209. /**
  210. 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.
  211. @example
  212. ```
  213. import Emittery = require('emittery');
  214. @Emittery.mixin('emittery')
  215. class MyClass {}
  216. const instance = new MyClass();
  217. instance.emit('event');
  218. ```
  219. */
  220. static mixin(
  221. emitteryPropertyName: string | symbol,
  222. methodNames?: readonly string[]
  223. ): <T extends {new (...arguments_: any[]): any}>(klass: T) => T; // eslint-disable-line @typescript-eslint/prefer-function-type
  224. /**
  225. Subscribe to one or more events.
  226. Using the same listener multiple times for the same event will result in only one method call per emitted event.
  227. @returns An unsubscribe method.
  228. @example
  229. ```
  230. import Emittery = require('emittery');
  231. const emitter = new Emittery();
  232. emitter.on('🦄', data => {
  233. console.log(data);
  234. });
  235. emitter.on(['🦄', '🐶'], data => {
  236. console.log(data);
  237. });
  238. emitter.emit('🦄', '🌈'); // log => '🌈' x2
  239. emitter.emit('🐶', '🍖'); // log => '🍖'
  240. ```
  241. */
  242. on<Name extends keyof AllEventData>(
  243. eventName: Name | Name[],
  244. listener: (eventData: AllEventData[Name]) => void | Promise<void>
  245. ): Emittery.UnsubscribeFn;
  246. /**
  247. Get an async iterator which buffers data each time an event is emitted.
  248. Call `return()` on the iterator to remove the subscription.
  249. @example
  250. ```
  251. import Emittery = require('emittery');
  252. const emitter = new Emittery();
  253. const iterator = emitter.events('🦄');
  254. emitter.emit('🦄', '🌈1'); // Buffered
  255. emitter.emit('🦄', '🌈2'); // Buffered
  256. iterator
  257. .next()
  258. .then(({value, done}) => {
  259. // done === false
  260. // value === '🌈1'
  261. return iterator.next();
  262. })
  263. .then(({value, done}) => {
  264. // done === false
  265. // value === '🌈2'
  266. // Revoke subscription
  267. return iterator.return();
  268. })
  269. .then(({done}) => {
  270. // done === true
  271. });
  272. ```
  273. 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.
  274. @example
  275. ```
  276. import Emittery = require('emittery');
  277. const emitter = new Emittery();
  278. const iterator = emitter.events('🦄');
  279. emitter.emit('🦄', '🌈1'); // Buffered
  280. emitter.emit('🦄', '🌈2'); // Buffered
  281. // In an async context.
  282. for await (const data of iterator) {
  283. if (data === '🌈2') {
  284. break; // Revoke the subscription when we see the value `🌈2`.
  285. }
  286. }
  287. ```
  288. It accepts multiple event names.
  289. @example
  290. ```
  291. import Emittery = require('emittery');
  292. const emitter = new Emittery();
  293. const iterator = emitter.events(['🦄', '🦊']);
  294. emitter.emit('🦄', '🌈1'); // Buffered
  295. emitter.emit('🦊', '🌈2'); // Buffered
  296. iterator
  297. .next()
  298. .then(({value, done}) => {
  299. // done === false
  300. // value === '🌈1'
  301. return iterator.next();
  302. })
  303. .then(({value, done}) => {
  304. // done === false
  305. // value === '🌈2'
  306. // Revoke subscription
  307. return iterator.return();
  308. })
  309. .then(({done}) => {
  310. // done === true
  311. });
  312. ```
  313. */
  314. events<Name extends keyof EventData>(
  315. eventName: Name | Name[]
  316. ): AsyncIterableIterator<EventData[Name]>;
  317. /**
  318. Remove one or more event subscriptions.
  319. @example
  320. ```
  321. import Emittery = require('emittery');
  322. const emitter = new Emittery();
  323. const listener = data => console.log(data);
  324. (async () => {
  325. emitter.on(['🦄', '🐶', '🦊'], listener);
  326. await emitter.emit('🦄', 'a');
  327. await emitter.emit('🐶', 'b');
  328. await emitter.emit('🦊', 'c');
  329. emitter.off('🦄', listener);
  330. emitter.off(['🐶', '🦊'], listener);
  331. await emitter.emit('🦄', 'a'); // nothing happens
  332. await emitter.emit('🐶', 'b'); // nothing happens
  333. await emitter.emit('🦊', 'c'); // nothing happens
  334. })();
  335. ```
  336. */
  337. off<Name extends keyof AllEventData>(
  338. eventName: Name | Name[],
  339. listener: (eventData: AllEventData[Name]) => void | Promise<void>
  340. ): void;
  341. /**
  342. Subscribe to one or more events only once. It will be unsubscribed after the first
  343. event.
  344. @returns The promise of event data when `eventName` is emitted. This promise is extended with an `off` method.
  345. @example
  346. ```
  347. import Emittery = require('emittery');
  348. const emitter = new Emittery();
  349. emitter.once('🦄').then(data => {
  350. console.log(data);
  351. //=> '🌈'
  352. });
  353. emitter.once(['🦄', '🐶']).then(data => {
  354. console.log(data);
  355. });
  356. emitter.emit('🦄', '🌈'); // Logs `🌈` twice
  357. emitter.emit('🐶', '🍖'); // Nothing happens
  358. ```
  359. */
  360. once<Name extends keyof AllEventData>(eventName: Name | Name[]): EmitteryOncePromise<AllEventData[Name]>;
  361. /**
  362. Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.
  363. @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.
  364. */
  365. emit<Name extends DatalessEvents>(eventName: Name): Promise<void>;
  366. emit<Name extends keyof EventData>(
  367. eventName: Name,
  368. eventData: EventData[Name]
  369. ): Promise<void>;
  370. /**
  371. 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.
  372. If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will *not* be called.
  373. @returns A promise that resolves when all the event listeners are done.
  374. */
  375. emitSerial<Name extends DatalessEvents>(eventName: Name): Promise<void>;
  376. emitSerial<Name extends keyof EventData>(
  377. eventName: Name,
  378. eventData: EventData[Name]
  379. ): Promise<void>;
  380. /**
  381. Subscribe to be notified about any event.
  382. @returns A method to unsubscribe.
  383. */
  384. onAny(
  385. listener: (
  386. eventName: keyof EventData,
  387. eventData: EventData[keyof EventData]
  388. ) => void | Promise<void>
  389. ): Emittery.UnsubscribeFn;
  390. /**
  391. Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.
  392. Call `return()` on the iterator to remove the subscription.
  393. In the same way as for `events`, you can subscribe by using the `for await` statement.
  394. @example
  395. ```
  396. import Emittery = require('emittery');
  397. const emitter = new Emittery();
  398. const iterator = emitter.anyEvent();
  399. emitter.emit('🦄', '🌈1'); // Buffered
  400. emitter.emit('🌟', '🌈2'); // Buffered
  401. iterator.next()
  402. .then(({value, done}) => {
  403. // done is false
  404. // value is ['🦄', '🌈1']
  405. return iterator.next();
  406. })
  407. .then(({value, done}) => {
  408. // done is false
  409. // value is ['🌟', '🌈2']
  410. // revoke subscription
  411. return iterator.return();
  412. })
  413. .then(({done}) => {
  414. // done is true
  415. });
  416. ```
  417. */
  418. anyEvent(): AsyncIterableIterator<
  419. [keyof EventData, EventData[keyof EventData]]
  420. >;
  421. /**
  422. Remove an `onAny` subscription.
  423. */
  424. offAny(
  425. listener: (
  426. eventName: keyof EventData,
  427. eventData: EventData[keyof EventData]
  428. ) => void | Promise<void>
  429. ): void;
  430. /**
  431. Clear all event listeners on the instance.
  432. If `eventName` is given, only the listeners for that event are cleared.
  433. */
  434. clearListeners<Name extends keyof EventData>(eventName?: Name | Name[]): void;
  435. /**
  436. The number of listeners for the `eventName` or all events if not specified.
  437. */
  438. listenerCount<Name extends keyof EventData>(eventName?: Name | Name[]): number;
  439. /**
  440. Bind the given `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the `target` object.
  441. @example
  442. ```
  443. import Emittery = require('emittery');
  444. const object = {};
  445. new Emittery().bindMethods(object);
  446. object.emit('event');
  447. ```
  448. */
  449. bindMethods(target: Record<string, unknown>, methodNames?: readonly string[]): void;
  450. }
  451. declare namespace Emittery {
  452. /**
  453. Removes an event subscription.
  454. */
  455. type UnsubscribeFn = () => void;
  456. /**
  457. The data provided as `eventData` when listening for `Emittery.listenerAdded` or `Emittery.listenerRemoved`.
  458. */
  459. interface ListenerChangedData {
  460. /**
  461. The listener that was added or removed.
  462. */
  463. listener: (eventData?: unknown) => void | Promise<void>;
  464. /**
  465. The name of the event that was added or removed if `.on()` or `.off()` was used, or `undefined` if `.onAny()` or `.offAny()` was used.
  466. */
  467. eventName?: EventName;
  468. }
  469. type OmnipresentEventData = _OmnipresentEventData;
  470. }
  471. export = Emittery;