@burdenoff/be-sdk 2026.512.102 → 2026.513.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 (37) hide show
  1. package/dist/EventQueueFactory-JQHBTQG3.js +8 -0
  2. package/dist/{EventQueueFactory-FUSC3YWI.js.map → EventQueueFactory-JQHBTQG3.js.map} +1 -1
  3. package/dist/{chunk-FPARMFI5.js → chunk-4YCH5SUK.js} +23 -5
  4. package/dist/chunk-4YCH5SUK.js.map +1 -0
  5. package/dist/chunk-BQRXB4CW.js +2183 -0
  6. package/dist/chunk-BQRXB4CW.js.map +1 -0
  7. package/dist/{chunk-RBGRCYDX.js → chunk-EODPHHEH.js} +3 -3
  8. package/dist/{chunk-RBGRCYDX.js.map → chunk-EODPHHEH.js.map} +1 -1
  9. package/dist/{chunk-AI5C77XX.js → chunk-I2PO7JBF.js} +3 -3
  10. package/dist/{chunk-AI5C77XX.js.map → chunk-I2PO7JBF.js.map} +1 -1
  11. package/dist/{chunk-JDXYYJTN.js → chunk-LIOZLSID.js} +3 -3
  12. package/dist/{chunk-JDXYYJTN.js.map → chunk-LIOZLSID.js.map} +1 -1
  13. package/dist/{chunk-ZGLPXNIO.js → chunk-ORMCFQNW.js} +5 -5
  14. package/dist/{chunk-ZGLPXNIO.js.map → chunk-ORMCFQNW.js.map} +1 -1
  15. package/dist/{chunk-VOFKF27Q.js → chunk-UVYDP6P6.js} +3 -2
  16. package/dist/chunk-UVYDP6P6.js.map +1 -0
  17. package/dist/config-QVYSAUMT.js +4 -0
  18. package/dist/{config-7U7J3QXQ.js.map → config-QVYSAUMT.js.map} +1 -1
  19. package/dist/esm-M2M7HGV4.js +1356 -0
  20. package/dist/esm-M2M7HGV4.js.map +1 -0
  21. package/dist/event-queue/index.d.ts +1 -1
  22. package/dist/event-queue/index.js +4 -4
  23. package/dist/graph/index.js +5 -5
  24. package/dist/{index-BF2uh_h9.d.ts → index-eUvoVdr7.d.ts} +158 -2
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.js +15 -15
  27. package/dist/init/index.js +3 -3
  28. package/dist/prisma/index.js +4 -4
  29. package/package.json +9 -1
  30. package/dist/EventQueueFactory-FUSC3YWI.js +0 -8
  31. package/dist/chunk-FPARMFI5.js.map +0 -1
  32. package/dist/chunk-L2F2SCEJ.js +0 -1080
  33. package/dist/chunk-L2F2SCEJ.js.map +0 -1
  34. package/dist/chunk-VOFKF27Q.js.map +0 -1
  35. package/dist/config-7U7J3QXQ.js +0 -4
  36. package/dist/esm-K6H7EIWK.js +0 -1450
  37. package/dist/esm-K6H7EIWK.js.map +0 -1
@@ -1,1080 +0,0 @@
1
- import { QueueType } from './chunk-VOFKF27Q.js';
2
- import { NatsConnectionManager } from './chunk-COSUYUCB.js';
3
- import { DEFAULT_LAYER_RESOURCES } from './chunk-NGMEI42S.js';
4
- import { logger } from './chunk-CBZNP6RF.js';
5
- import { __name } from './chunk-XE4OXN2W.js';
6
- import { RetentionPolicy, StorageType, AckPolicy, DeliverPolicy, headers } from 'nats';
7
-
8
- // src/event-queue/implementations/nats/trace-context.ts
9
- var otelApiPromise = null;
10
- async function loadOtelApi() {
11
- if (otelApiPromise) {
12
- return otelApiPromise;
13
- }
14
- otelApiPromise = (async () => {
15
- try {
16
- const mod = await import('./esm-K6H7EIWK.js');
17
- return mod;
18
- } catch {
19
- logger.debug("[trace-context] @opentelemetry/api not available; NATS traces disabled");
20
- return null;
21
- }
22
- })();
23
- return otelApiPromise;
24
- }
25
- __name(loadOtelApi, "loadOtelApi");
26
- var setter = {
27
- set(carrier, key, value) {
28
- carrier[key] = value;
29
- }
30
- };
31
- var getter = {
32
- get(carrier, key) {
33
- return carrier[key];
34
- },
35
- keys(carrier) {
36
- return Object.keys(carrier);
37
- }
38
- };
39
- async function injectW3CTraceContext(hdrs) {
40
- const api = await loadOtelApi();
41
- if (!api) return;
42
- try {
43
- const carrier = {};
44
- api.propagation.inject(api.context.active(), carrier, setter);
45
- for (const [key, value] of Object.entries(carrier)) {
46
- if (value) hdrs.set(key, value);
47
- }
48
- } catch (err) {
49
- logger.debug("[trace-context] injection failed", {
50
- error: err instanceof Error ? err.message : String(err)
51
- });
52
- }
53
- }
54
- __name(injectW3CTraceContext, "injectW3CTraceContext");
55
- async function extractW3CTraceContext(hdrs) {
56
- const api = await loadOtelApi();
57
- if (!api || !hdrs) return void 0;
58
- try {
59
- const carrier = {};
60
- for (const key of [
61
- "traceparent",
62
- "tracestate",
63
- "baggage"
64
- ]) {
65
- const value = hdrs.get(key);
66
- if (value) carrier[key] = value;
67
- }
68
- return api.propagation.extract(api.context.active(), carrier, getter);
69
- } catch (err) {
70
- logger.debug("[trace-context] extraction failed", {
71
- error: err instanceof Error ? err.message : String(err)
72
- });
73
- return void 0;
74
- }
75
- }
76
- __name(extractW3CTraceContext, "extractW3CTraceContext");
77
- async function runWithConsumerSpan(subject, hdrs, handler) {
78
- const api = await loadOtelApi();
79
- if (!api) return handler();
80
- try {
81
- const parentCtx = await extractW3CTraceContext(hdrs);
82
- const tracer = api.trace.getTracer("@burdenoff/be-sdk/nats");
83
- return await new Promise((resolve, reject) => {
84
- tracer.startActiveSpan(`nats.consume ${subject}`, {
85
- kind: 5,
86
- attributes: {
87
- "messaging.system": "nats",
88
- "messaging.destination.name": subject
89
- }
90
- }, parentCtx, async (span) => {
91
- try {
92
- const result = await handler();
93
- span.setStatus({
94
- code: 1
95
- });
96
- span.end();
97
- resolve(result);
98
- } catch (err) {
99
- span.recordException(err);
100
- span.setStatus({
101
- code: 2,
102
- message: err instanceof Error ? err.message : String(err)
103
- });
104
- span.end();
105
- reject(err);
106
- }
107
- });
108
- });
109
- } catch (err) {
110
- logger.debug("[trace-context] consumer span failed to start; running without span", {
111
- error: err instanceof Error ? err.message : String(err)
112
- });
113
- return handler();
114
- }
115
- }
116
- __name(runWithConsumerSpan, "runWithConsumerSpan");
117
- var DEFAULT_STREAM_MAX_BYTES = 10 * 1024 * 1024;
118
- var NatsSubscription = class NatsSubscription2 {
119
- static {
120
- __name(this, "NatsSubscription");
121
- }
122
- id;
123
- subject;
124
- stopFn;
125
- active = true;
126
- stats = {
127
- messagesReceived: 0,
128
- messagesProcessed: 0,
129
- messagesFailed: 0,
130
- lastActivity: (/* @__PURE__ */ new Date()).toISOString()
131
- };
132
- constructor(id, subject, stopFn) {
133
- this.id = id;
134
- this.subject = subject;
135
- this.stopFn = stopFn;
136
- }
137
- async unsubscribe() {
138
- if (!this.active) {
139
- return Promise.resolve();
140
- }
141
- this.active = false;
142
- this.stopFn();
143
- return Promise.resolve();
144
- }
145
- isActive() {
146
- return this.active;
147
- }
148
- getStats() {
149
- return {
150
- messagesReceived: this.stats.messagesReceived,
151
- messagesProcessed: this.stats.messagesProcessed,
152
- messagesFailed: this.stats.messagesFailed,
153
- lastActivity: this.stats.lastActivity
154
- };
155
- }
156
- incrementReceived() {
157
- this.stats.messagesReceived++;
158
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
159
- }
160
- incrementProcessed() {
161
- this.stats.messagesProcessed++;
162
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
163
- }
164
- incrementFailed() {
165
- this.stats.messagesFailed++;
166
- this.stats.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
167
- }
168
- };
169
- var NatsEventConsumer = class {
170
- static {
171
- __name(this, "NatsEventConsumer");
172
- }
173
- config;
174
- connectionManager;
175
- subscriptions = /* @__PURE__ */ new Map();
176
- constructor(config) {
177
- this.config = config;
178
- const baseConfig = {
179
- type: config.type || "nats",
180
- url: config.url || "nats://localhost:4222",
181
- user: config.user,
182
- password: config.password,
183
- token: config.token,
184
- creds: config.creds,
185
- credsFile: config.credsFile,
186
- maxReconnectAttempts: config.maxReconnectAttempts,
187
- reconnectTimeWait: config.reconnectTimeWait,
188
- connectionTimeout: config.connectionTimeout,
189
- name: config.name
190
- };
191
- this.connectionManager = new NatsConnectionManager(baseConfig);
192
- }
193
- /**
194
- * Connect to NATS server
195
- */
196
- async connect() {
197
- await this.connectionManager.connect();
198
- }
199
- /**
200
- * Disconnect from NATS server
201
- */
202
- async disconnect() {
203
- await this.unsubscribeAll();
204
- await this.connectionManager.disconnect();
205
- }
206
- /**
207
- * Check if connected
208
- */
209
- isConnected() {
210
- return this.connectionManager.isConnected();
211
- }
212
- /**
213
- * Health check
214
- */
215
- async healthCheck() {
216
- await Promise.resolve();
217
- const isConnected = this.isConnected();
218
- return {
219
- status: isConnected ? "healthy" : "unhealthy",
220
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
221
- connected: isConnected,
222
- details: {
223
- type: "nats",
224
- url: this.config.url,
225
- activeSubscriptions: this.subscriptions.size
226
- }
227
- };
228
- }
229
- /**
230
- * Get queue statistics
231
- */
232
- async getStatistics() {
233
- await Promise.resolve();
234
- let totalReceived = 0;
235
- let totalProcessed = 0;
236
- let totalFailed = 0;
237
- let lastActivity = null;
238
- for (const subscription of this.subscriptions.values()) {
239
- const stats = subscription.getStats();
240
- totalReceived += stats.messagesReceived;
241
- totalProcessed += stats.messagesProcessed;
242
- totalFailed += stats.messagesFailed;
243
- if (stats.lastActivity && (!lastActivity || stats.lastActivity > lastActivity)) {
244
- lastActivity = stats.lastActivity;
245
- }
246
- }
247
- return {
248
- messagesPublished: 0,
249
- messagesConsumed: totalProcessed,
250
- messagesFailed: totalFailed,
251
- activeConsumers: this.subscriptions.size,
252
- activePublishers: 0,
253
- queueSize: 0,
254
- lastActivity,
255
- details: {
256
- totalReceived,
257
- type: "nats"
258
- }
259
- };
260
- }
261
- /**
262
- * Ensure a stream exists
263
- */
264
- async ensureStream(config) {
265
- const jsm = this.connectionManager.getJetStreamManager();
266
- try {
267
- try {
268
- await jsm.streams.info(config.name);
269
- logger.debug("[NatsEventConsumer] Stream already exists", {
270
- stream: config.name
271
- });
272
- return;
273
- } catch {
274
- }
275
- const streamConfig = {
276
- name: config.name,
277
- subjects: config.subjects,
278
- retention: this.mapRetentionPolicy(config.retention),
279
- storage: this.mapStorageType(config.storage),
280
- max_consumers: config.maxConsumers,
281
- max_msgs: config.maxMsgs,
282
- max_bytes: config.maxBytes ?? DEFAULT_STREAM_MAX_BYTES,
283
- max_age: config.maxAge,
284
- duplicate_window: config.duplicateWindow
285
- };
286
- await jsm.streams.add(streamConfig);
287
- logger.info("[NatsEventConsumer] Stream created successfully", {
288
- stream: config.name,
289
- subjects: config.subjects
290
- });
291
- } catch (error) {
292
- logger.error("[NatsEventConsumer] Failed to ensure stream", {
293
- stream: config.name,
294
- error: error instanceof Error ? error.message : "Unknown error"
295
- });
296
- throw error;
297
- }
298
- }
299
- /**
300
- * Ensure a consumer exists
301
- */
302
- async ensureConsumer(config) {
303
- const jsm = this.connectionManager.getJetStreamManager();
304
- try {
305
- await jsm.consumers.add(config.stream, {
306
- name: config.consumer,
307
- durable_name: config.consumer,
308
- filter_subject: config.filterSubject,
309
- ack_policy: this.mapAckPolicy(config.ackPolicy),
310
- deliver_policy: this.mapDeliverPolicy(config.deliverPolicy),
311
- max_deliver: config.maxDeliver || 3,
312
- ack_wait: config.ackWait || 3e10,
313
- max_ack_pending: config.maxAckPending || 100
314
- });
315
- logger.info("[NatsEventConsumer] Consumer created successfully", {
316
- stream: config.stream,
317
- consumer: config.consumer
318
- });
319
- } catch (error) {
320
- if (error instanceof Error && error.message?.includes("already exists")) {
321
- logger.debug("[NatsEventConsumer] Consumer already exists", {
322
- stream: config.stream,
323
- consumer: config.consumer
324
- });
325
- } else {
326
- logger.error("[NatsEventConsumer] Failed to ensure consumer", {
327
- stream: config.stream,
328
- consumer: config.consumer,
329
- error: error instanceof Error ? error.message : "Unknown error"
330
- });
331
- throw error;
332
- }
333
- }
334
- }
335
- /**
336
- * Derive stream subject pattern from subscription subject
337
- * Examples:
338
- * - "channel.conversation.message" → ["channel.>"]
339
- * - "wspace.tags.created" → ["wspace.>"]
340
- * - "global.auth.login" → ["global.>"]
341
- */
342
- deriveStreamSubjects(subject) {
343
- const firstSegment = subject.split(".")[0];
344
- if (firstSegment) {
345
- return [
346
- `${firstSegment}.>`
347
- ];
348
- }
349
- return [
350
- `${subject.replace(/\.[^.]+$/, ".>")}`
351
- ];
352
- }
353
- /**
354
- * Subscribe to a subject
355
- */
356
- async subscribe(options) {
357
- const js = this.connectionManager.getJetStream();
358
- try {
359
- const streamName = options.options?.stream || this.config.stream;
360
- const consumerName = options.options?.consumer || `${this.config.consumer}-${options.subject.replace(/\./g, "-")}`;
361
- const streamSubjects = options.options?.streamSubjects || this.deriveStreamSubjects(options.subject);
362
- await this.ensureStream({
363
- name: streamName,
364
- subjects: streamSubjects,
365
- retention: options.options?.retention || "limits",
366
- storage: options.options?.storage || "file"
367
- });
368
- await this.ensureConsumer({
369
- type: this.config.type,
370
- url: this.config.url,
371
- consumer: consumerName,
372
- stream: streamName,
373
- filterSubject: options.subject,
374
- ackPolicy: options.options?.ackPolicy,
375
- deliverPolicy: options.options?.deliverPolicy,
376
- maxDeliver: options.options?.maxDeliver || this.config.maxDeliver,
377
- ackWait: options.options?.ackWait || this.config.ackWait,
378
- maxAckPending: options.options?.maxAckPending
379
- });
380
- const consumer = await js.consumers.get(streamName, consumerName);
381
- const subscriptionId = `sub_${Date.now()}_${crypto.randomUUID().substring(0, 7)}`;
382
- let stopRequested = false;
383
- const stopFn = /* @__PURE__ */ __name(() => {
384
- stopRequested = true;
385
- }, "stopFn");
386
- const subscription = new NatsSubscription(subscriptionId, options.subject, stopFn);
387
- this.subscriptions.set(subscriptionId, subscription);
388
- this.consumeMessages(consumer, subscription, options.handler, options.options?.maxConcurrent || this.config.maxConcurrent || 1, () => stopRequested).catch((error) => {
389
- logger.error("[NatsEventConsumer] Error in message consumption loop", {
390
- subject: options.subject,
391
- error: error instanceof Error ? error.message : "Unknown error"
392
- });
393
- });
394
- logger.info("[NatsEventConsumer] Subscription created", {
395
- subscriptionId,
396
- subject: options.subject
397
- });
398
- return subscription;
399
- } catch (error) {
400
- logger.error("[NatsEventConsumer] Failed to subscribe", {
401
- subject: options.subject,
402
- error: error instanceof Error ? error.message : "Unknown error"
403
- });
404
- throw error;
405
- }
406
- }
407
- /**
408
- * Subscribe to multiple subjects
409
- */
410
- async subscribeMultiple(subjects, handler, options) {
411
- const subscriptions = [];
412
- for (const subject of subjects) {
413
- const subscription = await this.subscribe({
414
- subject,
415
- handler,
416
- options
417
- });
418
- subscriptions.push(subscription);
419
- }
420
- return subscriptions;
421
- }
422
- /**
423
- * Pull messages manually
424
- */
425
- async pull(options) {
426
- const js = this.connectionManager.getJetStream();
427
- try {
428
- const consumer = await js.consumers.get(this.config.stream, this.config.consumer);
429
- const messages = await consumer.fetch({
430
- max_messages: options.batch || 10,
431
- expires: options.timeout || 3e4
432
- });
433
- const events = [];
434
- for await (const msg of messages) {
435
- const event = this.wrapMessage(msg);
436
- events.push(event);
437
- }
438
- return events;
439
- } catch (error) {
440
- logger.error("[NatsEventConsumer] Failed to pull messages", {
441
- subject: options.subject,
442
- error: error instanceof Error ? error.message : "Unknown error"
443
- });
444
- throw error;
445
- }
446
- }
447
- /**
448
- * Unsubscribe from all active subscriptions
449
- */
450
- async unsubscribeAll() {
451
- const unsubscribePromises = Array.from(this.subscriptions.values()).map(async (subscription) => subscription.unsubscribe());
452
- await Promise.all(unsubscribePromises);
453
- this.subscriptions.clear();
454
- logger.info("[NatsEventConsumer] All subscriptions unsubscribed");
455
- }
456
- /**
457
- * Get all active subscriptions
458
- */
459
- getSubscriptions() {
460
- return Array.from(this.subscriptions.values());
461
- }
462
- /**
463
- * Process pending messages in dead letter queue
464
- */
465
- async processDLQ(_handler) {
466
- await Promise.resolve();
467
- logger.warn("[NatsEventConsumer] DLQ processing not yet implemented");
468
- }
469
- /**
470
- * List subjects for the configured stream
471
- */
472
- async listSubjects(streamName) {
473
- const jsm = this.connectionManager.getJetStreamManager();
474
- const info = await jsm.streams.info(streamName || this.config.stream);
475
- return info.config.subjects || [];
476
- }
477
- /**
478
- * Consume messages from consumer
479
- */
480
- async consumeMessages(consumer, subscription, handler, maxConcurrent, stopRequested) {
481
- try {
482
- const messages = await consumer.consume({
483
- max_messages: maxConcurrent,
484
- expires: 3e4
485
- });
486
- for await (const msg of messages) {
487
- if (stopRequested()) {
488
- break;
489
- }
490
- subscription.incrementReceived();
491
- try {
492
- const event = this.wrapMessage(msg);
493
- await runWithConsumerSpan(msg.subject, msg.headers, async () => handler(event));
494
- subscription.incrementProcessed();
495
- } catch (error) {
496
- subscription.incrementFailed();
497
- logger.error("[NatsEventConsumer] Error processing message", {
498
- subject: msg.subject,
499
- error: error instanceof Error ? error.message : "Unknown error"
500
- });
501
- msg.nak();
502
- }
503
- }
504
- } catch (error) {
505
- logger.error("[NatsEventConsumer] Error consuming messages", {
506
- error: error instanceof Error ? error.message : "Unknown error"
507
- });
508
- }
509
- }
510
- /**
511
- * Wrap NATS message in AcknowledgeableEvent
512
- */
513
- wrapMessage(msg) {
514
- const eventMessage = JSON.parse(msg.data.toString());
515
- return {
516
- ...eventMessage,
517
- sequence: msg.seq,
518
- ack: /* @__PURE__ */ __name(async () => {
519
- await Promise.resolve();
520
- msg.ack();
521
- }, "ack"),
522
- nak: /* @__PURE__ */ __name(async (delay) => {
523
- await Promise.resolve();
524
- if (delay) {
525
- msg.nak(delay);
526
- } else {
527
- msg.nak();
528
- }
529
- }, "nak"),
530
- term: /* @__PURE__ */ __name(async () => {
531
- await Promise.resolve();
532
- msg.term();
533
- }, "term"),
534
- isRedelivered: /* @__PURE__ */ __name(() => {
535
- return msg.redelivered;
536
- }, "isRedelivered"),
537
- getDeliveryAttempt: /* @__PURE__ */ __name(() => {
538
- return msg.info.deliveryCount;
539
- }, "getDeliveryAttempt")
540
- };
541
- }
542
- /**
543
- * Map retention policy string to NATS enum
544
- */
545
- mapRetentionPolicy(policy) {
546
- switch (policy?.toLowerCase()) {
547
- case "limits":
548
- return RetentionPolicy.Limits;
549
- case "interest":
550
- return RetentionPolicy.Interest;
551
- case "workqueue":
552
- default:
553
- return RetentionPolicy.Workqueue;
554
- }
555
- }
556
- /**
557
- * Map storage type string to NATS enum
558
- */
559
- mapStorageType(storage) {
560
- switch (storage?.toLowerCase()) {
561
- case "memory":
562
- return StorageType.Memory;
563
- case "file":
564
- default:
565
- return StorageType.File;
566
- }
567
- }
568
- /**
569
- * Map ack policy string to NATS enum
570
- */
571
- mapAckPolicy(policy) {
572
- switch (policy?.toLowerCase()) {
573
- case "none":
574
- return AckPolicy.None;
575
- case "all":
576
- return AckPolicy.All;
577
- case "explicit":
578
- default:
579
- return AckPolicy.Explicit;
580
- }
581
- }
582
- /**
583
- * Map deliver policy string to NATS enum
584
- */
585
- mapDeliverPolicy(policy) {
586
- switch (policy?.toLowerCase()) {
587
- case "new":
588
- return DeliverPolicy.New;
589
- case "last":
590
- return DeliverPolicy.Last;
591
- case "lastpersubject":
592
- return DeliverPolicy.LastPerSubject;
593
- case "all":
594
- default:
595
- return DeliverPolicy.All;
596
- }
597
- }
598
- };
599
- var DEFAULT_STREAM_MAX_BYTES2 = 10 * 1024 * 1024;
600
- var NatsEventPublisher = class {
601
- static {
602
- __name(this, "NatsEventPublisher");
603
- }
604
- config;
605
- connectionManager;
606
- publishCount = 0;
607
- lastPublishTime = null;
608
- constructor(config) {
609
- this.config = config;
610
- this.connectionManager = new NatsConnectionManager(config);
611
- }
612
- /**
613
- * Connect to NATS server
614
- */
615
- async connect() {
616
- await this.connectionManager.connect();
617
- }
618
- /**
619
- * Disconnect from NATS server
620
- */
621
- async disconnect() {
622
- await this.connectionManager.disconnect();
623
- }
624
- /**
625
- * Check if connected
626
- */
627
- isConnected() {
628
- return this.connectionManager.isConnected();
629
- }
630
- /**
631
- * Health check
632
- */
633
- async healthCheck() {
634
- await Promise.resolve();
635
- const isConnected = this.isConnected();
636
- return {
637
- status: isConnected ? "healthy" : "unhealthy",
638
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
639
- details: {
640
- connected: isConnected,
641
- type: "nats",
642
- url: this.config.url
643
- }
644
- };
645
- }
646
- /**
647
- * Get queue statistics
648
- */
649
- async getStatistics() {
650
- const jsm = this.connectionManager.getJetStreamManager();
651
- try {
652
- const streams = await jsm.streams.list().next();
653
- const streamCount = streams.length;
654
- return {
655
- messagesPublished: this.publishCount,
656
- messagesConsumed: 0,
657
- messagesFailed: 0,
658
- activeConsumers: 0,
659
- activePublishers: 1,
660
- queueSize: 0,
661
- lastActivity: this.lastPublishTime?.toISOString() || null,
662
- details: {
663
- streamCount,
664
- type: "nats"
665
- }
666
- };
667
- } catch (error) {
668
- logger.error("[NatsEventPublisher] Failed to get statistics", {
669
- error: error instanceof Error ? error.message : "Unknown error"
670
- });
671
- throw error;
672
- }
673
- }
674
- /**
675
- * Ensure a stream exists
676
- */
677
- async ensureStream(config) {
678
- const jsm = this.connectionManager.getJetStreamManager();
679
- try {
680
- try {
681
- await jsm.streams.info(config.name);
682
- logger.debug("[NatsEventPublisher] Stream already exists", {
683
- stream: config.name
684
- });
685
- return;
686
- } catch {
687
- }
688
- const streamConfig = {
689
- name: config.name,
690
- subjects: config.subjects,
691
- retention: this.mapRetentionPolicy(config.retention),
692
- storage: this.mapStorageType(config.storage),
693
- max_consumers: config.maxConsumers,
694
- max_msgs: config.maxMsgs,
695
- max_bytes: config.maxBytes ?? DEFAULT_STREAM_MAX_BYTES2,
696
- max_age: config.maxAge,
697
- duplicate_window: config.duplicateWindow
698
- };
699
- await jsm.streams.add(streamConfig);
700
- logger.info("[NatsEventPublisher] Stream created successfully", {
701
- stream: config.name,
702
- subjects: config.subjects
703
- });
704
- } catch (error) {
705
- logger.error("[NatsEventPublisher] Failed to ensure stream", {
706
- stream: config.name,
707
- error: error instanceof Error ? error.message : "Unknown error"
708
- });
709
- throw error;
710
- }
711
- }
712
- /**
713
- * Derive stream subject pattern from subscription subject
714
- * Examples:
715
- * - "channel.conversation.message" → ["channel.>"]
716
- * - "wspace.tags.created" → ["wspace.>"]
717
- * - "global.auth.login" → ["global.>"]
718
- */
719
- deriveStreamSubjects(subject) {
720
- const firstSegment = subject.split(".")[0];
721
- if (firstSegment) {
722
- return [
723
- `${firstSegment}.>`
724
- ];
725
- }
726
- return [
727
- `${subject.replace(/\.[^.]+$/, ".>")}`
728
- ];
729
- }
730
- /**
731
- * Derive stream name from subject
732
- * Examples:
733
- * - "channel.conversation.message" → "CHANNEL_EVENTS"
734
- * - "wspace.tags.created" → "WSPACE_EVENTS"
735
- * - "global.auth.login" → "GLOBAL_EVENTS"
736
- */
737
- deriveStreamName(subject) {
738
- const firstSegment = subject.split(".")[0];
739
- if (firstSegment) {
740
- return `${firstSegment.toUpperCase()}_EVENTS`;
741
- }
742
- return "EVENTS";
743
- }
744
- /**
745
- * Publish an event to a subject
746
- */
747
- async publish(options) {
748
- const js = this.connectionManager.getJetStream();
749
- try {
750
- const streamName = options.options?.stream || this.deriveStreamName(options.subject);
751
- const streamSubjects = options.options?.streamSubjects || this.deriveStreamSubjects(options.subject);
752
- await this.ensureStream({
753
- name: streamName,
754
- subjects: streamSubjects,
755
- retention: options.options?.retention || "limits",
756
- storage: options.options?.storage || "file"
757
- });
758
- const message = {
759
- id: options.options?.messageId || this.generateMessageId(),
760
- subject: options.subject,
761
- data: options.data,
762
- metadata: {
763
- source: options.metadata?.source || "workspaces-backend",
764
- correlationId: options.metadata?.correlationId || this.generateCorrelationId(),
765
- userId: options.metadata?.userId,
766
- workspaceId: options.metadata?.workspaceId,
767
- priority: options.options?.priority || this.config.defaultPriority || "normal",
768
- ...options.metadata
769
- },
770
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
771
- };
772
- const hdrs = headers();
773
- hdrs.set("message-id", message.id);
774
- hdrs.set("correlation-id", message.metadata.correlationId);
775
- if (message.metadata.source) {
776
- hdrs.set("source", message.metadata.source);
777
- }
778
- if (message.metadata["priority"] && typeof message.metadata["priority"] === "string") {
779
- hdrs.set("priority", message.metadata["priority"]);
780
- }
781
- if (message.metadata.userId) {
782
- hdrs.set("user-id", message.metadata.userId);
783
- }
784
- if (message.metadata.workspaceId) {
785
- hdrs.set("workspace-id", message.metadata.workspaceId);
786
- }
787
- await injectW3CTraceContext(hdrs);
788
- const publishOpts = {
789
- msgID: this.config.enableDeduplication ? message.id : void 0,
790
- headers: hdrs
791
- };
792
- if (options.options?.ttl) {
793
- logger.warn("[NatsEventPublisher] Per-message TTL not supported in NATS", {
794
- subject: options.subject,
795
- ttl: options.options.ttl
796
- });
797
- }
798
- if (options.options?.delay) {
799
- logger.warn("[NatsEventPublisher] Message delay not supported in NATS", {
800
- subject: options.subject,
801
- delay: options.options.delay
802
- });
803
- }
804
- const ack = await js.publish(options.subject, JSON.stringify(message), publishOpts);
805
- this.publishCount++;
806
- this.lastPublishTime = /* @__PURE__ */ new Date();
807
- logger.debug("[NatsEventPublisher] Event published", {
808
- subject: options.subject,
809
- messageId: message.id,
810
- sequence: ack.seq
811
- });
812
- return ack.seq;
813
- } catch (error) {
814
- logger.error("[NatsEventPublisher] Failed to publish event", {
815
- subject: options.subject,
816
- error: error instanceof Error ? error.message : "Unknown error"
817
- });
818
- throw error;
819
- }
820
- }
821
- /**
822
- * Publish multiple events in a batch
823
- */
824
- async publishBatch(events) {
825
- const results = [];
826
- for (const event of events) {
827
- const seq = await this.publish(event);
828
- results.push(seq);
829
- }
830
- return results;
831
- }
832
- /**
833
- * Publish an event and wait for acknowledgment
834
- * Note: This is not natively supported by NATS JetStream
835
- * Would require implementing request-reply pattern
836
- */
837
- async publishWithAck(options) {
838
- const nc = this.connectionManager.getNatsConnection();
839
- try {
840
- const message = {
841
- id: this.generateMessageId(),
842
- subject: options.subject,
843
- data: options.data,
844
- metadata: {
845
- source: options.metadata?.source || "workspaces-backend",
846
- correlationId: options.metadata?.correlationId || this.generateCorrelationId(),
847
- userId: options.metadata?.userId,
848
- workspaceId: options.metadata?.workspaceId,
849
- ...options.metadata
850
- },
851
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
852
- };
853
- const response = await nc.request(options.subject, JSON.stringify(message), {
854
- timeout: options.timeout || 3e4
855
- });
856
- const result = JSON.parse(response.data.toString());
857
- logger.debug("[NatsEventPublisher] Event published with ack", {
858
- subject: options.subject,
859
- messageId: message.id
860
- });
861
- return result;
862
- } catch (error) {
863
- logger.error("[NatsEventPublisher] Failed to publish event with ack", {
864
- subject: options.subject,
865
- error: error instanceof Error ? error.message : "Unknown error"
866
- });
867
- throw error;
868
- }
869
- }
870
- /**
871
- * Map retention policy string to NATS enum
872
- */
873
- mapRetentionPolicy(policy) {
874
- switch (policy?.toLowerCase()) {
875
- case "limits":
876
- return RetentionPolicy.Limits;
877
- case "interest":
878
- return RetentionPolicy.Interest;
879
- case "workqueue":
880
- default:
881
- return RetentionPolicy.Workqueue;
882
- }
883
- }
884
- /**
885
- * Map storage type string to NATS enum
886
- */
887
- mapStorageType(storage) {
888
- switch (storage?.toLowerCase()) {
889
- case "memory":
890
- return StorageType.Memory;
891
- case "file":
892
- default:
893
- return StorageType.File;
894
- }
895
- }
896
- /**
897
- * Generate unique message ID
898
- */
899
- generateMessageId() {
900
- return `msg_${Date.now()}_${crypto.randomUUID().substring(0, 13)}`;
901
- }
902
- /**
903
- * Generate correlation ID
904
- */
905
- generateCorrelationId() {
906
- return `corr_${Date.now()}_${crypto.randomUUID().substring(0, 13)}`;
907
- }
908
- };
909
-
910
- // src/event-queue/factory/EventQueueFactory.ts
911
- var EventQueueFactory = class _EventQueueFactory {
912
- static {
913
- __name(this, "EventQueueFactory");
914
- }
915
- /**
916
- * Create an event publisher based on configuration
917
- */
918
- static createPublisher(config) {
919
- logger.info("[EventQueueFactory] Creating event publisher", {
920
- type: config.type,
921
- url: config.url
922
- });
923
- if (config.type === QueueType.NATS) {
924
- return new NatsEventPublisher(config);
925
- }
926
- throw new Error(`Unsupported queue type: ${config.type}`);
927
- }
928
- /**
929
- * Create an event consumer based on configuration
930
- */
931
- static createConsumer(config) {
932
- logger.info("[EventQueueFactory] Creating event consumer", {
933
- type: config.type,
934
- url: config.url,
935
- stream: config.stream,
936
- consumer: config.consumer
937
- });
938
- if (config.type === QueueType.NATS) {
939
- return new NatsEventConsumer(config);
940
- }
941
- throw new Error(`Unsupported queue type: ${config.type}`);
942
- }
943
- /**
944
- * Create a publisher from environment variables
945
- */
946
- static createPublisherFromEnv() {
947
- const config = {
948
- type: process.env["QUEUE_TYPE"] || QueueType.NATS,
949
- url: process.env["NATS_URL"] || "nats://localhost:4222",
950
- user: process.env["NATS_USER"],
951
- password: process.env["NATS_PASSWORD"],
952
- token: process.env["NATS_TOKEN"],
953
- creds: process.env["NATS_CREDS"],
954
- credsFile: process.env["NATS_CREDS_FILE"],
955
- name: process.env["QUEUE_CLIENT_NAME"] || "workspaces-backend-publisher",
956
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
957
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
958
- enableDeduplication: process.env["QUEUE_ENABLE_DEDUPLICATION"] === "true",
959
- defaultPriority: process.env["QUEUE_DEFAULT_PRIORITY"] || "normal",
960
- defaultTTL: process.env["QUEUE_DEFAULT_TTL"] ? parseInt(process.env["QUEUE_DEFAULT_TTL"], 10) : void 0
961
- };
962
- return _EventQueueFactory.createPublisher(config);
963
- }
964
- /**
965
- * Create a consumer from environment variables
966
- */
967
- static createConsumerFromEnv(stream, consumer) {
968
- const config = {
969
- type: process.env["QUEUE_TYPE"] || QueueType.NATS,
970
- url: process.env["NATS_URL"] || "nats://localhost:4222",
971
- user: process.env["NATS_USER"],
972
- password: process.env["NATS_PASSWORD"],
973
- token: process.env["NATS_TOKEN"],
974
- creds: process.env["NATS_CREDS"],
975
- credsFile: process.env["NATS_CREDS_FILE"],
976
- name: process.env["QUEUE_CLIENT_NAME"] || "workspaces-workers-consumer",
977
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
978
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
979
- stream,
980
- consumer,
981
- maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
982
- maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
983
- ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
984
- };
985
- return _EventQueueFactory.createConsumer(config);
986
- }
987
- // ========================================================================
988
- // Layer-Aware Factory Methods
989
- // ========================================================================
990
- /**
991
- * Create a publisher for a specific layer
992
- *
993
- * @param layer - Service layer ('wspace' or 'global')
994
- * @param serviceName - Service name for identification
995
- * @returns Publisher configured for the layer
996
- *
997
- * @example
998
- * ```typescript
999
- * const publisher = EventQueueFactory.createPublisherForLayer('wspace', 'wspace-tags-svc');
1000
- * await publisher.connect();
1001
- * await publisher.publish({ subject: 'wspace.tags.created', data: { id: '123' } });
1002
- * ```
1003
- */
1004
- static createPublisherForLayer(layer, serviceName) {
1005
- const envPrefix = layer.toUpperCase();
1006
- const defaults = DEFAULT_LAYER_RESOURCES[layer];
1007
- const config = {
1008
- type: QueueType.NATS,
1009
- url: process.env[`${envPrefix}_NATS_URL`] || process.env["NATS_URL"] || defaults.natsUrl,
1010
- user: process.env["NATS_USER"],
1011
- password: process.env["NATS_PASSWORD"],
1012
- token: process.env["NATS_TOKEN"],
1013
- creds: process.env["NATS_CREDS"],
1014
- credsFile: process.env["NATS_CREDS_FILE"],
1015
- name: serviceName,
1016
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1017
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
1018
- enableDeduplication: process.env["QUEUE_ENABLE_DEDUPLICATION"] === "true",
1019
- defaultPriority: process.env["QUEUE_DEFAULT_PRIORITY"] || "normal",
1020
- defaultTTL: process.env["QUEUE_DEFAULT_TTL"] ? parseInt(process.env["QUEUE_DEFAULT_TTL"], 10) : void 0
1021
- };
1022
- logger.info("[EventQueueFactory] Creating layer publisher", {
1023
- layer,
1024
- serviceName,
1025
- url: config.url
1026
- });
1027
- return _EventQueueFactory.createPublisher(config);
1028
- }
1029
- /**
1030
- * Create a consumer for a specific layer
1031
- *
1032
- * @param layer - Service layer ('wspace' or 'global')
1033
- * @param serviceName - Service name for identification
1034
- * @param stream - NATS stream name
1035
- * @param consumer - Consumer name
1036
- * @returns Consumer configured for the layer
1037
- *
1038
- * @example
1039
- * ```typescript
1040
- * const consumer = EventQueueFactory.createConsumerForLayer(
1041
- * 'wspace', 'wspace-tags-svc', 'WSPACE_EVENTS', 'tags-consumer'
1042
- * );
1043
- * await consumer.connect();
1044
- * await consumer.consume(async (msg) => { console.log(msg); });
1045
- * ```
1046
- */
1047
- static createConsumerForLayer(layer, serviceName, stream, consumer) {
1048
- const envPrefix = layer.toUpperCase();
1049
- const defaults = DEFAULT_LAYER_RESOURCES[layer];
1050
- const config = {
1051
- type: QueueType.NATS,
1052
- url: process.env[`${envPrefix}_NATS_URL`] || process.env["NATS_URL"] || defaults.natsUrl,
1053
- user: process.env["NATS_USER"],
1054
- password: process.env["NATS_PASSWORD"],
1055
- token: process.env["NATS_TOKEN"],
1056
- creds: process.env["NATS_CREDS"],
1057
- credsFile: process.env["NATS_CREDS_FILE"],
1058
- name: serviceName,
1059
- maxReconnectAttempts: process.env["NATS_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["NATS_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1060
- reconnectTimeWait: process.env["NATS_RECONNECT_TIME_WAIT"] ? parseInt(process.env["NATS_RECONNECT_TIME_WAIT"], 10) : 2e3,
1061
- stream,
1062
- consumer,
1063
- maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
1064
- maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
1065
- ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
1066
- };
1067
- logger.info("[EventQueueFactory] Creating layer consumer", {
1068
- layer,
1069
- serviceName,
1070
- stream,
1071
- consumer,
1072
- url: config.url
1073
- });
1074
- return _EventQueueFactory.createConsumer(config);
1075
- }
1076
- };
1077
-
1078
- export { EventQueueFactory, NatsEventConsumer, NatsEventPublisher };
1079
- //# sourceMappingURL=chunk-L2F2SCEJ.js.map
1080
- //# sourceMappingURL=chunk-L2F2SCEJ.js.map