|
| 1 | +#!/usr/bin/env node |
| 2 | +// Sibling pm2 process: asset-library-watcher |
| 3 | +// Watches source dirs, debounces 5s, rebuilds + restarts asset-library. |
| 4 | +import { watch } from "node:fs"; |
| 5 | +import { execSync } from "node:child_process"; |
| 6 | +import { resolve, dirname } from "node:path"; |
| 7 | +import { fileURLToPath } from "node:url"; |
| 8 | + |
| 9 | +const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 10 | +const ROOT = resolve(__dirname); |
| 11 | + |
| 12 | +const WATCH_DIRS = ["app", "lib", "components", "pages"]; |
| 13 | +const DEBOUNCE_MS = 5000; |
| 14 | + |
| 15 | +const NODE_PATH = `/opt/homebrew/opt/node@20/bin:${process.env.PATH ?? ""}`; |
| 16 | + |
| 17 | +function log(msg) { |
| 18 | + process.stdout.write(`[asset-library-watcher] ${new Date().toISOString()} ${msg}\n`); |
| 19 | +} |
| 20 | + |
| 21 | +let debounceTimer = null; |
| 22 | +let building = false; |
| 23 | + |
| 24 | +function triggerBuild(changedPath) { |
| 25 | + if (debounceTimer) clearTimeout(debounceTimer); |
| 26 | + debounceTimer = setTimeout(() => { |
| 27 | + if (building) { |
| 28 | + log("build in progress — skipping"); |
| 29 | + return; |
| 30 | + } |
| 31 | + building = true; |
| 32 | + log(`change: ${changedPath} — npm run build`); |
| 33 | + try { |
| 34 | + execSync("npm run build", { |
| 35 | + cwd: ROOT, |
| 36 | + stdio: "inherit", |
| 37 | + env: { ...process.env, NODE_ENV: "production", PATH: NODE_PATH }, |
| 38 | + }); |
| 39 | + log("build done — pm2 restart asset-library"); |
| 40 | + execSync("pm2 restart asset-library", { stdio: "inherit" }); |
| 41 | + log("restarted"); |
| 42 | + } catch (err) { |
| 43 | + log(`ERROR: ${err.message}`); |
| 44 | + } finally { |
| 45 | + building = false; |
| 46 | + } |
| 47 | + }, DEBOUNCE_MS); |
| 48 | +} |
| 49 | + |
| 50 | +let watching = 0; |
| 51 | +for (const dir of WATCH_DIRS) { |
| 52 | + const abs = resolve(ROOT, dir); |
| 53 | + try { |
| 54 | + watch(abs, { recursive: true }, (_event, filename) => { |
| 55 | + triggerBuild(`${abs}/${filename ?? "?"}`); |
| 56 | + }); |
| 57 | + log(`watching ${abs}`); |
| 58 | + watching++; |
| 59 | + } catch (err) { |
| 60 | + if (err.code === "ENOENT") { |
| 61 | + log(`skip ${abs} — not found`); |
| 62 | + } else { |
| 63 | + throw err; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +if (watching === 0) { |
| 69 | + log("ERROR: no directories found to watch — exiting"); |
| 70 | + process.exit(1); |
| 71 | +} |
| 72 | + |
| 73 | +log("watcher ready"); |
0 commit comments