'use strict';

var VO65XOWD_cjs = require('./VO65XOWD.cjs');
var esToolkit = require('es-toolkit');
var fs = require('fs');
var promises = require('fs/promises');
var os = require('os');
var path = require('path');

// src/core/lock.ts
VO65XOWD_cjs.init_cjs_shims();
var directory = path.join(os.homedir(), ".cache/vm-tooling/locks");
var defaultOptions = {
  interval: 1e3,
  timeout: 3e5
};
var signals = [
  "SIGINT",
  "SIGTERM",
  "SIGHUP"
];
var buildLockFilePath = /* @__PURE__ */ VO65XOWD_cjs.__name((key) => path.join(directory, key), "buildLockFilePath");
var lock = /* @__PURE__ */ VO65XOWD_cjs.__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__ */ VO65XOWD_cjs.__name(() => fs.rmSync(path, {
    force: true
  }), "unlock");
  while (true) {
    let lockError;
    try {
      await promises.mkdir(directory, {
        recursive: true
      });
      await promises.open(path, promises.constants.O_CREAT | promises.constants.O_EXCL);
      break;
    } catch (error) {
      lockError = error;
    }
    if (Date.now() - time > timeout) {
      unlock();
      throw new Error(`Timeout waiting for lock file ${info}: ${lockError.message}`);
    }
    await esToolkit.delay(interval);
  }
  for (const signal of signals) {
    process.addListener(signal, unlock);
  }
  console.log(`Acquired lock ${info}`);
  try {
    return await run();
  } finally {
    for (const signal of signals) {
      process.removeListener(signal, unlock);
    }
    unlock();
    console.log(`Released lock ${info}`);
  }
}, "lock");
var lockMany = /* @__PURE__ */ VO65XOWD_cjs.__name(async (keys, run) => (
  // Sort keys to avoid deadlocks.
  keys.sort().reduce((run2, key) => () => lock(key, run2), run)()
), "lockMany");

exports.buildLockFilePath = buildLockFilePath;
exports.lock = lock;
exports.lockMany = lockMany;
//# sourceMappingURL=NSZHKDNY.cjs.map
//# sourceMappingURL=NSZHKDNY.cjs.map