1 | import { EventEmitter } from 'events';
|
---|
2 | import { AsyncResource } from 'async_hooks';
|
---|
3 |
|
---|
4 | const kEventEmitter = Symbol('kEventEmitter');
|
---|
5 | const kAsyncResource = Symbol('kAsyncResource');
|
---|
6 |
|
---|
7 | type EventEmitterOptions = typeof EventEmitter extends {
|
---|
8 | new (options?: infer T) : EventEmitter;
|
---|
9 | } ? T : never;
|
---|
10 |
|
---|
11 | type AsyncResourceOptions = typeof AsyncResource extends {
|
---|
12 | new (name : string, options?: infer T) : AsyncResource;
|
---|
13 | } ? T : never;
|
---|
14 |
|
---|
15 | type Options = EventEmitterOptions & AsyncResourceOptions & {
|
---|
16 | name?: string;
|
---|
17 | };
|
---|
18 |
|
---|
19 | class EventEmitterReferencingAsyncResource extends AsyncResource {
|
---|
20 | [kEventEmitter] : EventEmitter;
|
---|
21 |
|
---|
22 | constructor (ee: EventEmitter, type: string, options?: AsyncResourceOptions) {
|
---|
23 | super(type, options);
|
---|
24 | this[kEventEmitter] = ee;
|
---|
25 | }
|
---|
26 |
|
---|
27 | get eventEmitter () : EventEmitter {
|
---|
28 | return this[kEventEmitter];
|
---|
29 | }
|
---|
30 | }
|
---|
31 |
|
---|
32 | class EventEmitterAsyncResource extends EventEmitter {
|
---|
33 | [kAsyncResource] : EventEmitterReferencingAsyncResource;
|
---|
34 |
|
---|
35 | constructor (options?: Options | string) {
|
---|
36 | let name;
|
---|
37 | if (typeof options === 'string') {
|
---|
38 | name = options;
|
---|
39 | options = undefined;
|
---|
40 | } else {
|
---|
41 | name = options?.name || new.target.name;
|
---|
42 | }
|
---|
43 | super(options);
|
---|
44 |
|
---|
45 | this[kAsyncResource] =
|
---|
46 | new EventEmitterReferencingAsyncResource(this, name, options);
|
---|
47 | }
|
---|
48 |
|
---|
49 | emit (event: string | symbol, ...args: any[]) : boolean {
|
---|
50 | return this.asyncResource.runInAsyncScope(
|
---|
51 | super.emit, this, event, ...args);
|
---|
52 | }
|
---|
53 |
|
---|
54 | emitDestroy () : void {
|
---|
55 | this.asyncResource.emitDestroy();
|
---|
56 | }
|
---|
57 |
|
---|
58 | asyncId () : number {
|
---|
59 | return this.asyncResource.asyncId();
|
---|
60 | }
|
---|
61 |
|
---|
62 | triggerAsyncId () : number {
|
---|
63 | return this.asyncResource.triggerAsyncId();
|
---|
64 | }
|
---|
65 |
|
---|
66 | get asyncResource () : EventEmitterReferencingAsyncResource {
|
---|
67 | return this[kAsyncResource];
|
---|
68 | }
|
---|
69 |
|
---|
70 | static get EventEmitterAsyncResource () { return EventEmitterAsyncResource; }
|
---|
71 | }
|
---|
72 |
|
---|
73 | export = EventEmitterAsyncResource;
|
---|