this repo has no description
1import { join } from "@std/path/join";
2import { renderPresentationHtml } from "../core/renderer.ts";
3import { serveDir } from "@std/http/file-server";
4
5export async function startDevServer(source: string) {
6 await Promise.all([
7 watchFile(source),
8 Deno.serve(makeHandler(source)),
9 ]);
10}
11
12async function watchFile(path: string) {
13 const channel = openChannel();
14 const watcher = Deno.watchFs(path);
15
16 for await (const _ of watcher) {
17 channel.postMessage("change");
18 }
19}
20
21function openChannel() {
22 return new BroadcastChannel("live-reload");
23}
24
25const LIVE_RELOAD_ROUTE = new URLPattern({ pathname: "/live-reload" });
26const STATIC_ROUTE = new URLPattern({ pathname: "/static/*" });
27
28function makeHandler(path: string) {
29 const channel = openChannel();
30
31 return async (req: Request) => {
32 const liveReloadMatch = LIVE_RELOAD_ROUTE.exec(req.url);
33 const staticMatch = STATIC_ROUTE.exec(req.url);
34
35 if (liveReloadMatch) {
36 const upgrade = req.headers.get("upgrade") ?? "";
37 if (upgrade.toLowerCase() !== "websocket") {
38 return new Response("no upgrade specified");
39 }
40
41 const { socket, response } = Deno.upgradeWebSocket(req);
42
43 channel.onmessage = () => {
44 socket.send("reload");
45 };
46
47 return response;
48 } else if (staticMatch) {
49 console.log(join(Deno.cwd(), "dist"));
50
51 return serveDir(req, {
52 enableCors: true,
53 fsRoot: join(Deno.cwd(), "dist"),
54 urlRoot: "static",
55 });
56 }
57
58 const html = await renderPresentationHtml(path, { devMode: true });
59
60 return new Response(
61 html,
62 {
63 status: 200,
64 headers: {
65 "Content-Type": "text/html",
66 "Cache-Control": "no-store",
67 },
68 },
69 );
70 };
71}