Creating Custom Processors
Processors in Ecopages are plugins that handle file transformations during the build process. This guide will show you how to create your own processor.
Basic Structure
A processor extends the Processor
abstract class from @ecopages/core
:
import { Processor } from '@ecopages/core/plugins/processor';
import type { BunPlugin } from 'bun';
class CustomProcessor extends Processor {
// Plugins used during build time
buildPlugins: BunPlugin[] = [];
// Plugins used during runtime
plugins: BunPlugin[] = [];
constructor(config: ProcessorConfig) {
super({
name: 'custom-processor',
watch: {
paths: ['src/custom'],
extensions: ['.custom'],
},
...config
});
}
async setup(): Promise<void> {
// Initialize resources, create cache directories, etc.
}
async process(input: unknown): Promise<unknown> {
// Transform the input
return input;
}
async teardown(): Promise<void> {
// Cleanup resources
}
}
Processor Lifecycle
- Setup: Called when the processor is initialized
- Process: Called for each file that matches the processor's configuration
- Teardown: Called when the processor is being shut down
Working with Cache
Processors have built-in caching capabilities:
class CustomProcessor extends Processor {
async process(input: string): Promise<string> {
const cacheKey = 'my-cache-key';
// Try to read from cache first
const cached = await this.readCache<string>(cacheKey);
if (cached) return cached;
// Process and cache result
const result = await someExpensiveOperation(input);
await this.writeCache(cacheKey, result);
return result;
}
}
Adding Bun Plugins
You can add Bun plugins for both build time and runtime:
import { plugin } from 'bun';
class CustomProcessor extends Processor {
buildPlugins = [
plugin({
name: 'custom-build-plugin',
setup(build) {
// Build-time plugin configuration
},
}),
];
plugins = [
plugin({
name: 'custom-runtime-plugin',
setup(build) {
// Runtime plugin configuration
},
}),
];
}
File Watching
Configure file watching for development mode:
class CustomProcessor extends Processor {
constructor() {
super({
name: 'custom-processor',
watch: {
paths: ['src/custom'],
extensions: ['.custom'],
onChange: async (path) => {
// Handle file changes
},
onDelete: async (path) => {
// Handle file deletions
},
},
});
}
}
Using the Processor
Register your processor in the Ecopages configuration:
import { ConfigBuilder } from '@ecopages/core';
const customProcessor = new CustomProcessor({
// processor options
});
const config = await new ConfigBuilder()
.addProcessor(customProcessor)
.build();
Best Practices
- Use meaningful names for your processors
- Implement proper error handling
- Cache expensive operations
- Clean up resources in teardown
- Follow TypeScript best practices
- Document your processor's API