|
| 1 | +import path from 'path'; |
| 2 | +import {watch} from 'node:fs/promises'; |
| 3 | +import {WebSocketServer} from 'ws'; |
| 4 | + |
| 5 | +const watchedContent = new Set(['.mdx', '.md', '.png', '.jpg', '.jpeg', '.gif', '.svg']); |
| 6 | + |
| 7 | +export const throttle = (fn, delay) => { |
| 8 | + let last = 0; |
| 9 | + return (...args) => { |
| 10 | + const now = Date.now(); |
| 11 | + if (now - last < delay) { |
| 12 | + return; |
| 13 | + } |
| 14 | + last = now; |
| 15 | + return fn(...args); |
| 16 | + }; |
| 17 | +}; |
| 18 | + |
| 19 | +const wss = new WebSocketServer({port: 8080}); |
| 20 | +console.info('⚡️ Hot reload watcher listening on ws://localhost:8080'); |
| 21 | + |
| 22 | +wss.on('connection', async function onConnect(ws) { |
| 23 | + ws.on('error', err => { |
| 24 | + console.log('ws error', err); |
| 25 | + }); |
| 26 | + ws.on('message', function incoming(_msg) { |
| 27 | + // no reason for the client to send messages for now |
| 28 | + }); |
| 29 | + |
| 30 | + const ac = new AbortController(); |
| 31 | + const {signal} = ac; |
| 32 | + ws.on('close', () => ac.abort()); |
| 33 | + |
| 34 | + // avoid fileystem chatter when you save a file |
| 35 | + const sendReload = throttle(() => ws.send('reload'), 10); |
| 36 | + |
| 37 | + try { |
| 38 | + const watcher = watch(path.join(import.meta.dirname, '..', 'docs'), { |
| 39 | + signal, |
| 40 | + recursive: true, |
| 41 | + }); |
| 42 | + for await (const event of watcher) { |
| 43 | + if (watchedContent.has(path.extname(event.filename))) { |
| 44 | + sendReload(); |
| 45 | + } |
| 46 | + } |
| 47 | + } catch (err) { |
| 48 | + if (err.name === 'AbortError') { |
| 49 | + return; |
| 50 | + } |
| 51 | + throw err; |
| 52 | + } |
| 53 | +}); |
0 commit comments