"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// ../../node_modules/.pnpm/nice-try@1.0.5/node_modules/nice-try/src/index.js
var require_src = __commonJS({
  "../../node_modules/.pnpm/nice-try@1.0.5/node_modules/nice-try/src/index.js"(exports, module2) {
    "use strict";
    module2.exports = function(fn) {
      try {
        return fn();
      } catch (e) {
      }
    };
  }
});

// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
var require_windows = __commonJS({
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module2) {
    module2.exports = isexe;
    isexe.sync = sync;
    var fs5 = require("fs");
    function checkPathExt(path, options) {
      var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
      if (!pathext) {
        return true;
      }
      pathext = pathext.split(";");
      if (pathext.indexOf("") !== -1) {
        return true;
      }
      for (var i = 0; i < pathext.length; i++) {
        var p = pathext[i].toLowerCase();
        if (p && path.substr(-p.length).toLowerCase() === p) {
          return true;
        }
      }
      return false;
    }
    function checkStat(stat, path, options) {
      if (!stat.isSymbolicLink() && !stat.isFile()) {
        return false;
      }
      return checkPathExt(path, options);
    }
    function isexe(path, options, cb) {
      fs5.stat(path, function(er, stat) {
        cb(er, er ? false : checkStat(stat, path, options));
      });
    }
    function sync(path, options) {
      return checkStat(fs5.statSync(path), path, options);
    }
  }
});

// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
var require_mode = __commonJS({
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module2) {
    module2.exports = isexe;
    isexe.sync = sync;
    var fs5 = require("fs");
    function isexe(path, options, cb) {
      fs5.stat(path, function(er, stat) {
        cb(er, er ? false : checkStat(stat, options));
      });
    }
    function sync(path, options) {
      return checkStat(fs5.statSync(path), options);
    }
    function checkStat(stat, options) {
      return stat.isFile() && checkMode(stat, options);
    }
    function checkMode(stat, options) {
      var mod = stat.mode;
      var uid = stat.uid;
      var gid = stat.gid;
      var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
      var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
      var u = parseInt("100", 8);
      var g = parseInt("010", 8);
      var o = parseInt("001", 8);
      var ug = u | g;
      var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
      return ret;
    }
  }
});

// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
var require_isexe = __commonJS({
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module2) {
    var fs5 = require("fs");
    var core;
    if (process.platform === "win32" || global.TESTING_WINDOWS) {
      core = require_windows();
    } else {
      core = require_mode();
    }
    module2.exports = isexe;
    isexe.sync = sync;
    function isexe(path, options, cb) {
      if (typeof options === "function") {
        cb = options;
        options = {};
      }
      if (!cb) {
        if (typeof Promise !== "function") {
          throw new TypeError("callback not provided");
        }
        return new Promise(function(resolve2, reject) {
          isexe(path, options || {}, function(er, is) {
            if (er) {
              reject(er);
            } else {
              resolve2(is);
            }
          });
        });
      }
      core(path, options || {}, function(er, is) {
        if (er) {
          if (er.code === "EACCES" || options && options.ignoreErrors) {
            er = null;
            is = false;
          }
        }
        cb(er, is);
      });
    }
    function sync(path, options) {
      try {
        return core.sync(path, options || {});
      } catch (er) {
        if (options && options.ignoreErrors || er.code === "EACCES") {
          return false;
        } else {
          throw er;
        }
      }
    }
  }
});

// ../../node_modules/.pnpm/which@1.3.1/node_modules/which/which.js
var require_which = __commonJS({
  "../../node_modules/.pnpm/which@1.3.1/node_modules/which/which.js"(exports, module2) {
    module2.exports = which2;
    which2.sync = whichSync;
    var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
    var path = require("path");
    var COLON = isWindows ? ";" : ":";
    var isexe = require_isexe();
    function getNotFoundError(cmd) {
      var er = new Error("not found: " + cmd);
      er.code = "ENOENT";
      return er;
    }
    function getPathInfo(cmd, opt) {
      var colon = opt.colon || COLON;
      var pathEnv = opt.path || process.env.PATH || "";
      var pathExt = [""];
      pathEnv = pathEnv.split(colon);
      var pathExtExe = "";
      if (isWindows) {
        pathEnv.unshift(process.cwd());
        pathExtExe = opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM";
        pathExt = pathExtExe.split(colon);
        if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
          pathExt.unshift("");
      }
      if (cmd.match(/\//) || isWindows && cmd.match(/\\/))
        pathEnv = [""];
      return {
        env: pathEnv,
        ext: pathExt,
        extExe: pathExtExe
      };
    }
    function which2(cmd, opt, cb) {
      if (typeof opt === "function") {
        cb = opt;
        opt = {};
      }
      var info = getPathInfo(cmd, opt);
      var pathEnv = info.env;
      var pathExt = info.ext;
      var pathExtExe = info.extExe;
      var found = [];
      (function F(i, l) {
        if (i === l) {
          if (opt.all && found.length)
            return cb(null, found);
          else
            return cb(getNotFoundError(cmd));
        }
        var pathPart = pathEnv[i];
        if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"')
          pathPart = pathPart.slice(1, -1);
        var p = path.join(pathPart, cmd);
        if (!pathPart && /^\.[\\\/]/.test(cmd)) {
          p = cmd.slice(0, 2) + p;
        }
        ;
        (function E(ii, ll) {
          if (ii === ll)
            return F(i + 1, l);
          var ext = pathExt[ii];
          isexe(p + ext, { pathExt: pathExtExe }, function(er, is) {
            if (!er && is) {
              if (opt.all)
                found.push(p + ext);
              else
                return cb(null, p + ext);
            }
            return E(ii + 1, ll);
          });
        })(0, pathExt.length);
      })(0, pathEnv.length);
    }
    function whichSync(cmd, opt) {
      opt = opt || {};
      var info = getPathInfo(cmd, opt);
      var pathEnv = info.env;
      var pathExt = info.ext;
      var pathExtExe = info.extExe;
      var found = [];
      for (var i = 0, l = pathEnv.length; i < l; i++) {
        var pathPart = pathEnv[i];
        if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"')
          pathPart = pathPart.slice(1, -1);
        var p = path.join(pathPart, cmd);
        if (!pathPart && /^\.[\\\/]/.test(cmd)) {
          p = cmd.slice(0, 2) + p;
        }
        for (var j = 0, ll = pathExt.length; j < ll; j++) {
          var cur = p + pathExt[j];
          var is;
          try {
            is = isexe.sync(cur, { pathExt: pathExtExe });
            if (is) {
              if (opt.all)
                found.push(cur);
              else
                return cur;
            }
          } catch (ex) {
          }
        }
      }
      if (opt.all && found.length)
        return found;
      if (opt.nothrow)
        return null;
      throw getNotFoundError(cmd);
    }
  }
});

// ../../node_modules/.pnpm/path-key@2.0.1/node_modules/path-key/index.js
var require_path_key = __commonJS({
  "../../node_modules/.pnpm/path-key@2.0.1/node_modules/path-key/index.js"(exports, module2) {
    "use strict";
    module2.exports = (opts) => {
      opts = opts || {};
      const env = opts.env || process.env;
      const platform = opts.platform || process.platform;
      if (platform !== "win32") {
        return "PATH";
      }
      return Object.keys(env).find((x) => x.toUpperCase() === "PATH") || "Path";
    };
  }
});

// ../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = __commonJS({
  "../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module2) {
    "use strict";
    var path = require("path");
    var which2 = require_which();
    var pathKey = require_path_key()();
    function resolveCommandAttempt(parsed, withoutPathExt) {
      const cwd = process.cwd();
      const hasCustomCwd = parsed.options.cwd != null;
      if (hasCustomCwd) {
        try {
          process.chdir(parsed.options.cwd);
        } catch (err) {
        }
      }
      let resolved;
      try {
        resolved = which2.sync(parsed.command, {
          path: (parsed.options.env || process.env)[pathKey],
          pathExt: withoutPathExt ? path.delimiter : void 0
        });
      } catch (e) {
      } finally {
        process.chdir(cwd);
      }
      if (resolved) {
        resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
      }
      return resolved;
    }
    function resolveCommand(parsed) {
      return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
    }
    module2.exports = resolveCommand;
  }
});

// ../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/util/escape.js
var require_escape = __commonJS({
  "../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/util/escape.js"(exports, module2) {
    "use strict";
    var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
    function escapeCommand(arg) {
      arg = arg.replace(metaCharsRegExp, "^$1");
      return arg;
    }
    function escapeArgument(arg, doubleEscapeMetaChars) {
      arg = `${arg}`;
      arg = arg.replace(/(\\*)"/g, '$1$1\\"');
      arg = arg.replace(/(\\*)$/, "$1$1");
      arg = `"${arg}"`;
      arg = arg.replace(metaCharsRegExp, "^$1");
      if (doubleEscapeMetaChars) {
        arg = arg.replace(metaCharsRegExp, "^$1");
      }
      return arg;
    }
    module2.exports.command = escapeCommand;
    module2.exports.argument = escapeArgument;
  }
});

// ../../node_modules/.pnpm/shebang-regex@1.0.0/node_modules/shebang-regex/index.js
var require_shebang_regex = __commonJS({
  "../../node_modules/.pnpm/shebang-regex@1.0.0/node_modules/shebang-regex/index.js"(exports, module2) {
    "use strict";
    module2.exports = /^#!.*/;
  }
});

// ../../node_modules/.pnpm/shebang-command@1.2.0/node_modules/shebang-command/index.js
var require_shebang_command = __commonJS({
  "../../node_modules/.pnpm/shebang-command@1.2.0/node_modules/shebang-command/index.js"(exports, module2) {
    "use strict";
    var shebangRegex = require_shebang_regex();
    module2.exports = function(str) {
      var match = str.match(shebangRegex);
      if (!match) {
        return null;
      }
      var arr = match[0].replace(/#! ?/, "").split(" ");
      var bin = arr[0].split("/").pop();
      var arg = arr[1];
      return bin === "env" ? arg : bin + (arg ? " " + arg : "");
    };
  }
});

// ../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/util/readShebang.js
var require_readShebang = __commonJS({
  "../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module2) {
    "use strict";
    var fs5 = require("fs");
    var shebangCommand = require_shebang_command();
    function readShebang(command) {
      const size = 150;
      let buffer;
      if (Buffer.alloc) {
        buffer = Buffer.alloc(size);
      } else {
        buffer = new Buffer(size);
        buffer.fill(0);
      }
      let fd;
      try {
        fd = fs5.openSync(command, "r");
        fs5.readSync(fd, buffer, 0, size, 0);
        fs5.closeSync(fd);
      } catch (e) {
      }
      return shebangCommand(buffer.toString());
    }
    module2.exports = readShebang;
  }
});

// ../../node_modules/.pnpm/semver@5.7.2/node_modules/semver/semver.js
var require_semver = __commonJS({
  "../../node_modules/.pnpm/semver@5.7.2/node_modules/semver/semver.js"(exports, module2) {
    exports = module2.exports = SemVer;
    var debug6;
    if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
      debug6 = function() {
        var args = Array.prototype.slice.call(arguments, 0);
        args.unshift("SEMVER");
        console.log.apply(console, args);
      };
    } else {
      debug6 = function() {
      };
    }
    exports.SEMVER_SPEC_VERSION = "2.0.0";
    var MAX_LENGTH = 256;
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
    9007199254740991;
    var MAX_SAFE_COMPONENT_LENGTH = 16;
    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
    var re = exports.re = [];
    var safeRe = exports.safeRe = [];
    var src = exports.src = [];
    var R = 0;
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var safeRegexReplacements = [
      ["\\s", 1],
      ["\\d", MAX_LENGTH],
      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
    ];
    function makeSafeRe(value) {
      for (var i2 = 0; i2 < safeRegexReplacements.length; i2++) {
        var token = safeRegexReplacements[i2][0];
        var max = safeRegexReplacements[i2][1];
        value = value.split(token + "*").join(token + "{0," + max + "}").split(token + "+").join(token + "{1," + max + "}");
      }
      return value;
    }
    var NUMERICIDENTIFIER = R++;
    src[NUMERICIDENTIFIER] = "0|[1-9]\\d*";
    var NUMERICIDENTIFIERLOOSE = R++;
    src[NUMERICIDENTIFIERLOOSE] = "\\d+";
    var NONNUMERICIDENTIFIER = R++;
    src[NONNUMERICIDENTIFIER] = "\\d*[a-zA-Z-]" + LETTERDASHNUMBER + "*";
    var MAINVERSION = R++;
    src[MAINVERSION] = "(" + src[NUMERICIDENTIFIER] + ")\\.(" + src[NUMERICIDENTIFIER] + ")\\.(" + src[NUMERICIDENTIFIER] + ")";
    var MAINVERSIONLOOSE = R++;
    src[MAINVERSIONLOOSE] = "(" + src[NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[NUMERICIDENTIFIERLOOSE] + ")";
    var PRERELEASEIDENTIFIER = R++;
    src[PRERELEASEIDENTIFIER] = "(?:" + src[NUMERICIDENTIFIER] + "|" + src[NONNUMERICIDENTIFIER] + ")";
    var PRERELEASEIDENTIFIERLOOSE = R++;
    src[PRERELEASEIDENTIFIERLOOSE] = "(?:" + src[NUMERICIDENTIFIERLOOSE] + "|" + src[NONNUMERICIDENTIFIER] + ")";
    var PRERELEASE = R++;
    src[PRERELEASE] = "(?:-(" + src[PRERELEASEIDENTIFIER] + "(?:\\." + src[PRERELEASEIDENTIFIER] + ")*))";
    var PRERELEASELOOSE = R++;
    src[PRERELEASELOOSE] = "(?:-?(" + src[PRERELEASEIDENTIFIERLOOSE] + "(?:\\." + src[PRERELEASEIDENTIFIERLOOSE] + ")*))";
    var BUILDIDENTIFIER = R++;
    src[BUILDIDENTIFIER] = LETTERDASHNUMBER + "+";
    var BUILD = R++;
    src[BUILD] = "(?:\\+(" + src[BUILDIDENTIFIER] + "(?:\\." + src[BUILDIDENTIFIER] + ")*))";
    var FULL = R++;
    var FULLPLAIN = "v?" + src[MAINVERSION] + src[PRERELEASE] + "?" + src[BUILD] + "?";
    src[FULL] = "^" + FULLPLAIN + "$";
    var LOOSEPLAIN = "[v=\\s]*" + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + "?" + src[BUILD] + "?";
    var LOOSE = R++;
    src[LOOSE] = "^" + LOOSEPLAIN + "$";
    var GTLT = R++;
    src[GTLT] = "((?:<|>)?=?)";
    var XRANGEIDENTIFIERLOOSE = R++;
    src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + "|x|X|\\*";
    var XRANGEIDENTIFIER = R++;
    src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + "|x|X|\\*";
    var XRANGEPLAIN = R++;
    src[XRANGEPLAIN] = "[v=\\s]*(" + src[XRANGEIDENTIFIER] + ")(?:\\.(" + src[XRANGEIDENTIFIER] + ")(?:\\.(" + src[XRANGEIDENTIFIER] + ")(?:" + src[PRERELEASE] + ")?" + src[BUILD] + "?)?)?";
    var XRANGEPLAINLOOSE = R++;
    src[XRANGEPLAINLOOSE] = "[v=\\s]*(" + src[XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[XRANGEIDENTIFIERLOOSE] + ")(?:" + src[PRERELEASELOOSE] + ")?" + src[BUILD] + "?)?)?";
    var XRANGE = R++;
    src[XRANGE] = "^" + src[GTLT] + "\\s*" + src[XRANGEPLAIN] + "$";
    var XRANGELOOSE = R++;
    src[XRANGELOOSE] = "^" + src[GTLT] + "\\s*" + src[XRANGEPLAINLOOSE] + "$";
    var COERCE = R++;
    src[COERCE] = "(?:^|[^\\d])(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "})(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:$|[^\\d])";
    var LONETILDE = R++;
    src[LONETILDE] = "(?:~>?)";
    var TILDETRIM = R++;
    src[TILDETRIM] = "(\\s*)" + src[LONETILDE] + "\\s+";
    re[TILDETRIM] = new RegExp(src[TILDETRIM], "g");
    safeRe[TILDETRIM] = new RegExp(makeSafeRe(src[TILDETRIM]), "g");
    var tildeTrimReplace = "$1~";
    var TILDE = R++;
    src[TILDE] = "^" + src[LONETILDE] + src[XRANGEPLAIN] + "$";
    var TILDELOOSE = R++;
    src[TILDELOOSE] = "^" + src[LONETILDE] + src[XRANGEPLAINLOOSE] + "$";
    var LONECARET = R++;
    src[LONECARET] = "(?:\\^)";
    var CARETTRIM = R++;
    src[CARETTRIM] = "(\\s*)" + src[LONECARET] + "\\s+";
    re[CARETTRIM] = new RegExp(src[CARETTRIM], "g");
    safeRe[CARETTRIM] = new RegExp(makeSafeRe(src[CARETTRIM]), "g");
    var caretTrimReplace = "$1^";
    var CARET = R++;
    src[CARET] = "^" + src[LONECARET] + src[XRANGEPLAIN] + "$";
    var CARETLOOSE = R++;
    src[CARETLOOSE] = "^" + src[LONECARET] + src[XRANGEPLAINLOOSE] + "$";
    var COMPARATORLOOSE = R++;
    src[COMPARATORLOOSE] = "^" + src[GTLT] + "\\s*(" + LOOSEPLAIN + ")$|^$";
    var COMPARATOR = R++;
    src[COMPARATOR] = "^" + src[GTLT] + "\\s*(" + FULLPLAIN + ")$|^$";
    var COMPARATORTRIM = R++;
    src[COMPARATORTRIM] = "(\\s*)" + src[GTLT] + "\\s*(" + LOOSEPLAIN + "|" + src[XRANGEPLAIN] + ")";
    re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], "g");
    safeRe[COMPARATORTRIM] = new RegExp(makeSafeRe(src[COMPARATORTRIM]), "g");
    var comparatorTrimReplace = "$1$2$3";
    var HYPHENRANGE = R++;
    src[HYPHENRANGE] = "^\\s*(" + src[XRANGEPLAIN] + ")\\s+-\\s+(" + src[XRANGEPLAIN] + ")\\s*$";
    var HYPHENRANGELOOSE = R++;
    src[HYPHENRANGELOOSE] = "^\\s*(" + src[XRANGEPLAINLOOSE] + ")\\s+-\\s+(" + src[XRANGEPLAINLOOSE] + ")\\s*$";
    var STAR = R++;
    src[STAR] = "(<|>)?=?\\s*\\*";
    for (i = 0; i < R; i++) {
      debug6(i, src[i]);
      if (!re[i]) {
        re[i] = new RegExp(src[i]);
        safeRe[i] = new RegExp(makeSafeRe(src[i]));
      }
    }
    var i;
    exports.parse = parse2;
    function parse2(version2, options) {
      if (!options || typeof options !== "object") {
        options = {
          loose: !!options,
          includePrerelease: false
        };
      }
      if (version2 instanceof SemVer) {
        return version2;
      }
      if (typeof version2 !== "string") {
        return null;
      }
      if (version2.length > MAX_LENGTH) {
        return null;
      }
      var r = options.loose ? safeRe[LOOSE] : safeRe[FULL];
      if (!r.test(version2)) {
        return null;
      }
      try {
        return new SemVer(version2, options);
      } catch (er) {
        return null;
      }
    }
    exports.valid = valid;
    function valid(version2, options) {
      var v = parse2(version2, options);
      return v ? v.version : null;
    }
    exports.clean = clean;
    function clean(version2, options) {
      var s = parse2(version2.trim().replace(/^[=v]+/, ""), options);
      return s ? s.version : null;
    }
    exports.SemVer = SemVer;
    function SemVer(version2, options) {
      if (!options || typeof options !== "object") {
        options = {
          loose: !!options,
          includePrerelease: false
        };
      }
      if (version2 instanceof SemVer) {
        if (version2.loose === options.loose) {
          return version2;
        } else {
          version2 = version2.version;
        }
      } else if (typeof version2 !== "string") {
        throw new TypeError("Invalid Version: " + version2);
      }
      if (version2.length > MAX_LENGTH) {
        throw new TypeError("version is longer than " + MAX_LENGTH + " characters");
      }
      if (!(this instanceof SemVer)) {
        return new SemVer(version2, options);
      }
      debug6("SemVer", version2, options);
      this.options = options;
      this.loose = !!options.loose;
      var m = version2.trim().match(options.loose ? safeRe[LOOSE] : safeRe[FULL]);
      if (!m) {
        throw new TypeError("Invalid Version: " + version2);
      }
      this.raw = version2;
      this.major = +m[1];
      this.minor = +m[2];
      this.patch = +m[3];
      if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
        throw new TypeError("Invalid major version");
      }
      if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
        throw new TypeError("Invalid minor version");
      }
      if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
        throw new TypeError("Invalid patch version");
      }
      if (!m[4]) {
        this.prerelease = [];
      } else {
        this.prerelease = m[4].split(".").map(function(id) {
          if (/^[0-9]+$/.test(id)) {
            var num = +id;
            if (num >= 0 && num < MAX_SAFE_INTEGER) {
              return num;
            }
          }
          return id;
        });
      }
      this.build = m[5] ? m[5].split(".") : [];
      this.format();
    }
    SemVer.prototype.format = function() {
      this.version = this.major + "." + this.minor + "." + this.patch;
      if (this.prerelease.length) {
        this.version += "-" + this.prerelease.join(".");
      }
      return this.version;
    };
    SemVer.prototype.toString = function() {
      return this.version;
    };
    SemVer.prototype.compare = function(other) {
      debug6("SemVer.compare", this.version, this.options, other);
      if (!(other instanceof SemVer)) {
        other = new SemVer(other, this.options);
      }
      return this.compareMain(other) || this.comparePre(other);
    };
    SemVer.prototype.compareMain = function(other) {
      if (!(other instanceof SemVer)) {
        other = new SemVer(other, this.options);
      }
      return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
    };
    SemVer.prototype.comparePre = function(other) {
      if (!(other instanceof SemVer)) {
        other = new SemVer(other, this.options);
      }
      if (this.prerelease.length && !other.prerelease.length) {
        return -1;
      } else if (!this.prerelease.length && other.prerelease.length) {
        return 1;
      } else if (!this.prerelease.length && !other.prerelease.length) {
        return 0;
      }
      var i2 = 0;
      do {
        var a = this.prerelease[i2];
        var b = other.prerelease[i2];
        debug6("prerelease compare", i2, a, b);
        if (a === void 0 && b === void 0) {
          return 0;
        } else if (b === void 0) {
          return 1;
        } else if (a === void 0) {
          return -1;
        } else if (a === b) {
          continue;
        } else {
          return compareIdentifiers(a, b);
        }
      } while (++i2);
    };
    SemVer.prototype.inc = function(release, identifier) {
      switch (release) {
        case "premajor":
          this.prerelease.length = 0;
          this.patch = 0;
          this.minor = 0;
          this.major++;
          this.inc("pre", identifier);
          break;
        case "preminor":
          this.prerelease.length = 0;
          this.patch = 0;
          this.minor++;
          this.inc("pre", identifier);
          break;
        case "prepatch":
          this.prerelease.length = 0;
          this.inc("patch", identifier);
          this.inc("pre", identifier);
          break;
        case "prerelease":
          if (this.prerelease.length === 0) {
            this.inc("patch", identifier);
          }
          this.inc("pre", identifier);
          break;
        case "major":
          if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
            this.major++;
          }
          this.minor = 0;
          this.patch = 0;
          this.prerelease = [];
          break;
        case "minor":
          if (this.patch !== 0 || this.prerelease.length === 0) {
            this.minor++;
          }
          this.patch = 0;
          this.prerelease = [];
          break;
        case "patch":
          if (this.prerelease.length === 0) {
            this.patch++;
          }
          this.prerelease = [];
          break;
        case "pre":
          if (this.prerelease.length === 0) {
            this.prerelease = [0];
          } else {
            var i2 = this.prerelease.length;
            while (--i2 >= 0) {
              if (typeof this.prerelease[i2] === "number") {
                this.prerelease[i2]++;
                i2 = -2;
              }
            }
            if (i2 === -1) {
              this.prerelease.push(0);
            }
          }
          if (identifier) {
            if (this.prerelease[0] === identifier) {
              if (isNaN(this.prerelease[1])) {
                this.prerelease = [identifier, 0];
              }
            } else {
              this.prerelease = [identifier, 0];
            }
          }
          break;
        default:
          throw new Error("invalid increment argument: " + release);
      }
      this.format();
      this.raw = this.version;
      return this;
    };
    exports.inc = inc;
    function inc(version2, release, loose, identifier) {
      if (typeof loose === "string") {
        identifier = loose;
        loose = void 0;
      }
      try {
        return new SemVer(version2, loose).inc(release, identifier).version;
      } catch (er) {
        return null;
      }
    }
    exports.diff = diff;
    function diff(version1, version2) {
      if (eq(version1, version2)) {
        return null;
      } else {
        var v1 = parse2(version1);
        var v2 = parse2(version2);
        var prefix = "";
        if (v1.prerelease.length || v2.prerelease.length) {
          prefix = "pre";
          var defaultResult = "prerelease";
        }
        for (var key in v1) {
          if (key === "major" || key === "minor" || key === "patch") {
            if (v1[key] !== v2[key]) {
              return prefix + key;
            }
          }
        }
        return defaultResult;
      }
    }
    exports.compareIdentifiers = compareIdentifiers;
    var numeric = /^[0-9]+$/;
    function compareIdentifiers(a, b) {
      var anum = numeric.test(a);
      var bnum = numeric.test(b);
      if (anum && bnum) {
        a = +a;
        b = +b;
      }
      return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
    }
    exports.rcompareIdentifiers = rcompareIdentifiers;
    function rcompareIdentifiers(a, b) {
      return compareIdentifiers(b, a);
    }
    exports.major = major;
    function major(a, loose) {
      return new SemVer(a, loose).major;
    }
    exports.minor = minor;
    function minor(a, loose) {
      return new SemVer(a, loose).minor;
    }
    exports.patch = patch;
    function patch(a, loose) {
      return new SemVer(a, loose).patch;
    }
    exports.compare = compare;
    function compare(a, b, loose) {
      return new SemVer(a, loose).compare(new SemVer(b, loose));
    }
    exports.compareLoose = compareLoose;
    function compareLoose(a, b) {
      return compare(a, b, true);
    }
    exports.rcompare = rcompare;
    function rcompare(a, b, loose) {
      return compare(b, a, loose);
    }
    exports.sort = sort;
    function sort(list, loose) {
      return list.sort(function(a, b) {
        return exports.compare(a, b, loose);
      });
    }
    exports.rsort = rsort;
    function rsort(list, loose) {
      return list.sort(function(a, b) {
        return exports.rcompare(a, b, loose);
      });
    }
    exports.gt = gt;
    function gt(a, b, loose) {
      return compare(a, b, loose) > 0;
    }
    exports.lt = lt;
    function lt(a, b, loose) {
      return compare(a, b, loose) < 0;
    }
    exports.eq = eq;
    function eq(a, b, loose) {
      return compare(a, b, loose) === 0;
    }
    exports.neq = neq;
    function neq(a, b, loose) {
      return compare(a, b, loose) !== 0;
    }
    exports.gte = gte;
    function gte(a, b, loose) {
      return compare(a, b, loose) >= 0;
    }
    exports.lte = lte;
    function lte(a, b, loose) {
      return compare(a, b, loose) <= 0;
    }
    exports.cmp = cmp;
    function cmp(a, op, b, loose) {
      switch (op) {
        case "===":
          if (typeof a === "object")
            a = a.version;
          if (typeof b === "object")
            b = b.version;
          return a === b;
        case "!==":
          if (typeof a === "object")
            a = a.version;
          if (typeof b === "object")
            b = b.version;
          return a !== b;
        case "":
        case "=":
        case "==":
          return eq(a, b, loose);
        case "!=":
          return neq(a, b, loose);
        case ">":
          return gt(a, b, loose);
        case ">=":
          return gte(a, b, loose);
        case "<":
          return lt(a, b, loose);
        case "<=":
          return lte(a, b, loose);
        default:
          throw new TypeError("Invalid operator: " + op);
      }
    }
    exports.Comparator = Comparator;
    function Comparator(comp, options) {
      if (!options || typeof options !== "object") {
        options = {
          loose: !!options,
          includePrerelease: false
        };
      }
      if (comp instanceof Comparator) {
        if (comp.loose === !!options.loose) {
          return comp;
        } else {
          comp = comp.value;
        }
      }
      if (!(this instanceof Comparator)) {
        return new Comparator(comp, options);
      }
      comp = comp.trim().split(/\s+/).join(" ");
      debug6("comparator", comp, options);
      this.options = options;
      this.loose = !!options.loose;
      this.parse(comp);
      if (this.semver === ANY) {
        this.value = "";
      } else {
        this.value = this.operator + this.semver.version;
      }
      debug6("comp", this);
    }
    var ANY = {};
    Comparator.prototype.parse = function(comp) {
      var r = this.options.loose ? safeRe[COMPARATORLOOSE] : safeRe[COMPARATOR];
      var m = comp.match(r);
      if (!m) {
        throw new TypeError("Invalid comparator: " + comp);
      }
      this.operator = m[1];
      if (this.operator === "=") {
        this.operator = "";
      }
      if (!m[2]) {
        this.semver = ANY;
      } else {
        this.semver = new SemVer(m[2], this.options.loose);
      }
    };
    Comparator.prototype.toString = function() {
      return this.value;
    };
    Comparator.prototype.test = function(version2) {
      debug6("Comparator.test", version2, this.options.loose);
      if (this.semver === ANY) {
        return true;
      }
      if (typeof version2 === "string") {
        version2 = new SemVer(version2, this.options);
      }
      return cmp(version2, this.operator, this.semver, this.options);
    };
    Comparator.prototype.intersects = function(comp, options) {
      if (!(comp instanceof Comparator)) {
        throw new TypeError("a Comparator is required");
      }
      if (!options || typeof options !== "object") {
        options = {
          loose: !!options,
          includePrerelease: false
        };
      }
      var rangeTmp;
      if (this.operator === "") {
        rangeTmp = new Range(comp.value, options);
        return satisfies2(this.value, rangeTmp, options);
      } else if (comp.operator === "") {
        rangeTmp = new Range(this.value, options);
        return satisfies2(comp.semver, rangeTmp, options);
      }
      var sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">");
      var sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<");
      var sameSemVer = this.semver.version === comp.semver.version;
      var differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<=");
      var oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && ((this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<"));
      var oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && ((this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">"));
      return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
    };
    exports.Range = Range;
    function Range(range, options) {
      if (!options || typeof options !== "object") {
        options = {
          loose: !!options,
          includePrerelease: false
        };
      }
      if (range instanceof Range) {
        if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
          return range;
        } else {
          return new Range(range.raw, options);
        }
      }
      if (range instanceof Comparator) {
        return new Range(range.value, options);
      }
      if (!(this instanceof Range)) {
        return new Range(range, options);
      }
      this.options = options;
      this.loose = !!options.loose;
      this.includePrerelease = !!options.includePrerelease;
      this.raw = range.trim().split(/\s+/).join(" ");
      this.set = this.raw.split("||").map(function(range2) {
        return this.parseRange(range2.trim());
      }, this).filter(function(c) {
        return c.length;
      });
      if (!this.set.length) {
        throw new TypeError("Invalid SemVer Range: " + this.raw);
      }
      this.format();
    }
    Range.prototype.format = function() {
      this.range = this.set.map(function(comps) {
        return comps.join(" ").trim();
      }).join("||").trim();
      return this.range;
    };
    Range.prototype.toString = function() {
      return this.range;
    };
    Range.prototype.parseRange = function(range) {
      var loose = this.options.loose;
      var hr = loose ? safeRe[HYPHENRANGELOOSE] : safeRe[HYPHENRANGE];
      range = range.replace(hr, hyphenReplace);
      debug6("hyphen replace", range);
      range = range.replace(safeRe[COMPARATORTRIM], comparatorTrimReplace);
      debug6("comparator trim", range, safeRe[COMPARATORTRIM]);
      range = range.replace(safeRe[TILDETRIM], tildeTrimReplace);
      range = range.replace(safeRe[CARETTRIM], caretTrimReplace);
      var compRe = loose ? safeRe[COMPARATORLOOSE] : safeRe[COMPARATOR];
      var set = range.split(" ").map(function(comp) {
        return parseComparator(comp, this.options);
      }, this).join(" ").split(/\s+/);
      if (this.options.loose) {
        set = set.filter(function(comp) {
          return !!comp.match(compRe);
        });
      }
      set = set.map(function(comp) {
        return new Comparator(comp, this.options);
      }, this);
      return set;
    };
    Range.prototype.intersects = function(range, options) {
      if (!(range instanceof Range)) {
        throw new TypeError("a Range is required");
      }
      return this.set.some(function(thisComparators) {
        return thisComparators.every(function(thisComparator) {
          return range.set.some(function(rangeComparators) {
            return rangeComparators.every(function(rangeComparator) {
              return thisComparator.intersects(rangeComparator, options);
            });
          });
        });
      });
    };
    exports.toComparators = toComparators;
    function toComparators(range, options) {
      return new Range(range, options).set.map(function(comp) {
        return comp.map(function(c) {
          return c.value;
        }).join(" ").trim().split(" ");
      });
    }
    function parseComparator(comp, options) {
      debug6("comp", comp, options);
      comp = replaceCarets(comp, options);
      debug6("caret", comp);
      comp = replaceTildes(comp, options);
      debug6("tildes", comp);
      comp = replaceXRanges(comp, options);
      debug6("xrange", comp);
      comp = replaceStars(comp, options);
      debug6("stars", comp);
      return comp;
    }
    function isX(id) {
      return !id || id.toLowerCase() === "x" || id === "*";
    }
    function replaceTildes(comp, options) {
      return comp.trim().split(/\s+/).map(function(comp2) {
        return replaceTilde(comp2, options);
      }).join(" ");
    }
    function replaceTilde(comp, options) {
      var r = options.loose ? safeRe[TILDELOOSE] : safeRe[TILDE];
      return comp.replace(r, function(_, M, m, p, pr) {
        debug6("tilde", comp, _, M, m, p, pr);
        var ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
        } else if (isX(p)) {
          ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
        } else if (pr) {
          debug6("replaceTilde pr", pr);
          ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
        } else {
          ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
        }
        debug6("tilde return", ret);
        return ret;
      });
    }
    function replaceCarets(comp, options) {
      return comp.trim().split(/\s+/).map(function(comp2) {
        return replaceCaret(comp2, options);
      }).join(" ");
    }
    function replaceCaret(comp, options) {
      debug6("caret", comp, options);
      var r = options.loose ? safeRe[CARETLOOSE] : safeRe[CARET];
      return comp.replace(r, function(_, M, m, p, pr) {
        debug6("caret", comp, _, M, m, p, pr);
        var ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m)) {
          ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
        } else if (isX(p)) {
          if (M === "0") {
            ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
          } else {
            ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0";
          }
        } else if (pr) {
          debug6("replaceCaret pr", pr);
          if (M === "0") {
            if (m === "0") {
              ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1);
            } else {
              ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
            }
          } else {
            ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0";
          }
        } else {
          debug6("no pr");
          if (M === "0") {
            if (m === "0") {
              ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1);
            } else {
              ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
            }
          } else {
            ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0";
          }
        }
        debug6("caret return", ret);
        return ret;
      });
    }
    function replaceXRanges(comp, options) {
      debug6("replaceXRanges", comp, options);
      return comp.split(/\s+/).map(function(comp2) {
        return replaceXRange(comp2, options);
      }).join(" ");
    }
    function replaceXRange(comp, options) {
      comp = comp.trim();
      var r = options.loose ? safeRe[XRANGELOOSE] : safeRe[XRANGE];
      return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
        debug6("xRange", comp, ret, gtlt, M, m, p, pr);
        var xM = isX(M);
        var xm = xM || isX(m);
        var xp = xm || isX(p);
        var anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m = 0;
          }
          p = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m = 0;
              p = 0;
            } else {
              m = +m + 1;
              p = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m = +m + 1;
            }
          }
          ret = gtlt + M + "." + m + "." + p;
        } else if (xm) {
          ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
        } else if (xp) {
          ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
        }
        debug6("xRange return", ret);
        return ret;
      });
    }
    function replaceStars(comp, options) {
      debug6("replaceStars", comp, options);
      return comp.trim().replace(safeRe[STAR], "");
    }
    function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
      if (isX(fM)) {
        from = "";
      } else if (isX(fm)) {
        from = ">=" + fM + ".0.0";
      } else if (isX(fp)) {
        from = ">=" + fM + "." + fm + ".0";
      } else {
        from = ">=" + from;
      }
      if (isX(tM)) {
        to = "";
      } else if (isX(tm)) {
        to = "<" + (+tM + 1) + ".0.0";
      } else if (isX(tp)) {
        to = "<" + tM + "." + (+tm + 1) + ".0";
      } else if (tpr) {
        to = "<=" + tM + "." + tm + "." + tp + "-" + tpr;
      } else {
        to = "<=" + to;
      }
      return (from + " " + to).trim();
    }
    Range.prototype.test = function(version2) {
      if (!version2) {
        return false;
      }
      if (typeof version2 === "string") {
        version2 = new SemVer(version2, this.options);
      }
      for (var i2 = 0; i2 < this.set.length; i2++) {
        if (testSet(this.set[i2], version2, this.options)) {
          return true;
        }
      }
      return false;
    };
    function testSet(set, version2, options) {
      for (var i2 = 0; i2 < set.length; i2++) {
        if (!set[i2].test(version2)) {
          return false;
        }
      }
      if (version2.prerelease.length && !options.includePrerelease) {
        for (i2 = 0; i2 < set.length; i2++) {
          debug6(set[i2].semver);
          if (set[i2].semver === ANY) {
            continue;
          }
          if (set[i2].semver.prerelease.length > 0) {
            var allowed = set[i2].semver;
            if (allowed.major === version2.major && allowed.minor === version2.minor && allowed.patch === version2.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    }
    exports.satisfies = satisfies2;
    function satisfies2(version2, range, options) {
      try {
        range = new Range(range, options);
      } catch (er) {
        return false;
      }
      return range.test(version2);
    }
    exports.maxSatisfying = maxSatisfying;
    function maxSatisfying(versions, range, options) {
      var max = null;
      var maxSV = null;
      try {
        var rangeObj = new Range(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach(function(v) {
        if (rangeObj.test(v)) {
          if (!max || maxSV.compare(v) === -1) {
            max = v;
            maxSV = new SemVer(max, options);
          }
        }
      });
      return max;
    }
    exports.minSatisfying = minSatisfying;
    function minSatisfying(versions, range, options) {
      var min = null;
      var minSV = null;
      try {
        var rangeObj = new Range(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach(function(v) {
        if (rangeObj.test(v)) {
          if (!min || minSV.compare(v) === 1) {
            min = v;
            minSV = new SemVer(min, options);
          }
        }
      });
      return min;
    }
    exports.minVersion = minVersion;
    function minVersion(range, loose) {
      range = new Range(range, loose);
      var minver = new SemVer("0.0.0");
      if (range.test(minver)) {
        return minver;
      }
      minver = new SemVer("0.0.0-0");
      if (range.test(minver)) {
        return minver;
      }
      minver = null;
      for (var i2 = 0; i2 < range.set.length; ++i2) {
        var comparators = range.set[i2];
        comparators.forEach(function(comparator) {
          var compver = new SemVer(comparator.semver.version);
          switch (comparator.operator) {
            case ">":
              if (compver.prerelease.length === 0) {
                compver.patch++;
              } else {
                compver.prerelease.push(0);
              }
              compver.raw = compver.format();
            case "":
            case ">=":
              if (!minver || gt(minver, compver)) {
                minver = compver;
              }
              break;
            case "<":
            case "<=":
              break;
            default:
              throw new Error("Unexpected operation: " + comparator.operator);
          }
        });
      }
      if (minver && range.test(minver)) {
        return minver;
      }
      return null;
    }
    exports.validRange = validRange;
    function validRange(range, options) {
      try {
        return new Range(range, options).range || "*";
      } catch (er) {
        return null;
      }
    }
    exports.ltr = ltr;
    function ltr(version2, range, options) {
      return outside(version2, range, "<", options);
    }
    exports.gtr = gtr;
    function gtr(version2, range, options) {
      return outside(version2, range, ">", options);
    }
    exports.outside = outside;
    function outside(version2, range, hilo, options) {
      version2 = new SemVer(version2, options);
      range = new Range(range, options);
      var gtfn, ltefn, ltfn, comp, ecomp;
      switch (hilo) {
        case ">":
          gtfn = gt;
          ltefn = lte;
          ltfn = lt;
          comp = ">";
          ecomp = ">=";
          break;
        case "<":
          gtfn = lt;
          ltefn = gte;
          ltfn = gt;
          comp = "<";
          ecomp = "<=";
          break;
        default:
          throw new TypeError('Must provide a hilo val of "<" or ">"');
      }
      if (satisfies2(version2, range, options)) {
        return false;
      }
      for (var i2 = 0; i2 < range.set.length; ++i2) {
        var comparators = range.set[i2];
        var high = null;
        var low = null;
        comparators.forEach(function(comparator) {
          if (comparator.semver === ANY) {
            comparator = new Comparator(">=0.0.0");
          }
          high = high || comparator;
          low = low || comparator;
          if (gtfn(comparator.semver, high.semver, options)) {
            high = comparator;
          } else if (ltfn(comparator.semver, low.semver, options)) {
            low = comparator;
          }
        });
        if (high.operator === comp || high.operator === ecomp) {
          return false;
        }
        if ((!low.operator || low.operator === comp) && ltefn(version2, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version2, low.semver)) {
          return false;
        }
      }
      return true;
    }
    exports.prerelease = prerelease;
    function prerelease(version2, options) {
      var parsed = parse2(version2, options);
      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
    }
    exports.intersects = intersects;
    function intersects(r1, r2, options) {
      r1 = new Range(r1, options);
      r2 = new Range(r2, options);
      return r1.intersects(r2);
    }
    exports.coerce = coerce;
    function coerce(version2) {
      if (version2 instanceof SemVer) {
        return version2;
      }
      if (typeof version2 !== "string") {
        return null;
      }
      var match = version2.match(safeRe[COERCE]);
      if (match == null) {
        return null;
      }
      return parse2(match[1] + "." + (match[2] || "0") + "." + (match[3] || "0"));
    }
  }
});

// ../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/parse.js
var require_parse = __commonJS({
  "../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/parse.js"(exports, module2) {
    "use strict";
    var path = require("path");
    var niceTry = require_src();
    var resolveCommand = require_resolveCommand();
    var escape = require_escape();
    var readShebang = require_readShebang();
    var semver = require_semver();
    var isWin4 = process.platform === "win32";
    var isExecutableRegExp = /\.(?:com|exe)$/i;
    var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
    var supportsShellOption = niceTry(() => semver.satisfies(process.version, "^4.8.0 || ^5.7.0 || >= 6.0.0", true)) || false;
    function detectShebang(parsed) {
      parsed.file = resolveCommand(parsed);
      const shebang = parsed.file && readShebang(parsed.file);
      if (shebang) {
        parsed.args.unshift(parsed.file);
        parsed.command = shebang;
        return resolveCommand(parsed);
      }
      return parsed.file;
    }
    function parseNonShell(parsed) {
      if (!isWin4) {
        return parsed;
      }
      const commandFile = detectShebang(parsed);
      const needsShell = !isExecutableRegExp.test(commandFile);
      if (parsed.options.forceShell || needsShell) {
        const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
        parsed.command = path.normalize(parsed.command);
        parsed.command = escape.command(parsed.command);
        parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
        const shellCommand = [parsed.command].concat(parsed.args).join(" ");
        parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
        parsed.command = process.env.comspec || "cmd.exe";
        parsed.options.windowsVerbatimArguments = true;
      }
      return parsed;
    }
    function parseShell(parsed) {
      if (supportsShellOption) {
        return parsed;
      }
      const shellCommand = [parsed.command].concat(parsed.args).join(" ");
      if (isWin4) {
        parsed.command = typeof parsed.options.shell === "string" ? parsed.options.shell : process.env.comspec || "cmd.exe";
        parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
        parsed.options.windowsVerbatimArguments = true;
      } else {
        if (typeof parsed.options.shell === "string") {
          parsed.command = parsed.options.shell;
        } else if (process.platform === "android") {
          parsed.command = "/system/bin/sh";
        } else {
          parsed.command = "/bin/sh";
        }
        parsed.args = ["-c", shellCommand];
      }
      return parsed;
    }
    function parse2(command, args, options) {
      if (args && !Array.isArray(args)) {
        options = args;
        args = null;
      }
      args = args ? args.slice(0) : [];
      options = Object.assign({}, options);
      const parsed = {
        command,
        args,
        options,
        file: void 0,
        original: {
          command,
          args
        }
      };
      return options.shell ? parseShell(parsed) : parseNonShell(parsed);
    }
    module2.exports = parse2;
  }
});

// ../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/enoent.js
var require_enoent = __commonJS({
  "../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/lib/enoent.js"(exports, module2) {
    "use strict";
    var isWin4 = process.platform === "win32";
    function notFoundError(original, syscall) {
      return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
        code: "ENOENT",
        errno: "ENOENT",
        syscall: `${syscall} ${original.command}`,
        path: original.command,
        spawnargs: original.args
      });
    }
    function hookChildProcess(cp, parsed) {
      if (!isWin4) {
        return;
      }
      const originalEmit = cp.emit;
      cp.emit = function(name, arg1) {
        if (name === "exit") {
          const err = verifyENOENT(arg1, parsed, "spawn");
          if (err) {
            return originalEmit.call(cp, "error", err);
          }
        }
        return originalEmit.apply(cp, arguments);
      };
    }
    function verifyENOENT(status, parsed) {
      if (isWin4 && status === 1 && !parsed.file) {
        return notFoundError(parsed.original, "spawn");
      }
      return null;
    }
    function verifyENOENTSync(status, parsed) {
      if (isWin4 && status === 1 && !parsed.file) {
        return notFoundError(parsed.original, "spawnSync");
      }
      return null;
    }
    module2.exports = {
      hookChildProcess,
      verifyENOENT,
      verifyENOENTSync,
      notFoundError
    };
  }
});

// ../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/index.js
var require_cross_spawn = __commonJS({
  "../../node_modules/.pnpm/cross-spawn@6.0.5/node_modules/cross-spawn/index.js"(exports, module2) {
    "use strict";
    var cp = require("child_process");
    var parse2 = require_parse();
    var enoent = require_enoent();
    function spawn2(command, args, options) {
      const parsed = parse2(command, args, options);
      const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
      enoent.hookChildProcess(spawned, parsed);
      return spawned;
    }
    function spawnSync(command, args, options) {
      const parsed = parse2(command, args, options);
      const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
      result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
      return result;
    }
    module2.exports = spawn2;
    module2.exports.spawn = spawn2;
    module2.exports.sync = spawnSync;
    module2.exports._parse = parse2;
    module2.exports._enoent = enoent;
  }
});

// ../../node_modules/.pnpm/strip-eof@1.0.0/node_modules/strip-eof/index.js
var require_strip_eof = __commonJS({
  "../../node_modules/.pnpm/strip-eof@1.0.0/node_modules/strip-eof/index.js"(exports, module2) {
    "use strict";
    module2.exports = function(x) {
      var lf = typeof x === "string" ? "\n" : "\n".charCodeAt();
      var cr = typeof x === "string" ? "\r" : "\r".charCodeAt();
      if (x[x.length - 1] === lf) {
        x = x.slice(0, x.length - 1);
      }
      if (x[x.length - 1] === cr) {
        x = x.slice(0, x.length - 1);
      }
      return x;
    };
  }
});

// ../../node_modules/.pnpm/npm-run-path@2.0.2/node_modules/npm-run-path/index.js
var require_npm_run_path = __commonJS({
  "../../node_modules/.pnpm/npm-run-path@2.0.2/node_modules/npm-run-path/index.js"(exports, module2) {
    "use strict";
    var path = require("path");
    var pathKey = require_path_key();
    module2.exports = (opts) => {
      opts = Object.assign({
        cwd: process.cwd(),
        path: process.env[pathKey()]
      }, opts);
      let prev;
      let pth = path.resolve(opts.cwd);
      const ret = [];
      while (prev !== pth) {
        ret.push(path.join(pth, "node_modules/.bin"));
        prev = pth;
        pth = path.resolve(pth, "..");
      }
      ret.push(path.dirname(process.execPath));
      return ret.concat(opts.path).join(path.delimiter);
    };
    module2.exports.env = (opts) => {
      opts = Object.assign({
        env: process.env
      }, opts);
      const env = Object.assign({}, opts.env);
      const path2 = pathKey({ env });
      opts.path = env[path2];
      env[path2] = module2.exports(opts);
      return env;
    };
  }
});

// ../../node_modules/.pnpm/is-stream@1.1.0/node_modules/is-stream/index.js
var require_is_stream = __commonJS({
  "../../node_modules/.pnpm/is-stream@1.1.0/node_modules/is-stream/index.js"(exports, module2) {
    "use strict";
    var isStream = module2.exports = function(stream) {
      return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
    };
    isStream.writable = function(stream) {
      return isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
    };
    isStream.readable = function(stream) {
      return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
    };
    isStream.duplex = function(stream) {
      return isStream.writable(stream) && isStream.readable(stream);
    };
    isStream.transform = function(stream) {
      return isStream.duplex(stream) && typeof stream._transform === "function" && typeof stream._transformState === "object";
    };
  }
});

// ../../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js
var require_wrappy = __commonJS({
  "../../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports, module2) {
    module2.exports = wrappy;
    function wrappy(fn, cb) {
      if (fn && cb)
        return wrappy(fn)(cb);
      if (typeof fn !== "function")
        throw new TypeError("need wrapper function");
      Object.keys(fn).forEach(function(k) {
        wrapper[k] = fn[k];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k) {
            ret[k] = cb2[k];
          });
        }
        return ret;
      }
    }
  }
});

// ../../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
var require_once = __commonJS({
  "../../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports, module2) {
    var wrappy = require_wrappy();
    module2.exports = wrappy(once);
    module2.exports.strict = wrappy(onceStrict);
    once.proto = once(function() {
      Object.defineProperty(Function.prototype, "once", {
        value: function() {
          return once(this);
        },
        configurable: true
      });
      Object.defineProperty(Function.prototype, "onceStrict", {
        value: function() {
          return onceStrict(this);
        },
        configurable: true
      });
    });
    function once(fn) {
      var f = function() {
        if (f.called)
          return f.value;
        f.called = true;
        return f.value = fn.apply(this, arguments);
      };
      f.called = false;
      return f;
    }
    function onceStrict(fn) {
      var f = function() {
        if (f.called)
          throw new Error(f.onceError);
        f.called = true;
        return f.value = fn.apply(this, arguments);
      };
      var name = fn.name || "Function wrapped with `once`";
      f.onceError = name + " shouldn't be called more than once";
      f.called = false;
      return f;
    }
  }
});

// ../../node_modules/.pnpm/end-of-stream@1.4.1/node_modules/end-of-stream/index.js
var require_end_of_stream = __commonJS({
  "../../node_modules/.pnpm/end-of-stream@1.4.1/node_modules/end-of-stream/index.js"(exports, module2) {
    var once = require_once();
    var noop = function() {
    };
    var isRequest = function(stream) {
      return stream.setHeader && typeof stream.abort === "function";
    };
    var isChildProcess = function(stream) {
      return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
    };
    var eos = function(stream, opts, callback) {
      if (typeof opts === "function")
        return eos(stream, null, opts);
      if (!opts)
        opts = {};
      callback = once(callback || noop);
      var ws = stream._writableState;
      var rs = stream._readableState;
      var readable = opts.readable || opts.readable !== false && stream.readable;
      var writable = opts.writable || opts.writable !== false && stream.writable;
      var onlegacyfinish = function() {
        if (!stream.writable)
          onfinish();
      };
      var onfinish = function() {
        writable = false;
        if (!readable)
          callback.call(stream);
      };
      var onend = function() {
        readable = false;
        if (!writable)
          callback.call(stream);
      };
      var onexit = function(exitCode) {
        callback.call(stream, exitCode ? new Error("exited with error code: " + exitCode) : null);
      };
      var onerror = function(err) {
        callback.call(stream, err);
      };
      var onclose = function() {
        if (readable && !(rs && rs.ended))
          return callback.call(stream, new Error("premature close"));
        if (writable && !(ws && ws.ended))
          return callback.call(stream, new Error("premature close"));
      };
      var onrequest = function() {
        stream.req.on("finish", onfinish);
      };
      if (isRequest(stream)) {
        stream.on("complete", onfinish);
        stream.on("abort", onclose);
        if (stream.req)
          onrequest();
        else
          stream.on("request", onrequest);
      } else if (writable && !ws) {
        stream.on("end", onlegacyfinish);
        stream.on("close", onlegacyfinish);
      }
      if (isChildProcess(stream))
        stream.on("exit", onexit);
      stream.on("end", onend);
      stream.on("finish", onfinish);
      if (opts.error !== false)
        stream.on("error", onerror);
      stream.on("close", onclose);
      return function() {
        stream.removeListener("complete", onfinish);
        stream.removeListener("abort", onclose);
        stream.removeListener("request", onrequest);
        if (stream.req)
          stream.req.removeListener("finish", onfinish);
        stream.removeListener("end", onlegacyfinish);
        stream.removeListener("close", onlegacyfinish);
        stream.removeListener("finish", onfinish);
        stream.removeListener("exit", onexit);
        stream.removeListener("end", onend);
        stream.removeListener("error", onerror);
        stream.removeListener("close", onclose);
      };
    };
    module2.exports = eos;
  }
});

// ../../node_modules/.pnpm/pump@3.0.2/node_modules/pump/index.js
var require_pump = __commonJS({
  "../../node_modules/.pnpm/pump@3.0.2/node_modules/pump/index.js"(exports, module2) {
    var once = require_once();
    var eos = require_end_of_stream();
    var fs5;
    try {
      fs5 = require("fs");
    } catch (e) {
    }
    var noop = function() {
    };
    var ancient = /^v?\.0/.test(process.version);
    var isFn = function(fn) {
      return typeof fn === "function";
    };
    var isFS = function(stream) {
      if (!ancient)
        return false;
      if (!fs5)
        return false;
      return (stream instanceof (fs5.ReadStream || noop) || stream instanceof (fs5.WriteStream || noop)) && isFn(stream.close);
    };
    var isRequest = function(stream) {
      return stream.setHeader && isFn(stream.abort);
    };
    var destroyer = function(stream, reading, writing, callback) {
      callback = once(callback);
      var closed = false;
      stream.on("close", function() {
        closed = true;
      });
      eos(stream, { readable: reading, writable: writing }, function(err) {
        if (err)
          return callback(err);
        closed = true;
        callback();
      });
      var destroyed = false;
      return function(err) {
        if (closed)
          return;
        if (destroyed)
          return;
        destroyed = true;
        if (isFS(stream))
          return stream.close(noop);
        if (isRequest(stream))
          return stream.abort();
        if (isFn(stream.destroy))
          return stream.destroy();
        callback(err || new Error("stream was destroyed"));
      };
    };
    var call = function(fn) {
      fn();
    };
    var pipe = function(from, to) {
      return from.pipe(to);
    };
    var pump = function() {
      var streams = Array.prototype.slice.call(arguments);
      var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
      if (Array.isArray(streams[0]))
        streams = streams[0];
      if (streams.length < 2)
        throw new Error("pump requires two streams per minimum");
      var error;
      var destroys = streams.map(function(stream, i) {
        var reading = i < streams.length - 1;
        var writing = i > 0;
        return destroyer(stream, reading, writing, function(err) {
          if (!error)
            error = err;
          if (err)
            destroys.forEach(call);
          if (reading)
            return;
          destroys.forEach(call);
          callback(error);
        });
      });
      return streams.reduce(pipe);
    };
    module2.exports = pump;
  }
});

// ../../node_modules/.pnpm/get-stream@4.1.0/node_modules/get-stream/buffer-stream.js
var require_buffer_stream = __commonJS({
  "../../node_modules/.pnpm/get-stream@4.1.0/node_modules/get-stream/buffer-stream.js"(exports, module2) {
    "use strict";
    var { PassThrough } = require("stream");
    module2.exports = (options) => {
      options = Object.assign({}, options);
      const { array } = options;
      let { encoding } = options;
      const buffer = encoding === "buffer";
      let objectMode = false;
      if (array) {
        objectMode = !(encoding || buffer);
      } else {
        encoding = encoding || "utf8";
      }
      if (buffer) {
        encoding = null;
      }
      let len = 0;
      const ret = [];
      const stream = new PassThrough({ objectMode });
      if (encoding) {
        stream.setEncoding(encoding);
      }
      stream.on("data", (chunk) => {
        ret.push(chunk);
        if (objectMode) {
          len = ret.length;
        } else {
          len += chunk.length;
        }
      });
      stream.getBufferedValue = () => {
        if (array) {
          return ret;
        }
        return buffer ? Buffer.concat(ret, len) : ret.join("");
      };
      stream.getBufferedLength = () => len;
      return stream;
    };
  }
});

// ../../node_modules/.pnpm/get-stream@4.1.0/node_modules/get-stream/index.js
var require_get_stream = __commonJS({
  "../../node_modules/.pnpm/get-stream@4.1.0/node_modules/get-stream/index.js"(exports, module2) {
    "use strict";
    var pump = require_pump();
    var bufferStream = require_buffer_stream();
    var MaxBufferError = class extends Error {
      constructor() {
        super("maxBuffer exceeded");
        this.name = "MaxBufferError";
      }
    };
    function getStream(inputStream, options) {
      if (!inputStream) {
        return Promise.reject(new Error("Expected a stream"));
      }
      options = Object.assign({ maxBuffer: Infinity }, options);
      const { maxBuffer } = options;
      let stream;
      return new Promise((resolve2, reject) => {
        const rejectPromise = (error) => {
          if (error) {
            error.bufferedData = stream.getBufferedValue();
          }
          reject(error);
        };
        stream = pump(inputStream, bufferStream(options), (error) => {
          if (error) {
            rejectPromise(error);
            return;
          }
          resolve2();
        });
        stream.on("data", () => {
          if (stream.getBufferedLength() > maxBuffer) {
            rejectPromise(new MaxBufferError());
          }
        });
      }).then(() => stream.getBufferedValue());
    }
    module2.exports = getStream;
    module2.exports.buffer = (stream, options) => getStream(stream, Object.assign({}, options, { encoding: "buffer" }));
    module2.exports.array = (stream, options) => getStream(stream, Object.assign({}, options, { array: true }));
    module2.exports.MaxBufferError = MaxBufferError;
  }
});

// ../../node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js
var require_p_finally = __commonJS({
  "../../node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js"(exports, module2) {
    "use strict";
    module2.exports = (promise, onFinally) => {
      onFinally = onFinally || (() => {
      });
      return promise.then(
        (val) => new Promise((resolve2) => {
          resolve2(onFinally());
        }).then(() => val),
        (err) => new Promise((resolve2) => {
          resolve2(onFinally());
        }).then(() => {
          throw err;
        })
      );
    };
  }
});

// ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js
var require_signals = __commonJS({
  "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js"(exports, module2) {
    module2.exports = [
      "SIGABRT",
      "SIGALRM",
      "SIGHUP",
      "SIGINT",
      "SIGTERM"
    ];
    if (process.platform !== "win32") {
      module2.exports.push(
        "SIGVTALRM",
        "SIGXCPU",
        "SIGXFSZ",
        "SIGUSR2",
        "SIGTRAP",
        "SIGSYS",
        "SIGQUIT",
        "SIGIOT"
        // should detect profiler and enable/disable accordingly.
        // see #21
        // 'SIGPROF'
      );
    }
    if (process.platform === "linux") {
      module2.exports.push(
        "SIGIO",
        "SIGPOLL",
        "SIGPWR",
        "SIGSTKFLT",
        "SIGUNUSED"
      );
    }
  }
});

// ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js
var require_signal_exit = __commonJS({
  "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js"(exports, module2) {
    var process2 = global.process;
    var processOk = function(process3) {
      return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
    };
    if (!processOk(process2)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert = require("assert");
      signals = require_signals();
      isWin4 = /^win/i.test(process2.platform);
      EE = require("events");
      if (typeof EE !== "function") {
        EE = EE.EventEmitter;
      }
      if (process2.__signal_exit_emitter__) {
        emitter = process2.__signal_exit_emitter__;
      } else {
        emitter = process2.__signal_exit_emitter__ = new EE();
        emitter.count = 0;
        emitter.emitted = {};
      }
      if (!emitter.infinite) {
        emitter.setMaxListeners(Infinity);
        emitter.infinite = true;
      }
      module2.exports = function(cb, opts) {
        if (!processOk(global.process)) {
          return function() {
          };
        }
        assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
        if (loaded === false) {
          load();
        }
        var ev = "exit";
        if (opts && opts.alwaysLast) {
          ev = "afterexit";
        }
        var remove = function() {
          emitter.removeListener(ev, cb);
          if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
            unload();
          }
        };
        emitter.on(ev, cb);
        return remove;
      };
      unload = function unload2() {
        if (!loaded || !processOk(global.process)) {
          return;
        }
        loaded = false;
        signals.forEach(function(sig) {
          try {
            process2.removeListener(sig, sigListeners[sig]);
          } catch (er) {
          }
        });
        process2.emit = originalProcessEmit;
        process2.reallyExit = originalProcessReallyExit;
        emitter.count -= 1;
      };
      module2.exports.unload = unload;
      emit = function emit2(event, code, signal) {
        if (emitter.emitted[event]) {
          return;
        }
        emitter.emitted[event] = true;
        emitter.emit(event, code, signal);
      };
      sigListeners = {};
      signals.forEach(function(sig) {
        sigListeners[sig] = function listener() {
          if (!processOk(global.process)) {
            return;
          }
          var listeners = process2.listeners(sig);
          if (listeners.length === emitter.count) {
            unload();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin4 && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process2.kill(process2.pid, sig);
          }
        };
      });
      module2.exports.signals = function() {
        return signals;
      };
      loaded = false;
      load = function load2() {
        if (loaded || !processOk(global.process)) {
          return;
        }
        loaded = true;
        emitter.count += 1;
        signals = signals.filter(function(sig) {
          try {
            process2.on(sig, sigListeners[sig]);
            return true;
          } catch (er) {
            return false;
          }
        });
        process2.emit = processEmit;
        process2.reallyExit = processReallyExit;
      };
      module2.exports.load = load;
      originalProcessReallyExit = process2.reallyExit;
      processReallyExit = function processReallyExit2(code) {
        if (!processOk(global.process)) {
          return;
        }
        process2.exitCode = code || /* istanbul ignore next */
        0;
        emit("exit", process2.exitCode, null);
        emit("afterexit", process2.exitCode, null);
        originalProcessReallyExit.call(process2, process2.exitCode);
      };
      originalProcessEmit = process2.emit;
      processEmit = function processEmit2(ev, arg) {
        if (ev === "exit" && processOk(global.process)) {
          if (arg !== void 0) {
            process2.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process2.exitCode, null);
          emit("afterexit", process2.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      };
    }
    var assert;
    var signals;
    var isWin4;
    var EE;
    var emitter;
    var unload;
    var emit;
    var sigListeners;
    var loaded;
    var load;
    var originalProcessReallyExit;
    var processReallyExit;
    var originalProcessEmit;
    var processEmit;
  }
});

// ../../node_modules/.pnpm/execa@1.0.0/node_modules/execa/lib/errname.js
var require_errname = __commonJS({
  "../../node_modules/.pnpm/execa@1.0.0/node_modules/execa/lib/errname.js"(exports, module2) {
    "use strict";
    var util = require("util");
    var uv;
    if (typeof util.getSystemErrorName === "function") {
      module2.exports = util.getSystemErrorName;
    } else {
      try {
        uv = process.binding("uv");
        if (typeof uv.errname !== "function") {
          throw new TypeError("uv.errname is not a function");
        }
      } catch (err) {
        console.error("execa/lib/errname: unable to establish process.binding('uv')", err);
        uv = null;
      }
      module2.exports = (code) => errname(uv, code);
    }
    module2.exports.__test__ = errname;
    function errname(uv2, code) {
      if (uv2) {
        return uv2.errname(code);
      }
      if (!(code < 0)) {
        throw new Error("err >= 0");
      }
      return `Unknown system error ${code}`;
    }
  }
});

// ../../node_modules/.pnpm/execa@1.0.0/node_modules/execa/lib/stdio.js
var require_stdio = __commonJS({
  "../../node_modules/.pnpm/execa@1.0.0/node_modules/execa/lib/stdio.js"(exports, module2) {
    "use strict";
    var alias = ["stdin", "stdout", "stderr"];
    var hasAlias = (opts) => alias.some((x) => Boolean(opts[x]));
    module2.exports = (opts) => {
      if (!opts) {
        return null;
      }
      if (opts.stdio && hasAlias(opts)) {
        throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map((x) => `\`${x}\``).join(", ")}`);
      }
      if (typeof opts.stdio === "string") {
        return opts.stdio;
      }
      const stdio = opts.stdio || [];
      if (!Array.isArray(stdio)) {
        throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
      }
      const result = [];
      const len = Math.max(stdio.length, alias.length);
      for (let i = 0; i < len; i++) {
        let value = null;
        if (stdio[i] !== void 0) {
          value = stdio[i];
        } else if (opts[alias[i]] !== void 0) {
          value = opts[alias[i]];
        }
        result[i] = value;
      }
      return result;
    };
  }
});

// ../../node_modules/.pnpm/execa@1.0.0/node_modules/execa/index.js
var require_execa = __commonJS({
  "../../node_modules/.pnpm/execa@1.0.0/node_modules/execa/index.js"(exports, module2) {
    "use strict";
    var path = require("path");
    var childProcess = require("child_process");
    var crossSpawn = require_cross_spawn();
    var stripEof = require_strip_eof();
    var npmRunPath = require_npm_run_path();
    var isStream = require_is_stream();
    var _getStream = require_get_stream();
    var pFinally = require_p_finally();
    var onExit = require_signal_exit();
    var errname = require_errname();
    var stdio = require_stdio();
    var TEN_MEGABYTES = 1e3 * 1e3 * 10;
    function handleArgs(cmd, args, opts) {
      let parsed;
      opts = Object.assign({
        extendEnv: true,
        env: {}
      }, opts);
      if (opts.extendEnv) {
        opts.env = Object.assign({}, process.env, opts.env);
      }
      if (opts.__winShell === true) {
        delete opts.__winShell;
        parsed = {
          command: cmd,
          args,
          options: opts,
          file: cmd,
          original: {
            cmd,
            args
          }
        };
      } else {
        parsed = crossSpawn._parse(cmd, args, opts);
      }
      opts = Object.assign({
        maxBuffer: TEN_MEGABYTES,
        buffer: true,
        stripEof: true,
        preferLocal: true,
        localDir: parsed.options.cwd || process.cwd(),
        encoding: "utf8",
        reject: true,
        cleanup: true
      }, parsed.options);
      opts.stdio = stdio(opts);
      if (opts.preferLocal) {
        opts.env = npmRunPath.env(Object.assign({}, opts, { cwd: opts.localDir }));
      }
      if (opts.detached) {
        opts.cleanup = false;
      }
      if (process.platform === "win32" && path.basename(parsed.command) === "cmd.exe") {
        parsed.args.unshift("/q");
      }
      return {
        cmd: parsed.command,
        args: parsed.args,
        opts,
        parsed
      };
    }
    function handleInput(spawned, input) {
      if (input === null || input === void 0) {
        return;
      }
      if (isStream(input)) {
        input.pipe(spawned.stdin);
      } else {
        spawned.stdin.end(input);
      }
    }
    function handleOutput(opts, val) {
      if (val && opts.stripEof) {
        val = stripEof(val);
      }
      return val;
    }
    function handleShell(fn, cmd, opts) {
      let file = "/bin/sh";
      let args = ["-c", cmd];
      opts = Object.assign({}, opts);
      if (process.platform === "win32") {
        opts.__winShell = true;
        file = process.env.comspec || "cmd.exe";
        args = ["/s", "/c", `"${cmd}"`];
        opts.windowsVerbatimArguments = true;
      }
      if (opts.shell) {
        file = opts.shell;
        delete opts.shell;
      }
      return fn(file, args, opts);
    }
    function getStream(process2, stream, { encoding, buffer, maxBuffer }) {
      if (!process2[stream]) {
        return null;
      }
      let ret;
      if (!buffer) {
        ret = new Promise((resolve2, reject) => {
          process2[stream].once("end", resolve2).once("error", reject);
        });
      } else if (encoding) {
        ret = _getStream(process2[stream], {
          encoding,
          maxBuffer
        });
      } else {
        ret = _getStream.buffer(process2[stream], { maxBuffer });
      }
      return ret.catch((err) => {
        err.stream = stream;
        err.message = `${stream} ${err.message}`;
        throw err;
      });
    }
    function makeError(result, options) {
      const { stdout, stderr } = result;
      let err = result.error;
      const { code, signal } = result;
      const { parsed, joinedCmd } = options;
      const timedOut = options.timedOut || false;
      if (!err) {
        let output = "";
        if (Array.isArray(parsed.opts.stdio)) {
          if (parsed.opts.stdio[2] !== "inherit") {
            output += output.length > 0 ? stderr : `
${stderr}`;
          }
          if (parsed.opts.stdio[1] !== "inherit") {
            output += `
${stdout}`;
          }
        } else if (parsed.opts.stdio !== "inherit") {
          output = `
${stderr}${stdout}`;
        }
        err = new Error(`Command failed: ${joinedCmd}${output}`);
        err.code = code < 0 ? errname(code) : code;
      }
      err.stdout = stdout;
      err.stderr = stderr;
      err.failed = true;
      err.signal = signal || null;
      err.cmd = joinedCmd;
      err.timedOut = timedOut;
      return err;
    }
    function joinCmd(cmd, args) {
      let joinedCmd = cmd;
      if (Array.isArray(args) && args.length > 0) {
        joinedCmd += " " + args.join(" ");
      }
      return joinedCmd;
    }
    module2.exports = (cmd, args, opts) => {
      const parsed = handleArgs(cmd, args, opts);
      const { encoding, buffer, maxBuffer } = parsed.opts;
      const joinedCmd = joinCmd(cmd, args);
      let spawned;
      try {
        spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts);
      } catch (err) {
        return Promise.reject(err);
      }
      let removeExitHandler;
      if (parsed.opts.cleanup) {
        removeExitHandler = onExit(() => {
          spawned.kill();
        });
      }
      let timeoutId = null;
      let timedOut = false;
      const cleanup = () => {
        if (timeoutId) {
          clearTimeout(timeoutId);
          timeoutId = null;
        }
        if (removeExitHandler) {
          removeExitHandler();
        }
      };
      if (parsed.opts.timeout > 0) {
        timeoutId = setTimeout(() => {
          timeoutId = null;
          timedOut = true;
          spawned.kill(parsed.opts.killSignal);
        }, parsed.opts.timeout);
      }
      const processDone = new Promise((resolve2) => {
        spawned.on("exit", (code, signal) => {
          cleanup();
          resolve2({ code, signal });
        });
        spawned.on("error", (err) => {
          cleanup();
          resolve2({ error: err });
        });
        if (spawned.stdin) {
          spawned.stdin.on("error", (err) => {
            cleanup();
            resolve2({ error: err });
          });
        }
      });
      function destroy() {
        if (spawned.stdout) {
          spawned.stdout.destroy();
        }
        if (spawned.stderr) {
          spawned.stderr.destroy();
        }
      }
      const handlePromise = () => pFinally(Promise.all([
        processDone,
        getStream(spawned, "stdout", { encoding, buffer, maxBuffer }),
        getStream(spawned, "stderr", { encoding, buffer, maxBuffer })
      ]).then((arr) => {
        const result = arr[0];
        result.stdout = arr[1];
        result.stderr = arr[2];
        if (result.error || result.code !== 0 || result.signal !== null) {
          const err = makeError(result, {
            joinedCmd,
            parsed,
            timedOut
          });
          err.killed = err.killed || spawned.killed;
          if (!parsed.opts.reject) {
            return err;
          }
          throw err;
        }
        return {
          stdout: handleOutput(parsed.opts, result.stdout),
          stderr: handleOutput(parsed.opts, result.stderr),
          code: 0,
          failed: false,
          killed: false,
          signal: null,
          cmd: joinedCmd,
          timedOut: false
        };
      }), destroy);
      crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
      handleInput(spawned, parsed.opts.input);
      spawned.then = (onfulfilled, onrejected) => handlePromise().then(onfulfilled, onrejected);
      spawned.catch = (onrejected) => handlePromise().catch(onrejected);
      return spawned;
    };
    module2.exports.stdout = (...args) => module2.exports(...args).then((x) => x.stdout);
    module2.exports.stderr = (...args) => module2.exports(...args).then((x) => x.stderr);
    module2.exports.shell = (cmd, opts) => handleShell(module2.exports, cmd, opts);
    module2.exports.sync = (cmd, args, opts) => {
      const parsed = handleArgs(cmd, args, opts);
      const joinedCmd = joinCmd(cmd, args);
      if (isStream(parsed.opts.input)) {
        throw new TypeError("The `input` option cannot be a stream in sync mode");
      }
      const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts);
      result.code = result.status;
      if (result.error || result.status !== 0 || result.signal !== null) {
        const err = makeError(result, {
          joinedCmd,
          parsed
        });
        if (!parsed.opts.reject) {
          return err;
        }
        throw err;
      }
      return {
        stdout: handleOutput(parsed.opts, result.stdout),
        stderr: handleOutput(parsed.opts, result.stderr),
        code: 0,
        failed: false,
        signal: null,
        cmd: joinedCmd,
        timedOut: false
      };
    };
    module2.exports.shellSync = (cmd, opts) => handleShell(module2.exports.sync, cmd, opts);
  }
});

// ../../node_modules/.pnpm/which@3.0.0/node_modules/which/lib/index.js
var require_lib = __commonJS({
  "../../node_modules/.pnpm/which@3.0.0/node_modules/which/lib/index.js"(exports, module2) {
    var isexe = require_isexe();
    var { join: join7, delimiter, sep, posix } = require("path");
    var isWindows = process.platform === "win32";
    var rSlash = new RegExp(`[${posix.sep}${sep === posix.sep ? "" : sep}]`.replace(/(\\)/g, "\\$1"));
    var rRel = new RegExp(`^\\.${rSlash.source}`);
    var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
    var getPathInfo = (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);
        if (cmd.includes(".") && pathExt[0] !== "") {
          pathExt.unshift("");
        }
        return { pathEnv, pathExt, pathExtExe };
      }
      return { pathEnv, pathExt: [""] };
    };
    var getPathPart = (raw, cmd) => {
      const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
      const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
      return prefix + join7(pathPart, cmd);
    };
    var which2 = 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);
    };
    var whichSync = (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 = isexe.sync(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);
    };
    module2.exports = which2;
    which2.sync = whichSync;
  }
});

// src/index.ts
var src_exports = {};
__export(src_exports, {
  build: () => build,
  defaultShouldServe: () => defaultShouldServe,
  downloadFilesInWorkPath: () => downloadFilesInWorkPath,
  installRequirement: () => installRequirement,
  installRequirementsFile: () => installRequirementsFile,
  shouldServe: () => shouldServe,
  startDevServer: () => startDevServer,
  version: () => version
});
module.exports = __toCommonJS(src_exports);
var import_fs5 = __toESM(require("fs"));
var import_util = require("util");
var import_path7 = require("path");
var import_build_utils8 = require("@vercel/build-utils");

// src/install.ts
var import_execa3 = __toESM(require_execa());
var import_fs3 = __toESM(require("fs"));
var import_os2 = __toESM(require("os"));
var import_path4 = require("path");
var import_build_utils4 = require("@vercel/build-utils");

// src/utils.ts
var import_fs2 = __toESM(require("fs"));
var import_path3 = require("path");
var import_build_utils2 = require("@vercel/build-utils");
var import_execa2 = __toESM(require_execa());

// src/uv.ts
var import_child_process = require("child_process");
var import_path = require("path");
var import_path2 = require("path");
var import_execa = __toESM(require_execa());
var import_fs = __toESM(require("fs"));
var import_os = __toESM(require("os"));
var import_which = __toESM(require_lib());
var import_build_utils = require("@vercel/build-utils");
var UV_VERSION = "0.9.22";
var UV_PYTHON_PATH_PREFIX = "/uv/python/";
var UV_PYTHON_DOWNLOADS_MODE = "automatic";
var isWin = process.platform === "win32";
var uvExec = isWin ? "uv.exe" : "uv";
function findUvInPath() {
  return import_which.default.sync("uv", { nothrow: true });
}
var UvRunner = class {
  constructor(uvPath) {
    this.uvPath = uvPath;
  }
  getPath() {
    return this.uvPath;
  }
  /**
   * List installed Python versions managed by uv.
   * Excludes system Python.
   */
  listInstalledPythons() {
    let output;
    try {
      output = (0, import_child_process.execSync)(
        `${this.uvPath} python list --only-installed --output-format json`,
        { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }
      );
    } catch (err) {
      throw new Error(
        `Failed to run 'uv python list': ${err instanceof Error ? err.message : String(err)}`
      );
    }
    if (!output || output.trim() === "" || output.trim() === "[]") {
      return /* @__PURE__ */ new Set();
    }
    let pyList;
    try {
      pyList = JSON.parse(output);
    } catch (err) {
      throw new Error(
        `Failed to parse 'uv python list' output: ${err instanceof Error ? err.message : String(err)}`
      );
    }
    return new Set(
      pyList.filter(
        (entry) => entry.path !== null && entry.path.startsWith(UV_PYTHON_PATH_PREFIX) && entry.implementation === "cpython"
      ).map(
        (entry) => `${entry.version_parts.major}.${entry.version_parts.minor}`
      )
    );
  }
  async sync(options) {
    const { venvPath, projectDir, locked } = options;
    const args = ["sync", "--active", "--no-dev", "--link-mode", "copy"];
    if (locked) {
      args.push("--locked");
    }
    args.push("--no-editable");
    await this.runUvCmd(args, projectDir, venvPath);
  }
  async lock(projectDir) {
    const args = ["lock"];
    const pretty = `uv ${args.join(" ")}`;
    (0, import_build_utils.debug)(`Running "${pretty}" in ${projectDir}...`);
    try {
      await (0, import_execa.default)(this.uvPath, args, {
        cwd: projectDir,
        env: getProtectedUvEnv(process.env)
      });
    } catch (err) {
      throw new Error(
        `Failed to run "${pretty}": ${err instanceof Error ? err.message : String(err)}`
      );
    }
  }
  async addDependencies(options) {
    const { venvPath, projectDir, dependencies } = options;
    const toAdd = dependencies.filter(Boolean);
    if (!toAdd.length)
      return;
    const args = ["add", "--active", ...toAdd];
    (0, import_build_utils.debug)(`Running "uv ${args.join(" ")}" in ${projectDir}...`);
    await this.runUvCmd(args, projectDir, venvPath);
  }
  async addFromFile(options) {
    const { venvPath, projectDir, requirementsPath } = options;
    const args = ["add", "--active", "-r", requirementsPath];
    (0, import_build_utils.debug)(`Running "uv ${args.join(" ")}" in ${projectDir}...`);
    await this.runUvCmd(args, projectDir, venvPath);
  }
  async runUvCmd(args, cwd, venvPath) {
    const pretty = `uv ${args.join(" ")}`;
    (0, import_build_utils.debug)(`Running "${pretty}"...`);
    try {
      await (0, import_execa.default)(this.uvPath, args, {
        cwd,
        env: this.getVenvEnv(venvPath)
      });
    } catch (err) {
      const error = new Error(
        `Failed to run "${pretty}": ${err instanceof Error ? err.message : String(err)}`
      );
      if (err && typeof err === "object") {
        if ("code" in err) {
          error.code = err.code;
        } else if ("signal" in err) {
          error.code = err.signal;
        }
      }
      throw error;
    }
  }
  getVenvEnv(venvPath) {
    const binDir = isWin ? (0, import_path.join)(venvPath, "Scripts") : (0, import_path.join)(venvPath, "bin");
    const existingPath = process.env.PATH || "";
    return {
      ...getProtectedUvEnv(process.env),
      VIRTUAL_ENV: venvPath,
      PATH: existingPath ? `${binDir}${import_path2.delimiter}${existingPath}` : binDir
    };
  }
};
async function getGlobalScriptsDir(pythonPath) {
  const code = `import sysconfig; print(sysconfig.get_path('scripts'))`;
  try {
    const { stdout } = await (0, import_execa.default)(pythonPath, ["-c", code]);
    const out = stdout.trim();
    return out || null;
  } catch (err) {
    (0, import_build_utils.debug)("Failed to resolve Python global scripts directory", err);
    return null;
  }
}
async function getUserScriptsDir(pythonPath) {
  const code = `import sys, sysconfig; print(sysconfig.get_path('scripts', scheme=('nt_user' if sys.platform == 'win32' else 'posix_user')))`.replace(
    /\n/g,
    " "
  );
  try {
    const { stdout } = await (0, import_execa.default)(pythonPath, ["-c", code]);
    const out = stdout.trim();
    return out || null;
  } catch (err) {
    (0, import_build_utils.debug)("Failed to resolve Python user scripts directory", err);
    return null;
  }
}
async function findUvBinary(pythonPath) {
  const found = import_which.default.sync("uv", { nothrow: true });
  if (found)
    return found;
  try {
    const globalScriptsDir = await getGlobalScriptsDir(pythonPath);
    if (globalScriptsDir) {
      const uvPath = (0, import_path.join)(globalScriptsDir, uvExec);
      if (import_fs.default.existsSync(uvPath))
        return uvPath;
    }
  } catch (err) {
    (0, import_build_utils.debug)("Failed to resolve Python global scripts directory", err);
  }
  try {
    const userScriptsDir = await getUserScriptsDir(pythonPath);
    if (userScriptsDir) {
      const uvPath = (0, import_path.join)(userScriptsDir, uvExec);
      if (import_fs.default.existsSync(uvPath))
        return uvPath;
    }
  } catch (err) {
    (0, import_build_utils.debug)("Failed to resolve Python user scripts directory", err);
  }
  try {
    const candidates = [];
    if (!isWin) {
      candidates.push((0, import_path.join)(import_os.default.homedir(), ".local", "bin", "uv"));
      candidates.push("/usr/local/bin/uv");
      candidates.push("/opt/homebrew/bin/uv");
    } else {
      candidates.push("C:\\Users\\Public\\uv\\uv.exe");
    }
    for (const p of candidates) {
      if (import_fs.default.existsSync(p))
        return p;
    }
  } catch (err) {
    (0, import_build_utils.debug)("Failed to resolve uv fallback paths", err);
  }
  return null;
}
async function getUvBinaryOrInstall(pythonPath) {
  const uvBin = await findUvBinary(pythonPath);
  if (uvBin)
    return uvBin;
  try {
    console.log("Installing uv...");
    await (0, import_execa.default)(
      pythonPath,
      [
        "-m",
        "pip",
        "install",
        "--disable-pip-version-check",
        "--no-cache-dir",
        "--user",
        `uv==${UV_VERSION}`
      ],
      { env: { ...process.env, PIP_USER: "1" } }
    );
  } catch (err) {
    throw new Error(
      `Failed to install uv via pip: ${err instanceof Error ? err.message : String(err)}`
    );
  }
  const resolvedUvBin = await findUvBinary(pythonPath);
  if (!resolvedUvBin) {
    throw new Error("Unable to resolve uv binary after pip install");
  }
  console.log(`Installed uv at "${resolvedUvBin}"`);
  return resolvedUvBin;
}
function filterUnsafeUvPipArgs(args) {
  return args.filter((arg) => arg !== "--no-warn-script-location");
}
function getProtectedUvEnv(baseEnv = process.env) {
  return {
    ...baseEnv,
    UV_PYTHON_DOWNLOADS: UV_PYTHON_DOWNLOADS_MODE
  };
}

// src/utils.ts
var isWin2 = process.platform === "win32";
var isInVirtualEnv = () => {
  return process.env.VIRTUAL_ENV;
};
function getVenvBinDir(venvPath) {
  return (0, import_path3.join)(venvPath, isWin2 ? "Scripts" : "bin");
}
function useVirtualEnv(workPath, env, systemPython) {
  const venvDirs = [".venv", "venv"];
  let pythonCmd = systemPython;
  for (const venv of venvDirs) {
    const venvRoot = (0, import_path3.join)(workPath, venv);
    const binDir = process.platform === "win32" ? (0, import_path3.join)(venvRoot, "Scripts") : (0, import_path3.join)(venvRoot, "bin");
    const candidates = process.platform === "win32" ? [(0, import_path3.join)(binDir, "python.exe"), (0, import_path3.join)(binDir, "python")] : [(0, import_path3.join)(binDir, "python3"), (0, import_path3.join)(binDir, "python")];
    const found = candidates.find((p) => import_fs2.default.existsSync(p));
    if (found) {
      pythonCmd = found;
      env.VIRTUAL_ENV = venvRoot;
      env.PATH = `${binDir}${import_path3.delimiter}${env.PATH || ""}`;
      return { pythonCmd, venvRoot };
    }
  }
  return { pythonCmd };
}
function createVenvEnv(venvPath, baseEnv = process.env) {
  const env = {
    ...getProtectedUvEnv(baseEnv),
    VIRTUAL_ENV: venvPath
  };
  const binDir = getVenvBinDir(venvPath);
  const existingPath = env.PATH || process.env.PATH || "";
  env.PATH = existingPath ? `${binDir}${import_path3.delimiter}${existingPath}` : binDir;
  return env;
}
async function ensureVenv({
  pythonPath,
  venvPath
}) {
  const marker = (0, import_path3.join)(venvPath, "pyvenv.cfg");
  try {
    await import_fs2.default.promises.access(marker);
    return;
  } catch {
  }
  await import_fs2.default.promises.mkdir(venvPath, { recursive: true });
  console.log(`Creating virtual environment at "${venvPath}"...`);
  await (0, import_execa2.default)(pythonPath, ["-m", "venv", venvPath]);
}
function getVenvPythonBin(venvPath) {
  return (0, import_path3.join)(getVenvBinDir(venvPath), isWin2 ? "python.exe" : "python");
}
async function runPyprojectScript(workPath, scriptNames, env, useUserVirtualEnv = true) {
  const pyprojectPath = (0, import_path3.join)(workPath, "pyproject.toml");
  if (!import_fs2.default.existsSync(pyprojectPath))
    return false;
  let pyproject = null;
  try {
    pyproject = await (0, import_build_utils2.readConfigFile)(pyprojectPath);
  } catch {
    console.error("Failed to parse pyproject.toml");
    return false;
  }
  const scripts = pyproject?.tool?.vercel?.scripts || {};
  const candidates = typeof scriptNames === "string" ? [scriptNames] : Array.from(scriptNames);
  const scriptToRun = candidates.find((name) => Boolean(scripts[name]));
  if (!scriptToRun)
    return false;
  const systemPython = process.platform === "win32" ? "python" : "python3";
  const finalEnv = { ...process.env, ...env };
  if (useUserVirtualEnv) {
    useVirtualEnv(workPath, finalEnv, systemPython);
  }
  const scriptCommand = scripts[scriptToRun];
  if (typeof scriptCommand === "string" && scriptCommand.trim()) {
    console.log(`Executing: ${scriptCommand}`);
    await (0, import_build_utils2.execCommand)(scriptCommand, {
      cwd: workPath,
      env: finalEnv
    });
    return true;
  }
  return false;
}
function findDir({
  file,
  entryDirectory,
  workPath,
  fsFiles
}) {
  if (fsFiles[(0, import_path3.join)(entryDirectory, file)]) {
    return (0, import_path3.join)(workPath, entryDirectory);
  }
  if (fsFiles[file]) {
    return workPath;
  }
  return null;
}

// src/version.ts
var import_build_utils3 = require("@vercel/build-utils");
var DEFAULT_PYTHON_VERSION = "3.12";
var allOptions = [
  {
    version: "3.14",
    pipPath: "pip3.14",
    pythonPath: "python3.14",
    runtime: "python3.14"
  },
  {
    version: "3.13",
    pipPath: "pip3.13",
    pythonPath: "python3.13",
    runtime: "python3.13"
  },
  {
    version: "3.12",
    pipPath: "pip3.12",
    pythonPath: "python3.12",
    runtime: "python3.12"
  },
  {
    version: "3.11",
    pipPath: "pip3.11",
    pythonPath: "python3.11",
    runtime: "python3.11"
  },
  {
    version: "3.10",
    pipPath: "pip3.10",
    pythonPath: "python3.10",
    runtime: "python3.10"
  },
  {
    version: "3.9",
    pipPath: "pip3.9",
    pythonPath: "python3.9",
    runtime: "python3.9"
  },
  {
    version: "3.6",
    pipPath: "pip3.6",
    pythonPath: "python3.6",
    runtime: "python3.6",
    discontinueDate: /* @__PURE__ */ new Date("2022-07-18")
  }
];
function getDevPythonVersion() {
  return {
    version: "3",
    pipPath: "pip3",
    pythonPath: "python3",
    runtime: "python3"
  };
}
function getDefaultPythonVersion({
  isDev
}) {
  if (isDev) {
    return getDevPythonVersion();
  }
  const defaultOption = allOptions.find(
    (opt) => opt.version === DEFAULT_PYTHON_VERSION && isInstalled(opt)
  );
  if (defaultOption) {
    return defaultOption;
  }
  const selection = allOptions.find(isInstalled);
  if (!selection) {
    throw new import_build_utils3.NowBuildError({
      code: "PYTHON_NOT_FOUND",
      link: "https://vercel.link/python-version",
      message: `Unable to find any supported Python versions.`
    });
  }
  return selection;
}
function parseVersionTuple(input) {
  const cleaned = input.trim().replace(/\s+/g, "");
  const m = cleaned.match(/^(\d+)(?:\.(\d+))?/);
  if (!m)
    return null;
  const major = Number(m[1]);
  const minor = m[2] !== void 0 ? Number(m[2]) : 0;
  if (Number.isNaN(major) || Number.isNaN(minor))
    return null;
  return [major, minor];
}
function compareTuples(a, b) {
  if (a[0] !== b[0])
    return a[0] - b[0];
  return a[1] - b[1];
}
function parseSpecifier(spec) {
  const s = spec.trim();
  const m = s.match(
    /^(<=|>=|==|!=|~=|<|>)\s*([0-9]+(?:\.[0-9]+)?)(?:\.[0-9]+)?(?:\.\*)?$/
  ) || // Bare version like "3.11" or "3.11.4" -> implied ==
  s.match(/^()([0-9]+(?:\.[0-9]+)?)(?:\.[0-9]+)?(?:\.\*)?$/);
  if (!m)
    return null;
  const op = m[1] || "==";
  const vt = parseVersionTuple(m[2]);
  if (!vt)
    return null;
  return { op, ver: vt };
}
function satisfies(candidate, spec) {
  const cmp = compareTuples(candidate, spec.ver);
  switch (spec.op) {
    case "==":
      return cmp === 0;
    case "!=":
      return cmp !== 0;
    case "<":
      return cmp < 0;
    case "<=":
      return cmp <= 0;
    case ">":
      return cmp > 0;
    case ">=":
      return cmp >= 0;
    case "~=": {
      const lowerOk = cmp >= 0;
      const upper = [spec.ver[0], spec.ver[1] + 1];
      return lowerOk && compareTuples(candidate, upper) < 0;
    }
    default:
      return false;
  }
}
function selectFromRequiresPython(expr) {
  const raw = expr.trim();
  if (!raw)
    return void 0;
  const parts = raw.split(",").map((p) => p.trim()).filter(Boolean);
  const specifiers = [];
  for (const p of parts) {
    const sp = parseSpecifier(p);
    if (sp)
      specifiers.push(sp);
  }
  if (specifiers.length === 0) {
    return allOptions.find((o) => o.version === raw);
  }
  const matches = allOptions.filter((opt) => {
    const vt = parseVersionTuple(opt.version);
    return specifiers.every((sp) => satisfies(vt, sp));
  });
  if (matches.length === 0)
    return void 0;
  const defaultMatch = matches.find(
    (opt) => opt.version === DEFAULT_PYTHON_VERSION && isInstalled(opt)
  );
  if (defaultMatch) {
    return defaultMatch;
  }
  const installedMatch = matches.find(isInstalled);
  return installedMatch ?? matches[0];
}
function getSupportedPythonVersion({
  isDev,
  declaredPythonVersion
}) {
  if (isDev) {
    return getDevPythonVersion();
  }
  let selection = getDefaultPythonVersion({ isDev: false });
  if (declaredPythonVersion) {
    const { version: version2, source } = declaredPythonVersion;
    let requested;
    if (source === "pyproject.toml" || source === ".python-version") {
      requested = selectFromRequiresPython(version2);
    } else {
      requested = allOptions.find((o) => o.version === version2);
    }
    if (requested) {
      if (isDiscontinued(requested)) {
        throw new import_build_utils3.NowBuildError({
          code: "BUILD_UTILS_PYTHON_VERSION_DISCONTINUED",
          link: "https://vercel.link/python-version",
          message: `Python version "${requested.version}" detected in ${source} is discontinued and must be upgraded.`
        });
      }
      if (isInstalled(requested)) {
        selection = requested;
        console.log(`Using Python ${selection.version} from ${source}`);
      } else {
        console.warn(
          `Warning: Python version "${version2}" detected in ${source} is not installed and will be ignored. https://vercel.link/python-version`
        );
        console.log(`Using python version: ${selection.version}`);
      }
    } else {
      console.warn(
        `Warning: Python version "${version2}" detected in ${source} is invalid and will be ignored. https://vercel.link/python-version`
      );
      console.log(`Using python version: ${selection.version}`);
    }
  } else {
    console.log(
      `No Python version specified in .python-version, pyproject.toml, or Pipfile.lock. Using python version: ${selection.version}`
    );
  }
  if (isDiscontinued(selection)) {
    throw new import_build_utils3.NowBuildError({
      code: "BUILD_UTILS_PYTHON_VERSION_DISCONTINUED",
      link: "https://vercel.link/python-version",
      message: `Python version "${selection.version}" declared in project configuration is discontinued and must be upgraded.`
    });
  }
  if (selection.discontinueDate) {
    const d = selection.discontinueDate.toISOString().split("T")[0];
    const srcSuffix = declaredPythonVersion ? `detected in ${declaredPythonVersion.source}` : "selected by runtime";
    console.warn(
      `Error: Python version "${selection.version}" ${srcSuffix} has reached End-of-Life. Deployments created on or after ${d} will fail to build. https://vercel.link/python-version`
    );
  }
  return selection;
}
function isDiscontinued({ discontinueDate }) {
  const today = Date.now();
  return discontinueDate !== void 0 && discontinueDate.getTime() <= today;
}
var installedPythonsCache = null;
function getInstalledPythons() {
  if (installedPythonsCache !== null) {
    return installedPythonsCache;
  }
  const uvPath = findUvInPath();
  if (!uvPath) {
    throw new import_build_utils3.NowBuildError({
      code: "UV_ERROR",
      link: "https://vercel.link/python-version",
      message: "uv is required but was not found in PATH."
    });
  }
  const uv = new UvRunner(uvPath);
  installedPythonsCache = uv.listInstalledPythons();
  return installedPythonsCache;
}
function isInstalled({ version: version2 }) {
  try {
    const installed = getInstalledPythons();
    return installed.has(version2);
  } catch (err) {
    throw new import_build_utils3.NowBuildError({
      code: "UV_ERROR",
      link: "https://vercel.link/python-version",
      message: err instanceof Error ? err.message : String(err)
    });
  }
}

// src/install.ts
var isWin3 = process.platform === "win32";
var makeDependencyCheckCode = (dependency) => `
from importlib import util
dep = '${dependency}'.replace('-', '_')
spec = util.find_spec(dep)
print(spec.origin)
`;
async function isInstalled2(pythonPath, dependency, cwd) {
  try {
    const { stdout } = await (0, import_execa3.default)(
      pythonPath,
      ["-c", makeDependencyCheckCode(dependency)],
      {
        stdio: "pipe",
        cwd,
        env: { ...process.env, PYTHONPATH: (0, import_path4.join)(cwd, resolveVendorDir()) }
      }
    );
    return stdout.startsWith(cwd);
  } catch (err) {
    return false;
  }
}
var makeRequirementsCheckCode = (requirementsPath) => `
import distutils.text_file
import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict
dependencies = distutils.text_file.TextFile(filename='${requirementsPath}').readlines()
pkg_resources.require(dependencies)
`;
async function areRequirementsInstalled(pythonPath, requirementsPath, cwd) {
  try {
    await (0, import_execa3.default)(
      pythonPath,
      ["-c", makeRequirementsCheckCode(requirementsPath)],
      {
        stdio: "pipe",
        cwd,
        env: { ...process.env, PYTHONPATH: (0, import_path4.join)(cwd, resolveVendorDir()) }
      }
    );
    return true;
  } catch (err) {
    return false;
  }
}
async function getSitePackagesDirs(pythonBin) {
  const code = `
import json
import sysconfig
paths = []
for key in ("purelib", "platlib"):
    candidate = sysconfig.get_path(key)
    if candidate and candidate not in paths:
        paths.append(candidate)
print(json.dumps(paths))
`.trim();
  const { stdout } = await (0, import_execa3.default)(pythonBin, ["-c", code]);
  try {
    const parsed = JSON.parse(stdout);
    if (Array.isArray(parsed)) {
      return parsed.filter((p) => typeof p === "string");
    }
  } catch (err) {
    (0, import_build_utils4.debug)("Failed to parse site-packages output", err);
  }
  return [];
}
async function getVenvSitePackagesDirs(venvPath) {
  const pythonBin = getVenvPythonBin(venvPath);
  return getSitePackagesDirs(pythonBin);
}
function resolveVendorDir() {
  const vendorDir = process.env.VERCEL_PYTHON_VENDOR_DIR || "_vendor";
  return vendorDir;
}
async function detectInstallSource({
  workPath,
  entryDirectory,
  fsFiles
}) {
  const uvLockDir = findDir({
    file: "uv.lock",
    entryDirectory,
    workPath,
    fsFiles
  });
  const pyprojectDir = findDir({
    file: "pyproject.toml",
    entryDirectory,
    workPath,
    fsFiles
  });
  const pipfileLockDir = findDir({
    file: "Pipfile.lock",
    entryDirectory,
    workPath,
    fsFiles
  });
  const pipfileDir = findDir({
    file: "Pipfile",
    entryDirectory,
    workPath,
    fsFiles
  });
  const requirementsDir = findDir({
    file: "requirements.txt",
    entryDirectory,
    workPath,
    fsFiles
  });
  let manifestPath = null;
  let manifestType = null;
  if (uvLockDir && pyprojectDir) {
    manifestType = "uv.lock";
    manifestPath = (0, import_path4.join)(uvLockDir, "uv.lock");
  } else if (pyprojectDir) {
    manifestType = "pyproject.toml";
    manifestPath = (0, import_path4.join)(pyprojectDir, "pyproject.toml");
  } else if (pipfileLockDir) {
    manifestType = "Pipfile.lock";
    manifestPath = (0, import_path4.join)(pipfileLockDir, "Pipfile.lock");
  } else if (pipfileDir) {
    manifestType = "Pipfile";
    manifestPath = (0, import_path4.join)(pipfileDir, "Pipfile");
  } else if (requirementsDir) {
    manifestType = "requirements.txt";
    manifestPath = (0, import_path4.join)(requirementsDir, "requirements.txt");
  }
  let manifestContent;
  if (manifestPath) {
    try {
      manifestContent = await import_fs3.default.promises.readFile(manifestPath, "utf8");
    } catch (err) {
      (0, import_build_utils4.debug)("Failed to read install manifest contents", err);
    }
  }
  return { manifestPath, manifestType, manifestContent };
}
async function createPyprojectToml({
  projectName,
  pyprojectPath,
  dependencies
}) {
  const requiresPython = `~=${DEFAULT_PYTHON_VERSION}.0`;
  const depsToml = dependencies.length > 0 ? [
    "dependencies = [",
    ...dependencies.map((dep) => `  "${dep}",`),
    "]"
  ].join("\n") : "dependencies = []";
  const content = [
    "[project]",
    `name = "${projectName}"`,
    'version = "0.1.0"',
    `requires-python = "${requiresPython}"`,
    "classifiers = [",
    '  "Private :: Do Not Upload",',
    "]",
    depsToml,
    ""
  ].join("\n");
  await import_fs3.default.promises.writeFile(pyprojectPath, content);
}
function getDependencyName(spec) {
  const match = spec.match(/^[A-Za-z0-9_.-]+/);
  return match ? match[0].toLowerCase() : spec.toLowerCase();
}
async function filterMissingRuntimeDependencies({
  pyprojectPath,
  runtimeDependencies
}) {
  let declared = [];
  try {
    const config = await (0, import_build_utils4.readConfigFile)(pyprojectPath);
    declared = config?.project?.dependencies || [];
  } catch (err) {
    (0, import_build_utils4.debug)("Failed to parse pyproject.toml when filtering runtime deps", err);
  }
  const declaredNames = new Set(declared.map(getDependencyName));
  return runtimeDependencies.filter((spec) => {
    const name = getDependencyName(spec);
    return !declaredNames.has(name);
  });
}
function findUvLockUpwards(startDir, repoRootPath) {
  const start = (0, import_path4.resolve)(startDir);
  const base = repoRootPath ? (0, import_path4.resolve)(repoRootPath) : void 0;
  for (const dir of (0, import_build_utils4.traverseUpDirectories)({ start, base })) {
    const lockPath = (0, import_path4.join)(dir, "uv.lock");
    const pyprojectPath = (0, import_path4.join)(dir, "pyproject.toml");
    if (import_fs3.default.existsSync(lockPath) && import_fs3.default.existsSync(pyprojectPath)) {
      return lockPath;
    }
  }
  return null;
}
async function ensureUvProject({
  workPath,
  entryDirectory,
  fsFiles,
  repoRootPath,
  pythonPath,
  pipPath,
  uv,
  venvPath,
  meta,
  runtimeDependencies
}) {
  const uvPath = uv.getPath();
  const installInfo = await detectInstallSource({
    workPath,
    entryDirectory,
    fsFiles
  });
  const { manifestType, manifestPath } = installInfo;
  let projectDir;
  let pyprojectPath;
  let lockPath = null;
  if (manifestType === "uv.lock") {
    if (!manifestPath) {
      throw new Error("Expected uv.lock path to be resolved, but it was null");
    }
    projectDir = (0, import_path4.dirname)(manifestPath);
    pyprojectPath = (0, import_path4.join)(projectDir, "pyproject.toml");
    if (!import_fs3.default.existsSync(pyprojectPath)) {
      throw new Error(
        `Expected "pyproject.toml" next to "uv.lock" in "${projectDir}"`
      );
    }
    lockPath = manifestPath;
    console.log("Installing required dependencies from uv.lock...");
  } else if (manifestType === "pyproject.toml") {
    if (!manifestPath) {
      throw new Error(
        "Expected pyproject.toml path to be resolved, but it was null"
      );
    }
    projectDir = (0, import_path4.dirname)(manifestPath);
    pyprojectPath = manifestPath;
    console.log("Installing required dependencies from pyproject.toml...");
    const workspaceLock = findUvLockUpwards(projectDir, repoRootPath);
    if (workspaceLock) {
      lockPath = workspaceLock;
    } else {
      await uv.lock(projectDir);
    }
  } else if (manifestType === "Pipfile.lock" || manifestType === "Pipfile") {
    if (!manifestPath) {
      throw new Error(
        "Expected Pipfile/Pipfile.lock path to be resolved, but it was null"
      );
    }
    projectDir = (0, import_path4.dirname)(manifestPath);
    console.log(`Installing required dependencies from ${manifestType}...`);
    const exportedReq = await exportRequirementsFromPipfile({
      pythonPath,
      pipPath,
      uvPath,
      projectDir,
      meta
    });
    pyprojectPath = (0, import_path4.join)(projectDir, "pyproject.toml");
    if (!import_fs3.default.existsSync(pyprojectPath)) {
      await createPyprojectToml({
        projectName: "app",
        pyprojectPath,
        dependencies: []
      });
    }
    await uv.addFromFile({
      venvPath,
      projectDir,
      requirementsPath: exportedReq
    });
  } else if (manifestType === "requirements.txt") {
    if (!manifestPath) {
      throw new Error(
        "Expected requirements.txt path to be resolved, but it was null"
      );
    }
    projectDir = (0, import_path4.dirname)(manifestPath);
    pyprojectPath = (0, import_path4.join)(projectDir, "pyproject.toml");
    console.log(
      "Installing required dependencies from requirements.txt with uv..."
    );
    if (!import_fs3.default.existsSync(pyprojectPath)) {
      await createPyprojectToml({
        projectName: "app",
        pyprojectPath,
        dependencies: []
      });
    }
    await uv.addFromFile({
      venvPath,
      projectDir,
      requirementsPath: manifestPath
    });
  } else {
    projectDir = workPath;
    pyprojectPath = (0, import_path4.join)(projectDir, "pyproject.toml");
    console.log(
      "No Python manifest found; creating an empty pyproject.toml and uv.lock..."
    );
    await createPyprojectToml({
      projectName: "app",
      pyprojectPath,
      dependencies: []
    });
    await uv.lock(projectDir);
  }
  if (runtimeDependencies.length) {
    const missingRuntimeDeps = await filterMissingRuntimeDependencies({
      pyprojectPath,
      runtimeDependencies
    });
    if (missingRuntimeDeps.length) {
      await uv.addDependencies({
        venvPath,
        projectDir,
        dependencies: missingRuntimeDeps
      });
    }
  }
  const resolvedLockPath = lockPath && import_fs3.default.existsSync(lockPath) ? lockPath : findUvLockUpwards(projectDir, repoRootPath) || (0, import_path4.join)(projectDir, "uv.lock");
  return { projectDir, pyprojectPath, lockPath: resolvedLockPath };
}
async function pipInstall(pipPath, uvPath, workPath, args, targetDir) {
  const target = targetDir ? (0, import_path4.join)(targetDir, resolveVendorDir()) : resolveVendorDir();
  process.env.PIP_USER = "0";
  if (uvPath) {
    const uvArgs = [
      "pip",
      "install",
      "--no-compile",
      "--no-cache-dir",
      "--target",
      target,
      ...filterUnsafeUvPipArgs(args)
    ];
    const prettyUv = `${uvPath} ${uvArgs.join(" ")}`;
    (0, import_build_utils4.debug)(`Running "${prettyUv}"...`);
    try {
      await (0, import_execa3.default)(uvPath, uvArgs, {
        cwd: workPath,
        env: getProtectedUvEnv()
      });
      return;
    } catch (err) {
      console.log(`Failed to run "${prettyUv}", falling back to pip`);
      (0, import_build_utils4.debug)(`error: ${err}`);
    }
  }
  const cmdArgs = [
    "install",
    "--disable-pip-version-check",
    "--no-compile",
    "--no-cache-dir",
    "--target",
    target,
    ...args
  ];
  const pretty = `${pipPath} ${cmdArgs.join(" ")}`;
  (0, import_build_utils4.debug)(`Running "${pretty}"...`);
  try {
    await (0, import_execa3.default)(pipPath, cmdArgs, {
      cwd: workPath
    });
  } catch (err) {
    console.log(`Failed to run "${pretty}"`);
    (0, import_build_utils4.debug)(`error: ${err}`);
    throw err;
  }
}
async function installRequirement({
  pythonPath,
  pipPath,
  uvPath,
  dependency,
  version: version2,
  workPath,
  targetDir,
  meta,
  args = []
}) {
  const actualTargetDir = targetDir || workPath;
  if (meta.isDev && await isInstalled2(pythonPath, dependency, actualTargetDir)) {
    (0, import_build_utils4.debug)(
      `Skipping ${dependency} dependency installation, already installed in ${actualTargetDir}`
    );
    return;
  }
  const exact = `${dependency}==${version2}`;
  await pipInstall(pipPath, uvPath, workPath, [exact, ...args], targetDir);
}
async function installRequirementsFile({
  pythonPath,
  pipPath,
  uvPath,
  filePath,
  workPath,
  targetDir,
  meta,
  args = []
}) {
  const actualTargetDir = targetDir || workPath;
  if (meta.isDev && await areRequirementsInstalled(pythonPath, filePath, actualTargetDir)) {
    (0, import_build_utils4.debug)(`Skipping requirements file installation, already installed`);
    return;
  }
  await pipInstall(
    pipPath,
    uvPath,
    workPath,
    ["--upgrade", "-r", filePath, ...args],
    targetDir
  );
}
async function exportRequirementsFromPipfile({
  pythonPath,
  pipPath,
  uvPath,
  projectDir,
  meta
}) {
  const tempDir = await import_fs3.default.promises.mkdtemp(
    (0, import_path4.join)(import_os2.default.tmpdir(), "vercel-pipenv-")
  );
  await installRequirement({
    pythonPath,
    pipPath,
    dependency: "pipfile-requirements",
    version: "0.3.0",
    workPath: tempDir,
    meta,
    args: ["--no-warn-script-location"],
    uvPath
  });
  const tempVendorDir = (0, import_path4.join)(tempDir, resolveVendorDir());
  const convertCmd = isWin3 ? (0, import_path4.join)(tempVendorDir, "Scripts", "pipfile2req.exe") : (0, import_path4.join)(tempVendorDir, "bin", "pipfile2req");
  (0, import_build_utils4.debug)(`Running "${convertCmd}" in ${projectDir}...`);
  let stdout;
  try {
    const { stdout: out } = await (0, import_execa3.default)(convertCmd, [], {
      cwd: projectDir,
      env: { ...process.env, PYTHONPATH: tempVendorDir }
    });
    stdout = out;
  } catch (err) {
    throw new Error(
      `Failed to run "${convertCmd}": ${err instanceof Error ? err.message : String(err)}`
    );
  }
  const outPath = (0, import_path4.join)(tempDir, "requirements.pipenv.txt");
  await import_fs3.default.promises.writeFile(outPath, stdout);
  (0, import_build_utils4.debug)(`Exported pipfile requirements to ${outPath}`);
  return outPath;
}
async function mirrorSitePackagesIntoVendor({
  venvPath,
  vendorDirName
}) {
  const vendorFiles = {};
  try {
    const sitePackageDirs = await getVenvSitePackagesDirs(venvPath);
    for (const dir of sitePackageDirs) {
      if (!import_fs3.default.existsSync(dir))
        continue;
      const dirFiles = await (0, import_build_utils4.glob)("**", dir);
      for (const relativePath of Object.keys(dirFiles)) {
        if (relativePath.endsWith(".pyc") || relativePath.includes("__pycache__")) {
          continue;
        }
        const srcFsPath = (0, import_path4.join)(dir, relativePath);
        const bundlePath = (0, import_path4.join)(vendorDirName, relativePath).replace(
          /\\/g,
          "/"
        );
        vendorFiles[bundlePath] = new import_build_utils4.FileFsRef({ fsPath: srcFsPath });
      }
    }
  } catch (err) {
    console.log("Failed to collect site-packages from virtual environment");
    throw err;
  }
  return vendorFiles;
}

// src/index.ts
var import_build_utils9 = require("@vercel/build-utils");

// src/start-dev-server.ts
var import_child_process2 = require("child_process");
var import_fs4 = require("fs");
var import_path6 = require("path");
var import_build_utils7 = require("@vercel/build-utils");

// src/entrypoint.ts
var import_path5 = require("path");
var import_build_utils5 = require("@vercel/build-utils");
var import_build_utils6 = require("@vercel/build-utils");
var PYTHON_ENTRYPOINT_FILENAMES = [
  "app",
  "index",
  "server",
  "main",
  "wsgi",
  "asgi"
];
var PYTHON_ENTRYPOINT_DIRS = ["", "src", "app", "api"];
var PYTHON_CANDIDATE_ENTRYPOINTS = PYTHON_ENTRYPOINT_FILENAMES.flatMap(
  (filename) => PYTHON_ENTRYPOINT_DIRS.map(
    (dir) => import_path5.posix.join(dir, `${filename}.py`)
  )
);
async function getPyprojectEntrypoint(workPath) {
  const pyprojectData = await (0, import_build_utils6.readConfigFile)((0, import_path5.join)(workPath, "pyproject.toml"));
  if (!pyprojectData)
    return null;
  const scripts = pyprojectData.project?.scripts;
  const appScript = scripts?.app;
  if (typeof appScript !== "string")
    return null;
  const match = appScript.match(/([A-Za-z_][\w.]*)\s*:\s*([A-Za-z_][\w]*)/);
  if (!match)
    return null;
  const modulePath = match[1];
  const relPath = modulePath.replace(/\./g, "/");
  try {
    const fsFiles = await (0, import_build_utils5.glob)("**", workPath);
    const candidates = [`${relPath}.py`, `${relPath}/__init__.py`];
    for (const candidate of candidates) {
      if (fsFiles[candidate])
        return candidate;
    }
    return null;
  } catch {
    (0, import_build_utils5.debug)("Failed to discover Python entrypoint from pyproject.toml");
    return null;
  }
}
async function detectGenericPythonEntrypoint(workPath, configuredEntrypoint) {
  const entry = configuredEntrypoint.endsWith(".py") ? configuredEntrypoint : `${configuredEntrypoint}.py`;
  try {
    const fsFiles = await (0, import_build_utils5.glob)("**", workPath);
    if (fsFiles[entry]) {
      const isValid = await (0, import_build_utils5.isPythonEntrypoint)(fsFiles[entry]);
      if (isValid) {
        (0, import_build_utils5.debug)(`Using configured Python entrypoint: ${entry}`);
        return entry;
      }
    }
    const candidates = PYTHON_CANDIDATE_ENTRYPOINTS.filter(
      (c) => !!fsFiles[c]
    );
    for (const candidate of candidates) {
      const isValid = await (0, import_build_utils5.isPythonEntrypoint)(fsFiles[candidate]);
      if (isValid) {
        (0, import_build_utils5.debug)(`Detected Python entrypoint: ${candidate}`);
        return candidate;
      }
    }
    return null;
  } catch {
    (0, import_build_utils5.debug)("Failed to discover Python entrypoint");
    return null;
  }
}
async function detectPythonEntrypoint(_framework, workPath, configuredEntrypoint) {
  const entrypoint = await detectGenericPythonEntrypoint(
    workPath,
    configuredEntrypoint
  );
  if (entrypoint)
    return entrypoint;
  return await getPyprojectEntrypoint(workPath);
}

// src/start-dev-server.ts
function silenceNodeWarnings() {
  const original = process.emitWarning.bind(
    process
  );
  let active = true;
  const wrapped = (warning, ...args) => {
    if (!active) {
      return original(
        warning,
        ...args
      );
    }
    return;
  };
  process.emitWarning = wrapped;
  return () => {
    if (!active)
      return;
    active = false;
    if (process.emitWarning === wrapped) {
      process.emitWarning = original;
    }
  };
}
var ANSI_PATTERN = "[\\u001B\\u009B][[\\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><]";
var ANSI_ESCAPE_RE = new RegExp(ANSI_PATTERN, "g");
var stripAnsi = (s) => s.replace(ANSI_ESCAPE_RE, "");
var ASGI_SHIM_MODULE = "vc_init_dev_asgi";
var WSGI_SHIM_MODULE = "vc_init_dev_wsgi";
var PERSISTENT_SERVERS = /* @__PURE__ */ new Map();
var PENDING_STARTS = /* @__PURE__ */ new Map();
var restoreWarnings = null;
var cleanupHandlersInstalled = false;
function installGlobalCleanupHandlers() {
  if (cleanupHandlersInstalled)
    return;
  cleanupHandlersInstalled = true;
  const killAll = () => {
    for (const [key, info] of PERSISTENT_SERVERS.entries()) {
      try {
        process.kill(info.pid, "SIGTERM");
      } catch (err) {
        (0, import_build_utils7.debug)(`Error sending SIGTERM to ${info.pid}: ${err}`);
      }
      try {
        process.kill(info.pid, "SIGKILL");
      } catch (err) {
        (0, import_build_utils7.debug)(`Error sending SIGKILL to ${info.pid}: ${err}`);
      }
      PERSISTENT_SERVERS.delete(key);
    }
    if (restoreWarnings) {
      try {
        restoreWarnings();
      } catch (err) {
        (0, import_build_utils7.debug)(`Error restoring warnings: ${err}`);
      }
      restoreWarnings = null;
    }
  };
  process.on("SIGINT", () => {
    killAll();
    process.exit(130);
  });
  process.on("SIGTERM", () => {
    killAll();
    process.exit(143);
  });
  process.on("exit", () => {
    killAll();
  });
}
function createDevAsgiShim(workPath, modulePath) {
  try {
    const vercelPythonDir = (0, import_path6.join)(workPath, ".vercel", "python");
    (0, import_fs4.mkdirSync)(vercelPythonDir, { recursive: true });
    const shimPath = (0, import_path6.join)(vercelPythonDir, `${ASGI_SHIM_MODULE}.py`);
    const templatePath = (0, import_path6.join)(__dirname, "..", `${ASGI_SHIM_MODULE}.py`);
    const template = (0, import_fs4.readFileSync)(templatePath, "utf8");
    const shimSource = template.replace(/__VC_DEV_MODULE_PATH__/g, modulePath);
    (0, import_fs4.writeFileSync)(shimPath, shimSource, "utf8");
    (0, import_build_utils7.debug)(`Prepared Python dev static shim at ${shimPath}`);
    return ASGI_SHIM_MODULE;
  } catch (err) {
    (0, import_build_utils7.debug)(`Failed to prepare dev static shim: ${err?.message || err}`);
    return null;
  }
}
function createDevWsgiShim(workPath, modulePath) {
  try {
    const vercelPythonDir = (0, import_path6.join)(workPath, ".vercel", "python");
    (0, import_fs4.mkdirSync)(vercelPythonDir, { recursive: true });
    const shimPath = (0, import_path6.join)(vercelPythonDir, `${WSGI_SHIM_MODULE}.py`);
    const templatePath = (0, import_path6.join)(__dirname, "..", `${WSGI_SHIM_MODULE}.py`);
    const template = (0, import_fs4.readFileSync)(templatePath, "utf8");
    const shimSource = template.replace(/__VC_DEV_MODULE_PATH__/g, modulePath);
    (0, import_fs4.writeFileSync)(shimPath, shimSource, "utf8");
    (0, import_build_utils7.debug)(`Prepared Python dev WSGI shim at ${shimPath}`);
    return WSGI_SHIM_MODULE;
  } catch (err) {
    (0, import_build_utils7.debug)(`Failed to prepare dev WSGI shim: ${err?.message || err}`);
    return null;
  }
}
var startDevServer = async (opts) => {
  const { entrypoint: rawEntrypoint, workPath, meta = {}, config } = opts;
  const framework = config?.framework;
  if (framework !== "fastapi" && framework !== "flask") {
    return null;
  }
  if (!restoreWarnings)
    restoreWarnings = silenceNodeWarnings();
  installGlobalCleanupHandlers();
  const entry = await detectPythonEntrypoint(
    framework,
    workPath,
    rawEntrypoint
  );
  if (!entry) {
    const searched = PYTHON_CANDIDATE_ENTRYPOINTS.join(", ");
    throw new import_build_utils7.NowBuildError({
      code: "PYTHON_ENTRYPOINT_NOT_FOUND",
      message: `No ${framework} entrypoint found. Add an 'app' script in pyproject.toml or define an entrypoint in one of: ${searched}.`,
      link: `https://vercel.com/docs/frameworks/backend/${framework?.toLowerCase()}#exporting-the-${framework?.toLowerCase()}-application`,
      action: "Learn More"
    });
  }
  const modulePath = entry.replace(/\.py$/i, "").replace(/[\\/]/g, ".");
  const env = { ...process.env, ...meta.env || {} };
  const serverKey = `${workPath}::${entry}::${framework}`;
  const existing = PERSISTENT_SERVERS.get(serverKey);
  if (existing) {
    return {
      port: existing.port,
      pid: existing.pid,
      shutdown: async () => {
      }
    };
  }
  {
    const pending = PENDING_STARTS.get(serverKey);
    if (pending) {
      const { port, pid } = await pending;
      return {
        port,
        pid,
        shutdown: async () => {
        }
      };
    }
  }
  let childProcess = null;
  let stdoutLogListener = null;
  let stderrLogListener = null;
  let resolveChildReady;
  let rejectChildReady;
  const childReady = new Promise(
    (resolve2, reject) => {
      resolveChildReady = resolve2;
      rejectChildReady = reject;
    }
  );
  PENDING_STARTS.set(serverKey, childReady);
  try {
    await new Promise((resolve2, reject) => {
      let resolved = false;
      const { pythonPath: systemPython } = getDefaultPythonVersion(meta);
      let pythonCmd = systemPython;
      const venv = isInVirtualEnv();
      if (venv) {
        (0, import_build_utils7.debug)(`Running in virtualenv at ${venv}`);
      } else {
        const { pythonCmd: venvPythonCmd, venvRoot } = useVirtualEnv(
          workPath,
          env,
          systemPython
        );
        pythonCmd = venvPythonCmd;
        if (venvRoot) {
          (0, import_build_utils7.debug)(`Using virtualenv at ${venvRoot}`);
        } else {
          (0, import_build_utils7.debug)("No virtualenv found");
          try {
            const yellow = "\x1B[33m";
            const reset = "\x1B[0m";
            const venvCmd = process.platform === "win32" ? "python -m venv .venv && .venv\\Scripts\\activate" : "python -m venv .venv && source .venv/bin/activate";
            process.stderr.write(
              `${yellow}Warning: no virtual environment detected in ${workPath}. Using system Python: ${pythonCmd}.${reset}
If you are using a virtual environment, activate it before running "vercel dev", or create one: ${venvCmd}
`
            );
          } catch (_) {
          }
        }
      }
      if (framework !== "flask") {
        const devShimModule = createDevAsgiShim(workPath, modulePath);
        if (devShimModule) {
          const vercelPythonDir = (0, import_path6.join)(workPath, ".vercel", "python");
          const existingPythonPath = env.PYTHONPATH || "";
          env.PYTHONPATH = existingPythonPath ? `${vercelPythonDir}:${existingPythonPath}` : vercelPythonDir;
        }
        const moduleToRun = devShimModule || modulePath;
        const argv = ["-u", "-m", moduleToRun];
        (0, import_build_utils7.debug)(
          `Starting ASGI dev server (${framework}): ${pythonCmd} ${argv.join(" ")}`
        );
        const child = (0, import_child_process2.spawn)(pythonCmd, argv, {
          cwd: workPath,
          env,
          stdio: ["inherit", "pipe", "pipe"]
        });
        childProcess = child;
        stdoutLogListener = (buf) => {
          const s = buf.toString();
          for (const line of s.split(/\r?\n/)) {
            if (line) {
              process.stdout.write(line.endsWith("\n") ? line : line + "\n");
            }
          }
        };
        stderrLogListener = (buf) => {
          const s = buf.toString();
          for (const line of s.split(/\r?\n/)) {
            if (line) {
              process.stderr.write(line.endsWith("\n") ? line : line + "\n");
            }
          }
        };
        child.stdout?.on("data", stdoutLogListener);
        child.stderr?.on("data", stderrLogListener);
        const readinessRegexes = [
          /Uvicorn running on https?:\/\/(?:\[[^\]]+\]|[^:]+):(\d+)/i,
          /Hypercorn running on https?:\/\/(?:\[[^\]]+\]|[^:]+):(\d+)/i,
          /(?:Running|Serving) on https?:\/\/(?:\[[^\]]+\]|[^:\s]+):(\d+)/i
        ];
        const onDetect = (chunk) => {
          const text = chunk.toString();
          const clean = stripAnsi(text);
          let portMatch = null;
          for (const rx of readinessRegexes) {
            const m = clean.match(rx);
            if (m) {
              portMatch = m;
              break;
            }
          }
          if (portMatch && child.pid) {
            if (!resolved) {
              resolved = true;
              child.stdout?.removeListener("data", onDetect);
              child.stderr?.removeListener("data", onDetect);
              const port2 = Number(portMatch[1]);
              resolveChildReady({ port: port2, pid: child.pid });
              resolve2();
            }
          }
        };
        child.stdout?.on("data", onDetect);
        child.stderr?.on("data", onDetect);
        child.once("error", (err) => {
          if (!resolved) {
            rejectChildReady(err);
            reject(err);
          }
        });
        child.once("exit", (code, signal) => {
          if (!resolved) {
            const err = new Error(
              `ASGI dev server exited before binding (code=${code}, signal=${signal})`
            );
            rejectChildReady(err);
            reject(err);
          }
        });
      } else {
        const devShimModule = createDevWsgiShim(workPath, modulePath);
        if (devShimModule) {
          const vercelPythonDir = (0, import_path6.join)(workPath, ".vercel", "python");
          const existingPythonPath = env.PYTHONPATH || "";
          env.PYTHONPATH = existingPythonPath ? `${vercelPythonDir}:${existingPythonPath}` : vercelPythonDir;
        }
        const moduleToRun = devShimModule || modulePath;
        const argv = ["-u", "-m", moduleToRun];
        (0, import_build_utils7.debug)(`Starting Flask dev server: ${pythonCmd} ${argv.join(" ")}`);
        const child = (0, import_child_process2.spawn)(pythonCmd, argv, {
          cwd: workPath,
          env,
          stdio: ["inherit", "pipe", "pipe"]
        });
        childProcess = child;
        stdoutLogListener = (buf) => {
          const s = buf.toString();
          for (const line of s.split(/\r?\n/)) {
            if (line) {
              process.stdout.write(line.endsWith("\n") ? line : line + "\n");
            }
          }
        };
        stderrLogListener = (buf) => {
          const s = buf.toString();
          for (const line of s.split(/\r?\n/)) {
            if (line) {
              process.stderr.write(line.endsWith("\n") ? line : line + "\n");
            }
          }
        };
        child.stdout?.on("data", stdoutLogListener);
        child.stderr?.on("data", stderrLogListener);
        const readinessRegexes = [
          /Werkzeug running on https?:\/\/(?:\[[^\]]+\]|[^:]+):(\d+)/i,
          /(?:Running|Serving) on https?:\/\/(?:\[[^\]]+\]|[^:\s]+):(\d+)/i
        ];
        const onDetect = (chunk) => {
          const text = chunk.toString();
          const clean = stripAnsi(text);
          let portMatch = null;
          for (const rx of readinessRegexes) {
            const m = clean.match(rx);
            if (m) {
              portMatch = m;
              break;
            }
          }
          if (portMatch && child.pid) {
            if (!resolved) {
              resolved = true;
              child.stdout?.removeListener("data", onDetect);
              child.stderr?.removeListener("data", onDetect);
              const port2 = Number(portMatch[1]);
              resolveChildReady({ port: port2, pid: child.pid });
              resolve2();
            }
          }
        };
        child.stdout?.on("data", onDetect);
        child.stderr?.on("data", onDetect);
        child.once("error", (err) => {
          if (!resolved) {
            rejectChildReady(err);
            reject(err);
          }
        });
        child.once("exit", (code, signal) => {
          if (!resolved) {
            const err = new Error(
              `Flask dev server exited before binding (code=${code}, signal=${signal})`
            );
            rejectChildReady(err);
            reject(err);
          }
        });
      }
    });
    const { port, pid } = await childReady;
    PERSISTENT_SERVERS.set(serverKey, {
      port,
      pid,
      child: childProcess,
      stdoutLogListener,
      stderrLogListener
    });
    const shutdown = async () => {
    };
    return { port, pid, shutdown };
  } finally {
    PENDING_STARTS.delete(serverKey);
  }
};

// src/index.ts
var readFile = (0, import_util.promisify)(import_fs5.default.readFile);
var writeFile = (0, import_util.promisify)(import_fs5.default.writeFile);
var version = 3;
async function downloadFilesInWorkPath({
  entrypoint,
  workPath,
  files,
  meta = {}
}) {
  (0, import_build_utils8.debug)("Downloading user files...");
  let downloadedFiles = await (0, import_build_utils8.download)(files, workPath, meta);
  if (meta.isDev) {
    const { devCacheDir = (0, import_path7.join)(workPath, ".now", "cache") } = meta;
    const destCache = (0, import_path7.join)(devCacheDir, (0, import_path7.basename)(entrypoint, ".py"));
    await (0, import_build_utils8.download)(downloadedFiles, destCache);
    downloadedFiles = await (0, import_build_utils8.glob)("**", destCache);
    workPath = destCache;
  }
  return workPath;
}
var build = async ({
  workPath,
  repoRootPath,
  files: originalFiles,
  entrypoint,
  meta = {},
  config
}) => {
  const framework = config?.framework;
  let spawnEnv;
  let projectInstallCommand;
  workPath = await downloadFilesInWorkPath({
    workPath,
    files: originalFiles,
    entrypoint,
    meta
  });
  try {
    if (meta.isDev) {
      const setupCfg = (0, import_path7.join)(workPath, "setup.cfg");
      await writeFile(setupCfg, "[install]\nprefix=\n");
    }
  } catch (err) {
    console.log('Failed to create "setup.cfg" file');
    throw err;
  }
  if ((0, import_build_utils8.isPythonFramework)(framework)) {
    const {
      cliType,
      lockfileVersion,
      packageJsonPackageManager,
      turboSupportsCorepackHome
    } = await (0, import_build_utils8.scanParentDirs)(workPath, true);
    spawnEnv = (0, import_build_utils8.getEnvForPackageManager)({
      cliType,
      lockfileVersion,
      packageJsonPackageManager,
      env: process.env,
      turboSupportsCorepackHome,
      projectCreatedAt: config?.projectSettings?.createdAt
    });
    const installCommand = config?.projectSettings?.installCommand;
    if (typeof installCommand === "string") {
      const trimmed = installCommand.trim();
      if (trimmed) {
        projectInstallCommand = trimmed;
      } else {
        console.log('Skipping "install" command...');
      }
    }
    const projectBuildCommand = config?.projectSettings?.buildCommand ?? // fallback if provided directly on config (some callers set this)
    config?.buildCommand;
    if (projectBuildCommand) {
      console.log(`Running "${projectBuildCommand}"`);
      await (0, import_build_utils8.execCommand)(projectBuildCommand, {
        env: spawnEnv,
        cwd: workPath
      });
    } else {
      await runPyprojectScript(
        workPath,
        ["vercel-build", "now-build", "build"],
        spawnEnv
      );
    }
  }
  let fsFiles = await (0, import_build_utils8.glob)("**", workPath);
  if ((0, import_build_utils8.isPythonFramework)(framework) && (!fsFiles[entrypoint] || !entrypoint.endsWith(".py"))) {
    const detected = await detectPythonEntrypoint(
      config.framework,
      workPath,
      entrypoint
    );
    if (detected) {
      (0, import_build_utils8.debug)(
        `Resolved Python entrypoint to "${detected}" (configured "${entrypoint}" not found).`
      );
      entrypoint = detected;
    } else {
      const searchedList = PYTHON_CANDIDATE_ENTRYPOINTS.join(", ");
      throw new import_build_utils8.NowBuildError({
        code: `${framework.toUpperCase()}_ENTRYPOINT_NOT_FOUND`,
        message: `No ${framework} entrypoint found. Add an 'app' script in pyproject.toml or define an entrypoint in one of: ${searchedList}.`,
        link: `https://vercel.com/docs/frameworks/backend/${framework}#exporting-the-${framework}-application`,
        action: "Learn More"
      });
    }
  }
  const entryDirectory = (0, import_path7.dirname)(entrypoint);
  const pyprojectDir = findDir({
    file: "pyproject.toml",
    entryDirectory,
    workPath,
    fsFiles
  });
  const pipfileLockDir = findDir({
    file: "Pipfile.lock",
    entryDirectory,
    workPath,
    fsFiles
  });
  const pythonVersionFileDir = findDir({
    file: ".python-version",
    entryDirectory,
    workPath,
    fsFiles
  });
  let declaredPythonVersion;
  if (pythonVersionFileDir) {
    try {
      const content = await readFile(
        (0, import_path7.join)(pythonVersionFileDir, ".python-version"),
        "utf8"
      );
      const version2 = parsePythonVersionFile(content);
      if (version2) {
        declaredPythonVersion = { version: version2, source: ".python-version" };
        (0, import_build_utils8.debug)(`Found Python version ${version2} in .python-version`);
      }
    } catch (err) {
      (0, import_build_utils8.debug)("Failed to read .python-version file", err);
    }
  }
  if (!declaredPythonVersion && pyprojectDir) {
    let requiresPython;
    try {
      const pyproject = await (0, import_build_utils9.readConfigFile)((0, import_path7.join)(pyprojectDir, "pyproject.toml"));
      requiresPython = pyproject?.project?.["requires-python"];
    } catch (err) {
      (0, import_build_utils8.debug)("Failed to parse pyproject.toml", err);
    }
    if (typeof requiresPython === "string" && requiresPython.trim()) {
      declaredPythonVersion = {
        version: requiresPython.trim(),
        source: "pyproject.toml"
      };
      (0, import_build_utils8.debug)(`Found requires-python "${requiresPython}" in pyproject.toml`);
    }
  }
  if (!declaredPythonVersion && pipfileLockDir) {
    let lock = {};
    try {
      const json = await readFile((0, import_path7.join)(pipfileLockDir, "Pipfile.lock"), "utf8");
      lock = JSON.parse(json);
    } catch (err) {
      throw new import_build_utils8.NowBuildError({
        code: "INVALID_PIPFILE_LOCK",
        message: "Unable to parse Pipfile.lock"
      });
    }
    const pyFromLock = lock?._meta?.requires?.python_version;
    if (pyFromLock) {
      declaredPythonVersion = { version: pyFromLock, source: "Pipfile.lock" };
      (0, import_build_utils8.debug)(`Found Python version ${pyFromLock} in Pipfile.lock`);
    }
  }
  const pythonVersion = getSupportedPythonVersion({
    isDev: meta.isDev,
    declaredPythonVersion
  });
  const selectedVersionTuple = parseVersionTuple(pythonVersion.version);
  const defaultVersionTuple = parseVersionTuple(DEFAULT_PYTHON_VERSION);
  if (!pythonVersionFileDir && pyprojectDir && declaredPythonVersion?.source === "pyproject.toml" && selectedVersionTuple && defaultVersionTuple && compareTuples(selectedVersionTuple, defaultVersionTuple) <= 0) {
    const pythonVersionFilePath = (0, import_path7.join)(pyprojectDir, ".python-version");
    await writeFile(pythonVersionFilePath, `${pythonVersion.version}
`);
    console.log(
      `Writing .python-version file with version ${pythonVersion.version}`
    );
  }
  fsFiles = await (0, import_build_utils8.glob)("**", workPath);
  const venvPath = (0, import_path7.join)(workPath, ".vercel", "python", ".venv");
  await ensureVenv({
    pythonPath: pythonVersion.pythonPath,
    venvPath
  });
  const hasCustomInstallCommand = (0, import_build_utils8.isPythonFramework)(framework) && !!projectInstallCommand;
  let useRuntime = false;
  if (hasCustomInstallCommand) {
    const baseEnv = spawnEnv || process.env;
    const pythonEnv = createVenvEnv(venvPath, baseEnv);
    pythonEnv.VERCEL_PYTHON_VENV_PATH = venvPath;
    const installCommand = projectInstallCommand;
    console.log(`Running "install" command: \`${installCommand}\`...`);
    await (0, import_build_utils8.execCommand)(installCommand, {
      env: pythonEnv,
      cwd: workPath
    });
  } else {
    let ranPyprojectInstall = false;
    if ((0, import_build_utils8.isPythonFramework)(framework)) {
      const baseEnv = spawnEnv || process.env;
      const pythonEnv = createVenvEnv(venvPath, baseEnv);
      pythonEnv.VERCEL_PYTHON_VENV_PATH = venvPath;
      ranPyprojectInstall = await runPyprojectScript(
        workPath,
        ["vercel-install", "now-install", "install"],
        pythonEnv,
        /* useUserVirtualEnv */
        false
      );
    }
    if (!ranPyprojectInstall) {
      let uv;
      try {
        const uvPath = await getUvBinaryOrInstall(pythonVersion.pythonPath);
        console.log(`Using uv at "${uvPath}"`);
        uv = new UvRunner(uvPath);
      } catch (err) {
        console.log("Failed to install or locate uv");
        throw new Error(
          `uv is required for this project but failed to install: ${err instanceof Error ? err.message : String(err)}`
        );
      }
      const baseEnv = spawnEnv || process.env;
      useRuntime = !!baseEnv.VERCEL_RUNTIME_PYTHON_ENABLED;
      const runtimeDependencies = [];
      if (useRuntime) {
        runtimeDependencies.push(
          baseEnv.VERCEL_RUNTIME_PYTHON || "vercel-runtime==0.1.0"
        );
      }
      runtimeDependencies.push("werkzeug>=1.0.1");
      if (framework !== "flask") {
        runtimeDependencies.push("uvicorn>=0.24");
      }
      const { projectDir } = await ensureUvProject({
        workPath,
        entryDirectory,
        fsFiles,
        repoRootPath,
        pythonPath: pythonVersion.pythonPath,
        pipPath: pythonVersion.pipPath,
        uv,
        venvPath,
        meta,
        runtimeDependencies
      });
      await uv.sync({
        venvPath,
        projectDir,
        locked: true
      });
    }
  }
  (0, import_build_utils8.debug)("Entrypoint is", entrypoint);
  const moduleName = entrypoint.replace(/\//g, ".").replace(/\.py$/i, "");
  const vendorDir = resolveVendorDir();
  const suffix = meta.isDev && !entrypoint.endsWith(".py") ? ".py" : "";
  const entrypointWithSuffix = `${entrypoint}${suffix}`;
  (0, import_build_utils8.debug)("Entrypoint with suffix is", entrypointWithSuffix);
  let handlerPyContents;
  if (useRuntime) {
    handlerPyContents = `
import importlib
import os
import os.path
import site
import sys

_here = os.path.dirname(__file__)

os.environ.update({
  "__VC_HANDLER_MODULE_NAME": "${moduleName}",
  "__VC_HANDLER_ENTRYPOINT": "${entrypointWithSuffix}",
  "__VC_HANDLER_ENTRYPOINT_ABS": os.path.join(_here, "${entrypointWithSuffix}"),
  "__VC_HANDLER_VENDOR_DIR": "${vendorDir}",
})

_vendor_rel = '${vendorDir}'
_vendor = os.path.normpath(os.path.join(_here, _vendor_rel))

if os.path.isdir(_vendor):
    # Process .pth files like a real site-packages dir
    site.addsitedir(_vendor)

    # Move _vendor to the front (after script dir if present)
    try:
        while _vendor in sys.path:
            sys.path.remove(_vendor)
    except ValueError:
        pass

    # Put vendored deps ahead of site-packages but after the script dir
    idx = 1 if (sys.path and sys.path[0] in ('', _here)) else 0
    sys.path.insert(idx, _vendor)

    importlib.invalidate_caches()

from vercel_runtime.vc_init import vc_handler
`;
  } else {
    const originalPyPath = (0, import_path7.join)(__dirname, "..", "vc_init.py");
    const originalHandlerPyContents = await readFile(originalPyPath, "utf8");
    handlerPyContents = originalHandlerPyContents.replace(/__VC_HANDLER_MODULE_NAME/g, moduleName).replace(/__VC_HANDLER_ENTRYPOINT/g, entrypointWithSuffix).replace(/__VC_HANDLER_VENDOR_DIR/g, vendorDir);
  }
  const predefinedExcludes = [
    ".git/**",
    ".gitignore",
    ".vercel/**",
    ".pnpm-store/**",
    "**/node_modules/**",
    "**/.next/**",
    "**/.nuxt/**",
    "**/.venv/**",
    "**/venv/**",
    "**/__pycache__/**",
    "**/.mypy_cache/**",
    "**/.ruff_cache/**",
    "**/public/**",
    "**/pnpm-lock.yaml",
    "**/yarn.lock",
    "**/package-lock.json"
  ];
  const lambdaEnv = {};
  lambdaEnv.PYTHONPATH = vendorDir;
  const globOptions = {
    cwd: workPath,
    ignore: config && typeof config.excludeFiles === "string" ? [...predefinedExcludes, config.excludeFiles] : predefinedExcludes
  };
  const files = await (0, import_build_utils8.glob)("**", globOptions);
  const vendorFiles = await mirrorSitePackagesIntoVendor({
    venvPath,
    vendorDirName: vendorDir
  });
  for (const [p, f] of Object.entries(vendorFiles)) {
    files[p] = f;
  }
  const handlerPyFilename = "vc__handler__python";
  files[`${handlerPyFilename}.py`] = new import_build_utils8.FileBlob({ data: handlerPyContents });
  if (config.framework === "fasthtml") {
    const { SESSKEY = "" } = process.env;
    files[".sesskey"] = new import_build_utils8.FileBlob({ data: `"${SESSKEY}"` });
  }
  const output = new import_build_utils8.Lambda({
    files,
    handler: `${handlerPyFilename}.vc_handler`,
    runtime: pythonVersion.runtime,
    environment: lambdaEnv,
    supportsResponseStreaming: true
  });
  return { output };
};
var shouldServe = (opts) => {
  const framework = opts.config.framework;
  if (framework === "fastapi") {
    const requestPath = opts.requestPath.replace(/\/$/, "");
    if (requestPath.startsWith("api") && opts.hasMatched) {
      return false;
    }
    return true;
  } else if (framework === "flask") {
    const requestPath = opts.requestPath.replace(/\/$/, "");
    if (requestPath.startsWith("api") && opts.hasMatched) {
      return false;
    }
    return true;
  }
  return defaultShouldServe(opts);
};
var defaultShouldServe = ({
  entrypoint,
  files,
  requestPath
}) => {
  requestPath = requestPath.replace(/\/$/, "");
  entrypoint = entrypoint.replace(/\\/g, "/");
  if (entrypoint === requestPath && hasProp(files, entrypoint)) {
    return true;
  }
  const { dir, name } = (0, import_path7.parse)(entrypoint);
  if (name === "index" && dir === requestPath && hasProp(files, entrypoint)) {
    return true;
  }
  return false;
};
function hasProp(obj, key) {
  return Object.hasOwnProperty.call(obj, key);
}
function parsePythonVersionFile(content) {
  const lines = content.split("\n");
  for (const line of lines) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#"))
      continue;
    return trimmed;
  }
  return void 0;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  build,
  defaultShouldServe,
  downloadFilesInWorkPath,
  installRequirement,
  installRequirementsFile,
  shouldServe,
  startDevServer,
  version
});
