import path from"node:path";import fs from"node:fs";import*as chokidar from"chokidar";import Files from"../files/files.mjs";export default class HotReload{static#a=new Map;static async watchForHotReload(a,t){if(await HotReload.stopWatching(),global.config.options.hotReload){global.express.debug&&await HotReload.#t({id:"core"}),a.system.flags.hotReload&&await HotReload.#t(a.system);for(const o of a.modules.filter((a=>a.flags.hotReload&&t[a.id])))await HotReload.#t(o)}}static async stopWatching(){for(let a of HotReload.#a.values())await a.close();HotReload.#a.clear()}static async#t(a){const t=new Set([".js",".mjs",".css",".html",".hbs",".json"]);let o="core"===a.id?t:new Set(a.flags.hotReload.extensions);if(o=new Set([...o].map((a=>a.startsWith(".")?a:`.${a}`))),!o.size)return void console.warn(`Hot Reload disabled for "${a.id}" because it has no extensions defined.`);const e="core"===a.id?global.paths.public:a.path;let s=[];if("core"!==a.id&&a.flags.hotReload.paths)for(const t of a.flags.hotReload.paths){const o=Files.standardizePath(path.join(e,t));Files.isPathContained(o,e)?s.push(o):console.warn(`Hot Reload skipped for "${a.id}" path "${o}" because it is not contained within the package directory.`)}0===s.length&&(s=[e]);const i=chokidar.watch(s);console.log(`Watching for changes to ${a.id} in ${s.join(", ")}`),i.on("change",(async t=>{const e=path.extname(t);if(!o.has(e))return;const s=fs.readFileSync(t,{encoding:"utf8"}),i=t.replace(path.normalize(global.paths.data),"").replace(path.normalize(global.paths.public),""),n=Files.standardizePath(i),l={packageType:a.type,packageId:a.id,content:s,path:n.startsWith("/")?n.slice(1):n,extension:e.replace(".","")};express.io.emit("hotReload",l)})),HotReload.#a.set(a.id,i)}}