| 1 | import { EventEmitter } from "events"; |
| 2 | import { vi } from "vitest"; |
| 3 | |
| 4 | /** |
| 5 | * Mocked base service class for testing |
| 6 | */ |
| 7 | export class BaseService<TState> extends EventEmitter { |
| 8 | protected serviceName: string; |
| 9 | protected currentState: TState; |
| 10 | private isInitialized: boolean = false; |
| 11 | |
| 12 | constructor(serviceName: string, initialState: TState) { |
| 13 | super(); |
| 14 | this.serviceName = serviceName; |
| 15 | this.currentState = initialState; |
| 16 | } |
| 17 | |
| 18 | // Mock the abstract method |
| 19 | doInitialize = vi.fn<any>(); |
| 20 | |
| 21 | async initialize(...args: any[]): Promise<TState> { |
| 22 | this.emit("initializing"); |
| 23 | try { |
| 24 | const state = await this.doInitialize(...args); |
| 25 | this.currentState = state; |
| 26 | this.isInitialized = true; |
| 27 | this.emit("initialized", state); |
| 28 | return state; |
| 29 | } catch (error) { |
| 30 | this.emit("error", error); |
| 31 | throw error; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | getState(): TState { |
| 36 | return { ...this.currentState }; |
| 37 | } |
| 38 | |
| 39 | protected setState(newState: Partial<TState>): void { |
| 40 | const previousState = this.currentState; |
| 41 | this.currentState = { ...this.currentState, ...newState }; |
| 42 | this.emit("stateChanged", this.currentState, previousState); |
| 43 | } |
| 44 | |
| 45 | isReady(): boolean { |
| 46 | return this.isInitialized; |
| 47 | } |
| 48 | |
| 49 | async reload(...args: any[]): Promise<TState> { |
| 50 | this.isInitialized = false; |
| 51 | return this.initialize(...args); |
| 52 | } |
| 53 | |
| 54 | async cleanup(): Promise<void> { |
| 55 | this.removeAllListeners(); |
| 56 | this.isInitialized = false; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Interface for services with dependencies |
| 62 | */ |
| 63 | export interface ServiceWithDependencies { |
| 64 | getDependencies(): string[]; |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Helper to check if a service has dependencies |
| 69 | */ |
| 70 | export function hasDependencies( |
| 71 | service: any, |
| 72 | ): service is ServiceWithDependencies { |
| 73 | return !!service && typeof service.getDependencies === "function"; |
| 74 | } |