import path from 'path'; import { watch } from "fs"; import { readdir, readFile } from "fs/promises"; import vm from 'vm'; import type {Server} from './Server'; async function hmr_ctrl_l(server: Server, file_p: string) { console.log('loading file ', file_p); const file_d = path.dirname(file_p); const content = await readFile(file_p, 'utf-8'); const script = new vm.Script(content, { filename: file_p, }); const ctx = { __dirname: file_d, exports: exports, require: require, module: module, __filename: file_p, }; vm.createContext(ctx); const ret = script.runInContext(ctx); console.log(ret); // const ctrl = new Ctrl(); // server.c_manager.reload(ctrl); } async function hmr_ctrls_frl(server: Server, dir_p: string) { const files = await readdir(dir_p); server.c_manager.ctrls = {}; await Promise.all(files.map(async (filename) => { const file_p = path.join(dir_p, filename); await hmr_ctrl_l(server, file_p); })); } export function hmr_ctrls(server: Server, dir_p: string) { const watcher = watch(path.resolve(dir_p), async (e, filename) => { if (filename === 'index.js') return; if (path.extname(filename) !== '.js') return; const file_p = path.join(dir_p, filename); if (e === 'change') { await hmr_ctrl_l(server, file_p); } if (e === 'rename') { hmr_ctrls_frl(server, dir_p); } }); process.on('SIGINT', (e) => { watcher.close(); }); process.on('SIGTERM', () => { watcher.close(); }) process.on('exit', () => { watcher.close(); }); }