const require_rolldown_runtime = require('../../../../_virtual/rolldown_runtime.cjs');
const require_package = require('../core/package.cjs');
let node_path = require("node:path");
let node_fs_promises = require("node:fs/promises");

//#region ../chokidar/dist/esm/utils/runOnce.mjs
const DEFAULT_RUN_ONCE_OPTIONS = { cacheTimeoutMs: 60 * 1e3 };
/**
* Ensures a callback function runs only once within a specified time window across multiple processes.
* Uses a sentinel file to coordinate execution and prevent duplicate work.
*
* @param sentinelFilePath - Path to the sentinel file used for coordination
* @param callback - The function to execute (should be async)
* @param options - The options for the runOnce function
*
* @example
* ```typescript
* await runPrepareIntlayerOnce(
*   '/tmp/intlayer-sentinel',
*   async () => {
*     // Your initialization logic here
*     await prepareIntlayer();
*   },
*   30 * 1000 // 30 seconds cache
* );
* ```
*
* @throws {Error} When there are unexpected filesystem errors
*/
const runOnce = async (sentinelFilePath, callback, options) => {
	const { onIsCached, cacheTimeoutMs, forceRun } = {
		...DEFAULT_RUN_ONCE_OPTIONS,
		...options ?? {}
	};
	const currentTimestamp = Date.now();
	try {
		const sentinelAge = currentTimestamp - (await (0, node_fs_promises.stat)(sentinelFilePath)).mtime.getTime();
		let shouldRebuild = Boolean(forceRun) || sentinelAge > cacheTimeoutMs;
		if (!shouldRebuild) try {
			const raw = await (0, node_fs_promises.readFile)(sentinelFilePath, "utf8");
			let cachedVersion;
			try {
				cachedVersion = JSON.parse(raw).version;
			} catch {
				cachedVersion = void 0;
			}
			if (!cachedVersion || cachedVersion !== require_package.version) shouldRebuild = true;
		} catch {
			shouldRebuild = true;
		}
		if (shouldRebuild) try {
			await (0, node_fs_promises.unlink)(sentinelFilePath);
		} catch (err) {
			if (err.code !== "ENOENT") throw err;
		}
		else {
			await onIsCached?.();
			return;
		}
	} catch (err) {
		if (err.code === "ENOENT") {} else throw err;
	}
	try {
		await (0, node_fs_promises.mkdir)((0, node_path.dirname)(sentinelFilePath), { recursive: true });
		const data = {
			version: require_package.version,
			timestamp: currentTimestamp
		};
		await (0, node_fs_promises.writeFile)(sentinelFilePath, JSON.stringify(data), { flag: "wx" });
	} catch (err) {
		if (err.code === "EEXIST") return;
		throw err;
	}
	await callback();
};

//#endregion
exports.runOnce = runOnce;
//# sourceMappingURL=runOnce.cjs.map