const require = (await import('node:module')).createRequire(import.meta.url); const __chunk_filename = (await import('node:url')).fileURLToPath(import.meta.url); const __chunk_dirname = (await import('node:path')).dirname(__chunk_filename);
import {
  ExitCodes,
  isTelemetrySdkInitialized,
  resetBrowserSession,
  shutdownTelemetry
} from "./chunk-B6FPEJHK.js";
import {
  Storage
} from "./chunk-UHHRGNIO.js";

// packages/cli/src/utils/cleanup.ts
import { promises as fs } from "node:fs";
import { join } from "node:path";
var cleanupFunctions = [];
var syncCleanupFunctions = [];
var configForTelemetry = null;
var isShuttingDown = false;
function registerCleanup(fn) {
  cleanupFunctions.push(fn);
}
function removeCleanup(fn) {
  const index = cleanupFunctions.indexOf(fn);
  if (index !== -1) {
    cleanupFunctions.splice(index, 1);
  }
}
function registerSyncCleanup(fn) {
  syncCleanupFunctions.push(fn);
}
function removeSyncCleanup(fn) {
  const index = syncCleanupFunctions.indexOf(fn);
  if (index !== -1) {
    syncCleanupFunctions.splice(index, 1);
  }
}
function resetCleanupForTesting() {
  cleanupFunctions.length = 0;
  syncCleanupFunctions.length = 0;
  configForTelemetry = null;
  isShuttingDown = false;
}
function runSyncCleanup() {
  for (const fn of syncCleanupFunctions) {
    try {
      fn();
    } catch {
    }
  }
  syncCleanupFunctions.length = 0;
}
function registerTelemetryConfig(config) {
  configForTelemetry = config;
}
async function runExitCleanup() {
  await drainStdin();
  runSyncCleanup();
  for (const fn of cleanupFunctions) {
    try {
      await fn();
    } catch {
    }
  }
  cleanupFunctions.length = 0;
  try {
    await resetBrowserSession();
  } catch {
  }
  if (configForTelemetry) {
    try {
      await configForTelemetry.dispose();
    } catch {
    }
  }
  if (configForTelemetry && isTelemetrySdkInitialized()) {
    try {
      await shutdownTelemetry(configForTelemetry);
    } catch {
    }
  }
}
async function drainStdin() {
  if (!process.stdin?.isTTY) return;
  process.stdin.resume().removeAllListeners("data").on("data", () => {
  });
  await new Promise((resolve) => setTimeout(resolve, 50));
}
async function gracefulShutdown(_reason) {
  if (isShuttingDown) {
    return;
  }
  isShuttingDown = true;
  await runExitCleanup();
  process.exit(ExitCodes.SUCCESS);
}
function setupSignalHandlers() {
  process.on("SIGHUP", () => gracefulShutdown("SIGHUP"));
  process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
  process.on("SIGINT", () => gracefulShutdown("SIGINT"));
}
function setupTtyCheck() {
  let intervalId = null;
  let isCheckingTty = false;
  intervalId = setInterval(async () => {
    if (isCheckingTty || isShuttingDown) {
      return;
    }
    if (process.env["SANDBOX"]) {
      return;
    }
    if (!process.stdin.isTTY && !process.stdout.isTTY) {
      isCheckingTty = true;
      if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
      }
      await gracefulShutdown("TTY loss");
    }
  }, 5e3);
  intervalId.unref();
  return () => {
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
  };
}
async function cleanupCheckpoints() {
  const storage = new Storage(process.cwd());
  await storage.initialize();
  const tempDir = storage.getProjectTempDir();
  const checkpointsDir = join(tempDir, "checkpoints");
  try {
    await fs.rm(checkpointsDir, { recursive: true, force: true });
  } catch {
  }
}

export {
  registerCleanup,
  removeCleanup,
  registerSyncCleanup,
  removeSyncCleanup,
  resetCleanupForTesting,
  runSyncCleanup,
  registerTelemetryConfig,
  runExitCleanup,
  setupSignalHandlers,
  setupTtyCheck,
  cleanupCheckpoints
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
