-
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathindex.d.ts
More file actions
767 lines (592 loc) Β· 20.6 KB
/
index.d.ts
File metadata and controls
767 lines (592 loc) Β· 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
/**
Emittery accepts strings, symbols, and numbers as event names.
Symbol event names are preferred given that they can be used to avoid name collisions when your classes are extended, especially for internal events.
*/
export type EventName = PropertyKey;
/**
The object passed to every event listener. Always includes `name`. Includes `data` only when the event was emitted with data.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery<{unicorn: string; close: undefined}>();
emitter.on('unicorn', ({name, data}) => {
console.log(name); //=> 'unicorn'
console.log(data); //=> 'π'
});
emitter.on('close', ({name}) => {
console.log(name); //=> 'close'
});
```
*/
export type EmitteryEvent<Name extends EventName, Data> = [Data] extends [undefined]
? {readonly name: Name; readonly data?: undefined}
: {readonly name: Name; readonly data: Data};
type EventDataPair<EventData, Name extends keyof EventData> = Name extends keyof EventData ? EmitteryEvent<Name, EventData[Name]> : never;
// 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.
type DatalessEventNames<EventData> = {
[Key in keyof EventData]: EventData[Key] extends undefined ? Key : never;
}[keyof EventData];
declare const listenerAdded: unique symbol;
declare const listenerRemoved: unique symbol;
type OmnipresentEventData = {[listenerAdded]: ListenerChangedData; [listenerRemoved]: ListenerChangedData};
/**
Emittery can collect and log debug information.
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.
See API for more information on how debugging works.
*/
export type DebugLogger<EventData, Name extends keyof EventData> = (type: string, debugName?: string, eventName?: Name, eventData?: EventData[Name]) => void;
/**
Configure debug options of an instance.
*/
export type DebugOptions<EventData> = {
/**
Define a name for the instance of Emittery to use when outputting debug data.
@default undefined
@example
```
import Emittery from 'emittery';
Emittery.isDebugEnabled = true;
const emitter = new Emittery({debug: {name: 'myEmitter'}});
emitter.on('test', () => {
// β¦
});
emitter.emit('test');
//=> [16:43:20.417][emittery:subscribe][myEmitter] Event Name: test
// data: undefined
```
*/
readonly name?: string;
/**
Toggle debug logging just for this instance.
@default false
@example
```
import Emittery from 'emittery';
const emitter1 = new Emittery({debug: {name: 'emitter1', enabled: true}});
const emitter2 = new Emittery({debug: {name: 'emitter2'}});
emitter1.on('test', () => {
// β¦
});
emitter2.on('test', () => {
// β¦
});
emitter1.emit('test');
//=> [16:43:20.417][emittery:subscribe][emitter1] Event Name: test
// data: undefined
emitter2.emit('test');
```
*/
readonly enabled?: boolean;
/**
Function that handles debug data.
@default
```
(type, debugName, eventName, eventData) => {
try {
eventData = JSON.stringify(eventData);
} catch {
eventData = `Object with the following keys failed to stringify: ${Object.keys(eventData).join(',')}`;
}
if (typeof eventName === 'symbol' || typeof eventName === 'number') {
eventName = eventName.toString();
}
const currentTime = new Date();
const logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;
console.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\n\tdata: ${eventData}`);
}
```
@example
```
import Emittery from 'emittery';
const myLogger = (type, debugName, eventName, eventData) => {
console.log(`[${type}]: ${eventName}`);
};
const emitter = new Emittery({
debug: {
name: 'myEmitter',
enabled: true,
logger: myLogger
}
});
emitter.on('test', () => {
// β¦
});
emitter.emit('test');
//=> [subscribe]: test
```
*/
readonly logger?: DebugLogger<EventData, keyof EventData>;
};
/**
Configuration options for Emittery.
*/
export type Options<EventData> = {
readonly debug?: DebugOptions<EventData>;
};
/**
A promise returned from `emittery.once` with an extra `off` method to cancel your subscription.
*/
export type EmitteryOncePromise<T> = {
off(): void;
} & Promise<T>;
/**
Removes an event subscription.
Can be used with the `using` keyword for automatic cleanup:
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
{
using off = emitter.on('event', ({data}) => {
console.log(data);
});
// auto-unsubscribes when leaving scope
}
```
*/
export type UnsubscribeFunction = (() => void) & Disposable;
/**
The data provided as `eventData` when listening for `Emittery.listenerAdded` or `Emittery.listenerRemoved`.
*/
export type ListenerChangedData = {
/**
The listener that was added or removed.
*/
listener: (event: unknown) => (void | Promise<void>);
/**
The name of the event that was added or removed if `.on()` or `.off()` was used, or `undefined` if `.onAny()` or `.offAny()` was used.
*/
eventName?: EventName;
};
/**
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`.
`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.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery<
// Pass `{[eventName: <string | symbol | number>]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
// 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.
{
open: string,
close: undefined
}
>();
// Typechecks just fine because the data type for the `open` event is `string`.
emitter.emit('open', 'foo\n');
// Typechecks just fine because `close` is present but points to undefined in the event data type map.
emitter.emit('close');
// TS compilation error because `1` isn't assignable to `string`.
emitter.emit('open', 1);
// TS compilation error because `other` isn't defined in the event data type map.
emitter.emit('other');
```
*/
export default class Emittery<
EventData = Record<EventName, unknown>, AllEventData = EventData & OmnipresentEventData,
DatalessEvents = DatalessEventNames<EventData>,
> {
/**
Toggle debug mode for all instances.
Default: `true` if the `DEBUG` environment variable is set to `emittery` or `*`, otherwise `false`.
@example
```
import Emittery from 'emittery';
Emittery.isDebugEnabled = true;
const emitter1 = new Emittery({debug: {name: 'myEmitter1'}});
const emitter2 = new Emittery({debug: {name: 'myEmitter2'}});
emitter1.on('test', () => {
// β¦
});
emitter2.on('otherTest', () => {
// β¦
});
emitter1.emit('test');
//=> [16:43:20.417][emittery:subscribe][myEmitter1] Event Name: test
// data: undefined
emitter2.emit('otherTest');
//=> [16:43:20.417][emittery:subscribe][myEmitter2] Event Name: otherTest
// data: undefined
```
*/
static isDebugEnabled: boolean;
/**
Fires when an event listener was added.
An object with `listener` and `eventName` (if `on` or `off` was used) is provided as event data.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
emitter.on(Emittery.listenerAdded, ({data: {listener, eventName}}) => {
console.log(listener);
//=> ({data}) => {}
console.log(eventName);
//=> 'π¦'
});
emitter.on('π¦', ({data}) => {
// Handle data
});
```
*/
static readonly listenerAdded: typeof listenerAdded;
/**
Fires when an event listener was removed.
An object with `listener` and `eventName` (if `on` or `off` was used) is provided as event data.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
const off = emitter.on('π¦', ({data}) => {
// Handle data
});
emitter.on(Emittery.listenerRemoved, ({data: {listener, eventName}}) => {
console.log(listener);
//=> ({data}) => {}
console.log(eventName);
//=> 'π¦'
});
off();
```
*/
static readonly listenerRemoved: typeof listenerRemoved;
/**
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.
@example
```
import Emittery from 'emittery';
@Emittery.mixin('emittery')
class MyClass {}
const instance = new MyClass();
instance.emit('event');
```
*/
static mixin(
emitteryPropertyName: string | symbol,
methodNames?: readonly string[]
): <T extends abstract new (...arguments_: readonly any[]) => any>(klass: T, context?: ClassDecoratorContext<T>) => T;
/**
Debugging options for the current instance.
*/
debug: DebugOptions<EventData>;
/**
Create a new Emittery instance with the specified options.
@returns An instance of Emittery that you can use to listen for and emit events.
*/
constructor(options?: Options<EventData>);
/**
Subscribe to one or more events.
Using the same listener multiple times for the same event will result in only one method call per emitted event.
@returns An unsubscribe method, which is also {@link Disposable} (can be used with `using`).
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
emitter.on('π¦', ({data}) => {
console.log(data);
});
emitter.on(['π¦', 'πΆ'], ({name, data}) => {
console.log(name, data);
});
emitter.emit('π¦', 'π'); // log => 'π' and 'π¦ π'
emitter.emit('πΆ', 'π'); // log => 'πΆ π'
```
@example
```
// With AbortSignal
const abortController = new AbortController();
emitter.on('π', ({data}) => {
console.log(data);
}, {signal: abortController.signal});
abortController.abort();
```
@example
```
// With `using` for automatic cleanup
{
using off = emitter.on('π¦', ({data}) => {
console.log(data);
});
await emitter.emit('π¦', 'π'); // Logs 'π'
}
await emitter.emit('π¦', 'π'); // Nothing happens
```
*/
on<Name extends keyof AllEventData>(
eventName: Name | readonly Name[],
listener: (event: EventDataPair<AllEventData, Name>) => void | Promise<void>,
options?: {signal?: AbortSignal}
): UnsubscribeFunction;
/**
Get an async iterator which buffers data each time an event is emitted.
Call `return()` on the iterator to remove the subscription. You can also pass an {@link AbortSignal} to cancel the subscription externally, or use `await using` for automatic cleanup.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
for await (const {data} of emitter.events('π¦')) {
console.log(data);
if (data === 'π2') {
break; // Revoke the subscription when we see the value 'π2'.
}
}
```
@example
```
// With multiple event names
for await (const {name, data} of emitter.events(['π¦', 'π¦'])) {
console.log(name, data);
}
```
@example
```
// With `await using` for automatic cleanup
{
await using iterator = emitter.events('π¦');
for await (const {data} of iterator) {
console.log(data);
}
} // Subscription is automatically revoked
```
*/
events<Name extends keyof EventData>(
eventName: Name | readonly Name[],
options?: {signal?: AbortSignal}
): AsyncIterableIterator<EventDataPair<EventData, Name>> & AsyncDisposable;
/**
Remove one or more event subscriptions.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
const listener = ({data}) => {
console.log(data);
};
emitter.on(['π¦', 'πΆ', 'π¦'], listener);
await emitter.emit('π¦', 'a');
await emitter.emit('πΆ', 'b');
await emitter.emit('π¦', 'c');
emitter.off('π¦', listener);
emitter.off(['πΆ', 'π¦'], listener);
await emitter.emit('π¦', 'a'); // Nothing happens
await emitter.emit('πΆ', 'b'); // Nothing happens
await emitter.emit('π¦', 'c'); // Nothing happens
```
*/
off<Name extends keyof AllEventData>(
eventName: Name | readonly Name[],
listener: (event: EventDataPair<AllEventData, Name>) => void | Promise<void>
): void;
/**
Subscribe to one or more events only once. It will be unsubscribed after the first event that matches the predicate (if provided).
The second argument can be a predicate function or an options object with `predicate` and/or `signal`.
@returns The promise of event data when `eventName` is emitted and predicate matches (if provided). The promise has an `off` method to cancel the subscription.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
const {data} = await emitter.once('π¦');
console.log(data);
//=> 'π'
```
@example
```
// With multiple event names
const {name, data} = await emitter.once(['π¦', 'πΆ']);
console.log(name, data);
```
@example
```
// With predicate
const event = await emitter.once('data', ({data}) => data.ok === true);
console.log(event.data);
//=> {ok: true, value: 42}
```
@example
```
// With AbortSignal for timeout
await emitter.once('ready', {signal: AbortSignal.timeout(5000)});
```
@example
```
// Cancel with .off()
const promise = emitter.once('π¦');
promise.off();
```
*/
once<Name extends keyof AllEventData>(
eventName: Name | readonly Name[],
predicate?: (event: EventDataPair<AllEventData, Name>) => boolean
): EmitteryOncePromise<EventDataPair<AllEventData, Name>>;
once<Name extends keyof AllEventData>(
eventName: Name | readonly Name[],
options?: {
predicate?: (event: EventDataPair<AllEventData, Name>) => boolean;
signal?: AbortSignal;
}
): EmitteryOncePromise<EventDataPair<AllEventData, Name>>;
/**
Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.
@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 listeners throw/reject, the returned promise rejects with an `AggregateError` β all listener errors are collected in `error.errors`, so no errors are silently lost. All listeners always run to completion, even if some throw or reject.
*/
emit<Name extends DatalessEvents>(eventName: Name): Promise<void>;
emit<Name extends keyof EventData>(
eventName: Name,
eventData: EventData[Name]
): Promise<void>;
/**
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.
If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will *not* be called.
@returns A promise that resolves when all the event listeners are done.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
emitter.on('π¦', async () => {
console.log('listener 1 start');
await new Promise(resolve => setTimeout(resolve, 100));
console.log('listener 1 done');
});
emitter.on('π¦', () => {
console.log('listener 2'); // Only runs after listener 1 is done
});
await emitter.emitSerial('π¦');
```
*/
emitSerial<Name extends DatalessEvents>(eventName: Name): Promise<void>;
emitSerial<Name extends keyof EventData>(
eventName: Name,
eventData: EventData[Name]
): Promise<void>;
/**
Subscribe to be notified about any event.
@returns A method to unsubscribe, which is also {@link Disposable}.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
const off = emitter.onAny(({name, data}) => {
console.log(name, data);
});
emitter.emit('π¦', 'π'); // log => 'π¦ π'
off();
```
*/
onAny(
listener: (event: EventDataPair<EventData, keyof EventData>) => void | Promise<void>,
options?: {signal?: AbortSignal}
): UnsubscribeFunction;
/**
Get an async iterator which buffers an event object each time an event is emitted.
Call `return()` on the iterator to remove the subscription. You can also pass an {@link AbortSignal} to cancel the subscription externally, or use `await using` for automatic cleanup.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
for await (const {name, data} of emitter.anyEvent()) {
console.log(name, data);
}
```
@example
```
// With `await using` for automatic cleanup
{
await using iterator = emitter.anyEvent();
for await (const {name, data} of iterator) {
console.log(name, data);
}
} // Subscription is automatically revoked
```
*/
anyEvent(options?: {signal?: AbortSignal}): AsyncIterableIterator<EventDataPair<EventData, keyof EventData>> & AsyncDisposable;
/**
Remove an `onAny` subscription.
*/
offAny(
listener: (event: EventDataPair<EventData, keyof EventData>) => void | Promise<void>
): void;
/**
Clear all event listeners on the instance.
If `eventNames` is given, only the listeners for those events are cleared. Accepts a single event name or an array.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
emitter.on('π¦', listener);
emitter.on('πΆ', listener);
emitter.clearListeners('π¦'); // Clear a single event
emitter.clearListeners(['πΆ', 'π¦']); // Clear multiple events
emitter.clearListeners(); // Clear all events
```
*/
clearListeners<Name extends keyof EventData>(eventName?: Name | readonly Name[]): void;
/**
Register a function to be called when the first `.on()` listener subscribes to `eventName`. The `initFn` can optionally return a cleanup (deinit) function, which is called when the last `.on()` listener unsubscribes (or when `clearListeners()` removes all listeners for that event).
If `.on()` listeners already exist when `init()` is called, `initFn` is called immediately.
Note: Lifecycle hooks only apply to `.on()` listeners. Subscriptions via `.events()` async iterators do not trigger the init or deinit functions.
@returns An unsubscribe function. Calling it removes the init/deinit hooks, and if the init is currently active, it calls deinit immediately.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
emitter.init('mouse', () => {
terminal.grabInput({mouse: 'button'});
terminal.on('mouse', (name, data) => {
emitter.emit('mouse', data);
});
return () => {
terminal.releaseInput();
};
});
// Init is called when the first listener subscribes
const off = emitter.on('mouse', handler);
// Adding more listeners does not call init again
emitter.on('mouse', anotherHandler);
// Removing one listener does not call deinit yet
off();
// Deinit is called when the last listener unsubscribes
emitter.off('mouse', anotherHandler);
```
@example
```
// With `using` for automatic cleanup of hooks
{
using removeInit = emitter.init('mouse', () => {
startListening();
return () => stopListening();
});
} // init/deinit hooks are automatically removed
```
*/
init<Name extends keyof EventData>(
eventName: Name,
initFn: () => (() => void) | void
): UnsubscribeFunction;
/**
The number of listeners for the `eventName` or all events if not specified.
@example
```
import Emittery from 'emittery';
const emitter = new Emittery();
emitter.on('π¦', listener);
emitter.on('πΆ', listener);
emitter.listenerCount('π¦'); // 1
emitter.listenerCount(); // 2
```
*/
listenerCount<Name extends keyof EventData>(eventName?: Name | readonly Name[]): number;
/**
Log debug information if debug mode is enabled (either globally via `Emittery.isDebugEnabled` or per-instance via `debug.enabled`).
*/
logIfDebugEnabled<Name extends keyof EventData>(type: string, eventName?: Name, eventData?: EventData[Name]): void;
/**
Bind the given `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the `target` object.
@example
```
import Emittery from 'emittery';
const object = {};
new Emittery().bindMethods(object);
object.emit('event');
```
*/
bindMethods(target: Record<string, unknown>, methodNames?: readonly string[]): void;
}