Hook Lifecycle
Bunli’s plugin system provides four lifecycle hooks that execute in a specific order:Setup Hook
Called once during CLI initialization. This is where you:- Modify configuration
- Register commands
- Add middleware
- Initialize plugin state
Signature
Context
Example: Dynamic Command Registration
Example: Configuration Modification
Example: Middleware Registration
Config Resolved Hook
Called after all plugins have runsetup and configuration is finalized. Config is now immutable.
Signature
Example: Configuration Validation
Example: Post-Config Initialization
Before Command Hook
Called before each command execution. This is where you:- Validate preconditions
- Inject context
- Update shared state
- Log command starts
Signature
Context
Example: Authentication Check
Example: Request Counter
Example: Environment Detection
Example: Flag Validation
After Command Hook
Called after command execution completes. Receives command result or error.Signature
Extended Context
Example: Error Logging
Example: Telemetry
Example: Success Notification
Hook Execution Order
When multiple plugins are registered, hooks execute in plugin registration order:Setup Phase
Command Phase
Hook Error Handling
Setup Errors
If asetup hook throws, CLI initialization fails:
Before Command Errors
IfbeforeCommand throws, command execution is aborted:
After Command Errors
Errors inafterCommand are logged but don’t affect the command result:
Graceful Error Handling
Hook Best Practices
Performance
- Keep
beforeCommandlightweight - runs on every command - Use
setupfor expensive initialization - Avoid synchronous I/O in hot paths
- Cache expensive computations
Type Safety
- Always type the store:
createPlugin<MyStore>() - Use TypeScript’s contextual typing
- Leverage type inference from context
Error Handling
- Use
better-resultfor recoverable errors - Log warnings instead of throwing when possible
- Provide helpful error messages
- Include context in error objects
Testing
- Test each hook independently
- Use mock contexts for unit tests
- Test error conditions
- Verify hook execution order
Next Steps
Plugin Store
Learn about type-safe shared state
Creating Plugins
Build your own plugins
Official Plugins
Study real hook implementations
Testing
Test plugin hooks effectively