const { ArrayIsArray: _p_ArrayIsArray, ArrayPrototypeUnshift: _p_ArrayPrototypeUnshift } = require('../../primordials/array.js')
const { BufferConcat: _p_BufferConcat } = require('../../primordials/buffer.js')

const { ErrorCtor: _p_ErrorCtor } = require('../../primordials/error.js')

const { SetCtor: _p_SetCtor } = require('../../primordials/map-set.js')

const { ObjectAssign: _p_ObjectAssign, ObjectDefineProperty: _p_ObjectDefineProperty, ObjectGetOwnPropertyDescriptor: _p_ObjectGetOwnPropertyDescriptor, ObjectKeys: _p_ObjectKeys } = require('../../primordials/object.js')

const { PromiseCtor: _p_PromiseCtor, PromiseReject: _p_PromiseReject } = require('../../primordials/promise.js')

const { RegExpCtor: _p_RegExpCtor } = require('../../primordials/regexp.js')

const { StringPrototypeCharAt: _p_StringPrototypeCharAt, StringPrototypeEndsWith: _p_StringPrototypeEndsWith, StringPrototypeSubstring: _p_StringPrototypeSubstring } = require('../../primordials/string.js')

"use strict";
/**
 * Bundled from @npmcli/promise-spawn
 * This is a zero-dependency bundle created by esbuild.
 */
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// node_modules/.pnpm/isexe@3.1.1/node_modules/isexe/dist/cjs/posix.js
var require_posix = __commonJS({
  "node_modules/.pnpm/isexe@3.1.1/node_modules/isexe/dist/cjs/posix.js"(exports2) {
    "use strict";
    _p_ObjectDefineProperty(exports2, "__esModule", { value: true });
    exports2.sync = exports2.isexe = void 0;
    var fs_1 = require("fs");
    var promises_1 = require("fs/promises");
    var isexe = /* @__PURE__ */ __name(async (path, options = {}) => {
      const { ignoreErrors = false } = options;
      try {
        return checkStat(await (0, promises_1.stat)(path), options);
      } catch (e) {
        const er = e;
        if (ignoreErrors || er.code === "EACCES")
          return false;
        throw er;
      }
    }, "isexe");
    exports2.isexe = isexe;
    var sync = /* @__PURE__ */ __name((path, options = {}) => {
      const { ignoreErrors = false } = options;
      try {
        return checkStat((0, fs_1.statSync)(path), options);
      } catch (e) {
        const er = e;
        if (ignoreErrors || er.code === "EACCES")
          return false;
        throw er;
      }
    }, "sync");
    exports2.sync = sync;
    var checkStat = /* @__PURE__ */ __name((stat, options) => stat.isFile() && checkMode(stat, options), "checkStat");
    var checkMode = /* @__PURE__ */ __name((stat, options) => {
      const myUid = options.uid ?? process.getuid?.();
      const myGroups = options.groups ?? process.getgroups?.() ?? [];
      const myGid = options.gid ?? process.getgid?.() ?? myGroups[0];
      if (myUid === void 0 || myGid === void 0) {
        throw new _p_ErrorCtor("cannot get uid or gid");
      }
      const groups = /* @__PURE__ */ new _p_SetCtor([myGid, ...myGroups]);
      const mod = stat.mode;
      const uid = stat.uid;
      const gid = stat.gid;
      const u = parseInt("100", 8);
      const g = parseInt("010", 8);
      const o = parseInt("001", 8);
      const ug = u | g;
      return !!(mod & o || mod & g && groups.has(gid) || mod & u && uid === myUid || mod & ug && myUid === 0);
    }, "checkMode");
  }
});

// node_modules/.pnpm/isexe@3.1.1/node_modules/isexe/dist/cjs/win32.js
var require_win32 = __commonJS({
  "node_modules/.pnpm/isexe@3.1.1/node_modules/isexe/dist/cjs/win32.js"(exports2) {
    "use strict";
    _p_ObjectDefineProperty(exports2, "__esModule", { value: true });
    exports2.sync = exports2.isexe = void 0;
    var fs_1 = require("fs");
    var promises_1 = require("fs/promises");
    var isexe = /* @__PURE__ */ __name(async (path, options = {}) => {
      const { ignoreErrors = false } = options;
      try {
        return checkStat(await (0, promises_1.stat)(path), path, options);
      } catch (e) {
        const er = e;
        if (ignoreErrors || er.code === "EACCES")
          return false;
        throw er;
      }
    }, "isexe");
    exports2.isexe = isexe;
    var sync = /* @__PURE__ */ __name((path, options = {}) => {
      const { ignoreErrors = false } = options;
      try {
        return checkStat((0, fs_1.statSync)(path), path, options);
      } catch (e) {
        const er = e;
        if (ignoreErrors || er.code === "EACCES")
          return false;
        throw er;
      }
    }, "sync");
    exports2.sync = sync;
    var checkPathExt = /* @__PURE__ */ __name((path, options) => {
      const { pathExt = process.env.PATHEXT || "" } = options;
      const peSplit = pathExt.split(";");
      if (peSplit.indexOf("") !== -1) {
        return true;
      }
      for (let i = 0; i < peSplit.length; i++) {
        const p = peSplit[i].toLowerCase();
        const ext = _p_StringPrototypeSubstring(path, path.length - p.length).toLowerCase();
        if (p && ext === p) {
          return true;
        }
      }
      return false;
    }, "checkPathExt");
    var checkStat = /* @__PURE__ */ __name((stat, path, options) => stat.isFile() && checkPathExt(path, options), "checkStat");
  }
});

// node_modules/.pnpm/isexe@3.1.1/node_modules/isexe/dist/cjs/options.js
var require_options = __commonJS({
  "node_modules/.pnpm/isexe@3.1.1/node_modules/isexe/dist/cjs/options.js"(exports2) {
    "use strict";
    _p_ObjectDefineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/.pnpm/isexe@3.1.1/node_modules/isexe/dist/cjs/index.js
var require_cjs = __commonJS({
  "node_modules/.pnpm/isexe@3.1.1/node_modules/isexe/dist/cjs/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = _p_ObjectGetOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      _p_ObjectDefineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      _p_ObjectDefineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    _p_ObjectDefineProperty(exports2, "__esModule", { value: true });
    exports2.sync = exports2.isexe = exports2.posix = exports2.win32 = void 0;
    var posix = __importStar(require_posix());
    exports2.posix = posix;
    var win32 = __importStar(require_win32());
    exports2.win32 = win32;
    __exportStar(require_options(), exports2);
    var platform = process.env._ISEXE_TEST_PLATFORM_ || process.platform;
    var impl = platform === "win32" ? win32 : posix;
    exports2.isexe = impl.isexe;
    exports2.sync = impl.sync;
  }
});

// node_modules/.pnpm/which@5.0.0/node_modules/which/lib/index.js
var require_lib = __commonJS({
  "node_modules/.pnpm/which@5.0.0/node_modules/which/lib/index.js"(exports2, module2) {
    var { isexe, sync: isexeSync } = require_cjs();
    var { join, delimiter, sep, posix } = require("path");
    var isWindows = process.platform === "win32";
    var rSlash = new _p_RegExpCtor(`[${posix.sep}${sep === posix.sep ? "" : sep}]`.replace(/(\\)/g, "\\$1"));
    var rRel = new _p_RegExpCtor(`^\\.${rSlash.source}`);
    var getNotFoundError = /* @__PURE__ */ __name((cmd) => _p_ObjectAssign(new _p_ErrorCtor(`not found: ${cmd}`), { code: "ENOENT" }), "getNotFoundError");
    var getPathInfo = /* @__PURE__ */ __name((cmd, {
      path: optPath = process.env.PATH,
      pathExt: optPathExt = process.env.PATHEXT,
      delimiter: optDelimiter = delimiter
    }) => {
      const pathEnv = cmd.match(rSlash) ? [""] : [
        // windows always checks the cwd first
        ...isWindows ? [process.cwd()] : [],
        ...(optPath || /* istanbul ignore next: very unusual */
        "").split(optDelimiter)
      ];
      if (isWindows) {
        const pathExtExe = optPathExt || [".EXE", ".CMD", ".BAT", ".COM"].join(optDelimiter);
        const pathExt = pathExtExe.split(optDelimiter).flatMap((item) => [item, item.toLowerCase()]);
        if (cmd.includes(".") && pathExt[0] !== "") {
          _p_ArrayPrototypeUnshift(pathExt, "");
        }
        return { pathEnv, pathExt, pathExtExe };
      }
      return { pathEnv, pathExt: [""] };
    }, "getPathInfo");
    var getPathPart = /* @__PURE__ */ __name((raw, cmd) => {
      const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
      const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
      return prefix + join(pathPart, cmd);
    }, "getPathPart");
    var which = /* @__PURE__ */ __name(async (cmd, opt = {}) => {
      const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
      const found = [];
      for (const envPart of pathEnv) {
        const p = getPathPart(envPart, cmd);
        for (const ext of pathExt) {
          const withExt = p + ext;
          const is = await isexe(withExt, { pathExt: pathExtExe, ignoreErrors: true });
          if (is) {
            if (!opt.all) {
              return withExt;
            }
            found.push(withExt);
          }
        }
      }
      if (opt.all && found.length) {
        return found;
      }
      if (opt.nothrow) {
        return null;
      }
      throw getNotFoundError(cmd);
    }, "which");
    var whichSync = /* @__PURE__ */ __name((cmd, opt = {}) => {
      const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
      const found = [];
      for (const pathEnvPart of pathEnv) {
        const p = getPathPart(pathEnvPart, cmd);
        for (const ext of pathExt) {
          const withExt = p + ext;
          const is = isexeSync(withExt, { pathExt: pathExtExe, ignoreErrors: true });
          if (is) {
            if (!opt.all) {
              return withExt;
            }
            found.push(withExt);
          }
        }
      }
      if (opt.all && found.length) {
        return found;
      }
      if (opt.nothrow) {
        return null;
      }
      throw getNotFoundError(cmd);
    }, "whichSync");
    module2.exports = which;
    which.sync = whichSync;
  }
});

// node_modules/.pnpm/@npmcli+promise-spawn@9.0.1/node_modules/@npmcli/promise-spawn/lib/escape.js
var require_escape = __commonJS({
  "node_modules/.pnpm/@npmcli+promise-spawn@9.0.1/node_modules/@npmcli/promise-spawn/lib/escape.js"(exports2, module2) {
    "use strict";
    var cmd = /* @__PURE__ */ __name((input, doubleEscape) => {
      if (!input.length) {
        return '""';
      }
      let result;
      if (!/[ \t\n\v"]/.test(input)) {
        result = input;
      } else {
        result = '"';
        for (let i = 0; i <= input.length; ++i) {
          let slashCount = 0;
          while (input[i] === "\\") {
            ++i;
            ++slashCount;
          }
          if (i === input.length) {
            result += "\\".repeat(slashCount * 2);
            break;
          }
          if (input[i] === '"') {
            result += "\\".repeat(slashCount * 2 + 1);
            result += input[i];
          } else {
            result += "\\".repeat(slashCount);
            result += input[i];
          }
        }
        result += '"';
      }
      result = result.replace(/[ !%^&()<>|"]/g, "^$&");
      if (doubleEscape) {
        result = result.replace(/[ !%^&()<>|"]/g, "^$&");
      }
      return result;
    }, "cmd");
    var sh = /* @__PURE__ */ __name((input) => {
      if (!input.length) {
        return `''`;
      }
      if (!/[\t\n\r "#$&'()*;<>?\\`|~]/.test(input)) {
        return input;
      }
      const result = `'${input.replace(/'/g, `'\\''`)}'`.replace(/^(?:'')+(?!$)/, "").replace(/\\'''/g, `\\'`);
      return result;
    }, "sh");
    module2.exports = {
      cmd,
      sh
    };
  }
});

// node_modules/.pnpm/@npmcli+promise-spawn@9.0.1/node_modules/@npmcli/promise-spawn/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/.pnpm/@npmcli+promise-spawn@9.0.1/node_modules/@npmcli/promise-spawn/lib/index.js"(exports2, module2) {
    "use strict";
    var { spawn } = require("child_process");
    var os = require("os");
    var which = require_lib();
    var escape = require_escape();
    var promiseSpawn = /* @__PURE__ */ __name((cmd, args, opts = {}, extra = {}) => {
      if (opts.shell) {
        return spawnWithShell(cmd, args, opts, extra);
      }
      let resolve, reject;
      const promise = new _p_PromiseCtor((_resolve, _reject) => {
        resolve = _resolve;
        reject = _reject;
      });
      const closeError = new _p_ErrorCtor("command failed");
      const stdout = [];
      const stderr = [];
      const getResult = /* @__PURE__ */ __name((result) => ({
        cmd,
        args,
        ...result,
        ...stdioResult(stdout, stderr, opts),
        ...extra
      }), "getResult");
      const rejectWithOpts = /* @__PURE__ */ __name((er, erOpts) => {
        const resultError = getResult(erOpts);
        reject(_p_ObjectAssign(er, resultError));
      }, "rejectWithOpts");
      const proc = spawn(cmd, args, opts);
      promise.stdin = proc.stdin;
      promise.process = proc;
      proc.on("error", rejectWithOpts);
      if (proc.stdout) {
        proc.stdout.on("data", (c) => stdout.push(c));
        proc.stdout.on("error", rejectWithOpts);
      }
      if (proc.stderr) {
        proc.stderr.on("data", (c) => stderr.push(c));
        proc.stderr.on("error", rejectWithOpts);
      }
      proc.on("close", (code, signal) => {
        if (code || signal) {
          rejectWithOpts(closeError, { code, signal });
        } else {
          resolve(getResult({ code, signal }));
        }
      });
      return promise;
    }, "promiseSpawn");
    var spawnWithShell = /* @__PURE__ */ __name((cmd, args, opts, extra) => {
      let command = opts.shell;
      if (command === true) {
        command = process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "sh";
      }
      const options = { ...opts, shell: false };
      const realArgs = [];
      let script = cmd;
      const isCmd = /(?:^|\\)cmd(?:\.exe)?$/i.test(command);
      if (isCmd) {
        let doubleEscape = false;
        let initialCmd = "";
        let insideQuotes = false;
        for (let i = 0; i < cmd.length; ++i) {
          const char = _p_StringPrototypeCharAt(cmd, i);
          if (char === " " && !insideQuotes) {
            break;
          }
          initialCmd += char;
          if (char === '"' || char === "'") {
            insideQuotes = !insideQuotes;
          }
        }
        let pathToInitial;
        try {
          pathToInitial = which.sync(initialCmd, {
            path: options.env && findInObject(options.env, "PATH") || process.env.PATH,
            pathext: options.env && findInObject(options.env, "PATHEXT") || process.env.PATHEXT
          }).toLowerCase();
        } catch (err) {
          pathToInitial = initialCmd.toLowerCase();
        }
        doubleEscape = _p_StringPrototypeEndsWith(pathToInitial, ".cmd") || _p_StringPrototypeEndsWith(pathToInitial, ".bat");
        for (const arg of args) {
          script += ` ${escape.cmd(arg, doubleEscape)}`;
        }
        realArgs.push("/d", "/s", "/c", script);
        options.windowsVerbatimArguments = true;
      } else {
        for (const arg of args) {
          script += ` ${escape.sh(arg)}`;
        }
        realArgs.push("-c", script);
      }
      return promiseSpawn(command, realArgs, options, extra);
    }, "spawnWithShell");
    var open = /* @__PURE__ */ __name((_args, opts = {}, extra = {}) => {
      const options = { ...opts, shell: true };
      const args = [].concat(_args);
      let platform = process.platform;
      if (platform === "linux" && os.release().toLowerCase().includes("microsoft")) {
        platform = "wsl";
        if (!process.env.BROWSER) {
          return _p_PromiseReject(
            new _p_ErrorCtor("Set the BROWSER environment variable to your desired browser.")
          );
        }
      }
      let command = options.command;
      if (!command) {
        if (platform === "win32") {
          options.shell = process.env.ComSpec;
          command = 'start ""';
        } else if (platform === "wsl") {
          command = "sensible-browser";
        } else if (platform === "darwin") {
          command = "open";
        } else {
          command = "xdg-open";
        }
      }
      return spawnWithShell(command, args, options, extra);
    }, "open");
    promiseSpawn.open = open;
    var isPipe = /* @__PURE__ */ __name((stdio = "pipe", fd) => {
      if (stdio === "pipe" || stdio === null) {
        return true;
      }
      if (_p_ArrayIsArray(stdio)) {
        return isPipe(stdio[fd], fd);
      }
      return false;
    }, "isPipe");
    var stdioResult = /* @__PURE__ */ __name((stdout, stderr, { stdioString = true, stdio }) => {
      const result = {
        stdout: null,
        stderr: null
      };
      if (isPipe(stdio, 1)) {
        result.stdout = _p_BufferConcat(stdout);
        if (stdioString) {
          result.stdout = result.stdout.toString().trim();
        }
      }
      if (isPipe(stdio, 2)) {
        result.stderr = _p_BufferConcat(stderr);
        if (stdioString) {
          result.stderr = result.stderr.toString().trim();
        }
      }
      return result;
    }, "stdioResult");
    var findInObject = /* @__PURE__ */ __name((obj, key) => {
      key = key.toLowerCase();
      for (const objKey of _p_ObjectKeys(obj).sort()) {
        if (objKey.toLowerCase() === key) {
          return obj[objKey];
        }
      }
    }, "findInObject");
    module2.exports = promiseSpawn;
  }
});

// src/external/@npmcli/promise-spawn.js
module.exports = require_lib2();
