@hazeljs/event-emitter 0.2.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2024 HazelJS Team
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+
19
+ ---
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # @hazeljs/event-emitter
2
+
3
+ **Event Emitter Module for HazelJS**
4
+
5
+ Event-driven architecture with decorators, similar to `@nestjs/event-emitter`. Built on [eventemitter2](https://github.com/EventEmitter2/EventEmitter2) with support for wildcards, namespaces, and async listeners.
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@hazeljs/event-emitter.svg)](https://www.npmjs.com/package/@hazeljs/event-emitter)
8
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
9
+
10
+ ## Features
11
+
12
+ - **Decorator-Based API** - `@OnEvent()` for declarative event listeners
13
+ - **DI Integration** - Inject `EventEmitterService` anywhere in your app
14
+ - **Wildcards** - Listen to event patterns (e.g. `order.*`) when enabled
15
+ - **Async Listeners** - Support for async event handlers
16
+ - **Error Handling** - Configurable error suppression for listeners
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install @hazeljs/event-emitter
22
+ ```
23
+
24
+ ## Quick Start
25
+
26
+ ### 1. Import EventEmitterModule
27
+
28
+ ```typescript
29
+ import { HazelModule } from '@hazeljs/core';
30
+ import { EventEmitterModule } from '@hazeljs/event-emitter';
31
+
32
+ @HazelModule({
33
+ imports: [EventEmitterModule.forRoot()],
34
+ providers: [OrderService, OrderEventHandler],
35
+ })
36
+ export class AppModule {}
37
+ ```
38
+
39
+ ### 2. Emit Events
40
+
41
+ ```typescript
42
+ import { Injectable } from '@hazeljs/core';
43
+ import { EventEmitterService } from '@hazeljs/event-emitter';
44
+
45
+ @Injectable()
46
+ export class OrderService {
47
+ constructor(private eventEmitter: EventEmitterService) {}
48
+
49
+ createOrder(order: Order) {
50
+ // ... create order
51
+ this.eventEmitter.emit('order.created', { orderId: order.id, order });
52
+ }
53
+ }
54
+ ```
55
+
56
+ ### 3. Listen to Events
57
+
58
+ ```typescript
59
+ import { Injectable } from '@hazeljs/core';
60
+ import { OnEvent, EventEmitterModule } from '@hazeljs/event-emitter';
61
+
62
+ @Injectable()
63
+ export class OrderEventHandler {
64
+ @OnEvent('order.created')
65
+ handleOrderCreated(payload: { orderId: string; order: Order }) {
66
+ console.log('Order created:', payload.orderId);
67
+ }
68
+ }
69
+ ```
70
+
71
+ ### 4. Register Listeners
72
+
73
+ After your app initializes, register listeners from providers that have `@OnEvent` decorators:
74
+
75
+ ```typescript
76
+ import { EventEmitterModule } from '@hazeljs/event-emitter';
77
+
78
+ // Register from provider classes (resolves from DI container)
79
+ EventEmitterModule.registerListenersFromProviders([OrderEventHandler]);
80
+
81
+ // Or register from a specific instance
82
+ const orderHandler = container.resolve(OrderEventHandler);
83
+ EventEmitterModule.registerListenersFromProvider(orderHandler);
84
+ ```
85
+
86
+ ## Configuration
87
+
88
+ ```typescript
89
+ EventEmitterModule.forRoot({
90
+ wildcard: true, // Enable 'order.*' style patterns
91
+ delimiter: '.', // Namespace delimiter
92
+ maxListeners: 10, // Max listeners per event
93
+ isGlobal: true, // Global module (default)
94
+ });
95
+ ```
96
+
97
+ ## @OnEvent Options
98
+
99
+ ```typescript
100
+ @OnEvent('order.created', { async: true })
101
+ async handleOrderCreated(payload: OrderCreatedEvent) {
102
+ await sendEmail(payload);
103
+ }
104
+
105
+ @OnEvent('order.*', { suppressErrors: false })
106
+ handleOrderEvents(payload: unknown) {
107
+ // Errors will be rethrown
108
+ }
109
+ ```
110
+
111
+ ## API
112
+
113
+ - **EventEmitterModule** - Module with `forRoot(options?)` and `registerListenersFromProvider(provider)`
114
+ - **EventEmitterService** - Injectable service extending EventEmitter2 (`emit`, `emitAsync`, `on`, etc.)
115
+ - **OnEvent(event, options?)** - Decorator for event listeners
116
+ - **getOnEventMetadata(target)** - Get @OnEvent metadata from a class
@@ -0,0 +1,68 @@
1
+ import { EventEmitterService } from './event-emitter.service';
2
+ import type { EventEmitterModuleOptions } from './event-emitter.types';
3
+ /**
4
+ * Event emitter module options
5
+ */
6
+ export interface EventEmitterModuleConfig extends EventEmitterModuleOptions {
7
+ /**
8
+ * Whether this is a global module
9
+ * @default true
10
+ */
11
+ isGlobal?: boolean;
12
+ }
13
+ /**
14
+ * Event emitter module for HazelJS
15
+ * Provides event-driven architecture with decorators, similar to @nestjs/event-emitter
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // app.module.ts
20
+ * @HazelModule({
21
+ * imports: [
22
+ * EventEmitterModule.forRoot({ wildcard: true })
23
+ * ],
24
+ * controllers: [AppController],
25
+ * providers: [OrderService, OrderEventHandler]
26
+ * })
27
+ * export class AppModule {}
28
+ * ```
29
+ */
30
+ export declare class EventEmitterModule {
31
+ /**
32
+ * Configure event emitter module with options (passed to eventemitter2)
33
+ */
34
+ static forRoot(options?: EventEmitterModuleConfig): {
35
+ module: typeof EventEmitterModule;
36
+ providers: Array<{
37
+ provide: typeof EventEmitterService;
38
+ useFactory: () => EventEmitterService;
39
+ }>;
40
+ exports: Array<typeof EventEmitterService>;
41
+ global: boolean;
42
+ };
43
+ /**
44
+ * Register event listeners from providers that have @OnEvent decorators
45
+ * Call this after providers are instantiated (e.g. from a module's providers)
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const orderHandler = container.resolve(OrderEventHandler);
50
+ * EventEmitterModule.registerListenersFromProvider(orderHandler);
51
+ * ```
52
+ */
53
+ static registerListenersFromProvider(provider: object): void;
54
+ /**
55
+ * Register event listeners from multiple provider classes
56
+ * Resolves each from the container and registers their @OnEvent handlers
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * EventEmitterModule.registerListenersFromProviders([
61
+ * OrderEventHandler,
62
+ * UserEventHandler,
63
+ * ]);
64
+ * ```
65
+ */
66
+ static registerListenersFromProviders(providerClasses: (new (...args: unknown[]) => object)[]): void;
67
+ }
68
+ //# sourceMappingURL=event-emitter.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-emitter.module.d.ts","sourceRoot":"","sources":["../src/event-emitter.module.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAEvE;;GAEG;AACH,MAAM,WAAW,wBAAyB,SAAQ,yBAAyB;IACzE;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,qBAIa,kBAAkB;IAC7B;;OAEG;IACH,MAAM,CAAC,OAAO,CAAC,OAAO,GAAE,wBAA6B,GAAG;QACtD,MAAM,EAAE,OAAO,kBAAkB,CAAC;QAClC,SAAS,EAAE,KAAK,CAAC;YACf,OAAO,EAAE,OAAO,mBAAmB,CAAC;YACpC,UAAU,EAAE,MAAM,mBAAmB,CAAC;SACvC,CAAC,CAAC;QACH,OAAO,EAAE,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;QAC3C,MAAM,EAAE,OAAO,CAAC;KACjB;IAkBD;;;;;;;;;OASG;IACH,MAAM,CAAC,6BAA6B,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IA+D5D;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,8BAA8B,CACnC,eAAe,EAAE,CAAC,KAAK,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,MAAM,CAAC,EAAE,GACtD,IAAI;CAWR"}
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ var EventEmitterModule_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.EventEmitterModule = void 0;
14
+ const core_1 = require("@hazeljs/core");
15
+ const core_2 = require("@hazeljs/core");
16
+ const core_3 = __importDefault(require("@hazeljs/core"));
17
+ const event_emitter_service_1 = require("./event-emitter.service");
18
+ const on_event_decorator_1 = require("./on-event.decorator");
19
+ /**
20
+ * Event emitter module for HazelJS
21
+ * Provides event-driven architecture with decorators, similar to @nestjs/event-emitter
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * // app.module.ts
26
+ * @HazelModule({
27
+ * imports: [
28
+ * EventEmitterModule.forRoot({ wildcard: true })
29
+ * ],
30
+ * controllers: [AppController],
31
+ * providers: [OrderService, OrderEventHandler]
32
+ * })
33
+ * export class AppModule {}
34
+ * ```
35
+ */
36
+ let EventEmitterModule = EventEmitterModule_1 = class EventEmitterModule {
37
+ /**
38
+ * Configure event emitter module with options (passed to eventemitter2)
39
+ */
40
+ static forRoot(options = {}) {
41
+ const { isGlobal = true, ...eeOptions } = options;
42
+ core_3.default.info('Configuring event emitter module...');
43
+ const eventEmitterProvider = {
44
+ provide: event_emitter_service_1.EventEmitterService,
45
+ useFactory: () => new event_emitter_service_1.EventEmitterService(eeOptions),
46
+ };
47
+ return {
48
+ module: EventEmitterModule_1,
49
+ providers: [eventEmitterProvider],
50
+ exports: [event_emitter_service_1.EventEmitterService],
51
+ global: isGlobal,
52
+ };
53
+ }
54
+ /**
55
+ * Register event listeners from providers that have @OnEvent decorators
56
+ * Call this after providers are instantiated (e.g. from a module's providers)
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * const orderHandler = container.resolve(OrderEventHandler);
61
+ * EventEmitterModule.registerListenersFromProvider(orderHandler);
62
+ * ```
63
+ */
64
+ static registerListenersFromProvider(provider) {
65
+ try {
66
+ const container = core_2.Container.getInstance();
67
+ const eventEmitter = container.resolve(event_emitter_service_1.EventEmitterService);
68
+ if (!eventEmitter) {
69
+ core_3.default.warn('EventEmitterService not found in DI container');
70
+ return;
71
+ }
72
+ const metadataList = (0, on_event_decorator_1.getOnEventMetadata)(provider);
73
+ for (const meta of metadataList) {
74
+ const instance = provider;
75
+ const callback = instance[meta.methodName];
76
+ if (typeof callback !== 'function') {
77
+ core_3.default.warn(`@OnEvent: method "${meta.methodName}" not found on ${provider.constructor?.name}`);
78
+ continue;
79
+ }
80
+ const boundCallback = callback.bind(provider);
81
+ const opts = meta.options ?? {};
82
+ if (opts.async) {
83
+ eventEmitter.on(meta.event, async (...args) => {
84
+ try {
85
+ await boundCallback(...args);
86
+ }
87
+ catch (err) {
88
+ if (!opts.suppressErrors)
89
+ throw err;
90
+ core_3.default.error('Event listener error:', err);
91
+ }
92
+ }, opts);
93
+ }
94
+ else {
95
+ eventEmitter.on(meta.event, (...args) => {
96
+ try {
97
+ return boundCallback(...args);
98
+ }
99
+ catch (err) {
100
+ if (!opts.suppressErrors)
101
+ throw err;
102
+ core_3.default.error('Event listener error:', err);
103
+ }
104
+ }, opts);
105
+ }
106
+ core_3.default.debug(`Registered event listener: ${String(meta.event)} on ${provider.constructor?.name}`);
107
+ }
108
+ }
109
+ catch (error) {
110
+ core_3.default.error('Error registering event listeners from provider:', error);
111
+ }
112
+ }
113
+ /**
114
+ * Register event listeners from multiple provider classes
115
+ * Resolves each from the container and registers their @OnEvent handlers
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * EventEmitterModule.registerListenersFromProviders([
120
+ * OrderEventHandler,
121
+ * UserEventHandler,
122
+ * ]);
123
+ * ```
124
+ */
125
+ static registerListenersFromProviders(providerClasses) {
126
+ const container = core_2.Container.getInstance();
127
+ for (const Cls of providerClasses) {
128
+ const instance = container.resolve(Cls);
129
+ if (instance) {
130
+ this.registerListenersFromProvider(instance);
131
+ }
132
+ else {
133
+ core_3.default.warn(`Provider ${Cls.name} not found in DI container`);
134
+ }
135
+ }
136
+ }
137
+ };
138
+ exports.EventEmitterModule = EventEmitterModule;
139
+ exports.EventEmitterModule = EventEmitterModule = EventEmitterModule_1 = __decorate([
140
+ (0, core_1.HazelModule)({
141
+ providers: [event_emitter_service_1.EventEmitterService],
142
+ exports: [event_emitter_service_1.EventEmitterService],
143
+ })
144
+ ], EventEmitterModule);
@@ -0,0 +1,33 @@
1
+ import EventEmitter2 from 'eventemitter2';
2
+ import type { EventEmitterModuleOptions } from './event-emitter.types';
3
+ /**
4
+ * Event emitter service - wraps EventEmitter2 for DI injection
5
+ * Use this service to emit events throughout your application
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * @Injectable()
10
+ * class OrderService {
11
+ * constructor(private eventEmitter: EventEmitterService) {}
12
+ *
13
+ * createOrder(order: Order) {
14
+ * // ... create order
15
+ * this.eventEmitter.emit('order.created', new OrderCreatedEvent(order));
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ export declare class EventEmitterService extends EventEmitter2 {
21
+ constructor(options?: EventEmitterModuleOptions);
22
+ /**
23
+ * Emit an event
24
+ * @param event - Event name
25
+ * @param values - Payload values (spread as arguments to listeners)
26
+ */
27
+ emit(event: string | symbol, ...values: unknown[]): boolean;
28
+ /**
29
+ * Emit an event asynchronously (listeners receive a promise)
30
+ */
31
+ emitAsync(event: string | symbol, ...values: unknown[]): Promise<unknown[]>;
32
+ }
33
+ //# sourceMappingURL=event-emitter.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-emitter.service.d.ts","sourceRoot":"","sources":["../src/event-emitter.service.ts"],"names":[],"mappings":"AACA,OAAO,aAAa,MAAM,eAAe,CAAC;AAC1C,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAEvE;;;;;;;;;;;;;;;;GAgBG;AACH,qBACa,mBAAoB,SAAQ,aAAa;gBACxC,OAAO,CAAC,EAAE,yBAAyB;IAI/C;;;;OAIG;IACM,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO;IAIpE;;OAEG;IACM,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;CAGrF"}
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.EventEmitterService = void 0;
16
+ const core_1 = require("@hazeljs/core");
17
+ const eventemitter2_1 = __importDefault(require("eventemitter2"));
18
+ /**
19
+ * Event emitter service - wraps EventEmitter2 for DI injection
20
+ * Use this service to emit events throughout your application
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * @Injectable()
25
+ * class OrderService {
26
+ * constructor(private eventEmitter: EventEmitterService) {}
27
+ *
28
+ * createOrder(order: Order) {
29
+ * // ... create order
30
+ * this.eventEmitter.emit('order.created', new OrderCreatedEvent(order));
31
+ * }
32
+ * }
33
+ * ```
34
+ */
35
+ let EventEmitterService = class EventEmitterService extends eventemitter2_1.default {
36
+ constructor(options) {
37
+ super(options ?? {});
38
+ }
39
+ /**
40
+ * Emit an event
41
+ * @param event - Event name
42
+ * @param values - Payload values (spread as arguments to listeners)
43
+ */
44
+ emit(event, ...values) {
45
+ return super.emit(event, ...values);
46
+ }
47
+ /**
48
+ * Emit an event asynchronously (listeners receive a promise)
49
+ */
50
+ emitAsync(event, ...values) {
51
+ return super.emitAsync(event, ...values);
52
+ }
53
+ };
54
+ exports.EventEmitterService = EventEmitterService;
55
+ exports.EventEmitterService = EventEmitterService = __decorate([
56
+ (0, core_1.Injectable)(),
57
+ __metadata("design:paramtypes", [Object])
58
+ ], EventEmitterService);
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Event emitter configuration options (passed to eventemitter2)
3
+ */
4
+ export interface EventEmitterModuleOptions {
5
+ /**
6
+ * Use wildcards for event names (e.g. 'order.*')
7
+ * @default false
8
+ */
9
+ wildcard?: boolean;
10
+ /**
11
+ * Delimiter used to segment namespaces
12
+ * @default '.'
13
+ */
14
+ delimiter?: string;
15
+ /**
16
+ * Emit newListener event when adding listeners
17
+ * @default false
18
+ */
19
+ newListener?: boolean;
20
+ /**
21
+ * Emit removeListener event when removing listeners
22
+ * @default false
23
+ */
24
+ removeListener?: boolean;
25
+ /**
26
+ * Maximum number of listeners per event
27
+ * @default 10
28
+ */
29
+ maxListeners?: number;
30
+ /**
31
+ * Show event name in memory leak message
32
+ * @default false
33
+ */
34
+ verboseMemoryLeak?: boolean;
35
+ /**
36
+ * Disable throwing uncaughtException if error event has no listeners
37
+ * @default false
38
+ */
39
+ ignoreErrors?: boolean;
40
+ }
41
+ /**
42
+ * Options for @OnEvent decorator
43
+ */
44
+ export interface OnEventOptions {
45
+ /**
46
+ * If true, listener runs asynchronously
47
+ * @default false
48
+ */
49
+ async?: boolean;
50
+ /**
51
+ * If true, prepends listener instead of appending
52
+ * @default false
53
+ */
54
+ prependListener?: boolean;
55
+ /**
56
+ * If true, errors in the handler are suppressed (not rethrown)
57
+ * @default true
58
+ */
59
+ suppressErrors?: boolean;
60
+ }
61
+ //# sourceMappingURL=event-emitter.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-emitter.types.d.ts","sourceRoot":"","sources":["../src/event-emitter.types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;;OAGG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAE5B;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhB;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B;;;OAGG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @hazeljs/event-emitter - Event emitter module for HazelJS
3
+ *
4
+ * Event-driven architecture with decorators, similar to @nestjs/event-emitter.
5
+ * Built on eventemitter2 - supports wildcards, namespaces, and async listeners.
6
+ */
7
+ export { EventEmitterModule, type EventEmitterModuleConfig } from './event-emitter.module';
8
+ export { EventEmitterService } from './event-emitter.service';
9
+ export { OnEvent, getOnEventMetadata } from './on-event.decorator';
10
+ export type { OnEventMetadata } from './on-event.decorator';
11
+ export type { EventEmitterModuleOptions, OnEventOptions } from './event-emitter.types';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,kBAAkB,EAAE,KAAK,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACnE,YAAY,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,YAAY,EAAE,yBAAyB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ /**
3
+ * @hazeljs/event-emitter - Event emitter module for HazelJS
4
+ *
5
+ * Event-driven architecture with decorators, similar to @nestjs/event-emitter.
6
+ * Built on eventemitter2 - supports wildcards, namespaces, and async listeners.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.getOnEventMetadata = exports.OnEvent = exports.EventEmitterService = exports.EventEmitterModule = void 0;
10
+ var event_emitter_module_1 = require("./event-emitter.module");
11
+ Object.defineProperty(exports, "EventEmitterModule", { enumerable: true, get: function () { return event_emitter_module_1.EventEmitterModule; } });
12
+ var event_emitter_service_1 = require("./event-emitter.service");
13
+ Object.defineProperty(exports, "EventEmitterService", { enumerable: true, get: function () { return event_emitter_service_1.EventEmitterService; } });
14
+ var on_event_decorator_1 = require("./on-event.decorator");
15
+ Object.defineProperty(exports, "OnEvent", { enumerable: true, get: function () { return on_event_decorator_1.OnEvent; } });
16
+ Object.defineProperty(exports, "getOnEventMetadata", { enumerable: true, get: function () { return on_event_decorator_1.getOnEventMetadata; } });
@@ -0,0 +1,36 @@
1
+ import 'reflect-metadata';
2
+ import { OnEventOptions } from './event-emitter.types';
3
+ /**
4
+ * Metadata key for event listeners
5
+ */
6
+ export declare const ON_EVENT_METADATA_KEY: unique symbol;
7
+ export interface OnEventMetadata {
8
+ event: string | symbol | string[];
9
+ methodName: string;
10
+ options?: OnEventOptions;
11
+ }
12
+ /**
13
+ * Decorator to mark a method as an event listener
14
+ * @param event - Event name(s) to listen for. With wildcards enabled, supports patterns like 'order.*'
15
+ * @param options - Listener options
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * @OnEvent('order.created')
20
+ * handleOrderCreated(payload: OrderCreatedEvent) {
21
+ * // handle event
22
+ * }
23
+ *
24
+ * // With wildcards (when EventEmitterModule.forRoot({ wildcard: true }))
25
+ * @OnEvent('order.*')
26
+ * handleOrderEvents(payload: OrderCreatedEvent | OrderUpdatedEvent) {
27
+ * // handle any order event
28
+ * }
29
+ * ```
30
+ */
31
+ export declare function OnEvent(event: string | symbol | string[], options?: OnEventOptions): MethodDecorator;
32
+ /**
33
+ * Get @OnEvent metadata from a class
34
+ */
35
+ export declare function getOnEventMetadata(target: object): OnEventMetadata[];
36
+ //# sourceMappingURL=on-event.decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"on-event.decorator.d.ts","sourceRoot":"","sources":["../src/on-event.decorator.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvD;;GAEG;AACH,eAAO,MAAM,qBAAqB,eAAmC,CAAC;AAEtE,MAAM,WAAW,eAAe;IAC9B,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,CAAC;IAClC,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,cAAc,CAAC;CAC1B;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,OAAO,CACrB,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,EACjC,OAAO,CAAC,EAAE,cAAc,GACvB,eAAe,CAgBjB;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,EAAE,CAEpE"}
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ON_EVENT_METADATA_KEY = void 0;
4
+ exports.OnEvent = OnEvent;
5
+ exports.getOnEventMetadata = getOnEventMetadata;
6
+ require("reflect-metadata");
7
+ /**
8
+ * Metadata key for event listeners
9
+ */
10
+ exports.ON_EVENT_METADATA_KEY = Symbol('event-emitter:on-event');
11
+ /**
12
+ * Decorator to mark a method as an event listener
13
+ * @param event - Event name(s) to listen for. With wildcards enabled, supports patterns like 'order.*'
14
+ * @param options - Listener options
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * @OnEvent('order.created')
19
+ * handleOrderCreated(payload: OrderCreatedEvent) {
20
+ * // handle event
21
+ * }
22
+ *
23
+ * // With wildcards (when EventEmitterModule.forRoot({ wildcard: true }))
24
+ * @OnEvent('order.*')
25
+ * handleOrderEvents(payload: OrderCreatedEvent | OrderUpdatedEvent) {
26
+ * // handle any order event
27
+ * }
28
+ * ```
29
+ */
30
+ function OnEvent(event, options) {
31
+ return (target, propertyKey, _descriptor) => {
32
+ const existing = Reflect.getMetadata(exports.ON_EVENT_METADATA_KEY, target.constructor) || [];
33
+ existing.push({
34
+ event,
35
+ methodName: propertyKey.toString(),
36
+ options: {
37
+ suppressErrors: true,
38
+ ...options,
39
+ },
40
+ });
41
+ Reflect.defineMetadata(exports.ON_EVENT_METADATA_KEY, existing, target.constructor);
42
+ };
43
+ }
44
+ /**
45
+ * Get @OnEvent metadata from a class
46
+ */
47
+ function getOnEventMetadata(target) {
48
+ return Reflect.getMetadata(exports.ON_EVENT_METADATA_KEY, target.constructor) || [];
49
+ }
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@hazeljs/event-emitter",
3
+ "version": "0.2.0-beta.31",
4
+ "description": "Event emitter module for HazelJS framework - event-driven architecture with decorators",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "test": "jest --coverage --passWithNoTests",
13
+ "lint": "eslint \"src/**/*.ts\"",
14
+ "lint:fix": "eslint \"src/**/*.ts\" --fix",
15
+ "clean": "rm -rf dist"
16
+ },
17
+ "dependencies": {
18
+ "eventemitter2": "^6.4.9"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^20.17.50",
22
+ "@typescript-eslint/eslint-plugin": "^8.18.2",
23
+ "@typescript-eslint/parser": "^8.18.2",
24
+ "eslint": "^8.56.0",
25
+ "jest": "^29.7.0",
26
+ "ts-jest": "^29.1.2",
27
+ "typescript": "^5.3.3"
28
+ },
29
+ "peerDependencies": {
30
+ "@hazeljs/core": ">=0.2.0-beta.0"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/hazel-js/hazeljs.git",
38
+ "directory": "packages/event-emitter"
39
+ },
40
+ "keywords": [
41
+ "hazeljs",
42
+ "events",
43
+ "event-emitter",
44
+ "event-driven",
45
+ "decorators"
46
+ ],
47
+ "author": "Muhammad Arslan <muhammad.arslan@hazeljs.com>",
48
+ "license": "Apache-2.0",
49
+ "bugs": {
50
+ "url": "https://github.com/hazeljs/hazel-js/issues"
51
+ },
52
+ "homepage": "https://hazeljs.com",
53
+ "gitHead": "e74f78d2da808a9bdfa9053e38dba2d2eef3cedf"
54
+ }