66 lines
1.4 KiB
JavaScript
66 lines
1.4 KiB
JavaScript
const path = require("path");
|
|
const { spawn } = require("child_process");
|
|
|
|
const entry = path.join(__dirname, "src", "main.js");
|
|
const safeModeEntry = path.join(__dirname, "safe-mode.js");
|
|
const maxRestarts = Number(process.env.MAX_RESTARTS || 25);
|
|
const restartDelayMs = Number(process.env.RESTART_DELAY_MS || 1500);
|
|
const restartCodes = new Set([10, 100]);
|
|
|
|
let restarts = 0;
|
|
let safeModeStarted = false;
|
|
|
|
function startSafeMode() {
|
|
if (safeModeStarted) {
|
|
return;
|
|
}
|
|
safeModeStarted = true;
|
|
const child = spawn(process.execPath, [safeModeEntry], {
|
|
stdio: "inherit",
|
|
env: { ...process.env, SAFE_MODE: "1" }
|
|
});
|
|
child.on("exit", (code) => {
|
|
safeModeStarted = false;
|
|
if (code === 10) {
|
|
restarts = 0;
|
|
startChild();
|
|
}
|
|
});
|
|
}
|
|
|
|
function startChild() {
|
|
const child = spawn(process.execPath, [entry], {
|
|
stdio: "inherit",
|
|
env: { ...process.env, BOT_WRAPPER: "1" }
|
|
});
|
|
|
|
child.on("exit", (code, signal) => {
|
|
if (signal) {
|
|
process.exit(0);
|
|
return;
|
|
}
|
|
|
|
const shouldRestart =
|
|
restartCodes.has(code) || (code !== 0 && restarts < maxRestarts);
|
|
|
|
if (code === 100) {
|
|
startSafeMode();
|
|
return;
|
|
}
|
|
|
|
if (!shouldRestart) {
|
|
if (code && restarts >= maxRestarts) {
|
|
startSafeMode();
|
|
return;
|
|
}
|
|
process.exit(code || 0);
|
|
return;
|
|
}
|
|
|
|
restarts += 1;
|
|
setTimeout(startChild, restartDelayMs);
|
|
});
|
|
}
|
|
|
|
startChild();
|