-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hot-reload.mjs
53 lines (43 loc) · 1.25 KB
/
hot-reload.mjs
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
import { randomUUID } from "node:crypto";
import { watch } from "node:fs";
import fp from "fastify-plugin";
import ws from "@fastify/websocket";
import * as z from "zod";
let connections = [];
const hotReloadWatchOptionsSchema = z.object({
paths: z.array(z.string()),
disabled: z.boolean().default(false),
});
const fileWatchEventHandler = (_eventType, _filename) => {
if (connections.length > 0) {
connections.forEach((connection) => connection.socket.send("reload"));
}
};
export default fp(async function (fastify, opts) {
const params = hotReloadWatchOptionsSchema.parse(opts);
if (params.disabled) return;
if (params.paths.length <= 0) return;
await fastify.register(ws);
fastify.get("/_hmr", { websocket: true }, (connection) => {
const id = randomUUID();
connection.socket.on("message", () => {
connections.push({
id,
socket: connection.socket,
});
});
connection.socket.on("close", () => {
connections = connections.filter((conn) => conn.id !== id);
});
});
params.paths.forEach((path) => {
watch(
path,
{
persistent: true,
// recursive: true // not supported everywhere, give all dir paths
},
fileWatchEventHandler
);
});
});