UNPKG

@netronk/mdx-remote

Version:

The remote MDX files adapter for Netronk Gen

80 lines (77 loc) 1.86 kB
// src/github/dev/server.ts import { WebSocketServer } from "ws"; // src/github/dev/watcher.ts import path from "path"; import { watch as watchFn } from "chokidar"; function watch(options) { const { cwd = process.cwd(), files } = options; const watcher = watchFn(files, { cwd }); let ready = false; watcher.once("ready", () => { ready = true; }); watcher.on("all", (eventName, relativePath) => { if (!ready) return; const absolutePath = path.resolve(cwd, relativePath); if (eventName === "add") { options.onChange({ type: "add", path: absolutePath }); } if (eventName === "unlink") { options.onChange({ type: "delete", path: absolutePath }); } if (eventName === "change") { options.onChange({ type: "update", path: absolutePath }); } }); return watcher; } // src/github/dev/server.ts function createServer({ files, port = 3001 }) { process.env.NODE_ENV ??= "development"; if (process.env.NODE_ENV !== "development") { console.warn( `'createServer()' is being invoked on ${process.env.NODE_ENV} mode, it should be only used on development mode.` ); } const wss = new WebSocketServer({ port }); wss.on("listening", () => { console.log(`Development Server listening on port ${port.toString()}`); }); const watcher = watch({ files, onChange(message) { wss.clients.forEach((c) => { c.send(JSON.stringify(message)); }); } }); process.on("SIGINT", () => { wss.close(); void watcher.close(); }); process.on("beforeExit", () => { wss.close(); void watcher.close(); }); } var created = false; function initServer(options) { if (created) return; createServer(options); created = true; } export { createServer, initServer };