-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
183 lines (158 loc) · 4.63 KB
/
index.js
File metadata and controls
183 lines (158 loc) · 4.63 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
const fs = require('fs');
const path = require('path');
const Module = require('module');
const EventEmitter = require('node:events');
const originalRequire = Module.prototype.require;
//const originalResolveFilename = Module._resolveFilename;
const modsDir = path.resolve(process.cwd(), 'mods');
class Mod extends EventEmitter {
constructor(mods, name, ctx) {
super();
this.mods = mods;
this.name = name;
this.ctx = ctx;
this.timeouts = [];
this.intervals = [];
}
broadcast(event, ...args) {
this.mods.forEach(mod => {
mod.emit(event, ...args);
});
}
setTimeout(fn, ms) {
const timeout = setTimeout(fn, ms);
this.timeouts.push(timeout);
return timeout;
}
setInterval(fn, ms) {
const interval = setInterval(fn, ms);
this.intervals.push(interval);
return interval;
}
clearTimeout(timeout) {
clearTimeout(timeout);
this.timeouts.splice(this.timeouts.indexOf(timeout), 1);
}
clearInterval(interval) {
clearInterval(interval);
this.intervals.splice(this.intervals.indexOf(interval), 1);
}
async unload(isReloading = false) {
this.emit('beforeUnload', isReloading);
this.removeAllListeners();
this.timeouts.forEach(timeout => clearTimeout(timeout));
this.intervals.forEach(interval => clearInterval(interval));
const beforeUnload = await this.beforeUnload;
beforeUnload && await beforeUnload();
}
}
class Mods {
constructor(mods, name, ctx) {
this.mods = mods;
this.name = name;
this.ctx = ctx;
this.graph = {};
this.loaded = {};
}
async autoload(ctx) {
const files = fs.readdirSync(modsDir);
await Promise.all(files.map(file => this.load(file.replace('.js', ''), ctx)));
}
async load(name, ctx) {
if (Array.isArray(name)) {
return Promise.all(name.map(mod => this.load(mod)));
}
const load = originalRequire(`${modsDir}/${name}`);
const mod = new Mod(this, name, ctx);
this.loaded[name] = mod;
mod.beforeUnload = load.call(mod, ctx); // We need to set the beforeUnload even before loading is complete (so the unload can work correctly)
await mod.beforeUnload;
return mod;
}
async unload(name, isReloading = false) {
if (!name) {
await Promise.all(Object.keys(this.loaded).map(mod => this.unload(mod, isReloading)));
return;
}
if (Array.isArray(name)) {
await Promise.all(name.map(mod => this.unload(mod, isReloading)));
return;
}
if (!this.loaded[name]) {
return;
}
await this.loaded[name].unload(isReloading);
delete this.loaded[name];
}
uncache(filename, uncached = {}) {
if (uncached[filename]) {
return;
}
uncached[filename] = true;
delete require.cache[filename];
if (this.graph[filename]) {
this.graph[filename].requires.forEach(dependency => {
this.uncache(dependency, uncached);
});
}
}
async reload(name, ctx) {
if (!name) {
await Promise.all(Object.keys(this.loaded).map(mod => this.reload(mod, ctx)));
return;
}
if (Array.isArray(name)) {
await Promise.all(name.map(mod => this.reload(mod, ctx)));
return;
}
await this.unload(name, true);
this.uncache(`${modsDir}/${name}`);
await this.load(name, ctx);
}
}
const mods = new Mods();
Module.prototype.require = function(name) {
if (!mods.graph[this.filename]) {
mods.graph[this.filename] = {
requires: new Set(),
}
}
const filename = require.resolve(name, {
paths: [path.dirname(this.filename)]
});
mods.graph[this.filename].requires.add(name);
return originalRequire.call(this, filename);
};
/*Module._resolveFilename = function(request, parent, isMain, options) {
const resolvedPath = originalResolveFilename.apply(this, arguments);
// Now you have both the requested module name and its resolved path
console.log(`${request} resolves to ${resolvedPath}`);
return resolvedPath;
};*/
// Handle process exit events
const exitSignals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
let isExiting = false;
const cleanup = async () => {
if (isExiting) return;
isExiting = true;
try {
await mods.unload();
} catch (error) {
console.error('Error during module cleanup:', error);
} finally {
process.exit(0);
}
};
exitSignals.forEach(signal => {
process.on(signal, cleanup);
});
// Handle uncaught exceptions and unhandled rejections
process.on('uncaughtException', async (error) => {
console.error('Uncaught Exception:', error);
await cleanup();
});
process.on('unhandledRejection', async (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
await cleanup();
});
module.exports = mods;