Skip to content

Commit 038149e

Browse files
committed
fix: apply event worker context to custom events
1 parent 6a237c7 commit 038149e

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

packages/commandkit/src/events/CommandKitEventsChannel.ts

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import EventEmitter from 'node:events';
22
import type { CommandKit } from '../CommandKit';
33
import type { AsyncFunction, GenericFunction } from '../context/async-context';
4+
import { runInEventWorkerContext } from '../app/events/EventWorkerContext';
45

56
export type ListenerFunction = GenericFunction | AsyncFunction;
67

@@ -20,15 +21,24 @@ export class CommandKitEventsChannel {
2021
}
2122

2223
public on(namespace: string, event: string, listener: ListenerFunction) {
23-
this.emitter.on(`${namespace}:${event}`, listener);
24+
this.emitter.on(
25+
`${namespace}:${event}`,
26+
this.prepareListener(namespace, event, listener),
27+
);
2428
}
2529

2630
public off(namespace: string, event: string, listener: ListenerFunction) {
27-
this.emitter.off(`${namespace}:${event}`, listener);
31+
this.emitter.off(
32+
`${namespace}:${event}`,
33+
this.prepareListener(namespace, event, listener),
34+
);
2835
}
2936

3037
public once(namespace: string, event: string, listener: ListenerFunction) {
31-
this.emitter.once(`${namespace}:${event}`, listener);
38+
this.emitter.once(
39+
`${namespace}:${event}`,
40+
this.prepareListener(namespace, event, listener),
41+
);
3242
}
3343

3444
public emit(namespace: string, event: string, ...args: any[]) {
@@ -44,4 +54,28 @@ export class CommandKitEventsChannel {
4454
this.emitter.removeAllListeners(namespace);
4555
}
4656
}
57+
58+
private prepareListener<L extends ListenerFunction>(
59+
namespace: string,
60+
event: string,
61+
listener: L,
62+
): L {
63+
return ((...args) => {
64+
return runInEventWorkerContext(
65+
{
66+
arguments: args,
67+
commandkit: this.commandkit,
68+
data: {
69+
event,
70+
namespace,
71+
listeners: [],
72+
path: `virtual:${namespace}/${event}`,
73+
},
74+
event,
75+
namespace,
76+
},
77+
listener,
78+
);
79+
}) as L;
80+
}
4781
}

0 commit comments

Comments
 (0)