diff --git a/src/plugin.ts b/src/plugin.ts new file mode 100644 index 0000000..d0c25d8 --- /dev/null +++ b/src/plugin.ts @@ -0,0 +1,20 @@ +import { Bus } from './bus'; + +export interface ScopeNode { + kind: 'step' | 'provider'; + name: string; + needs: string[]; + provides: string[]; + run: (ctx: any) => any; +} + +export interface ScopeApi { add(node: ScopeNode): void } +export interface PluginApi { bus: { on: Bus['on'] }; scope: ScopeApi } +export type Plugin = (api: PluginApi) => void; + +export function mountPlugin(plugin: Plugin, bus: Bus, scope: ScopeApi): void { + // Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural. + const api: PluginApi = { bus: { on: bus.on.bind(bus) }, scope }; + plugin(api); + bus.emit('plugin:mounted', { name: plugin.name || 'anonymous' }); +} diff --git a/test/plugin.test.ts b/test/plugin.test.ts new file mode 100644 index 0000000..c1f620b --- /dev/null +++ b/test/plugin.test.ts @@ -0,0 +1,30 @@ +import { expect, test, vi } from 'vitest'; +import { Bus } from '../src/bus'; +import { mountPlugin, Plugin, ScopeApi } from '../src/plugin'; + +test('plugin can observe via bus.on and add to its own scope', () => { + const bus = new Bus(); + const added: string[] = []; + const scope: ScopeApi = { add: (n) => added.push(n.name) }; + + const logger: Plugin = (api) => { + api.bus.on('request:step:enter', () => {}); + api.scope.add({ kind: 'step', name: 'log', needs: [], provides: [], run: () => ({}) }); + }; + + const mounted = vi.fn(); + bus.on('plugin:mounted', mounted); + mountPlugin(logger, bus, scope); + + expect(added).toEqual(['log']); + expect(mounted).toHaveBeenCalled(); +}); + +test('plugin api does NOT expose bus.emit', () => { + const bus = new Bus(); + const scope: ScopeApi = { add: () => {} }; + const plugin: Plugin = (api) => { + expect((api.bus as any).emit).toBeUndefined(); + }; + mountPlugin(plugin, bus, scope); +});