@open-wa/hyperemitter 5.6.5 → 5.6.7

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/dist/index.mjs ADDED
@@ -0,0 +1,1039 @@
1
+ import { Cause, Effect, Exit, Fiber, PubSub, Scope, Stream } from "effect";
2
+ import { createLogger } from "@open-wa/logger";
3
+ //#region src/routing/RadixNode.ts
4
+ /**
5
+ * Monomorphic radix tree node for MQTT-style wildcard routing.
6
+ */
7
+ var RadixNode = class {
8
+ segment;
9
+ listeners;
10
+ children;
11
+ wildcardSingle;
12
+ wildcardMulti;
13
+ constructor(segment) {
14
+ this.segment = segment;
15
+ this.listeners = [];
16
+ this.children = null;
17
+ this.wildcardSingle = null;
18
+ this.wildcardMulti = null;
19
+ }
20
+ };
21
+ //#endregion
22
+ //#region src/routing/RadixTree.ts
23
+ /** Segment trie; multi-segment wildcard states are deduplicated during matching. */
24
+ var RadixTree = class {
25
+ delimiter;
26
+ style;
27
+ root = new RadixNode("");
28
+ single;
29
+ multi;
30
+ constructor(delimiter = ".", style = "mqtt") {
31
+ this.delimiter = delimiter;
32
+ this.style = style;
33
+ this.single = style === "mqtt" ? "+" : "*";
34
+ this.multi = style === "mqtt" ? "#" : "**";
35
+ }
36
+ insert(pattern, value, prepend = false) {
37
+ let node = this.root;
38
+ for (const segment of pattern.split(this.delimiter)) if (segment === this.single) node = node.wildcardSingle ??= new RadixNode(this.single);
39
+ else if (segment === this.multi) {
40
+ node = node.wildcardMulti ??= new RadixNode(this.multi);
41
+ if (this.style === "mqtt") break;
42
+ } else {
43
+ node.children ??= /* @__PURE__ */ new Map();
44
+ let child = node.children.get(segment);
45
+ if (!child) node.children.set(segment, child = new RadixNode(segment));
46
+ node = child;
47
+ }
48
+ if (prepend) node.listeners.unshift(value);
49
+ else node.listeners.push(value);
50
+ }
51
+ remove(pattern, value) {
52
+ let node = this.root;
53
+ const path = [];
54
+ for (const segment of pattern.split(this.delimiter)) {
55
+ const child = segment === this.single ? node.wildcardSingle : segment === this.multi ? node.wildcardMulti : node.children?.get(segment);
56
+ if (!child) return;
57
+ path.push([
58
+ node,
59
+ child,
60
+ segment
61
+ ]);
62
+ node = child;
63
+ if (segment === this.multi && this.style === "mqtt") break;
64
+ }
65
+ const index = node.listeners.indexOf(value);
66
+ if (index >= 0) node.listeners.splice(index, 1);
67
+ for (const [parent, child, segment] of path.reverse()) {
68
+ if (child.listeners.length || child.children?.size || child.wildcardSingle || child.wildcardMulti) break;
69
+ if (segment === this.single) parent.wildcardSingle = null;
70
+ else if (segment === this.multi) parent.wildcardMulti = null;
71
+ else parent.children?.delete(segment);
72
+ }
73
+ }
74
+ match(event) {
75
+ const segments = event.split(this.delimiter);
76
+ if (this.style === "mqtt") {
77
+ const stack = [[this.root, 0]];
78
+ const results = [];
79
+ while (stack.length) {
80
+ const [node, index] = stack.pop();
81
+ if (node.wildcardMulti) results.push(...node.wildcardMulti.listeners);
82
+ if (index === segments.length) {
83
+ results.push(...node.listeners);
84
+ continue;
85
+ }
86
+ if (node.wildcardSingle) stack.push([node.wildcardSingle, index + 1]);
87
+ const child = node.children?.get(segments[index]);
88
+ if (child) stack.push([child, index + 1]);
89
+ }
90
+ return results;
91
+ }
92
+ const stack = [[this.root, 0]];
93
+ const visited = /* @__PURE__ */ new Map();
94
+ const collected = /* @__PURE__ */ new Set();
95
+ const results = [];
96
+ while (stack.length) {
97
+ const [node, index] = stack.pop();
98
+ let indices = visited.get(node);
99
+ if (indices?.has(index)) continue;
100
+ if (!indices) visited.set(node, indices = /* @__PURE__ */ new Set());
101
+ indices.add(index);
102
+ if ((index === segments.length || node.segment === this.multi) && !collected.has(node)) {
103
+ results.push(...node.listeners);
104
+ collected.add(node);
105
+ }
106
+ if (node.wildcardMulti) stack.push([node.wildcardMulti, index]);
107
+ if (index < segments.length) {
108
+ if (node.segment === this.multi) stack.push([node, index + 1]);
109
+ if (node.wildcardSingle) stack.push([node.wildcardSingle, index + 1]);
110
+ const child = node.children?.get(segments[index]);
111
+ if (child) stack.push([child, index + 1]);
112
+ }
113
+ }
114
+ return results;
115
+ }
116
+ };
117
+ //#endregion
118
+ //#region src/routing/patternsIntersect.ts
119
+ /** Whether two namespace patterns share at least one concrete event name. */
120
+ function patternsIntersect(left, right, delimiter = ".") {
121
+ const a = left.split(delimiter), b = right.split(delimiter);
122
+ const stack = [[0, 0]];
123
+ const seen = /* @__PURE__ */ new Set();
124
+ while (stack.length) {
125
+ const [i, j] = stack.pop();
126
+ const state = `${i}:${j}`;
127
+ if (seen.has(state)) continue;
128
+ seen.add(state);
129
+ if (i === a.length && j === b.length) return true;
130
+ if (a[i] === "**") stack.push([i + 1, j]);
131
+ if (b[j] === "**") stack.push([i, j + 1]);
132
+ if (i === a.length || j === b.length) continue;
133
+ if (a[i] === b[j] || a[i] === "*" || a[i] === "**" || b[j] === "*" || b[j] === "**") stack.push([a[i] === "**" ? i : i + 1, b[j] === "**" ? j : j + 1]);
134
+ }
135
+ return false;
136
+ }
137
+ //#endregion
138
+ //#region src/core/EmissionHub.ts
139
+ /** Optional queued observation; normal callbacks never depend on consumers draining. */
140
+ var EmissionHub = class {
141
+ hub;
142
+ configuration;
143
+ accepted = 0;
144
+ rejected = 0;
145
+ get enabled() {
146
+ return !!this.hub && !PubSub.isShutdownUnsafe(this.hub);
147
+ }
148
+ get(options) {
149
+ if (this.hub && options === void 0) return this.hub;
150
+ const strategy = options?.strategy ?? "unbounded";
151
+ const capacity = options && "capacity" in options ? options.capacity : Infinity;
152
+ const replay = options?.replay ?? 0;
153
+ if (![
154
+ "unbounded",
155
+ "dropping",
156
+ "sliding"
157
+ ].includes(strategy)) throw new TypeError("PubSub observations require a non-blocking strategy");
158
+ if (strategy === "unbounded" && options && "capacity" in options) throw new TypeError("Choose dropping or sliding when specifying PubSub capacity");
159
+ if (strategy !== "unbounded" && (!Number.isInteger(capacity) || capacity <= 0)) throw new TypeError("PubSub capacity must be a positive integer");
160
+ if (!Number.isInteger(replay) || replay < 0) throw new TypeError("PubSub replay must be a non-negative integer");
161
+ if (this.hub) {
162
+ const current = this.configuration;
163
+ if (current.strategy !== strategy || current.capacity !== capacity || current.replay !== replay) throw new Error("PubSub is already configured; choose its options before subscribing");
164
+ return this.hub;
165
+ }
166
+ const hub = Effect.runSync(strategy === "unbounded" ? PubSub.unbounded({ replay }) : strategy === "dropping" ? PubSub.dropping({
167
+ capacity,
168
+ replay
169
+ }) : PubSub.sliding({
170
+ capacity,
171
+ replay
172
+ }));
173
+ this.configuration = {
174
+ strategy,
175
+ capacity,
176
+ replay
177
+ };
178
+ this.hub = hub;
179
+ return hub;
180
+ }
181
+ publish(value) {
182
+ if (!this.hub) return;
183
+ if (this.configuration.strategy === "sliding" ? Effect.runSync(PubSub.publish(this.hub, value)) : PubSub.publishUnsafe(this.hub, value)) this.accepted++;
184
+ else this.rejected++;
185
+ }
186
+ status() {
187
+ return {
188
+ enabled: !!this.hub,
189
+ shutdown: !!this.hub && PubSub.isShutdownUnsafe(this.hub),
190
+ strategy: this.configuration?.strategy,
191
+ accepted: this.accepted,
192
+ rejected: this.rejected
193
+ };
194
+ }
195
+ close() {
196
+ return this.hub ? PubSub.shutdown(this.hub) : Effect.void;
197
+ }
198
+ };
199
+ //#endregion
200
+ //#region src/utils/listener.ts
201
+ function createRecord(fn, opts, finalizer) {
202
+ const record = {
203
+ fn,
204
+ once: false,
205
+ any: false,
206
+ signal: opts.signal,
207
+ captureRejections: opts.captureRejections
208
+ };
209
+ if (opts.weak && typeof WeakRef !== "undefined") {
210
+ record.weakRef = new WeakRef(opts.weak);
211
+ if (finalizer) {
212
+ const token = {};
213
+ record.finalizerToken = token;
214
+ finalizer.register(opts.weak, token, token);
215
+ }
216
+ }
217
+ return record;
218
+ }
219
+ function attachAbort(record, remove) {
220
+ if (!record.signal) return;
221
+ if (record.signal.aborted) {
222
+ remove();
223
+ return;
224
+ }
225
+ const handler = () => remove();
226
+ record.abortHandler = handler;
227
+ record.signal.addEventListener("abort", handler, { once: true });
228
+ }
229
+ function cleanupAbort(record) {
230
+ if (record.signal && record.abortHandler) {
231
+ record.signal.removeEventListener("abort", record.abortHandler);
232
+ record.abortHandler = void 0;
233
+ }
234
+ }
235
+ //#endregion
236
+ //#region src/core/HyperEmitter.ts
237
+ const emitted = Effect.succeed(true);
238
+ const noListeners = Effect.succeed(false);
239
+ var HyperEmitter = class {
240
+ delimiter;
241
+ captureRejections;
242
+ wildcardStyle;
243
+ onError;
244
+ finalizer;
245
+ logger;
246
+ debugEnabled;
247
+ baseLogContext;
248
+ exactListeners;
249
+ wildcardTree;
250
+ wildcardIndex;
251
+ hasWildcards = false;
252
+ anyListeners = /* @__PURE__ */ new Map();
253
+ scope = Scope.makeUnsafe();
254
+ closed = false;
255
+ observations = new EmissionHub();
256
+ get isClosed() {
257
+ return this.closed;
258
+ }
259
+ /** Enable queued observations lazily; direct PubSub publishing reaches this feed only. */
260
+ pubsub(options) {
261
+ this.assertOpen();
262
+ return this.observations.get(options);
263
+ }
264
+ get hasPubSub() {
265
+ return !this.closed && this.observations.enabled;
266
+ }
267
+ get pubsubStatus() {
268
+ return this.observations.status();
269
+ }
270
+ subscribe(options) {
271
+ return Effect.suspend(() => PubSub.subscribe(this.pubsub(options)));
272
+ }
273
+ stream(options) {
274
+ return Stream.suspend(() => Stream.fromPubSub(this.pubsub(options)));
275
+ }
276
+ constructor(options = {}) {
277
+ this.delimiter = options.delimiter ?? ".";
278
+ this.wildcardStyle = options.wildcardStyle ?? "mqtt";
279
+ this.captureRejections = options.captureRejections ?? false;
280
+ this.onError = options.onError;
281
+ this.debugEnabled = !!options.debug;
282
+ this.baseLogContext = {
283
+ component: "hyperemitter",
284
+ ...options.loggerContext
285
+ };
286
+ this.logger = options.logger?.withContext?.(this.baseLogContext) ?? createLogger({
287
+ component: "hyperemitter",
288
+ ...options.loggerContext
289
+ });
290
+ if (typeof FinalizationRegistry !== "undefined") this.finalizer = new FinalizationRegistry((token) => {
291
+ if (token && typeof token === "object") {}
292
+ });
293
+ this.exactListeners = /* @__PURE__ */ new Map();
294
+ this.wildcardTree = new RadixTree(this.delimiter, this.wildcardStyle);
295
+ this.wildcardIndex = /* @__PURE__ */ new Map();
296
+ }
297
+ on(event, listener, options = {}) {
298
+ const record = createRecord(listener, options, this.finalizer);
299
+ this.add(event, record, options.prepend);
300
+ return this;
301
+ }
302
+ once(event, listener, options = {}) {
303
+ const record = createRecord(listener, options, this.finalizer);
304
+ record.once = true;
305
+ this.add(event, record, options.prepend);
306
+ return this;
307
+ }
308
+ /** Register a listener and own its in-flight Effects until the caller's scope closes. */
309
+ onScoped(event, listener, options = {}) {
310
+ return Effect.acquireRelease(Effect.sync(() => {
311
+ this.assertOpen();
312
+ const record = createRecord(listener, options, this.finalizer);
313
+ record.scope = Scope.forkUnsafe(this.scope);
314
+ this.add(event, record, options.prepend);
315
+ return record;
316
+ }), (record) => Effect.sync(() => this.offListener(record)).pipe(Effect.andThen(Scope.close(record.scope, Exit.void)))).pipe(Effect.asVoid);
317
+ }
318
+ off(event, listener) {
319
+ const list = this.exactListeners.get(event);
320
+ if (list) {
321
+ const idx = list.findIndex((l) => l.fn === listener);
322
+ if (idx !== -1) {
323
+ cleanupAbort(list[idx]);
324
+ list.splice(idx, 1);
325
+ }
326
+ if (list.length === 0) this.exactListeners.delete(event);
327
+ }
328
+ if (this.hasWildcards && this.isWildcard(event)) this.removeWildcard(event, listener);
329
+ return this;
330
+ }
331
+ emit(event, payload) {
332
+ if (this.closed) return false;
333
+ if (this.observations.enabled) this.observations.publish(Object.freeze({
334
+ event,
335
+ payload
336
+ }));
337
+ if (this.exactListeners.size === 0 && this.wildcardIndex.size === 0 && this.anyListeners.size === 0) return false;
338
+ const records = this.snapshot(event);
339
+ let called = false;
340
+ for (const record of records) {
341
+ if (!this.prepare(record)) continue;
342
+ called = true;
343
+ try {
344
+ const result = record.any ? record.fn(event, payload) : record.fn(payload);
345
+ if (Effect.isEffect(result) || result && typeof result.then === "function") Effect.runSync(Effect.forkIn(this.resultEffect(result).pipe(Effect.catchCause((cause) => Effect.sync(() => {
346
+ if (!Cause.hasInterruptsOnly(cause)) this.handleRejection(record, Cause.squash(cause));
347
+ }))), record.scope ?? this.scope, { startImmediately: true }));
348
+ } catch (error) {
349
+ if (!this.shouldCapture(record)) throw error;
350
+ this.handleRejection(record, error);
351
+ }
352
+ }
353
+ return called;
354
+ }
355
+ /** Emit lazily and await every listener, including Promise and Effect callbacks. */
356
+ emitEffect(event, payload) {
357
+ return this.dispatch(event, payload, true);
358
+ }
359
+ dispatch(event, payload, awaitListeners) {
360
+ return Effect.suspend(() => {
361
+ if (this.closed) return noListeners;
362
+ if (this.observations.enabled) this.observations.publish(Object.freeze({
363
+ event,
364
+ payload
365
+ }));
366
+ const records = this.snapshot(event);
367
+ if (records.length === 0) return noListeners;
368
+ let pending;
369
+ let called = false;
370
+ let hasAsync = false;
371
+ const loop = (start) => {
372
+ for (let index = start; index < records.length; index++) {
373
+ const record = records[index];
374
+ if (!this.prepare(record)) continue;
375
+ called = true;
376
+ let result;
377
+ try {
378
+ result = record.any ? record.fn(event, payload) : record.fn(payload);
379
+ } catch (error) {
380
+ if (!this.shouldCapture(record)) return Effect.fail(error);
381
+ this.handleRejection(record, error);
382
+ continue;
383
+ }
384
+ if (!Effect.isEffect(result) && !(result && typeof result.then === "function")) continue;
385
+ hasAsync = true;
386
+ const work = this.resultEffect(result);
387
+ const handled = !awaitListeners || this.shouldCapture(record) ? work.pipe(Effect.catchCause((cause) => Effect.sync(() => {
388
+ if (!Cause.hasInterruptsOnly(cause)) this.handleRejection(record, Cause.squash(cause));
389
+ }))) : work;
390
+ return Effect.forkIn(handled, record.scope ?? this.scope, { startImmediately: true }).pipe(Effect.flatMap((fiber) => {
391
+ if (awaitListeners) (pending ??= []).push(fiber);
392
+ return Effect.suspend(() => loop(index + 1));
393
+ }));
394
+ }
395
+ return pending ? Fiber.joinAll(pending).pipe(Effect.as(called)) : called ? emitted : noListeners;
396
+ };
397
+ const program = loop(0);
398
+ return awaitListeners && hasAsync ? program.pipe(Effect.ensuring(Effect.suspend(() => pending ? Fiber.interruptAll(pending) : Effect.void))) : program;
399
+ });
400
+ }
401
+ /**
402
+ * Register a catch-all listener that fires on every emit with (event, payload).
403
+ * Useful for event bridging / debugging.
404
+ */
405
+ onAny(listener, options = {}) {
406
+ this.assertOpen();
407
+ const existing = this.anyListeners.get(listener);
408
+ if (existing) cleanupAbort(existing);
409
+ const record = createRecord(listener, options, this.finalizer);
410
+ record.any = true;
411
+ if (options.prepend) this.anyListeners = new Map([[listener, record], ...this.anyListeners]);
412
+ else this.anyListeners.set(listener, record);
413
+ attachAbort(record, () => this.offAny(listener));
414
+ return this;
415
+ }
416
+ onAnyScoped(listener, options = {}) {
417
+ const owned = (event, payload) => listener(event, payload);
418
+ return Effect.acquireRelease(Effect.sync(() => {
419
+ this.assertOpen();
420
+ const record = createRecord(owned, options, this.finalizer);
421
+ record.original = listener;
422
+ record.any = true;
423
+ record.scope = Scope.forkUnsafe(this.scope);
424
+ this.anyListeners.set(owned, record);
425
+ attachAbort(record, () => this.offAny(owned));
426
+ return record;
427
+ }), (record) => Effect.sync(() => this.offAny(owned)).pipe(Effect.andThen(Scope.close(record.scope, Exit.void)))).pipe(Effect.asVoid);
428
+ }
429
+ /**
430
+ * Remove a catch-all listener registered via onAny.
431
+ */
432
+ offAny(listener) {
433
+ const record = this.anyListeners.get(listener) ?? [...this.anyListeners.values()].find((record) => record.original === listener);
434
+ if (record) {
435
+ cleanupAbort(record);
436
+ this.anyListeners.delete(record.fn);
437
+ }
438
+ return this;
439
+ }
440
+ listeners(event) {
441
+ return this.snapshot(event).filter((record) => !record.any && this.isLive(record)).map((record) => record.fn);
442
+ }
443
+ hasListeners(event) {
444
+ return this.snapshot(event).some((record) => this.isLive(record));
445
+ }
446
+ listenerCount(event) {
447
+ if (!event) {
448
+ let total = this.wildcardIndex.size + this.anyListeners.size;
449
+ for (const arr of this.exactListeners.values()) total += arr.length;
450
+ return total;
451
+ }
452
+ return this.listeners(event).length;
453
+ }
454
+ removeAllListeners(event) {
455
+ if (!event) {
456
+ for (const arr of this.exactListeners.values()) arr.forEach(cleanupAbort);
457
+ this.exactListeners.clear();
458
+ for (const record of this.wildcardIndex.keys()) cleanupAbort(record);
459
+ for (const record of this.anyListeners.values()) cleanupAbort(record);
460
+ this.anyListeners.clear();
461
+ this.wildcardTree = new RadixTree(this.delimiter, this.wildcardStyle);
462
+ this.hasWildcards = false;
463
+ this.wildcardIndex.clear();
464
+ return this;
465
+ }
466
+ const list = this.exactListeners.get(event);
467
+ if (list) {
468
+ list.forEach(cleanupAbort);
469
+ this.exactListeners.delete(event);
470
+ }
471
+ if (this.hasWildcards && this.isWildcard(event)) {
472
+ for (const [record, pattern] of this.wildcardIndex.entries()) if (pattern === event) {
473
+ cleanupAbort(record);
474
+ this.wildcardTree.remove(pattern, record);
475
+ this.wildcardIndex.delete(record);
476
+ }
477
+ }
478
+ return this;
479
+ }
480
+ /** Remove subscriptions and interrupt listener work owned by this emitter. */
481
+ close() {
482
+ return Effect.suspend(() => {
483
+ if (this.closed) return Effect.void;
484
+ this.closed = true;
485
+ this.removeAllListeners();
486
+ return this.observations.close().pipe(Effect.andThen(Scope.close(this.scope, Exit.void)));
487
+ });
488
+ }
489
+ /**
490
+ * Bridge from a Node EventEmitter: forward Node events into this emitter.
491
+ */
492
+ fromNodeEmitter(emitter, event) {
493
+ const handler = (...args) => {
494
+ this.emit(event, args[0]);
495
+ };
496
+ emitter.on(event, handler);
497
+ return () => emitter.off(event, handler);
498
+ }
499
+ /**
500
+ * Bridge to a Node EventEmitter: emit HyperEmitter events on a provided Node emitter.
501
+ */
502
+ toNodeEmitter(target) {
503
+ const forwarder = (event, payload) => {
504
+ target.emit(event, payload);
505
+ };
506
+ this.onAny(forwarder);
507
+ return () => {
508
+ this.offAny(forwarder);
509
+ };
510
+ }
511
+ /**
512
+ * Attach a handler to an EventTarget and re-emit through HyperEmitter.
513
+ */
514
+ onEventTarget(target, type, eventName) {
515
+ const handler = (ev) => {
516
+ this.emit(eventName, ev);
517
+ };
518
+ target.addEventListener(type, handler);
519
+ return () => target.removeEventListener(type, handler);
520
+ }
521
+ add(event, record, prepend = false) {
522
+ this.assertOpen();
523
+ const isWildcard = this.isWildcard(event);
524
+ if (isWildcard) {
525
+ this.hasWildcards = true;
526
+ this.wildcardTree.insert(event, record, prepend);
527
+ this.wildcardIndex.set(record, event);
528
+ } else {
529
+ const list = this.exactListeners.get(event);
530
+ if (list) {
531
+ if (prepend) list.unshift(record);
532
+ else list.push(record);
533
+ } else this.exactListeners.set(event, [record]);
534
+ }
535
+ attachAbort(record, () => this.off(event, record.fn));
536
+ this.logDebug("listener_registered", {
537
+ event,
538
+ once: record.once,
539
+ wildcard: isWildcard
540
+ });
541
+ }
542
+ listenersAny() {
543
+ return [...this.anyListeners.values()].filter((record) => this.isLive(record)).map((record) => record.original ?? record.fn);
544
+ }
545
+ eventNames() {
546
+ return [.../* @__PURE__ */ new Set([...this.exactListeners.keys(), ...this.wildcardIndex.values()])];
547
+ }
548
+ isWildcard(event) {
549
+ if (this.wildcardStyle === "mqtt" ? !event.includes("+") && !event.includes("#") : !event.includes("*")) return false;
550
+ const tokens = this.wildcardStyle === "mqtt" ? ["+", "#"] : ["*", "**"];
551
+ return event.split(this.delimiter).some((segment) => tokens.includes(segment));
552
+ }
553
+ assertOpen() {
554
+ if (this.closed) throw new Error("HyperEmitter is closed");
555
+ }
556
+ snapshot(event) {
557
+ if (this.wildcardStyle === "eventemitter" && this.isWildcard(event)) {
558
+ const records = [...this.anyListeners.values()];
559
+ for (const [pattern, listeners] of this.exactListeners) if (patternsIntersect(pattern, event, this.delimiter)) records.push(...listeners);
560
+ for (const [record, pattern] of this.wildcardIndex) if (patternsIntersect(pattern, event, this.delimiter)) records.push(record);
561
+ return records;
562
+ }
563
+ const exact = this.exactListeners.get(event);
564
+ if (!this.hasWildcards && this.anyListeners.size === 0) return exact?.slice() ?? [];
565
+ return [
566
+ ...this.wildcardStyle === "eventemitter" ? this.anyListeners.values() : [],
567
+ ...exact ?? [],
568
+ ...this.hasWildcards ? this.wildcardTree.match(event) : [],
569
+ ...this.wildcardStyle === "mqtt" ? this.anyListeners.values() : []
570
+ ];
571
+ }
572
+ isLive(record) {
573
+ return !record.signal?.aborted && (!record.weakRef || !!record.weakRef.deref());
574
+ }
575
+ prepare(record) {
576
+ if (!this.isLive(record)) {
577
+ this.offListener(record);
578
+ return false;
579
+ }
580
+ if (record.once) {
581
+ if (record.fired) return false;
582
+ record.fired = true;
583
+ this.offListener(record);
584
+ }
585
+ return true;
586
+ }
587
+ resultEffect(result) {
588
+ if (Effect.isEffect(result)) return result;
589
+ if (result && typeof result.then === "function") return Effect.tryPromise({
590
+ try: () => Promise.resolve(result),
591
+ catch: (error) => error
592
+ });
593
+ return Effect.succeed(result);
594
+ }
595
+ offListener(record) {
596
+ for (const [event, arr] of this.exactListeners.entries()) {
597
+ const idx = arr.indexOf(record);
598
+ if (idx !== -1) {
599
+ cleanupAbort(arr[idx]);
600
+ arr.splice(idx, 1);
601
+ if (arr.length === 0) this.exactListeners.delete(event);
602
+ return;
603
+ }
604
+ }
605
+ const pattern = this.wildcardIndex.get(record);
606
+ if (pattern) {
607
+ cleanupAbort(record);
608
+ this.wildcardTree.remove(pattern, record);
609
+ this.wildcardIndex.delete(record);
610
+ return;
611
+ }
612
+ if (this.anyListeners.get(record.fn) === record) this.offAny(record.fn);
613
+ }
614
+ shouldCapture(record) {
615
+ return record.captureRejections ?? this.captureRejections;
616
+ }
617
+ handleRejection(record, err) {
618
+ if (!this.shouldCapture(record)) {
619
+ queueMicrotask(() => {
620
+ throw err;
621
+ });
622
+ return;
623
+ }
624
+ if (this.onError) {
625
+ try {
626
+ this.onError(err);
627
+ } catch {}
628
+ return;
629
+ }
630
+ this.logger?.error("listener_rejection", {
631
+ error: err,
632
+ ...this.baseLogContext
633
+ });
634
+ }
635
+ removeWildcard(event, listener) {
636
+ for (const [record, pattern] of this.wildcardIndex.entries()) if (pattern === event && record.fn === listener) {
637
+ this.wildcardTree.remove(pattern, record);
638
+ this.wildcardIndex.delete(record);
639
+ cleanupAbort(record);
640
+ break;
641
+ }
642
+ }
643
+ logDebug(message, meta) {
644
+ if (!this.debugEnabled) return;
645
+ this.logger?.debug(message, {
646
+ ...this.baseLogContext,
647
+ ...meta
648
+ });
649
+ }
650
+ };
651
+ //#endregion
652
+ //#region src/core/EventEmitter.ts
653
+ /** The process-level OpenWA API, backed by the tuned HyperEmitter dispatcher. */
654
+ var EventEmitter = class EventEmitter {
655
+ options;
656
+ static defaultMaxListeners = 10;
657
+ delimiter;
658
+ wildcard = true;
659
+ ignoreErrors;
660
+ event = "";
661
+ engine;
662
+ registrations = /* @__PURE__ */ new Map();
663
+ symbolRoutes = /* @__PURE__ */ new Map();
664
+ observers = /* @__PURE__ */ new Set();
665
+ pendingWaits = /* @__PURE__ */ new Set();
666
+ maxListeners;
667
+ closed = false;
668
+ observations = new EmissionHub();
669
+ constructor(options = {}) {
670
+ this.options = options;
671
+ this.delimiter = options.delimiter ?? ".";
672
+ this.ignoreErrors = options.ignoreErrors ?? false;
673
+ this.maxListeners = options.maxListeners ?? EventEmitter.defaultMaxListeners;
674
+ this.engine = new HyperEmitter({
675
+ delimiter: this.delimiter,
676
+ wildcardStyle: "eventemitter"
677
+ });
678
+ }
679
+ get isClosed() {
680
+ return this.closed || this.engine.isClosed;
681
+ }
682
+ /** Raw queued observation; use emit/emitEffect to deliver through both interfaces. */
683
+ pubsub(options) {
684
+ if (this.isClosed) throw new Error("EventEmitter is closed");
685
+ return this.observations.get(options);
686
+ }
687
+ get hasPubSub() {
688
+ return !this.isClosed && this.observations.enabled;
689
+ }
690
+ get pubsubStatus() {
691
+ return this.observations.status();
692
+ }
693
+ subscribe(options) {
694
+ return Effect.suspend(() => PubSub.subscribe(this.pubsub(options)));
695
+ }
696
+ stream(options) {
697
+ return Stream.suspend(() => Stream.fromPubSub(this.pubsub(options)));
698
+ }
699
+ on(event, listener, options) {
700
+ return this.register(event, listener, options);
701
+ }
702
+ addListener(event, listener, options) {
703
+ return this.register(event, listener, options);
704
+ }
705
+ prependListener(event, listener, options) {
706
+ return this.register(event, listener, options, true);
707
+ }
708
+ once(event, listener, options) {
709
+ return this.register(event, listener, options, false, 1);
710
+ }
711
+ prependOnceListener(event, listener, options) {
712
+ return this.register(event, listener, options, true, 1);
713
+ }
714
+ many(event, times, listener, options) {
715
+ return this.register(event, listener, options, false, times);
716
+ }
717
+ prependMany(event, times, listener, options) {
718
+ return this.register(event, listener, options, true, times);
719
+ }
720
+ onAny(listener) {
721
+ this.register("", listener, void 0, false, Infinity, true);
722
+ return this;
723
+ }
724
+ prependAny(listener) {
725
+ this.register("", listener, void 0, true, Infinity, true);
726
+ return this;
727
+ }
728
+ offAny(listener) {
729
+ for (const registration of this.registrations.values()) if (registration.any && (!listener || registration.listener === listener)) {
730
+ this.remove(registration);
731
+ if (listener) break;
732
+ }
733
+ return this;
734
+ }
735
+ off(event, listener) {
736
+ const route = this.route(event);
737
+ for (const registration of this.registrations.values()) if (!registration.any && registration.route === route && (registration.listener === listener || registration.wrapped === listener)) {
738
+ this.remove(registration);
739
+ break;
740
+ }
741
+ return this;
742
+ }
743
+ removeListener(event, listener) {
744
+ return this.off(event, listener);
745
+ }
746
+ removeAllListeners(event) {
747
+ const matches = event === void 0 ? void 0 : new Set(this.engine.listeners(this.route(event)));
748
+ for (const registration of this.registrations.values()) if (!registration.any && (!matches || matches.has(registration.wrapped))) this.remove(registration);
749
+ return this;
750
+ }
751
+ listeners(event) {
752
+ if (event === void 0) throw new Error("event name required for wildcard emitter");
753
+ return this.engine.listeners(this.route(event)).map((fn) => this.registrations.get(fn).listener);
754
+ }
755
+ listenersAny() {
756
+ return this.engine.listenersAny().map((fn) => this.registrations.get(fn).listener);
757
+ }
758
+ listenerCount(event) {
759
+ return this.listeners(event).length;
760
+ }
761
+ hasListeners(event) {
762
+ if (event === void 0) return this.registrations.size > 0;
763
+ const name = event instanceof String ? event.valueOf() : event;
764
+ return this.engine.listeners(this.route(name)).length > 0;
765
+ }
766
+ eventNames(nsAsArray = false) {
767
+ const tree = { children: /* @__PURE__ */ new Map() };
768
+ for (const registration of this.registrations.values()) {
769
+ if (registration.any) continue;
770
+ const segments = typeof registration.event === "string" ? registration.event.split(this.delimiter) : typeof registration.event === "symbol" ? [registration.event] : [...registration.event];
771
+ let node = tree;
772
+ for (const segment of segments) {
773
+ let child = node.children.get(segment);
774
+ if (!child) node.children.set(segment, child = { children: /* @__PURE__ */ new Map() });
775
+ node = child;
776
+ }
777
+ node.name = nsAsArray || segments.some((segment) => typeof segment === "symbol") ? segments : segments.join(this.delimiter);
778
+ }
779
+ const names = [];
780
+ const visit = (node) => {
781
+ if (node.name !== void 0) names.push(node.name);
782
+ for (const key of Reflect.ownKeys(Object.fromEntries(node.children)).reverse()) visit(node.children.get(key));
783
+ };
784
+ visit(tree);
785
+ return names;
786
+ }
787
+ setMaxListeners(count) {
788
+ if (typeof count !== "number" || count < 0 || Number.isNaN(count)) throw new TypeError("count must be a non-negative number");
789
+ this.maxListeners = count;
790
+ }
791
+ getMaxListeners() {
792
+ return this.maxListeners;
793
+ }
794
+ emit(event, ...values) {
795
+ this.checkError(event, values);
796
+ if (this.isClosed) return false;
797
+ this.observe(event, values);
798
+ return this.engine.emit(this.route(event), {
799
+ name: this.name(event),
800
+ values
801
+ });
802
+ }
803
+ emitEffect(event, ...values) {
804
+ return Effect.suspend(() => {
805
+ this.checkError(event, values);
806
+ if (this.isClosed) return Effect.succeed(false);
807
+ this.observe(event, values);
808
+ return this.engine.emitEffect(this.route(event), {
809
+ name: this.name(event),
810
+ values
811
+ });
812
+ });
813
+ }
814
+ emitAsync(event, ...values) {
815
+ const packet = {
816
+ name: this.name(event),
817
+ values,
818
+ results: []
819
+ };
820
+ return Effect.runPromise(Effect.suspend(() => {
821
+ this.checkError(event, values);
822
+ if (this.isClosed) return Effect.succeed(false);
823
+ this.observe(event, values);
824
+ return this.engine.emitEffect(this.route(event), packet);
825
+ })).then(() => packet.results);
826
+ }
827
+ onScoped(event, listener, options = {}) {
828
+ return Effect.acquireRelease(Effect.gen({ self: this }, function* () {
829
+ const registration = this.makeRegistration(event, listener, options, Infinity, false);
830
+ yield* this.engine.onScoped(registration.route, registration.wrapped, options).pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? Effect.sync(() => this.remove(registration)) : Effect.void));
831
+ if (options.signal?.aborted) this.remove(registration);
832
+ return registration;
833
+ }), (registration) => Effect.sync(() => {
834
+ this.remove(registration);
835
+ })).pipe(Effect.asVoid);
836
+ }
837
+ onAnyScoped(listener, options = {}) {
838
+ return Effect.acquireRelease(Effect.gen({ self: this }, function* () {
839
+ const registration = this.makeRegistration("", listener, options, Infinity, true);
840
+ yield* this.engine.onAnyScoped(registration.wrapped, options).pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? Effect.sync(() => this.remove(registration)) : Effect.void));
841
+ if (options.signal?.aborted) this.remove(registration);
842
+ return registration;
843
+ }), (registration) => Effect.sync(() => {
844
+ this.remove(registration);
845
+ })).pipe(Effect.asVoid);
846
+ }
847
+ waitFor(event, input = {}) {
848
+ const options = typeof input === "number" ? { timeout: input } : typeof input === "function" ? { filter: input } : input;
849
+ const PromiseType = options.Promise ?? Promise;
850
+ let cancel;
851
+ const promise = new PromiseType((resolve, reject) => {
852
+ let settled = false;
853
+ let timer;
854
+ const cleanup = () => {
855
+ this.off(event, listener);
856
+ if (timer) clearTimeout(timer);
857
+ this.pendingWaits.delete(cancel);
858
+ };
859
+ const listener = (...values) => {
860
+ if (options.filter && !options.filter.apply(this, values)) return;
861
+ settled = true;
862
+ cleanup();
863
+ if (options.handleError && values[0]) reject(values[0]);
864
+ else resolve(options.handleError ? values.slice(1) : values);
865
+ };
866
+ cancel = (reason) => {
867
+ if (settled) return void 0;
868
+ settled = true;
869
+ cleanup();
870
+ reject(reason ?? Object.assign(/* @__PURE__ */ new Error("canceled"), { code: "ECANCELED" }));
871
+ };
872
+ this.on(event, listener);
873
+ this.pendingWaits.add(cancel);
874
+ if (options.timeout) timer = setTimeout(() => cancel(Object.assign(/* @__PURE__ */ new Error("timeout"), { code: "ETIMEDOUT" })), options.timeout);
875
+ });
876
+ promise.cancel = cancel;
877
+ return promise;
878
+ }
879
+ listenTo(target, events, options = {}) {
880
+ const on = options.on ?? target.on ?? target.addListener ?? target.addEventListener;
881
+ const off = options.off ?? target.off ?? target.removeListener ?? target.removeEventListener;
882
+ if (!on || !off) throw new TypeError("target must support listener registration and removal");
883
+ const mapping = typeof events === "string" ? Object.fromEntries(events.split(/\s+/).map((event) => [event, event])) : typeof events === "symbol" ? { [events]: events } : Array.isArray(events) ? Object.fromEntries(events.map((event) => [event, event])) : events;
884
+ for (const original of Reflect.ownKeys(mapping)) {
885
+ if ([...this.observers].some((observer) => observer.target === target && observer.event === original)) continue;
886
+ const handler = (...data) => {
887
+ const event = {
888
+ name: mapping[original],
889
+ original,
890
+ data
891
+ };
892
+ if ((typeof options.reducers === "function" ? options.reducers : options.reducers?.[original])?.(event) !== false) this.emit(event.name, ...event.data);
893
+ };
894
+ on.call(target, original, handler);
895
+ this.observers.add({
896
+ target,
897
+ event: original,
898
+ handler,
899
+ off
900
+ });
901
+ }
902
+ return this;
903
+ }
904
+ stopListeningTo(target, event) {
905
+ let removed = false;
906
+ for (const observer of this.observers) if ((!target || observer.target === target) && (event === void 0 || observer.event === event)) {
907
+ observer.off.call(observer.target, observer.event, observer.handler);
908
+ this.observers.delete(observer);
909
+ removed = true;
910
+ }
911
+ return removed;
912
+ }
913
+ close() {
914
+ return Effect.suspend(() => {
915
+ if (this.closed) return Effect.void;
916
+ this.closed = true;
917
+ this.stopListeningTo();
918
+ for (const cancel of this.pendingWaits) cancel(/* @__PURE__ */ new Error("EventEmitter is closed"));
919
+ for (const registration of this.registrations.values()) registration.cleanup?.();
920
+ this.registrations.clear();
921
+ this.symbolRoutes.clear();
922
+ return this.observations.close().pipe(Effect.andThen(this.engine.close()));
923
+ });
924
+ }
925
+ register(event, listener, input, prepend = false, times = Infinity, any = false) {
926
+ const options = this.listenerOptions(input);
927
+ const registration = this.makeRegistration(event, listener, options, times, any);
928
+ try {
929
+ if (any) this.engine.onAny(registration.wrapped, {
930
+ ...options,
931
+ prepend
932
+ });
933
+ else this.engine.on(registration.route, registration.wrapped, {
934
+ ...options,
935
+ prepend
936
+ });
937
+ } catch (error) {
938
+ this.remove(registration);
939
+ throw error;
940
+ }
941
+ if (options.signal?.aborted) this.remove(registration);
942
+ if (options.objectify) {
943
+ const subscription = {
944
+ emitter: this,
945
+ event,
946
+ listener: registration.wrapped,
947
+ off: () => {
948
+ this.remove(registration);
949
+ return subscription;
950
+ }
951
+ };
952
+ return subscription;
953
+ }
954
+ return this;
955
+ }
956
+ makeRegistration(event, listener, options, times, any) {
957
+ if (this.isClosed) throw new Error("EventEmitter is closed");
958
+ if (typeof listener !== "function") throw new TypeError("listener must be a function");
959
+ const registration = {
960
+ event,
961
+ route: this.route(event),
962
+ listener,
963
+ any,
964
+ wrapped: void 0
965
+ };
966
+ let remaining = times;
967
+ const invoke = (packet) => {
968
+ if (remaining === 0 || options.signal?.aborted) return;
969
+ if (--remaining === 0) this.remove(registration);
970
+ this.event = packet.name;
971
+ const values = any ? [packet.name, ...packet.values] : packet.values;
972
+ const call = () => {
973
+ this.event = packet.name;
974
+ return listener.apply(this, values);
975
+ };
976
+ const result = options.async || options.nextTick || options.promisify ? options.promisify ?? listener.constructor.name === "AsyncFunction" ? new Promise((resolve) => options.nextTick ? process.nextTick(resolve) : setImmediate(resolve)).then(call) : options.nextTick ? process.nextTick(call) : setImmediate(call) : call();
977
+ if (!packet.results) return result;
978
+ const index = packet.results.length;
979
+ packet.results.push(void 0);
980
+ if (Effect.isEffect(result)) return result.pipe(Effect.tap((value) => Effect.sync(() => {
981
+ packet.results[index] = value;
982
+ })));
983
+ if (result && typeof result.then === "function") return Promise.resolve(result).then((value) => {
984
+ packet.results[index] = value;
985
+ return value;
986
+ });
987
+ packet.results[index] = result;
988
+ return result;
989
+ };
990
+ registration.wrapped = any ? ((_event, packet) => invoke(packet)) : invoke;
991
+ if (this.options.newListener) this.emit("newListener", event, listener);
992
+ this.registrations.set(registration.wrapped, registration);
993
+ if (options.signal) {
994
+ const abort = () => this.remove(registration);
995
+ options.signal.addEventListener("abort", abort, { once: true });
996
+ registration.cleanup = () => options.signal.removeEventListener("abort", abort);
997
+ }
998
+ return registration;
999
+ }
1000
+ remove(registration) {
1001
+ if (!this.registrations.delete(registration.wrapped)) return;
1002
+ registration.cleanup?.();
1003
+ if (registration.any) this.engine.offAny(registration.wrapped);
1004
+ else this.engine.off(registration.route, registration.wrapped);
1005
+ if (this.options.removeListener) this.emit(registration.any ? "removeListenerAny" : "removeListener", registration.event, registration.listener);
1006
+ }
1007
+ listenerOptions(input) {
1008
+ return input === true ? { promisify: true } : input === false ? { async: true } : input ?? {};
1009
+ }
1010
+ observe(event, values) {
1011
+ if (!this.observations.enabled) return;
1012
+ const name = this.name(event);
1013
+ this.observations.publish(Object.freeze({
1014
+ event: Array.isArray(name) ? Object.freeze(name.slice()) : name,
1015
+ args: Object.freeze(values.slice())
1016
+ }));
1017
+ }
1018
+ checkError(event, values) {
1019
+ if (!this.ignoreErrors && event === "error" && !this.hasListeners(event) && !this.listenersAny().length) throw values[0] instanceof Error ? values[0] : /* @__PURE__ */ new Error("Uncaught, unspecified 'error' event.");
1020
+ }
1021
+ name(event) {
1022
+ return Array.isArray(event) && !event.some((segment) => typeof segment === "symbol") ? event.join(this.delimiter) : event;
1023
+ }
1024
+ route(event) {
1025
+ if (typeof event === "string" && !event.includes("\0")) return event;
1026
+ const encode = (segment) => {
1027
+ if (typeof segment === "string") return segment.replace(/\u0000/g, "\0s");
1028
+ let key = this.symbolRoutes.get(segment);
1029
+ if (!key) this.symbolRoutes.set(segment, key = `\u0000${this.symbolRoutes.size}`);
1030
+ return key;
1031
+ };
1032
+ if (typeof event === "string") return encode(event);
1033
+ return (typeof event === "symbol" ? [event] : event).map(encode).join(this.delimiter);
1034
+ }
1035
+ };
1036
+ //#endregion
1037
+ export { EventEmitter, HyperEmitter };
1038
+
1039
+ //# sourceMappingURL=index.mjs.map