@open-wa/hyperemitter 5.0.0-alpha.7 → 5.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.
- package/LICENSE +202 -0
- package/README.md +2 -2
- package/dist/index.d.cts +4 -6
- package/dist/index.d.cts.map +1 -1
- package/package.json +13 -6
- package/.turbo/turbo-build.log +0 -15
- package/.turbo/turbo-lint.log +0 -6
- package/.turbo/turbo-typecheck.log +0 -5
- package/CHANGELOG.md +0 -61
- package/LICENSE.md +0 -67
- package/benchmarks/baseline/README.md +0 -9
- package/benchmarks/baseline/results/baseline-node-20.8.0.json +0 -51
- package/benchmarks/baseline/run-baseline.js +0 -215
- package/src/core/HyperEmitter.ts +0 -337
- package/src/index.ts +0 -7
- package/src/routing/RadixNode.ts +0 -19
- package/src/routing/RadixTree.ts +0 -124
- package/src/types/index.ts +0 -39
- package/src/utils/listener.ts +0 -59
- package/tsconfig.json +0 -21
- package/tsconfig.tsbuildinfo +0 -1
|
@@ -1,215 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* Baseline benchmark runner for competitor event emitters.
|
|
4
|
-
* Captures exact-match (3 args) and wildcard (if supported) throughput.
|
|
5
|
-
* Designed to run before HyperEmitter lands, producing JSON baselines for regression checks.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
const fs = require('node:fs');
|
|
9
|
-
const path = require('node:path');
|
|
10
|
-
const { performance } = require('node:perf_hooks');
|
|
11
|
-
|
|
12
|
-
const args = process.argv.slice(2);
|
|
13
|
-
const ciMode = args.includes('--ci');
|
|
14
|
-
const iterationsArg = getArgValue(args, '--iterations');
|
|
15
|
-
const outputArg = getArgValue(args, '--output');
|
|
16
|
-
|
|
17
|
-
const ITERATIONS = iterationsArg ? Number(iterationsArg) : 500_000;
|
|
18
|
-
const WARMUP = 20_000;
|
|
19
|
-
|
|
20
|
-
const OUT_DIR = path.join(__dirname, 'results');
|
|
21
|
-
const OUT_FILE =
|
|
22
|
-
outputArg ||
|
|
23
|
-
path.join(OUT_DIR, `baseline-node-${process.versions.node}.json`);
|
|
24
|
-
|
|
25
|
-
ensureDir(OUT_DIR);
|
|
26
|
-
|
|
27
|
-
const competitors = [
|
|
28
|
-
{
|
|
29
|
-
name: 'node:events',
|
|
30
|
-
supportsWildcard: false,
|
|
31
|
-
setupExact: () => {
|
|
32
|
-
const { EventEmitter } = require('node:events');
|
|
33
|
-
const emitter = new EventEmitter();
|
|
34
|
-
const handler = noop;
|
|
35
|
-
emitter.on('test.event', handler);
|
|
36
|
-
return () => emitter.emit('test.event', 1, 2, 3);
|
|
37
|
-
}
|
|
38
|
-
},
|
|
39
|
-
{
|
|
40
|
-
name: 'eventemitter3',
|
|
41
|
-
module: 'eventemitter3',
|
|
42
|
-
supportsWildcard: false,
|
|
43
|
-
setupExact: (mod) => {
|
|
44
|
-
const emitter = new mod();
|
|
45
|
-
const handler = noop;
|
|
46
|
-
emitter.on('test.event', handler);
|
|
47
|
-
return () => emitter.emit('test.event', 1, 2, 3);
|
|
48
|
-
}
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
name: 'eventemitter2',
|
|
52
|
-
module: 'eventemitter2',
|
|
53
|
-
supportsWildcard: true,
|
|
54
|
-
setupExact: (mod) => {
|
|
55
|
-
const emitter = new mod();
|
|
56
|
-
const handler = noop;
|
|
57
|
-
emitter.on('test.event', handler);
|
|
58
|
-
return () => emitter.emit('test.event', 1, 2, 3);
|
|
59
|
-
},
|
|
60
|
-
setupWildcard: (mod) => {
|
|
61
|
-
const emitter = new mod({ wildcard: true, delimiter: '.' });
|
|
62
|
-
const handler = noop;
|
|
63
|
-
emitter.on('a.**', handler); // multi-level wildcard
|
|
64
|
-
return () => emitter.emit('a.b.c', 1, 2, 3);
|
|
65
|
-
}
|
|
66
|
-
},
|
|
67
|
-
{
|
|
68
|
-
name: 'emittery',
|
|
69
|
-
module: 'emittery',
|
|
70
|
-
supportsWildcard: true,
|
|
71
|
-
setupExact: (mod) => {
|
|
72
|
-
const emitter = new mod();
|
|
73
|
-
const handler = noop;
|
|
74
|
-
emitter.on('test.event', handler);
|
|
75
|
-
return () => emitter.emit('test.event', { args: [1, 2, 3] });
|
|
76
|
-
},
|
|
77
|
-
setupWildcard: (mod) => {
|
|
78
|
-
const emitter = new mod();
|
|
79
|
-
const handler = noop;
|
|
80
|
-
emitter.on('a.*', handler);
|
|
81
|
-
return () => emitter.emit('a.b', { args: [1, 2, 3] });
|
|
82
|
-
}
|
|
83
|
-
},
|
|
84
|
-
{
|
|
85
|
-
name: 'mitt',
|
|
86
|
-
module: 'mitt',
|
|
87
|
-
supportsWildcard: false,
|
|
88
|
-
setupExact: (mod) => {
|
|
89
|
-
const emitter = mod.default ? mod.default() : mod();
|
|
90
|
-
const handler = noop;
|
|
91
|
-
emitter.on('test.event', handler);
|
|
92
|
-
return () => emitter.emit('test.event', { args: [1, 2, 3] });
|
|
93
|
-
}
|
|
94
|
-
},
|
|
95
|
-
{
|
|
96
|
-
name: 'tseep',
|
|
97
|
-
module: 'tseep',
|
|
98
|
-
supportsWildcard: false,
|
|
99
|
-
setupExact: (mod) => {
|
|
100
|
-
const emitter = new mod();
|
|
101
|
-
const handler = noop;
|
|
102
|
-
emitter.on('test.event', handler);
|
|
103
|
-
return () => emitter.emit('test.event', 1, 2, 3);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
];
|
|
107
|
-
|
|
108
|
-
const results = {
|
|
109
|
-
meta: {
|
|
110
|
-
nodeVersion: process.versions.node,
|
|
111
|
-
date: new Date().toISOString(),
|
|
112
|
-
iterations: ITERATIONS,
|
|
113
|
-
warmup: WARMUP
|
|
114
|
-
},
|
|
115
|
-
exact: {},
|
|
116
|
-
wildcard: {}
|
|
117
|
-
};
|
|
118
|
-
|
|
119
|
-
for (const competitor of competitors) {
|
|
120
|
-
const mod = competitor.module ? tryRequire(competitor.module) : null;
|
|
121
|
-
if (competitor.module && !mod) {
|
|
122
|
-
results.exact[competitor.name] = skip('module not installed');
|
|
123
|
-
if (competitor.supportsWildcard) {
|
|
124
|
-
results.wildcard[competitor.name] = skip('module not installed');
|
|
125
|
-
}
|
|
126
|
-
continue;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
// Exact match benchmark
|
|
130
|
-
if (competitor.setupExact) {
|
|
131
|
-
const runner = competitor.setupExact(mod);
|
|
132
|
-
results.exact[competitor.name] = runBenchmark(runner);
|
|
133
|
-
} else {
|
|
134
|
-
results.exact[competitor.name] = skip('no exact benchmark');
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// Wildcard benchmark
|
|
138
|
-
if (competitor.supportsWildcard && competitor.setupWildcard) {
|
|
139
|
-
const runner = competitor.setupWildcard(mod);
|
|
140
|
-
results.wildcard[competitor.name] = runBenchmark(runner);
|
|
141
|
-
} else if (competitor.supportsWildcard) {
|
|
142
|
-
results.wildcard[competitor.name] = skip('no wildcard benchmark');
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
fs.writeFileSync(OUT_FILE, JSON.stringify(results, null, 2));
|
|
147
|
-
|
|
148
|
-
if (!ciMode) {
|
|
149
|
-
console.log('Baseline benchmarks complete.');
|
|
150
|
-
console.log(`Saved to: ${OUT_FILE}`);
|
|
151
|
-
console.table(formatTable(results.exact, 'exact ops/sec'));
|
|
152
|
-
if (Object.keys(results.wildcard).length) {
|
|
153
|
-
console.table(formatTable(results.wildcard, 'wildcard ops/sec'));
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
function runBenchmark(fn) {
|
|
158
|
-
// Warmup
|
|
159
|
-
for (let i = 0; i < WARMUP; i++) {
|
|
160
|
-
fn();
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
const start = performance.now();
|
|
164
|
-
for (let i = 0; i < ITERATIONS; i++) {
|
|
165
|
-
fn();
|
|
166
|
-
}
|
|
167
|
-
const end = performance.now();
|
|
168
|
-
|
|
169
|
-
const durationMs = end - start;
|
|
170
|
-
const opsPerSec = (ITERATIONS / durationMs) * 1000;
|
|
171
|
-
const nsPerOp = (durationMs * 1_000_000) / ITERATIONS;
|
|
172
|
-
|
|
173
|
-
return {
|
|
174
|
-
opsPerSec,
|
|
175
|
-
nsPerOp,
|
|
176
|
-
durationMs
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
function tryRequire(name) {
|
|
181
|
-
try {
|
|
182
|
-
return require(name);
|
|
183
|
-
} catch (err) {
|
|
184
|
-
if (!ciMode) {
|
|
185
|
-
console.warn(`Skipping ${name}: ${err.message}`);
|
|
186
|
-
}
|
|
187
|
-
return null;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
function skip(reason) {
|
|
192
|
-
return { skipped: true, reason };
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
function ensureDir(dir) {
|
|
196
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
function getArgValue(argv, key) {
|
|
200
|
-
const idx = argv.indexOf(key);
|
|
201
|
-
if (idx === -1) return undefined;
|
|
202
|
-
return argv[idx + 1];
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function formatTable(map, label) {
|
|
206
|
-
const table = {};
|
|
207
|
-
for (const [name, result] of Object.entries(map)) {
|
|
208
|
-
table[name] = result.skipped
|
|
209
|
-
? result.reason
|
|
210
|
-
: `${result.opsPerSec.toFixed(2)} ops/s (${result.nsPerOp.toFixed(2)} ns/op)`;
|
|
211
|
-
}
|
|
212
|
-
return table;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
function noop() {}
|
package/src/core/HyperEmitter.ts
DELETED
|
@@ -1,337 +0,0 @@
|
|
|
1
|
-
import { EventEmitter as NodeEmitter } from 'node:events';
|
|
2
|
-
import { RadixTree } from '../routing/RadixTree.js';
|
|
3
|
-
import { ListenerOptions, HyperEmitterOptions } from '../types/index.js';
|
|
4
|
-
import {
|
|
5
|
-
ListenerRecord,
|
|
6
|
-
attachAbort,
|
|
7
|
-
cleanupAbort,
|
|
8
|
-
createRecord
|
|
9
|
-
} from '../utils/listener.js';
|
|
10
|
-
import { createLogger, Logger } from '@open-wa/logger';
|
|
11
|
-
import type { LogContext } from '@open-wa/logger';
|
|
12
|
-
|
|
13
|
-
type AnyFn = (...args: any[]) => any;
|
|
14
|
-
|
|
15
|
-
export class HyperEmitter<TMap extends object = Record<string, unknown>> {
|
|
16
|
-
private readonly delimiter: string;
|
|
17
|
-
private readonly captureRejections: boolean;
|
|
18
|
-
private readonly onError?: (err: unknown) => void;
|
|
19
|
-
private readonly finalizer?: FinalizationRegistry<unknown>;
|
|
20
|
-
private readonly logger?: Logger;
|
|
21
|
-
private readonly debugEnabled: boolean;
|
|
22
|
-
private readonly baseLogContext: LogContext;
|
|
23
|
-
|
|
24
|
-
private exactListeners: Map<string, ListenerRecord<AnyFn>[]>;
|
|
25
|
-
private wildcardTree: RadixTree<ListenerRecord<AnyFn>>;
|
|
26
|
-
private wildcardIndex: Map<ListenerRecord<AnyFn>, string>;
|
|
27
|
-
private hasWildcards = false;
|
|
28
|
-
private anyListeners: Set<(event: string, payload: any) => void> = new Set();
|
|
29
|
-
|
|
30
|
-
constructor(options: HyperEmitterOptions = {}) {
|
|
31
|
-
this.delimiter = options.delimiter ?? '.';
|
|
32
|
-
this.captureRejections = options.captureRejections ?? false;
|
|
33
|
-
this.onError = options.onError;
|
|
34
|
-
this.debugEnabled = !!options.debug;
|
|
35
|
-
this.baseLogContext = {
|
|
36
|
-
component: 'hyperemitter',
|
|
37
|
-
...options.loggerContext
|
|
38
|
-
};
|
|
39
|
-
this.logger =
|
|
40
|
-
options.logger?.withContext?.(this.baseLogContext) ??
|
|
41
|
-
createLogger({ component: 'hyperemitter', ...options.loggerContext });
|
|
42
|
-
|
|
43
|
-
// WeakRef support
|
|
44
|
-
if (typeof FinalizationRegistry !== 'undefined') {
|
|
45
|
-
this.finalizer = new FinalizationRegistry((token: unknown) => {
|
|
46
|
-
if (token && typeof token === 'object') {
|
|
47
|
-
// token is used only for unregister; actual removal is handled during emit via deref
|
|
48
|
-
}
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
this.exactListeners = new Map();
|
|
53
|
-
this.wildcardTree = new RadixTree<ListenerRecord<AnyFn>>(this.delimiter);
|
|
54
|
-
this.wildcardIndex = new Map();
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
on<K extends keyof TMap & string>(
|
|
58
|
-
event: K,
|
|
59
|
-
listener: (payload: TMap[K]) => void | Promise<void>,
|
|
60
|
-
options: ListenerOptions = {}
|
|
61
|
-
): this {
|
|
62
|
-
const record = createRecord(listener as AnyFn, options, this.finalizer as any);
|
|
63
|
-
this.add(event, record);
|
|
64
|
-
return this;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
once<K extends keyof TMap & string>(
|
|
68
|
-
event: K,
|
|
69
|
-
listener: (payload: TMap[K]) => void | Promise<void>,
|
|
70
|
-
options: ListenerOptions = {}
|
|
71
|
-
): this {
|
|
72
|
-
const record = createRecord(listener as AnyFn, options, this.finalizer as any);
|
|
73
|
-
record.once = true;
|
|
74
|
-
this.add(event, record);
|
|
75
|
-
return this;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
off<K extends keyof TMap & string>(event: K, listener: (payload: TMap[K]) => void | Promise<void>): this {
|
|
79
|
-
const list = this.exactListeners.get(event);
|
|
80
|
-
if (list) {
|
|
81
|
-
const idx = list.findIndex(l => l.fn === listener);
|
|
82
|
-
if (idx !== -1) {
|
|
83
|
-
cleanupAbort(list[idx]);
|
|
84
|
-
list.splice(idx, 1);
|
|
85
|
-
}
|
|
86
|
-
if (list.length === 0) this.exactListeners.delete(event);
|
|
87
|
-
}
|
|
88
|
-
if (this.hasWildcards && (event.includes('+') || event.includes('#'))) {
|
|
89
|
-
this.removeWildcard(event, listener as AnyFn);
|
|
90
|
-
}
|
|
91
|
-
return this;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
emit<K extends keyof TMap & string>(
|
|
95
|
-
event: K,
|
|
96
|
-
payload: TMap[K]
|
|
97
|
-
): boolean {
|
|
98
|
-
const exact = this.exactListeners.get(event as string);
|
|
99
|
-
const wildcard = this.hasWildcards
|
|
100
|
-
? this.wildcardTree.match(event as string)
|
|
101
|
-
: undefined;
|
|
102
|
-
|
|
103
|
-
const called = this.dispatch(exact, [payload]) | this.dispatch(wildcard, [payload]);
|
|
104
|
-
|
|
105
|
-
// Notify catch-all listeners
|
|
106
|
-
for (const listener of this.anyListeners) {
|
|
107
|
-
try {
|
|
108
|
-
listener(event as string, payload);
|
|
109
|
-
} catch { /* swallow */ }
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
return Boolean(called);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Register a catch-all listener that fires on every emit with (event, payload).
|
|
117
|
-
* Useful for event bridging / debugging.
|
|
118
|
-
*/
|
|
119
|
-
onAny(listener: (event: string, payload: any) => void): this {
|
|
120
|
-
this.anyListeners.add(listener);
|
|
121
|
-
return this;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Remove a catch-all listener registered via onAny.
|
|
126
|
-
*/
|
|
127
|
-
offAny(listener: (event: string, payload: any) => void): this {
|
|
128
|
-
this.anyListeners.delete(listener);
|
|
129
|
-
return this;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
listenerCount(event?: keyof TMap & string): number {
|
|
133
|
-
if (!event) {
|
|
134
|
-
let total = 0;
|
|
135
|
-
for (const arr of this.exactListeners.values()) total += arr.length;
|
|
136
|
-
return total;
|
|
137
|
-
}
|
|
138
|
-
return this.exactListeners.get(event)?.length ?? 0;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
removeAllListeners(event?: keyof TMap & string): this {
|
|
142
|
-
if (!event) {
|
|
143
|
-
for (const arr of this.exactListeners.values()) {
|
|
144
|
-
arr.forEach(cleanupAbort);
|
|
145
|
-
}
|
|
146
|
-
this.exactListeners.clear();
|
|
147
|
-
this.wildcardTree = new RadixTree<ListenerRecord<AnyFn>>(this.delimiter);
|
|
148
|
-
this.hasWildcards = false;
|
|
149
|
-
this.wildcardIndex.clear();
|
|
150
|
-
return this;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
const list = this.exactListeners.get(event);
|
|
154
|
-
if (list) {
|
|
155
|
-
list.forEach(cleanupAbort);
|
|
156
|
-
this.exactListeners.delete(event);
|
|
157
|
-
}
|
|
158
|
-
// Wildcards: best effort clear by rebuilding tree
|
|
159
|
-
if (this.hasWildcards && (event.includes('+') || event.includes('#'))) {
|
|
160
|
-
for (const [record, pattern] of this.wildcardIndex.entries()) {
|
|
161
|
-
if (pattern === event) {
|
|
162
|
-
this.wildcardTree.remove(pattern, record);
|
|
163
|
-
this.wildcardIndex.delete(record);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
return this;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/**
|
|
171
|
-
* Bridge from a Node EventEmitter: forward Node events into this emitter.
|
|
172
|
-
*/
|
|
173
|
-
fromNodeEmitter(emitter: NodeEmitter, event: string): () => void {
|
|
174
|
-
const handler = (...args: any[]) => {
|
|
175
|
-
// @ts-expect-error safe runtime emit
|
|
176
|
-
this.emit(event as any, ...args);
|
|
177
|
-
};
|
|
178
|
-
emitter.on(event, handler);
|
|
179
|
-
return () => emitter.off(event, handler);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Bridge to a Node EventEmitter: emit HyperEmitter events on a provided Node emitter.
|
|
184
|
-
*/
|
|
185
|
-
toNodeEmitter(target: NodeEmitter): () => void {
|
|
186
|
-
const forwarder = (event: string, args: any[]) => target.emit(event, ...args);
|
|
187
|
-
// naive bridge: wrap emit; caller can replace as needed
|
|
188
|
-
const original = (this as any).emit;
|
|
189
|
-
(this as any).emit = (ev: string, ...args: any[]) => {
|
|
190
|
-
forwarder(ev, args);
|
|
191
|
-
return original.call(this, ev, ...args);
|
|
192
|
-
};
|
|
193
|
-
return () => {
|
|
194
|
-
(this as any).emit = original;
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* Attach a handler to an EventTarget and re-emit through HyperEmitter.
|
|
200
|
-
*/
|
|
201
|
-
onEventTarget(target: EventTarget, type: string, eventName: keyof TMap & string) {
|
|
202
|
-
const handler = (ev: Event) => {
|
|
203
|
-
// @ts-expect-error forwarding payload
|
|
204
|
-
this.emit(eventName, ev);
|
|
205
|
-
};
|
|
206
|
-
target.addEventListener(type, handler);
|
|
207
|
-
return () => target.removeEventListener(type, handler);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
private add(event: string, record: ListenerRecord<AnyFn>) {
|
|
211
|
-
// Wildcard patterns contain '+' or '#'
|
|
212
|
-
const isWildcard = event.includes('+') || event.includes('#');
|
|
213
|
-
if (isWildcard) {
|
|
214
|
-
this.hasWildcards = true;
|
|
215
|
-
this.wildcardTree.insert(event, record);
|
|
216
|
-
this.wildcardIndex.set(record, event);
|
|
217
|
-
} else {
|
|
218
|
-
const list = this.exactListeners.get(event);
|
|
219
|
-
if (list) {
|
|
220
|
-
list.push(record);
|
|
221
|
-
} else {
|
|
222
|
-
this.exactListeners.set(event, [record]);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
attachAbort(record, () => this.off(event as any, record.fn as any));
|
|
227
|
-
this.logDebug('listener_registered', {
|
|
228
|
-
event,
|
|
229
|
-
once: record.once,
|
|
230
|
-
wildcard: isWildcard
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
private dispatch(list: ListenerRecord<AnyFn>[] | undefined, args: any[]): number {
|
|
235
|
-
if (!list || list.length === 0) return 0;
|
|
236
|
-
// Copy-on-write to avoid mutation during emit.
|
|
237
|
-
const snapshot = list.slice();
|
|
238
|
-
let called = 0;
|
|
239
|
-
for (const record of snapshot) {
|
|
240
|
-
// WeakRef cleanup: if target gone, remove and skip.
|
|
241
|
-
if (record.weakRef && !record.weakRef.deref()) {
|
|
242
|
-
this.offListener(record);
|
|
243
|
-
continue;
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
called++;
|
|
247
|
-
const result = this.invoke(record, args);
|
|
248
|
-
if (record.once) {
|
|
249
|
-
this.offListener(record);
|
|
250
|
-
}
|
|
251
|
-
if (result && typeof result.then === 'function') {
|
|
252
|
-
result.catch((err: unknown) => this.handleRejection(record, err));
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
return called;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
private invoke(record: ListenerRecord<AnyFn>, args: any[]) {
|
|
259
|
-
switch (args.length) {
|
|
260
|
-
case 0:
|
|
261
|
-
return record.fn();
|
|
262
|
-
case 1:
|
|
263
|
-
return record.fn(args[0]);
|
|
264
|
-
case 2:
|
|
265
|
-
return record.fn(args[0], args[1]);
|
|
266
|
-
case 3:
|
|
267
|
-
return record.fn(args[0], args[1], args[2]);
|
|
268
|
-
default:
|
|
269
|
-
return record.fn(...args);
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
private offListener(record: ListenerRecord<AnyFn>) {
|
|
274
|
-
// Exact listeners
|
|
275
|
-
for (const [event, arr] of this.exactListeners.entries()) {
|
|
276
|
-
const idx = arr.indexOf(record);
|
|
277
|
-
if (idx !== -1) {
|
|
278
|
-
cleanupAbort(arr[idx]);
|
|
279
|
-
arr.splice(idx, 1);
|
|
280
|
-
if (arr.length === 0) this.exactListeners.delete(event);
|
|
281
|
-
return;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
// Wildcard listeners (pattern tracked)
|
|
285
|
-
const pattern = this.wildcardIndex.get(record);
|
|
286
|
-
if (pattern) {
|
|
287
|
-
this.wildcardTree.remove(pattern, record);
|
|
288
|
-
this.wildcardIndex.delete(record);
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
private handleRejection(record: ListenerRecord<AnyFn>, err: unknown) {
|
|
293
|
-
const shouldCapture =
|
|
294
|
-
record.captureRejections !== undefined
|
|
295
|
-
? record.captureRejections
|
|
296
|
-
: this.captureRejections;
|
|
297
|
-
|
|
298
|
-
if (!shouldCapture) {
|
|
299
|
-
queueMicrotask(() => {
|
|
300
|
-
throw err;
|
|
301
|
-
});
|
|
302
|
-
return;
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
if (this.onError) {
|
|
306
|
-
try {
|
|
307
|
-
this.onError(err);
|
|
308
|
-
} catch {
|
|
309
|
-
// swallow secondary errors
|
|
310
|
-
}
|
|
311
|
-
return;
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
// Fallback logging
|
|
315
|
-
this.logger?.error('listener_rejection', {
|
|
316
|
-
error: err as any,
|
|
317
|
-
...this.baseLogContext
|
|
318
|
-
});
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
private removeWildcard(event: string, listener: AnyFn) {
|
|
322
|
-
// Slow path: tree removal requires record reference; search recorded patterns.
|
|
323
|
-
for (const [record, pattern] of this.wildcardIndex.entries()) {
|
|
324
|
-
if (pattern === event && record.fn === listener) {
|
|
325
|
-
this.wildcardTree.remove(pattern, record);
|
|
326
|
-
this.wildcardIndex.delete(record);
|
|
327
|
-
cleanupAbort(record);
|
|
328
|
-
break;
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
private logDebug(message: string, meta?: LogContext) {
|
|
334
|
-
if (!this.debugEnabled) return;
|
|
335
|
-
this.logger?.debug(message, { ...this.baseLogContext, ...meta });
|
|
336
|
-
}
|
|
337
|
-
}
|
package/src/index.ts
DELETED
package/src/routing/RadixNode.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Monomorphic radix tree node for MQTT-style wildcard routing.
|
|
3
|
-
*/
|
|
4
|
-
export class RadixNode<T> {
|
|
5
|
-
segment: string;
|
|
6
|
-
listeners: T[];
|
|
7
|
-
children: Map<string, RadixNode<T>> | null;
|
|
8
|
-
wildcardSingle: RadixNode<T> | null; // '+'
|
|
9
|
-
wildcardMulti: RadixNode<T> | null; // '#'
|
|
10
|
-
|
|
11
|
-
constructor(segment: string) {
|
|
12
|
-
// Preserve property order for hidden-class stability.
|
|
13
|
-
this.segment = segment;
|
|
14
|
-
this.listeners = [];
|
|
15
|
-
this.children = null;
|
|
16
|
-
this.wildcardSingle = null;
|
|
17
|
-
this.wildcardMulti = null;
|
|
18
|
-
}
|
|
19
|
-
}
|
package/src/routing/RadixTree.ts
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
import { RadixNode } from './RadixNode.js';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Radix tree with MQTT-style wildcards.
|
|
5
|
-
* Complexity: O(K) where K = number of path segments.
|
|
6
|
-
*/
|
|
7
|
-
export class RadixTree<T> {
|
|
8
|
-
private readonly delimiter: string;
|
|
9
|
-
private readonly root: RadixNode<T>;
|
|
10
|
-
|
|
11
|
-
constructor(delimiter = '.') {
|
|
12
|
-
this.delimiter = delimiter;
|
|
13
|
-
this.root = new RadixNode<T>('');
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
insert(pattern: string, value: T) {
|
|
17
|
-
const segments = this.tokenize(pattern);
|
|
18
|
-
let node = this.root;
|
|
19
|
-
|
|
20
|
-
for (const segment of segments) {
|
|
21
|
-
if (segment === '+') {
|
|
22
|
-
if (!node.wildcardSingle) node.wildcardSingle = new RadixNode<T>('+');
|
|
23
|
-
node = node.wildcardSingle;
|
|
24
|
-
continue;
|
|
25
|
-
}
|
|
26
|
-
if (segment === '#') {
|
|
27
|
-
if (!node.wildcardMulti) node.wildcardMulti = new RadixNode<T>('#');
|
|
28
|
-
node = node.wildcardMulti;
|
|
29
|
-
break; // '#' consumes the rest
|
|
30
|
-
}
|
|
31
|
-
if (!node.children) node.children = new Map();
|
|
32
|
-
let child = node.children.get(segment);
|
|
33
|
-
if (!child) {
|
|
34
|
-
child = new RadixNode<T>(segment);
|
|
35
|
-
node.children.set(segment, child);
|
|
36
|
-
}
|
|
37
|
-
node = child;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
node.listeners.push(value);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
remove(pattern: string, value: T) {
|
|
44
|
-
const path: Array<[RadixNode<T>, string]> = [];
|
|
45
|
-
let node = this.root;
|
|
46
|
-
const segments = this.tokenize(pattern);
|
|
47
|
-
|
|
48
|
-
for (const segment of segments) {
|
|
49
|
-
path.push([node, segment]);
|
|
50
|
-
if (segment === '+') {
|
|
51
|
-
if (!node.wildcardSingle) return;
|
|
52
|
-
node = node.wildcardSingle;
|
|
53
|
-
} else if (segment === '#') {
|
|
54
|
-
if (!node.wildcardMulti) return;
|
|
55
|
-
node = node.wildcardMulti;
|
|
56
|
-
break;
|
|
57
|
-
} else {
|
|
58
|
-
if (!node.children) return;
|
|
59
|
-
const next = node.children.get(segment);
|
|
60
|
-
if (!next) return;
|
|
61
|
-
node = next;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const idx = node.listeners.indexOf(value);
|
|
66
|
-
if (idx !== -1) {
|
|
67
|
-
node.listeners.splice(idx, 1);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
match(event: string): T[] {
|
|
72
|
-
const segments = this.tokenize(event);
|
|
73
|
-
const stack: Array<{ node: RadixNode<T>; index: number }> = [
|
|
74
|
-
{ node: this.root, index: 0 }
|
|
75
|
-
];
|
|
76
|
-
const results: T[] = [];
|
|
77
|
-
|
|
78
|
-
while (stack.length > 0) {
|
|
79
|
-
const { node, index } = stack.pop()!;
|
|
80
|
-
|
|
81
|
-
if (index === segments.length) {
|
|
82
|
-
// Exact depth match
|
|
83
|
-
if (node.listeners.length) results.push(...node.listeners);
|
|
84
|
-
// '#' can also match empty suffix
|
|
85
|
-
if (node.wildcardMulti && node.wildcardMulti.listeners.length) {
|
|
86
|
-
results.push(...node.wildcardMulti.listeners);
|
|
87
|
-
}
|
|
88
|
-
continue;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const seg = segments[index];
|
|
92
|
-
|
|
93
|
-
// Exact child
|
|
94
|
-
if (node.children) {
|
|
95
|
-
const child = node.children.get(seg);
|
|
96
|
-
if (child) {
|
|
97
|
-
stack.push({ node: child, index: index + 1 });
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Single-level wildcard '+'
|
|
102
|
-
if (node.wildcardSingle) {
|
|
103
|
-
stack.push({ node: node.wildcardSingle, index: index + 1 });
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// Multi-level wildcard '#'
|
|
107
|
-
if (node.wildcardMulti) {
|
|
108
|
-
// '#' consumes the rest, so we can collect listeners directly
|
|
109
|
-
if (node.wildcardMulti.listeners.length) {
|
|
110
|
-
results.push(...node.wildcardMulti.listeners);
|
|
111
|
-
}
|
|
112
|
-
// But it can also match additional segments
|
|
113
|
-
stack.push({ node: node.wildcardMulti, index: index + 1 });
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
return results;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
private tokenize(path: string): string[] {
|
|
121
|
-
// Simple tokenizer; allocations are acceptable for initial implementation.
|
|
122
|
-
return path.split(this.delimiter);
|
|
123
|
-
}
|
|
124
|
-
}
|