import { init_esm_shims, __name } from './6AHA7PAZ.js';
import { delay } from 'es-toolkit';
import * as console from 'console';
import { rmSync } from 'fs';
import { mkdir, open, constants } from 'fs/promises';
import { homedir } from 'os';
import { join } from 'path';

// src/core/lock.ts
init_esm_shims();
var directory = join(homedir(), ".cache/vm-tooling/locks");
var defaultOptions = {
  interval: 1e3,
  timeout: 15 * 6e4
};
var signals = [
  "SIGINT",
  "SIGTERM",
  "SIGHUP"
];
var buildLockFilePath = /* @__PURE__ */ __name((key) => join(directory, key), "buildLockFilePath");
var lock = /* @__PURE__ */ __name(async (key, run, options = {}) => {
  const { interval, timeout } = {
    ...defaultOptions,
    ...options
  };
  const path = buildLockFilePath(key);
  const packageName = process.env.npm_package_name;
  const info = [
    ...packageName ? [
      "for",
      packageName
    ] : [],
    "at",
    path
  ].join(" ");
  const time = Date.now();
  const unlock = /* @__PURE__ */ __name(() => rmSync(path, {
    force: true
  }), "unlock");
  while (true) {
    let lockError;
    try {
      await mkdir(directory, {
        recursive: true
      });
      const handle = await open(path, constants.O_CREAT | constants.O_EXCL);
      await handle.close();
      break;
    } catch (error) {
      lockError = error;
    }
    if (Date.now() - time > timeout) {
      unlock();
      throw new Error(`Timeout waiting for lock file ${info}: ${lockError.message}`);
    }
    await delay(interval);
  }
  for (const signal of signals) {
    process.addListener(signal, unlock);
  }
  console.log(`\u{1F512} Acquired lock ${info}`);
  try {
    return await run();
  } finally {
    for (const signal of signals) {
      process.removeListener(signal, unlock);
    }
    unlock();
    console.log(`\u{1F513} Released lock ${info}`);
  }
}, "lock");
var lockMany = /* @__PURE__ */ __name(async (keys, run) => (
  // Sort keys to avoid deadlocks.
  keys.sort().reduce((run2, key) => () => lock(key, run2), run)()
), "lockMany");

export { buildLockFilePath, lock, lockMany };
//# sourceMappingURL=BAPGOHFS.js.map
//# sourceMappingURL=BAPGOHFS.js.map