Migrate From Bun to Express
This commit is contained in:
parent
b525cc0dd0
commit
d2c014e744
8 changed files with 3054 additions and 668 deletions
133
index.js
133
index.js
|
|
@ -4,6 +4,10 @@ import { join, dirname } from 'path';
|
|||
import { fileURLToPath } from 'url';
|
||||
import { secureImportModule } from './utils/plugins.js';
|
||||
import * as logs from './utils/logs.js';
|
||||
import express from 'express';
|
||||
import { createServer } from 'http';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { spawn } from 'child_process';
|
||||
|
||||
// Load environment variables from .env file
|
||||
import dotenv from 'dotenv';
|
||||
|
|
@ -45,10 +49,9 @@ if (process.argv.includes('-d')) {
|
|||
}
|
||||
// Spawn new background process
|
||||
const args = process.argv.slice(1).filter((arg) => arg !== '-d');
|
||||
const cp = Bun.spawn({
|
||||
cmd: [process.argv[0], ...args],
|
||||
const cp = spawn(process.argv[0], args, {
|
||||
detached: true,
|
||||
stdio: ['ignore', 'ignore', 'ignore'],
|
||||
stdio: 'ignore'
|
||||
});
|
||||
cp.unref();
|
||||
writeFileSync(pidFile, cp.pid.toString(), 'utf8');
|
||||
|
|
@ -105,21 +108,14 @@ async function initDataDirectories() {
|
|||
}
|
||||
|
||||
function staticFileMiddleware() {
|
||||
return async (request) => {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
if (pathname.startsWith('/webfont/') || pathname.startsWith('/js/')) {
|
||||
const filePath = join(rootDir, 'pages/interstitial', pathname.slice(1));
|
||||
try {
|
||||
return new Response(Bun.file(filePath), {
|
||||
headers: { 'Cache-Control': 'public, max-age=604800' },
|
||||
});
|
||||
} catch {
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const router = express.Router();
|
||||
router.use('/webfont', express.static(join(rootDir, 'pages/interstitial/webfont'), {
|
||||
maxAge: '7d'
|
||||
}));
|
||||
router.use('/js', express.static(join(rootDir, 'pages/interstitial/js'), {
|
||||
maxAge: '7d'
|
||||
}));
|
||||
return router;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
|
|
@ -132,7 +128,19 @@ async function main() {
|
|||
logs.config('stats', 'loaded');
|
||||
|
||||
logs.section('OPERATIONS');
|
||||
let wsHandler;
|
||||
|
||||
const app = express();
|
||||
const server = createServer(app);
|
||||
|
||||
// Trust proxy headers (important for proper protocol detection)
|
||||
app.set('trust proxy', true);
|
||||
|
||||
// Initialize WebSocket server
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
|
||||
// Store WebSocket handlers
|
||||
let wsHandlers = {};
|
||||
|
||||
try {
|
||||
await secureImportModule('checkpoint.js');
|
||||
} catch (e) {
|
||||
|
|
@ -146,7 +154,9 @@ async function main() {
|
|||
try {
|
||||
await secureImportModule('plugins/proxy.js');
|
||||
const mod = await import('./plugins/proxy.js');
|
||||
wsHandler = mod.proxyWebSocketHandler;
|
||||
if (mod.proxyWebSocketHandler) {
|
||||
wsHandlers = mod.proxyWebSocketHandler;
|
||||
}
|
||||
} catch (e) {
|
||||
logs.error('proxy', `Failed to load proxy plugin: ${e}`);
|
||||
}
|
||||
|
|
@ -156,7 +166,8 @@ async function main() {
|
|||
logs.error('stats', `Failed to load stats plugin: ${e}`);
|
||||
}
|
||||
|
||||
registerPlugin('static', staticFileMiddleware());
|
||||
// Register static middleware
|
||||
app.use(staticFileMiddleware());
|
||||
|
||||
logs.section('PLUGINS');
|
||||
// Ensure ipfilter runs first by moving it to front of the registry
|
||||
|
|
@ -169,28 +180,76 @@ async function main() {
|
|||
logs.section('SYSTEM');
|
||||
freezePlugins();
|
||||
|
||||
logs.section('SERVER');
|
||||
const portNumber = Number(process.env.PORT || 3000);
|
||||
// Apply all plugin middlewares to Express
|
||||
const middlewareHandlers = loadPlugins();
|
||||
logs.server(`🚀 Server is up and running on port ${portNumber}...`);
|
||||
logs.section('REQ LOGS');
|
||||
Bun.serve({
|
||||
port: portNumber,
|
||||
async fetch(request, server) {
|
||||
for (const handler of middlewareHandlers) {
|
||||
middlewareHandlers.forEach(handler => {
|
||||
if (typeof handler === 'function') {
|
||||
// Wrap plugin handlers to work with Express
|
||||
app.use(async (req, res, next) => {
|
||||
try {
|
||||
const resp = await handler(request, server);
|
||||
if (resp instanceof Response) return resp;
|
||||
const result = await handler(req, { upgrade: () => false });
|
||||
if (result instanceof Response) {
|
||||
// Convert Response to Express response
|
||||
res.status(result.status);
|
||||
result.headers.forEach((value, key) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
const body = await result.text();
|
||||
res.send(body);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
} catch (err) {
|
||||
logs.error('server', `Handler error: ${err}`);
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
} else if (handler && handler.middleware) {
|
||||
// If plugin exports Express middleware directly
|
||||
app.use(handler.middleware);
|
||||
}
|
||||
});
|
||||
|
||||
// 404 handler
|
||||
app.use((req, res) => {
|
||||
res.status(404).send('Not Found');
|
||||
});
|
||||
|
||||
// Error handler
|
||||
app.use((err, req, res, next) => {
|
||||
logs.error('server', `Server error: ${err.message}`);
|
||||
res.status(500).send(`Server Error: ${err.message}`);
|
||||
});
|
||||
|
||||
// Handle WebSocket upgrades
|
||||
server.on('upgrade', (request, socket, head) => {
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit('connection', ws, request);
|
||||
});
|
||||
});
|
||||
|
||||
// WebSocket connection handler
|
||||
if (wsHandlers.open) {
|
||||
wss.on('connection', (ws, request) => {
|
||||
ws.data = {};
|
||||
if (wsHandlers.open) wsHandlers.open(ws);
|
||||
if (wsHandlers.message) {
|
||||
ws.on('message', (message) => wsHandlers.message(ws, message));
|
||||
}
|
||||
return new Response('Not Found', { status: 404 });
|
||||
},
|
||||
websocket: wsHandler,
|
||||
error(err) {
|
||||
return new Response(`Server Error: ${err.message}`, { status: 500 });
|
||||
},
|
||||
if (wsHandlers.close) {
|
||||
ws.on('close', (code, reason) => wsHandlers.close(ws, code, reason));
|
||||
}
|
||||
if (wsHandlers.error) {
|
||||
ws.on('error', (err) => wsHandlers.error(ws, err));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
logs.section('SERVER');
|
||||
const portNumber = Number(process.env.PORT || 3000);
|
||||
server.listen(portNumber, () => {
|
||||
logs.server(`🚀 Server is up and running on port ${portNumber}...`);
|
||||
logs.section('REQ LOGS');
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue