Files
turbo-sync/lib/watch/files.ts
T
2026-08-10 11:07:39 +01:00

96 lines
3.1 KiB
TypeScript

import fs from "fs";
import delay from "../../utils/delay";
import { SyncFilesFnParams } from "../../types";
import sync from "../../utils/sync";
import SyncScheduler from "../../utils/sync-scheduler";
export default async function watchFiles({
files,
options,
}: SyncFilesFnParams) {
const UPDATE_TIMEOUT = 1000;
try {
const INTERVAL = options?.interval ? options.interval : UPDATE_TIMEOUT;
const scheduler = new SyncScheduler(
(filePath, firstRun) =>
sync({
options,
dirPath: filePath,
dirs: files,
isFiles: true,
firstRun,
}),
INTERVAL
);
for (let i = 0; i < files.length; i++) {
const file = files[i];
const filePath =
typeof file == "string" ? file : file?.path ? file.path : null;
const interval = typeof file == "object" ? file.interval : null;
if (!filePath) continue;
if (typeof file == "string" && !fs.existsSync(filePath)) {
try {
const existingFilePath = files.find((fl) => {
if (typeof fl == "string") return fs.existsSync(fl);
if (!fl.host) return fs.existsSync(fl.path); // TODO handle remote
});
if (!existingFilePath) {
throw new Error("No existing Files for reference");
}
const fileDirPath =
typeof existingFilePath == "string"
? existingFilePath
: existingFilePath.path;
if (!fs.existsSync(fileDirPath)) {
fs.mkdirSync(fileDirPath, { recursive: true });
}
fs.writeFileSync(filePath, "");
} catch (error: any) {
throw new Error(
`File Doesn't exist and couldn't be created. Please check if Directory exists.\nERROR => ${error.message}`
);
}
}
if (typeof file == "string" && !fs.statSync(filePath).isFile()) {
throw new Error(`'${filePath}' is not a File!`);
}
if (typeof file == "object" && file.host) {
// TODO Handle SSH
} else if (typeof file == "string") {
await delay();
fs.watchFile(
filePath,
{
interval: interval || 200,
},
(curr, prev) => {
scheduler.schedule(filePath);
}
);
}
}
const lastUpdatedFile = files[0];
const lastUpdatedFilePath =
typeof lastUpdatedFile == "string"
? lastUpdatedFile
: lastUpdatedFile.path;
scheduler.enqueue(lastUpdatedFilePath, true);
} catch (error: any) {
console.log("ERROR:", error.message);
process.exit(0);
}
}