|
| 1 | +import { |
| 2 | + AnyOnInitHookFunction, |
| 3 | + LifecycleHooksManager, |
| 4 | + RegisteredHookFunction, |
| 5 | + RegisterHookFunctionParams, |
| 6 | +} from "./types.js"; |
| 7 | + |
| 8 | +export class StandardLifecycleHooksManager implements LifecycleHooksManager { |
| 9 | + private initHooks: Map<string, RegisteredHookFunction<AnyOnInitHookFunction>> = new Map(); |
| 10 | + private taskInitHooks: Map<string, string> = new Map(); |
| 11 | + |
| 12 | + registerGlobalInitHook(hook: RegisterHookFunctionParams<AnyOnInitHookFunction>): void { |
| 13 | + // if there is no id, lets generate one based on the contents of the function |
| 14 | + const id = generateHookId(hook); |
| 15 | + |
| 16 | + const registeredHook = { |
| 17 | + id, |
| 18 | + name: hook.id ?? hook.fn.name, |
| 19 | + fn: hook.fn, |
| 20 | + }; |
| 21 | + |
| 22 | + this.initHooks.set(id, registeredHook); |
| 23 | + } |
| 24 | + |
| 25 | + registerTaskInitHook( |
| 26 | + taskId: string, |
| 27 | + hook: RegisterHookFunctionParams<AnyOnInitHookFunction> |
| 28 | + ): void { |
| 29 | + const registeredHook = { |
| 30 | + id: generateHookId(hook), |
| 31 | + name: taskId, |
| 32 | + fn: hook.fn, |
| 33 | + }; |
| 34 | + |
| 35 | + this.initHooks.set(registeredHook.id, registeredHook); |
| 36 | + this.taskInitHooks.set(taskId, registeredHook.id); |
| 37 | + } |
| 38 | + |
| 39 | + getTaskInitHook(taskId: string): AnyOnInitHookFunction | undefined { |
| 40 | + const hookId = this.taskInitHooks.get(taskId); |
| 41 | + if (!hookId) return undefined; |
| 42 | + return this.initHooks.get(hookId)?.fn; |
| 43 | + } |
| 44 | + |
| 45 | + getGlobalInitHooks(): RegisteredHookFunction<AnyOnInitHookFunction>[] { |
| 46 | + return Array.from(this.initHooks.values()); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +export class NoopLifecycleHooksManager implements LifecycleHooksManager { |
| 51 | + registerGlobalInitHook(hook: RegisterHookFunctionParams<AnyOnInitHookFunction>): void { |
| 52 | + // Noop |
| 53 | + } |
| 54 | + |
| 55 | + registerTaskInitHook( |
| 56 | + taskId: string, |
| 57 | + hook: RegisterHookFunctionParams<AnyOnInitHookFunction> |
| 58 | + ): void { |
| 59 | + // Noop |
| 60 | + } |
| 61 | + |
| 62 | + getTaskInitHook(taskId: string): AnyOnInitHookFunction | undefined { |
| 63 | + return undefined; |
| 64 | + } |
| 65 | + |
| 66 | + getGlobalInitHooks(): RegisteredHookFunction<AnyOnInitHookFunction>[] { |
| 67 | + return []; |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +function generateHookId(hook: RegisterHookFunctionParams<any>): string { |
| 72 | + return hook.id ?? hook.fn.name ?? hook.fn.toString(); |
| 73 | +} |
0 commit comments