//#region src/heartbeat/wake.ts
const DEFAULT_COALESCE_MS = 250;
const RETRY_MS = 1e3;
/**
* Coalesces wake requests within coalesceMs and serializes handler execution.
*/
function createHeartbeatWake(handler) {
	let running = false;
	let timer;
	let pendingReasons = [];
	function schedule(delayMs) {
		if (timer) clearTimeout(timer);
		timer = setTimeout(async () => {
			timer = void 0;
			if (running) {
				schedule(RETRY_MS);
				return;
			}
			running = true;
			const reasons = [...pendingReasons];
			pendingReasons = [];
			try {
				await handler(reasons);
			} finally {
				running = false;
				if (pendingReasons.length > 0) schedule(DEFAULT_COALESCE_MS);
			}
		}, delayMs);
		timer.unref?.();
	}
	return {
		request(opts) {
			pendingReasons.push(opts?.reason ?? "interval");
			schedule(opts?.coalesceMs ?? DEFAULT_COALESCE_MS);
		},
		stop() {
			if (timer) {
				clearTimeout(timer);
				timer = void 0;
			}
			pendingReasons = [];
		}
	};
}
//#endregion
export { createHeartbeatWake };

//# sourceMappingURL=wake.js.map