Repository navigation
Expand file tree
/
Copy pathplugin-system.js
More file actions
593 lines (516 loc) · 21.6 KB
/
Copy pathplugin-system.js
File metadata and controls
593 lines (516 loc) · 21.6 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
// Enhanced Plugin System with Injection Support
const fs = require('fs');
const path = require('path');
const InjectionEngine = require('./injection-engine');
class PluginSystem {
constructor(app, router, proxyHandler, instanceManager = null) {
this.app = app;
this.router = router;
this.proxyHandler = proxyHandler;
this.instanceManager = instanceManager;
this.injectionEngine = new InjectionEngine();
this.plugins = [];
this.pluginDir = path.join(__dirname, 'plugins');
this.hooks = new Map();
this.errors = []; // Track plugin errors
this.maxErrors = 100; // Max errors to retain
this.setupAssetRoutes();
this.setupInjectionProcessor();
this.setupManagementRoutes();
}
// Record a plugin error
_recordError(pluginId, context, error) {
const entry = {
pluginId,
context,
message: error?.message || String(error),
stack: error?.stack,
timestamp: new Date().toISOString()
};
this.errors.push(entry);
if (this.errors.length > this.maxErrors) {
this.errors = this.errors.slice(-this.maxErrors);
}
console.error(`[Plugin:${pluginId}] Error in ${context}:`, entry.message);
this.executeHook('plugin:error', entry).catch(() => {});
return entry;
}
// Setup routes for serving plugin assets
setupAssetRoutes() {
// Serve plugin assets at /_plugins/assets/:pluginId/:filename
this.app.get('/_plugins/assets/:pluginId/:filename', (req, res) => {
const { pluginId, filename } = req.params;
const assetId = `${pluginId}/${filename}`;
const asset = this.injectionEngine.getAsset(assetId);
if (asset) {
res.set('Content-Type', asset.contentType);
res.set('Cache-Control', 'public, max-age=3600');
res.send(asset.content);
} else {
res.status(404).send('Asset not found');
}
});
// Plugin info endpoint
this.app.get('/_plugins/info', (req, res) => {
res.json({
plugins: this.plugins.map(p => ({
id: p.id,
name: p.name,
version: p.version,
description: p.description,
author: p.author,
enabled: p.enabled !== false,
loadedAt: p.loadedAt
})),
injections: this.injectionEngine.getStats(),
assets: this.injectionEngine.listAssets(),
errors: this.errors.slice(-20)
});
});
}
// Management API for plugins
setupManagementRoutes() {
// Enable/disable a plugin
this.app.post('/_plugins/:id/toggle', (req, res) => {
const plugin = this.plugins.find(p => p.id === req.params.id);
if (!plugin) return res.status(404).json({ error: 'Plugin not found' });
plugin.enabled = !(plugin.enabled !== false);
if (plugin.enabled && plugin.onEnable) {
try { plugin.onEnable(); } catch (e) { this._recordError(plugin.id, 'onEnable', e); }
} else if (!plugin.enabled && plugin.onDisable) {
try { plugin.onDisable(); } catch (e) { this._recordError(plugin.id, 'onDisable', e); }
}
res.json({ id: plugin.id, enabled: plugin.enabled });
});
// Reload a specific plugin
this.app.post('/_plugins/:id/reload', (req, res) => {
const success = this.reload(req.params.id);
res.json({ success, id: req.params.id });
});
// Get plugin errors
this.app.get('/_plugins/errors', (req, res) => {
const pluginId = req.query.plugin;
const errors = pluginId
? this.errors.filter(e => e.pluginId === pluginId)
: this.errors;
res.json({ errors });
});
// Clear errors
this.app.post('/_plugins/errors/clear', (req, res) => {
this.errors = [];
res.json({ success: true });
});
}
// Setup response processing for injections
setupInjectionProcessor() {
this.proxyHandler.addResponseModifier((body, proxyRes, req) => {
const contentType = proxyRes.headers['content-type'] || '';
// Only process HTML responses from Discord
if (contentType.includes('text/html') && req._target?.includes('discord.com')) {
return this.injectionEngine.processHTML(body);
}
return body;
});
}
// Load a plugin
load(plugin) {
let pluginSource = null;
if (typeof plugin === 'string') {
pluginSource = plugin;
try {
const pluginPath = require.resolve(plugin);
delete require.cache[pluginPath]; // Allow reloading
plugin = require(pluginPath);
} catch (err) {
this._recordError(pluginSource, 'require', err);
console.error(`[Plugin] ✗ Failed to require ${pluginSource}:`, err.message);
return this;
}
}
// Validate plugin structure
if (!plugin || typeof plugin !== 'object') {
const id = pluginSource || 'unknown';
this._recordError(id, 'validate', new Error('Plugin must export an object'));
console.error(`[Plugin] ✗ Invalid plugin export from ${id}`);
return this;
}
const pluginInstance = {
id: plugin.id || plugin.name?.toLowerCase().replace(/\s+/g, '-') || `plugin-${Date.now()}`,
name: plugin.name || 'unnamed',
version: plugin.version || '1.0.0',
description: plugin.description || '',
author: plugin.author || '',
enabled: plugin.enabled !== false,
hooks: new Map(),
loadedAt: new Date().toISOString(),
_source: pluginSource,
...plugin
};
// Check for duplicate IDs
const existing = this.plugins.find(p => p.id === pluginInstance.id);
if (existing) {
console.warn(`[Plugin] Duplicate ID '${pluginInstance.id}', skipping`);
return this;
}
// Create plugin API context
const api = this.createPluginAPI(pluginInstance);
// Initialize plugin with error boundary
if (plugin.init) {
try {
const result = plugin.init(api);
// Support async init
if (result && typeof result.then === 'function') {
result.catch(err => {
this._recordError(pluginInstance.id, 'asyncInit', err);
});
}
console.log(`[Plugin] ✓ Loaded: ${pluginInstance.name} v${pluginInstance.version}`);
} catch (err) {
this._recordError(pluginInstance.id, 'init', err);
console.error(`[Plugin] ✗ Failed to initialize ${pluginInstance.name}:`, err.message);
// Still register the plugin but mark as failed
pluginInstance.enabled = false;
pluginInstance._initError = err.message;
this.plugins.push(pluginInstance);
return this;
}
}
this.plugins.push(pluginInstance);
this.executeHook('plugin:loaded', { plugin: pluginInstance }).catch(() => {});
return this;
}
// Create API for a specific plugin
createPluginAPI(plugin) {
const self = this;
const engine = this.injectionEngine;
const pluginId = plugin.id;
// Safe wrapper - catches errors in plugin-provided callbacks
const safeCall = (fn, context) => {
return (...args) => {
try {
return fn(...args);
} catch (err) {
self._recordError(pluginId, context, err);
}
};
};
return {
// Plugin info
id: pluginId,
name: plugin.name,
version: plugin.version,
// Express app access (wrapped to catch route handler errors)
app: this._createSafeApp(pluginId),
// Router and instance manager access
addRoute: (matcher, target) => this.router.addRoute(matcher, target),
instanceManager: this.instanceManager,
// Proxy modifications (wrapped for safety)
addRewriter: (pattern, replacement) => this.proxyHandler.addRewriter(pattern, replacement),
addResponseModifier: (modifier) => {
this.proxyHandler.addResponseModifier((body, proxyRes, req) => {
try {
return modifier(body, proxyRes, req);
} catch (err) {
self._recordError(pluginId, 'responseModifier', err);
return body;
}
});
},
// === INJECTION API ===
// Inject raw HTML at specific positions
injectHTML: (position, html) => {
engine.injectHTML(position, html, pluginId);
},
// Inject CSS styles
injectCSS: (css, important = false) => {
engine.injectCSS(css, pluginId, important);
},
// Inject JavaScript
injectJS: (js, position = 'bodyEnd') => {
engine.injectJS(js, pluginId, position);
},
// Inject external script
injectScript: (url, async = true, position = 'head') => {
engine.injectScript(url, pluginId, async, position);
},
// Inject external stylesheet
injectStylesheet: (url) => {
engine.injectStylesheet(url, pluginId);
},
// Add virtual asset (accessible at /_plugins/assets/:pluginId/:filename)
addAsset: (filename, content, contentType) => {
const assetId = `${pluginId}/${filename}`;
engine.addAsset(assetId, content, contentType);
},
// Add CSS file as asset and auto-inject
addCSSAsset: (filename, css) => {
const assetId = `${pluginId}/${filename}`;
engine.addAsset(assetId, css, 'text/css');
engine.injectStylesheet(`/_plugins/assets/${pluginId}/${filename}`, pluginId);
},
// Add JS file as asset and auto-inject
addJSAsset: (filename, js, async = true) => {
const assetId = `${pluginId}/${filename}`;
engine.addAsset(assetId, js, 'application/javascript');
engine.injectScript(`/_plugins/assets/${pluginId}/${filename}`, pluginId, async, 'head');
},
// === DOM MANIPULATION HELPERS ===
// Inject UI component
addComponent: (selector, html, position = 'before') => {
const fullPosition = `${position}:${selector}`;
engine.injectHTML(fullPosition, html, pluginId);
},
// Modify existing Discord elements
modifyElement: (selector, modifications) => {
const css = Object.entries(modifications)
.map(([prop, val]) => `${prop}: ${val} !important;`)
.join(' ');
engine.injectCSS(`${selector} { ${css} }`, pluginId, true);
},
// Hide elements
hideElement: (selector) => {
engine.injectCSS(`${selector} { display: none !important; }`, pluginId, true);
},
// Add event listener helper (injects JS to attach listener)
onEvent: (selector, event, handler) => {
const js = `
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('${selector}').forEach(el => {
el.addEventListener('${event}', ${handler.toString()});
});
});
`;
engine.injectJS(js, pluginId, 'bodyEnd');
},
// Wait for element and execute callback (injects polling script)
waitForElement: (selector, callback) => {
const js = `
(function wait() {
const el = document.querySelector('${selector}');
if (el) {
(${callback.toString()})(el);
} else {
setTimeout(wait, 100);
}
})();
`;
engine.injectJS(js, pluginId, 'bodyEnd');
},
// === HOOKS ===
registerHook: (event, handler) => {
if (!self.hooks.has(event)) {
self.hooks.set(event, []);
}
self.hooks.get(event).push({ pluginId, handler });
},
// === UTILITIES ===
log: (...args) => console.log(`[${plugin.name}]`, ...args),
error: (...args) => {
console.error(`[${plugin.name}]`, ...args);
self._recordError(pluginId, 'plugin.error', args.join(' '));
},
warn: (...args) => console.warn(`[${plugin.name}]`, ...args),
// Config access
config: require('./config'),
// Storage (simple in-memory key-value per plugin)
storage: {
get: (key) => plugin._storage?.[key],
set: (key, value) => {
if (!plugin._storage) plugin._storage = {};
plugin._storage[key] = value;
},
delete: (key) => {
if (plugin._storage) delete plugin._storage[key];
},
clear: () => { plugin._storage = {}; },
keys: () => Object.keys(plugin._storage || {})
}
};
}
// Create a safe Express app wrapper that catches route handler errors
_createSafeApp(pluginId) {
const self = this;
const realApp = this.app;
const wrapHandler = (handler) => {
return async (req, res, next) => {
try {
const result = handler(req, res, next);
if (result && typeof result.then === 'function') {
result.catch(err => {
self._recordError(pluginId, 'routeHandler', err);
if (!res.headersSent) {
res.status(500).json({ error: 'Plugin error', plugin: pluginId });
}
});
}
} catch (err) {
self._recordError(pluginId, 'routeHandler', err);
if (!res.headersSent) {
res.status(500).json({ error: 'Plugin error', plugin: pluginId });
}
}
};
};
// Proxy the app methods to wrap handlers
return new Proxy(realApp, {
get(target, prop) {
const httpMethods = ['get', 'post', 'put', 'delete', 'patch', 'all', 'use'];
if (httpMethods.includes(prop)) {
return (path, ...handlers) => {
const wrappedHandlers = handlers.map(h =>
typeof h === 'function' ? wrapHandler(h) : h
);
return target[prop](path, ...wrappedHandlers);
};
}
return target[prop];
}
});
}
// Load all plugins from directory (supports both flat .js files and subdirectories with plugin.js)
loadAll() {
if (!fs.existsSync(this.pluginDir)) {
fs.mkdirSync(this.pluginDir, { recursive: true });
return this;
}
const entries = fs.readdirSync(this.pluginDir, { withFileTypes: true });
const pluginPaths = [];
for (const entry of entries) {
if (entry.name === 'README.md' || entry.name.startsWith('.')) continue;
if (entry.isFile() && entry.name.endsWith('.js')) {
// Flat plugin file
pluginPaths.push({
name: entry.name,
path: path.join(this.pluginDir, entry.name)
});
} else if (entry.isDirectory()) {
// Subdirectory plugin — look for plugin.js or index.js
const subPlugin = path.join(this.pluginDir, entry.name, 'plugin.js');
const subIndex = path.join(this.pluginDir, entry.name, 'index.js');
if (fs.existsSync(subPlugin)) {
pluginPaths.push({ name: entry.name, path: subPlugin });
} else if (fs.existsSync(subIndex)) {
pluginPaths.push({ name: entry.name, path: subIndex });
}
}
}
// Sort: load core plugins first, then alphabetically
pluginPaths.sort((a, b) => {
if (a.name.includes('core-')) return -1;
if (b.name.includes('core-')) return 1;
return a.name.localeCompare(b.name);
});
for (const { name, path: pluginPath } of pluginPaths) {
try {
this.load(pluginPath);
} catch (err) {
this._recordError(name, 'load', err);
console.error(`[Plugin] Failed to load ${name}:`, err.message);
}
}
const enabled = this.plugins.filter(p => p.enabled !== false).length;
const failed = this.plugins.filter(p => p.enabled === false && p._initError).length;
console.log(`[PluginSystem] Loaded ${this.plugins.length} plugin(s) (${enabled} enabled, ${failed} failed)`);
return this;
}
// Execute a hook with error isolation per handler
async executeHook(event, data) {
const handlers = this.hooks.get(event) || [];
const results = [];
for (const { pluginId, handler } of handlers) {
try {
const result = await Promise.resolve(handler(data));
results.push({ pluginId, success: true, result });
} catch (err) {
this._recordError(pluginId, `hook:${event}`, err);
results.push({ pluginId, success: false, error: err.message });
}
}
return results;
}
// Express middleware with error protection
middleware() {
return async (req, res, next) => {
try {
await this.executeHook('request:start', { req, res });
} catch (err) {
console.error('[PluginSystem] Hook middleware error:', err.message);
}
res.on('finish', () => {
this.executeHook('request:end', { req, res }).catch(() => {});
});
next();
};
}
// List loaded plugins
list() {
return this.plugins.map(p => ({
id: p.id,
name: p.name,
version: p.version,
description: p.description,
author: p.author
}));
}
// Reload a plugin by ID
reload(pluginId) {
const idx = this.plugins.findIndex(p => p.id === pluginId);
if (idx === -1) {
console.error(`[PluginSystem] Plugin ${pluginId} not found`);
return false;
}
const oldPlugin = this.plugins[idx];
// Call destroy lifecycle if available
if (oldPlugin.destroy) {
try {
oldPlugin.destroy();
} catch (err) {
this._recordError(pluginId, 'destroy', err);
}
}
// Remove old injections and hooks
this.injectionEngine.removeById(pluginId);
for (const [event, handlers] of this.hooks) {
this.hooks.set(event, handlers.filter(h => h.pluginId !== pluginId));
}
// Remove from list
this.plugins.splice(idx, 1);
// Try to find and reload from file
const source = oldPlugin._source;
if (source && fs.existsSync(source)) {
this.load(source);
console.log(`[PluginSystem] Reloaded ${pluginId}`);
return true;
}
// Try common locations
const candidates = [
path.join(this.pluginDir, `${pluginId}.js`),
path.join(this.pluginDir, pluginId, 'plugin.js'),
path.join(this.pluginDir, pluginId, 'index.js')
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
this.load(candidate);
console.log(`[PluginSystem] Reloaded ${pluginId} from ${candidate}`);
return true;
}
}
console.error(`[PluginSystem] Could not find source for ${pluginId}`);
return false;
}
// Graceful shutdown - call destroy on all plugins
async shutdown() {
console.log('[PluginSystem] Shutting down plugins...');
for (const plugin of this.plugins) {
if (plugin.destroy) {
try {
await Promise.resolve(plugin.destroy());
} catch (err) {
this._recordError(plugin.id, 'shutdown', err);
}
}
}
await this.executeHook('system:shutdown', {});
}
}
module.exports = PluginSystem;