Repository navigation
Expand file tree
/
Copy pathplugin-manager.js
More file actions
98 lines (86 loc) · 2.9 KB
/
Copy pathplugin-manager.js
File metadata and controls
98 lines (86 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const fs = require('fs');
const path = require('path');
class PluginManager {
constructor(app, router, proxyHandler) {
this.app = app;
this.router = router;
this.proxyHandler = proxyHandler;
this.plugins = [];
this.pluginDir = path.join(__dirname, 'plugins');
}
// Load a single plugin
load(plugin) {
if (typeof plugin === 'string') {
// Load from file path
const pluginPath = require.resolve(plugin);
plugin = require(pluginPath);
}
const pluginInstance = {
name: plugin.name || 'unnamed',
version: plugin.version || '1.0.0',
hooks: {},
...plugin
};
// Initialize plugin with context
if (plugin.init) {
plugin.init({
app: this.app,
router: this.router,
proxyHandler: this.proxyHandler,
registerHook: (event, handler) => this.registerHook(pluginInstance, event, handler),
addRoute: (matcher, target) => this.router.addRoute(matcher, target),
addRewriter: (pattern, replacement) => this.proxyHandler.addRewriter(pattern, replacement),
addResponseModifier: (modifier) => this.proxyHandler.addResponseModifier(modifier)
});
}
this.plugins.push(pluginInstance);
console.log(`[Plugin] Loaded: ${pluginInstance.name} v${pluginInstance.version}`);
return this;
}
// Load all plugins from plugin directory
loadAll() {
if (!fs.existsSync(this.pluginDir)) {
fs.mkdirSync(this.pluginDir, { recursive: true });
return this;
}
const files = fs.readdirSync(this.pluginDir);
for (const file of files) {
if (file.endsWith('.js')) {
const pluginPath = path.join(this.pluginDir, file);
try {
this.load(pluginPath);
} catch (err) {
console.error(`[Plugin] Failed to load ${file}:`, err.message);
}
}
}
return this;
}
registerHook(plugin, event, handler) {
if (!plugin.hooks[event]) {
plugin.hooks[event] = [];
}
plugin.hooks[event].push(handler);
}
// Execute hooks
async execute(event, data) {
for (const plugin of this.plugins) {
if (plugin.hooks[event]) {
for (const handler of plugin.hooks[event]) {
await handler(data);
}
}
}
}
// Middleware generator for Express
middleware() {
return async (req, res, next) => {
await this.execute('request', { req, res });
next();
};
}
list() {
return this.plugins.map(p => ({ name: p.name, version: p.version }));
}
}
module.exports = PluginManager;