@flusys/nestjs-shared 6.4.0 → 7.0.0-beta.1

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.
Files changed (111) hide show
  1. package/README.md +437 -0
  2. package/cjs/classes/api-service.class.js +71 -8
  3. package/cjs/classes/api-service.class.spec.js +220 -0
  4. package/cjs/classes/disabled-event-bus.class.js +15 -0
  5. package/cjs/classes/disabled-event-bus.class.spec.js +40 -0
  6. package/cjs/classes/domain-event.publisher.js +76 -0
  7. package/cjs/classes/domain-event.publisher.spec.js +234 -0
  8. package/cjs/classes/event-bus.registry.js +69 -0
  9. package/cjs/classes/event-bus.registry.spec.js +116 -0
  10. package/cjs/classes/event-transports/event-transport.registry.js +41 -0
  11. package/cjs/classes/event-transports/event-transport.registry.spec.js +31 -0
  12. package/cjs/classes/event-transports/index.js +23 -0
  13. package/cjs/classes/event-transports/kafka-transport.optional.js +151 -0
  14. package/cjs/classes/event-transports/kafka-transport.optional.spec.js +199 -0
  15. package/cjs/classes/event-transports/memory-transport.js +54 -0
  16. package/cjs/classes/event-transports/memory-transport.spec.js +58 -0
  17. package/cjs/classes/event-transports/rabbitmq-transport.optional.js +184 -0
  18. package/cjs/classes/event-transports/rabbitmq-transport.optional.spec.js +256 -0
  19. package/cjs/classes/hybrid-event-bus.class.js +261 -0
  20. package/cjs/classes/hybrid-event-bus.class.spec.js +189 -0
  21. package/cjs/classes/index.js +5 -0
  22. package/cjs/constants/index.js +24 -0
  23. package/cjs/decorators/index.js +1 -0
  24. package/cjs/decorators/on-domain-event.decorator.js +13 -0
  25. package/cjs/decorators/on-domain-event.decorator.spec.js +50 -0
  26. package/cjs/entities/user-root.js +2 -2
  27. package/cjs/enums/event-action.enum.js +18 -0
  28. package/cjs/enums/index.js +1 -0
  29. package/cjs/interfaces/event-bus.interface.js +4 -0
  30. package/cjs/interfaces/index.js +1 -0
  31. package/cjs/modules/event-bus/event-bus.explorer.js +124 -0
  32. package/cjs/modules/event-bus/event-bus.explorer.spec.js +189 -0
  33. package/cjs/modules/event-bus/event-bus.integration.spec.js +254 -0
  34. package/cjs/modules/event-bus/event-bus.module.js +94 -0
  35. package/cjs/modules/event-bus/event-bus.module.spec.js +149 -0
  36. package/cjs/modules/event-bus/module-events.provider.js +39 -0
  37. package/cjs/modules/event-bus/module-events.provider.spec.js +56 -0
  38. package/cjs/modules/index.js +3 -0
  39. package/cjs/utils/event-pattern.util.js +98 -0
  40. package/cjs/utils/event-pattern.util.spec.js +234 -0
  41. package/cjs/utils/index.js +2 -0
  42. package/cjs/utils/optional-module.util.js +35 -0
  43. package/cjs/utils/optional-module.util.spec.js +14 -0
  44. package/classes/api-service.class.d.ts +11 -1
  45. package/classes/disabled-event-bus.class.d.ts +6 -0
  46. package/classes/domain-event.publisher.d.ts +14 -0
  47. package/classes/event-bus.registry.d.ts +14 -0
  48. package/classes/event-transports/event-transport.registry.d.ts +10 -0
  49. package/classes/event-transports/index.d.ts +2 -0
  50. package/classes/event-transports/kafka-transport.optional.d.ts +21 -0
  51. package/classes/event-transports/memory-transport.d.ts +13 -0
  52. package/classes/event-transports/rabbitmq-transport.optional.d.ts +27 -0
  53. package/classes/hybrid-event-bus.class.d.ts +32 -0
  54. package/classes/index.d.ts +5 -0
  55. package/constants/index.d.ts +6 -0
  56. package/decorators/index.d.ts +1 -0
  57. package/decorators/on-domain-event.decorator.d.ts +1 -0
  58. package/enums/event-action.enum.d.ts +7 -0
  59. package/enums/index.d.ts +1 -0
  60. package/fesm/classes/api-service.class.js +71 -8
  61. package/fesm/classes/api-service.class.spec.js +220 -0
  62. package/fesm/classes/disabled-event-bus.class.js +11 -0
  63. package/fesm/classes/disabled-event-bus.class.spec.js +36 -0
  64. package/fesm/classes/domain-event.publisher.js +63 -0
  65. package/fesm/classes/domain-event.publisher.spec.js +230 -0
  66. package/fesm/classes/event-bus.registry.js +65 -0
  67. package/fesm/classes/event-bus.registry.spec.js +112 -0
  68. package/fesm/classes/event-transports/event-transport.registry.js +35 -0
  69. package/fesm/classes/event-transports/event-transport.registry.spec.js +27 -0
  70. package/fesm/classes/event-transports/index.js +6 -0
  71. package/fesm/classes/event-transports/kafka-transport.optional.js +144 -0
  72. package/fesm/classes/event-transports/kafka-transport.optional.spec.js +195 -0
  73. package/fesm/classes/event-transports/memory-transport.js +46 -0
  74. package/fesm/classes/event-transports/memory-transport.spec.js +54 -0
  75. package/fesm/classes/event-transports/rabbitmq-transport.optional.js +174 -0
  76. package/fesm/classes/event-transports/rabbitmq-transport.optional.spec.js +252 -0
  77. package/fesm/classes/hybrid-event-bus.class.js +217 -0
  78. package/fesm/classes/hybrid-event-bus.class.spec.js +185 -0
  79. package/fesm/classes/index.js +5 -0
  80. package/fesm/constants/index.js +7 -0
  81. package/fesm/decorators/index.js +1 -0
  82. package/fesm/decorators/on-domain-event.decorator.js +10 -0
  83. package/fesm/decorators/on-domain-event.decorator.spec.js +46 -0
  84. package/fesm/entities/user-root.js +1 -1
  85. package/fesm/enums/event-action.enum.js +8 -0
  86. package/fesm/enums/index.js +1 -0
  87. package/fesm/interfaces/event-bus.interface.js +1 -0
  88. package/fesm/interfaces/index.js +1 -0
  89. package/fesm/modules/event-bus/event-bus.explorer.js +114 -0
  90. package/fesm/modules/event-bus/event-bus.explorer.spec.js +185 -0
  91. package/fesm/modules/event-bus/event-bus.integration.spec.js +250 -0
  92. package/fesm/modules/event-bus/event-bus.module.js +84 -0
  93. package/fesm/modules/event-bus/event-bus.module.spec.js +145 -0
  94. package/fesm/modules/event-bus/module-events.provider.js +26 -0
  95. package/fesm/modules/event-bus/module-events.provider.spec.js +52 -0
  96. package/fesm/modules/index.js +3 -0
  97. package/fesm/utils/event-pattern.util.js +86 -0
  98. package/fesm/utils/event-pattern.util.spec.js +230 -0
  99. package/fesm/utils/index.js +2 -0
  100. package/fesm/utils/optional-module.util.js +25 -0
  101. package/fesm/utils/optional-module.util.spec.js +10 -0
  102. package/interfaces/event-bus.interface.d.ts +74 -0
  103. package/interfaces/index.d.ts +1 -0
  104. package/modules/event-bus/event-bus.explorer.d.ts +14 -0
  105. package/modules/event-bus/event-bus.module.d.ts +8 -0
  106. package/modules/event-bus/module-events.provider.d.ts +3 -0
  107. package/modules/index.d.ts +3 -0
  108. package/package.json +2 -2
  109. package/utils/event-pattern.util.d.ts +3 -0
  110. package/utils/index.d.ts +2 -0
  111. package/utils/optional-module.util.d.ts +1 -0
@@ -0,0 +1,63 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { getCompanyId, getRequestId, getTenantId } from '../middlewares/logger.middleware';
3
+ import { sanitizeEventPayload } from '../utils/event-pattern.util';
4
+ import { EventBusRegistry } from './event-bus.registry';
5
+ export const DOMAIN_EVENT_VERSION = 1;
6
+ export function buildDomainEvent(input) {
7
+ const rows = input.data === undefined ? [] : toArray(input.data);
8
+ const ids = input.ids ?? collectIds(rows);
9
+ return {
10
+ id: randomUUID(),
11
+ name: `${input.module}.${input.entity}.${input.action}`,
12
+ module: input.module,
13
+ entity: input.entity,
14
+ action: input.action,
15
+ payload: {
16
+ ids,
17
+ ...rows.length && EventBusRegistry.shouldIncludePayload(input.module) ? {
18
+ data: sanitizeEventPayload(rows)
19
+ } : {},
20
+ ...input.metadata ? {
21
+ metadata: sanitizeEventPayload(input.metadata)
22
+ } : {}
23
+ },
24
+ actor: {
25
+ userId: input.user?.id ?? null,
26
+ companyId: input.user?.companyId ?? getCompanyId() ?? null,
27
+ tenantId: getTenantId() ?? null,
28
+ requestId: getRequestId() ?? null
29
+ },
30
+ occurredAt: new Date().toISOString(),
31
+ version: DOMAIN_EVENT_VERSION
32
+ };
33
+ }
34
+ /**
35
+ * Publishes a domain event for an operation that is not plain CRUD - a form
36
+ * submission, a login, a file upload. Honours the publishing module's own
37
+ * `events` config and never throws, so a broker outage cannot break the caller.
38
+ *
39
+ * Supplying `eventBus` chooses which bus to publish on; it never overrides the
40
+ * module's on/off switch, otherwise turning a module's events off would leave
41
+ * every service holding its own bus still publishing.
42
+ */ export async function publishDomainEvent(input) {
43
+ const bus = input.eventBus ?? EventBusRegistry.getBus();
44
+ if (!bus) return;
45
+ if (!EventBusRegistry.isEnabled(input.module, input.entity, input.action)) return;
46
+ try {
47
+ await bus.publish(buildDomainEvent(input));
48
+ } catch {
49
+ // Events must never break the operation that produced them
50
+ }
51
+ }
52
+ function toArray(value) {
53
+ return Array.isArray(value) ? value : [
54
+ value
55
+ ];
56
+ }
57
+ function collectIds(rows) {
58
+ return rows.reduce((ids, row)=>{
59
+ const id = row?.id;
60
+ if (id) ids.push(id);
61
+ return ids;
62
+ }, []);
63
+ }
@@ -0,0 +1,230 @@
1
+ import { buildDomainEvent, publishDomainEvent } from './domain-event.publisher';
2
+ import { EventBusRegistry } from './event-bus.registry';
3
+ const user = {
4
+ id: 'user-1',
5
+ email: 'ada@example.com',
6
+ companyId: 'company-1'
7
+ };
8
+ describe('buildDomainEvent', ()=>{
9
+ beforeEach(()=>{
10
+ EventBusRegistry.reset();
11
+ EventBusRegistry.configureModule('form-builder', {
12
+ enabled: true
13
+ });
14
+ });
15
+ afterEach(()=>{
16
+ EventBusRegistry.reset();
17
+ });
18
+ it('should name the event <module>.<entity>.<action>', ()=>{
19
+ const event = buildDomainEvent({
20
+ module: 'form-builder',
21
+ entity: 'form_result',
22
+ action: 'submitted'
23
+ });
24
+ expect(event.name).toBe('form-builder.form_result.submitted');
25
+ expect(event.version).toBe(1);
26
+ expect(event.id).toEqual(expect.any(String));
27
+ });
28
+ it('should derive ids from the supplied rows when none are given', ()=>{
29
+ const event = buildDomainEvent({
30
+ module: 'form-builder',
31
+ entity: 'form_result',
32
+ action: 'submitted',
33
+ data: [
34
+ {
35
+ id: 'a'
36
+ },
37
+ {
38
+ id: 'b'
39
+ }
40
+ ]
41
+ });
42
+ expect(event.payload.ids).toEqual([
43
+ 'a',
44
+ 'b'
45
+ ]);
46
+ });
47
+ it('should prefer explicitly supplied ids', ()=>{
48
+ const event = buildDomainEvent({
49
+ module: 'form-builder',
50
+ entity: 'form_result',
51
+ action: 'submitted',
52
+ ids: [
53
+ 'explicit'
54
+ ],
55
+ data: {
56
+ id: 'ignored'
57
+ }
58
+ });
59
+ expect(event.payload.ids).toEqual([
60
+ 'explicit'
61
+ ]);
62
+ });
63
+ it('should attach metadata regardless of the includePayload setting', ()=>{
64
+ EventBusRegistry.configureModule('form-builder', {
65
+ enabled: true,
66
+ includePayload: false
67
+ });
68
+ const event = buildDomainEvent({
69
+ module: 'form-builder',
70
+ entity: 'form_result',
71
+ action: 'submitted',
72
+ data: {
73
+ id: 'a',
74
+ answer: 'secret-ish'
75
+ },
76
+ metadata: {
77
+ formId: 'form-1',
78
+ isDraft: false
79
+ }
80
+ });
81
+ expect(event.payload.data).toBeUndefined();
82
+ expect(event.payload.metadata).toEqual({
83
+ formId: 'form-1',
84
+ isDraft: false
85
+ });
86
+ });
87
+ it('should redact credential-like fields from data and metadata', ()=>{
88
+ const event = buildDomainEvent({
89
+ module: 'form-builder',
90
+ entity: 'form_result',
91
+ action: 'submitted',
92
+ data: {
93
+ id: 'a',
94
+ password: 'hunter2'
95
+ },
96
+ metadata: {
97
+ token: 'abc'
98
+ }
99
+ });
100
+ expect(event.payload.data).toEqual([
101
+ {
102
+ id: 'a',
103
+ password: '[REDACTED]'
104
+ }
105
+ ]);
106
+ expect(event.payload.metadata).toEqual({
107
+ token: '[REDACTED]'
108
+ });
109
+ });
110
+ it('should record the acting user', ()=>{
111
+ const event = buildDomainEvent({
112
+ module: 'form-builder',
113
+ entity: 'form_result',
114
+ action: 'submitted',
115
+ user
116
+ });
117
+ expect(event.actor).toEqual(expect.objectContaining({
118
+ userId: 'user-1',
119
+ companyId: 'company-1'
120
+ }));
121
+ });
122
+ });
123
+ describe('publishDomainEvent', ()=>{
124
+ let publish;
125
+ beforeEach(()=>{
126
+ publish = jest.fn().mockResolvedValue(undefined);
127
+ EventBusRegistry.reset();
128
+ EventBusRegistry.setBus({
129
+ publish,
130
+ subscribe: jest.fn(),
131
+ close: jest.fn()
132
+ });
133
+ });
134
+ afterEach(()=>{
135
+ EventBusRegistry.reset();
136
+ });
137
+ it('should publish when the module has events enabled', async ()=>{
138
+ EventBusRegistry.configureModule('auth', {
139
+ enabled: true
140
+ });
141
+ await publishDomainEvent({
142
+ module: 'auth',
143
+ entity: 'session',
144
+ action: 'logged-in'
145
+ });
146
+ expect(publish).toHaveBeenCalledWith(expect.objectContaining({
147
+ name: 'auth.session.logged-in'
148
+ }));
149
+ });
150
+ it('should stay silent when the module has events disabled', async ()=>{
151
+ EventBusRegistry.configureModule('auth', {
152
+ enabled: false
153
+ });
154
+ await publishDomainEvent({
155
+ module: 'auth',
156
+ entity: 'session',
157
+ action: 'logged-in'
158
+ });
159
+ expect(publish).not.toHaveBeenCalled();
160
+ });
161
+ it('should honour an action allowlist that names a domain action', async ()=>{
162
+ EventBusRegistry.configureModule('auth', {
163
+ enabled: true,
164
+ actions: [
165
+ 'logged-in'
166
+ ]
167
+ });
168
+ await publishDomainEvent({
169
+ module: 'auth',
170
+ entity: 'session',
171
+ action: 'logged-in'
172
+ });
173
+ await publishDomainEvent({
174
+ module: 'auth',
175
+ entity: 'session',
176
+ action: 'logged-out'
177
+ });
178
+ expect(publish).toHaveBeenCalledTimes(1);
179
+ });
180
+ it('should publish through an explicitly supplied bus instead of the registered one', async ()=>{
181
+ const directPublish = jest.fn().mockResolvedValue(undefined);
182
+ EventBusRegistry.configureModule('auth', {
183
+ enabled: true
184
+ });
185
+ await publishDomainEvent({
186
+ module: 'auth',
187
+ entity: 'session',
188
+ action: 'logged-in',
189
+ eventBus: {
190
+ publish: directPublish
191
+ }
192
+ });
193
+ expect(directPublish).toHaveBeenCalled();
194
+ expect(publish).not.toHaveBeenCalled();
195
+ });
196
+ it('should still respect the module switch when a bus is supplied explicitly', async ()=>{
197
+ const directPublish = jest.fn().mockResolvedValue(undefined);
198
+ EventBusRegistry.configureModule('auth', {
199
+ enabled: false
200
+ });
201
+ await publishDomainEvent({
202
+ module: 'auth',
203
+ entity: 'session',
204
+ action: 'logged-in',
205
+ eventBus: {
206
+ publish: directPublish
207
+ }
208
+ });
209
+ expect(directPublish).not.toHaveBeenCalled();
210
+ });
211
+ it('should do nothing when no bus is registered', async ()=>{
212
+ EventBusRegistry.reset();
213
+ await expect(publishDomainEvent({
214
+ module: 'auth',
215
+ entity: 'session',
216
+ action: 'logged-in'
217
+ })).resolves.toBeUndefined();
218
+ });
219
+ it('should swallow a broker failure', async ()=>{
220
+ EventBusRegistry.configureModule('auth', {
221
+ enabled: true
222
+ });
223
+ publish.mockRejectedValue(new Error('broker down'));
224
+ await expect(publishDomainEvent({
225
+ module: 'auth',
226
+ entity: 'session',
227
+ action: 'logged-in'
228
+ })).resolves.toBeUndefined();
229
+ });
230
+ });
@@ -0,0 +1,65 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ const DISABLED = {
15
+ enabled: false
16
+ };
17
+ /**
18
+ * Ambient access point for the event bus.
19
+ *
20
+ * ApiService is request scoped and is extended by every feature package, so the
21
+ * bus is resolved from here instead of being threaded through 20+ constructors.
22
+ * Services may still receive a bus explicitly - that instance wins.
23
+ */ export class EventBusRegistry {
24
+ static setBus(bus) {
25
+ this.bus = bus;
26
+ }
27
+ static getBus() {
28
+ return this.bus;
29
+ }
30
+ static setDefaultModuleEvents(config) {
31
+ this.defaultConfig = config ?? DISABLED;
32
+ }
33
+ /** Called by each feature module with the `events` block from its own config */ static configureModule(moduleName, config) {
34
+ this.moduleConfigs.set(moduleName, config ?? DISABLED);
35
+ }
36
+ static getModuleConfig(moduleName) {
37
+ if (!moduleName) return this.defaultConfig;
38
+ return this.moduleConfigs.get(moduleName) ?? this.defaultConfig;
39
+ }
40
+ /**
41
+ * Answers only "is this module configured to publish this" - whether a bus
42
+ * exists is the publisher's concern, so an explicitly supplied bus is still
43
+ * held to the module's own on/off switch.
44
+ */ static isEnabled(moduleName, entity, action) {
45
+ const config = this.getModuleConfig(moduleName);
46
+ if (!config.enabled) return false;
47
+ if (config.excludeEntities?.includes(entity)) return false;
48
+ if (config.entities?.length && !config.entities.includes(entity)) return false;
49
+ // Without an explicit allowlist, CRUD lifecycle actions and every domain
50
+ // action a package defines are all published.
51
+ if (!config.actions?.length) return true;
52
+ return config.actions.includes(action);
53
+ }
54
+ static shouldIncludePayload(moduleName) {
55
+ return this.getModuleConfig(moduleName).includePayload ?? true;
56
+ }
57
+ static reset() {
58
+ this.bus = undefined;
59
+ this.moduleConfigs.clear();
60
+ this.defaultConfig = DISABLED;
61
+ }
62
+ }
63
+ _define_property(EventBusRegistry, "bus", void 0);
64
+ _define_property(EventBusRegistry, "moduleConfigs", new Map());
65
+ _define_property(EventBusRegistry, "defaultConfig", DISABLED);
@@ -0,0 +1,112 @@
1
+ import { EventAction } from '../enums/event-action.enum';
2
+ import { EventBusRegistry } from './event-bus.registry';
3
+ const bus = {
4
+ publish: jest.fn(),
5
+ subscribe: jest.fn(),
6
+ close: jest.fn()
7
+ };
8
+ describe('EventBusRegistry', ()=>{
9
+ beforeEach(()=>{
10
+ EventBusRegistry.reset();
11
+ EventBusRegistry.setBus(bus);
12
+ });
13
+ afterEach(()=>{
14
+ EventBusRegistry.reset();
15
+ });
16
+ it('should expose the registered bus', ()=>{
17
+ expect(EventBusRegistry.getBus()).toBe(bus);
18
+ });
19
+ it('should answer from the module config alone, independent of any registered bus', ()=>{
20
+ EventBusRegistry.reset();
21
+ EventBusRegistry.configureModule('storage', {
22
+ enabled: true
23
+ });
24
+ expect(EventBusRegistry.getBus()).toBeUndefined();
25
+ expect(EventBusRegistry.isEnabled('storage', 'folder', EventAction.CREATED)).toBe(true);
26
+ });
27
+ it('should report disabled for a module that never registered a config', ()=>{
28
+ expect(EventBusRegistry.isEnabled('storage', 'folder', EventAction.CREATED)).toBe(false);
29
+ });
30
+ it('should enable every action of an enabled module by default', ()=>{
31
+ EventBusRegistry.configureModule('storage', {
32
+ enabled: true
33
+ });
34
+ expect(EventBusRegistry.isEnabled('storage', 'folder', EventAction.CREATED)).toBe(true);
35
+ expect(EventBusRegistry.isEnabled('storage', 'folder', EventAction.DELETED)).toBe(true);
36
+ });
37
+ it('should honour an action allowlist', ()=>{
38
+ EventBusRegistry.configureModule('storage', {
39
+ enabled: true,
40
+ actions: [
41
+ EventAction.CREATED
42
+ ]
43
+ });
44
+ expect(EventBusRegistry.isEnabled('storage', 'folder', EventAction.CREATED)).toBe(true);
45
+ expect(EventBusRegistry.isEnabled('storage', 'folder', EventAction.UPDATED)).toBe(false);
46
+ });
47
+ it('should honour an allowlist that mixes CRUD lifecycle and domain actions', ()=>{
48
+ EventBusRegistry.configureModule('auth', {
49
+ enabled: true,
50
+ actions: [
51
+ EventAction.CREATED,
52
+ 'logged-in'
53
+ ]
54
+ });
55
+ expect(EventBusRegistry.isEnabled('auth', 'appuser', EventAction.CREATED)).toBe(true);
56
+ expect(EventBusRegistry.isEnabled('auth', 'session', 'logged-in')).toBe(true);
57
+ expect(EventBusRegistry.isEnabled('auth', 'appuser', EventAction.UPDATED)).toBe(false);
58
+ expect(EventBusRegistry.isEnabled('auth', 'session', 'logged-out')).toBe(false);
59
+ });
60
+ it('should silence CRUD when the allowlist names only domain actions', ()=>{
61
+ EventBusRegistry.configureModule('auth', {
62
+ enabled: true,
63
+ actions: [
64
+ 'logged-in'
65
+ ]
66
+ });
67
+ expect(EventBusRegistry.isEnabled('auth', 'session', 'logged-in')).toBe(true);
68
+ expect(EventBusRegistry.isEnabled('auth', 'appuser', EventAction.CREATED)).toBe(false);
69
+ });
70
+ it('should honour an entity allowlist and exclusion list', ()=>{
71
+ EventBusRegistry.configureModule('storage', {
72
+ enabled: true,
73
+ entities: [
74
+ 'folder',
75
+ 'file_manager'
76
+ ],
77
+ excludeEntities: [
78
+ 'file_manager'
79
+ ]
80
+ });
81
+ expect(EventBusRegistry.isEnabled('storage', 'folder', EventAction.CREATED)).toBe(true);
82
+ expect(EventBusRegistry.isEnabled('storage', 'file_manager', EventAction.CREATED)).toBe(false);
83
+ expect(EventBusRegistry.isEnabled('storage', 'storageConfig', EventAction.CREATED)).toBe(false);
84
+ });
85
+ it('should fall back to the default config for unregistered modules', ()=>{
86
+ EventBusRegistry.setDefaultModuleEvents({
87
+ enabled: true
88
+ });
89
+ expect(EventBusRegistry.isEnabled('unknown-module', 'thing', EventAction.CREATED)).toBe(true);
90
+ });
91
+ it('should include the payload unless a module opts out', ()=>{
92
+ EventBusRegistry.configureModule('storage', {
93
+ enabled: true
94
+ });
95
+ EventBusRegistry.configureModule('auth', {
96
+ enabled: true,
97
+ includePayload: false
98
+ });
99
+ expect(EventBusRegistry.shouldIncludePayload('storage')).toBe(true);
100
+ expect(EventBusRegistry.shouldIncludePayload('auth')).toBe(false);
101
+ });
102
+ it('should clear everything on reset', ()=>{
103
+ EventBusRegistry.configureModule('storage', {
104
+ enabled: true
105
+ });
106
+ EventBusRegistry.reset();
107
+ expect(EventBusRegistry.getBus()).toBeUndefined();
108
+ expect(EventBusRegistry.getModuleConfig('storage')).toEqual({
109
+ enabled: false
110
+ });
111
+ });
112
+ });
@@ -0,0 +1,35 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ /**
15
+ * Static registry for event transports.
16
+ * Broker transports register themselves on import so nestjs-shared never has to
17
+ * depend on `amqplib` or `kafkajs` at build time.
18
+ */ export class EventTransportRegistry {
19
+ static register(name, factory) {
20
+ this.transports.set(name.toLowerCase(), factory);
21
+ }
22
+ static get(name) {
23
+ return this.transports.get(name.toLowerCase());
24
+ }
25
+ static has(name) {
26
+ return this.transports.has(name.toLowerCase());
27
+ }
28
+ static getAll() {
29
+ return Array.from(this.transports.keys());
30
+ }
31
+ static clear() {
32
+ this.transports.clear();
33
+ }
34
+ }
35
+ _define_property(EventTransportRegistry, "transports", new Map());
@@ -0,0 +1,27 @@
1
+ import { EventTransportRegistry } from './event-transport.registry';
2
+ const stubTransport = {};
3
+ describe('EventTransportRegistry', ()=>{
4
+ afterEach(()=>{
5
+ EventTransportRegistry.clear();
6
+ });
7
+ it('should register and resolve a transport factory', ()=>{
8
+ EventTransportRegistry.register('rabbitmq', ()=>stubTransport);
9
+ expect(EventTransportRegistry.get('rabbitmq')({})).toBe(stubTransport);
10
+ });
11
+ it('should resolve case insensitively', ()=>{
12
+ EventTransportRegistry.register('Kafka', ()=>stubTransport);
13
+ expect(EventTransportRegistry.has('kafka')).toBe(true);
14
+ });
15
+ it('should return undefined for an unknown transport', ()=>{
16
+ expect(EventTransportRegistry.get('nats')).toBeUndefined();
17
+ expect(EventTransportRegistry.has('nats')).toBe(false);
18
+ });
19
+ it('should list every registered transport', ()=>{
20
+ EventTransportRegistry.register('memory', ()=>stubTransport);
21
+ EventTransportRegistry.register('kafka', ()=>stubTransport);
22
+ expect(EventTransportRegistry.getAll().sort()).toEqual([
23
+ 'kafka',
24
+ 'memory'
25
+ ]);
26
+ });
27
+ });
@@ -0,0 +1,6 @@
1
+ export * from './event-transport.registry';
2
+ // Built-in transport (no external dependencies)
3
+ export * from './memory-transport'; // Note: Broker transports are loaded dynamically by HybridEventBus.
4
+ // Import them directly when registering manually:
5
+ // - import { RabbitMqTransport } from '@flusys/nestjs-shared/classes/event-transports/rabbitmq-transport.optional';
6
+ // - import { KafkaTransport } from '@flusys/nestjs-shared/classes/event-transports/kafka-transport.optional';
@@ -0,0 +1,144 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ /**
15
+ * Optional Kafka event transport
16
+ * Requires: npm install kafkajs
17
+ */ import { InternalServerErrorException, Logger } from '@nestjs/common';
18
+ import { DEFAULT_EVENT_SERVICE_NAME, DEFAULT_EVENT_TOPIC, SYSTEM_MESSAGES } from '../../constants';
19
+ import { loadOptionalModule } from '../../utils/optional-module.util';
20
+ import { EventTransportRegistry } from './event-transport.registry';
21
+ const DEFAULT_BROKERS = [
22
+ 'localhost:9092'
23
+ ];
24
+ /**
25
+ * Every domain event lands on a single topic keyed by event name; pattern
26
+ * filtering happens in the bus, which keeps consumer group management trivial.
27
+ */ export class KafkaTransport {
28
+ async connect() {
29
+ let kafkajs;
30
+ try {
31
+ kafkajs = await loadOptionalModule('kafkajs');
32
+ } catch {
33
+ throw new InternalServerErrorException({
34
+ message: 'kafkajs not found',
35
+ messageKey: SYSTEM_MESSAGES.SDK_NOT_INSTALLED,
36
+ messageVariables: {
37
+ sdk: 'kafkajs'
38
+ }
39
+ });
40
+ }
41
+ const Kafka = kafkajs.Kafka ?? kafkajs.default.Kafka;
42
+ this.client = new Kafka({
43
+ clientId: this.config.clientId ?? DEFAULT_EVENT_SERVICE_NAME,
44
+ brokers: this.config.brokers ?? DEFAULT_BROKERS,
45
+ ssl: this.config.ssl,
46
+ sasl: this.config.sasl
47
+ });
48
+ this.producer = this.client.producer();
49
+ await this.producer.connect();
50
+ // The consumer is built on the first bind, never here: subscribing to a
51
+ // topic that does not exist yet, or a coordinator that is not ready, would
52
+ // otherwise fail the whole transport and take publishing down with it - and
53
+ // a service that only publishes would join a consumer group for nothing.
54
+ if (this.boundPatterns.size) await this.startConsuming();
55
+ }
56
+ async publish(event) {
57
+ if (!this.producer) return;
58
+ await this.producer.send({
59
+ topic: this.topic,
60
+ messages: [
61
+ {
62
+ key: event.name,
63
+ value: JSON.stringify(event),
64
+ headers: {
65
+ eventId: event.id,
66
+ module: event.module,
67
+ action: String(event.action)
68
+ }
69
+ }
70
+ ]
71
+ });
72
+ }
73
+ async bind(pattern) {
74
+ if (this.boundPatterns.has(pattern)) return;
75
+ this.boundPatterns.add(pattern);
76
+ await this.startConsuming();
77
+ }
78
+ onMessage(handler) {
79
+ this.handlers.push(handler);
80
+ }
81
+ async close() {
82
+ await this.consumer?.disconnect().catch(()=>{});
83
+ await this.producer?.disconnect().catch(()=>{});
84
+ this.consumer = undefined;
85
+ this.producer = undefined;
86
+ this.client = undefined;
87
+ this.running = false;
88
+ }
89
+ isReady() {
90
+ return Boolean(this.producer);
91
+ }
92
+ get topic() {
93
+ return this.config.topic ?? DEFAULT_EVENT_TOPIC;
94
+ }
95
+ async startConsuming() {
96
+ if (this.running || !this.client) return;
97
+ this.running = true;
98
+ try {
99
+ this.consumer = this.client.consumer({
100
+ groupId: this.config.groupId ?? `${DEFAULT_EVENT_SERVICE_NAME}-events`
101
+ });
102
+ await this.consumer.connect();
103
+ await this.consumer.subscribe({
104
+ topic: this.topic,
105
+ fromBeginning: false
106
+ });
107
+ await this.consumer.run({
108
+ eachMessage: async ({ message })=>{
109
+ // A compacted topic delivers tombstones with no value at all
110
+ if (!message?.value) return;
111
+ try {
112
+ const event = JSON.parse(message.value.toString());
113
+ await Promise.all(this.handlers.map((handler)=>handler(event)));
114
+ } catch (error) {
115
+ this.logger.error(error instanceof Error ? error.message : 'Failed to handle event');
116
+ }
117
+ }
118
+ });
119
+ } catch (error) {
120
+ // Released so a later bind can try again; the producer stays usable
121
+ this.running = false;
122
+ this.consumer = undefined;
123
+ throw error;
124
+ }
125
+ }
126
+ constructor(config = {}){
127
+ _define_property(this, "config", void 0);
128
+ _define_property(this, "name", void 0);
129
+ _define_property(this, "logger", void 0);
130
+ _define_property(this, "handlers", void 0);
131
+ _define_property(this, "boundPatterns", void 0);
132
+ _define_property(this, "client", void 0);
133
+ _define_property(this, "producer", void 0);
134
+ _define_property(this, "consumer", void 0);
135
+ _define_property(this, "running", void 0);
136
+ this.config = config;
137
+ this.name = 'kafka';
138
+ this.logger = new Logger(KafkaTransport.name);
139
+ this.handlers = [];
140
+ this.boundPatterns = new Set();
141
+ this.running = false;
142
+ }
143
+ }
144
+ EventTransportRegistry.register('kafka', (config)=>new KafkaTransport(config));