Interface defining the lifecycle hooks
Arguments type for ctx.fail() (default: [string])
Interface defining the lifecycle hooks
Arguments type for ctx.fail() (default: [string])
Optionaloptions: HookEngine.Options<FailArgs>Subscribe to a lifecycle hook.
Name of the lifecycle hook
Callback function receiving spread args + ctx
Optionaloptions: HookEngine.AddOptionsOptions for this subscription
Cleanup function to remove the subscription
// Simple callback
const cleanup = hooks.add('beforeRequest', (url, opts, ctx) => {
console.log('Request:', url);
});
// With options
hooks.add('analytics', (event, ctx) => {
track(event);
}, { once: true, ignoreOnFail: true });
// With priority (lower runs first)
hooks.add('beforeRequest', cb, { priority: -10 });
// Remove subscription
cleanup();
Execute middleware hooks as an onion (nested) composition.
Unlike run() which executes hooks linearly, pipe() composes hooks
as nested middleware. Each hook receives a next function that calls
the next layer. The innermost layer is coreFn. Control flow is
managed by calling or not calling next() — no ctx.returns() needed.
Hooks execute in priority order (lower first = outermost layer).
The result from the middleware chain
// Retry plugin wraps the fetch call
hooks.add('execute', async (next, opts, ctx) => {
for (let i = 0; i < 3; i++) {
const [result, err] = await attempt(next);
if (!err) return result;
await wait(1000 * i);
}
throw lastError;
}, { priority: -20 });
// Dedupe plugin wraps retry
hooks.add('execute', async (next, opts, ctx) => {
const inflight = getInflight(key);
if (inflight) return inflight;
const result = await next();
share(result);
return result;
}, { priority: -30 });
// Execute: dedupe( retry( makeCall() ) )
const response = await hooks.pipe(
'execute',
() => makeCall(opts),
opts
);
Register hook names for runtime validation. Once any hooks are registered, all hooks must be registered before use.
this (for chaining)
Run all callbacks for a hook asynchronously.
Name of the lifecycle hook to run
Arguments to pass to callbacks (spread + ctx)
RunResult with final args, result, and returned flag
Run all callbacks for a hook synchronously.
Name of the lifecycle hook to run
Arguments to pass to callbacks (spread + ctx)
RunResult with final args, result, and returned flag
Wrap an async function with pre/post lifecycle hooks.
(result, ...originalArgs), can transform resultWrapped function with same signature
Wrap a synchronous function with pre/post lifecycle hooks.
Wrapped function with same signature
A lightweight, type-safe lifecycle hook system.
HookEngine allows you to define lifecycle events and subscribe to them. Callbacks receive spread arguments with a context object as the last param.
Example