@redwoodjs/sdk
Version:
Build fast, server-driven webapps on Cloudflare with SSR, RSC, and realtime
81 lines (80 loc) • 3.64 kB
JavaScript
import path from "path";
import { pathExists, remove } from "fs-extra";
import { $ } from "../lib/$.mjs";
export function rwSdkDebugWatcher({ projectRootDir, rwSdkSrc, }) {
const sdkSrcDir = path.resolve(rwSdkSrc, "src");
const sdkDistDir = path.resolve(rwSdkSrc, "dist");
const viteCacheDir = path.resolve(projectRootDir, "node_modules/.vite");
const debounceMs = 200;
let buildTimeout = null;
let restartTimeout = null;
let buildInProgress = false;
return {
name: "rw-sdk-debug-watcher",
async configureServer(server) {
console.log(">>> rw-sdk-debug enabled");
const watcher = server.watcher;
// === Watch RWSDK_SRC/src → debounced build
watcher.add(sdkSrcDir);
watcher.on("change", (filePath) => {
if (!filePath.startsWith(sdkSrcDir))
return;
if (buildTimeout)
clearTimeout(buildTimeout);
buildTimeout = setTimeout(async () => {
if (buildInProgress)
return;
buildInProgress = true;
console.log(`[rw-sdk-debug] building due to: ${filePath}`);
try {
await $({ cwd: rwSdkSrc }) `pnpm build:src`;
await $({ cwd: rwSdkSrc }) `pnpm build:vendor`;
}
catch (err) {
console.error("[rw-sdk-debug] build failed:", err);
}
finally {
buildInProgress = false;
}
}, debounceMs);
});
// === Watch RWSDK_SRC/dist → clear cache + restart + kill port 9229
watcher.add(sdkDistDir);
watcher.on("all", (_event, filePath) => {
if (!filePath.startsWith(sdkDistDir))
return;
if (filePath.endsWith(".d.ts")) {
console.log(`[rw-sdk-debug] ignoring .d.ts change: ${filePath}`);
return;
}
if (restartTimeout)
clearTimeout(restartTimeout);
restartTimeout = setTimeout(async () => {
console.log(`[rw-sdk-debug] dist changed: ${filePath}`);
try {
const exists = await pathExists(viteCacheDir);
if (exists) {
console.log("[rw-sdk-debug] clearing .vite cache...");
await remove(viteCacheDir);
}
console.log("[rw-sdk-debug] killing inspector port 9229...");
const { stdout = "" } = await $ `lsof -ti :9229`;
const pids = stdout
.split("\n")
.map((s) => s.trim())
.filter((pid) => pid && pid !== String(process.pid));
if (pids.length) {
console.log(`[rw-sdk-debug] killing rogue processes on :9229 → ${pids.join(", ")}`);
await $ `kill -9 ${pids.join(" ")}`;
}
console.log("[rw-sdk-debug] restarting dev server...");
server.restart();
}
catch (err) {
console.warn("[rw-sdk-debug] failed during restart sequence:", err);
}
}, debounceMs);
});
},
};
}