feat: read-only lifecycle observer bus

This commit is contained in:
chrnx committed 2026-06-26 00:33:48 -05:00
1 parent efa89360e4
commit 96880d055b
2 files changed
+56

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
export type LifecycleEvent =
| 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail'
| 'request:step:enter' | 'request:step:leave' | 'request:step:error'
| 'plugin:mounted';
export interface EventPayload {
name: string;
scope?: string;
error?: unknown;
durationMs?: number;
}
export class Bus {
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
on(event: LifecycleEvent, fn: (p: EventPayload) => void): () => void {
const set = this.listeners.get(event) ?? new Set();
set.add(fn);
this.listeners.set(event, set);
return () => set.delete(fn);
}
emit(event: LifecycleEvent, p: EventPayload): void {
for (const fn of this.listeners.get(event) ?? []) {
try { fn(p); } catch { /* observers must never break the pipeline */ }
}
}
}
+28
View File
@@ -0,0 +1,28 @@
import { expect, test, vi } from 'vitest';
import { Bus } from '../src/bus';
test('subscribers receive emitted events', () => {
const bus = new Bus();
const spy = vi.fn();
bus.on('request:step:enter', spy);
bus.emit('request:step:enter', { name: 'auth' });
expect(spy).toHaveBeenCalledWith({ name: 'auth' });
});
test('unsubscribe stops delivery', () => {
const bus = new Bus();
const spy = vi.fn();
const off = bus.on('plugin:mounted', spy);
off();
bus.emit('plugin:mounted', { name: 'logger' });
expect(spy).not.toHaveBeenCalled();
});
test('a throwing subscriber does not break emit for others', () => {
const bus = new Bus();
const good = vi.fn();
bus.on('request:step:error', () => { throw new Error('boom'); });
bus.on('request:step:error', good);
expect(() => bus.emit('request:step:error', { name: 's' })).not.toThrow();
expect(good).toHaveBeenCalled();
});