-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.dev.js
More file actions
93 lines (80 loc) · 2.45 KB
/
index.dev.js
File metadata and controls
93 lines (80 loc) · 2.45 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
import "dotenv/config";
import express from "express";
import * as vite from "vite";
const app = express();
/**
Route handlers and static hosting
*/
console.log("Starting development server");
const viteDevServer = await vite.createServer({
server: { middlewareMode: true },
});
// Track the current server module to enable hot reloading
let currentServerApp = null;
// Function to load/reload the server module
async function loadServerModule() {
try {
const source = await viteDevServer.ssrLoadModule("./app/server.ts");
currentServerApp = source.app;
console.log("Server module (re)loaded");
} catch (error) {
if (error instanceof Error) {
viteDevServer.ssrFixStacktrace(error);
}
console.error("Error loading server module:", error);
}
}
// Initial load
void loadServerModule();
// Add Vite middleware first
app.use(viteDevServer.middlewares);
// Proxy all requests to the current server app
// This allows us to hot-swap the server without restarting Express
app.use((req, res, next) => {
if (currentServerApp) {
currentServerApp(req, res, next);
} else {
res.status(503).send("Server module not loaded");
}
});
// Listen for file changes and reload server module
viteDevServer.watcher.on("change", async (file) => {
// Only reload for server-side files (not client components)
if (
file.includes("/app/server.ts") ||
file.includes("/app/discord/") ||
file.includes("/app/commands/") ||
file.includes("/app/helpers/") ||
file.includes("/app/models/")
) {
console.log(`Server file changed: ${file}, reloading...`);
// Invalidate Vite's module cache
const modules = viteDevServer.moduleGraph.getModulesByFile(file);
if (modules) {
for (const mod of modules) {
viteDevServer.moduleGraph.invalidateModule(mod);
}
}
// Reload the server module
await loadServerModule();
}
});
// Fix stack traces for unhandled errors using Vite's source map support
process.on("uncaughtException", (error) => {
if (error instanceof Error) {
viteDevServer.ssrFixStacktrace(error);
}
console.error("Uncaught Exception:", error);
process.exit(1);
});
process.on("unhandledRejection", (reason) => {
if (reason instanceof Error) {
viteDevServer.ssrFixStacktrace(reason);
}
console.error("Unhandled Rejection:", reason);
process.exit(1);
});
const PORT = process.env.PORT ?? "3000";
app.listen(PORT, async () => {
console.log("INI", "Now listening on port", PORT);
});