@signaltree/events 7.6.0 → 8.0.0

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.
@@ -1,301 +0,0 @@
1
- 'use strict';
2
-
3
- var factory = require('../core/factory.cjs');
4
- var types = require('../core/types.cjs');
5
-
6
- /**
7
- * Mock Event Bus for testing
8
- *
9
- * @example
10
- * ```typescript
11
- * const eventBus = createMockEventBus();
12
- *
13
- * // Subscribe to events
14
- * eventBus.subscribe('TradeProposalCreated', (event) => {
15
- * expect(event.data.tradeId).toBe('123');
16
- * });
17
- *
18
- * // Publish an event
19
- * await eventBus.publish({
20
- * type: 'TradeProposalCreated',
21
- * data: { tradeId: '123' },
22
- * });
23
- *
24
- * // Assert published events
25
- * expect(eventBus.getPublishedEvents()).toHaveLength(1);
26
- * expect(eventBus.wasPublished('TradeProposalCreated')).toBe(true);
27
- * ```
28
- */
29
- class MockEventBus {
30
- options;
31
- publishedEvents = [];
32
- subscriptions = new Map();
33
- allSubscriptions = new Set();
34
- constructor(options = {}) {
35
- this.options = options;
36
- this.options = {
37
- simulateAsync: false,
38
- asyncDelayMs: 10,
39
- autoGenerateIds: true,
40
- throwOnError: false,
41
- source: 'mock-event-bus',
42
- environment: 'test',
43
- ...options
44
- };
45
- }
46
- /**
47
- * Create an event with defaults (matches EventBusService.createEvent API)
48
- *
49
- * @example
50
- * ```typescript
51
- * const event = mockBus.createEvent('TradeAccepted', {
52
- * tradeId: '123',
53
- * acceptedById: 'user-1',
54
- * }, {
55
- * actor: { id: 'user-1', type: 'user' },
56
- * });
57
- * ```
58
- */
59
- createEvent(type, data, options = {}) {
60
- const id = options.id ?? (this.options.autoGenerateIds ? factory.generateEventId() : 'test-event-id');
61
- const correlationId = options.correlationId ?? factory.generateCorrelationId();
62
- const timestamp = options.timestamp ?? new Date().toISOString();
63
- const actor = options.actor ?? {
64
- id: 'test-user',
65
- type: 'user'
66
- };
67
- const metadata = {
68
- source: this.options.source ?? 'mock-event-bus',
69
- environment: this.options.environment ?? 'test',
70
- ...options.metadata
71
- };
72
- return {
73
- id,
74
- type,
75
- version: options.version ?? types.DEFAULT_EVENT_VERSION,
76
- timestamp,
77
- correlationId,
78
- causationId: options.causationId,
79
- actor,
80
- metadata,
81
- data,
82
- priority: options.priority,
83
- aggregate: options.aggregate
84
- };
85
- }
86
- /**
87
- * Convenience method to create and publish an event in one call
88
- * (matches EventBusService.publishEvent API)
89
- *
90
- * @example
91
- * ```typescript
92
- * await mockBus.publishEvent('TradeAccepted', {
93
- * tradeId: '123',
94
- * acceptedById: 'user-1',
95
- * }, {
96
- * actor: { id: 'user-1', type: 'user' },
97
- * });
98
- * ```
99
- */
100
- async publishEvent(type, data, options = {}) {
101
- const event = this.createEvent(type, data, options);
102
- return this.publish(event, {
103
- queue: options.queue,
104
- delay: options.delay
105
- });
106
- }
107
- /**
108
- * Publish an event
109
- */
110
- async publish(event, options) {
111
- // Complete the event
112
- const fullEvent = {
113
- ...event,
114
- id: event.id ?? (this.options.autoGenerateIds ? factory.generateEventId() : 'test-event-id'),
115
- timestamp: event.timestamp ?? new Date().toISOString(),
116
- correlationId: event.correlationId ?? factory.generateCorrelationId()
117
- };
118
- const queue = options?.queue ?? this.getQueueForPriority(fullEvent.priority);
119
- // Record the published event
120
- this.publishedEvents.push({
121
- event: fullEvent,
122
- queue,
123
- publishedAt: new Date(),
124
- delay: options?.delay
125
- });
126
- // Simulate async if configured
127
- if (this.options.simulateAsync) {
128
- await this.delay(this.options.asyncDelayMs ?? 10);
129
- }
130
- // Notify subscribers
131
- await this.notifySubscribers(fullEvent);
132
- return {
133
- eventId: fullEvent.id,
134
- queue
135
- };
136
- }
137
- /**
138
- * Publish multiple events
139
- */
140
- async publishBatch(events, options) {
141
- const correlationId = factory.generateCorrelationId();
142
- return Promise.all(events.map(event => this.publish({
143
- ...event,
144
- correlationId
145
- }, {
146
- ...options
147
- })));
148
- }
149
- /**
150
- * Subscribe to a specific event type
151
- */
152
- subscribe(eventType, handler) {
153
- let handlers = this.subscriptions.get(eventType);
154
- if (!handlers) {
155
- handlers = new Set();
156
- this.subscriptions.set(eventType, handlers);
157
- }
158
- handlers.add(handler);
159
- // Return unsubscribe function
160
- // handlers is guaranteed to exist at this point since we just set it above
161
- return () => {
162
- const h = this.subscriptions.get(eventType);
163
- if (h) {
164
- h.delete(handler);
165
- }
166
- };
167
- }
168
- /**
169
- * Subscribe to all events
170
- */
171
- subscribeAll(handler) {
172
- this.allSubscriptions.add(handler);
173
- return () => {
174
- this.allSubscriptions.delete(handler);
175
- };
176
- }
177
- /**
178
- * Get all published events
179
- */
180
- getPublishedEvents() {
181
- return [...this.publishedEvents];
182
- }
183
- /**
184
- * Get published events by type
185
- */
186
- getPublishedEventsByType(type) {
187
- return this.publishedEvents.filter(p => p.event.type === type);
188
- }
189
- /**
190
- * Get the last published event
191
- */
192
- getLastPublishedEvent() {
193
- return this.publishedEvents[this.publishedEvents.length - 1];
194
- }
195
- /**
196
- * Get the last published event of a specific type
197
- */
198
- getLastPublishedEventByType(type) {
199
- const events = this.getPublishedEventsByType(type);
200
- return events[events.length - 1];
201
- }
202
- /**
203
- * Check if an event type was published
204
- */
205
- wasPublished(eventType) {
206
- return this.publishedEvents.some(p => p.event.type === eventType);
207
- }
208
- /**
209
- * Check if an event with specific data was published
210
- */
211
- wasPublishedWith(eventType, predicate) {
212
- return this.publishedEvents.some(p => p.event.type === eventType && predicate(p.event));
213
- }
214
- /**
215
- * Get count of published events
216
- */
217
- getPublishedCount(eventType) {
218
- if (eventType) {
219
- return this.publishedEvents.filter(p => p.event.type === eventType).length;
220
- }
221
- return this.publishedEvents.length;
222
- }
223
- /**
224
- * Clear all published events (for test cleanup)
225
- */
226
- clearHistory() {
227
- this.publishedEvents = [];
228
- }
229
- /**
230
- * Clear all subscriptions
231
- */
232
- clearSubscriptions() {
233
- this.subscriptions.clear();
234
- this.allSubscriptions.clear();
235
- }
236
- /**
237
- * Reset the mock (clear history and subscriptions)
238
- */
239
- reset() {
240
- this.clearHistory();
241
- this.clearSubscriptions();
242
- }
243
- /**
244
- * Simulate an incoming event (as if received from server)
245
- */
246
- async simulateIncomingEvent(event) {
247
- await this.notifySubscribers(event);
248
- }
249
- // Private methods
250
- async notifySubscribers(event) {
251
- const errors = [];
252
- // Notify type-specific subscribers
253
- const handlers = this.subscriptions.get(event.type);
254
- if (handlers) {
255
- for (const handler of handlers) {
256
- try {
257
- await handler(event);
258
- } catch (error) {
259
- errors.push(error instanceof Error ? error : new Error(String(error)));
260
- }
261
- }
262
- }
263
- // Notify all-event subscribers
264
- for (const handler of this.allSubscriptions) {
265
- try {
266
- await handler(event);
267
- } catch (error) {
268
- errors.push(error instanceof Error ? error : new Error(String(error)));
269
- }
270
- }
271
- if (errors.length > 0 && this.options.throwOnError) {
272
- throw new AggregateError(errors, 'Subscriber errors');
273
- }
274
- }
275
- getQueueForPriority(priority) {
276
- switch (priority) {
277
- case 'critical':
278
- return 'events-critical';
279
- case 'high':
280
- return 'events-high';
281
- case 'low':
282
- return 'events-low';
283
- case 'bulk':
284
- return 'events-bulk';
285
- default:
286
- return 'events-normal';
287
- }
288
- }
289
- delay(ms) {
290
- return new Promise(resolve => setTimeout(resolve, ms));
291
- }
292
- }
293
- /**
294
- * Create a mock event bus for testing
295
- */
296
- function createMockEventBus(options) {
297
- return new MockEventBus(options);
298
- }
299
-
300
- exports.MockEventBus = MockEventBus;
301
- exports.createMockEventBus = createMockEventBus;