We're having a growing number of packages in this repository. This PR moves them into a `packages/` directory like it's commonly done in other projects.
40 lines
1.0 KiB
TypeScript
40 lines
1.0 KiB
TypeScript
import type { Middleware } from "../../middlewares/mod.ts";
|
|
import { ALIVE_URL } from "../../constants.ts";
|
|
|
|
// Live reload: Send updates to browser
|
|
export function liveReload<T>(): Middleware<T> {
|
|
const revision = Date.now();
|
|
|
|
return (ctx) => {
|
|
const { config, req, url } = ctx;
|
|
|
|
const aliveUrl = config.basePath + ALIVE_URL;
|
|
|
|
if (url.pathname === aliveUrl) {
|
|
if (req.headers.get("upgrade") !== "websocket") {
|
|
return new Response(null, { status: 501 });
|
|
}
|
|
|
|
// TODO: When a change is made the Deno server restarts,
|
|
// so for now the WebSocket connection is only used for
|
|
// the client to know when the server is back up. Once we
|
|
// have HMR we'll actively start sending messages back
|
|
// and forth.
|
|
const { response, socket } = Deno.upgradeWebSocket(req);
|
|
|
|
socket.addEventListener("open", () => {
|
|
socket.send(
|
|
JSON.stringify({
|
|
type: "initial-state",
|
|
revision,
|
|
}),
|
|
);
|
|
});
|
|
|
|
return response;
|
|
}
|
|
|
|
return ctx.next();
|
|
};
|
|
}
|