'use strict';

var U7VZULNU_cjs = require('./U7VZULNU.cjs');
var esToolkit = require('es-toolkit');
var console = require('console');
var fs = require('fs');
var promises = require('fs/promises');
var os = require('os');
var path = require('path');

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var console__namespace = /*#__PURE__*/_interopNamespace(console);

// src/core/lock.ts
U7VZULNU_cjs.init_cjs_shims();
var directory = path.join(os.homedir(), ".cache/vm-tooling/locks");
var defaultOptions = {
  interval: 1e3,
  timeout: 15 * 6e4
};
var signals = [
  "SIGINT",
  "SIGTERM",
  "SIGHUP"
];
var buildLockFilePath = /* @__PURE__ */ U7VZULNU_cjs.__name((key) => path.join(directory, key), "buildLockFilePath");
var lock = /* @__PURE__ */ U7VZULNU_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__ */ U7VZULNU_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__namespace.log(`\u{1F512} Acquired lock ${info}`);
  try {
    return await run();
  } finally {
    for (const signal of signals) {
      process.removeListener(signal, unlock);
    }
    unlock();
    console__namespace.log(`\u{1F513} Released lock ${info}`);
  }
}, "lock");
var lockMany = /* @__PURE__ */ U7VZULNU_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=6NIOUVPA.cjs.map
//# sourceMappingURL=6NIOUVPA.cjs.map