"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/make-dir/node_modules/semver/semver.js
var require_semver = __commonJS({
  "node_modules/make-dir/node_modules/semver/semver.js"(exports2, module2) {
    "use strict";
    exports2 = module2.exports = SemVer;
    var debug;
    if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
      debug = function() {
        var args = Array.prototype.slice.call(arguments, 0);
        args.unshift("SEMVER");
        console.log.apply(console, args);
      };
    } else {
      debug = function() {
      };
    }
    exports2.SEMVER_SPEC_VERSION = "2.0.0";
    var MAX_LENGTH = 256;
    var MAX_SAFE_INTEGER3 = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
    9007199254740991;
    var MAX_SAFE_COMPONENT_LENGTH = 16;
    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
    var re = exports2.re = [];
    var safeRe = exports2.safeRe = [];
    var src = exports2.src = [];
    var t = exports2.tokens = {};
    var R = 0;
    function tok(n) {
      t[n] = R++;
    }
    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 max2 = safeRegexReplacements[i2][1];
        value = value.split(token + "*").join(token + "{0," + max2 + "}").split(token + "+").join(token + "{1," + max2 + "}");
      }
      return value;
    }
    tok("NUMERICIDENTIFIER");
    src[t.NUMERICIDENTIFIER] = "0|[1-9]\\d*";
    tok("NUMERICIDENTIFIERLOOSE");
    src[t.NUMERICIDENTIFIERLOOSE] = "\\d+";
    tok("NONNUMERICIDENTIFIER");
    src[t.NONNUMERICIDENTIFIER] = "\\d*[a-zA-Z-]" + LETTERDASHNUMBER + "*";
    tok("MAINVERSION");
    src[t.MAINVERSION] = "(" + src[t.NUMERICIDENTIFIER] + ")\\.(" + src[t.NUMERICIDENTIFIER] + ")\\.(" + src[t.NUMERICIDENTIFIER] + ")";
    tok("MAINVERSIONLOOSE");
    src[t.MAINVERSIONLOOSE] = "(" + src[t.NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[t.NUMERICIDENTIFIERLOOSE] + ")\\.(" + src[t.NUMERICIDENTIFIERLOOSE] + ")";
    tok("PRERELEASEIDENTIFIER");
    src[t.PRERELEASEIDENTIFIER] = "(?:" + src[t.NUMERICIDENTIFIER] + "|" + src[t.NONNUMERICIDENTIFIER] + ")";
    tok("PRERELEASEIDENTIFIERLOOSE");
    src[t.PRERELEASEIDENTIFIERLOOSE] = "(?:" + src[t.NUMERICIDENTIFIERLOOSE] + "|" + src[t.NONNUMERICIDENTIFIER] + ")";
    tok("PRERELEASE");
    src[t.PRERELEASE] = "(?:-(" + src[t.PRERELEASEIDENTIFIER] + "(?:\\." + src[t.PRERELEASEIDENTIFIER] + ")*))";
    tok("PRERELEASELOOSE");
    src[t.PRERELEASELOOSE] = "(?:-?(" + src[t.PRERELEASEIDENTIFIERLOOSE] + "(?:\\." + src[t.PRERELEASEIDENTIFIERLOOSE] + ")*))";
    tok("BUILDIDENTIFIER");
    src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + "+";
    tok("BUILD");
    src[t.BUILD] = "(?:\\+(" + src[t.BUILDIDENTIFIER] + "(?:\\." + src[t.BUILDIDENTIFIER] + ")*))";
    tok("FULL");
    tok("FULLPLAIN");
    src[t.FULLPLAIN] = "v?" + src[t.MAINVERSION] + src[t.PRERELEASE] + "?" + src[t.BUILD] + "?";
    src[t.FULL] = "^" + src[t.FULLPLAIN] + "$";
    tok("LOOSEPLAIN");
    src[t.LOOSEPLAIN] = "[v=\\s]*" + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + "?" + src[t.BUILD] + "?";
    tok("LOOSE");
    src[t.LOOSE] = "^" + src[t.LOOSEPLAIN] + "$";
    tok("GTLT");
    src[t.GTLT] = "((?:<|>)?=?)";
    tok("XRANGEIDENTIFIERLOOSE");
    src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + "|x|X|\\*";
    tok("XRANGEIDENTIFIER");
    src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + "|x|X|\\*";
    tok("XRANGEPLAIN");
    src[t.XRANGEPLAIN] = "[v=\\s]*(" + src[t.XRANGEIDENTIFIER] + ")(?:\\.(" + src[t.XRANGEIDENTIFIER] + ")(?:\\.(" + src[t.XRANGEIDENTIFIER] + ")(?:" + src[t.PRERELEASE] + ")?" + src[t.BUILD] + "?)?)?";
    tok("XRANGEPLAINLOOSE");
    src[t.XRANGEPLAINLOOSE] = "[v=\\s]*(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:\\.(" + src[t.XRANGEIDENTIFIERLOOSE] + ")(?:" + src[t.PRERELEASELOOSE] + ")?" + src[t.BUILD] + "?)?)?";
    tok("XRANGE");
    src[t.XRANGE] = "^" + src[t.GTLT] + "\\s*" + src[t.XRANGEPLAIN] + "$";
    tok("XRANGELOOSE");
    src[t.XRANGELOOSE] = "^" + src[t.GTLT] + "\\s*" + src[t.XRANGEPLAINLOOSE] + "$";
    tok("COERCE");
    src[t.COERCE] = "(^|[^\\d])(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "})(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?(?:$|[^\\d])";
    tok("COERCERTL");
    re[t.COERCERTL] = new RegExp(src[t.COERCE], "g");
    safeRe[t.COERCERTL] = new RegExp(makeSafeRe(src[t.COERCE]), "g");
    tok("LONETILDE");
    src[t.LONETILDE] = "(?:~>?)";
    tok("TILDETRIM");
    src[t.TILDETRIM] = "(\\s*)" + src[t.LONETILDE] + "\\s+";
    re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], "g");
    safeRe[t.TILDETRIM] = new RegExp(makeSafeRe(src[t.TILDETRIM]), "g");
    var tildeTrimReplace = "$1~";
    tok("TILDE");
    src[t.TILDE] = "^" + src[t.LONETILDE] + src[t.XRANGEPLAIN] + "$";
    tok("TILDELOOSE");
    src[t.TILDELOOSE] = "^" + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + "$";
    tok("LONECARET");
    src[t.LONECARET] = "(?:\\^)";
    tok("CARETTRIM");
    src[t.CARETTRIM] = "(\\s*)" + src[t.LONECARET] + "\\s+";
    re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], "g");
    safeRe[t.CARETTRIM] = new RegExp(makeSafeRe(src[t.CARETTRIM]), "g");
    var caretTrimReplace = "$1^";
    tok("CARET");
    src[t.CARET] = "^" + src[t.LONECARET] + src[t.XRANGEPLAIN] + "$";
    tok("CARETLOOSE");
    src[t.CARETLOOSE] = "^" + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + "$";
    tok("COMPARATORLOOSE");
    src[t.COMPARATORLOOSE] = "^" + src[t.GTLT] + "\\s*(" + src[t.LOOSEPLAIN] + ")$|^$";
    tok("COMPARATOR");
    src[t.COMPARATOR] = "^" + src[t.GTLT] + "\\s*(" + src[t.FULLPLAIN] + ")$|^$";
    tok("COMPARATORTRIM");
    src[t.COMPARATORTRIM] = "(\\s*)" + src[t.GTLT] + "\\s*(" + src[t.LOOSEPLAIN] + "|" + src[t.XRANGEPLAIN] + ")";
    re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], "g");
    safeRe[t.COMPARATORTRIM] = new RegExp(makeSafeRe(src[t.COMPARATORTRIM]), "g");
    var comparatorTrimReplace = "$1$2$3";
    tok("HYPHENRANGE");
    src[t.HYPHENRANGE] = "^\\s*(" + src[t.XRANGEPLAIN] + ")\\s+-\\s+(" + src[t.XRANGEPLAIN] + ")\\s*$";
    tok("HYPHENRANGELOOSE");
    src[t.HYPHENRANGELOOSE] = "^\\s*(" + src[t.XRANGEPLAINLOOSE] + ")\\s+-\\s+(" + src[t.XRANGEPLAINLOOSE] + ")\\s*$";
    tok("STAR");
    src[t.STAR] = "(<|>)?=?\\s*\\*";
    for (i = 0; i < R; i++) {
      debug(i, src[i]);
      if (!re[i]) {
        re[i] = new RegExp(src[i]);
        safeRe[i] = new RegExp(makeSafeRe(src[i]));
      }
    }
    var i;
    exports2.parse = parse6;
    function parse6(version3, options) {
      if (!options || typeof options !== "object") {
        options = {
          loose: !!options,
          includePrerelease: false
        };
      }
      if (version3 instanceof SemVer) {
        return version3;
      }
      if (typeof version3 !== "string") {
        return null;
      }
      if (version3.length > MAX_LENGTH) {
        return null;
      }
      var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL];
      if (!r.test(version3)) {
        return null;
      }
      try {
        return new SemVer(version3, options);
      } catch (er) {
        return null;
      }
    }
    exports2.valid = valid;
    function valid(version3, options) {
      var v = parse6(version3, options);
      return v ? v.version : null;
    }
    exports2.clean = clean;
    function clean(version3, options) {
      var s = parse6(version3.trim().replace(/^[=v]+/, ""), options);
      return s ? s.version : null;
    }
    exports2.SemVer = SemVer;
    function SemVer(version3, options) {
      if (!options || typeof options !== "object") {
        options = {
          loose: !!options,
          includePrerelease: false
        };
      }
      if (version3 instanceof SemVer) {
        if (version3.loose === options.loose) {
          return version3;
        } else {
          version3 = version3.version;
        }
      } else if (typeof version3 !== "string") {
        throw new TypeError("Invalid Version: " + version3);
      }
      if (version3.length > MAX_LENGTH) {
        throw new TypeError("version is longer than " + MAX_LENGTH + " characters");
      }
      if (!(this instanceof SemVer)) {
        return new SemVer(version3, options);
      }
      debug("SemVer", version3, options);
      this.options = options;
      this.loose = !!options.loose;
      var m = version3.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]);
      if (!m) {
        throw new TypeError("Invalid Version: " + version3);
      }
      this.raw = version3;
      this.major = +m[1];
      this.minor = +m[2];
      this.patch = +m[3];
      if (this.major > MAX_SAFE_INTEGER3 || this.major < 0) {
        throw new TypeError("Invalid major version");
      }
      if (this.minor > MAX_SAFE_INTEGER3 || this.minor < 0) {
        throw new TypeError("Invalid minor version");
      }
      if (this.patch > MAX_SAFE_INTEGER3 || 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_INTEGER3) {
              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) {
      debug("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];
        debug("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.compareBuild = function(other) {
      if (!(other instanceof SemVer)) {
        other = new SemVer(other, this.options);
      }
      var i2 = 0;
      do {
        var a = this.build[i2];
        var b = other.build[i2];
        debug("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;
    };
    exports2.inc = inc;
    function inc(version3, release, loose, identifier) {
      if (typeof loose === "string") {
        identifier = loose;
        loose = void 0;
      }
      try {
        return new SemVer(version3, loose).inc(release, identifier).version;
      } catch (er) {
        return null;
      }
    }
    exports2.diff = diff;
    function diff(version1, version22) {
      if (eq2(version1, version22)) {
        return null;
      } else {
        var v1 = parse6(version1);
        var v2 = parse6(version22);
        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;
      }
    }
    exports2.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;
    }
    exports2.rcompareIdentifiers = rcompareIdentifiers;
    function rcompareIdentifiers(a, b) {
      return compareIdentifiers(b, a);
    }
    exports2.major = major;
    function major(a, loose) {
      return new SemVer(a, loose).major;
    }
    exports2.minor = minor;
    function minor(a, loose) {
      return new SemVer(a, loose).minor;
    }
    exports2.patch = patch;
    function patch(a, loose) {
      return new SemVer(a, loose).patch;
    }
    exports2.compare = compare;
    function compare(a, b, loose) {
      return new SemVer(a, loose).compare(new SemVer(b, loose));
    }
    exports2.compareLoose = compareLoose;
    function compareLoose(a, b) {
      return compare(a, b, true);
    }
    exports2.compareBuild = compareBuild;
    function compareBuild(a, b, loose) {
      var versionA = new SemVer(a, loose);
      var versionB = new SemVer(b, loose);
      return versionA.compare(versionB) || versionA.compareBuild(versionB);
    }
    exports2.rcompare = rcompare;
    function rcompare(a, b, loose) {
      return compare(b, a, loose);
    }
    exports2.sort = sort;
    function sort(list, loose) {
      return list.sort(function(a, b) {
        return exports2.compareBuild(a, b, loose);
      });
    }
    exports2.rsort = rsort;
    function rsort(list, loose) {
      return list.sort(function(a, b) {
        return exports2.compareBuild(b, a, loose);
      });
    }
    exports2.gt = gt;
    function gt(a, b, loose) {
      return compare(a, b, loose) > 0;
    }
    exports2.lt = lt;
    function lt(a, b, loose) {
      return compare(a, b, loose) < 0;
    }
    exports2.eq = eq2;
    function eq2(a, b, loose) {
      return compare(a, b, loose) === 0;
    }
    exports2.neq = neq;
    function neq(a, b, loose) {
      return compare(a, b, loose) !== 0;
    }
    exports2.gte = gte;
    function gte(a, b, loose) {
      return compare(a, b, loose) >= 0;
    }
    exports2.lte = lte;
    function lte(a, b, loose) {
      return compare(a, b, loose) <= 0;
    }
    exports2.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 eq2(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);
      }
    }
    exports2.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(" ");
      debug("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;
      }
      debug("comp", this);
    }
    var ANY = {};
    Comparator.prototype.parse = function(comp) {
      var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR];
      var m = comp.match(r);
      if (!m) {
        throw new TypeError("Invalid comparator: " + comp);
      }
      this.operator = m[1] !== void 0 ? 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(version3) {
      debug("Comparator.test", version3, this.options.loose);
      if (this.semver === ANY || version3 === ANY) {
        return true;
      }
      if (typeof version3 === "string") {
        try {
          version3 = new SemVer(version3, this.options);
        } catch (er) {
          return false;
        }
      }
      return cmp(version3, 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 === "") {
        if (this.value === "") {
          return true;
        }
        rangeTmp = new Range6(comp.value, options);
        return satisfies(this.value, rangeTmp, options);
      } else if (comp.operator === "") {
        if (comp.value === "") {
          return true;
        }
        rangeTmp = new Range6(this.value, options);
        return satisfies(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;
    };
    exports2.Range = Range6;
    function Range6(range, options) {
      if (!options || typeof options !== "object") {
        options = {
          loose: !!options,
          includePrerelease: false
        };
      }
      if (range instanceof Range6) {
        if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
          return range;
        } else {
          return new Range6(range.raw, options);
        }
      }
      if (range instanceof Comparator) {
        return new Range6(range.value, options);
      }
      if (!(this instanceof Range6)) {
        return new Range6(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();
    }
    Range6.prototype.format = function() {
      this.range = this.set.map(function(comps) {
        return comps.join(" ").trim();
      }).join("||").trim();
      return this.range;
    };
    Range6.prototype.toString = function() {
      return this.range;
    };
    Range6.prototype.parseRange = function(range) {
      var loose = this.options.loose;
      var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE];
      range = range.replace(hr, hyphenReplace);
      debug("hyphen replace", range);
      range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace);
      debug("comparator trim", range, safeRe[t.COMPARATORTRIM]);
      range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace);
      range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace);
      range = range.split(/\s+/).join(" ");
      var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.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;
    };
    Range6.prototype.intersects = function(range, options) {
      if (!(range instanceof Range6)) {
        throw new TypeError("a Range is required");
      }
      return this.set.some(function(thisComparators) {
        return isSatisfiable(thisComparators, options) && range.set.some(function(rangeComparators) {
          return isSatisfiable(rangeComparators, options) && thisComparators.every(function(thisComparator) {
            return rangeComparators.every(function(rangeComparator) {
              return thisComparator.intersects(rangeComparator, options);
            });
          });
        });
      });
    };
    function isSatisfiable(comparators, options) {
      var result = true;
      var remainingComparators = comparators.slice();
      var testComparator = remainingComparators.pop();
      while (result && remainingComparators.length) {
        result = remainingComparators.every(function(otherComparator) {
          return testComparator.intersects(otherComparator, options);
        });
        testComparator = remainingComparators.pop();
      }
      return result;
    }
    exports2.toComparators = toComparators;
    function toComparators(range, options) {
      return new Range6(range, options).set.map(function(comp) {
        return comp.map(function(c) {
          return c.value;
        }).join(" ").trim().split(" ");
      });
    }
    function parseComparator(comp, options) {
      debug("comp", comp, options);
      comp = replaceCarets(comp, options);
      debug("caret", comp);
      comp = replaceTildes(comp, options);
      debug("tildes", comp);
      comp = replaceXRanges(comp, options);
      debug("xrange", comp);
      comp = replaceStars(comp, options);
      debug("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[t.TILDELOOSE] : safeRe[t.TILDE];
      return comp.replace(r, function(_, M, m, p, pr) {
        debug("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) {
          debug("replaceTilde pr", pr);
          ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
        } else {
          ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
        }
        debug("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) {
      debug("caret", comp, options);
      var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET];
      return comp.replace(r, function(_, M, m, p, pr) {
        debug("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) {
          debug("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 {
          debug("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";
          }
        }
        debug("caret return", ret);
        return ret;
      });
    }
    function replaceXRanges(comp, options) {
      debug("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[t.XRANGELOOSE] : safeRe[t.XRANGE];
      return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
        debug("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 = "";
        }
        pr = options.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.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 + pr;
        } else if (xm) {
          ret = ">=" + M + ".0.0" + pr + " <" + (+M + 1) + ".0.0" + pr;
        } else if (xp) {
          ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr;
        }
        debug("xRange return", ret);
        return ret;
      });
    }
    function replaceStars(comp, options) {
      debug("replaceStars", comp, options);
      return comp.trim().replace(safeRe[t.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();
    }
    Range6.prototype.test = function(version3) {
      if (!version3) {
        return false;
      }
      if (typeof version3 === "string") {
        try {
          version3 = new SemVer(version3, this.options);
        } catch (er) {
          return false;
        }
      }
      for (var i2 = 0; i2 < this.set.length; i2++) {
        if (testSet(this.set[i2], version3, this.options)) {
          return true;
        }
      }
      return false;
    };
    function testSet(set, version3, options) {
      for (var i2 = 0; i2 < set.length; i2++) {
        if (!set[i2].test(version3)) {
          return false;
        }
      }
      if (version3.prerelease.length && !options.includePrerelease) {
        for (i2 = 0; i2 < set.length; i2++) {
          debug(set[i2].semver);
          if (set[i2].semver === ANY) {
            continue;
          }
          if (set[i2].semver.prerelease.length > 0) {
            var allowed = set[i2].semver;
            if (allowed.major === version3.major && allowed.minor === version3.minor && allowed.patch === version3.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    }
    exports2.satisfies = satisfies;
    function satisfies(version3, range, options) {
      try {
        range = new Range6(range, options);
      } catch (er) {
        return false;
      }
      return range.test(version3);
    }
    exports2.maxSatisfying = maxSatisfying;
    function maxSatisfying(versions, range, options) {
      var max2 = null;
      var maxSV = null;
      try {
        var rangeObj = new Range6(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach(function(v) {
        if (rangeObj.test(v)) {
          if (!max2 || maxSV.compare(v) === -1) {
            max2 = v;
            maxSV = new SemVer(max2, options);
          }
        }
      });
      return max2;
    }
    exports2.minSatisfying = minSatisfying;
    function minSatisfying(versions, range, options) {
      var min2 = null;
      var minSV = null;
      try {
        var rangeObj = new Range6(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach(function(v) {
        if (rangeObj.test(v)) {
          if (!min2 || minSV.compare(v) === 1) {
            min2 = v;
            minSV = new SemVer(min2, options);
          }
        }
      });
      return min2;
    }
    exports2.minVersion = minVersion;
    function minVersion(range, loose) {
      range = new Range6(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;
    }
    exports2.validRange = validRange;
    function validRange(range, options) {
      try {
        return new Range6(range, options).range || "*";
      } catch (er) {
        return null;
      }
    }
    exports2.ltr = ltr;
    function ltr(version3, range, options) {
      return outside(version3, range, "<", options);
    }
    exports2.gtr = gtr;
    function gtr(version3, range, options) {
      return outside(version3, range, ">", options);
    }
    exports2.outside = outside;
    function outside(version3, range, hilo, options) {
      version3 = new SemVer(version3, options);
      range = new Range6(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 (satisfies(version3, 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(version3, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version3, low.semver)) {
          return false;
        }
      }
      return true;
    }
    exports2.prerelease = prerelease;
    function prerelease(version3, options) {
      var parsed = parse6(version3, options);
      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
    }
    exports2.intersects = intersects;
    function intersects(r1, r2, options) {
      r1 = new Range6(r1, options);
      r2 = new Range6(r2, options);
      return r1.intersects(r2);
    }
    exports2.coerce = coerce;
    function coerce(version3, options) {
      if (version3 instanceof SemVer) {
        return version3;
      }
      if (typeof version3 === "number") {
        version3 = String(version3);
      }
      if (typeof version3 !== "string") {
        return null;
      }
      options = options || {};
      var match3 = null;
      if (!options.rtl) {
        match3 = version3.match(safeRe[t.COERCE]);
      } else {
        var next;
        while ((next = safeRe[t.COERCERTL].exec(version3)) && (!match3 || match3.index + match3[0].length !== version3.length)) {
          if (!match3 || next.index + next[0].length !== match3.index + match3[0].length) {
            match3 = next;
          }
          safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
        }
        safeRe[t.COERCERTL].lastIndex = -1;
      }
      if (match3 === null) {
        return null;
      }
      return parse6(match3[2] + "." + (match3[3] || "0") + "." + (match3[4] || "0"), options);
    }
  }
});

// node_modules/make-dir/index.js
var require_make_dir = __commonJS({
  "node_modules/make-dir/index.js"(exports2, module2) {
    "use strict";
    var fs4 = require("fs");
    var path3 = require("path");
    var { promisify: promisify2 } = require("util");
    var semver = require_semver();
    var useNativeRecursiveOption = semver.satisfies(process.version, ">=10.12.0");
    var checkPath = (pth) => {
      if (process.platform === "win32") {
        const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path3.parse(pth).root, ""));
        if (pathHasInvalidWinCharacters) {
          const error = new Error(`Path contains invalid characters: ${pth}`);
          error.code = "EINVAL";
          throw error;
        }
      }
    };
    var processOptions = (options) => {
      const defaults2 = {
        mode: 511,
        fs: fs4
      };
      return {
        ...defaults2,
        ...options
      };
    };
    var permissionError = (pth) => {
      const error = new Error(`operation not permitted, mkdir '${pth}'`);
      error.code = "EPERM";
      error.errno = -4048;
      error.path = pth;
      error.syscall = "mkdir";
      return error;
    };
    var makeDir2 = async (input2, options) => {
      checkPath(input2);
      options = processOptions(options);
      const mkdir2 = promisify2(options.fs.mkdir);
      const stat3 = promisify2(options.fs.stat);
      if (useNativeRecursiveOption && options.fs.mkdir === fs4.mkdir) {
        const pth = path3.resolve(input2);
        await mkdir2(pth, {
          mode: options.mode,
          recursive: true
        });
        return pth;
      }
      const make = async (pth) => {
        try {
          await mkdir2(pth, options.mode);
          return pth;
        } catch (error) {
          if (error.code === "EPERM") {
            throw error;
          }
          if (error.code === "ENOENT") {
            if (path3.dirname(pth) === pth) {
              throw permissionError(pth);
            }
            if (error.message.includes("null bytes")) {
              throw error;
            }
            await make(path3.dirname(pth));
            return make(pth);
          }
          try {
            const stats = await stat3(pth);
            if (!stats.isDirectory()) {
              throw new Error("The path is not a directory");
            }
          } catch (_) {
            throw error;
          }
          return pth;
        }
      };
      return make(path3.resolve(input2));
    };
    module2.exports = makeDir2;
    module2.exports.sync = (input2, options) => {
      checkPath(input2);
      options = processOptions(options);
      if (useNativeRecursiveOption && options.fs.mkdirSync === fs4.mkdirSync) {
        const pth = path3.resolve(input2);
        fs4.mkdirSync(pth, {
          mode: options.mode,
          recursive: true
        });
        return pth;
      }
      const make = (pth) => {
        try {
          options.fs.mkdirSync(pth, options.mode);
        } catch (error) {
          if (error.code === "EPERM") {
            throw error;
          }
          if (error.code === "ENOENT") {
            if (path3.dirname(pth) === pth) {
              throw permissionError(pth);
            }
            if (error.message.includes("null bytes")) {
              throw error;
            }
            make(path3.dirname(pth));
            return make(pth);
          }
          try {
            if (!options.fs.statSync(pth).isDirectory()) {
              throw new Error("The path is not a directory");
            }
          } catch (_) {
            throw error;
          }
        }
        return pth;
      };
      return make(path3.resolve(input2));
    };
  }
});

// node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
  "node_modules/balanced-match/index.js"(exports2, module2) {
    "use strict";
    module2.exports = balanced;
    function balanced(a, b, str) {
      if (a instanceof RegExp)
        a = maybeMatch(a, str);
      if (b instanceof RegExp)
        b = maybeMatch(b, str);
      var r = range(a, b, str);
      return r && {
        start: r[0],
        end: r[1],
        pre: str.slice(0, r[0]),
        body: str.slice(r[0] + a.length, r[1]),
        post: str.slice(r[1] + b.length)
      };
    }
    function maybeMatch(reg, str) {
      var m = str.match(reg);
      return m ? m[0] : null;
    }
    balanced.range = range;
    function range(a, b, str) {
      var begs, beg, left, right, result;
      var ai = str.indexOf(a);
      var bi = str.indexOf(b, ai + 1);
      var i = ai;
      if (ai >= 0 && bi > 0) {
        if (a === b) {
          return [ai, bi];
        }
        begs = [];
        left = str.length;
        while (i >= 0 && !result) {
          if (i == ai) {
            begs.push(i);
            ai = str.indexOf(a, i + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left) {
              left = beg;
              right = bi;
            }
            bi = str.indexOf(b, i + 1);
          }
          i = ai < bi && ai >= 0 ? ai : bi;
        }
        if (begs.length) {
          result = [left, right];
        }
      }
      return result;
    }
  }
});

// node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
  "node_modules/brace-expansion/index.js"(exports2, module2) {
    "use strict";
    var balanced = require_balanced_match();
    module2.exports = expandTop;
    var escSlash = "\0SLASH" + Math.random() + "\0";
    var escOpen = "\0OPEN" + Math.random() + "\0";
    var escClose = "\0CLOSE" + Math.random() + "\0";
    var escComma = "\0COMMA" + Math.random() + "\0";
    var escPeriod = "\0PERIOD" + Math.random() + "\0";
    function numeric(str) {
      return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
    }
    function escapeBraces(str) {
      return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
    }
    function unescapeBraces(str) {
      return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
    }
    function parseCommaParts(str) {
      if (!str)
        return [""];
      var parts = [];
      var m = balanced("{", "}", str);
      if (!m)
        return str.split(",");
      var pre = m.pre;
      var body = m.body;
      var post = m.post;
      var p = pre.split(",");
      p[p.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p[p.length - 1] += postParts.shift();
        p.push.apply(p, postParts);
      }
      parts.push.apply(parts, p);
      return parts;
    }
    function expandTop(str) {
      if (!str)
        return [];
      if (str.substr(0, 2) === "{}") {
        str = "\\{\\}" + str.substr(2);
      }
      return expand2(escapeBraces(str), true).map(unescapeBraces);
    }
    function embrace(str) {
      return "{" + str + "}";
    }
    function isPadded(el) {
      return /^-?0\d/.test(el);
    }
    function lte(i, y) {
      return i <= y;
    }
    function gte(i, y) {
      return i >= y;
    }
    function expand2(str, isTop) {
      var expansions = [];
      var m = balanced("{", "}", str);
      if (!m)
        return [str];
      var pre = m.pre;
      var post = m.post.length ? expand2(m.post, false) : [""];
      if (/\$$/.test(m.pre)) {
        for (var k = 0; k < post.length; k++) {
          var expansion = pre + "{" + m.body + "}" + post[k];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m.post.match(/,.*\}/)) {
            str = m.pre + "{" + m.body + escClose + m.post;
            return expand2(str);
          }
          return [str];
        }
        var n;
        if (isSequence) {
          n = m.body.split(/\.\./);
        } else {
          n = parseCommaParts(m.body);
          if (n.length === 1) {
            n = expand2(n[0], false).map(embrace);
            if (n.length === 1) {
              return post.map(function(p) {
                return m.pre + n[0] + p;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x = numeric(n[0]);
          var y = numeric(n[1]);
          var width = Math.max(n[0].length, n[1].length);
          var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
          var test = lte;
          var reverse = y < x;
          if (reverse) {
            incr *= -1;
            test = gte;
          }
          var pad = n.some(isPadded);
          N = [];
          for (var i = x; test(i, y); i += incr) {
            var c;
            if (isAlphaSequence) {
              c = String.fromCharCode(i);
              if (c === "\\")
                c = "";
            } else {
              c = String(i);
              if (pad) {
                var need = width - c.length;
                if (need > 0) {
                  var z = new Array(need + 1).join("0");
                  if (i < 0)
                    c = "-" + z + c.slice(1);
                  else
                    c = z + c;
                }
              }
            }
            N.push(c);
          }
        } else {
          N = [];
          for (var j = 0; j < n.length; j++) {
            N.push.apply(N, expand2(n[j], false));
          }
        }
        for (var j = 0; j < N.length; j++) {
          for (var k = 0; k < post.length; k++) {
            var expansion = pre + N[j] + post[k];
            if (!isTop || isSequence || expansion)
              expansions.push(expansion);
          }
        }
      }
      return expansions;
    }
  }
});

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

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

// node_modules/which/node_modules/isexe/dist/cjs/options.js
var require_options = __commonJS({
  "node_modules/which/node_modules/isexe/dist/cjs/options.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

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

// node_modules/which/lib/index.js
var require_lib = __commonJS({
  "node_modules/which/lib/index.js"(exports2, module2) {
    "use strict";
    var { isexe, sync: isexeSync } = require_cjs();
    var { join, delimiter, sep: sep2, posix: posix3 } = require("path");
    var isWindows3 = process.platform === "win32";
    var rSlash = new RegExp(`[${posix3.sep}${sep2 === posix3.sep ? "" : sep2}]`.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
        ...isWindows3 ? [process.cwd()] : [],
        ...(optPath || /* istanbul ignore next: very unusual */
        "").split(optDelimiter)
      ];
      if (isWindows3) {
        const pathExtExe = optPathExt || [".EXE", ".CMD", ".BAT", ".COM"].join(optDelimiter);
        const pathExt = pathExtExe.split(optDelimiter).flatMap((item) => [item, item.toLowerCase()]);
        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 + join(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 ext2 of pathExt) {
          const withExt = p + ext2;
          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 ext2 of pathExt) {
          const withExt = p + ext2;
          const is = isexeSync(withExt, { pathExt: pathExtExe, ignoreErrors: true });
          if (is) {
            if (!opt.all) {
              return withExt;
            }
            found.push(withExt);
          }
        }
      }
      if (opt.all && found.length) {
        return found;
      }
      if (opt.nothrow) {
        return null;
      }
      throw getNotFoundError(cmd);
    };
    module2.exports = which2;
    which2.sync = whichSync;
  }
});

// node_modules/minimatch/lib/path.js
var require_path = __commonJS({
  "node_modules/minimatch/lib/path.js"(exports2, module2) {
    "use strict";
    var isWindows3 = typeof process === "object" && process && process.platform === "win32";
    module2.exports = isWindows3 ? { sep: "\\" } : { sep: "/" };
  }
});

// node_modules/minimatch/minimatch.js
var require_minimatch = __commonJS({
  "node_modules/minimatch/minimatch.js"(exports2, module2) {
    "use strict";
    var minimatch4 = module2.exports = (p, pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch2(pattern, options).match(p);
    };
    module2.exports = minimatch4;
    var path3 = require_path();
    minimatch4.sep = path3.sep;
    var GLOBSTAR2 = Symbol("globstar **");
    minimatch4.GLOBSTAR = GLOBSTAR2;
    var expand2 = require_brace_expansion();
    var plTypes = {
      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
      "?": { open: "(?:", close: ")?" },
      "+": { open: "(?:", close: ")+" },
      "*": { open: "(?:", close: ")*" },
      "@": { open: "(?:", close: ")" }
    };
    var qmark3 = "[^/]";
    var star3 = qmark3 + "*?";
    var twoStarDot2 = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    var twoStarNoDot2 = "(?:(?!(?:\\/|^)\\.).)*?";
    var charSet = (s) => s.split("").reduce((set, c) => {
      set[c] = true;
      return set;
    }, {});
    var reSpecials2 = charSet("().*{}+?[]^$\\!");
    var addPatternStartSet = charSet("[.(");
    var slashSplit = /\/+/;
    minimatch4.filter = (pattern, options = {}) => (p, i, list) => minimatch4(p, pattern, options);
    var ext2 = (a, b = {}) => {
      const t = {};
      Object.keys(a).forEach((k) => t[k] = a[k]);
      Object.keys(b).forEach((k) => t[k] = b[k]);
      return t;
    };
    minimatch4.defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch4;
      }
      const orig = minimatch4;
      const m = (p, pattern, options) => orig(p, pattern, ext2(def, options));
      m.Minimatch = class Minimatch extends orig.Minimatch {
        constructor(pattern, options) {
          super(pattern, ext2(def, options));
        }
      };
      m.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
      m.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
      m.defaults = (options) => orig.defaults(ext2(def, options));
      m.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
      m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
      m.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
      return m;
    };
    minimatch4.braceExpand = (pattern, options) => braceExpand2(pattern, options);
    var braceExpand2 = (pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return expand2(pattern);
    };
    var MAX_PATTERN_LENGTH2 = 1024 * 64;
    var assertValidPattern2 = (pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH2) {
        throw new TypeError("pattern is too long");
      }
    };
    var SUBPARSE = Symbol("subparse");
    minimatch4.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
    minimatch4.match = (list, pattern, options = {}) => {
      const mm = new Minimatch2(pattern, options);
      list = list.filter((f) => mm.match(f));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    var globUnescape = (s) => s.replace(/\\(.)/g, "$1");
    var charUnescape = (s) => s.replace(/\\([^-\]])/g, "$1");
    var regExpEscape3 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    var braExpEscape = (s) => s.replace(/[[\]\\]/g, "\\$&");
    var Minimatch2 = class {
      constructor(pattern, options) {
        assertValidPattern2(pattern);
        if (!options)
          options = {};
        this.options = options;
        this.set = [];
        this.pattern = pattern;
        this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.regexp = null;
        this.negate = false;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.make();
      }
      debug() {
      }
      make() {
        const pattern = this.pattern;
        const options = this.options;
        if (!options.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        let set = this.globSet = this.braceExpand();
        if (options.debug)
          this.debug = (...args) => console.error(...args);
        this.debug(this.pattern, set);
        set = this.globParts = set.map((s) => s.split(slashSplit));
        this.debug(this.pattern, set);
        set = set.map((s, si, set2) => s.map(this.parse, this));
        this.debug(this.pattern, set);
        set = set.filter((s) => s.indexOf(false) === -1);
        this.debug(this.pattern, set);
        this.set = set;
      }
      parseNegate() {
        if (this.options.nonegate)
          return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset)
          this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial) {
        var options = this.options;
        this.debug(
          "matchOne",
          { "this": this, file, pattern }
        );
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p = pattern[pi];
          var f = file[fi];
          this.debug(pattern, p, f);
          if (p === false)
            return false;
          if (p === GLOBSTAR2) {
            this.debug("GLOBSTAR", [pattern, p, f]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
                  return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl)
                return true;
            }
            return false;
          }
          var hit;
          if (typeof p === "string") {
            hit = f === p;
            this.debug("string match", p, f, hit);
          } else {
            hit = f.match(p);
            this.debug("pattern match", p, f, hit);
          }
          if (!hit)
            return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        }
        throw new Error("wtf?");
      }
      braceExpand() {
        return braceExpand2(this.pattern, this.options);
      }
      parse(pattern, isSub) {
        assertValidPattern2(pattern);
        const options = this.options;
        if (pattern === "**") {
          if (!options.noglobstar)
            return GLOBSTAR2;
          else
            pattern = "*";
        }
        if (pattern === "")
          return "";
        let re = "";
        let hasMagic2 = false;
        let escaping = false;
        const patternListStack = [];
        const negativeLists = [];
        let stateChar;
        let inClass = false;
        let reClassStart = -1;
        let classStart = -1;
        let cs;
        let pl;
        let sp;
        let dotTravAllowed = pattern.charAt(0) === ".";
        let dotFileAllowed = options.dot || dotTravAllowed;
        const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const subPatternStart = (p) => p.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const clearStateChar = () => {
          if (stateChar) {
            switch (stateChar) {
              case "*":
                re += star3;
                hasMagic2 = true;
                break;
              case "?":
                re += qmark3;
                hasMagic2 = true;
                break;
              default:
                re += "\\" + stateChar;
                break;
            }
            this.debug("clearStateChar %j %j", stateChar, re);
            stateChar = false;
          }
        };
        for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) {
          this.debug("%s	%s %s %j", pattern, i, re, c);
          if (escaping) {
            if (c === "/") {
              return false;
            }
            if (reSpecials2[c]) {
              re += "\\";
            }
            re += c;
            escaping = false;
            continue;
          }
          switch (c) {
            case "/": {
              return false;
            }
            case "\\":
              if (inClass && pattern.charAt(i + 1) === "-") {
                re += c;
                continue;
              }
              clearStateChar();
              escaping = true;
              continue;
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i, re, c);
              if (inClass) {
                this.debug("  in class");
                if (c === "!" && i === classStart + 1)
                  c = "^";
                re += c;
                continue;
              }
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c;
              if (options.noext)
                clearStateChar();
              continue;
            case "(": {
              if (inClass) {
                re += "(";
                continue;
              }
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i - 1,
                reStart: re.length,
                open: plTypes[stateChar].open,
                close: plTypes[stateChar].close
              };
              this.debug(this.pattern, "	", plEntry);
              patternListStack.push(plEntry);
              re += plEntry.open;
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i + 1));
              }
              this.debug("plType %j %j", stateChar, re);
              stateChar = false;
              continue;
            }
            case ")": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (inClass || !plEntry) {
                re += "\\)";
                continue;
              }
              patternListStack.pop();
              clearStateChar();
              hasMagic2 = true;
              pl = plEntry;
              re += pl.close;
              if (pl.type === "!") {
                negativeLists.push(Object.assign(pl, { reEnd: re.length }));
              }
              continue;
            }
            case "|": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (inClass || !plEntry) {
                re += "\\|";
                continue;
              }
              clearStateChar();
              re += "|";
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i + 1));
              }
              continue;
            }
            case "[":
              clearStateChar();
              if (inClass) {
                re += "\\" + c;
                continue;
              }
              inClass = true;
              classStart = i;
              reClassStart = re.length;
              re += c;
              continue;
            case "]":
              if (i === classStart + 1 || !inClass) {
                re += "\\" + c;
                continue;
              }
              cs = pattern.substring(classStart + 1, i);
              try {
                RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
                re += c;
              } catch (er) {
                re = re.substring(0, reClassStart) + "(?:$.)";
              }
              hasMagic2 = true;
              inClass = false;
              continue;
            default:
              clearStateChar();
              if (reSpecials2[c] && !(c === "^" && inClass)) {
                re += "\\";
              }
              re += c;
              break;
          }
        }
        if (inClass) {
          cs = pattern.slice(classStart + 1);
          sp = this.parse(cs, SUBPARSE);
          re = re.substring(0, reClassStart) + "\\[" + sp[0];
          hasMagic2 = hasMagic2 || sp[1];
        }
        for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
          let tail;
          tail = re.slice(pl.reStart + pl.open.length);
          this.debug("setting tail", re, pl);
          tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t = pl.type === "*" ? star3 : pl.type === "?" ? qmark3 : "\\" + pl.type;
          hasMagic2 = true;
          re = re.slice(0, pl.reStart) + t + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart2 = addPatternStartSet[re.charAt(0)];
        for (let n = negativeLists.length - 1; n > -1; n--) {
          const nl = negativeLists[n];
          const nlBefore = re.slice(0, nl.reStart);
          const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
          let nlAfter = re.slice(nl.reEnd);
          const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
          const closeParensBefore = nlBefore.split(")").length;
          const openParensBefore = nlBefore.split("(").length - closeParensBefore;
          let cleanAfter = nlAfter;
          for (let i = 0; i < openParensBefore; i++) {
            cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
          }
          nlAfter = cleanAfter;
          const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
          re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
        }
        if (re !== "" && hasMagic2) {
          re = "(?=.)" + re;
        }
        if (addPatternStart2) {
          re = patternStart() + re;
        }
        if (isSub === SUBPARSE) {
          return [re, hasMagic2];
        }
        if (options.nocase && !hasMagic2) {
          hasMagic2 = pattern.toUpperCase() !== pattern.toLowerCase();
        }
        if (!hasMagic2) {
          return globUnescape(pattern);
        }
        const flags = options.nocase ? "i" : "";
        try {
          return Object.assign(new RegExp("^" + re + "$", flags), {
            _glob: pattern,
            _src: re
          });
        } catch (er) {
          return new RegExp("$.");
        }
      }
      makeRe() {
        if (this.regexp || this.regexp === false)
          return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar ? star3 : options.dot ? twoStarDot2 : twoStarNoDot2;
        const flags = options.nocase ? "i" : "";
        let re = set.map((pattern) => {
          pattern = pattern.map(
            (p) => typeof p === "string" ? regExpEscape3(p) : p === GLOBSTAR2 ? GLOBSTAR2 : p._src
          ).reduce((set2, p) => {
            if (!(set2[set2.length - 1] === GLOBSTAR2 && p === GLOBSTAR2)) {
              set2.push(p);
            }
            return set2;
          }, []);
          pattern.forEach((p, i) => {
            if (p !== GLOBSTAR2 || pattern[i - 1] === GLOBSTAR2) {
              return;
            }
            if (i === 0) {
              if (pattern.length > 1) {
                pattern[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i + 1];
              } else {
                pattern[i] = twoStar;
              }
            } else if (i === pattern.length - 1) {
              pattern[i - 1] += "(?:\\/|" + twoStar + ")?";
            } else {
              pattern[i - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i + 1];
              pattern[i + 1] = GLOBSTAR2;
            }
          });
          return pattern.filter((p) => p !== GLOBSTAR2).join("/");
        }).join("|");
        re = "^(?:" + re + ")$";
        if (this.negate)
          re = "^(?!" + re + ").*$";
        try {
          this.regexp = new RegExp(re, flags);
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      match(f, partial = this.partial) {
        this.debug("match", f, this.pattern);
        if (this.comment)
          return false;
        if (this.empty)
          return f === "";
        if (f === "/" && partial)
          return true;
        const options = this.options;
        if (path3.sep !== "/") {
          f = f.split(path3.sep).join("/");
        }
        f = f.split(slashSplit);
        this.debug(this.pattern, "split", f);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename;
        for (let i = f.length - 1; i >= 0; i--) {
          filename = f[i];
          if (filename)
            break;
        }
        for (let i = 0; i < set.length; i++) {
          const pattern = set[i];
          let file = f;
          if (options.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options.flipNegate)
              return true;
            return !this.negate;
          }
        }
        if (options.flipNegate)
          return false;
        return this.negate;
      }
      static defaults(def) {
        return minimatch4.defaults(def).Minimatch;
      }
    };
    minimatch4.Minimatch = Minimatch2;
  }
});

// node_modules/color-name/index.js
var require_color_name = __commonJS({
  "node_modules/color-name/index.js"(exports2, module2) {
    "use strict";
    module2.exports = {
      "aliceblue": [240, 248, 255],
      "antiquewhite": [250, 235, 215],
      "aqua": [0, 255, 255],
      "aquamarine": [127, 255, 212],
      "azure": [240, 255, 255],
      "beige": [245, 245, 220],
      "bisque": [255, 228, 196],
      "black": [0, 0, 0],
      "blanchedalmond": [255, 235, 205],
      "blue": [0, 0, 255],
      "blueviolet": [138, 43, 226],
      "brown": [165, 42, 42],
      "burlywood": [222, 184, 135],
      "cadetblue": [95, 158, 160],
      "chartreuse": [127, 255, 0],
      "chocolate": [210, 105, 30],
      "coral": [255, 127, 80],
      "cornflowerblue": [100, 149, 237],
      "cornsilk": [255, 248, 220],
      "crimson": [220, 20, 60],
      "cyan": [0, 255, 255],
      "darkblue": [0, 0, 139],
      "darkcyan": [0, 139, 139],
      "darkgoldenrod": [184, 134, 11],
      "darkgray": [169, 169, 169],
      "darkgreen": [0, 100, 0],
      "darkgrey": [169, 169, 169],
      "darkkhaki": [189, 183, 107],
      "darkmagenta": [139, 0, 139],
      "darkolivegreen": [85, 107, 47],
      "darkorange": [255, 140, 0],
      "darkorchid": [153, 50, 204],
      "darkred": [139, 0, 0],
      "darksalmon": [233, 150, 122],
      "darkseagreen": [143, 188, 143],
      "darkslateblue": [72, 61, 139],
      "darkslategray": [47, 79, 79],
      "darkslategrey": [47, 79, 79],
      "darkturquoise": [0, 206, 209],
      "darkviolet": [148, 0, 211],
      "deeppink": [255, 20, 147],
      "deepskyblue": [0, 191, 255],
      "dimgray": [105, 105, 105],
      "dimgrey": [105, 105, 105],
      "dodgerblue": [30, 144, 255],
      "firebrick": [178, 34, 34],
      "floralwhite": [255, 250, 240],
      "forestgreen": [34, 139, 34],
      "fuchsia": [255, 0, 255],
      "gainsboro": [220, 220, 220],
      "ghostwhite": [248, 248, 255],
      "gold": [255, 215, 0],
      "goldenrod": [218, 165, 32],
      "gray": [128, 128, 128],
      "green": [0, 128, 0],
      "greenyellow": [173, 255, 47],
      "grey": [128, 128, 128],
      "honeydew": [240, 255, 240],
      "hotpink": [255, 105, 180],
      "indianred": [205, 92, 92],
      "indigo": [75, 0, 130],
      "ivory": [255, 255, 240],
      "khaki": [240, 230, 140],
      "lavender": [230, 230, 250],
      "lavenderblush": [255, 240, 245],
      "lawngreen": [124, 252, 0],
      "lemonchiffon": [255, 250, 205],
      "lightblue": [173, 216, 230],
      "lightcoral": [240, 128, 128],
      "lightcyan": [224, 255, 255],
      "lightgoldenrodyellow": [250, 250, 210],
      "lightgray": [211, 211, 211],
      "lightgreen": [144, 238, 144],
      "lightgrey": [211, 211, 211],
      "lightpink": [255, 182, 193],
      "lightsalmon": [255, 160, 122],
      "lightseagreen": [32, 178, 170],
      "lightskyblue": [135, 206, 250],
      "lightslategray": [119, 136, 153],
      "lightslategrey": [119, 136, 153],
      "lightsteelblue": [176, 196, 222],
      "lightyellow": [255, 255, 224],
      "lime": [0, 255, 0],
      "limegreen": [50, 205, 50],
      "linen": [250, 240, 230],
      "magenta": [255, 0, 255],
      "maroon": [128, 0, 0],
      "mediumaquamarine": [102, 205, 170],
      "mediumblue": [0, 0, 205],
      "mediumorchid": [186, 85, 211],
      "mediumpurple": [147, 112, 219],
      "mediumseagreen": [60, 179, 113],
      "mediumslateblue": [123, 104, 238],
      "mediumspringgreen": [0, 250, 154],
      "mediumturquoise": [72, 209, 204],
      "mediumvioletred": [199, 21, 133],
      "midnightblue": [25, 25, 112],
      "mintcream": [245, 255, 250],
      "mistyrose": [255, 228, 225],
      "moccasin": [255, 228, 181],
      "navajowhite": [255, 222, 173],
      "navy": [0, 0, 128],
      "oldlace": [253, 245, 230],
      "olive": [128, 128, 0],
      "olivedrab": [107, 142, 35],
      "orange": [255, 165, 0],
      "orangered": [255, 69, 0],
      "orchid": [218, 112, 214],
      "palegoldenrod": [238, 232, 170],
      "palegreen": [152, 251, 152],
      "paleturquoise": [175, 238, 238],
      "palevioletred": [219, 112, 147],
      "papayawhip": [255, 239, 213],
      "peachpuff": [255, 218, 185],
      "peru": [205, 133, 63],
      "pink": [255, 192, 203],
      "plum": [221, 160, 221],
      "powderblue": [176, 224, 230],
      "purple": [128, 0, 128],
      "rebeccapurple": [102, 51, 153],
      "red": [255, 0, 0],
      "rosybrown": [188, 143, 143],
      "royalblue": [65, 105, 225],
      "saddlebrown": [139, 69, 19],
      "salmon": [250, 128, 114],
      "sandybrown": [244, 164, 96],
      "seagreen": [46, 139, 87],
      "seashell": [255, 245, 238],
      "sienna": [160, 82, 45],
      "silver": [192, 192, 192],
      "skyblue": [135, 206, 235],
      "slateblue": [106, 90, 205],
      "slategray": [112, 128, 144],
      "slategrey": [112, 128, 144],
      "snow": [255, 250, 250],
      "springgreen": [0, 255, 127],
      "steelblue": [70, 130, 180],
      "tan": [210, 180, 140],
      "teal": [0, 128, 128],
      "thistle": [216, 191, 216],
      "tomato": [255, 99, 71],
      "turquoise": [64, 224, 208],
      "violet": [238, 130, 238],
      "wheat": [245, 222, 179],
      "white": [255, 255, 255],
      "whitesmoke": [245, 245, 245],
      "yellow": [255, 255, 0],
      "yellowgreen": [154, 205, 50]
    };
  }
});

// node_modules/color-convert/conversions.js
var require_conversions = __commonJS({
  "node_modules/color-convert/conversions.js"(exports2, module2) {
    "use strict";
    var cssKeywords = require_color_name();
    var reverseKeywords = {};
    for (const key of Object.keys(cssKeywords)) {
      reverseKeywords[cssKeywords[key]] = key;
    }
    var convert2 = {
      rgb: { channels: 3, labels: "rgb" },
      hsl: { channels: 3, labels: "hsl" },
      hsv: { channels: 3, labels: "hsv" },
      hwb: { channels: 3, labels: "hwb" },
      cmyk: { channels: 4, labels: "cmyk" },
      xyz: { channels: 3, labels: "xyz" },
      lab: { channels: 3, labels: "lab" },
      lch: { channels: 3, labels: "lch" },
      hex: { channels: 1, labels: ["hex"] },
      keyword: { channels: 1, labels: ["keyword"] },
      ansi16: { channels: 1, labels: ["ansi16"] },
      ansi256: { channels: 1, labels: ["ansi256"] },
      hcg: { channels: 3, labels: ["h", "c", "g"] },
      apple: { channels: 3, labels: ["r16", "g16", "b16"] },
      gray: { channels: 1, labels: ["gray"] }
    };
    module2.exports = convert2;
    for (const model of Object.keys(convert2)) {
      if (!("channels" in convert2[model])) {
        throw new Error("missing channels property: " + model);
      }
      if (!("labels" in convert2[model])) {
        throw new Error("missing channel labels property: " + model);
      }
      if (convert2[model].labels.length !== convert2[model].channels) {
        throw new Error("channel and label counts mismatch: " + model);
      }
      const { channels, labels } = convert2[model];
      delete convert2[model].channels;
      delete convert2[model].labels;
      Object.defineProperty(convert2[model], "channels", { value: channels });
      Object.defineProperty(convert2[model], "labels", { value: labels });
    }
    convert2.rgb.hsl = function(rgb) {
      const r = rgb[0] / 255;
      const g = rgb[1] / 255;
      const b = rgb[2] / 255;
      const min2 = Math.min(r, g, b);
      const max2 = Math.max(r, g, b);
      const delta = max2 - min2;
      let h;
      let s;
      if (max2 === min2) {
        h = 0;
      } else if (r === max2) {
        h = (g - b) / delta;
      } else if (g === max2) {
        h = 2 + (b - r) / delta;
      } else if (b === max2) {
        h = 4 + (r - g) / delta;
      }
      h = Math.min(h * 60, 360);
      if (h < 0) {
        h += 360;
      }
      const l = (min2 + max2) / 2;
      if (max2 === min2) {
        s = 0;
      } else if (l <= 0.5) {
        s = delta / (max2 + min2);
      } else {
        s = delta / (2 - max2 - min2);
      }
      return [h, s * 100, l * 100];
    };
    convert2.rgb.hsv = function(rgb) {
      let rdif;
      let gdif;
      let bdif;
      let h;
      let s;
      const r = rgb[0] / 255;
      const g = rgb[1] / 255;
      const b = rgb[2] / 255;
      const v = Math.max(r, g, b);
      const diff = v - Math.min(r, g, b);
      const diffc = function(c) {
        return (v - c) / 6 / diff + 1 / 2;
      };
      if (diff === 0) {
        h = 0;
        s = 0;
      } else {
        s = diff / v;
        rdif = diffc(r);
        gdif = diffc(g);
        bdif = diffc(b);
        if (r === v) {
          h = bdif - gdif;
        } else if (g === v) {
          h = 1 / 3 + rdif - bdif;
        } else if (b === v) {
          h = 2 / 3 + gdif - rdif;
        }
        if (h < 0) {
          h += 1;
        } else if (h > 1) {
          h -= 1;
        }
      }
      return [
        h * 360,
        s * 100,
        v * 100
      ];
    };
    convert2.rgb.hwb = function(rgb) {
      const r = rgb[0];
      const g = rgb[1];
      let b = rgb[2];
      const h = convert2.rgb.hsl(rgb)[0];
      const w = 1 / 255 * Math.min(r, Math.min(g, b));
      b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
      return [h, w * 100, b * 100];
    };
    convert2.rgb.cmyk = function(rgb) {
      const r = rgb[0] / 255;
      const g = rgb[1] / 255;
      const b = rgb[2] / 255;
      const k = Math.min(1 - r, 1 - g, 1 - b);
      const c = (1 - r - k) / (1 - k) || 0;
      const m = (1 - g - k) / (1 - k) || 0;
      const y = (1 - b - k) / (1 - k) || 0;
      return [c * 100, m * 100, y * 100, k * 100];
    };
    function comparativeDistance(x, y) {
      return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
    }
    convert2.rgb.keyword = function(rgb) {
      const reversed = reverseKeywords[rgb];
      if (reversed) {
        return reversed;
      }
      let currentClosestDistance = Infinity;
      let currentClosestKeyword;
      for (const keyword of Object.keys(cssKeywords)) {
        const value = cssKeywords[keyword];
        const distance = comparativeDistance(rgb, value);
        if (distance < currentClosestDistance) {
          currentClosestDistance = distance;
          currentClosestKeyword = keyword;
        }
      }
      return currentClosestKeyword;
    };
    convert2.keyword.rgb = function(keyword) {
      return cssKeywords[keyword];
    };
    convert2.rgb.xyz = function(rgb) {
      let r = rgb[0] / 255;
      let g = rgb[1] / 255;
      let b = rgb[2] / 255;
      r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
      g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
      b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
      const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
      const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
      const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
      return [x * 100, y * 100, z * 100];
    };
    convert2.rgb.lab = function(rgb) {
      const xyz = convert2.rgb.xyz(rgb);
      let x = xyz[0];
      let y = xyz[1];
      let z = xyz[2];
      x /= 95.047;
      y /= 100;
      z /= 108.883;
      x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
      y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
      z = z > 8856e-6 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
      const l = 116 * y - 16;
      const a = 500 * (x - y);
      const b = 200 * (y - z);
      return [l, a, b];
    };
    convert2.hsl.rgb = function(hsl) {
      const h = hsl[0] / 360;
      const s = hsl[1] / 100;
      const l = hsl[2] / 100;
      let t2;
      let t3;
      let val;
      if (s === 0) {
        val = l * 255;
        return [val, val, val];
      }
      if (l < 0.5) {
        t2 = l * (1 + s);
      } else {
        t2 = l + s - l * s;
      }
      const t1 = 2 * l - t2;
      const rgb = [0, 0, 0];
      for (let i = 0; i < 3; i++) {
        t3 = h + 1 / 3 * -(i - 1);
        if (t3 < 0) {
          t3++;
        }
        if (t3 > 1) {
          t3--;
        }
        if (6 * t3 < 1) {
          val = t1 + (t2 - t1) * 6 * t3;
        } else if (2 * t3 < 1) {
          val = t2;
        } else if (3 * t3 < 2) {
          val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
        } else {
          val = t1;
        }
        rgb[i] = val * 255;
      }
      return rgb;
    };
    convert2.hsl.hsv = function(hsl) {
      const h = hsl[0];
      let s = hsl[1] / 100;
      let l = hsl[2] / 100;
      let smin = s;
      const lmin = Math.max(l, 0.01);
      l *= 2;
      s *= l <= 1 ? l : 2 - l;
      smin *= lmin <= 1 ? lmin : 2 - lmin;
      const v = (l + s) / 2;
      const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
      return [h, sv * 100, v * 100];
    };
    convert2.hsv.rgb = function(hsv) {
      const h = hsv[0] / 60;
      const s = hsv[1] / 100;
      let v = hsv[2] / 100;
      const hi = Math.floor(h) % 6;
      const f = h - Math.floor(h);
      const p = 255 * v * (1 - s);
      const q = 255 * v * (1 - s * f);
      const t = 255 * v * (1 - s * (1 - f));
      v *= 255;
      switch (hi) {
        case 0:
          return [v, t, p];
        case 1:
          return [q, v, p];
        case 2:
          return [p, v, t];
        case 3:
          return [p, q, v];
        case 4:
          return [t, p, v];
        case 5:
          return [v, p, q];
      }
    };
    convert2.hsv.hsl = function(hsv) {
      const h = hsv[0];
      const s = hsv[1] / 100;
      const v = hsv[2] / 100;
      const vmin = Math.max(v, 0.01);
      let sl;
      let l;
      l = (2 - s) * v;
      const lmin = (2 - s) * vmin;
      sl = s * vmin;
      sl /= lmin <= 1 ? lmin : 2 - lmin;
      sl = sl || 0;
      l /= 2;
      return [h, sl * 100, l * 100];
    };
    convert2.hwb.rgb = function(hwb) {
      const h = hwb[0] / 360;
      let wh = hwb[1] / 100;
      let bl = hwb[2] / 100;
      const ratio = wh + bl;
      let f;
      if (ratio > 1) {
        wh /= ratio;
        bl /= ratio;
      }
      const i = Math.floor(6 * h);
      const v = 1 - bl;
      f = 6 * h - i;
      if ((i & 1) !== 0) {
        f = 1 - f;
      }
      const n = wh + f * (v - wh);
      let r;
      let g;
      let b;
      switch (i) {
        default:
        case 6:
        case 0:
          r = v;
          g = n;
          b = wh;
          break;
        case 1:
          r = n;
          g = v;
          b = wh;
          break;
        case 2:
          r = wh;
          g = v;
          b = n;
          break;
        case 3:
          r = wh;
          g = n;
          b = v;
          break;
        case 4:
          r = n;
          g = wh;
          b = v;
          break;
        case 5:
          r = v;
          g = wh;
          b = n;
          break;
      }
      return [r * 255, g * 255, b * 255];
    };
    convert2.cmyk.rgb = function(cmyk) {
      const c = cmyk[0] / 100;
      const m = cmyk[1] / 100;
      const y = cmyk[2] / 100;
      const k = cmyk[3] / 100;
      const r = 1 - Math.min(1, c * (1 - k) + k);
      const g = 1 - Math.min(1, m * (1 - k) + k);
      const b = 1 - Math.min(1, y * (1 - k) + k);
      return [r * 255, g * 255, b * 255];
    };
    convert2.xyz.rgb = function(xyz) {
      const x = xyz[0] / 100;
      const y = xyz[1] / 100;
      const z = xyz[2] / 100;
      let r;
      let g;
      let b;
      r = x * 3.2406 + y * -1.5372 + z * -0.4986;
      g = x * -0.9689 + y * 1.8758 + z * 0.0415;
      b = x * 0.0557 + y * -0.204 + z * 1.057;
      r = r > 31308e-7 ? 1.055 * r ** (1 / 2.4) - 0.055 : r * 12.92;
      g = g > 31308e-7 ? 1.055 * g ** (1 / 2.4) - 0.055 : g * 12.92;
      b = b > 31308e-7 ? 1.055 * b ** (1 / 2.4) - 0.055 : b * 12.92;
      r = Math.min(Math.max(0, r), 1);
      g = Math.min(Math.max(0, g), 1);
      b = Math.min(Math.max(0, b), 1);
      return [r * 255, g * 255, b * 255];
    };
    convert2.xyz.lab = function(xyz) {
      let x = xyz[0];
      let y = xyz[1];
      let z = xyz[2];
      x /= 95.047;
      y /= 100;
      z /= 108.883;
      x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
      y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
      z = z > 8856e-6 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
      const l = 116 * y - 16;
      const a = 500 * (x - y);
      const b = 200 * (y - z);
      return [l, a, b];
    };
    convert2.lab.xyz = function(lab) {
      const l = lab[0];
      const a = lab[1];
      const b = lab[2];
      let x;
      let y;
      let z;
      y = (l + 16) / 116;
      x = a / 500 + y;
      z = y - b / 200;
      const y2 = y ** 3;
      const x2 = x ** 3;
      const z2 = z ** 3;
      y = y2 > 8856e-6 ? y2 : (y - 16 / 116) / 7.787;
      x = x2 > 8856e-6 ? x2 : (x - 16 / 116) / 7.787;
      z = z2 > 8856e-6 ? z2 : (z - 16 / 116) / 7.787;
      x *= 95.047;
      y *= 100;
      z *= 108.883;
      return [x, y, z];
    };
    convert2.lab.lch = function(lab) {
      const l = lab[0];
      const a = lab[1];
      const b = lab[2];
      let h;
      const hr = Math.atan2(b, a);
      h = hr * 360 / 2 / Math.PI;
      if (h < 0) {
        h += 360;
      }
      const c = Math.sqrt(a * a + b * b);
      return [l, c, h];
    };
    convert2.lch.lab = function(lch) {
      const l = lch[0];
      const c = lch[1];
      const h = lch[2];
      const hr = h / 360 * 2 * Math.PI;
      const a = c * Math.cos(hr);
      const b = c * Math.sin(hr);
      return [l, a, b];
    };
    convert2.rgb.ansi16 = function(args, saturation = null) {
      const [r, g, b] = args;
      let value = saturation === null ? convert2.rgb.hsv(args)[2] : saturation;
      value = Math.round(value / 50);
      if (value === 0) {
        return 30;
      }
      let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
      if (value === 2) {
        ansi += 60;
      }
      return ansi;
    };
    convert2.hsv.ansi16 = function(args) {
      return convert2.rgb.ansi16(convert2.hsv.rgb(args), args[2]);
    };
    convert2.rgb.ansi256 = function(args) {
      const r = args[0];
      const g = args[1];
      const b = args[2];
      if (r === g && g === b) {
        if (r < 8) {
          return 16;
        }
        if (r > 248) {
          return 231;
        }
        return Math.round((r - 8) / 247 * 24) + 232;
      }
      const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
      return ansi;
    };
    convert2.ansi16.rgb = function(args) {
      let color = args % 10;
      if (color === 0 || color === 7) {
        if (args > 50) {
          color += 3.5;
        }
        color = color / 10.5 * 255;
        return [color, color, color];
      }
      const mult = (~~(args > 50) + 1) * 0.5;
      const r = (color & 1) * mult * 255;
      const g = (color >> 1 & 1) * mult * 255;
      const b = (color >> 2 & 1) * mult * 255;
      return [r, g, b];
    };
    convert2.ansi256.rgb = function(args) {
      if (args >= 232) {
        const c = (args - 232) * 10 + 8;
        return [c, c, c];
      }
      args -= 16;
      let rem;
      const r = Math.floor(args / 36) / 5 * 255;
      const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
      const b = rem % 6 / 5 * 255;
      return [r, g, b];
    };
    convert2.rgb.hex = function(args) {
      const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
      const string = integer.toString(16).toUpperCase();
      return "000000".substring(string.length) + string;
    };
    convert2.hex.rgb = function(args) {
      const match3 = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
      if (!match3) {
        return [0, 0, 0];
      }
      let colorString = match3[0];
      if (match3[0].length === 3) {
        colorString = colorString.split("").map((char) => {
          return char + char;
        }).join("");
      }
      const integer = parseInt(colorString, 16);
      const r = integer >> 16 & 255;
      const g = integer >> 8 & 255;
      const b = integer & 255;
      return [r, g, b];
    };
    convert2.rgb.hcg = function(rgb) {
      const r = rgb[0] / 255;
      const g = rgb[1] / 255;
      const b = rgb[2] / 255;
      const max2 = Math.max(Math.max(r, g), b);
      const min2 = Math.min(Math.min(r, g), b);
      const chroma = max2 - min2;
      let grayscale;
      let hue;
      if (chroma < 1) {
        grayscale = min2 / (1 - chroma);
      } else {
        grayscale = 0;
      }
      if (chroma <= 0) {
        hue = 0;
      } else if (max2 === r) {
        hue = (g - b) / chroma % 6;
      } else if (max2 === g) {
        hue = 2 + (b - r) / chroma;
      } else {
        hue = 4 + (r - g) / chroma;
      }
      hue /= 6;
      hue %= 1;
      return [hue * 360, chroma * 100, grayscale * 100];
    };
    convert2.hsl.hcg = function(hsl) {
      const s = hsl[1] / 100;
      const l = hsl[2] / 100;
      const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l);
      let f = 0;
      if (c < 1) {
        f = (l - 0.5 * c) / (1 - c);
      }
      return [hsl[0], c * 100, f * 100];
    };
    convert2.hsv.hcg = function(hsv) {
      const s = hsv[1] / 100;
      const v = hsv[2] / 100;
      const c = s * v;
      let f = 0;
      if (c < 1) {
        f = (v - c) / (1 - c);
      }
      return [hsv[0], c * 100, f * 100];
    };
    convert2.hcg.rgb = function(hcg) {
      const h = hcg[0] / 360;
      const c = hcg[1] / 100;
      const g = hcg[2] / 100;
      if (c === 0) {
        return [g * 255, g * 255, g * 255];
      }
      const pure = [0, 0, 0];
      const hi = h % 1 * 6;
      const v = hi % 1;
      const w = 1 - v;
      let mg = 0;
      switch (Math.floor(hi)) {
        case 0:
          pure[0] = 1;
          pure[1] = v;
          pure[2] = 0;
          break;
        case 1:
          pure[0] = w;
          pure[1] = 1;
          pure[2] = 0;
          break;
        case 2:
          pure[0] = 0;
          pure[1] = 1;
          pure[2] = v;
          break;
        case 3:
          pure[0] = 0;
          pure[1] = w;
          pure[2] = 1;
          break;
        case 4:
          pure[0] = v;
          pure[1] = 0;
          pure[2] = 1;
          break;
        default:
          pure[0] = 1;
          pure[1] = 0;
          pure[2] = w;
      }
      mg = (1 - c) * g;
      return [
        (c * pure[0] + mg) * 255,
        (c * pure[1] + mg) * 255,
        (c * pure[2] + mg) * 255
      ];
    };
    convert2.hcg.hsv = function(hcg) {
      const c = hcg[1] / 100;
      const g = hcg[2] / 100;
      const v = c + g * (1 - c);
      let f = 0;
      if (v > 0) {
        f = c / v;
      }
      return [hcg[0], f * 100, v * 100];
    };
    convert2.hcg.hsl = function(hcg) {
      const c = hcg[1] / 100;
      const g = hcg[2] / 100;
      const l = g * (1 - c) + 0.5 * c;
      let s = 0;
      if (l > 0 && l < 0.5) {
        s = c / (2 * l);
      } else if (l >= 0.5 && l < 1) {
        s = c / (2 * (1 - l));
      }
      return [hcg[0], s * 100, l * 100];
    };
    convert2.hcg.hwb = function(hcg) {
      const c = hcg[1] / 100;
      const g = hcg[2] / 100;
      const v = c + g * (1 - c);
      return [hcg[0], (v - c) * 100, (1 - v) * 100];
    };
    convert2.hwb.hcg = function(hwb) {
      const w = hwb[1] / 100;
      const b = hwb[2] / 100;
      const v = 1 - b;
      const c = v - w;
      let g = 0;
      if (c < 1) {
        g = (v - c) / (1 - c);
      }
      return [hwb[0], c * 100, g * 100];
    };
    convert2.apple.rgb = function(apple) {
      return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
    };
    convert2.rgb.apple = function(rgb) {
      return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
    };
    convert2.gray.rgb = function(args) {
      return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
    };
    convert2.gray.hsl = function(args) {
      return [0, 0, args[0]];
    };
    convert2.gray.hsv = convert2.gray.hsl;
    convert2.gray.hwb = function(gray) {
      return [0, 100, gray[0]];
    };
    convert2.gray.cmyk = function(gray) {
      return [0, 0, 0, gray[0]];
    };
    convert2.gray.lab = function(gray) {
      return [gray[0], 0, 0];
    };
    convert2.gray.hex = function(gray) {
      const val = Math.round(gray[0] / 100 * 255) & 255;
      const integer = (val << 16) + (val << 8) + val;
      const string = integer.toString(16).toUpperCase();
      return "000000".substring(string.length) + string;
    };
    convert2.rgb.gray = function(rgb) {
      const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
      return [val / 255 * 100];
    };
  }
});

// node_modules/color-convert/route.js
var require_route = __commonJS({
  "node_modules/color-convert/route.js"(exports2, module2) {
    "use strict";
    var conversions = require_conversions();
    function buildGraph() {
      const graph = {};
      const models = Object.keys(conversions);
      for (let len = models.length, i = 0; i < len; i++) {
        graph[models[i]] = {
          // http://jsperf.com/1-vs-infinity
          // micro-opt, but this is simple.
          distance: -1,
          parent: null
        };
      }
      return graph;
    }
    function deriveBFS(fromModel) {
      const graph = buildGraph();
      const queue = [fromModel];
      graph[fromModel].distance = 0;
      while (queue.length) {
        const current = queue.pop();
        const adjacents = Object.keys(conversions[current]);
        for (let len = adjacents.length, i = 0; i < len; i++) {
          const adjacent = adjacents[i];
          const node = graph[adjacent];
          if (node.distance === -1) {
            node.distance = graph[current].distance + 1;
            node.parent = current;
            queue.unshift(adjacent);
          }
        }
      }
      return graph;
    }
    function link(from, to) {
      return function(args) {
        return to(from(args));
      };
    }
    function wrapConversion(toModel, graph) {
      const path3 = [graph[toModel].parent, toModel];
      let fn = conversions[graph[toModel].parent][toModel];
      let cur = graph[toModel].parent;
      while (graph[cur].parent) {
        path3.unshift(graph[cur].parent);
        fn = link(conversions[graph[cur].parent][cur], fn);
        cur = graph[cur].parent;
      }
      fn.conversion = path3;
      return fn;
    }
    module2.exports = function(fromModel) {
      const graph = deriveBFS(fromModel);
      const conversion = {};
      const models = Object.keys(graph);
      for (let len = models.length, i = 0; i < len; i++) {
        const toModel = models[i];
        const node = graph[toModel];
        if (node.parent === null) {
          continue;
        }
        conversion[toModel] = wrapConversion(toModel, graph);
      }
      return conversion;
    };
  }
});

// node_modules/color-convert/index.js
var require_color_convert = __commonJS({
  "node_modules/color-convert/index.js"(exports2, module2) {
    "use strict";
    var conversions = require_conversions();
    var route = require_route();
    var convert2 = {};
    var models = Object.keys(conversions);
    function wrapRaw(fn) {
      const wrappedFn = function(...args) {
        const arg0 = args[0];
        if (arg0 === void 0 || arg0 === null) {
          return arg0;
        }
        if (arg0.length > 1) {
          args = arg0;
        }
        return fn(args);
      };
      if ("conversion" in fn) {
        wrappedFn.conversion = fn.conversion;
      }
      return wrappedFn;
    }
    function wrapRounded(fn) {
      const wrappedFn = function(...args) {
        const arg0 = args[0];
        if (arg0 === void 0 || arg0 === null) {
          return arg0;
        }
        if (arg0.length > 1) {
          args = arg0;
        }
        const result = fn(args);
        if (typeof result === "object") {
          for (let len = result.length, i = 0; i < len; i++) {
            result[i] = Math.round(result[i]);
          }
        }
        return result;
      };
      if ("conversion" in fn) {
        wrappedFn.conversion = fn.conversion;
      }
      return wrappedFn;
    }
    models.forEach((fromModel) => {
      convert2[fromModel] = {};
      Object.defineProperty(convert2[fromModel], "channels", { value: conversions[fromModel].channels });
      Object.defineProperty(convert2[fromModel], "labels", { value: conversions[fromModel].labels });
      const routes = route(fromModel);
      const routeModels = Object.keys(routes);
      routeModels.forEach((toModel) => {
        const fn = routes[toModel];
        convert2[fromModel][toModel] = wrapRounded(fn);
        convert2[fromModel][toModel].raw = wrapRaw(fn);
      });
    });
    module2.exports = convert2;
  }
});

// node_modules/p-map/index.js
var require_p_map = __commonJS({
  "node_modules/p-map/index.js"(exports2, module2) {
    "use strict";
    var pMap = (iterable, mapper, options) => new Promise((resolve6, reject) => {
      options = Object.assign({
        concurrency: Infinity
      }, options);
      if (typeof mapper !== "function") {
        throw new TypeError("Mapper function is required");
      }
      const { concurrency } = options;
      if (!(typeof concurrency === "number" && concurrency >= 1)) {
        throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`);
      }
      const ret = [];
      const iterator2 = iterable[Symbol.iterator]();
      let isRejected = false;
      let isIterableDone = false;
      let resolvingCount = 0;
      let currentIndex = 0;
      const next = () => {
        if (isRejected) {
          return;
        }
        const nextItem = iterator2.next();
        const i = currentIndex;
        currentIndex++;
        if (nextItem.done) {
          isIterableDone = true;
          if (resolvingCount === 0) {
            resolve6(ret);
          }
          return;
        }
        resolvingCount++;
        Promise.resolve(nextItem.value).then((element) => mapper(element, i)).then(
          (value) => {
            ret[i] = value;
            resolvingCount--;
            next();
          },
          (error) => {
            isRejected = true;
            reject(error);
          }
        );
      };
      for (let i = 0; i < concurrency; i++) {
        next();
        if (isIterableDone) {
          break;
        }
      }
    });
    module2.exports = pMap;
    module2.exports.default = pMap;
  }
});

// node_modules/p-filter/index.js
var require_p_filter = __commonJS({
  "node_modules/p-filter/index.js"(exports2, module2) {
    "use strict";
    var pMap = require_p_map();
    var pFilter3 = async (iterable, filterer, options) => {
      const values = await pMap(
        iterable,
        (element, index) => Promise.all([filterer(element, index), element]),
        options
      );
      return values.filter((value) => Boolean(value[0])).map((value) => value[1]);
    };
    module2.exports = pFilter3;
    module2.exports.default = pFilter3;
  }
});

// node_modules/command-exists/lib/command-exists.js
var require_command_exists = __commonJS({
  "node_modules/command-exists/lib/command-exists.js"(exports2, module2) {
    "use strict";
    var exec2 = require("child_process").exec;
    var execSync = require("child_process").execSync;
    var fs4 = require("fs");
    var path3 = require("path");
    var access = fs4.access;
    var accessSync = fs4.accessSync;
    var constants = fs4.constants || fs4;
    var isUsingWindows = process.platform == "win32";
    var fileNotExists = function(commandName, callback) {
      access(
        commandName,
        constants.F_OK,
        function(err) {
          callback(!err);
        }
      );
    };
    var fileNotExistsSync = function(commandName) {
      try {
        accessSync(commandName, constants.F_OK);
        return false;
      } catch (e) {
        return true;
      }
    };
    var localExecutable = function(commandName, callback) {
      access(
        commandName,
        constants.F_OK | constants.X_OK,
        function(err) {
          callback(null, !err);
        }
      );
    };
    var localExecutableSync = function(commandName) {
      try {
        accessSync(commandName, constants.F_OK | constants.X_OK);
        return true;
      } catch (e) {
        return false;
      }
    };
    var commandExistsUnix = function(commandName, cleanedCommandName, callback) {
      fileNotExists(commandName, function(isFile) {
        if (!isFile) {
          var child = exec2(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }",
            function(error, stdout, stderr) {
              callback(null, !!stdout);
            }
          );
          return;
        }
        localExecutable(commandName, callback);
      });
    };
    var commandExistsWindows = function(commandName, cleanedCommandName, callback) {
      if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
        callback(null, false);
        return;
      }
      var child = exec2(
        "where " + cleanedCommandName,
        function(error) {
          if (error !== null) {
            callback(null, false);
          } else {
            callback(null, true);
          }
        }
      );
    };
    var commandExistsUnixSync = function(commandName, cleanedCommandName) {
      if (fileNotExistsSync(commandName)) {
        try {
          var stdout = execSync(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }"
          );
          return !!stdout;
        } catch (error) {
          return false;
        }
      }
      return localExecutableSync(commandName);
    };
    var commandExistsWindowsSync = function(commandName, cleanedCommandName, callback) {
      if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
        return false;
      }
      try {
        var stdout = execSync("where " + cleanedCommandName, { stdio: [] });
        return !!stdout;
      } catch (error) {
        return false;
      }
    };
    var cleanInput = function(s) {
      if (/[^A-Za-z0-9_\/:=-]/.test(s)) {
        s = "'" + s.replace(/'/g, "'\\''") + "'";
        s = s.replace(/^(?:'')+/g, "").replace(/\\'''/g, "\\'");
      }
      return s;
    };
    if (isUsingWindows) {
      cleanInput = function(s) {
        var isPathName = /[\\]/.test(s);
        if (isPathName) {
          var dirname = '"' + path3.dirname(s) + '"';
          var basename2 = '"' + path3.basename(s) + '"';
          return dirname + ":" + basename2;
        }
        return '"' + s + '"';
      };
    }
    module2.exports = function commandExists2(commandName, callback) {
      var cleanedCommandName = cleanInput(commandName);
      if (!callback && typeof Promise !== "undefined") {
        return new Promise(function(resolve6, reject) {
          commandExists2(commandName, function(error, output) {
            if (output) {
              resolve6(commandName);
            } else {
              reject(error);
            }
          });
        });
      }
      if (isUsingWindows) {
        commandExistsWindows(commandName, cleanedCommandName, callback);
      } else {
        commandExistsUnix(commandName, cleanedCommandName, callback);
      }
    };
    module2.exports.sync = function(commandName) {
      var cleanedCommandName = cleanInput(commandName);
      if (isUsingWindows) {
        return commandExistsWindowsSync(commandName, cleanedCommandName);
      } else {
        return commandExistsUnixSync(commandName, cleanedCommandName);
      }
    };
  }
});

// node_modules/command-exists/index.js
var require_command_exists2 = __commonJS({
  "node_modules/command-exists/index.js"(exports2, module2) {
    "use strict";
    module2.exports = require_command_exists();
  }
});

// node_modules/isbinaryfile/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/isbinaryfile/lib/index.js"(exports2) {
    "use strict";
    var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve6) {
          resolve6(value);
        });
      }
      return new (P || (P = Promise))(function(resolve6, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step(result) {
          result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isBinaryFileSync = exports2.isBinaryFile = void 0;
    var fs4 = require("fs");
    var util_1 = require("util");
    var statAsync = util_1.promisify(fs4.stat);
    var openAsync = util_1.promisify(fs4.open);
    var closeAsync = util_1.promisify(fs4.close);
    var MAX_BYTES = 512;
    var Reader = class {
      constructor(fileBuffer, size) {
        this.fileBuffer = fileBuffer;
        this.size = size;
        this.offset = 0;
        this.error = false;
      }
      hasError() {
        return this.error;
      }
      nextByte() {
        if (this.offset === this.size || this.hasError()) {
          this.error = true;
          return 255;
        }
        return this.fileBuffer[this.offset++];
      }
      next(len) {
        const n = new Array();
        for (let i = 0; i < len; i++) {
          n[i] = this.nextByte();
        }
        return n;
      }
    };
    function readProtoVarInt(reader) {
      let idx = 0;
      let varInt = 0;
      while (!reader.hasError()) {
        const b = reader.nextByte();
        varInt = varInt | (b & 127) << 7 * idx;
        if ((b & 128) === 0) {
          break;
        }
        idx++;
      }
      return varInt;
    }
    function readProtoMessage(reader) {
      const varInt = readProtoVarInt(reader);
      const wireType = varInt & 7;
      switch (wireType) {
        case 0:
          readProtoVarInt(reader);
          return true;
        case 1:
          reader.next(8);
          return true;
        case 2:
          const len = readProtoVarInt(reader);
          reader.next(len);
          return true;
        case 5:
          reader.next(4);
          return true;
      }
      return false;
    }
    function isBinaryProto(fileBuffer, totalBytes) {
      const reader = new Reader(fileBuffer, totalBytes);
      let numMessages = 0;
      while (true) {
        if (!readProtoMessage(reader) && !reader.hasError()) {
          return false;
        }
        if (reader.hasError()) {
          break;
        }
        numMessages++;
      }
      return numMessages > 0;
    }
    function isBinaryFile2(file, size) {
      return __awaiter2(this, void 0, void 0, function* () {
        if (isString(file)) {
          const stat3 = yield statAsync(file);
          isStatFile(stat3);
          const fileDescriptor = yield openAsync(file, "r");
          const allocBuffer = Buffer.alloc(MAX_BYTES);
          return new Promise((fulfill, reject) => {
            fs4.read(fileDescriptor, allocBuffer, 0, MAX_BYTES, 0, (err, bytesRead, _) => {
              closeAsync(fileDescriptor);
              if (err) {
                reject(err);
              } else {
                fulfill(isBinaryCheck(allocBuffer, bytesRead));
              }
            });
          });
        } else {
          if (size === void 0) {
            size = file.length;
          }
          return isBinaryCheck(file, size);
        }
      });
    }
    exports2.isBinaryFile = isBinaryFile2;
    function isBinaryFileSync(file, size) {
      if (isString(file)) {
        const stat3 = fs4.statSync(file);
        isStatFile(stat3);
        const fileDescriptor = fs4.openSync(file, "r");
        const allocBuffer = Buffer.alloc(MAX_BYTES);
        const bytesRead = fs4.readSync(fileDescriptor, allocBuffer, 0, MAX_BYTES, 0);
        fs4.closeSync(fileDescriptor);
        return isBinaryCheck(allocBuffer, bytesRead);
      } else {
        if (size === void 0) {
          size = file.length;
        }
        return isBinaryCheck(file, size);
      }
    }
    exports2.isBinaryFileSync = isBinaryFileSync;
    function isBinaryCheck(fileBuffer, bytesRead) {
      if (bytesRead === 0) {
        return false;
      }
      let suspiciousBytes = 0;
      const totalBytes = Math.min(bytesRead, MAX_BYTES);
      if (bytesRead >= 3 && fileBuffer[0] === 239 && fileBuffer[1] === 187 && fileBuffer[2] === 191) {
        return false;
      }
      if (bytesRead >= 4 && fileBuffer[0] === 0 && fileBuffer[1] === 0 && fileBuffer[2] === 254 && fileBuffer[3] === 255) {
        return false;
      }
      if (bytesRead >= 4 && fileBuffer[0] === 255 && fileBuffer[1] === 254 && fileBuffer[2] === 0 && fileBuffer[3] === 0) {
        return false;
      }
      if (bytesRead >= 4 && fileBuffer[0] === 132 && fileBuffer[1] === 49 && fileBuffer[2] === 149 && fileBuffer[3] === 51) {
        return false;
      }
      if (totalBytes >= 5 && fileBuffer.slice(0, 5).toString() === "%PDF-") {
        return true;
      }
      if (bytesRead >= 2 && fileBuffer[0] === 254 && fileBuffer[1] === 255) {
        return false;
      }
      if (bytesRead >= 2 && fileBuffer[0] === 255 && fileBuffer[1] === 254) {
        return false;
      }
      for (let i = 0; i < totalBytes; i++) {
        if (fileBuffer[i] === 0) {
          return true;
        } else if ((fileBuffer[i] < 7 || fileBuffer[i] > 14) && (fileBuffer[i] < 32 || fileBuffer[i] > 127)) {
          if (fileBuffer[i] > 193 && fileBuffer[i] < 224 && i + 1 < totalBytes) {
            i++;
            if (fileBuffer[i] > 127 && fileBuffer[i] < 192) {
              continue;
            }
          } else if (fileBuffer[i] > 223 && fileBuffer[i] < 240 && i + 2 < totalBytes) {
            i++;
            if (fileBuffer[i] > 127 && fileBuffer[i] < 192 && fileBuffer[i + 1] > 127 && fileBuffer[i + 1] < 192) {
              i++;
              continue;
            }
          }
          suspiciousBytes++;
          if (i >= 32 && suspiciousBytes * 100 / totalBytes > 10) {
            return true;
          }
        }
      }
      if (suspiciousBytes * 100 / totalBytes > 10) {
        return true;
      }
      if (suspiciousBytes > 1 && isBinaryProto(fileBuffer, totalBytes)) {
        return true;
      }
      return false;
    }
    function isString(x) {
      return typeof x === "string";
    }
    function isStatFile(stat3) {
      if (!stat3.isFile()) {
        throw new Error(`Path provided was not a file!`);
      }
    }
  }
});

// node_modules/is-docker/index.js
var require_is_docker = __commonJS({
  "node_modules/is-docker/index.js"(exports2, module2) {
    "use strict";
    var fs4 = require("fs");
    var isDocker;
    function hasDockerEnv() {
      try {
        fs4.statSync("/.dockerenv");
        return true;
      } catch (_) {
        return false;
      }
    }
    function hasDockerCGroup() {
      try {
        return fs4.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
      } catch (_) {
        return false;
      }
    }
    module2.exports = () => {
      if (isDocker === void 0) {
        isDocker = hasDockerEnv() || hasDockerCGroup();
      }
      return isDocker;
    };
  }
});

// node_modules/is-wsl/index.js
var require_is_wsl = __commonJS({
  "node_modules/is-wsl/index.js"(exports2, module2) {
    "use strict";
    var os3 = require("os");
    var fs4 = require("fs");
    var isDocker = require_is_docker();
    var isWsl = () => {
      if (process.platform !== "linux") {
        return false;
      }
      if (os3.release().toLowerCase().includes("microsoft")) {
        if (isDocker()) {
          return false;
        }
        return true;
      }
      try {
        return fs4.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
      } catch (_) {
        return false;
      }
    };
    if (process.env.__IS_WSL_TEST__) {
      module2.exports = isWsl;
    } else {
      module2.exports = isWsl();
    }
  }
});

// node_modules/define-lazy-prop/index.js
var require_define_lazy_prop = __commonJS({
  "node_modules/define-lazy-prop/index.js"(exports2, module2) {
    "use strict";
    module2.exports = (object, propertyName, fn) => {
      const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
      Object.defineProperty(object, propertyName, {
        configurable: true,
        enumerable: true,
        get() {
          const result = fn();
          define(result);
          return result;
        },
        set(value) {
          define(value);
        }
      });
      return object;
    };
  }
});

// node_modules/open/index.js
var require_open = __commonJS({
  "node_modules/open/index.js"(exports2, module2) {
    "use strict";
    var path3 = require("path");
    var childProcess = require("child_process");
    var { promises: fs4, constants: fsConstants } = require("fs");
    var isWsl = require_is_wsl();
    var isDocker = require_is_docker();
    var defineLazyProperty = require_define_lazy_prop();
    var localXdgOpenPath = path3.join(__dirname, "xdg-open");
    var { platform, arch } = process;
    var hasContainerEnv = () => {
      try {
        fs4.statSync("/run/.containerenv");
        return true;
      } catch {
        return false;
      }
    };
    var cachedResult;
    function isInsideContainer() {
      if (cachedResult === void 0) {
        cachedResult = hasContainerEnv() || isDocker();
      }
      return cachedResult;
    }
    var getWslDrivesMountPoint = /* @__PURE__ */ (() => {
      const defaultMountPoint = "/mnt/";
      let mountPoint;
      return async function() {
        if (mountPoint) {
          return mountPoint;
        }
        const configFilePath = "/etc/wsl.conf";
        let isConfigFileExists = false;
        try {
          await fs4.access(configFilePath, fsConstants.F_OK);
          isConfigFileExists = true;
        } catch {
        }
        if (!isConfigFileExists) {
          return defaultMountPoint;
        }
        const configContent = await fs4.readFile(configFilePath, { encoding: "utf8" });
        const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
        if (!configMountPoint) {
          return defaultMountPoint;
        }
        mountPoint = configMountPoint.groups.mountPoint.trim();
        mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
        return mountPoint;
      };
    })();
    var pTryEach = async (array, mapper) => {
      let latestError;
      for (const item of array) {
        try {
          return await mapper(item);
        } catch (error) {
          latestError = error;
        }
      }
      throw latestError;
    };
    var baseOpen = async (options) => {
      options = {
        wait: false,
        background: false,
        newInstance: false,
        allowNonzeroExitCode: false,
        ...options
      };
      if (Array.isArray(options.app)) {
        return pTryEach(options.app, (singleApp) => baseOpen({
          ...options,
          app: singleApp
        }));
      }
      let { name: app, arguments: appArguments = [] } = options.app || {};
      appArguments = [...appArguments];
      if (Array.isArray(app)) {
        return pTryEach(app, (appName) => baseOpen({
          ...options,
          app: {
            name: appName,
            arguments: appArguments
          }
        }));
      }
      let command;
      const cliArguments = [];
      const childProcessOptions = {};
      if (platform === "darwin") {
        command = "open";
        if (options.wait) {
          cliArguments.push("--wait-apps");
        }
        if (options.background) {
          cliArguments.push("--background");
        }
        if (options.newInstance) {
          cliArguments.push("--new");
        }
        if (app) {
          cliArguments.push("-a", app);
        }
      } else if (platform === "win32" || isWsl && !isInsideContainer() && !app) {
        const mountPoint = await getWslDrivesMountPoint();
        command = isWsl ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
        cliArguments.push(
          "-NoProfile",
          "-NonInteractive",
          "\u2013ExecutionPolicy",
          "Bypass",
          "-EncodedCommand"
        );
        if (!isWsl) {
          childProcessOptions.windowsVerbatimArguments = true;
        }
        const encodedArguments = ["Start"];
        if (options.wait) {
          encodedArguments.push("-Wait");
        }
        if (app) {
          encodedArguments.push(`"\`"${app}\`""`, "-ArgumentList");
          if (options.target) {
            appArguments.unshift(options.target);
          }
        } else if (options.target) {
          encodedArguments.push(`"${options.target}"`);
        }
        if (appArguments.length > 0) {
          appArguments = appArguments.map((arg) => `"\`"${arg}\`""`);
          encodedArguments.push(appArguments.join(","));
        }
        options.target = Buffer.from(encodedArguments.join(" "), "utf16le").toString("base64");
      } else {
        if (app) {
          command = app;
        } else {
          const isBundled = !__dirname || __dirname === "/";
          let exeLocalXdgOpen = false;
          try {
            await fs4.access(localXdgOpenPath, fsConstants.X_OK);
            exeLocalXdgOpen = true;
          } catch {
          }
          const useSystemXdgOpen = process.versions.electron || platform === "android" || isBundled || !exeLocalXdgOpen;
          command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
        }
        if (appArguments.length > 0) {
          cliArguments.push(...appArguments);
        }
        if (!options.wait) {
          childProcessOptions.stdio = "ignore";
          childProcessOptions.detached = true;
        }
      }
      if (options.target) {
        cliArguments.push(options.target);
      }
      if (platform === "darwin" && appArguments.length > 0) {
        cliArguments.push("--args", ...appArguments);
      }
      const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
      if (options.wait) {
        return new Promise((resolve6, reject) => {
          subprocess.once("error", reject);
          subprocess.once("close", (exitCode) => {
            if (!options.allowNonzeroExitCode && exitCode > 0) {
              reject(new Error(`Exited with code ${exitCode}`));
              return;
            }
            resolve6(subprocess);
          });
        });
      }
      subprocess.unref();
      return subprocess;
    };
    var open2 = (target, options) => {
      if (typeof target !== "string") {
        throw new TypeError("Expected a `target`");
      }
      return baseOpen({
        ...options,
        target
      });
    };
    var openApp = (name, options) => {
      if (typeof name !== "string") {
        throw new TypeError("Expected a `name`");
      }
      const { arguments: appArguments = [] } = options || {};
      if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) {
        throw new TypeError("Expected `appArguments` as Array type");
      }
      return baseOpen({
        ...options,
        app: {
          name,
          arguments: appArguments
        }
      });
    };
    function detectArchBinary(binary) {
      if (typeof binary === "string" || Array.isArray(binary)) {
        return binary;
      }
      const { [arch]: archBinary } = binary;
      if (!archBinary) {
        throw new Error(`${arch} is not supported`);
      }
      return archBinary;
    }
    function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
      if (wsl && isWsl) {
        return detectArchBinary(wsl);
      }
      if (!platformBinary) {
        throw new Error(`${platform} is not supported`);
      }
      return detectArchBinary(platformBinary);
    }
    var apps = {};
    defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
      darwin: "google chrome",
      win32: "chrome",
      linux: ["google-chrome", "google-chrome-stable", "chromium"]
    }, {
      wsl: {
        ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
        x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
      }
    }));
    defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
      darwin: "firefox",
      win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
      linux: "firefox"
    }, {
      wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
    }));
    defineLazyProperty(apps, "edge", () => detectPlatformBinary({
      darwin: "microsoft edge",
      win32: "msedge",
      linux: ["microsoft-edge", "microsoft-edge-dev"]
    }, {
      wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
    }));
    open2.apps = apps;
    open2.openApp = openApp;
    module2.exports = open2;
  }
});

// node_modules/pretty-bytes/index.js
var require_pretty_bytes = __commonJS({
  "node_modules/pretty-bytes/index.js"(exports2, module2) {
    "use strict";
    var BYTE_UNITS = [
      "B",
      "kB",
      "MB",
      "GB",
      "TB",
      "PB",
      "EB",
      "ZB",
      "YB"
    ];
    var BIBYTE_UNITS = [
      "B",
      "kiB",
      "MiB",
      "GiB",
      "TiB",
      "PiB",
      "EiB",
      "ZiB",
      "YiB"
    ];
    var BIT_UNITS = [
      "b",
      "kbit",
      "Mbit",
      "Gbit",
      "Tbit",
      "Pbit",
      "Ebit",
      "Zbit",
      "Ybit"
    ];
    var BIBIT_UNITS = [
      "b",
      "kibit",
      "Mibit",
      "Gibit",
      "Tibit",
      "Pibit",
      "Eibit",
      "Zibit",
      "Yibit"
    ];
    var toLocaleString = (number, locale, options) => {
      let result = number;
      if (typeof locale === "string" || Array.isArray(locale)) {
        result = number.toLocaleString(locale, options);
      } else if (locale === true || options !== void 0) {
        result = number.toLocaleString(void 0, options);
      }
      return result;
    };
    module2.exports = (number, options) => {
      if (!Number.isFinite(number)) {
        throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
      }
      options = Object.assign({ bits: false, binary: false }, options);
      const UNITS = options.bits ? options.binary ? BIBIT_UNITS : BIT_UNITS : options.binary ? BIBYTE_UNITS : BYTE_UNITS;
      if (options.signed && number === 0) {
        return ` 0 ${UNITS[0]}`;
      }
      const isNegative = number < 0;
      const prefix = isNegative ? "-" : options.signed ? "+" : "";
      if (isNegative) {
        number = -number;
      }
      let localeOptions;
      if (options.minimumFractionDigits !== void 0) {
        localeOptions = { minimumFractionDigits: options.minimumFractionDigits };
      }
      if (options.maximumFractionDigits !== void 0) {
        localeOptions = Object.assign({ maximumFractionDigits: options.maximumFractionDigits }, localeOptions);
      }
      if (number < 1) {
        const numberString2 = toLocaleString(number, options.locale, localeOptions);
        return prefix + numberString2 + " " + UNITS[0];
      }
      const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1);
      number /= Math.pow(options.binary ? 1024 : 1e3, exponent);
      if (!localeOptions) {
        number = number.toPrecision(3);
      }
      const numberString = toLocaleString(Number(number), options.locale, localeOptions);
      const unit = UNITS[exponent];
      return prefix + numberString + " " + unit;
    };
  }
});

// src/index.ts
var src_exports = {};
__export(src_exports, {
  activate: () => activate
});
module.exports = __toCommonJS(src_exports);

// node_modules/coc-helper/lib/esm/index.js
var import_coc15 = require("coc.nvim");

// node_modules/coc-helper/lib/esm/FloatingWindow.js
var import_coc11 = require("coc.nvim");

// node_modules/coc-helper/lib/esm/notifier.js
var import_coc5 = require("coc.nvim");

// node_modules/coc-helper/lib/esm/util/collection.js
var compactI = (arr) => arr.filter((it) => it !== void 0 && it !== null);

// node_modules/coc-helper/lib/esm/util/config.js
var import_coc2 = require("coc.nvim");

// node_modules/coc-helper/lib/esm/util/text.js
var import_coc = require("coc.nvim");

// node_modules/coc-helper/lib/esm/util/env.js
var isWindows = process.platform === "win32";
var isMacintosh = process.platform === "darwin";
var isLinux = process.platform === "linux";
var isTest = process.env.NODE_ENV === "test";

// node_modules/coc-helper/lib/esm/util/text.js
async function displayWidth(content) {
  return await import_coc.workspace.nvim.call("strdisplaywidth", [content]);
}

// node_modules/coc-helper/lib/esm/util/log.js
var import_coc3 = require("coc.nvim");
var import_util = __toESM(require("util"));
var levelList = [
  "trace",
  "debug",
  "info",
  "warn",
  "error",
  "fatal",
  "off"
];
var levelErrorNum = levelList.indexOf("error");
function formatDate(date) {
  return `${date.toLocaleString()} ${date.getMilliseconds().toString().padStart(3, "0")}`;
}
var HelperLogger = class {
  constructor(channelName) {
    this.channelName = channelName;
    this.timeMarkers = /* @__PURE__ */ new Map();
    this.levelStatus = "trace";
    this.levelNumber = levelList.indexOf(this.levelStatus);
    this.appendLine = (line) => {
      this.outputChannel.appendLine(line);
    };
    this.appendErrorLine = (line) => {
      if (isTest) {
        console.error(line);
      } else {
        void import_coc3.window.showErrorMessage(line);
      }
    };
    this.log = (levelName, data) => {
      var _a2, _b;
      const levelNum = levelList[levelName];
      if (levelNum < this.levelNumber) {
        return;
      }
      const prefix = `[${formatDate(/* @__PURE__ */ new Date())}] [${levelName}]: `;
      if (data instanceof Error) {
        this.appendLine(`${prefix}${(_a2 = data.stack) !== null && _a2 !== void 0 ? _a2 : data.toString()}`);
        this.appendErrorLine(data.message);
        if (isTest) {
          console.error((_b = data.stack) !== null && _b !== void 0 ? _b : data.toString());
        }
        return;
      }
      this.appendLine(`${prefix}${data}`);
      if (levelNum > levelErrorNum) {
        this.appendErrorLine(data);
      }
    };
    this.trace = (line) => {
      this.log("trace", line);
    };
    this.debug = (line) => {
      this.log("debug", line);
    };
    this.info = (line) => {
      this.log("info", line);
    };
    this.warn = (line) => {
      this.log("warn", line);
    };
    this.error = (data) => {
      if (!(data instanceof Error)) {
        data = new Error(data);
      }
      this.log("error", data);
    };
    this.fatal = (data) => {
      this.log("fatal", data);
    };
    this.prettyPrint = (...data) => {
      this.info(prettyObject(...data));
      this.appendErrorLine(`[${formatDate(/* @__PURE__ */ new Date())}] ${prettyObject(...data)}`);
    };
  }
  /**
   * Default level is 'trace'
   */
  set level(level) {
    this.levelStatus = level;
    this.levelNumber = levelList[level];
  }
  get level() {
    return this.levelStatus;
  }
  dispose() {
    var _a2;
    (_a2 = this.outputChannel_) === null || _a2 === void 0 ? void 0 : _a2.dispose();
  }
  get outputChannel() {
    if (!this.outputChannel_) {
      this.outputChannel_ = import_coc3.window.createOutputChannel(this.channelName);
    }
    return this.outputChannel_;
  }
  time(label = "default") {
    this.timeMarkers.set(label, (/* @__PURE__ */ new Date()).valueOf());
  }
  /**
   * @returns milliseconds
   */
  timeElapsed(label = "default") {
    const time = this.timeMarkers.get(label);
    if (time !== void 0) {
      return (/* @__PURE__ */ new Date()).valueOf() - time;
    }
  }
  timeLog(label = "default") {
    const time = this.timeElapsed(label);
    if (time !== void 0) {
      this.appendLine(`${label}: ${time} ms`);
    }
  }
  measureTime(task) {
    const time = (/* @__PURE__ */ new Date()).valueOf();
    const result = task();
    if (result instanceof Promise) {
      return result.then((r) => {
        return [r, (/* @__PURE__ */ new Date()).valueOf() - time];
      });
    }
    return [result, (/* @__PURE__ */ new Date()).valueOf() - time];
  }
  measureTask(task, label = "default", level = "info") {
    const response = this.measureTime(task);
    if (!("then" in response)) {
      const [result, time] = response;
      this.log(level, `[measureTask] ${label}: ${time} ms`);
      return result;
    }
    return response.then(([result, time]) => {
      this.log(level, `${label}: ${time} ms`);
      return result;
    });
  }
  /**
   * Wrap the async function and catch the error
   */
  asyncCatch(fn) {
    return async (...args) => {
      try {
        return await fn(...args);
      } catch (e) {
        this.error(e);
      }
    };
  }
};
var helperLogger = new HelperLogger("coc-helper");
function prettyObject(...data) {
  return data.map((d) => import_util.default.inspect(d)).join(" ");
}

// node_modules/coc-helper/lib/esm/_package.json
var package_default = {
  name: "coc-helper",
  version: "0.16.3",
  description: "Helpers for coc.nvim",
  module: "lib/esm/index.js",
  main: "lib/cjs/index.js",
  homepage: "https://github.com/weirongxu/coc-helper",
  repository: "git@github.com:weirongxu/coc-helper.git",
  author: "Weirong Xu <weirongxu.raidou@gmail.com>",
  license: "MIT",
  files: [
    "lib",
    "jest.config.js",
    "tests"
  ],
  scripts: {
    clean: "shx rm -rf lib",
    "copy:pkg": "shx cp package.json src/_package.json",
    "build:esm": "tsc -p ./tsconfig.prod.json --module es2020 --outDir lib/esm",
    "build:cjs": "tsc -p ./tsconfig.prod.json --module commonjs --outDir lib/cjs",
    build: "run-s clean copy:pkg build:esm build:cjs",
    lint: "eslint src --ext ts",
    prepare: "run-s clean build",
    unittest: "jest",
    test: "run-s copy:pkg lint unittest"
  },
  engines: {
    coc: "^0.0.77"
  },
  activationEvents: [
    "*"
  ],
  prettier: {
    singleQuote: true,
    printWidth: 80,
    semi: true,
    trailingComma: "all"
  },
  peerDependencies: {
    "coc.nvim": "*"
  },
  devDependencies: {
    "@chemzqm/neovim": "^6.1.1",
    "@raidou/eslint-config-base": "^1.6.0",
    "@types/eslint": "^8.4.10",
    "@types/jest": "^29.2.5",
    "@types/node": "^18.11.18",
    "@types/rimraf": "^3.0.2",
    "@types/uuid": "^9.0.0",
    "coc.nvim": "0.0.83-next.9",
    eslint: "^8.31.0",
    jest: "^29.3.1",
    log4js: "^6.7.1",
    "npm-run-all": "^4.1.5",
    prettier: "^2.8.2",
    shx: "^0.3.4",
    "ts-jest": "^29.0.4",
    typescript: "^4.9.4"
  },
  dependencies: {
    rimraf: "^3.0.2",
    uuid: "^9.0.0"
  }
};

// node_modules/coc-helper/lib/esm/util/version.js
var version = package_default.version;
var versionName = version.replace(/[.-]/g, "_");

// node_modules/coc-helper/lib/esm/util/vim.js
var import_coc4 = require("coc.nvim");
async function registerRuntimepath(context2) {
  const { nvim } = import_coc4.workspace;
  const extensionPath = context2.extensionPath;
  const paths = await nvim.runtimePaths;
  if (!paths.includes(extensionPath)) {
    await nvim.command(`execute 'noa set rtp+='.fnameescape('${extensionPath.replace(/'/g, "''")}')`);
  }
}

// node_modules/coc-helper/lib/esm/notifier.js
var Notifier = class _Notifier {
  static async run(notifier) {
    if (!notifier) {
      return;
    }
    if ("then" in notifier) {
      const awaitedNotifier = await notifier;
      if (awaitedNotifier) {
        return awaitedNotifier.run();
      }
    } else {
      return notifier.run();
    }
  }
  static notifyAll(lazyNotifies) {
    for (const n of lazyNotifies) {
      if (n) {
        n.notify();
      }
    }
  }
  static async runAll(notifierPromises) {
    const notifiers = await Promise.all(notifierPromises);
    import_coc5.workspace.nvim.pauseNotification();
    this.notifyAll(notifiers);
    return import_coc5.workspace.nvim.resumeNotification();
  }
  static combine(notifiers) {
    const compactedNotifiers = compactI(notifiers);
    if (compactedNotifiers.length < 1) {
      return _Notifier.noop();
    }
    if (compactedNotifiers.length === 1) {
      return compactedNotifiers[0];
    }
    return compactedNotifiers.reduce((ret, cur) => ret.concat(cur), _Notifier.noop());
  }
  static noop() {
    return this.create(() => {
    });
  }
  static create(notify) {
    return new _Notifier(notify);
  }
  constructor(notify) {
    this.notifyFns = [];
    this.notifyFns.push(notify);
  }
  async run() {
    return _Notifier.runAll([this]);
  }
  notify() {
    for (const fn of this.notifyFns) {
      fn();
    }
  }
  concat(notifier) {
    this.notifyFns.push(...notifier.notifyFns);
    return this;
  }
};

// node_modules/coc-helper/lib/esm/modules/floating.js
var import_coc8 = require("coc.nvim");

// node_modules/coc-helper/lib/esm/VimModule.js
var import_coc6 = require("coc.nvim");

// node_modules/coc-helper/lib/esm/util/module.js
var globalModuleIdSym = Symbol("helper_module_max_id");
function getModuleId(key) {
  if (!(globalModuleIdSym in global)) {
    global[globalModuleIdSym] = {};
  }
  const moduleIds = global[globalModuleIdSym];
  if (!(key in moduleIds)) {
    moduleIds[key] = 0;
  }
  moduleIds[key] += 1;
  return moduleIds[key];
}

// node_modules/coc-helper/lib/esm/VimModule.js
var mid = getModuleId("VimModule");
var globalKey = `coc_helper_module_m${mid}_v${versionName}`;
var globalVariable = `g:${globalKey}`;
var callFunc = `CocHelperCallFn_m${mid}_v${versionName}`;
var declareVar = `CocHelperCallVar_m${mid}_v${versionName}`;
function filterLineCont(content) {
  return content.replace(/\n\s*\\/g, "");
}
var VimModule = class _VimModule {
  static async init(context2) {
    this.inited = true;
    await import_coc6.workspace.nvim.call("execute", `
        if !exists('${globalVariable}')
          let ${globalVariable} = {}
        endif

        function! ${callFunc}(module_key, method_name, args)
          try
            return call(${globalVariable}[a:module_key][a:method_name], a:args)
          catch
            let ex = v:exception
            let msg = printf('error when call %s.%s.%s, args: [%s]', '${globalVariable}', a:module_key, a:method_name, join(a:args, ','))
            echom msg
            echom ex
            throw msg . ' ' . ex
          endtry
        endfunction

        function! ${declareVar}(module_key, var_name, expression)
          try
            let ${globalVariable}[a:module_key][a:var_name] = eval(a:expression)
          catch
            let ex = v:exception
            let msg = printf('error when declare %s.%s.%s, expression: %s', '${globalVariable}', a:module_key, a:var_name, a:expression)
            echom msg
            echom ex
            throw msg . ' ' . ex
          endtry
        endfunction
      `);
    const queue = [...this.initQueue];
    while (queue.length) {
      const it = queue.shift();
      try {
        await it.fn(context2);
      } catch (error) {
        helperLogger.error(error);
      }
      if (this.initAfterQueue.length) {
        queue.push(...this.initAfterQueue);
        this.initAfterQueue = [];
      }
    }
  }
  static registerInit(description, fn) {
    if (!this.inited) {
      this.initQueue.push({ description, fn });
    } else {
      this.initAfterQueue.push({ description, fn });
    }
  }
  static create(moduleName, cb) {
    const id = getModuleId("VimModule.module");
    const moduleKey = `${id}_${moduleName}`;
    const vMod = new _VimModule(moduleKey);
    let mod = void 0;
    function initedMod() {
      if (!mod) {
        mod = cb(vMod);
      }
      return mod;
    }
    _VimModule.registerInit(`module ${moduleKey}`, async () => {
      await import_coc6.workspace.nvim.call("execute", `
          if !exists('${globalVariable}.${moduleKey}')
            let ${globalVariable}.${moduleKey} = {}
          endif
        `);
      initedMod();
    });
    return new Proxy({}, {
      get(_o, key) {
        return Reflect.get(initedMod(), key);
      },
      has(_o, key) {
        return key in initedMod();
      },
      ownKeys() {
        return Object.keys(initedMod());
      }
    });
  }
  constructor(moduleKey) {
    this.moduleKey = moduleKey;
  }
  registerInit(description, fn) {
    if (typeof description === "string") {
      return _VimModule.registerInit(description, fn);
    } else {
      return this.registerInit("", description);
    }
  }
  fn(fnName, getContent) {
    const { nvim } = import_coc6.workspace;
    const name = `${globalVariable}.${this.moduleKey}.${fnName}`;
    const content = getContent({ name });
    this.registerInit(`fn ${name}`, async () => {
      helperLogger.debug(`declare fn ${name}`);
      await nvim.call("execute", [filterLineCont(content)]);
    });
    return {
      name,
      inlineCall: (argsExpression = "") => `${callFunc}('${this.moduleKey}', '${fnName}', [${argsExpression}])`,
      call: (...args) => {
        helperLogger.debug(`call ${name}`);
        return nvim.call(callFunc, [
          this.moduleKey,
          fnName,
          args
        ]);
      },
      callNotify: (...args) => {
        helperLogger.debug(`callNotify ${name}`);
        return nvim.call(callFunc, [this.moduleKey, fnName, args], true);
      },
      callNotifier: (...args) => {
        helperLogger.debug(`callNotifier ${name}`);
        return Notifier.create(() => {
          nvim.call(callFunc, [this.moduleKey, fnName, args], true);
        });
      }
    };
  }
  var(varName, expression) {
    const { nvim } = import_coc6.workspace;
    const name = `${globalVariable}.${this.moduleKey}.${varName}`;
    this.registerInit(`var ${name}`, async () => {
      helperLogger.debug(`declare var ${name}`);
      await nvim.call(declareVar, [
        this.moduleKey,
        varName,
        filterLineCont(expression)
      ]);
    });
    return {
      name,
      inline: name,
      get: () => {
        return nvim.eval(name);
      },
      set: async (expression2) => {
        await nvim.call(declareVar, [
          this.moduleKey,
          varName,
          filterLineCont(expression2)
        ]);
      },
      setNotify: (expression2) => {
        nvim.call(declareVar, [this.moduleKey, varName, filterLineCont(expression2)], true);
      },
      setNotifier: (expression2) => {
        return Notifier.create(() => {
          nvim.call(declareVar, [this.moduleKey, varName, filterLineCont(expression2)], true);
        });
      }
    };
  }
};
VimModule.inited = false;
VimModule.initQueue = [];
VimModule.initAfterQueue = [];

// node_modules/coc-helper/lib/esm/modules/buf.js
var import_coc7 = require("coc.nvim");
var bufModule = VimModule.create("buf", (m) => {
  const isNvim = import_coc7.workspace.isNvim;
  const createByName = m.fn("create_by_name", ({ name }) => `
      function! ${name}(name) abort
        return bufadd(a:name)
      endfunction
    `);
  return {
    createByName,
    create: m.fn("create", ({ name }) => isNvim ? `
          function! ${name}(...) abort
            let name = get(a:000, 0, '')
            if name is ''
              return nvim_create_buf(v:false, v:true)
            else
              return ${createByName.inlineCall("name")}
            endif
          endfunction
        ` : `
          function! ${name}(...) abort
            let name = get(a:000, 0, '')
            return ${createByName.inlineCall("name")}
          endfunction
        `)
  };
});

// node_modules/coc-helper/lib/esm/modules/floating.js
var floatingModule = VimModule.create("float", (m) => {
  const isNvim = import_coc8.workspace.isNvim;
  const initExecute = m.fn("init_execute", ({ name }) => `
      function! ${name}(ctx, inited_execute) abort
        execute a:inited_execute
      endfunction
    `);
  const openWin = m.fn("open_win", ({ name }) => isNvim ? `
        function! ${name}(bufnr, focus, win_config, win_hl, inited_execute) abort
          noau let winid = nvim_open_win(a:bufnr, a:focus, a:win_config)
          if !empty(a:win_hl)
            call nvim_win_set_option(winid, 'winhl', a:win_hl)
          endif
          if !empty(a:inited_execute)
            call ${initExecute.inlineCall("{'bufnr': a:bufnr, 'winid': winid}, a:inited_execute")}
          endif
          return winid
        endfunction
      ` : `
        function! ${name}(bufnr, focus, win_config, win_hl, inited_execute) abort
          let winid = popup_create(a:bufnr, a:win_config)
          call ${initExecute.inlineCall("{'bufnr': a:bufnr, 'winid': winid}, a:inited_execute")}

          return winid
        endfunction
      `);
  return {
    create: m.fn("create", ({ name }) => isNvim ? `
            function! ${name}(name, inited_execute, has_border_buf, border_inited_execute) abort
              let bufnr = ${bufModule.create.inlineCall("a:name")}
              call ${initExecute.inlineCall("{'bufnr': bufnr}, a:inited_execute")}

              let border_bufnr = v:null
              if a:has_border_buf
                let border_bufnr = nvim_create_buf(v:false, v:true)
                call ${initExecute.inlineCall("{'bufnr': border_bufnr}, a:border_inited_execute")}
              endif
              return [bufnr, border_bufnr]
            endfunction
          ` : `
            function! ${name}(name, inited_execute, has_border_buf, border_inited_execute) abort
              let bufnr = ${bufModule.create.inlineCall("a:name")}
              call ${initExecute.inlineCall("{'bufnr': bufnr}, a:inited_execute")}
              return [bufnr, v:null]
            endfunction
          `),
    open: m.fn("open", ({ name }) => `
        function! ${name}(bufnr, win_config, inited_execute, border_bufnr, border_win_config, border_inited_execute, focus, win_hl) abort
          let winid = ${openWin.inlineCall("a:bufnr, a:focus, a:win_config, a:win_hl, a:inited_execute")}
          call setbufvar(a:bufnr, 'coc_helper_winid', winid)

          if a:border_bufnr
            let border_winid = ${openWin.inlineCall("a:border_bufnr, v:false, a:border_win_config, a:win_hl, a:border_inited_execute")}
            call setbufvar(a:bufnr, 'coc_helper_border_winid', border_winid)
          endif
        endfunction
      `),
    resume: m.fn("resume", ({ name }) => `
        function! ${name}(bufnr, win_config, border_bufnr, border_win_config, focus, win_hl) abort
          let winid = ${openWin.inlineCall("a:bufnr, a:focus, a:win_config, a:win_hl, ''")}
          call setbufvar(a:bufnr, 'coc_helper_winid', winid)

          if a:border_bufnr
            let border_winid = ${openWin.inlineCall("border_bufnr, v:false, a:border_win_config, a:win_hl, ''")}
            call setbufvar(a:bufnr, 'coc_helper_border_winid', border_winid)
          endif
        endfunction
      `),
    update: m.fn("update", ({ name }) => isNvim ? `
          function! ${name}(bufnr, win_config, border_bufnr, border_win_config, win_hl) abort
            let winid = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
            if !winid
              return
            endif
            call nvim_win_set_config(winid, a:win_config)
            if !empty(a:win_hl)
              call nvim_win_set_option(winid, 'winhl', a:win_hl)
            endif
            if has('nvim')
              redraw!
            endif

            if a:border_bufnr
              let border_winid = getbufvar(a:bufnr, 'coc_helper_border_winid', v:null)
              if border_winid
                call nvim_win_set_config(border_winid, a:border_win_config)
                if !empty(a:win_hl)
                  call nvim_win_set_option(border_winid, 'winhl', a:win_hl)
                endif
                if has('nvim')
                  redraw!
                endif
              endif
            endif
          endfunction
        ` : `
          function! ${name}(bufnr, win_config, border_bufnr, border_win_config, win_hl) abort
            let winid = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
            if !winid
              return
            endif
            call popup_setoptions(winid, a:win_config)
          endfunction
        `),
    winid: m.fn("winid", ({ name }) => `
        function! ${name}(bufnr) abort
          let id = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
          let nr = win_id2win(id)
          return nr is 0 ? v:null : id
        endfunction
      `),
    borderWinid: m.fn("border_winid", ({ name }) => `
        function! ${name}(bufnr) abort
          return getbufvar(a:bufnr, 'coc_helper_border_winid', v:null)
        endfunction
      `),
    close: m.fn("close", ({ name }) => isNvim ? `
            function! ${name}(bufnr) abort
              let winid = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
              let border_winid = getbufvar(a:bufnr, 'coc_helper_border_winid', v:null)
              try
                if winid
                  call nvim_win_close(winid, v:true)
                endif
                if border_winid
                  call nvim_win_close(border_winid, v:true)
                endif
              catch
              endtry
            endfunction
          ` : `
            function! ${name}(bufnr) abort
              let winid = getbufvar(a:bufnr, 'coc_helper_winid', v:null)
              try
                if winid
                  call popup_close(winid)
                endif
              catch
              endtry
            endfunction
          `)
  };
});

// node_modules/coc-helper/lib/esm/modules/util.js
var import_coc9 = require("coc.nvim");
var utilModule = VimModule.create("util", (m) => {
  const isNvim = import_coc9.workspace.isNvim;
  return {
    globalCursorPosition: m.fn("global_cursor_position", ({ name }) => `
        function! ${name}()
          let nr = winnr()
          let [row, col] = win_screenpos(nr)
          return [row + winline() - 2, col + wincol() - 2]
        endfunction
      `),
    isFloat: m.fn("is_float", ({ name }) => isNvim ? `
          function! ${name}(winnr) abort
            if !exists('*nvim_win_get_config')
              return v:false
            endif
            let winid = win_getid(a:winnr)
            return nvim_win_get_config(winid)['relative'] != ''
          endfunction
        ` : `
          function! ${name}(winnr) abort
            return v:false
          endfunction
        `),
    closeWinByBufnr: m.fn("close_win_by_bufnr", ({ name }) => `
        if exists('*nvim_win_close')
          function! ${name}(bufnrs) abort
            for bufnr in a:bufnrs
              try
                let winid = bufwinid(bufnr)
                if winid >= 0
                  call nvim_win_close(winid, v:true)
                endif
              catch
              endtry
            endfor
          endfunction
        else
          function! ${name}(bufnrs) abort
            for bufnr in a:bufnrs
              try
                let winnr = bufwinnr(bufnr)
                if winnr >= 0
                  execute winnr . 'wincmd c'
                endif
              catch
              endtry
            endfor
          endfunction
        endif
      `),
    runCocCmd: m.fn("run_coc_cmd", ({ name }) => `
        function! ${name}(name, ...) abort
          return call('CocAction', extend(['runCommand', a:name], a:000))
        endfunction
      `),
    runCocCmdAsync: m.fn("run_coc_cmd_async", ({ name }) => `
        function! ${name}(name, ...) abort
          return call('CocActionAsync', extend(['runCommand', a:name], a:000))
        endfunction
      `)
  };
});

// node_modules/coc-helper/lib/esm/FloatingUtil.js
var import_coc10 = require("coc.nvim");
var defaultBorderChars = ["\u2500", "\u2502", "\u2500", "\u2502", "\u250C", "\u2510", "\u2518", "\u2514"];
var defaultWinHl = "CocHelperNormalFloat";
var defaultWinHlNC = "CocHelperNormalFloatNC";
var defaultBorderWinHl = "CocHelperNormalFloatBorder";
var FloatingUtil = class {
  constructor(srcId) {
    this.srcId = srcId;
  }
  async createContext(options) {
    var _a2, _b;
    return (_a2 = options.context) !== null && _a2 !== void 0 ? _a2 : {
      lines: import_coc10.workspace.env.lines,
      columns: import_coc10.workspace.env.columns - import_coc10.workspace.env.cmdheight - 1,
      globalCursorPosition: await utilModule.globalCursorPosition.call(),
      title: options.title ? {
        text: options.title,
        width: await displayWidth(options.title)
      } : { text: "", width: 0 },
      borderEnabled: !!options.border,
      border: this.extendEdges((_b = options.border) === null || _b === void 0 ? void 0 : _b.map((b) => typeof b === "boolean" ? 1 : b)),
      paddingEnabled: !!options.padding,
      padding: this.extendEdges(options.padding)
    };
  }
  getCenterPos(ctx, box) {
    const [, , width, height] = box;
    const top = Math.floor((ctx.lines - height) / 2);
    const left = Math.floor((ctx.columns - width) / 2);
    return [top, left];
  }
  getPosForAround(ctx, size, cursorPosition, preferAbove = false) {
    const columns = ctx.columns;
    const lines = ctx.lines - 1;
    const [width, height] = size;
    let [top, left] = cursorPosition;
    if (preferAbove) {
      if (top - height < 0) {
        top += 1;
      } else {
        top -= height;
      }
    } else {
      if (top + height >= lines) {
        top -= height;
      } else {
        top += 1;
      }
    }
    if (left + width >= columns) {
      left -= width - 1;
    }
    return [top, left];
  }
  /**
   * Extend around number to 4
   */
  extendEdges(edges) {
    var _a2, _b, _c, _d;
    if (!edges) {
      return [0, 0, 0, 0];
    }
    const top = (_a2 = edges[0]) !== null && _a2 !== void 0 ? _a2 : 1;
    const right = (_b = edges[1]) !== null && _b !== void 0 ? _b : top;
    const bottom = (_c = edges[2]) !== null && _c !== void 0 ? _c : top;
    const left = (_d = edges[3]) !== null && _d !== void 0 ? _d : right;
    return [top, right, bottom, left];
  }
  /**
   * Change window box by around edges
   */
  changeBoxByEdgesList(box, edgesList) {
    let retBox = [...box];
    for (const edges of edgesList) {
      retBox = this.changeBoxByEdges(retBox, edges);
    }
    return retBox;
  }
  /**
   * Change window box by around edge
   */
  changeBoxByEdges(box, edges) {
    if (!edges) {
      return box;
    }
    const [wTop, wRight, wBottom, wLeft] = edges;
    let [top, left, width, height] = box;
    top -= wTop;
    left -= wLeft;
    width += wLeft + wRight;
    height += wTop + wBottom;
    return [top, left, width, height];
  }
  getBoxSizes(ctx, options, updateCursorPosition) {
    var _a2, _b;
    const [top, left] = [(_a2 = options.top) !== null && _a2 !== void 0 ? _a2 : 0, (_b = options.left) !== null && _b !== void 0 ? _b : 0];
    const width = Math.max(options.width, ctx.title.width);
    const contentBox = [0, 0, width, options.height];
    const paddingBox = this.changeBoxByEdges(contentBox, ctx.padding);
    const borderBox = this.changeBoxByEdges(paddingBox, ctx.border);
    let fullPos;
    if (options.relative === "center") {
      fullPos = this.getCenterPos(ctx, borderBox);
    } else {
      const cursorPosition = !updateCursorPosition && this.storeCursorPosition ? this.storeCursorPosition : ctx.globalCursorPosition;
      if (options.relative === "cursor") {
        fullPos = cursorPosition;
      } else if (options.relative === "cursor-around") {
        fullPos = this.getPosForAround(ctx, [borderBox[2], borderBox[3]], cursorPosition);
      } else {
        fullPos = [top, left];
      }
      this.storeCursorPosition = cursorPosition;
    }
    [borderBox[0], borderBox[1]] = [fullPos[0], fullPos[1]];
    [paddingBox[0], paddingBox[1]] = [
      borderBox[0] + ctx.border[0],
      borderBox[1] + ctx.border[3]
    ];
    [contentBox[0], contentBox[1]] = [
      paddingBox[0] + ctx.padding[0],
      paddingBox[1] + ctx.padding[3]
    ];
    return {
      contentBox,
      paddingBox,
      borderBox
    };
  }
  vimWinConfig(ctx, options, updateCursorPosition) {
    var _a2, _b, _c, _d, _e, _f, _g, _h;
    const [top, left, width, height] = [
      (_a2 = options.top) !== null && _a2 !== void 0 ? _a2 : 0,
      (_b = options.left) !== null && _b !== void 0 ? _b : 0,
      options.width,
      options.height
    ];
    const config4 = {
      line: 0,
      col: 0,
      zindex: ((_c = options.borderOnly) !== null && _c !== void 0 ? _c : false) ? 1 : 100,
      minwidth: width,
      minheight: height,
      maxwidth: width,
      maxheight: height
    };
    if (options.relative === "center") {
      config4.pos = "center";
    } else {
      const cursorPosition = !updateCursorPosition && this.storeCursorPosition ? this.storeCursorPosition : ctx.globalCursorPosition;
      if (options.relative === "cursor") {
        [config4.line, config4.col] = cursorPosition;
      } else if (options.relative === "cursor-around") {
        const box = this.changeBoxByEdgesList([top, left, width, height], [ctx.padding, ctx.border]);
        [config4.line, config4.col] = this.getPosForAround(ctx, [box[2], box[3]], cursorPosition);
      } else {
        [config4.line, config4.col] = [top, left];
      }
      this.storeCursorPosition = cursorPosition;
      config4.line += 1;
      config4.col += 1;
    }
    const topOffset = (_d = options.topOffset) !== null && _d !== void 0 ? _d : 0;
    const leftOffset = (_e = options.leftOffset) !== null && _e !== void 0 ? _e : 0;
    config4.line += topOffset;
    config4.col += leftOffset;
    if (options.maxWidth) {
      config4.maxwidth = options.maxWidth;
    }
    if (options.maxHeight) {
      config4.maxheight = options.maxHeight;
    }
    config4.highlight = (_f = options.winHl) !== null && _f !== void 0 ? _f : defaultWinHl;
    if (options.padding) {
      config4.padding = options.padding;
    }
    if (ctx.borderEnabled) {
      config4.border = ctx.border;
      if (config4.border[0]) {
        if (ctx.title.width) {
          config4.title = ctx.title.text;
        }
        config4.close = "button";
      }
      config4.borderchars = (_g = options.borderChars) !== null && _g !== void 0 ? _g : defaultBorderChars;
      config4.borderhighlight = [(_h = options.borderWinHl) !== null && _h !== void 0 ? _h : defaultBorderWinHl];
    }
    return config4;
  }
  nvimWinConfig(ctx, options, updateCursorPosition) {
    var _a2, _b, _c;
    const { contentBox, borderBox } = this.getBoxSizes(ctx, options, updateCursorPosition);
    const topOffset = (_a2 = options.topOffset) !== null && _a2 !== void 0 ? _a2 : 0;
    const leftOffset = (_b = options.leftOffset) !== null && _b !== void 0 ? _b : 0;
    const winConfig = {
      relative: "editor",
      row: contentBox[0] + topOffset,
      col: contentBox[1] + leftOffset,
      width: contentBox[2],
      height: contentBox[3],
      focusable: (_c = options.focusable) !== null && _c !== void 0 ? _c : true
    };
    let winConfigBorder;
    if (borderBox) {
      winConfigBorder = {
        relative: "editor",
        row: borderBox[0] + topOffset,
        col: borderBox[1] + leftOffset,
        width: borderBox[2],
        height: borderBox[3],
        focusable: false
      };
    }
    return [winConfig, winConfigBorder];
  }
  winConfig(ctx, options, updateCursorPosition = true) {
    return import_coc10.workspace.isVim ? [this.vimWinConfig(ctx, options, updateCursorPosition), void 0] : this.nvimWinConfig(ctx, options, updateCursorPosition);
  }
  getRenderBorderData(ctx, options, winOptions) {
    var _a2, _b, _c, _d, _e, _f;
    const title = (_b = (_a2 = ctx.title) === null || _a2 === void 0 ? void 0 : _a2.text) !== null && _b !== void 0 ? _b : "";
    const titleWidth = (_d = (_c = ctx.title) === null || _c === void 0 ? void 0 : _c.width) !== null && _d !== void 0 ? _d : 0;
    if (!ctx.borderEnabled) {
      return;
    }
    const [bTop, bRight, bBottom, bLeft] = ctx.border;
    let [cTop, cRight, cBottom, cLeft, cTopleft, cTopright, cBotright, cBotleft] = (_e = options.borderChars) !== null && _e !== void 0 ? _e : defaultBorderChars;
    if (!bTop) {
      cTop = "";
    }
    if (!bRight) {
      cRight = "";
    }
    if (!bBottom) {
      cBottom = "";
    }
    if (!bLeft) {
      cLeft = "";
    }
    if (!bTop || !bLeft) {
      cTopleft = "";
    }
    if (!bTop || !bRight) {
      cTopright = "";
    }
    if (!bBottom || !bLeft) {
      cBotleft = "";
    }
    if (!bBottom || !bRight) {
      cBotright = "";
    }
    const width = winOptions[0];
    const height = winOptions[1];
    const spaceWidth = width - bLeft - bRight;
    const spaceHeight = height - bTop - bBottom;
    const lines = [];
    if (bTop) {
      lines.push(cTopleft + title + cTop.repeat(spaceWidth - titleWidth) + cTopright);
    }
    lines.push(...Array.from({ length: spaceHeight }, () => cLeft + " ".repeat(spaceWidth) + cRight));
    if (bBottom) {
      lines.push(cBotleft + cBottom.repeat(spaceWidth) + cBotright);
    }
    const highlights = [];
    const borderWinHl = (_f = options.borderWinHl) !== null && _f !== void 0 ? _f : defaultBorderWinHl;
    if (borderWinHl) {
      highlights.push({
        hlGroup: borderWinHl,
        line: 0,
        colStart: 0,
        colEnd: width
      });
      for (let l = 0, len = spaceHeight; l < len; l++) {
        if (bLeft) {
          highlights.push({
            hlGroup: borderWinHl,
            line: l + 1,
            colStart: 0,
            colEnd: bLeft
          });
        }
        if (bRight) {
          highlights.push({
            hlGroup: borderWinHl,
            line: l + 1,
            colStart: bLeft + spaceWidth,
            colEnd: width
          });
        }
      }
      if (bBottom) {
        highlights.push({
          hlGroup: borderWinHl,
          line: height - 1,
          colStart: 0,
          colEnd: width
        });
      }
    }
    return {
      lines,
      highlights
    };
  }
  renderBorderNotifier(buf, ctx, options, winOptions) {
    const renderData = this.getRenderBorderData(ctx, options, "width" in winOptions ? [winOptions.width, winOptions.height] : [winOptions.minwidth, winOptions.minheight]);
    if (!renderData) {
      return Notifier.noop();
    }
    const { lines, highlights } = renderData;
    return Notifier.create(() => {
      buf.setOption("modifiable", true, true);
      buf.setOption("readonly", false, true);
      void buf.setLines(lines, { start: 0, end: -1 }, true);
      buf.setOption("modifiable", false, true);
      buf.setOption("readonly", true, true);
      this.addHighlightsNotify(buf, highlights);
    });
  }
  nvimWinHl(options) {
    var _a2, _b;
    if (import_coc10.workspace.isVim) {
      return "";
    }
    const arr = [];
    arr.push(`Normal:${(_a2 = options.winHl) !== null && _a2 !== void 0 ? _a2 : defaultWinHl}`);
    arr.push(`NormalNC:${(_b = options.winHlNC) !== null && _b !== void 0 ? _b : defaultWinHlNC}`);
    return arr.join(",");
  }
  addHighlightsNotify(buf, highlights) {
    for (const hl of highlights) {
      if (!hl.hlGroup || hl.line === void 0 || hl.colStart === void 0 || hl.colEnd === void 0) {
        continue;
      }
      buf.highlightRanges(this.srcId, hl.hlGroup, [
        import_coc10.Range.create(hl.line, hl.colStart, hl.line, hl.colEnd)
      ]);
    }
  }
};

// node_modules/coc-helper/lib/esm/FloatingWindow.js
var FloatingWindow = class _FloatingWindow {
  static getInitedExecute(mode, options) {
    var _a2, _b, _c, _d;
    let initedExecute = (_b = (_a2 = options.initedExecute) === null || _a2 === void 0 ? void 0 : _a2.call(options, _FloatingWindow.initedContextVars.create)) !== null && _b !== void 0 ? _b : "";
    initedExecute = `${_FloatingWindow.modePresets[mode].createInitedExecute(_FloatingWindow.initedContextVars.create)}
${initedExecute}`;
    const borderInitedExecute = (_d = (_c = options.borderInitedExecute) === null || _c === void 0 ? void 0 : _c.call(options, _FloatingWindow.initedContextVars.create)) !== null && _d !== void 0 ? _d : _FloatingWindow.modePresets.show.createInitedExecute(_FloatingWindow.initedContextVars.create);
    return [initedExecute, borderInitedExecute];
  }
  static async create(options = {}) {
    var _a2, _b, _c;
    const mode = (_a2 = options.mode) !== null && _a2 !== void 0 ? _a2 : "default";
    const [initedExecute, borderInitedExecute] = this.getInitedExecute(mode, options);
    const [bufnr, borderBufnr] = await floatingModule.create.call((_b = options.name) !== null && _b !== void 0 ? _b : "", initedExecute, (_c = options.hasBorderBuf) !== null && _c !== void 0 ? _c : true, borderInitedExecute);
    const floatingUtil = new FloatingUtil(this.srcId);
    return new _FloatingWindow(bufnr, borderBufnr !== null && borderBufnr !== void 0 ? borderBufnr : void 0, options, mode, floatingUtil);
  }
  constructor(bufnr, borderBufnr, createOptions, mode, util2) {
    this.bufnr = bufnr;
    this.borderBufnr = borderBufnr;
    this.createOptions = createOptions;
    this.mode = mode;
    this.util = util2;
    this.nvim = import_coc11.workspace.nvim;
    this.disposables = [];
    this.nvim = import_coc11.workspace.nvim;
    this.buffer = this.nvim.createBuffer(bufnr);
    if (borderBufnr) {
      this.borderBuffer = import_coc11.workspace.nvim.createBuffer(borderBufnr);
      this.disposables.push(import_coc11.events.on("BufWinLeave", helperLogger.asyncCatch(async (curBufnr) => {
        if (this.borderBufnr && curBufnr === this.bufnr) {
          await utilModule.closeWinByBufnr.call([this.borderBufnr]);
        }
      })));
    }
  }
  getInitedExecute(options) {
    var _a2, _b, _c, _d;
    let initedExecute = (_b = (_a2 = options.initedExecute) === null || _a2 === void 0 ? void 0 : _a2.call(options, _FloatingWindow.initedContextVars.open)) !== null && _b !== void 0 ? _b : "";
    initedExecute = `${_FloatingWindow.modePresets[this.mode].openInitedExecute(_FloatingWindow.initedContextVars.open)}
${initedExecute}`;
    const borderInitedExecute = (_d = (_c = options.borderInitedExecute) === null || _c === void 0 ? void 0 : _c.call(options, _FloatingWindow.initedContextVars.open)) !== null && _d !== void 0 ? _d : _FloatingWindow.modePresets.show.openInitedExecute(_FloatingWindow.initedContextVars.open);
    return [initedExecute, borderInitedExecute];
  }
  getFocus(options) {
    var _a2, _b;
    return (_b = (_a2 = options.focus) !== null && _a2 !== void 0 ? _a2 : this.mode ? _FloatingWindow.modePresets[this.mode].focus : void 0) !== null && _b !== void 0 ? _b : false;
  }
  getModifiable(options) {
    var _a2, _b;
    return (_b = (_a2 = options.modifiable) !== null && _a2 !== void 0 ? _a2 : this.mode ? _FloatingWindow.modePresets[this.mode].modifiable : void 0) !== null && _b !== void 0 ? _b : false;
  }
  setLinesNotifier(options) {
    return Notifier.create(() => {
      if (!options.lines && !options.modifiable) {
        return;
      }
      const modifiable = this.getModifiable(options);
      this.buffer.setOption("modifiable", true, true);
      this.buffer.setOption("readonly", false, true);
      if (options.lines) {
        void this.buffer.setLines(options.lines, { start: 0, end: -1 }, true);
      }
      if (!modifiable) {
        this.buffer.setOption("modifiable", false, true);
        this.buffer.setOption("readonly", true, true);
      }
      if (options.highlights) {
        for (const hl of options.highlights) {
          this.util.addHighlightsNotify(this.buffer, [hl]);
        }
      }
      if (import_coc11.workspace.isVim) {
        this.nvim.command("redraw!", true);
      }
    });
  }
  async setLines(options) {
    await this.setLinesNotifier(options).run();
  }
  async opened() {
    const win = await this.win();
    return !!win;
  }
  async openNotifier(options) {
    var _a2;
    if (options.width <= 0 || options.height <= 0) {
      return Notifier.noop();
    }
    const notifiers = [];
    notifiers.push(this.closeNotifier());
    const ctx = await this.util.createContext(options);
    const [initedExecute, borderInitedExecute] = this.getInitedExecute(options);
    const [winConfig, borderWinConfig] = this.util.winConfig(ctx, options);
    if (options.borderOnly && borderWinConfig) {
      notifiers.push(floatingModule.open.callNotifier(this.bufnr, borderWinConfig, borderInitedExecute, null, null, "", false, this.util.nvimWinHl(options)));
      notifiers.push(this.util.renderBorderNotifier(this.buffer, ctx, options, borderWinConfig));
    } else {
      notifiers.push(floatingModule.open.callNotifier(this.bufnr, winConfig, initedExecute, (_a2 = this.borderBufnr) !== null && _a2 !== void 0 ? _a2 : null, borderWinConfig !== null && borderWinConfig !== void 0 ? borderWinConfig : null, borderInitedExecute, this.getFocus(options), this.util.nvimWinHl(options)));
    }
    if (import_coc11.workspace.isNvim && this.borderBuffer && borderWinConfig) {
      notifiers.push(this.util.renderBorderNotifier(this.borderBuffer, ctx, options, borderWinConfig));
    }
    notifiers.push(this.setLinesNotifier(options), Notifier.create(() => {
      if (options.filetype) {
        this.buffer.setOption("filetype", options.filetype, true);
      }
    }));
    return Notifier.combine(notifiers);
  }
  async open(options) {
    await (await this.openNotifier(options)).run();
  }
  async resumeNotifier(options) {
    const ctx = await this.util.createContext(options);
    const [winConfig, borderWinConfig] = this.util.winConfig(ctx, options);
    return Notifier.create(() => {
      var _a2;
      floatingModule.resume.callNotify(this.bufnr, winConfig, (_a2 = this.borderBufnr) !== null && _a2 !== void 0 ? _a2 : null, borderWinConfig !== null && borderWinConfig !== void 0 ? borderWinConfig : null, this.getFocus(options), this.util.nvimWinHl(options));
      if (this.borderBuffer && borderWinConfig) {
        this.util.renderBorderNotifier(this.borderBuffer, ctx, options, borderWinConfig).notify();
      }
      if (import_coc11.workspace.isVim) {
        this.nvim.command("redraw!", true);
      }
    });
  }
  async resume(options) {
    await (await this.resumeNotifier(options)).run();
  }
  async resizeNotifier(options) {
    var _a2;
    const ctx = await this.util.createContext(options);
    const [winConfig, borderWinConfig] = this.util.winConfig(ctx, options, false);
    const notifiers = [];
    if (options.borderOnly && borderWinConfig) {
      notifiers.push(floatingModule.update.callNotifier(this.bufnr, borderWinConfig, null, null, this.util.nvimWinHl(options)));
      notifiers.push(this.util.renderBorderNotifier(this.buffer, ctx, options, borderWinConfig));
    } else {
      notifiers.push(floatingModule.update.callNotifier(this.bufnr, winConfig, (_a2 = this.borderBufnr) !== null && _a2 !== void 0 ? _a2 : null, borderWinConfig !== null && borderWinConfig !== void 0 ? borderWinConfig : null, this.util.nvimWinHl(options)));
    }
    if (import_coc11.workspace.isNvim && this.borderBuffer && borderWinConfig) {
      notifiers.push(this.util.renderBorderNotifier(this.borderBuffer, ctx, options, borderWinConfig));
    }
    notifiers.push(Notifier.create(() => {
      if (import_coc11.workspace.isVim) {
        this.nvim.command("redraw!", true);
      }
    }));
    return Notifier.combine(notifiers);
  }
  async resize(options) {
    await (await this.resizeNotifier(options)).run();
  }
  async win() {
    const winid = await floatingModule.winid.call(this.bufnr);
    return winid ? this.nvim.createWindow(winid) : void 0;
  }
  async borderWin() {
    const borderWinid = await floatingModule.winid.call(this.bufnr);
    return borderWinid ? this.nvim.createWindow(borderWinid) : void 0;
  }
  closeNotifier() {
    return floatingModule.close.callNotifier(this.bufnr);
  }
  async close() {
    await this.closeNotifier().run();
  }
  dispose() {
    (0, import_coc11.disposeAll)(this.disposables);
    this.disposables.forEach((s) => s.dispose());
  }
};
FloatingWindow.modePresets = {
  default: {
    modifiable: false,
    focus: false,
    createInitedExecute: () => "",
    openInitedExecute: () => ""
  },
  base: {
    createInitedExecute: (ctx) => `
        call setbufvar(${ctx.bufnr}, '&buftype', 'nofile')
        call setbufvar(${ctx.bufnr}, '&bufhidden', 'hide')
        call setbufvar(${ctx.bufnr}, '&buflisted', 0)

        call setbufvar(${ctx.bufnr}, '&wrap', 1)

        call setbufvar(${ctx.bufnr}, '&swapfile', 0)

        call setbufvar(${ctx.bufnr}, '&modeline', 0)
      `,
    openInitedExecute: (ctx) => `
        call setbufvar(${ctx.bufnr}, '&list', 0)

        call setbufvar(${ctx.bufnr}, '&listchars', '')
        if has('nvim')
          call setbufvar(${ctx.bufnr}, '&fillchars', 'eob: ')
        endif

        call setbufvar(${ctx.bufnr}, '&signcolumn', 'no')
        call setbufvar(${ctx.bufnr}, '&number', 0)
        call setbufvar(${ctx.bufnr}, '&relativenumber', 0)
        call setbufvar(${ctx.bufnr}, '&foldenable', 0)
        call setbufvar(${ctx.bufnr}, '&foldcolumn', 0)

        call setbufvar(${ctx.bufnr}, '&spell', 0)

        call setbufvar(${ctx.bufnr}, '&cursorcolumn', 0)
        call setbufvar(${ctx.bufnr}, '&cursorline', 0)
        call setbufvar(${ctx.bufnr}, '&colorcolumn', '')
      `
  },
  show: {
    modifiable: false,
    createInitedExecute: (ctx) => `
        ${FloatingWindow.modePresets.base.createInitedExecute(ctx)}
        " call setbufvar(${ctx.bufnr}, '&undofile', 0)
        " call setbufvar(${ctx.bufnr}, '&undolevels', -1)

        call setbufvar(${ctx.bufnr}, '&modifiable', 0)
        call setbufvar(${ctx.bufnr}, '&modified', 0)
        call setbufvar(${ctx.bufnr}, '&readonly', 1)
      `,
    openInitedExecute: (ctx) => `
        ${FloatingWindow.modePresets.base.openInitedExecute(ctx)}
      `
  }
};
FloatingWindow.initedContextVars = {
  create: { bufnr: "a:ctx.bufnr" },
  open: { bufnr: "a:ctx.bufnr", winid: "a:ctx.winid" }
};
FloatingWindow.srcId = "coc-helper-floatwin";

// node_modules/coc-helper/lib/esm/MultiFloatingWindow.js
var import_coc12 = require("coc.nvim");

// node_modules/coc-helper/lib/esm/events.js
var import_coc13 = require("coc.nvim");
var HelperEventEmitter = class {
  constructor(helperLogger2, concurrent = false) {
    this.helperLogger = helperLogger2;
    this.concurrent = concurrent;
    this.listenersMap = /* @__PURE__ */ new Map();
  }
  listeners(event) {
    if (!this.listenersMap.has(event)) {
      const listeners = [];
      this.listenersMap.set(event, listeners);
      return listeners;
    }
    return this.listenersMap.get(event);
  }
  once(event, listener, disposables) {
    this.listeners(event).push(async (...args) => {
      const result = await listener(...args);
      disposable.dispose();
      return result;
    });
    const disposable = import_coc13.Disposable.create(() => this.off(event, listener));
    if (disposables) {
      disposables.push(disposable);
    }
    return disposable;
  }
  on(event, listener, disposables) {
    this.listeners(event).push(listener);
    const disposable = import_coc13.Disposable.create(() => this.off(event, listener));
    if (disposables) {
      disposables.push(disposable);
    }
    return disposable;
  }
  off(event, listener) {
    if (typeof listener.cancel === "function") {
      listener.cancel();
    }
    const listeners = this.listeners(event);
    const index = listeners.indexOf(listener);
    if (index !== -1) {
      listeners.splice(index, 1);
    }
  }
  async fire(event, ...args) {
    if (this.concurrent) {
      await Promise.all(this.listeners(event).map(async (listener) => {
        try {
          await listener(...args);
        } catch (e) {
          this.helperLogger.error(e);
        }
      }));
    } else {
      for (const listener of this.listeners(event)) {
        try {
          await listener(...args);
        } catch (e) {
          this.helperLogger.error(e);
        }
      }
    }
  }
};

// node_modules/coc-helper/lib/esm/WinLayoutFinder.js
var import_coc14 = require("coc.nvim");
var WinLayoutFinder = class {
  static convertVimLayoutNode(vimLayout, parent) {
    if (vimLayout[0] === "leaf") {
      return {
        type: vimLayout[0],
        winid: vimLayout[1],
        parent
      };
    } else {
      const group = {
        type: vimLayout[0],
        children: []
      };
      group.children = vimLayout[1].map((child, idx) => this.convertVimLayoutNode(child, {
        group,
        indexInParent: idx
      }));
      return group;
    }
  }
  /**
   * Create a WinLayoutFinder instance
   *
   * @param tabnr The tabnr or use current tab with undefined
   *
   * @return Promise<WinLayoutFinder> instance
   */
  static async create(tabnr) {
    const args = tabnr ? [tabnr] : [];
    const root2 = await import_coc14.workspace.nvim.call("winlayout", args);
    return new this(this.convertVimLayoutNode(root2));
  }
  static getFirstLeafWinid(node) {
    if (node.type === "leaf") {
      return node.winid;
    } else {
      return this.getFirstLeafWinid(node.children[0]);
    }
  }
  constructor(root2) {
    this.root = root2;
  }
  /**
   * @return [node, parent, indexInParent]
   */
  findWinid(winid, beginNode = this.root) {
    if (beginNode.type === "leaf") {
      if (beginNode.winid === winid) {
        return beginNode;
      }
    } else {
      for (const child of beginNode.children) {
        const target = this.findWinid(winid, child);
        if (target) {
          return target;
        }
      }
    }
  }
  findClosest(beginNode, matchWinids) {
    const checked = /* @__PURE__ */ new Set([beginNode]);
    const queue = [beginNode];
    while (queue.length) {
      const node = queue.shift();
      if (node.type === "leaf") {
        if (matchWinids.includes(node.winid)) {
          return node;
        }
      } else {
        for (const child of node.children) {
          if (!checked.has(child)) {
            queue.push(child);
            checked.add(child);
            continue;
          }
        }
      }
      if (node.parent && !checked.has(node.parent.group)) {
        queue.push(node.parent.group);
        checked.add(node.parent.group);
      }
    }
  }
};

// node_modules/coc-helper/lib/esm/index.js
async function activateHelper(context2, options = {}) {
  var _a2;
  if ((_a2 = options.vimModule) !== null && _a2 !== void 0 ? _a2 : true) {
    await VimModule.init(context2);
  }
  try {
    await import_coc15.workspace.nvim.command("hi default link CocHelperNormalFloatNC CocHelperNormalFloat");
  } catch (error) {
    void import_coc15.window.showErrorMessage(error.toString());
  }
}

// src/index.ts
var import_coc68 = require("coc.nvim");

// src/lists/actions.ts
var import_coc21 = require("coc.nvim");

// src/util/string.ts
function byteLength(str) {
  return Buffer.byteLength(str);
}
function splitCount(str, sep2, count = 2) {
  const ret = [];
  let remain = str;
  let idx = str.indexOf(sep2);
  while (idx !== -1 && count > 1) {
    ret.push(remain.slice(0, idx));
    remain = remain.slice(idx + 1);
    idx = remain.indexOf(sep2);
    count -= 1;
  }
  ret.push(remain);
  return ret;
}
function isASCII(str) {
  return /^[\x00-\xFF]*$/.test(str);
}

// src/util/number.ts
var subscriptTable = {
  0: "\u2080",
  1: "\u2081",
  2: "\u2082",
  3: "\u2083",
  4: "\u2084",
  5: "\u2085",
  6: "\u2086",
  7: "\u2087",
  8: "\u2088",
  9: "\u2089"
};
function toSubscriptNumbers(s) {
  return s.toString().split("").map((c) => subscriptTable[c] ?? c).join("");
}

// node_modules/lodash-es/_freeGlobal.js
var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
var freeGlobal_default = freeGlobal;

// node_modules/lodash-es/_root.js
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = freeGlobal_default || freeSelf || Function("return this")();
var root_default = root;

// node_modules/lodash-es/_Symbol.js
var Symbol2 = root_default.Symbol;
var Symbol_default = Symbol2;

// node_modules/lodash-es/_getRawTag.js
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
var nativeObjectToString = objectProto.toString;
var symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
  var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
  try {
    value[symToStringTag] = void 0;
    var unmasked = true;
  } catch (e) {
  }
  var result = nativeObjectToString.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }
  return result;
}
var getRawTag_default = getRawTag;

// node_modules/lodash-es/_objectToString.js
var objectProto2 = Object.prototype;
var nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
  return nativeObjectToString2.call(value);
}
var objectToString_default = objectToString;

// node_modules/lodash-es/_baseGetTag.js
var nullTag = "[object Null]";
var undefinedTag = "[object Undefined]";
var symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
  if (value == null) {
    return value === void 0 ? undefinedTag : nullTag;
  }
  return symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
var baseGetTag_default = baseGetTag;

// node_modules/lodash-es/isObjectLike.js
function isObjectLike(value) {
  return value != null && typeof value == "object";
}
var isObjectLike_default = isObjectLike;

// node_modules/lodash-es/isSymbol.js
var symbolTag = "[object Symbol]";
function isSymbol(value) {
  return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag;
}
var isSymbol_default = isSymbol;

// node_modules/lodash-es/_arrayMap.js
function arrayMap(array, iteratee) {
  var index = -1, length = array == null ? 0 : array.length, result = Array(length);
  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}
var arrayMap_default = arrayMap;

// node_modules/lodash-es/isArray.js
var isArray = Array.isArray;
var isArray_default = isArray;

// node_modules/lodash-es/_baseToString.js
var INFINITY = 1 / 0;
var symbolProto = Symbol_default ? Symbol_default.prototype : void 0;
var symbolToString = symbolProto ? symbolProto.toString : void 0;
function baseToString(value) {
  if (typeof value == "string") {
    return value;
  }
  if (isArray_default(value)) {
    return arrayMap_default(value, baseToString) + "";
  }
  if (isSymbol_default(value)) {
    return symbolToString ? symbolToString.call(value) : "";
  }
  var result = value + "";
  return result == "0" && 1 / value == -INFINITY ? "-0" : result;
}
var baseToString_default = baseToString;

// node_modules/lodash-es/_trimmedEndIndex.js
var reWhitespace = /\s/;
function trimmedEndIndex(string) {
  var index = string.length;
  while (index-- && reWhitespace.test(string.charAt(index))) {
  }
  return index;
}
var trimmedEndIndex_default = trimmedEndIndex;

// node_modules/lodash-es/_baseTrim.js
var reTrimStart = /^\s+/;
function baseTrim(string) {
  return string ? string.slice(0, trimmedEndIndex_default(string) + 1).replace(reTrimStart, "") : string;
}
var baseTrim_default = baseTrim;

// node_modules/lodash-es/isObject.js
function isObject(value) {
  var type = typeof value;
  return value != null && (type == "object" || type == "function");
}
var isObject_default = isObject;

// node_modules/lodash-es/toNumber.js
var NAN = 0 / 0;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
function toNumber(value) {
  if (typeof value == "number") {
    return value;
  }
  if (isSymbol_default(value)) {
    return NAN;
  }
  if (isObject_default(value)) {
    var other = typeof value.valueOf == "function" ? value.valueOf() : value;
    value = isObject_default(other) ? other + "" : other;
  }
  if (typeof value != "string") {
    return value === 0 ? value : +value;
  }
  value = baseTrim_default(value);
  var isBinary = reIsBinary.test(value);
  return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var toNumber_default = toNumber;

// node_modules/lodash-es/toFinite.js
var INFINITY2 = 1 / 0;
var MAX_INTEGER = 17976931348623157e292;
function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = toNumber_default(value);
  if (value === INFINITY2 || value === -INFINITY2) {
    var sign = value < 0 ? -1 : 1;
    return sign * MAX_INTEGER;
  }
  return value === value ? value : 0;
}
var toFinite_default = toFinite;

// node_modules/lodash-es/toInteger.js
function toInteger(value) {
  var result = toFinite_default(value), remainder = result % 1;
  return result === result ? remainder ? result - remainder : result : 0;
}
var toInteger_default = toInteger;

// node_modules/lodash-es/identity.js
function identity(value) {
  return value;
}
var identity_default = identity;

// node_modules/lodash-es/isFunction.js
var asyncTag = "[object AsyncFunction]";
var funcTag = "[object Function]";
var genTag = "[object GeneratorFunction]";
var proxyTag = "[object Proxy]";
function isFunction(value) {
  if (!isObject_default(value)) {
    return false;
  }
  var tag = baseGetTag_default(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_default = isFunction;

// node_modules/lodash-es/_coreJsData.js
var coreJsData = root_default["__core-js_shared__"];
var coreJsData_default = coreJsData;

// node_modules/lodash-es/_isMasked.js
var maskSrcKey = function() {
  var uid = /[^.]+$/.exec(coreJsData_default && coreJsData_default.keys && coreJsData_default.keys.IE_PROTO || "");
  return uid ? "Symbol(src)_1." + uid : "";
}();
function isMasked(func) {
  return !!maskSrcKey && maskSrcKey in func;
}
var isMasked_default = isMasked;

// node_modules/lodash-es/_toSource.js
var funcProto = Function.prototype;
var funcToString = funcProto.toString;
function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {
    }
    try {
      return func + "";
    } catch (e) {
    }
  }
  return "";
}
var toSource_default = toSource;

// node_modules/lodash-es/_baseIsNative.js
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
var reIsHostCtor = /^\[object .+?Constructor\]$/;
var funcProto2 = Function.prototype;
var objectProto3 = Object.prototype;
var funcToString2 = funcProto2.toString;
var hasOwnProperty2 = objectProto3.hasOwnProperty;
var reIsNative = RegExp(
  "^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
);
function baseIsNative(value) {
  if (!isObject_default(value) || isMasked_default(value)) {
    return false;
  }
  var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource_default(value));
}
var baseIsNative_default = baseIsNative;

// node_modules/lodash-es/_getValue.js
function getValue(object, key) {
  return object == null ? void 0 : object[key];
}
var getValue_default = getValue;

// node_modules/lodash-es/_getNative.js
function getNative(object, key) {
  var value = getValue_default(object, key);
  return baseIsNative_default(value) ? value : void 0;
}
var getNative_default = getNative;

// node_modules/lodash-es/_WeakMap.js
var WeakMap = getNative_default(root_default, "WeakMap");
var WeakMap_default = WeakMap;

// node_modules/lodash-es/noop.js
function noop() {
}
var noop_default = noop;

// node_modules/lodash-es/_defineProperty.js
var defineProperty = function() {
  try {
    var func = getNative_default(Object, "defineProperty");
    func({}, "", {});
    return func;
  } catch (e) {
  }
}();
var defineProperty_default = defineProperty;

// node_modules/lodash-es/_baseFindIndex.js
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length, index = fromIndex + (fromRight ? 1 : -1);
  while (fromRight ? index-- : ++index < length) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}
var baseFindIndex_default = baseFindIndex;

// node_modules/lodash-es/_baseIsNaN.js
function baseIsNaN(value) {
  return value !== value;
}
var baseIsNaN_default = baseIsNaN;

// node_modules/lodash-es/_strictIndexOf.js
function strictIndexOf(array, value, fromIndex) {
  var index = fromIndex - 1, length = array.length;
  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}
var strictIndexOf_default = strictIndexOf;

// node_modules/lodash-es/_baseIndexOf.js
function baseIndexOf(array, value, fromIndex) {
  return value === value ? strictIndexOf_default(array, value, fromIndex) : baseFindIndex_default(array, baseIsNaN_default, fromIndex);
}
var baseIndexOf_default = baseIndexOf;

// node_modules/lodash-es/_arrayIncludes.js
function arrayIncludes(array, value) {
  var length = array == null ? 0 : array.length;
  return !!length && baseIndexOf_default(array, value, 0) > -1;
}
var arrayIncludes_default = arrayIncludes;

// node_modules/lodash-es/_isIndex.js
var MAX_SAFE_INTEGER = 9007199254740991;
var reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
}
var isIndex_default = isIndex;

// node_modules/lodash-es/_baseAssignValue.js
function baseAssignValue(object, key, value) {
  if (key == "__proto__" && defineProperty_default) {
    defineProperty_default(object, key, {
      "configurable": true,
      "enumerable": true,
      "value": value,
      "writable": true
    });
  } else {
    object[key] = value;
  }
}
var baseAssignValue_default = baseAssignValue;

// node_modules/lodash-es/eq.js
function eq(value, other) {
  return value === other || value !== value && other !== other;
}
var eq_default = eq;

// node_modules/lodash-es/isLength.js
var MAX_SAFE_INTEGER2 = 9007199254740991;
function isLength(value) {
  return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
}
var isLength_default = isLength;

// node_modules/lodash-es/isArrayLike.js
function isArrayLike(value) {
  return value != null && isLength_default(value.length) && !isFunction_default(value);
}
var isArrayLike_default = isArrayLike;

// node_modules/lodash-es/_isPrototype.js
var objectProto4 = Object.prototype;
function isPrototype(value) {
  var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto4;
  return value === proto;
}
var isPrototype_default = isPrototype;

// node_modules/lodash-es/_baseTimes.js
function baseTimes(n, iteratee) {
  var index = -1, result = Array(n);
  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}
var baseTimes_default = baseTimes;

// node_modules/lodash-es/_baseIsArguments.js
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
  return isObjectLike_default(value) && baseGetTag_default(value) == argsTag;
}
var baseIsArguments_default = baseIsArguments;

// node_modules/lodash-es/isArguments.js
var objectProto5 = Object.prototype;
var hasOwnProperty3 = objectProto5.hasOwnProperty;
var propertyIsEnumerable = objectProto5.propertyIsEnumerable;
var isArguments = baseIsArguments_default(/* @__PURE__ */ function() {
  return arguments;
}()) ? baseIsArguments_default : function(value) {
  return isObjectLike_default(value) && hasOwnProperty3.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
};
var isArguments_default = isArguments;

// node_modules/lodash-es/stubFalse.js
function stubFalse() {
  return false;
}
var stubFalse_default = stubFalse;

// node_modules/lodash-es/isBuffer.js
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module;
var moduleExports = freeModule && freeModule.exports === freeExports;
var Buffer2 = moduleExports ? root_default.Buffer : void 0;
var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0;
var isBuffer = nativeIsBuffer || stubFalse_default;
var isBuffer_default = isBuffer;

// node_modules/lodash-es/_baseIsTypedArray.js
var argsTag2 = "[object Arguments]";
var arrayTag = "[object Array]";
var boolTag = "[object Boolean]";
var dateTag = "[object Date]";
var errorTag = "[object Error]";
var funcTag2 = "[object Function]";
var mapTag = "[object Map]";
var numberTag = "[object Number]";
var objectTag = "[object Object]";
var regexpTag = "[object RegExp]";
var setTag = "[object Set]";
var stringTag = "[object String]";
var weakMapTag = "[object WeakMap]";
var arrayBufferTag = "[object ArrayBuffer]";
var dataViewTag = "[object DataView]";
var float32Tag = "[object Float32Array]";
var float64Tag = "[object Float64Array]";
var int8Tag = "[object Int8Array]";
var int16Tag = "[object Int16Array]";
var int32Tag = "[object Int32Array]";
var uint8Tag = "[object Uint8Array]";
var uint8ClampedTag = "[object Uint8ClampedArray]";
var uint16Tag = "[object Uint16Array]";
var uint32Tag = "[object Uint32Array]";
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag2] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag2] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
function baseIsTypedArray(value) {
  return isObjectLike_default(value) && isLength_default(value.length) && !!typedArrayTags[baseGetTag_default(value)];
}
var baseIsTypedArray_default = baseIsTypedArray;

// node_modules/lodash-es/_baseUnary.js
function baseUnary(func) {
  return function(value) {
    return func(value);
  };
}
var baseUnary_default = baseUnary;

// node_modules/lodash-es/_nodeUtil.js
var freeExports2 = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule2 = freeExports2 && typeof module == "object" && module && !module.nodeType && module;
var moduleExports2 = freeModule2 && freeModule2.exports === freeExports2;
var freeProcess = moduleExports2 && freeGlobal_default.process;
var nodeUtil = function() {
  try {
    var types2 = freeModule2 && freeModule2.require && freeModule2.require("util").types;
    if (types2) {
      return types2;
    }
    return freeProcess && freeProcess.binding && freeProcess.binding("util");
  } catch (e) {
  }
}();
var nodeUtil_default = nodeUtil;

// node_modules/lodash-es/isTypedArray.js
var nodeIsTypedArray = nodeUtil_default && nodeUtil_default.isTypedArray;
var isTypedArray = nodeIsTypedArray ? baseUnary_default(nodeIsTypedArray) : baseIsTypedArray_default;
var isTypedArray_default = isTypedArray;

// node_modules/lodash-es/_arrayLikeKeys.js
var objectProto6 = Object.prototype;
var hasOwnProperty4 = objectProto6.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
  var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes_default(value.length, String) : [], length = result.length;
  for (var key in value) {
    if ((inherited || hasOwnProperty4.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
    (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
    isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
    isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
    isIndex_default(key, length)))) {
      result.push(key);
    }
  }
  return result;
}
var arrayLikeKeys_default = arrayLikeKeys;

// node_modules/lodash-es/_overArg.js
function overArg(func, transform) {
  return function(arg) {
    return func(transform(arg));
  };
}
var overArg_default = overArg;

// node_modules/lodash-es/_nativeKeys.js
var nativeKeys = overArg_default(Object.keys, Object);
var nativeKeys_default = nativeKeys;

// node_modules/lodash-es/_baseKeys.js
var objectProto7 = Object.prototype;
var hasOwnProperty5 = objectProto7.hasOwnProperty;
function baseKeys(object) {
  if (!isPrototype_default(object)) {
    return nativeKeys_default(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty5.call(object, key) && key != "constructor") {
      result.push(key);
    }
  }
  return result;
}
var baseKeys_default = baseKeys;

// node_modules/lodash-es/keys.js
function keys(object) {
  return isArrayLike_default(object) ? arrayLikeKeys_default(object) : baseKeys_default(object);
}
var keys_default = keys;

// node_modules/lodash-es/_isKey.js
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var reIsPlainProp = /^\w*$/;
function isKey(value, object) {
  if (isArray_default(value)) {
    return false;
  }
  var type = typeof value;
  if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol_default(value)) {
    return true;
  }
  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
var isKey_default = isKey;

// node_modules/lodash-es/_nativeCreate.js
var nativeCreate = getNative_default(Object, "create");
var nativeCreate_default = nativeCreate;

// node_modules/lodash-es/_hashClear.js
function hashClear() {
  this.__data__ = nativeCreate_default ? nativeCreate_default(null) : {};
  this.size = 0;
}
var hashClear_default = hashClear;

// node_modules/lodash-es/_hashDelete.js
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}
var hashDelete_default = hashDelete;

// node_modules/lodash-es/_hashGet.js
var HASH_UNDEFINED = "__lodash_hash_undefined__";
var objectProto8 = Object.prototype;
var hasOwnProperty6 = objectProto8.hasOwnProperty;
function hashGet(key) {
  var data = this.__data__;
  if (nativeCreate_default) {
    var result = data[key];
    return result === HASH_UNDEFINED ? void 0 : result;
  }
  return hasOwnProperty6.call(data, key) ? data[key] : void 0;
}
var hashGet_default = hashGet;

// node_modules/lodash-es/_hashHas.js
var objectProto9 = Object.prototype;
var hasOwnProperty7 = objectProto9.hasOwnProperty;
function hashHas(key) {
  var data = this.__data__;
  return nativeCreate_default ? data[key] !== void 0 : hasOwnProperty7.call(data, key);
}
var hashHas_default = hashHas;

// node_modules/lodash-es/_hashSet.js
var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value;
  return this;
}
var hashSet_default = hashSet;

// node_modules/lodash-es/_Hash.js
function Hash(entries) {
  var index = -1, length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
Hash.prototype.clear = hashClear_default;
Hash.prototype["delete"] = hashDelete_default;
Hash.prototype.get = hashGet_default;
Hash.prototype.has = hashHas_default;
Hash.prototype.set = hashSet_default;
var Hash_default = Hash;

// node_modules/lodash-es/_listCacheClear.js
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}
var listCacheClear_default = listCacheClear;

// node_modules/lodash-es/_assocIndexOf.js
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (eq_default(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}
var assocIndexOf_default = assocIndexOf;

// node_modules/lodash-es/_listCacheDelete.js
var arrayProto = Array.prototype;
var splice = arrayProto.splice;
function listCacheDelete(key) {
  var data = this.__data__, index = assocIndexOf_default(data, key);
  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  --this.size;
  return true;
}
var listCacheDelete_default = listCacheDelete;

// node_modules/lodash-es/_listCacheGet.js
function listCacheGet(key) {
  var data = this.__data__, index = assocIndexOf_default(data, key);
  return index < 0 ? void 0 : data[index][1];
}
var listCacheGet_default = listCacheGet;

// node_modules/lodash-es/_listCacheHas.js
function listCacheHas(key) {
  return assocIndexOf_default(this.__data__, key) > -1;
}
var listCacheHas_default = listCacheHas;

// node_modules/lodash-es/_listCacheSet.js
function listCacheSet(key, value) {
  var data = this.__data__, index = assocIndexOf_default(data, key);
  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}
var listCacheSet_default = listCacheSet;

// node_modules/lodash-es/_ListCache.js
function ListCache(entries) {
  var index = -1, length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
ListCache.prototype.clear = listCacheClear_default;
ListCache.prototype["delete"] = listCacheDelete_default;
ListCache.prototype.get = listCacheGet_default;
ListCache.prototype.has = listCacheHas_default;
ListCache.prototype.set = listCacheSet_default;
var ListCache_default = ListCache;

// node_modules/lodash-es/_Map.js
var Map2 = getNative_default(root_default, "Map");
var Map_default = Map2;

// node_modules/lodash-es/_mapCacheClear.js
function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    "hash": new Hash_default(),
    "map": new (Map_default || ListCache_default)(),
    "string": new Hash_default()
  };
}
var mapCacheClear_default = mapCacheClear;

// node_modules/lodash-es/_isKeyable.js
function isKeyable(value) {
  var type = typeof value;
  return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
var isKeyable_default = isKeyable;

// node_modules/lodash-es/_getMapData.js
function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
var getMapData_default = getMapData;

// node_modules/lodash-es/_mapCacheDelete.js
function mapCacheDelete(key) {
  var result = getMapData_default(this, key)["delete"](key);
  this.size -= result ? 1 : 0;
  return result;
}
var mapCacheDelete_default = mapCacheDelete;

// node_modules/lodash-es/_mapCacheGet.js
function mapCacheGet(key) {
  return getMapData_default(this, key).get(key);
}
var mapCacheGet_default = mapCacheGet;

// node_modules/lodash-es/_mapCacheHas.js
function mapCacheHas(key) {
  return getMapData_default(this, key).has(key);
}
var mapCacheHas_default = mapCacheHas;

// node_modules/lodash-es/_mapCacheSet.js
function mapCacheSet(key, value) {
  var data = getMapData_default(this, key), size = data.size;
  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}
var mapCacheSet_default = mapCacheSet;

// node_modules/lodash-es/_MapCache.js
function MapCache(entries) {
  var index = -1, length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}
MapCache.prototype.clear = mapCacheClear_default;
MapCache.prototype["delete"] = mapCacheDelete_default;
MapCache.prototype.get = mapCacheGet_default;
MapCache.prototype.has = mapCacheHas_default;
MapCache.prototype.set = mapCacheSet_default;
var MapCache_default = MapCache;

// node_modules/lodash-es/memoize.js
var FUNC_ERROR_TEXT = "Expected a function";
function memoize(func, resolver) {
  if (typeof func != "function" || resolver != null && typeof resolver != "function") {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var memoized = function() {
    var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
    if (cache.has(key)) {
      return cache.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };
  memoized.cache = new (memoize.Cache || MapCache_default)();
  return memoized;
}
memoize.Cache = MapCache_default;
var memoize_default = memoize;

// node_modules/lodash-es/_memoizeCapped.js
var MAX_MEMOIZE_SIZE = 500;
function memoizeCapped(func) {
  var result = memoize_default(func, function(key) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }
    return key;
  });
  var cache = result.cache;
  return result;
}
var memoizeCapped_default = memoizeCapped;

// node_modules/lodash-es/_stringToPath.js
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
var reEscapeChar = /\\(\\)?/g;
var stringToPath = memoizeCapped_default(function(string) {
  var result = [];
  if (string.charCodeAt(0) === 46) {
    result.push("");
  }
  string.replace(rePropName, function(match3, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match3);
  });
  return result;
});
var stringToPath_default = stringToPath;

// node_modules/lodash-es/toString.js
function toString(value) {
  return value == null ? "" : baseToString_default(value);
}
var toString_default = toString;

// node_modules/lodash-es/_castPath.js
function castPath(value, object) {
  if (isArray_default(value)) {
    return value;
  }
  return isKey_default(value, object) ? [value] : stringToPath_default(toString_default(value));
}
var castPath_default = castPath;

// node_modules/lodash-es/_toKey.js
var INFINITY3 = 1 / 0;
function toKey(value) {
  if (typeof value == "string" || isSymbol_default(value)) {
    return value;
  }
  var result = value + "";
  return result == "0" && 1 / value == -INFINITY3 ? "-0" : result;
}
var toKey_default = toKey;

// node_modules/lodash-es/_baseGet.js
function baseGet(object, path3) {
  path3 = castPath_default(path3, object);
  var index = 0, length = path3.length;
  while (object != null && index < length) {
    object = object[toKey_default(path3[index++])];
  }
  return index && index == length ? object : void 0;
}
var baseGet_default = baseGet;

// node_modules/lodash-es/get.js
function get(object, path3, defaultValue) {
  var result = object == null ? void 0 : baseGet_default(object, path3);
  return result === void 0 ? defaultValue : result;
}
var get_default = get;

// node_modules/lodash-es/_arrayPush.js
function arrayPush(array, values) {
  var index = -1, length = values.length, offset = array.length;
  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}
var arrayPush_default = arrayPush;

// node_modules/lodash-es/_stackClear.js
function stackClear() {
  this.__data__ = new ListCache_default();
  this.size = 0;
}
var stackClear_default = stackClear;

// node_modules/lodash-es/_stackDelete.js
function stackDelete(key) {
  var data = this.__data__, result = data["delete"](key);
  this.size = data.size;
  return result;
}
var stackDelete_default = stackDelete;

// node_modules/lodash-es/_stackGet.js
function stackGet(key) {
  return this.__data__.get(key);
}
var stackGet_default = stackGet;

// node_modules/lodash-es/_stackHas.js
function stackHas(key) {
  return this.__data__.has(key);
}
var stackHas_default = stackHas;

// node_modules/lodash-es/_stackSet.js
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
  var data = this.__data__;
  if (data instanceof ListCache_default) {
    var pairs = data.__data__;
    if (!Map_default || pairs.length < LARGE_ARRAY_SIZE - 1) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new MapCache_default(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}
var stackSet_default = stackSet;

// node_modules/lodash-es/_Stack.js
function Stack(entries) {
  var data = this.__data__ = new ListCache_default(entries);
  this.size = data.size;
}
Stack.prototype.clear = stackClear_default;
Stack.prototype["delete"] = stackDelete_default;
Stack.prototype.get = stackGet_default;
Stack.prototype.has = stackHas_default;
Stack.prototype.set = stackSet_default;
var Stack_default = Stack;

// node_modules/lodash-es/_arrayFilter.js
function arrayFilter(array, predicate) {
  var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}
var arrayFilter_default = arrayFilter;

// node_modules/lodash-es/stubArray.js
function stubArray() {
  return [];
}
var stubArray_default = stubArray;

// node_modules/lodash-es/_getSymbols.js
var objectProto10 = Object.prototype;
var propertyIsEnumerable2 = objectProto10.propertyIsEnumerable;
var nativeGetSymbols = Object.getOwnPropertySymbols;
var getSymbols = !nativeGetSymbols ? stubArray_default : function(object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return arrayFilter_default(nativeGetSymbols(object), function(symbol) {
    return propertyIsEnumerable2.call(object, symbol);
  });
};
var getSymbols_default = getSymbols;

// node_modules/lodash-es/_baseGetAllKeys.js
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray_default(object) ? result : arrayPush_default(result, symbolsFunc(object));
}
var baseGetAllKeys_default = baseGetAllKeys;

// node_modules/lodash-es/_getAllKeys.js
function getAllKeys(object) {
  return baseGetAllKeys_default(object, keys_default, getSymbols_default);
}
var getAllKeys_default = getAllKeys;

// node_modules/lodash-es/_DataView.js
var DataView = getNative_default(root_default, "DataView");
var DataView_default = DataView;

// node_modules/lodash-es/_Promise.js
var Promise2 = getNative_default(root_default, "Promise");
var Promise_default = Promise2;

// node_modules/lodash-es/_Set.js
var Set2 = getNative_default(root_default, "Set");
var Set_default = Set2;

// node_modules/lodash-es/_getTag.js
var mapTag2 = "[object Map]";
var objectTag2 = "[object Object]";
var promiseTag = "[object Promise]";
var setTag2 = "[object Set]";
var weakMapTag2 = "[object WeakMap]";
var dataViewTag2 = "[object DataView]";
var dataViewCtorString = toSource_default(DataView_default);
var mapCtorString = toSource_default(Map_default);
var promiseCtorString = toSource_default(Promise_default);
var setCtorString = toSource_default(Set_default);
var weakMapCtorString = toSource_default(WeakMap_default);
var getTag = baseGetTag_default;
if (DataView_default && getTag(new DataView_default(new ArrayBuffer(1))) != dataViewTag2 || Map_default && getTag(new Map_default()) != mapTag2 || Promise_default && getTag(Promise_default.resolve()) != promiseTag || Set_default && getTag(new Set_default()) != setTag2 || WeakMap_default && getTag(new WeakMap_default()) != weakMapTag2) {
  getTag = function(value) {
    var result = baseGetTag_default(value), Ctor = result == objectTag2 ? value.constructor : void 0, ctorString = Ctor ? toSource_default(Ctor) : "";
    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString:
          return dataViewTag2;
        case mapCtorString:
          return mapTag2;
        case promiseCtorString:
          return promiseTag;
        case setCtorString:
          return setTag2;
        case weakMapCtorString:
          return weakMapTag2;
      }
    }
    return result;
  };
}
var getTag_default = getTag;

// node_modules/lodash-es/_Uint8Array.js
var Uint8Array2 = root_default.Uint8Array;
var Uint8Array_default = Uint8Array2;

// node_modules/lodash-es/_setCacheAdd.js
var HASH_UNDEFINED3 = "__lodash_hash_undefined__";
function setCacheAdd(value) {
  this.__data__.set(value, HASH_UNDEFINED3);
  return this;
}
var setCacheAdd_default = setCacheAdd;

// node_modules/lodash-es/_setCacheHas.js
function setCacheHas(value) {
  return this.__data__.has(value);
}
var setCacheHas_default = setCacheHas;

// node_modules/lodash-es/_SetCache.js
function SetCache(values) {
  var index = -1, length = values == null ? 0 : values.length;
  this.__data__ = new MapCache_default();
  while (++index < length) {
    this.add(values[index]);
  }
}
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd_default;
SetCache.prototype.has = setCacheHas_default;
var SetCache_default = SetCache;

// node_modules/lodash-es/_arraySome.js
function arraySome(array, predicate) {
  var index = -1, length = array == null ? 0 : array.length;
  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }
  return false;
}
var arraySome_default = arraySome;

// node_modules/lodash-es/_cacheHas.js
function cacheHas(cache, key) {
  return cache.has(key);
}
var cacheHas_default = cacheHas;

// node_modules/lodash-es/_equalArrays.js
var COMPARE_PARTIAL_FLAG = 1;
var COMPARE_UNORDERED_FLAG = 2;
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  var arrStacked = stack.get(array);
  var othStacked = stack.get(other);
  if (arrStacked && othStacked) {
    return arrStacked == other && othStacked == array;
  }
  var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache_default() : void 0;
  stack.set(array, other);
  stack.set(other, array);
  while (++index < arrLength) {
    var arrValue = array[index], othValue = other[index];
    if (customizer) {
      var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
    }
    if (compared !== void 0) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    if (seen) {
      if (!arraySome_default(other, function(othValue2, othIndex) {
        if (!cacheHas_default(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
          return seen.push(othIndex);
        }
      })) {
        result = false;
        break;
      }
    } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
      result = false;
      break;
    }
  }
  stack["delete"](array);
  stack["delete"](other);
  return result;
}
var equalArrays_default = equalArrays;

// node_modules/lodash-es/_mapToArray.js
function mapToArray(map) {
  var index = -1, result = Array(map.size);
  map.forEach(function(value, key) {
    result[++index] = [key, value];
  });
  return result;
}
var mapToArray_default = mapToArray;

// node_modules/lodash-es/_setToArray.js
function setToArray(set) {
  var index = -1, result = Array(set.size);
  set.forEach(function(value) {
    result[++index] = value;
  });
  return result;
}
var setToArray_default = setToArray;

// node_modules/lodash-es/_equalByTag.js
var COMPARE_PARTIAL_FLAG2 = 1;
var COMPARE_UNORDERED_FLAG2 = 2;
var boolTag2 = "[object Boolean]";
var dateTag2 = "[object Date]";
var errorTag2 = "[object Error]";
var mapTag3 = "[object Map]";
var numberTag2 = "[object Number]";
var regexpTag2 = "[object RegExp]";
var setTag3 = "[object Set]";
var stringTag2 = "[object String]";
var symbolTag2 = "[object Symbol]";
var arrayBufferTag2 = "[object ArrayBuffer]";
var dataViewTag3 = "[object DataView]";
var symbolProto2 = Symbol_default ? Symbol_default.prototype : void 0;
var symbolValueOf = symbolProto2 ? symbolProto2.valueOf : void 0;
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case dataViewTag3:
      if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;
    case arrayBufferTag2:
      if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array_default(object), new Uint8Array_default(other))) {
        return false;
      }
      return true;
    case boolTag2:
    case dateTag2:
    case numberTag2:
      return eq_default(+object, +other);
    case errorTag2:
      return object.name == other.name && object.message == other.message;
    case regexpTag2:
    case stringTag2:
      return object == other + "";
    case mapTag3:
      var convert2 = mapToArray_default;
    case setTag3:
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG2;
      convert2 || (convert2 = setToArray_default);
      if (object.size != other.size && !isPartial) {
        return false;
      }
      var stacked = stack.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= COMPARE_UNORDERED_FLAG2;
      stack.set(object, other);
      var result = equalArrays_default(convert2(object), convert2(other), bitmask, customizer, equalFunc, stack);
      stack["delete"](object);
      return result;
    case symbolTag2:
      if (symbolValueOf) {
        return symbolValueOf.call(object) == symbolValueOf.call(other);
      }
  }
  return false;
}
var equalByTag_default = equalByTag;

// node_modules/lodash-es/_equalObjects.js
var COMPARE_PARTIAL_FLAG3 = 1;
var objectProto11 = Object.prototype;
var hasOwnProperty8 = objectProto11.hasOwnProperty;
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG3, objProps = getAllKeys_default(object), objLength = objProps.length, othProps = getAllKeys_default(other), othLength = othProps.length;
  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index = objLength;
  while (index--) {
    var key = objProps[index];
    if (!(isPartial ? key in other : hasOwnProperty8.call(other, key))) {
      return false;
    }
  }
  var objStacked = stack.get(object);
  var othStacked = stack.get(other);
  if (objStacked && othStacked) {
    return objStacked == other && othStacked == object;
  }
  var result = true;
  stack.set(object, other);
  stack.set(other, object);
  var skipCtor = isPartial;
  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key], othValue = other[key];
    if (customizer) {
      var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
    }
    if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == "constructor");
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor, othCtor = other.constructor;
    if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack["delete"](object);
  stack["delete"](other);
  return result;
}
var equalObjects_default = equalObjects;

// node_modules/lodash-es/_baseIsEqualDeep.js
var COMPARE_PARTIAL_FLAG4 = 1;
var argsTag3 = "[object Arguments]";
var arrayTag2 = "[object Array]";
var objectTag3 = "[object Object]";
var objectProto12 = Object.prototype;
var hasOwnProperty9 = objectProto12.hasOwnProperty;
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = isArray_default(object), othIsArr = isArray_default(other), objTag = objIsArr ? arrayTag2 : getTag_default(object), othTag = othIsArr ? arrayTag2 : getTag_default(other);
  objTag = objTag == argsTag3 ? objectTag3 : objTag;
  othTag = othTag == argsTag3 ? objectTag3 : othTag;
  var objIsObj = objTag == objectTag3, othIsObj = othTag == objectTag3, isSameTag = objTag == othTag;
  if (isSameTag && isBuffer_default(object)) {
    if (!isBuffer_default(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack || (stack = new Stack_default());
    return objIsArr || isTypedArray_default(object) ? equalArrays_default(object, other, bitmask, customizer, equalFunc, stack) : equalByTag_default(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }
  if (!(bitmask & COMPARE_PARTIAL_FLAG4)) {
    var objIsWrapped = objIsObj && hasOwnProperty9.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty9.call(other, "__wrapped__");
    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
      stack || (stack = new Stack_default());
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack || (stack = new Stack_default());
  return equalObjects_default(object, other, bitmask, customizer, equalFunc, stack);
}
var baseIsEqualDeep_default = baseIsEqualDeep;

// node_modules/lodash-es/_baseIsEqual.js
function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || !isObjectLike_default(value) && !isObjectLike_default(other)) {
    return value !== value && other !== other;
  }
  return baseIsEqualDeep_default(value, other, bitmask, customizer, baseIsEqual, stack);
}
var baseIsEqual_default = baseIsEqual;

// node_modules/lodash-es/_baseIsMatch.js
var COMPARE_PARTIAL_FLAG5 = 1;
var COMPARE_UNORDERED_FLAG3 = 2;
function baseIsMatch(object, source, matchData, customizer) {
  var index = matchData.length, length = index, noCustomizer = !customizer;
  if (object == null) {
    return !length;
  }
  object = Object(object);
  while (index--) {
    var data = matchData[index];
    if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
      return false;
    }
  }
  while (++index < length) {
    data = matchData[index];
    var key = data[0], objValue = object[key], srcValue = data[1];
    if (noCustomizer && data[2]) {
      if (objValue === void 0 && !(key in object)) {
        return false;
      }
    } else {
      var stack = new Stack_default();
      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source, stack);
      }
      if (!(result === void 0 ? baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG5 | COMPARE_UNORDERED_FLAG3, customizer, stack) : result)) {
        return false;
      }
    }
  }
  return true;
}
var baseIsMatch_default = baseIsMatch;

// node_modules/lodash-es/_isStrictComparable.js
function isStrictComparable(value) {
  return value === value && !isObject_default(value);
}
var isStrictComparable_default = isStrictComparable;

// node_modules/lodash-es/_getMatchData.js
function getMatchData(object) {
  var result = keys_default(object), length = result.length;
  while (length--) {
    var key = result[length], value = object[key];
    result[length] = [key, value, isStrictComparable_default(value)];
  }
  return result;
}
var getMatchData_default = getMatchData;

// node_modules/lodash-es/_matchesStrictComparable.js
function matchesStrictComparable(key, srcValue) {
  return function(object) {
    if (object == null) {
      return false;
    }
    return object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
  };
}
var matchesStrictComparable_default = matchesStrictComparable;

// node_modules/lodash-es/_baseMatches.js
function baseMatches(source) {
  var matchData = getMatchData_default(source);
  if (matchData.length == 1 && matchData[0][2]) {
    return matchesStrictComparable_default(matchData[0][0], matchData[0][1]);
  }
  return function(object) {
    return object === source || baseIsMatch_default(object, source, matchData);
  };
}
var baseMatches_default = baseMatches;

// node_modules/lodash-es/_baseHasIn.js
function baseHasIn(object, key) {
  return object != null && key in Object(object);
}
var baseHasIn_default = baseHasIn;

// node_modules/lodash-es/_hasPath.js
function hasPath(object, path3, hasFunc) {
  path3 = castPath_default(path3, object);
  var index = -1, length = path3.length, result = false;
  while (++index < length) {
    var key = toKey_default(path3[index]);
    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }
    object = object[key];
  }
  if (result || ++index != length) {
    return result;
  }
  length = object == null ? 0 : object.length;
  return !!length && isLength_default(length) && isIndex_default(key, length) && (isArray_default(object) || isArguments_default(object));
}
var hasPath_default = hasPath;

// node_modules/lodash-es/hasIn.js
function hasIn(object, path3) {
  return object != null && hasPath_default(object, path3, baseHasIn_default);
}
var hasIn_default = hasIn;

// node_modules/lodash-es/_baseMatchesProperty.js
var COMPARE_PARTIAL_FLAG6 = 1;
var COMPARE_UNORDERED_FLAG4 = 2;
function baseMatchesProperty(path3, srcValue) {
  if (isKey_default(path3) && isStrictComparable_default(srcValue)) {
    return matchesStrictComparable_default(toKey_default(path3), srcValue);
  }
  return function(object) {
    var objValue = get_default(object, path3);
    return objValue === void 0 && objValue === srcValue ? hasIn_default(object, path3) : baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG6 | COMPARE_UNORDERED_FLAG4);
  };
}
var baseMatchesProperty_default = baseMatchesProperty;

// node_modules/lodash-es/_baseProperty.js
function baseProperty(key) {
  return function(object) {
    return object == null ? void 0 : object[key];
  };
}
var baseProperty_default = baseProperty;

// node_modules/lodash-es/_basePropertyDeep.js
function basePropertyDeep(path3) {
  return function(object) {
    return baseGet_default(object, path3);
  };
}
var basePropertyDeep_default = basePropertyDeep;

// node_modules/lodash-es/property.js
function property(path3) {
  return isKey_default(path3) ? baseProperty_default(toKey_default(path3)) : basePropertyDeep_default(path3);
}
var property_default = property;

// node_modules/lodash-es/_baseIteratee.js
function baseIteratee(value) {
  if (typeof value == "function") {
    return value;
  }
  if (value == null) {
    return identity_default;
  }
  if (typeof value == "object") {
    return isArray_default(value) ? baseMatchesProperty_default(value[0], value[1]) : baseMatches_default(value);
  }
  return property_default(value);
}
var baseIteratee_default = baseIteratee;

// node_modules/lodash-es/_arrayAggregator.js
function arrayAggregator(array, setter, iteratee, accumulator) {
  var index = -1, length = array == null ? 0 : array.length;
  while (++index < length) {
    var value = array[index];
    setter(accumulator, value, iteratee(value), array);
  }
  return accumulator;
}
var arrayAggregator_default = arrayAggregator;

// node_modules/lodash-es/_createBaseFor.js
function createBaseFor(fromRight) {
  return function(object, iteratee, keysFunc) {
    var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
    while (length--) {
      var key = props[fromRight ? length : ++index];
      if (iteratee(iterable[key], key, iterable) === false) {
        break;
      }
    }
    return object;
  };
}
var createBaseFor_default = createBaseFor;

// node_modules/lodash-es/_baseFor.js
var baseFor = createBaseFor_default();
var baseFor_default = baseFor;

// node_modules/lodash-es/_baseForOwn.js
function baseForOwn(object, iteratee) {
  return object && baseFor_default(object, iteratee, keys_default);
}
var baseForOwn_default = baseForOwn;

// node_modules/lodash-es/_createBaseEach.js
function createBaseEach(eachFunc, fromRight) {
  return function(collection, iteratee) {
    if (collection == null) {
      return collection;
    }
    if (!isArrayLike_default(collection)) {
      return eachFunc(collection, iteratee);
    }
    var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection);
    while (fromRight ? index-- : ++index < length) {
      if (iteratee(iterable[index], index, iterable) === false) {
        break;
      }
    }
    return collection;
  };
}
var createBaseEach_default = createBaseEach;

// node_modules/lodash-es/_baseEach.js
var baseEach = createBaseEach_default(baseForOwn_default);
var baseEach_default = baseEach;

// node_modules/lodash-es/_baseAggregator.js
function baseAggregator(collection, setter, iteratee, accumulator) {
  baseEach_default(collection, function(value, key, collection2) {
    setter(accumulator, value, iteratee(value), collection2);
  });
  return accumulator;
}
var baseAggregator_default = baseAggregator;

// node_modules/lodash-es/_createAggregator.js
function createAggregator(setter, initializer) {
  return function(collection, iteratee) {
    var func = isArray_default(collection) ? arrayAggregator_default : baseAggregator_default, accumulator = initializer ? initializer() : {};
    return func(collection, setter, baseIteratee_default(iteratee, 2), accumulator);
  };
}
var createAggregator_default = createAggregator;

// node_modules/lodash-es/_arrayIncludesWith.js
function arrayIncludesWith(array, value, comparator) {
  var index = -1, length = array == null ? 0 : array.length;
  while (++index < length) {
    if (comparator(value, array[index])) {
      return true;
    }
  }
  return false;
}
var arrayIncludesWith_default = arrayIncludesWith;

// node_modules/lodash-es/findIndex.js
var nativeMax = Math.max;
function findIndex(array, predicate, fromIndex) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return -1;
  }
  var index = fromIndex == null ? 0 : toInteger_default(fromIndex);
  if (index < 0) {
    index = nativeMax(length + index, 0);
  }
  return baseFindIndex_default(array, baseIteratee_default(predicate, 3), index);
}
var findIndex_default = findIndex;

// node_modules/lodash-es/findLastIndex.js
var nativeMax2 = Math.max;
var nativeMin = Math.min;
function findLastIndex(array, predicate, fromIndex) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return -1;
  }
  var index = length - 1;
  if (fromIndex !== void 0) {
    index = toInteger_default(fromIndex);
    index = fromIndex < 0 ? nativeMax2(length + index, 0) : nativeMin(index, length - 1);
  }
  return baseFindIndex_default(array, baseIteratee_default(predicate, 3), index, true);
}
var findLastIndex_default = findLastIndex;

// node_modules/lodash-es/groupBy.js
var objectProto13 = Object.prototype;
var hasOwnProperty10 = objectProto13.hasOwnProperty;
var groupBy = createAggregator_default(function(result, value, key) {
  if (hasOwnProperty10.call(result, key)) {
    result[key].push(value);
  } else {
    baseAssignValue_default(result, key, [value]);
  }
});
var groupBy_default = groupBy;

// node_modules/lodash-es/_baseGt.js
function baseGt(value, other) {
  return value > other;
}
var baseGt_default = baseGt;

// node_modules/lodash-es/keyBy.js
var keyBy = createAggregator_default(function(result, value, key) {
  baseAssignValue_default(result, key, value);
});
var keyBy_default = keyBy;

// node_modules/lodash-es/_baseLt.js
function baseLt(value, other) {
  return value < other;
}
var baseLt_default = baseLt;

// node_modules/lodash-es/_baseExtremum.js
function baseExtremum(array, iteratee, comparator) {
  var index = -1, length = array.length;
  while (++index < length) {
    var value = array[index], current = iteratee(value);
    if (current != null && (computed === void 0 ? current === current && !isSymbol_default(current) : comparator(current, computed))) {
      var computed = current, result = value;
    }
  }
  return result;
}
var baseExtremum_default = baseExtremum;

// node_modules/lodash-es/max.js
function max(array) {
  return array && array.length ? baseExtremum_default(array, identity_default, baseGt_default) : void 0;
}
var max_default = max;

// node_modules/lodash-es/_baseSum.js
function baseSum(array, iteratee) {
  var result, index = -1, length = array.length;
  while (++index < length) {
    var current = iteratee(array[index]);
    if (current !== void 0) {
      result = result === void 0 ? current : result + current;
    }
  }
  return result;
}
var baseSum_default = baseSum;

// node_modules/lodash-es/min.js
function min(array) {
  return array && array.length ? baseExtremum_default(array, identity_default, baseLt_default) : void 0;
}
var min_default = min;

// node_modules/lodash-es/minBy.js
function minBy(array, iteratee) {
  return array && array.length ? baseExtremum_default(array, baseIteratee_default(iteratee, 2), baseLt_default) : void 0;
}
var minBy_default = minBy;

// node_modules/lodash-es/partition.js
var partition = createAggregator_default(function(result, value, key) {
  result[key ? 0 : 1].push(value);
}, function() {
  return [[], []];
});
var partition_default = partition;

// node_modules/lodash-es/sum.js
function sum2(array) {
  return array && array.length ? baseSum_default(array, identity_default) : 0;
}
var sum_default = sum2;

// node_modules/lodash-es/_createSet.js
var INFINITY4 = 1 / 0;
var createSet = !(Set_default && 1 / setToArray_default(new Set_default([, -0]))[1] == INFINITY4) ? noop_default : function(values) {
  return new Set_default(values);
};
var createSet_default = createSet;

// node_modules/lodash-es/_baseUniq.js
var LARGE_ARRAY_SIZE2 = 200;
function baseUniq(array, iteratee, comparator) {
  var index = -1, includes = arrayIncludes_default, length = array.length, isCommon = true, result = [], seen = result;
  if (comparator) {
    isCommon = false;
    includes = arrayIncludesWith_default;
  } else if (length >= LARGE_ARRAY_SIZE2) {
    var set = iteratee ? null : createSet_default(array);
    if (set) {
      return setToArray_default(set);
    }
    isCommon = false;
    includes = cacheHas_default;
    seen = new SetCache_default();
  } else {
    seen = iteratee ? [] : result;
  }
  outer:
    while (++index < length) {
      var value = array[index], computed = iteratee ? iteratee(value) : value;
      value = comparator || value !== 0 ? value : 0;
      if (isCommon && computed === computed) {
        var seenIndex = seen.length;
        while (seenIndex--) {
          if (seen[seenIndex] === computed) {
            continue outer;
          }
        }
        if (iteratee) {
          seen.push(computed);
        }
        result.push(value);
      } else if (!includes(seen, computed, comparator)) {
        if (seen !== result) {
          seen.push(computed);
        }
        result.push(value);
      }
    }
  return result;
}
var baseUniq_default = baseUniq;

// node_modules/lodash-es/uniq.js
function uniq(array) {
  return array && array.length ? baseUniq_default(array) : [];
}
var uniq_default = uniq;

// src/util/collection.ts
var compactI2 = (arr) => arr.filter((it) => it !== void 0 && it !== null);
function mapGetWithDefault(map, key, fetchDefault) {
  let v = map.get(key);
  if (v === void 0) {
    v = fetchDefault();
    map.set(key, v);
  }
  return v;
}
function findPair(list, predicate) {
  const index = list.findIndex(predicate);
  if (index === -1) {
    return [void 0, void 0];
  }
  return [index, list[index]];
}
function scanIndexPrev(list, startIndex, wrapscan, condition) {
  if (startIndex > 0) {
    const index = findLastIndex_default(list, condition, startIndex - 1);
    if (index !== -1) {
      return index;
    }
  }
  if (wrapscan && startIndex < list.length - 1) {
    const index = findLastIndex_default(list.slice(startIndex + 1), condition);
    return index === -1 ? void 0 : index + startIndex + 1;
  }
}
function scanIndexNext(list, startIndex, wrapscan, condition) {
  if (startIndex < list.length - 1) {
    const index = findIndex_default(list, condition, startIndex + 1);
    if (index !== -1) {
      return index;
    }
  }
  if (wrapscan && startIndex > 0) {
    const index = findIndex_default(list.slice(0, startIndex), condition);
    return index === -1 ? void 0 : index;
  }
}

// src/util/async.ts
var sleep2 = (ms) => {
  return new Promise((resolve6) => {
    setTimeout(resolve6, ms);
  });
};

// src/util/fs.ts
var import_fs12 = __toESM(require("fs"));
var import_os2 = __toESM(require("os"));
var import_make_dir = __toESM(require_make_dir());
var import_path7 = __toESM(require("path"));
var import_readline = __toESM(require("readline"));

// node_modules/rimraf/dist/mjs/opt-arg.js
var optArgT = (opt) => {
  assertRimrafOptions(opt);
  const { glob: glob2, ...options } = opt;
  if (!glob2) {
    return options;
  }
  const globOpt = glob2 === true ? opt.signal ? { signal: opt.signal } : {} : opt.signal ? {
    signal: opt.signal,
    ...glob2
  } : glob2;
  return {
    ...options,
    glob: {
      ...globOpt,
      // always get absolute paths from glob, to ensure
      // that we are referencing the correct thing.
      absolute: true,
      withFileTypes: false
    }
  };
};
var optArg = (opt = {}) => optArgT(opt);
var optArgSync = (opt = {}) => optArgT(opt);

// node_modules/rimraf/dist/mjs/path-arg.js
var import_path = require("path");
var import_util9 = require("util");

// node_modules/rimraf/dist/mjs/platform.js
var platform_default = process.env.__TESTING_RIMRAF_PLATFORM__ || process.platform;

// node_modules/rimraf/dist/mjs/path-arg.js
var pathArg = (path3, opt = {}) => {
  const type = typeof path3;
  if (type !== "string") {
    const ctor = path3 && type === "object" && path3.constructor;
    const received = ctor && ctor.name ? `an instance of ${ctor.name}` : type === "object" ? (0, import_util9.inspect)(path3) : `type ${type} ${path3}`;
    const msg = `The "path" argument must be of type string. Received ${received}`;
    throw Object.assign(new TypeError(msg), {
      path: path3,
      code: "ERR_INVALID_ARG_TYPE"
    });
  }
  if (/\0/.test(path3)) {
    const msg = "path must be a string without null bytes";
    throw Object.assign(new TypeError(msg), {
      path: path3,
      code: "ERR_INVALID_ARG_VALUE"
    });
  }
  path3 = (0, import_path.resolve)(path3);
  const { root: root2 } = (0, import_path.parse)(path3);
  if (path3 === root2 && opt.preserveRoot !== false) {
    const msg = "refusing to remove root directory without preserveRoot:false";
    throw Object.assign(new Error(msg), {
      path: path3,
      code: "ERR_PRESERVE_ROOT"
    });
  }
  if (platform_default === "win32") {
    const badWinChars = /[*|"<>?:]/;
    const { root: root3 } = (0, import_path.parse)(path3);
    if (badWinChars.test(path3.substring(root3.length))) {
      throw Object.assign(new Error("Illegal characters in path."), {
        path: path3,
        code: "EINVAL"
      });
    }
  }
  return path3;
};
var path_arg_default = pathArg;

// node_modules/rimraf/node_modules/minimatch/dist/mjs/index.js
var import_brace_expansion = __toESM(require_brace_expansion(), 1);

// node_modules/rimraf/node_modules/minimatch/dist/mjs/assert-valid-pattern.js
var MAX_PATTERN_LENGTH = 1024 * 64;
var assertValidPattern = (pattern) => {
  if (typeof pattern !== "string") {
    throw new TypeError("invalid pattern");
  }
  if (pattern.length > MAX_PATTERN_LENGTH) {
    throw new TypeError("pattern is too long");
  }
};

// node_modules/rimraf/node_modules/minimatch/dist/mjs/brace-expressions.js
var posixClasses = {
  "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
  "[:alpha:]": ["\\p{L}\\p{Nl}", true],
  "[:ascii:]": ["\\x00-\\x7f", false],
  "[:blank:]": ["\\p{Zs}\\t", true],
  "[:cntrl:]": ["\\p{Cc}", true],
  "[:digit:]": ["\\p{Nd}", true],
  "[:graph:]": ["\\p{Z}\\p{C}", true, true],
  "[:lower:]": ["\\p{Ll}", true],
  "[:print:]": ["\\p{C}", true],
  "[:punct:]": ["\\p{P}", true],
  "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
  "[:upper:]": ["\\p{Lu}", true],
  "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
  "[:xdigit:]": ["A-Fa-f0-9", false]
};
var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var rangesToString = (ranges) => ranges.join("");
var parseClass = (glob2, position) => {
  const pos = position;
  if (glob2.charAt(pos) !== "[") {
    throw new Error("not in a brace expression");
  }
  const ranges = [];
  const negs = [];
  let i = pos + 1;
  let sawStart = false;
  let uflag = false;
  let escaping = false;
  let negate = false;
  let endPos = pos;
  let rangeStart = "";
  WHILE:
    while (i < glob2.length) {
      const c = glob2.charAt(i);
      if ((c === "!" || c === "^") && i === pos + 1) {
        negate = true;
        i++;
        continue;
      }
      if (c === "]" && sawStart && !escaping) {
        endPos = i + 1;
        break;
      }
      sawStart = true;
      if (c === "\\") {
        if (!escaping) {
          escaping = true;
          i++;
          continue;
        }
      }
      if (c === "[" && !escaping) {
        for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
          if (glob2.startsWith(cls, i)) {
            if (rangeStart) {
              return ["$.", false, glob2.length - pos, true];
            }
            i += cls.length;
            if (neg)
              negs.push(unip);
            else
              ranges.push(unip);
            uflag = uflag || u;
            continue WHILE;
          }
        }
      }
      escaping = false;
      if (rangeStart) {
        if (c > rangeStart) {
          ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
        } else if (c === rangeStart) {
          ranges.push(braceEscape(c));
        }
        rangeStart = "";
        i++;
        continue;
      }
      if (glob2.startsWith("-]", i + 1)) {
        ranges.push(braceEscape(c + "-"));
        i += 2;
        continue;
      }
      if (glob2.startsWith("-", i + 1)) {
        rangeStart = c;
        i += 2;
        continue;
      }
      ranges.push(braceEscape(c));
      i++;
    }
  if (endPos < i) {
    return ["", false, 0, false];
  }
  if (!ranges.length && !negs.length) {
    return ["$.", false, glob2.length - pos, true];
  }
  if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
    const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
    return [regexpEscape(r), false, endPos - pos, false];
  }
  const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
  const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
  const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
  return [comb, uflag, endPos - pos, true];
};

// node_modules/rimraf/node_modules/minimatch/dist/mjs/unescape.js
var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
  return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
};

// node_modules/rimraf/node_modules/minimatch/dist/mjs/ast.js
var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
var isExtglobType = (c) => types.has(c);
var startNoTraversal = "(?!\\.\\.?(?:$|/))";
var startNoDot = "(?!\\.)";
var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
var justDots = /* @__PURE__ */ new Set(["..", "."]);
var reSpecials = new Set("().*{}+?[]^$\\!");
var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var qmark = "[^/]";
var star = qmark + "*?";
var starNoEmpty = qmark + "+?";
var AST = class _AST {
  type;
  #root;
  #hasMagic;
  #uflag = false;
  #parts = [];
  #parent;
  #parentIndex;
  #negs;
  #filledNegs = false;
  #options;
  #toString;
  // set to true if it's an extglob with no children
  // (which really means one child of '')
  #emptyExt = false;
  constructor(type, parent, options = {}) {
    this.type = type;
    if (type)
      this.#hasMagic = true;
    this.#parent = parent;
    this.#root = this.#parent ? this.#parent.#root : this;
    this.#options = this.#root === this ? options : this.#root.#options;
    this.#negs = this.#root === this ? [] : this.#root.#negs;
    if (type === "!" && !this.#root.#filledNegs)
      this.#negs.push(this);
    this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  }
  get hasMagic() {
    if (this.#hasMagic !== void 0)
      return this.#hasMagic;
    for (const p of this.#parts) {
      if (typeof p === "string")
        continue;
      if (p.type || p.hasMagic)
        return this.#hasMagic = true;
    }
    return this.#hasMagic;
  }
  // reconstructs the pattern
  toString() {
    if (this.#toString !== void 0)
      return this.#toString;
    if (!this.type) {
      return this.#toString = this.#parts.map((p) => String(p)).join("");
    } else {
      return this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";
    }
  }
  #fillNegs() {
    if (this !== this.#root)
      throw new Error("should only call on root");
    if (this.#filledNegs)
      return this;
    this.toString();
    this.#filledNegs = true;
    let n;
    while (n = this.#negs.pop()) {
      if (n.type !== "!")
        continue;
      let p = n;
      let pp = p.#parent;
      while (pp) {
        for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
          for (const part of n.#parts) {
            if (typeof part === "string") {
              throw new Error("string part in extglob AST??");
            }
            part.copyIn(pp.#parts[i]);
          }
        }
        p = pp;
        pp = p.#parent;
      }
    }
    return this;
  }
  push(...parts) {
    for (const p of parts) {
      if (p === "")
        continue;
      if (typeof p !== "string" && !(p instanceof _AST && p.#parent === this)) {
        throw new Error("invalid part: " + p);
      }
      this.#parts.push(p);
    }
  }
  toJSON() {
    var _a2;
    const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];
    if (this.isStart() && !this.type)
      ret.unshift([]);
    if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && ((_a2 = this.#parent) == null ? void 0 : _a2.type) === "!")) {
      ret.push({});
    }
    return ret;
  }
  isStart() {
    var _a2;
    if (this.#root === this)
      return true;
    if (!((_a2 = this.#parent) == null ? void 0 : _a2.isStart()))
      return false;
    if (this.#parentIndex === 0)
      return true;
    const p = this.#parent;
    for (let i = 0; i < this.#parentIndex; i++) {
      const pp = p.#parts[i];
      if (!(pp instanceof _AST && pp.type === "!")) {
        return false;
      }
    }
    return true;
  }
  isEnd() {
    var _a2, _b, _c;
    if (this.#root === this)
      return true;
    if (((_a2 = this.#parent) == null ? void 0 : _a2.type) === "!")
      return true;
    if (!((_b = this.#parent) == null ? void 0 : _b.isEnd()))
      return false;
    if (!this.type)
      return (_c = this.#parent) == null ? void 0 : _c.isEnd();
    const pl = this.#parent ? this.#parent.#parts.length : 0;
    return this.#parentIndex === pl - 1;
  }
  copyIn(part) {
    if (typeof part === "string")
      this.push(part);
    else
      this.push(part.clone(this));
  }
  clone(parent) {
    const c = new _AST(this.type, parent);
    for (const p of this.#parts) {
      c.copyIn(p);
    }
    return c;
  }
  static #parseAST(str, ast, pos, opt) {
    let escaping = false;
    let inBrace = false;
    let braceStart = -1;
    let braceNeg = false;
    if (ast.type === null) {
      let i2 = pos;
      let acc2 = "";
      while (i2 < str.length) {
        const c = str.charAt(i2++);
        if (escaping || c === "\\") {
          escaping = !escaping;
          acc2 += c;
          continue;
        }
        if (inBrace) {
          if (i2 === braceStart + 1) {
            if (c === "^" || c === "!") {
              braceNeg = true;
            }
          } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {
            inBrace = false;
          }
          acc2 += c;
          continue;
        } else if (c === "[") {
          inBrace = true;
          braceStart = i2;
          braceNeg = false;
          acc2 += c;
          continue;
        }
        if (!opt.noext && isExtglobType(c) && str.charAt(i2) === "(") {
          ast.push(acc2);
          acc2 = "";
          const ext2 = new _AST(c, ast);
          i2 = _AST.#parseAST(str, ext2, i2, opt);
          ast.push(ext2);
          continue;
        }
        acc2 += c;
      }
      ast.push(acc2);
      return i2;
    }
    let i = pos + 1;
    let part = new _AST(null, ast);
    const parts = [];
    let acc = "";
    while (i < str.length) {
      const c = str.charAt(i++);
      if (escaping || c === "\\") {
        escaping = !escaping;
        acc += c;
        continue;
      }
      if (inBrace) {
        if (i === braceStart + 1) {
          if (c === "^" || c === "!") {
            braceNeg = true;
          }
        } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {
          inBrace = false;
        }
        acc += c;
        continue;
      } else if (c === "[") {
        inBrace = true;
        braceStart = i;
        braceNeg = false;
        acc += c;
        continue;
      }
      if (isExtglobType(c) && str.charAt(i) === "(") {
        part.push(acc);
        acc = "";
        const ext2 = new _AST(c, part);
        part.push(ext2);
        i = _AST.#parseAST(str, ext2, i, opt);
        continue;
      }
      if (c === "|") {
        part.push(acc);
        acc = "";
        parts.push(part);
        part = new _AST(null, ast);
        continue;
      }
      if (c === ")") {
        if (acc === "" && ast.#parts.length === 0) {
          ast.#emptyExt = true;
        }
        part.push(acc);
        acc = "";
        ast.push(...parts, part);
        return i;
      }
      acc += c;
    }
    ast.type = null;
    ast.#hasMagic = void 0;
    ast.#parts = [str.substring(pos - 1)];
    return i;
  }
  static fromGlob(pattern, options = {}) {
    const ast = new _AST(null, void 0, options);
    _AST.#parseAST(pattern, ast, 0, options);
    return ast;
  }
  // returns the regular expression if there's magic, or the unescaped
  // string if not.
  toMMPattern() {
    if (this !== this.#root)
      return this.#root.toMMPattern();
    const glob2 = this.toString();
    const [re, body, hasMagic2, uflag] = this.toRegExpSource();
    const anyMagic = hasMagic2 || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob2.toUpperCase() !== glob2.toLowerCase();
    if (!anyMagic) {
      return body;
    }
    const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
    return Object.assign(new RegExp(`^${re}$`, flags), {
      _src: re,
      _glob: glob2
    });
  }
  // returns the string match, the regexp source, whether there's magic
  // in the regexp (so a regular expression is required) and whether or
  // not the uflag is needed for the regular expression (for posix classes)
  // TODO: instead of injecting the start/end at this point, just return
  // the BODY of the regexp, along with the start/end portions suitable
  // for binding the start/end in either a joined full-path makeRe context
  // (where we bind to (^|/), or a standalone matchPart context (where
  // we bind to ^, and not /).  Otherwise slashes get duped!
  //
  // In part-matching mode, the start is:
  // - if not isStart: nothing
  // - if traversal possible, but not allowed: ^(?!\.\.?$)
  // - if dots allowed or not possible: ^
  // - if dots possible and not allowed: ^(?!\.)
  // end is:
  // - if not isEnd(): nothing
  // - else: $
  //
  // In full-path matching mode, we put the slash at the START of the
  // pattern, so start is:
  // - if first pattern: same as part-matching mode
  // - if not isStart(): nothing
  // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  // - if dots allowed or not possible: /
  // - if dots possible and not allowed: /(?!\.)
  // end is:
  // - if last pattern, same as part-matching mode
  // - else nothing
  //
  // Always put the (?:$|/) on negated tails, though, because that has to be
  // there to bind the end of the negated pattern portion, and it's easier to
  // just stick it in now rather than try to inject it later in the middle of
  // the pattern.
  //
  // We can just always return the same end, and leave it up to the caller
  // to know whether it's going to be used joined or in parts.
  // And, if the start is adjusted slightly, can do the same there:
  // - if not isStart: nothing
  // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  // - if dots allowed or not possible: (?:/|^)
  // - if dots possible and not allowed: (?:/|^)(?!\.)
  //
  // But it's better to have a simpler binding without a conditional, for
  // performance, so probably better to return both start options.
  //
  // Then the caller just ignores the end if it's not the first pattern,
  // and the start always gets applied.
  //
  // But that's always going to be $ if it's the ending pattern, or nothing,
  // so the caller can just attach $ at the end of the pattern when building.
  //
  // So the todo is:
  // - better detect what kind of start is needed
  // - return both flavors of starting pattern
  // - attach $ at the end of the pattern when creating the actual RegExp
  //
  // Ah, but wait, no, that all only applies to the root when the first pattern
  // is not an extglob. If the first pattern IS an extglob, then we need all
  // that dot prevention biz to live in the extglob portions, because eg
  // +(*|.x*) can match .xy but not .yx.
  //
  // So, return the two flavors if it's #root and the first child is not an
  // AST, otherwise leave it to the child AST to handle it, and there,
  // use the (?:^|/) style of start binding.
  //
  // Even simplified further:
  // - Since the start for a join is eg /(?!\.) and the start for a part
  // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  // or start or whatever) and prepend ^ or / at the Regexp construction.
  toRegExpSource() {
    var _a2;
    if (this.#root === this)
      this.#fillNegs();
    if (!this.type) {
      const noEmpty = this.isStart() && this.isEnd();
      const src = this.#parts.map((p) => {
        const [re, _, hasMagic2, uflag] = typeof p === "string" ? _AST.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource();
        this.#hasMagic = this.#hasMagic || hasMagic2;
        this.#uflag = this.#uflag || uflag;
        return re;
      }).join("");
      let start2 = "";
      if (this.isStart()) {
        if (typeof this.#parts[0] === "string") {
          const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
          if (!dotTravAllowed) {
            const aps = addPatternStart;
            const needNoTrav = (
              // dots are allowed, and the pattern starts with [ or .
              this.#options.dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or .
              src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or .
              src.startsWith("\\.\\.") && aps.has(src.charAt(4))
            );
            const needNoDot = !this.#options.dot && aps.has(src.charAt(0));
            start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
          }
        }
      }
      let end = "";
      if (this.isEnd() && this.#root.#filledNegs && ((_a2 = this.#parent) == null ? void 0 : _a2.type) === "!") {
        end = "(?:$|\\/)";
      }
      const final2 = start2 + src + end;
      return [
        final2,
        unescape(src),
        this.#hasMagic = !!this.#hasMagic,
        this.#uflag
      ];
    }
    const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
    const body = this.#parts.map((p) => {
      if (typeof p === "string") {
        throw new Error("string type in extglob ast??");
      }
      const [re, _, _hasMagic, uflag] = p.toRegExpSource();
      this.#uflag = this.#uflag || uflag;
      return re;
    }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
    if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
      const s = this.toString();
      this.#parts = [s];
      this.type = null;
      this.#hasMagic = void 0;
      return [s, unescape(this.toString()), false, false];
    }
    let final = "";
    if (this.type === "!" && this.#emptyExt) {
      final = (this.isStart() && !this.#options.dot ? startNoDot : "") + starNoEmpty;
    } else {
      const close = this.type === "!" ? (
        // !() must match something,but !(x) can match ''
        "))" + (this.isStart() && !this.#options.dot ? startNoDot : "") + star + ")"
      ) : this.type === "@" ? ")" : `)${this.type}`;
      final = start + body + close;
    }
    return [
      final,
      unescape(body),
      this.#hasMagic = !!this.#hasMagic,
      this.#uflag
    ];
  }
  static #parseGlob(glob2, hasMagic2, noEmpty = false) {
    let escaping = false;
    let re = "";
    let uflag = false;
    for (let i = 0; i < glob2.length; i++) {
      const c = glob2.charAt(i);
      if (escaping) {
        escaping = false;
        re += (reSpecials.has(c) ? "\\" : "") + c;
        continue;
      }
      if (c === "\\") {
        if (i === glob2.length - 1) {
          re += "\\\\";
        } else {
          escaping = true;
        }
        continue;
      }
      if (c === "[") {
        const [src, needUflag, consumed, magic] = parseClass(glob2, i);
        if (consumed) {
          re += src;
          uflag = uflag || needUflag;
          i += consumed - 1;
          hasMagic2 = hasMagic2 || magic;
          continue;
        }
      }
      if (c === "*") {
        if (noEmpty && glob2 === "*")
          re += starNoEmpty;
        else
          re += star;
        hasMagic2 = true;
        continue;
      }
      if (c === "?") {
        re += qmark;
        hasMagic2 = true;
        continue;
      }
      re += regExpEscape(c);
    }
    return [re, unescape(glob2), !!hasMagic2, uflag];
  }
};

// node_modules/rimraf/node_modules/minimatch/dist/mjs/escape.js
var escape = (s, { windowsPathsNoEscape = false } = {}) => {
  return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
};

// node_modules/rimraf/node_modules/minimatch/dist/mjs/index.js
var minimatch = (p, pattern, options = {}) => {
  assertValidPattern(pattern);
  if (!options.nocomment && pattern.charAt(0) === "#") {
    return false;
  }
  return new Minimatch(pattern, options).match(p);
};
var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
var starDotExtTestNocase = (ext2) => {
  ext2 = ext2.toLowerCase();
  return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
};
var starDotExtTestNocaseDot = (ext2) => {
  ext2 = ext2.toLowerCase();
  return (f) => f.toLowerCase().endsWith(ext2);
};
var starDotStarRE = /^\*+\.\*+$/;
var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
var dotStarRE = /^\.\*+$/;
var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
var starRE = /^\*+$/;
var starTest = (f) => f.length !== 0 && !f.startsWith(".");
var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
var qmarksTestNocase = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExt([$0]);
  if (!ext2)
    return noext;
  ext2 = ext2.toLowerCase();
  return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
};
var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExtDot([$0]);
  if (!ext2)
    return noext;
  ext2 = ext2.toLowerCase();
  return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
};
var qmarksTestDot = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExtDot([$0]);
  return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
};
var qmarksTest = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExt([$0]);
  return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
};
var qmarksTestNoExt = ([$0]) => {
  const len = $0.length;
  return (f) => f.length === len && !f.startsWith(".");
};
var qmarksTestNoExtDot = ([$0]) => {
  const len = $0.length;
  return (f) => f.length === len && f !== "." && f !== "..";
};
var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
var path = {
  win32: { sep: "\\" },
  posix: { sep: "/" }
};
var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
minimatch.sep = sep;
var GLOBSTAR = Symbol("globstar **");
minimatch.GLOBSTAR = GLOBSTAR;
var qmark2 = "[^/]";
var star2 = qmark2 + "*?";
var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
minimatch.filter = filter;
var ext = (a, b = {}) => Object.assign({}, a, b);
var defaults = (def) => {
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
    return minimatch;
  }
  const orig = minimatch;
  const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  return Object.assign(m, {
    Minimatch: class Minimatch extends orig.Minimatch {
      constructor(pattern, options = {}) {
        super(pattern, ext(def, options));
      }
      static defaults(options) {
        return orig.defaults(ext(def, options)).Minimatch;
      }
    },
    AST: class AST extends orig.AST {
      /* c8 ignore start */
      constructor(type, parent, options = {}) {
        super(type, parent, ext(def, options));
      }
      /* c8 ignore stop */
      static fromGlob(pattern, options = {}) {
        return orig.AST.fromGlob(pattern, ext(def, options));
      }
    },
    unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
    escape: (s, options = {}) => orig.escape(s, ext(def, options)),
    filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
    defaults: (options) => orig.defaults(ext(def, options)),
    makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
    braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
    match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
    sep: orig.sep,
    GLOBSTAR
  });
};
minimatch.defaults = defaults;
var braceExpand = (pattern, options = {}) => {
  assertValidPattern(pattern);
  if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
    return [pattern];
  }
  return (0, import_brace_expansion.default)(pattern);
};
minimatch.braceExpand = braceExpand;
var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
minimatch.makeRe = makeRe;
var match = (list, pattern, options = {}) => {
  const mm = new Minimatch(pattern, options);
  list = list.filter((f) => mm.match(f));
  if (mm.options.nonull && !list.length) {
    list.push(pattern);
  }
  return list;
};
minimatch.match = match;
var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
var regExpEscape2 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var Minimatch = class {
  options;
  set;
  pattern;
  windowsPathsNoEscape;
  nonegate;
  negate;
  comment;
  empty;
  preserveMultipleSlashes;
  partial;
  globSet;
  globParts;
  nocase;
  isWindows;
  platform;
  windowsNoMagicRoot;
  regexp;
  constructor(pattern, options = {}) {
    assertValidPattern(pattern);
    options = options || {};
    this.options = options;
    this.pattern = pattern;
    this.platform = options.platform || defaultPlatform;
    this.isWindows = this.platform === "win32";
    this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
    if (this.windowsPathsNoEscape) {
      this.pattern = this.pattern.replace(/\\/g, "/");
    }
    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
    this.regexp = null;
    this.negate = false;
    this.nonegate = !!options.nonegate;
    this.comment = false;
    this.empty = false;
    this.partial = !!options.partial;
    this.nocase = !!this.options.nocase;
    this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
    this.globSet = [];
    this.globParts = [];
    this.set = [];
    this.make();
  }
  hasMagic() {
    if (this.options.magicalBraces && this.set.length > 1) {
      return true;
    }
    for (const pattern of this.set) {
      for (const part of pattern) {
        if (typeof part !== "string")
          return true;
      }
    }
    return false;
  }
  debug(..._) {
  }
  make() {
    const pattern = this.pattern;
    const options = this.options;
    if (!options.nocomment && pattern.charAt(0) === "#") {
      this.comment = true;
      return;
    }
    if (!pattern) {
      this.empty = true;
      return;
    }
    this.parseNegate();
    this.globSet = [...new Set(this.braceExpand())];
    if (options.debug) {
      this.debug = (...args) => console.error(...args);
    }
    this.debug(this.pattern, this.globSet);
    const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
    this.globParts = this.preprocess(rawGlobParts);
    this.debug(this.pattern, this.globParts);
    let set = this.globParts.map((s, _, __) => {
      if (this.isWindows && this.windowsNoMagicRoot) {
        const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
        const isDrive = /^[a-z]:/i.test(s[0]);
        if (isUNC) {
          return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
        } else if (isDrive) {
          return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
        }
      }
      return s.map((ss) => this.parse(ss));
    });
    this.debug(this.pattern, set);
    this.set = set.filter((s) => s.indexOf(false) === -1);
    if (this.isWindows) {
      for (let i = 0; i < this.set.length; i++) {
        const p = this.set[i];
        if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
          p[2] = "?";
        }
      }
    }
    this.debug(this.pattern, this.set);
  }
  // various transforms to equivalent pattern sets that are
  // faster to process in a filesystem walk.  The goal is to
  // eliminate what we can, and push all ** patterns as far
  // to the right as possible, even if it increases the number
  // of patterns that we have to process.
  preprocess(globParts) {
    if (this.options.noglobstar) {
      for (let i = 0; i < globParts.length; i++) {
        for (let j = 0; j < globParts[i].length; j++) {
          if (globParts[i][j] === "**") {
            globParts[i][j] = "*";
          }
        }
      }
    }
    const { optimizationLevel = 1 } = this.options;
    if (optimizationLevel >= 2) {
      globParts = this.firstPhasePreProcess(globParts);
      globParts = this.secondPhasePreProcess(globParts);
    } else if (optimizationLevel >= 1) {
      globParts = this.levelOneOptimize(globParts);
    } else {
      globParts = this.adjascentGlobstarOptimize(globParts);
    }
    return globParts;
  }
  // just get rid of adjascent ** portions
  adjascentGlobstarOptimize(globParts) {
    return globParts.map((parts) => {
      let gs = -1;
      while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
        let i = gs;
        while (parts[i + 1] === "**") {
          i++;
        }
        if (i !== gs) {
          parts.splice(gs, i - gs);
        }
      }
      return parts;
    });
  }
  // get rid of adjascent ** and resolve .. portions
  levelOneOptimize(globParts) {
    return globParts.map((parts) => {
      parts = parts.reduce((set, part) => {
        const prev = set[set.length - 1];
        if (part === "**" && prev === "**") {
          return set;
        }
        if (part === "..") {
          if (prev && prev !== ".." && prev !== "." && prev !== "**") {
            set.pop();
            return set;
          }
        }
        set.push(part);
        return set;
      }, []);
      return parts.length === 0 ? [""] : parts;
    });
  }
  levelTwoFileOptimize(parts) {
    if (!Array.isArray(parts)) {
      parts = this.slashSplit(parts);
    }
    let didSomething = false;
    do {
      didSomething = false;
      if (!this.preserveMultipleSlashes) {
        for (let i = 1; i < parts.length - 1; i++) {
          const p = parts[i];
          if (i === 1 && p === "" && parts[0] === "")
            continue;
          if (p === "." || p === "") {
            didSomething = true;
            parts.splice(i, 1);
            i--;
          }
        }
        if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
          didSomething = true;
          parts.pop();
        }
      }
      let dd = 0;
      while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
        const p = parts[dd - 1];
        if (p && p !== "." && p !== ".." && p !== "**") {
          didSomething = true;
          parts.splice(dd - 1, 2);
          dd -= 2;
        }
      }
    } while (didSomething);
    return parts.length === 0 ? [""] : parts;
  }
  // First phase: single-pattern processing
  // <pre> is 1 or more portions
  // <rest> is 1 or more portions
  // <p> is any portion other than ., .., '', or **
  // <e> is . or ''
  //
  // **/.. is *brutal* for filesystem walking performance, because
  // it effectively resets the recursive walk each time it occurs,
  // and ** cannot be reduced out by a .. pattern part like a regexp
  // or most strings (other than .., ., and '') can be.
  //
  // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  // <pre>/<e>/<rest> -> <pre>/<rest>
  // <pre>/<p>/../<rest> -> <pre>/<rest>
  // **/**/<rest> -> **/<rest>
  //
  // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  // this WOULD be allowed if ** did follow symlinks, or * didn't
  firstPhasePreProcess(globParts) {
    let didSomething = false;
    do {
      didSomething = false;
      for (let parts of globParts) {
        let gs = -1;
        while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
          let gss = gs;
          while (parts[gss + 1] === "**") {
            gss++;
          }
          if (gss > gs) {
            parts.splice(gs + 1, gss - gs);
          }
          let next = parts[gs + 1];
          const p = parts[gs + 2];
          const p2 = parts[gs + 3];
          if (next !== "..")
            continue;
          if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
            continue;
          }
          didSomething = true;
          parts.splice(gs, 1);
          const other = parts.slice(0);
          other[gs] = "**";
          globParts.push(other);
          gs--;
        }
        if (!this.preserveMultipleSlashes) {
          for (let i = 1; i < parts.length - 1; i++) {
            const p = parts[i];
            if (i === 1 && p === "" && parts[0] === "")
              continue;
            if (p === "." || p === "") {
              didSomething = true;
              parts.splice(i, 1);
              i--;
            }
          }
          if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
            didSomething = true;
            parts.pop();
          }
        }
        let dd = 0;
        while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
          const p = parts[dd - 1];
          if (p && p !== "." && p !== ".." && p !== "**") {
            didSomething = true;
            const needDot = dd === 1 && parts[dd + 1] === "**";
            const splin = needDot ? ["."] : [];
            parts.splice(dd - 1, 2, ...splin);
            if (parts.length === 0)
              parts.push("");
            dd -= 2;
          }
        }
      }
    } while (didSomething);
    return globParts;
  }
  // second phase: multi-pattern dedupes
  // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  //
  // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  // ^-- not valid because ** doens't follow symlinks
  secondPhasePreProcess(globParts) {
    for (let i = 0; i < globParts.length - 1; i++) {
      for (let j = i + 1; j < globParts.length; j++) {
        const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
        if (!matched)
          continue;
        globParts[i] = matched;
        globParts[j] = [];
      }
    }
    return globParts.filter((gs) => gs.length);
  }
  partsMatch(a, b, emptyGSMatch = false) {
    let ai = 0;
    let bi = 0;
    let result = [];
    let which2 = "";
    while (ai < a.length && bi < b.length) {
      if (a[ai] === b[bi]) {
        result.push(which2 === "b" ? b[bi] : a[ai]);
        ai++;
        bi++;
      } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
        result.push(a[ai]);
        ai++;
      } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
        result.push(b[bi]);
        bi++;
      } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
        if (which2 === "b")
          return false;
        which2 = "a";
        result.push(a[ai]);
        ai++;
        bi++;
      } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
        if (which2 === "a")
          return false;
        which2 = "b";
        result.push(b[bi]);
        ai++;
        bi++;
      } else {
        return false;
      }
    }
    return a.length === b.length && result;
  }
  parseNegate() {
    if (this.nonegate)
      return;
    const pattern = this.pattern;
    let negate = false;
    let negateOffset = 0;
    for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
      negate = !negate;
      negateOffset++;
    }
    if (negateOffset)
      this.pattern = pattern.slice(negateOffset);
    this.negate = negate;
  }
  // set partial to true to test if, for example,
  // "/a/b" matches the start of "/*/b/*/d"
  // Partial means, if you run out of file before you run
  // out of pattern, then that's fine, as long as all
  // the parts match.
  matchOne(file, pattern, partial = false) {
    const options = this.options;
    if (this.isWindows) {
      const fileUNC = file[0] === "" && file[1] === "" && file[2] === "?" && typeof file[3] === "string" && /^[a-z]:$/i.test(file[3]);
      const patternUNC = pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
      if (fileUNC && patternUNC) {
        const fd = file[3];
        const pd = pattern[3];
        if (fd.toLowerCase() === pd.toLowerCase()) {
          file[3] = pd;
        }
      } else if (patternUNC && typeof file[0] === "string") {
        const pd = pattern[3];
        const fd = file[0];
        if (pd.toLowerCase() === fd.toLowerCase()) {
          pattern[3] = fd;
          pattern = pattern.slice(3);
        }
      } else if (fileUNC && typeof pattern[0] === "string") {
        const fd = file[3];
        if (fd.toLowerCase() === pattern[0].toLowerCase()) {
          pattern[0] = fd;
          file = file.slice(3);
        }
      }
    }
    const { optimizationLevel = 1 } = this.options;
    if (optimizationLevel >= 2) {
      file = this.levelTwoFileOptimize(file);
    }
    this.debug("matchOne", this, { file, pattern });
    this.debug("matchOne", file.length, pattern.length);
    for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
      this.debug("matchOne loop");
      var p = pattern[pi];
      var f = file[fi];
      this.debug(pattern, p, f);
      if (p === false) {
        return false;
      }
      if (p === GLOBSTAR) {
        this.debug("GLOBSTAR", [pattern, p, f]);
        var fr = fi;
        var pr = pi + 1;
        if (pr === pl) {
          this.debug("** at the end");
          for (; fi < fl; fi++) {
            if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
              return false;
          }
          return true;
        }
        while (fr < fl) {
          var swallowee = file[fr];
          this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
            this.debug("globstar found match!", fr, fl, swallowee);
            return true;
          } else {
            if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
              this.debug("dot detected!", file, fr, pattern, pr);
              break;
            }
            this.debug("globstar swallow a segment, and continue");
            fr++;
          }
        }
        if (partial) {
          this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
          if (fr === fl) {
            return true;
          }
        }
        return false;
      }
      let hit;
      if (typeof p === "string") {
        hit = f === p;
        this.debug("string match", p, f, hit);
      } else {
        hit = p.test(f);
        this.debug("pattern match", p, f, hit);
      }
      if (!hit)
        return false;
    }
    if (fi === fl && pi === pl) {
      return true;
    } else if (fi === fl) {
      return partial;
    } else if (pi === pl) {
      return fi === fl - 1 && file[fi] === "";
    } else {
      throw new Error("wtf?");
    }
  }
  braceExpand() {
    return braceExpand(this.pattern, this.options);
  }
  parse(pattern) {
    assertValidPattern(pattern);
    const options = this.options;
    if (pattern === "**")
      return GLOBSTAR;
    if (pattern === "")
      return "";
    let m;
    let fastTest = null;
    if (m = pattern.match(starRE)) {
      fastTest = options.dot ? starTestDot : starTest;
    } else if (m = pattern.match(starDotExtRE)) {
      fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
    } else if (m = pattern.match(qmarksRE)) {
      fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
    } else if (m = pattern.match(starDotStarRE)) {
      fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
    } else if (m = pattern.match(dotStarRE)) {
      fastTest = dotStarTest;
    }
    const re = AST.fromGlob(pattern, this.options).toMMPattern();
    return fastTest ? Object.assign(re, { test: fastTest }) : re;
  }
  makeRe() {
    if (this.regexp || this.regexp === false)
      return this.regexp;
    const set = this.set;
    if (!set.length) {
      this.regexp = false;
      return this.regexp;
    }
    const options = this.options;
    const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;
    const flags = new Set(options.nocase ? ["i"] : []);
    let re = set.map((pattern) => {
      const pp = pattern.map((p) => {
        if (p instanceof RegExp) {
          for (const f of p.flags.split(""))
            flags.add(f);
        }
        return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;
      });
      pp.forEach((p, i) => {
        const next = pp[i + 1];
        const prev = pp[i - 1];
        if (p !== GLOBSTAR || prev === GLOBSTAR) {
          return;
        }
        if (prev === void 0) {
          if (next !== void 0 && next !== GLOBSTAR) {
            pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
          } else {
            pp[i] = twoStar;
          }
        } else if (next === void 0) {
          pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
        } else if (next !== GLOBSTAR) {
          pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
          pp[i + 1] = GLOBSTAR;
        }
      });
      return pp.filter((p) => p !== GLOBSTAR).join("/");
    }).join("|");
    const [open2, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
    re = "^" + open2 + re + close + "$";
    if (this.negate)
      re = "^(?!" + re + ").+$";
    try {
      this.regexp = new RegExp(re, [...flags].join(""));
    } catch (ex) {
      this.regexp = false;
    }
    return this.regexp;
  }
  slashSplit(p) {
    if (this.preserveMultipleSlashes) {
      return p.split("/");
    } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
      return ["", ...p.split(/\/+/)];
    } else {
      return p.split(/\/+/);
    }
  }
  match(f, partial = this.partial) {
    this.debug("match", f, this.pattern);
    if (this.comment) {
      return false;
    }
    if (this.empty) {
      return f === "";
    }
    if (f === "/" && partial) {
      return true;
    }
    const options = this.options;
    if (this.isWindows) {
      f = f.split("\\").join("/");
    }
    const ff = this.slashSplit(f);
    this.debug(this.pattern, "split", ff);
    const set = this.set;
    this.debug(this.pattern, "set", set);
    let filename = ff[ff.length - 1];
    if (!filename) {
      for (let i = ff.length - 2; !filename && i >= 0; i--) {
        filename = ff[i];
      }
    }
    for (let i = 0; i < set.length; i++) {
      const pattern = set[i];
      let file = ff;
      if (options.matchBase && pattern.length === 1) {
        file = [filename];
      }
      const hit = this.matchOne(file, pattern, partial);
      if (hit) {
        if (options.flipNegate) {
          return true;
        }
        return !this.negate;
      }
    }
    if (options.flipNegate) {
      return false;
    }
    return this.negate;
  }
  static defaults(def) {
    return minimatch.defaults(def).Minimatch;
  }
};
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape;
minimatch.unescape = unescape;

// node_modules/lru-cache/dist/esm/index.js
var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
var warned = /* @__PURE__ */ new Set();
var PROCESS = typeof process === "object" && !!process ? process : {};
var emitWarning = (msg, type, code, fn) => {
  typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
};
var AC = globalThis.AbortController;
var AS = globalThis.AbortSignal;
var _a;
if (typeof AC === "undefined") {
  AS = class AbortSignal {
    onabort;
    _onabort = [];
    reason;
    aborted = false;
    addEventListener(_, fn) {
      this._onabort.push(fn);
    }
  };
  AC = class AbortController {
    constructor() {
      warnACPolyfill();
    }
    signal = new AS();
    abort(reason) {
      var _a2, _b;
      if (this.signal.aborted)
        return;
      this.signal.reason = reason;
      this.signal.aborted = true;
      for (const fn of this.signal._onabort) {
        fn(reason);
      }
      (_b = (_a2 = this.signal).onabort) == null ? void 0 : _b.call(_a2, reason);
    }
  };
  let printACPolyfillWarning = ((_a = PROCESS.env) == null ? void 0 : _a.LRU_CACHE_IGNORE_AC_WARNING) !== "1";
  const warnACPolyfill = () => {
    if (!printACPolyfillWarning)
      return;
    printACPolyfillWarning = false;
    emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
  };
}
var shouldWarn = (code) => !warned.has(code);
var TYPE = Symbol("type");
var isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
var getUintArray = (max2) => !isPosInt(max2) ? null : max2 <= Math.pow(2, 8) ? Uint8Array : max2 <= Math.pow(2, 16) ? Uint16Array : max2 <= Math.pow(2, 32) ? Uint32Array : max2 <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
var ZeroArray = class extends Array {
  constructor(size) {
    super(size);
    this.fill(0);
  }
};
var Stack2 = class _Stack {
  heap;
  length;
  // private constructor
  static #constructing = false;
  static create(max2) {
    const HeapCls = getUintArray(max2);
    if (!HeapCls)
      return [];
    _Stack.#constructing = true;
    const s = new _Stack(max2, HeapCls);
    _Stack.#constructing = false;
    return s;
  }
  constructor(max2, HeapCls) {
    if (!_Stack.#constructing) {
      throw new TypeError("instantiate Stack using Stack.create(n)");
    }
    this.heap = new HeapCls(max2);
    this.length = 0;
  }
  push(n) {
    this.heap[this.length++] = n;
  }
  pop() {
    return this.heap[--this.length];
  }
};
var LRUCache = class _LRUCache {
  // properties coming in from the options of these, only max and maxSize
  // really *need* to be protected. The rest can be modified, as they just
  // set defaults for various methods.
  #max;
  #maxSize;
  #dispose;
  #disposeAfter;
  #fetchMethod;
  /**
   * {@link LRUCache.OptionsBase.ttl}
   */
  ttl;
  /**
   * {@link LRUCache.OptionsBase.ttlResolution}
   */
  ttlResolution;
  /**
   * {@link LRUCache.OptionsBase.ttlAutopurge}
   */
  ttlAutopurge;
  /**
   * {@link LRUCache.OptionsBase.updateAgeOnGet}
   */
  updateAgeOnGet;
  /**
   * {@link LRUCache.OptionsBase.updateAgeOnHas}
   */
  updateAgeOnHas;
  /**
   * {@link LRUCache.OptionsBase.allowStale}
   */
  allowStale;
  /**
   * {@link LRUCache.OptionsBase.noDisposeOnSet}
   */
  noDisposeOnSet;
  /**
   * {@link LRUCache.OptionsBase.noUpdateTTL}
   */
  noUpdateTTL;
  /**
   * {@link LRUCache.OptionsBase.maxEntrySize}
   */
  maxEntrySize;
  /**
   * {@link LRUCache.OptionsBase.sizeCalculation}
   */
  sizeCalculation;
  /**
   * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
   */
  noDeleteOnFetchRejection;
  /**
   * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
   */
  noDeleteOnStaleGet;
  /**
   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
   */
  allowStaleOnFetchAbort;
  /**
   * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
   */
  allowStaleOnFetchRejection;
  /**
   * {@link LRUCache.OptionsBase.ignoreFetchAbort}
   */
  ignoreFetchAbort;
  // computed properties
  #size;
  #calculatedSize;
  #keyMap;
  #keyList;
  #valList;
  #next;
  #prev;
  #head;
  #tail;
  #free;
  #disposed;
  #sizes;
  #starts;
  #ttls;
  #hasDispose;
  #hasFetchMethod;
  #hasDisposeAfter;
  /**
   * Do not call this method unless you need to inspect the
   * inner workings of the cache.  If anything returned by this
   * object is modified in any way, strange breakage may occur.
   *
   * These fields are private for a reason!
   *
   * @internal
   */
  static unsafeExposeInternals(c) {
    return {
      // properties
      starts: c.#starts,
      ttls: c.#ttls,
      sizes: c.#sizes,
      keyMap: c.#keyMap,
      keyList: c.#keyList,
      valList: c.#valList,
      next: c.#next,
      prev: c.#prev,
      get head() {
        return c.#head;
      },
      get tail() {
        return c.#tail;
      },
      free: c.#free,
      // methods
      isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
      backgroundFetch: (k, index, options, context2) => c.#backgroundFetch(k, index, options, context2),
      moveToTail: (index) => c.#moveToTail(index),
      indexes: (options) => c.#indexes(options),
      rindexes: (options) => c.#rindexes(options),
      isStale: (index) => c.#isStale(index)
    };
  }
  // Protected read-only members
  /**
   * {@link LRUCache.OptionsBase.max} (read-only)
   */
  get max() {
    return this.#max;
  }
  /**
   * {@link LRUCache.OptionsBase.maxSize} (read-only)
   */
  get maxSize() {
    return this.#maxSize;
  }
  /**
   * The total computed size of items in the cache (read-only)
   */
  get calculatedSize() {
    return this.#calculatedSize;
  }
  /**
   * The number of items stored in the cache (read-only)
   */
  get size() {
    return this.#size;
  }
  /**
   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
   */
  get fetchMethod() {
    return this.#fetchMethod;
  }
  /**
   * {@link LRUCache.OptionsBase.dispose} (read-only)
   */
  get dispose() {
    return this.#dispose;
  }
  /**
   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
   */
  get disposeAfter() {
    return this.#disposeAfter;
  }
  constructor(options) {
    const { max: max2 = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;
    if (max2 !== 0 && !isPosInt(max2)) {
      throw new TypeError("max option must be a nonnegative integer");
    }
    const UintArray = max2 ? getUintArray(max2) : Array;
    if (!UintArray) {
      throw new Error("invalid max value: " + max2);
    }
    this.#max = max2;
    this.#maxSize = maxSize;
    this.maxEntrySize = maxEntrySize || this.#maxSize;
    this.sizeCalculation = sizeCalculation;
    if (this.sizeCalculation) {
      if (!this.#maxSize && !this.maxEntrySize) {
        throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
      }
      if (typeof this.sizeCalculation !== "function") {
        throw new TypeError("sizeCalculation set to non-function");
      }
    }
    if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
      throw new TypeError("fetchMethod must be a function if specified");
    }
    this.#fetchMethod = fetchMethod;
    this.#hasFetchMethod = !!fetchMethod;
    this.#keyMap = /* @__PURE__ */ new Map();
    this.#keyList = new Array(max2).fill(void 0);
    this.#valList = new Array(max2).fill(void 0);
    this.#next = new UintArray(max2);
    this.#prev = new UintArray(max2);
    this.#head = 0;
    this.#tail = 0;
    this.#free = Stack2.create(max2);
    this.#size = 0;
    this.#calculatedSize = 0;
    if (typeof dispose === "function") {
      this.#dispose = dispose;
    }
    if (typeof disposeAfter === "function") {
      this.#disposeAfter = disposeAfter;
      this.#disposed = [];
    } else {
      this.#disposeAfter = void 0;
      this.#disposed = void 0;
    }
    this.#hasDispose = !!this.#dispose;
    this.#hasDisposeAfter = !!this.#disposeAfter;
    this.noDisposeOnSet = !!noDisposeOnSet;
    this.noUpdateTTL = !!noUpdateTTL;
    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
    this.ignoreFetchAbort = !!ignoreFetchAbort;
    if (this.maxEntrySize !== 0) {
      if (this.#maxSize !== 0) {
        if (!isPosInt(this.#maxSize)) {
          throw new TypeError("maxSize must be a positive integer if specified");
        }
      }
      if (!isPosInt(this.maxEntrySize)) {
        throw new TypeError("maxEntrySize must be a positive integer if specified");
      }
      this.#initializeSizeTracking();
    }
    this.allowStale = !!allowStale;
    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
    this.updateAgeOnGet = !!updateAgeOnGet;
    this.updateAgeOnHas = !!updateAgeOnHas;
    this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
    this.ttlAutopurge = !!ttlAutopurge;
    this.ttl = ttl || 0;
    if (this.ttl) {
      if (!isPosInt(this.ttl)) {
        throw new TypeError("ttl must be a positive integer if specified");
      }
      this.#initializeTTLTracking();
    }
    if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
      throw new TypeError("At least one of max, maxSize, or ttl is required");
    }
    if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
      const code = "LRU_CACHE_UNBOUNDED";
      if (shouldWarn(code)) {
        warned.add(code);
        const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
        emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
      }
    }
  }
  /**
   * Return the remaining TTL time for a given entry key
   */
  getRemainingTTL(key) {
    return this.#keyMap.has(key) ? Infinity : 0;
  }
  #initializeTTLTracking() {
    const ttls = new ZeroArray(this.#max);
    const starts = new ZeroArray(this.#max);
    this.#ttls = ttls;
    this.#starts = starts;
    this.#setItemTTL = (index, ttl, start = perf.now()) => {
      starts[index] = ttl !== 0 ? start : 0;
      ttls[index] = ttl;
      if (ttl !== 0 && this.ttlAutopurge) {
        const t = setTimeout(() => {
          if (this.#isStale(index)) {
            this.delete(this.#keyList[index]);
          }
        }, ttl + 1);
        if (t.unref) {
          t.unref();
        }
      }
    };
    this.#updateItemAge = (index) => {
      starts[index] = ttls[index] !== 0 ? perf.now() : 0;
    };
    this.#statusTTL = (status, index) => {
      if (ttls[index]) {
        const ttl = ttls[index];
        const start = starts[index];
        if (!ttl || !start)
          return;
        status.ttl = ttl;
        status.start = start;
        status.now = cachedNow || getNow();
        const age = status.now - start;
        status.remainingTTL = ttl - age;
      }
    };
    let cachedNow = 0;
    const getNow = () => {
      const n = perf.now();
      if (this.ttlResolution > 0) {
        cachedNow = n;
        const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
        if (t.unref) {
          t.unref();
        }
      }
      return n;
    };
    this.getRemainingTTL = (key) => {
      const index = this.#keyMap.get(key);
      if (index === void 0) {
        return 0;
      }
      const ttl = ttls[index];
      const start = starts[index];
      if (!ttl || !start) {
        return Infinity;
      }
      const age = (cachedNow || getNow()) - start;
      return ttl - age;
    };
    this.#isStale = (index) => {
      const s = starts[index];
      const t = ttls[index];
      return !!t && !!s && (cachedNow || getNow()) - s > t;
    };
  }
  // conditionally set private methods related to TTL
  #updateItemAge = () => {
  };
  #statusTTL = () => {
  };
  #setItemTTL = () => {
  };
  /* c8 ignore stop */
  #isStale = () => false;
  #initializeSizeTracking() {
    const sizes = new ZeroArray(this.#max);
    this.#calculatedSize = 0;
    this.#sizes = sizes;
    this.#removeItemSize = (index) => {
      this.#calculatedSize -= sizes[index];
      sizes[index] = 0;
    };
    this.#requireSize = (k, v, size, sizeCalculation) => {
      if (this.#isBackgroundFetch(v)) {
        return 0;
      }
      if (!isPosInt(size)) {
        if (sizeCalculation) {
          if (typeof sizeCalculation !== "function") {
            throw new TypeError("sizeCalculation must be a function");
          }
          size = sizeCalculation(v, k);
          if (!isPosInt(size)) {
            throw new TypeError("sizeCalculation return invalid (expect positive integer)");
          }
        } else {
          throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
        }
      }
      return size;
    };
    this.#addItemSize = (index, size, status) => {
      sizes[index] = size;
      if (this.#maxSize) {
        const maxSize = this.#maxSize - sizes[index];
        while (this.#calculatedSize > maxSize) {
          this.#evict(true);
        }
      }
      this.#calculatedSize += sizes[index];
      if (status) {
        status.entrySize = size;
        status.totalCalculatedSize = this.#calculatedSize;
      }
    };
  }
  #removeItemSize = (_i) => {
  };
  #addItemSize = (_i, _s, _st) => {
  };
  #requireSize = (_k, _v, size, sizeCalculation) => {
    if (size || sizeCalculation) {
      throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
    }
    return 0;
  };
  *#indexes({ allowStale = this.allowStale } = {}) {
    if (this.#size) {
      for (let i = this.#tail; true; ) {
        if (!this.#isValidIndex(i)) {
          break;
        }
        if (allowStale || !this.#isStale(i)) {
          yield i;
        }
        if (i === this.#head) {
          break;
        } else {
          i = this.#prev[i];
        }
      }
    }
  }
  *#rindexes({ allowStale = this.allowStale } = {}) {
    if (this.#size) {
      for (let i = this.#head; true; ) {
        if (!this.#isValidIndex(i)) {
          break;
        }
        if (allowStale || !this.#isStale(i)) {
          yield i;
        }
        if (i === this.#tail) {
          break;
        } else {
          i = this.#next[i];
        }
      }
    }
  }
  #isValidIndex(index) {
    return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
  }
  /**
   * Return a generator yielding `[key, value]` pairs,
   * in order from most recently used to least recently used.
   */
  *entries() {
    for (const i of this.#indexes()) {
      if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
        yield [this.#keyList[i], this.#valList[i]];
      }
    }
  }
  /**
   * Inverse order version of {@link LRUCache.entries}
   *
   * Return a generator yielding `[key, value]` pairs,
   * in order from least recently used to most recently used.
   */
  *rentries() {
    for (const i of this.#rindexes()) {
      if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
        yield [this.#keyList[i], this.#valList[i]];
      }
    }
  }
  /**
   * Return a generator yielding the keys in the cache,
   * in order from most recently used to least recently used.
   */
  *keys() {
    for (const i of this.#indexes()) {
      const k = this.#keyList[i];
      if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
        yield k;
      }
    }
  }
  /**
   * Inverse order version of {@link LRUCache.keys}
   *
   * Return a generator yielding the keys in the cache,
   * in order from least recently used to most recently used.
   */
  *rkeys() {
    for (const i of this.#rindexes()) {
      const k = this.#keyList[i];
      if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
        yield k;
      }
    }
  }
  /**
   * Return a generator yielding the values in the cache,
   * in order from most recently used to least recently used.
   */
  *values() {
    for (const i of this.#indexes()) {
      const v = this.#valList[i];
      if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
        yield this.#valList[i];
      }
    }
  }
  /**
   * Inverse order version of {@link LRUCache.values}
   *
   * Return a generator yielding the values in the cache,
   * in order from least recently used to most recently used.
   */
  *rvalues() {
    for (const i of this.#rindexes()) {
      const v = this.#valList[i];
      if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
        yield this.#valList[i];
      }
    }
  }
  /**
   * Iterating over the cache itself yields the same results as
   * {@link LRUCache.entries}
   */
  [Symbol.iterator]() {
    return this.entries();
  }
  /**
   * A String value that is used in the creation of the default string description of an object.
   * Called by the built-in method Object.prototype.toString.
   */
  [Symbol.toStringTag] = "LRUCache";
  /**
   * Find a value for which the supplied fn method returns a truthy value,
   * similar to Array.find().  fn is called as fn(value, key, cache).
   */
  find(fn, getOptions = {}) {
    for (const i of this.#indexes()) {
      const v = this.#valList[i];
      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
      if (value === void 0)
        continue;
      if (fn(value, this.#keyList[i], this)) {
        return this.get(this.#keyList[i], getOptions);
      }
    }
  }
  /**
   * Call the supplied function on each item in the cache, in order from
   * most recently used to least recently used.  fn is called as
   * fn(value, key, cache).  Does not update age or recenty of use.
   * Does not iterate over stale values.
   */
  forEach(fn, thisp = this) {
    for (const i of this.#indexes()) {
      const v = this.#valList[i];
      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
      if (value === void 0)
        continue;
      fn.call(thisp, value, this.#keyList[i], this);
    }
  }
  /**
   * The same as {@link LRUCache.forEach} but items are iterated over in
   * reverse order.  (ie, less recently used items are iterated over first.)
   */
  rforEach(fn, thisp = this) {
    for (const i of this.#rindexes()) {
      const v = this.#valList[i];
      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
      if (value === void 0)
        continue;
      fn.call(thisp, value, this.#keyList[i], this);
    }
  }
  /**
   * Delete any stale entries. Returns true if anything was removed,
   * false otherwise.
   */
  purgeStale() {
    let deleted = false;
    for (const i of this.#rindexes({ allowStale: true })) {
      if (this.#isStale(i)) {
        this.delete(this.#keyList[i]);
        deleted = true;
      }
    }
    return deleted;
  }
  /**
   * Get the extended info about a given entry, to get its value, size, and
   * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
   * single key. Always returns stale values, if their info is found in the
   * cache, so be sure to check for expired TTLs if relevant.
   */
  info(key) {
    const i = this.#keyMap.get(key);
    if (i === void 0)
      return void 0;
    const v = this.#valList[i];
    const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
    if (value === void 0)
      return void 0;
    const entry = { value };
    if (this.#ttls && this.#starts) {
      const ttl = this.#ttls[i];
      const start = this.#starts[i];
      if (ttl && start) {
        const remain = ttl - (perf.now() - start);
        entry.ttl = remain;
        entry.start = Date.now();
      }
    }
    if (this.#sizes) {
      entry.size = this.#sizes[i];
    }
    return entry;
  }
  /**
   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
   * passed to cache.load()
   */
  dump() {
    const arr = [];
    for (const i of this.#indexes({ allowStale: true })) {
      const key = this.#keyList[i];
      const v = this.#valList[i];
      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
      if (value === void 0 || key === void 0)
        continue;
      const entry = { value };
      if (this.#ttls && this.#starts) {
        entry.ttl = this.#ttls[i];
        const age = perf.now() - this.#starts[i];
        entry.start = Math.floor(Date.now() - age);
      }
      if (this.#sizes) {
        entry.size = this.#sizes[i];
      }
      arr.unshift([key, entry]);
    }
    return arr;
  }
  /**
   * Reset the cache and load in the items in entries in the order listed.
   * Note that the shape of the resulting cache may be different if the
   * same options are not used in both caches.
   */
  load(arr) {
    this.clear();
    for (const [key, entry] of arr) {
      if (entry.start) {
        const age = Date.now() - entry.start;
        entry.start = perf.now() - age;
      }
      this.set(key, entry.value, entry);
    }
  }
  /**
   * Add a value to the cache.
   *
   * Note: if `undefined` is specified as a value, this is an alias for
   * {@link LRUCache#delete}
   */
  set(k, v, setOptions = {}) {
    var _a2, _b, _c, _d, _e;
    if (v === void 0) {
      this.delete(k);
      return this;
    }
    const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
    let { noUpdateTTL = this.noUpdateTTL } = setOptions;
    const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
    if (this.maxEntrySize && size > this.maxEntrySize) {
      if (status) {
        status.set = "miss";
        status.maxEntrySizeExceeded = true;
      }
      this.delete(k);
      return this;
    }
    let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
    if (index === void 0) {
      index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
      this.#keyList[index] = k;
      this.#valList[index] = v;
      this.#keyMap.set(k, index);
      this.#next[this.#tail] = index;
      this.#prev[index] = this.#tail;
      this.#tail = index;
      this.#size++;
      this.#addItemSize(index, size, status);
      if (status)
        status.set = "add";
      noUpdateTTL = false;
    } else {
      this.#moveToTail(index);
      const oldVal = this.#valList[index];
      if (v !== oldVal) {
        if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
          oldVal.__abortController.abort(new Error("replaced"));
          const { __staleWhileFetching: s } = oldVal;
          if (s !== void 0 && !noDisposeOnSet) {
            if (this.#hasDispose) {
              (_a2 = this.#dispose) == null ? void 0 : _a2.call(this, s, k, "set");
            }
            if (this.#hasDisposeAfter) {
              (_b = this.#disposed) == null ? void 0 : _b.push([s, k, "set"]);
            }
          }
        } else if (!noDisposeOnSet) {
          if (this.#hasDispose) {
            (_c = this.#dispose) == null ? void 0 : _c.call(this, oldVal, k, "set");
          }
          if (this.#hasDisposeAfter) {
            (_d = this.#disposed) == null ? void 0 : _d.push([oldVal, k, "set"]);
          }
        }
        this.#removeItemSize(index);
        this.#addItemSize(index, size, status);
        this.#valList[index] = v;
        if (status) {
          status.set = "replace";
          const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
          if (oldValue !== void 0)
            status.oldValue = oldValue;
        }
      } else if (status) {
        status.set = "update";
      }
    }
    if (ttl !== 0 && !this.#ttls) {
      this.#initializeTTLTracking();
    }
    if (this.#ttls) {
      if (!noUpdateTTL) {
        this.#setItemTTL(index, ttl, start);
      }
      if (status)
        this.#statusTTL(status, index);
    }
    if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
      const dt = this.#disposed;
      let task;
      while (task = dt == null ? void 0 : dt.shift()) {
        (_e = this.#disposeAfter) == null ? void 0 : _e.call(this, ...task);
      }
    }
    return this;
  }
  /**
   * Evict the least recently used item, returning its value or
   * `undefined` if cache is empty.
   */
  pop() {
    var _a2;
    try {
      while (this.#size) {
        const val = this.#valList[this.#head];
        this.#evict(true);
        if (this.#isBackgroundFetch(val)) {
          if (val.__staleWhileFetching) {
            return val.__staleWhileFetching;
          }
        } else if (val !== void 0) {
          return val;
        }
      }
    } finally {
      if (this.#hasDisposeAfter && this.#disposed) {
        const dt = this.#disposed;
        let task;
        while (task = dt == null ? void 0 : dt.shift()) {
          (_a2 = this.#disposeAfter) == null ? void 0 : _a2.call(this, ...task);
        }
      }
    }
  }
  #evict(free) {
    var _a2, _b;
    const head = this.#head;
    const k = this.#keyList[head];
    const v = this.#valList[head];
    if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
      v.__abortController.abort(new Error("evicted"));
    } else if (this.#hasDispose || this.#hasDisposeAfter) {
      if (this.#hasDispose) {
        (_a2 = this.#dispose) == null ? void 0 : _a2.call(this, v, k, "evict");
      }
      if (this.#hasDisposeAfter) {
        (_b = this.#disposed) == null ? void 0 : _b.push([v, k, "evict"]);
      }
    }
    this.#removeItemSize(head);
    if (free) {
      this.#keyList[head] = void 0;
      this.#valList[head] = void 0;
      this.#free.push(head);
    }
    if (this.#size === 1) {
      this.#head = this.#tail = 0;
      this.#free.length = 0;
    } else {
      this.#head = this.#next[head];
    }
    this.#keyMap.delete(k);
    this.#size--;
    return head;
  }
  /**
   * Check if a key is in the cache, without updating the recency of use.
   * Will return false if the item is stale, even though it is technically
   * in the cache.
   *
   * Will not update item age unless
   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
   */
  has(k, hasOptions = {}) {
    const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
    const index = this.#keyMap.get(k);
    if (index !== void 0) {
      const v = this.#valList[index];
      if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
        return false;
      }
      if (!this.#isStale(index)) {
        if (updateAgeOnHas) {
          this.#updateItemAge(index);
        }
        if (status) {
          status.has = "hit";
          this.#statusTTL(status, index);
        }
        return true;
      } else if (status) {
        status.has = "stale";
        this.#statusTTL(status, index);
      }
    } else if (status) {
      status.has = "miss";
    }
    return false;
  }
  /**
   * Like {@link LRUCache#get} but doesn't update recency or delete stale
   * items.
   *
   * Returns `undefined` if the item is stale, unless
   * {@link LRUCache.OptionsBase.allowStale} is set.
   */
  peek(k, peekOptions = {}) {
    const { allowStale = this.allowStale } = peekOptions;
    const index = this.#keyMap.get(k);
    if (index === void 0 || !allowStale && this.#isStale(index)) {
      return;
    }
    const v = this.#valList[index];
    return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  }
  #backgroundFetch(k, index, options, context2) {
    const v = index === void 0 ? void 0 : this.#valList[index];
    if (this.#isBackgroundFetch(v)) {
      return v;
    }
    const ac = new AC();
    const { signal } = options;
    signal == null ? void 0 : signal.addEventListener("abort", () => ac.abort(signal.reason), {
      signal: ac.signal
    });
    const fetchOpts = {
      signal: ac.signal,
      options,
      context: context2
    };
    const cb = (v2, updateCache = false) => {
      const { aborted } = ac.signal;
      const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
      if (options.status) {
        if (aborted && !updateCache) {
          options.status.fetchAborted = true;
          options.status.fetchError = ac.signal.reason;
          if (ignoreAbort)
            options.status.fetchAbortIgnored = true;
        } else {
          options.status.fetchResolved = true;
        }
      }
      if (aborted && !ignoreAbort && !updateCache) {
        return fetchFail(ac.signal.reason);
      }
      const bf2 = p;
      if (this.#valList[index] === p) {
        if (v2 === void 0) {
          if (bf2.__staleWhileFetching) {
            this.#valList[index] = bf2.__staleWhileFetching;
          } else {
            this.delete(k);
          }
        } else {
          if (options.status)
            options.status.fetchUpdated = true;
          this.set(k, v2, fetchOpts.options);
        }
      }
      return v2;
    };
    const eb = (er) => {
      if (options.status) {
        options.status.fetchRejected = true;
        options.status.fetchError = er;
      }
      return fetchFail(er);
    };
    const fetchFail = (er) => {
      const { aborted } = ac.signal;
      const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
      const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
      const noDelete = allowStale || options.noDeleteOnFetchRejection;
      const bf2 = p;
      if (this.#valList[index] === p) {
        const del = !noDelete || bf2.__staleWhileFetching === void 0;
        if (del) {
          this.delete(k);
        } else if (!allowStaleAborted) {
          this.#valList[index] = bf2.__staleWhileFetching;
        }
      }
      if (allowStale) {
        if (options.status && bf2.__staleWhileFetching !== void 0) {
          options.status.returnedStale = true;
        }
        return bf2.__staleWhileFetching;
      } else if (bf2.__returned === bf2) {
        throw er;
      }
    };
    const pcall = (res, rej) => {
      var _a2;
      const fmp = (_a2 = this.#fetchMethod) == null ? void 0 : _a2.call(this, k, v, fetchOpts);
      if (fmp && fmp instanceof Promise) {
        fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
      }
      ac.signal.addEventListener("abort", () => {
        if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
          res(void 0);
          if (options.allowStaleOnFetchAbort) {
            res = (v2) => cb(v2, true);
          }
        }
      });
    };
    if (options.status)
      options.status.fetchDispatched = true;
    const p = new Promise(pcall).then(cb, eb);
    const bf = Object.assign(p, {
      __abortController: ac,
      __staleWhileFetching: v,
      __returned: void 0
    });
    if (index === void 0) {
      this.set(k, bf, { ...fetchOpts.options, status: void 0 });
      index = this.#keyMap.get(k);
    } else {
      this.#valList[index] = bf;
    }
    return bf;
  }
  #isBackgroundFetch(p) {
    if (!this.#hasFetchMethod)
      return false;
    const b = p;
    return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
  }
  async fetch(k, fetchOptions = {}) {
    const {
      // get options
      allowStale = this.allowStale,
      updateAgeOnGet = this.updateAgeOnGet,
      noDeleteOnStaleGet = this.noDeleteOnStaleGet,
      // set options
      ttl = this.ttl,
      noDisposeOnSet = this.noDisposeOnSet,
      size = 0,
      sizeCalculation = this.sizeCalculation,
      noUpdateTTL = this.noUpdateTTL,
      // fetch exclusive options
      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
      ignoreFetchAbort = this.ignoreFetchAbort,
      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
      context: context2,
      forceRefresh = false,
      status,
      signal
    } = fetchOptions;
    if (!this.#hasFetchMethod) {
      if (status)
        status.fetch = "get";
      return this.get(k, {
        allowStale,
        updateAgeOnGet,
        noDeleteOnStaleGet,
        status
      });
    }
    const options = {
      allowStale,
      updateAgeOnGet,
      noDeleteOnStaleGet,
      ttl,
      noDisposeOnSet,
      size,
      sizeCalculation,
      noUpdateTTL,
      noDeleteOnFetchRejection,
      allowStaleOnFetchRejection,
      allowStaleOnFetchAbort,
      ignoreFetchAbort,
      status,
      signal
    };
    let index = this.#keyMap.get(k);
    if (index === void 0) {
      if (status)
        status.fetch = "miss";
      const p = this.#backgroundFetch(k, index, options, context2);
      return p.__returned = p;
    } else {
      const v = this.#valList[index];
      if (this.#isBackgroundFetch(v)) {
        const stale = allowStale && v.__staleWhileFetching !== void 0;
        if (status) {
          status.fetch = "inflight";
          if (stale)
            status.returnedStale = true;
        }
        return stale ? v.__staleWhileFetching : v.__returned = v;
      }
      const isStale = this.#isStale(index);
      if (!forceRefresh && !isStale) {
        if (status)
          status.fetch = "hit";
        this.#moveToTail(index);
        if (updateAgeOnGet) {
          this.#updateItemAge(index);
        }
        if (status)
          this.#statusTTL(status, index);
        return v;
      }
      const p = this.#backgroundFetch(k, index, options, context2);
      const hasStale = p.__staleWhileFetching !== void 0;
      const staleVal = hasStale && allowStale;
      if (status) {
        status.fetch = isStale ? "stale" : "refresh";
        if (staleVal && isStale)
          status.returnedStale = true;
      }
      return staleVal ? p.__staleWhileFetching : p.__returned = p;
    }
  }
  /**
   * Return a value from the cache. Will update the recency of the cache
   * entry found.
   *
   * If the key is not found, get() will return `undefined`.
   */
  get(k, getOptions = {}) {
    const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
    const index = this.#keyMap.get(k);
    if (index !== void 0) {
      const value = this.#valList[index];
      const fetching = this.#isBackgroundFetch(value);
      if (status)
        this.#statusTTL(status, index);
      if (this.#isStale(index)) {
        if (status)
          status.get = "stale";
        if (!fetching) {
          if (!noDeleteOnStaleGet) {
            this.delete(k);
          }
          if (status && allowStale)
            status.returnedStale = true;
          return allowStale ? value : void 0;
        } else {
          if (status && allowStale && value.__staleWhileFetching !== void 0) {
            status.returnedStale = true;
          }
          return allowStale ? value.__staleWhileFetching : void 0;
        }
      } else {
        if (status)
          status.get = "hit";
        if (fetching) {
          return value.__staleWhileFetching;
        }
        this.#moveToTail(index);
        if (updateAgeOnGet) {
          this.#updateItemAge(index);
        }
        return value;
      }
    } else if (status) {
      status.get = "miss";
    }
  }
  #connect(p, n) {
    this.#prev[n] = p;
    this.#next[p] = n;
  }
  #moveToTail(index) {
    if (index !== this.#tail) {
      if (index === this.#head) {
        this.#head = this.#next[index];
      } else {
        this.#connect(this.#prev[index], this.#next[index]);
      }
      this.#connect(this.#tail, index);
      this.#tail = index;
    }
  }
  /**
   * Deletes a key out of the cache.
   * Returns true if the key was deleted, false otherwise.
   */
  delete(k) {
    var _a2, _b, _c, _d;
    let deleted = false;
    if (this.#size !== 0) {
      const index = this.#keyMap.get(k);
      if (index !== void 0) {
        deleted = true;
        if (this.#size === 1) {
          this.clear();
        } else {
          this.#removeItemSize(index);
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v)) {
            v.__abortController.abort(new Error("deleted"));
          } else if (this.#hasDispose || this.#hasDisposeAfter) {
            if (this.#hasDispose) {
              (_a2 = this.#dispose) == null ? void 0 : _a2.call(this, v, k, "delete");
            }
            if (this.#hasDisposeAfter) {
              (_b = this.#disposed) == null ? void 0 : _b.push([v, k, "delete"]);
            }
          }
          this.#keyMap.delete(k);
          this.#keyList[index] = void 0;
          this.#valList[index] = void 0;
          if (index === this.#tail) {
            this.#tail = this.#prev[index];
          } else if (index === this.#head) {
            this.#head = this.#next[index];
          } else {
            const pi = this.#prev[index];
            this.#next[pi] = this.#next[index];
            const ni = this.#next[index];
            this.#prev[ni] = this.#prev[index];
          }
          this.#size--;
          this.#free.push(index);
        }
      }
    }
    if (this.#hasDisposeAfter && ((_c = this.#disposed) == null ? void 0 : _c.length)) {
      const dt = this.#disposed;
      let task;
      while (task = dt == null ? void 0 : dt.shift()) {
        (_d = this.#disposeAfter) == null ? void 0 : _d.call(this, ...task);
      }
    }
    return deleted;
  }
  /**
   * Clear the cache entirely, throwing away all values.
   */
  clear() {
    var _a2, _b, _c;
    for (const index of this.#rindexes({ allowStale: true })) {
      const v = this.#valList[index];
      if (this.#isBackgroundFetch(v)) {
        v.__abortController.abort(new Error("deleted"));
      } else {
        const k = this.#keyList[index];
        if (this.#hasDispose) {
          (_a2 = this.#dispose) == null ? void 0 : _a2.call(this, v, k, "delete");
        }
        if (this.#hasDisposeAfter) {
          (_b = this.#disposed) == null ? void 0 : _b.push([v, k, "delete"]);
        }
      }
    }
    this.#keyMap.clear();
    this.#valList.fill(void 0);
    this.#keyList.fill(void 0);
    if (this.#ttls && this.#starts) {
      this.#ttls.fill(0);
      this.#starts.fill(0);
    }
    if (this.#sizes) {
      this.#sizes.fill(0);
    }
    this.#head = 0;
    this.#tail = 0;
    this.#free.length = 0;
    this.#calculatedSize = 0;
    this.#size = 0;
    if (this.#hasDisposeAfter && this.#disposed) {
      const dt = this.#disposed;
      let task;
      while (task = dt == null ? void 0 : dt.shift()) {
        (_c = this.#disposeAfter) == null ? void 0 : _c.call(this, ...task);
      }
    }
  }
};

// node_modules/path-scurry/dist/esm/index.js
var import_node_path = require("path");
var import_node_url = require("url");
var import_fs = require("fs");
var actualFS = __toESM(require("fs"), 1);
var import_promises = require("fs/promises");

// node_modules/minipass/dist/esm/index.js
var import_node_events = require("events");
var import_node_stream = __toESM(require("stream"), 1);
var import_node_string_decoder = require("string_decoder");
var proc = typeof process === "object" && process ? process : {
  stdout: null,
  stderr: null
};
var isStream = (s) => !!s && typeof s === "object" && (s instanceof Minipass || s instanceof import_node_stream.default || isReadable(s) || isWritable(s));
var isReadable = (s) => !!s && typeof s === "object" && s instanceof import_node_events.EventEmitter && typeof s.pipe === "function" && // node core Writable streams have a pipe() method, but it throws
s.pipe !== import_node_stream.default.Writable.prototype.pipe;
var isWritable = (s) => !!s && typeof s === "object" && s instanceof import_node_events.EventEmitter && typeof s.write === "function" && typeof s.end === "function";
var EOF = Symbol("EOF");
var MAYBE_EMIT_END = Symbol("maybeEmitEnd");
var EMITTED_END = Symbol("emittedEnd");
var EMITTING_END = Symbol("emittingEnd");
var EMITTED_ERROR = Symbol("emittedError");
var CLOSED = Symbol("closed");
var READ = Symbol("read");
var FLUSH = Symbol("flush");
var FLUSHCHUNK = Symbol("flushChunk");
var ENCODING = Symbol("encoding");
var DECODER = Symbol("decoder");
var FLOWING = Symbol("flowing");
var PAUSED = Symbol("paused");
var RESUME = Symbol("resume");
var BUFFER = Symbol("buffer");
var PIPES = Symbol("pipes");
var BUFFERLENGTH = Symbol("bufferLength");
var BUFFERPUSH = Symbol("bufferPush");
var BUFFERSHIFT = Symbol("bufferShift");
var OBJECTMODE = Symbol("objectMode");
var DESTROYED = Symbol("destroyed");
var ERROR = Symbol("error");
var EMITDATA = Symbol("emitData");
var EMITEND = Symbol("emitEnd");
var EMITEND2 = Symbol("emitEnd2");
var ASYNC = Symbol("async");
var ABORT = Symbol("abort");
var ABORTED = Symbol("aborted");
var SIGNAL = Symbol("signal");
var DATALISTENERS = Symbol("dataListeners");
var DISCARDED = Symbol("discarded");
var defer = (fn) => Promise.resolve().then(fn);
var nodefer = (fn) => fn();
var isEndish = (ev) => ev === "end" || ev === "finish" || ev === "prefinish";
var isArrayBufferLike = (b) => b instanceof ArrayBuffer || !!b && typeof b === "object" && b.constructor && b.constructor.name === "ArrayBuffer" && b.byteLength >= 0;
var isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
var Pipe = class {
  src;
  dest;
  opts;
  ondrain;
  constructor(src, dest, opts) {
    this.src = src;
    this.dest = dest;
    this.opts = opts;
    this.ondrain = () => src[RESUME]();
    this.dest.on("drain", this.ondrain);
  }
  unpipe() {
    this.dest.removeListener("drain", this.ondrain);
  }
  // only here for the prototype
  /* c8 ignore start */
  proxyErrors(_er) {
  }
  /* c8 ignore stop */
  end() {
    this.unpipe();
    if (this.opts.end)
      this.dest.end();
  }
};
var PipeProxyErrors = class extends Pipe {
  unpipe() {
    this.src.removeListener("error", this.proxyErrors);
    super.unpipe();
  }
  constructor(src, dest, opts) {
    super(src, dest, opts);
    this.proxyErrors = (er) => dest.emit("error", er);
    src.on("error", this.proxyErrors);
  }
};
var isObjectModeOptions = (o) => !!o.objectMode;
var isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== "buffer";
var Minipass = class extends import_node_events.EventEmitter {
  [FLOWING] = false;
  [PAUSED] = false;
  [PIPES] = [];
  [BUFFER] = [];
  [OBJECTMODE];
  [ENCODING];
  [ASYNC];
  [DECODER];
  [EOF] = false;
  [EMITTED_END] = false;
  [EMITTING_END] = false;
  [CLOSED] = false;
  [EMITTED_ERROR] = null;
  [BUFFERLENGTH] = 0;
  [DESTROYED] = false;
  [SIGNAL];
  [ABORTED] = false;
  [DATALISTENERS] = 0;
  [DISCARDED] = false;
  /**
   * true if the stream can be written
   */
  writable = true;
  /**
   * true if the stream can be read
   */
  readable = true;
  /**
   * If `RType` is Buffer, then options do not need to be provided.
   * Otherwise, an options object must be provided to specify either
   * {@link Minipass.SharedOptions.objectMode} or
   * {@link Minipass.SharedOptions.encoding}, as appropriate.
   */
  constructor(...args) {
    const options = args[0] || {};
    super();
    if (options.objectMode && typeof options.encoding === "string") {
      throw new TypeError("Encoding and objectMode may not be used together");
    }
    if (isObjectModeOptions(options)) {
      this[OBJECTMODE] = true;
      this[ENCODING] = null;
    } else if (isEncodingOptions(options)) {
      this[ENCODING] = options.encoding;
      this[OBJECTMODE] = false;
    } else {
      this[OBJECTMODE] = false;
      this[ENCODING] = null;
    }
    this[ASYNC] = !!options.async;
    this[DECODER] = this[ENCODING] ? new import_node_string_decoder.StringDecoder(this[ENCODING]) : null;
    if (options && options.debugExposeBuffer === true) {
      Object.defineProperty(this, "buffer", { get: () => this[BUFFER] });
    }
    if (options && options.debugExposePipes === true) {
      Object.defineProperty(this, "pipes", { get: () => this[PIPES] });
    }
    const { signal } = options;
    if (signal) {
      this[SIGNAL] = signal;
      if (signal.aborted) {
        this[ABORT]();
      } else {
        signal.addEventListener("abort", () => this[ABORT]());
      }
    }
  }
  /**
   * The amount of data stored in the buffer waiting to be read.
   *
   * For Buffer strings, this will be the total byte length.
   * For string encoding streams, this will be the string character length,
   * according to JavaScript's `string.length` logic.
   * For objectMode streams, this is a count of the items waiting to be
   * emitted.
   */
  get bufferLength() {
    return this[BUFFERLENGTH];
  }
  /**
   * The `BufferEncoding` currently in use, or `null`
   */
  get encoding() {
    return this[ENCODING];
  }
  /**
   * @deprecated - This is a read only property
   */
  set encoding(_enc) {
    throw new Error("Encoding must be set at instantiation time");
  }
  /**
   * @deprecated - Encoding may only be set at instantiation time
   */
  setEncoding(_enc) {
    throw new Error("Encoding must be set at instantiation time");
  }
  /**
   * True if this is an objectMode stream
   */
  get objectMode() {
    return this[OBJECTMODE];
  }
  /**
   * @deprecated - This is a read-only property
   */
  set objectMode(_om) {
    throw new Error("objectMode must be set at instantiation time");
  }
  /**
   * true if this is an async stream
   */
  get ["async"]() {
    return this[ASYNC];
  }
  /**
   * Set to true to make this stream async.
   *
   * Once set, it cannot be unset, as this would potentially cause incorrect
   * behavior.  Ie, a sync stream can be made async, but an async stream
   * cannot be safely made sync.
   */
  set ["async"](a) {
    this[ASYNC] = this[ASYNC] || !!a;
  }
  // drop everything and get out of the flow completely
  [ABORT]() {
    var _a2, _b;
    this[ABORTED] = true;
    this.emit("abort", (_a2 = this[SIGNAL]) == null ? void 0 : _a2.reason);
    this.destroy((_b = this[SIGNAL]) == null ? void 0 : _b.reason);
  }
  /**
   * True if the stream has been aborted.
   */
  get aborted() {
    return this[ABORTED];
  }
  /**
   * No-op setter. Stream aborted status is set via the AbortSignal provided
   * in the constructor options.
   */
  set aborted(_) {
  }
  write(chunk, encoding, cb) {
    var _a2;
    if (this[ABORTED])
      return false;
    if (this[EOF])
      throw new Error("write after end");
    if (this[DESTROYED]) {
      this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" }));
      return true;
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = "utf8";
    }
    if (!encoding)
      encoding = "utf8";
    const fn = this[ASYNC] ? defer : nodefer;
    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
      if (isArrayBufferView(chunk)) {
        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
      } else if (isArrayBufferLike(chunk)) {
        chunk = Buffer.from(chunk);
      } else if (typeof chunk !== "string") {
        throw new Error("Non-contiguous data written to non-objectMode stream");
      }
    }
    if (this[OBJECTMODE]) {
      if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
        this[FLUSH](true);
      if (this[FLOWING])
        this.emit("data", chunk);
      else
        this[BUFFERPUSH](chunk);
      if (this[BUFFERLENGTH] !== 0)
        this.emit("readable");
      if (cb)
        fn(cb);
      return this[FLOWING];
    }
    if (!chunk.length) {
      if (this[BUFFERLENGTH] !== 0)
        this.emit("readable");
      if (cb)
        fn(cb);
      return this[FLOWING];
    }
    if (typeof chunk === "string" && // unless it is a string already ready for us to use
    !(encoding === this[ENCODING] && !((_a2 = this[DECODER]) == null ? void 0 : _a2.lastNeed))) {
      chunk = Buffer.from(chunk, encoding);
    }
    if (Buffer.isBuffer(chunk) && this[ENCODING]) {
      chunk = this[DECODER].write(chunk);
    }
    if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
      this[FLUSH](true);
    if (this[FLOWING])
      this.emit("data", chunk);
    else
      this[BUFFERPUSH](chunk);
    if (this[BUFFERLENGTH] !== 0)
      this.emit("readable");
    if (cb)
      fn(cb);
    return this[FLOWING];
  }
  /**
   * Low-level explicit read method.
   *
   * In objectMode, the argument is ignored, and one item is returned if
   * available.
   *
   * `n` is the number of bytes (or in the case of encoding streams,
   * characters) to consume. If `n` is not provided, then the entire buffer
   * is returned, or `null` is returned if no data is available.
   *
   * If `n` is greater that the amount of data in the internal buffer,
   * then `null` is returned.
   */
  read(n) {
    if (this[DESTROYED])
      return null;
    this[DISCARDED] = false;
    if (this[BUFFERLENGTH] === 0 || n === 0 || n && n > this[BUFFERLENGTH]) {
      this[MAYBE_EMIT_END]();
      return null;
    }
    if (this[OBJECTMODE])
      n = null;
    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
      this[BUFFER] = [
        this[ENCODING] ? this[BUFFER].join("") : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])
      ];
    }
    const ret = this[READ](n || null, this[BUFFER][0]);
    this[MAYBE_EMIT_END]();
    return ret;
  }
  [READ](n, chunk) {
    if (this[OBJECTMODE])
      this[BUFFERSHIFT]();
    else {
      const c = chunk;
      if (n === c.length || n === null)
        this[BUFFERSHIFT]();
      else if (typeof c === "string") {
        this[BUFFER][0] = c.slice(n);
        chunk = c.slice(0, n);
        this[BUFFERLENGTH] -= n;
      } else {
        this[BUFFER][0] = c.subarray(n);
        chunk = c.subarray(0, n);
        this[BUFFERLENGTH] -= n;
      }
    }
    this.emit("data", chunk);
    if (!this[BUFFER].length && !this[EOF])
      this.emit("drain");
    return chunk;
  }
  end(chunk, encoding, cb) {
    if (typeof chunk === "function") {
      cb = chunk;
      chunk = void 0;
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = "utf8";
    }
    if (chunk !== void 0)
      this.write(chunk, encoding);
    if (cb)
      this.once("end", cb);
    this[EOF] = true;
    this.writable = false;
    if (this[FLOWING] || !this[PAUSED])
      this[MAYBE_EMIT_END]();
    return this;
  }
  // don't let the internal resume be overwritten
  [RESUME]() {
    if (this[DESTROYED])
      return;
    if (!this[DATALISTENERS] && !this[PIPES].length) {
      this[DISCARDED] = true;
    }
    this[PAUSED] = false;
    this[FLOWING] = true;
    this.emit("resume");
    if (this[BUFFER].length)
      this[FLUSH]();
    else if (this[EOF])
      this[MAYBE_EMIT_END]();
    else
      this.emit("drain");
  }
  /**
   * Resume the stream if it is currently in a paused state
   *
   * If called when there are no pipe destinations or `data` event listeners,
   * this will place the stream in a "discarded" state, where all data will
   * be thrown away. The discarded state is removed if a pipe destination or
   * data handler is added, if pause() is called, or if any synchronous or
   * asynchronous iteration is started.
   */
  resume() {
    return this[RESUME]();
  }
  /**
   * Pause the stream
   */
  pause() {
    this[FLOWING] = false;
    this[PAUSED] = true;
    this[DISCARDED] = false;
  }
  /**
   * true if the stream has been forcibly destroyed
   */
  get destroyed() {
    return this[DESTROYED];
  }
  /**
   * true if the stream is currently in a flowing state, meaning that
   * any writes will be immediately emitted.
   */
  get flowing() {
    return this[FLOWING];
  }
  /**
   * true if the stream is currently in a paused state
   */
  get paused() {
    return this[PAUSED];
  }
  [BUFFERPUSH](chunk) {
    if (this[OBJECTMODE])
      this[BUFFERLENGTH] += 1;
    else
      this[BUFFERLENGTH] += chunk.length;
    this[BUFFER].push(chunk);
  }
  [BUFFERSHIFT]() {
    if (this[OBJECTMODE])
      this[BUFFERLENGTH] -= 1;
    else
      this[BUFFERLENGTH] -= this[BUFFER][0].length;
    return this[BUFFER].shift();
  }
  [FLUSH](noDrain = false) {
    do {
    } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length);
    if (!noDrain && !this[BUFFER].length && !this[EOF])
      this.emit("drain");
  }
  [FLUSHCHUNK](chunk) {
    this.emit("data", chunk);
    return this[FLOWING];
  }
  /**
   * Pipe all data emitted by this stream into the destination provided.
   *
   * Triggers the flow of data.
   */
  pipe(dest, opts) {
    if (this[DESTROYED])
      return dest;
    this[DISCARDED] = false;
    const ended = this[EMITTED_END];
    opts = opts || {};
    if (dest === proc.stdout || dest === proc.stderr)
      opts.end = false;
    else
      opts.end = opts.end !== false;
    opts.proxyErrors = !!opts.proxyErrors;
    if (ended) {
      if (opts.end)
        dest.end();
    } else {
      this[PIPES].push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts));
      if (this[ASYNC])
        defer(() => this[RESUME]());
      else
        this[RESUME]();
    }
    return dest;
  }
  /**
   * Fully unhook a piped destination stream.
   *
   * If the destination stream was the only consumer of this stream (ie,
   * there are no other piped destinations or `'data'` event listeners)
   * then the flow of data will stop until there is another consumer or
   * {@link Minipass#resume} is explicitly called.
   */
  unpipe(dest) {
    const p = this[PIPES].find((p2) => p2.dest === dest);
    if (p) {
      if (this[PIPES].length === 1) {
        if (this[FLOWING] && this[DATALISTENERS] === 0) {
          this[FLOWING] = false;
        }
        this[PIPES] = [];
      } else
        this[PIPES].splice(this[PIPES].indexOf(p), 1);
      p.unpipe();
    }
  }
  /**
   * Alias for {@link Minipass#on}
   */
  addListener(ev, handler) {
    return this.on(ev, handler);
  }
  /**
   * Mostly identical to `EventEmitter.on`, with the following
   * behavior differences to prevent data loss and unnecessary hangs:
   *
   * - Adding a 'data' event handler will trigger the flow of data
   *
   * - Adding a 'readable' event handler when there is data waiting to be read
   *   will cause 'readable' to be emitted immediately.
   *
   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
   *   already passed will cause the event to be emitted immediately and all
   *   handlers removed.
   *
   * - Adding an 'error' event handler after an error has been emitted will
   *   cause the event to be re-emitted immediately with the error previously
   *   raised.
   */
  on(ev, handler) {
    const ret = super.on(ev, handler);
    if (ev === "data") {
      this[DISCARDED] = false;
      this[DATALISTENERS]++;
      if (!this[PIPES].length && !this[FLOWING]) {
        this[RESUME]();
      }
    } else if (ev === "readable" && this[BUFFERLENGTH] !== 0) {
      super.emit("readable");
    } else if (isEndish(ev) && this[EMITTED_END]) {
      super.emit(ev);
      this.removeAllListeners(ev);
    } else if (ev === "error" && this[EMITTED_ERROR]) {
      const h = handler;
      if (this[ASYNC])
        defer(() => h.call(this, this[EMITTED_ERROR]));
      else
        h.call(this, this[EMITTED_ERROR]);
    }
    return ret;
  }
  /**
   * Alias for {@link Minipass#off}
   */
  removeListener(ev, handler) {
    return this.off(ev, handler);
  }
  /**
   * Mostly identical to `EventEmitter.off`
   *
   * If a 'data' event handler is removed, and it was the last consumer
   * (ie, there are no pipe destinations or other 'data' event listeners),
   * then the flow of data will stop until there is another consumer or
   * {@link Minipass#resume} is explicitly called.
   */
  off(ev, handler) {
    const ret = super.off(ev, handler);
    if (ev === "data") {
      this[DATALISTENERS] = this.listeners("data").length;
      if (this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length) {
        this[FLOWING] = false;
      }
    }
    return ret;
  }
  /**
   * Mostly identical to `EventEmitter.removeAllListeners`
   *
   * If all 'data' event handlers are removed, and they were the last consumer
   * (ie, there are no pipe destinations), then the flow of data will stop
   * until there is another consumer or {@link Minipass#resume} is explicitly
   * called.
   */
  removeAllListeners(ev) {
    const ret = super.removeAllListeners(ev);
    if (ev === "data" || ev === void 0) {
      this[DATALISTENERS] = 0;
      if (!this[DISCARDED] && !this[PIPES].length) {
        this[FLOWING] = false;
      }
    }
    return ret;
  }
  /**
   * true if the 'end' event has been emitted
   */
  get emittedEnd() {
    return this[EMITTED_END];
  }
  [MAYBE_EMIT_END]() {
    if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF]) {
      this[EMITTING_END] = true;
      this.emit("end");
      this.emit("prefinish");
      this.emit("finish");
      if (this[CLOSED])
        this.emit("close");
      this[EMITTING_END] = false;
    }
  }
  /**
   * Mostly identical to `EventEmitter.emit`, with the following
   * behavior differences to prevent data loss and unnecessary hangs:
   *
   * If the stream has been destroyed, and the event is something other
   * than 'close' or 'error', then `false` is returned and no handlers
   * are called.
   *
   * If the event is 'end', and has already been emitted, then the event
   * is ignored. If the stream is in a paused or non-flowing state, then
   * the event will be deferred until data flow resumes. If the stream is
   * async, then handlers will be called on the next tick rather than
   * immediately.
   *
   * If the event is 'close', and 'end' has not yet been emitted, then
   * the event will be deferred until after 'end' is emitted.
   *
   * If the event is 'error', and an AbortSignal was provided for the stream,
   * and there are no listeners, then the event is ignored, matching the
   * behavior of node core streams in the presense of an AbortSignal.
   *
   * If the event is 'finish' or 'prefinish', then all listeners will be
   * removed after emitting the event, to prevent double-firing.
   */
  emit(ev, ...args) {
    const data = args[0];
    if (ev !== "error" && ev !== "close" && ev !== DESTROYED && this[DESTROYED]) {
      return false;
    } else if (ev === "data") {
      return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? (defer(() => this[EMITDATA](data)), true) : this[EMITDATA](data);
    } else if (ev === "end") {
      return this[EMITEND]();
    } else if (ev === "close") {
      this[CLOSED] = true;
      if (!this[EMITTED_END] && !this[DESTROYED])
        return false;
      const ret2 = super.emit("close");
      this.removeAllListeners("close");
      return ret2;
    } else if (ev === "error") {
      this[EMITTED_ERROR] = data;
      super.emit(ERROR, data);
      const ret2 = !this[SIGNAL] || this.listeners("error").length ? super.emit("error", data) : false;
      this[MAYBE_EMIT_END]();
      return ret2;
    } else if (ev === "resume") {
      const ret2 = super.emit("resume");
      this[MAYBE_EMIT_END]();
      return ret2;
    } else if (ev === "finish" || ev === "prefinish") {
      const ret2 = super.emit(ev);
      this.removeAllListeners(ev);
      return ret2;
    }
    const ret = super.emit(ev, ...args);
    this[MAYBE_EMIT_END]();
    return ret;
  }
  [EMITDATA](data) {
    for (const p of this[PIPES]) {
      if (p.dest.write(data) === false)
        this.pause();
    }
    const ret = this[DISCARDED] ? false : super.emit("data", data);
    this[MAYBE_EMIT_END]();
    return ret;
  }
  [EMITEND]() {
    if (this[EMITTED_END])
      return false;
    this[EMITTED_END] = true;
    this.readable = false;
    return this[ASYNC] ? (defer(() => this[EMITEND2]()), true) : this[EMITEND2]();
  }
  [EMITEND2]() {
    if (this[DECODER]) {
      const data = this[DECODER].end();
      if (data) {
        for (const p of this[PIPES]) {
          p.dest.write(data);
        }
        if (!this[DISCARDED])
          super.emit("data", data);
      }
    }
    for (const p of this[PIPES]) {
      p.end();
    }
    const ret = super.emit("end");
    this.removeAllListeners("end");
    return ret;
  }
  /**
   * Return a Promise that resolves to an array of all emitted data once
   * the stream ends.
   */
  async collect() {
    const buf = Object.assign([], {
      dataLength: 0
    });
    if (!this[OBJECTMODE])
      buf.dataLength = 0;
    const p = this.promise();
    this.on("data", (c) => {
      buf.push(c);
      if (!this[OBJECTMODE])
        buf.dataLength += c.length;
    });
    await p;
    return buf;
  }
  /**
   * Return a Promise that resolves to the concatenation of all emitted data
   * once the stream ends.
   *
   * Not allowed on objectMode streams.
   */
  async concat() {
    if (this[OBJECTMODE]) {
      throw new Error("cannot concat in objectMode");
    }
    const buf = await this.collect();
    return this[ENCODING] ? buf.join("") : Buffer.concat(buf, buf.dataLength);
  }
  /**
   * Return a void Promise that resolves once the stream ends.
   */
  async promise() {
    return new Promise((resolve6, reject) => {
      this.on(DESTROYED, () => reject(new Error("stream destroyed")));
      this.on("error", (er) => reject(er));
      this.on("end", () => resolve6());
    });
  }
  /**
   * Asynchronous `for await of` iteration.
   *
   * This will continue emitting all chunks until the stream terminates.
   */
  [Symbol.asyncIterator]() {
    this[DISCARDED] = false;
    let stopped = false;
    const stop = async () => {
      this.pause();
      stopped = true;
      return { value: void 0, done: true };
    };
    const next = () => {
      if (stopped)
        return stop();
      const res = this.read();
      if (res !== null)
        return Promise.resolve({ done: false, value: res });
      if (this[EOF])
        return stop();
      let resolve6;
      let reject;
      const onerr = (er) => {
        this.off("data", ondata);
        this.off("end", onend);
        this.off(DESTROYED, ondestroy);
        stop();
        reject(er);
      };
      const ondata = (value) => {
        this.off("error", onerr);
        this.off("end", onend);
        this.off(DESTROYED, ondestroy);
        this.pause();
        resolve6({ value, done: !!this[EOF] });
      };
      const onend = () => {
        this.off("error", onerr);
        this.off("data", ondata);
        this.off(DESTROYED, ondestroy);
        stop();
        resolve6({ done: true, value: void 0 });
      };
      const ondestroy = () => onerr(new Error("stream destroyed"));
      return new Promise((res2, rej) => {
        reject = rej;
        resolve6 = res2;
        this.once(DESTROYED, ondestroy);
        this.once("error", onerr);
        this.once("end", onend);
        this.once("data", ondata);
      });
    };
    return {
      next,
      throw: stop,
      return: stop,
      [Symbol.asyncIterator]() {
        return this;
      }
    };
  }
  /**
   * Synchronous `for of` iteration.
   *
   * The iteration will terminate when the internal buffer runs out, even
   * if the stream has not yet terminated.
   */
  [Symbol.iterator]() {
    this[DISCARDED] = false;
    let stopped = false;
    const stop = () => {
      this.pause();
      this.off(ERROR, stop);
      this.off(DESTROYED, stop);
      this.off("end", stop);
      stopped = true;
      return { done: true, value: void 0 };
    };
    const next = () => {
      if (stopped)
        return stop();
      const value = this.read();
      return value === null ? stop() : { done: false, value };
    };
    this.once("end", stop);
    this.once(ERROR, stop);
    this.once(DESTROYED, stop);
    return {
      next,
      throw: stop,
      return: stop,
      [Symbol.iterator]() {
        return this;
      }
    };
  }
  /**
   * Destroy a stream, preventing it from being used for any further purpose.
   *
   * If the stream has a `close()` method, then it will be called on
   * destruction.
   *
   * After destruction, any attempt to write data, read data, or emit most
   * events will be ignored.
   *
   * If an error argument is provided, then it will be emitted in an
   * 'error' event.
   */
  destroy(er) {
    if (this[DESTROYED]) {
      if (er)
        this.emit("error", er);
      else
        this.emit(DESTROYED);
      return this;
    }
    this[DESTROYED] = true;
    this[DISCARDED] = true;
    this[BUFFER].length = 0;
    this[BUFFERLENGTH] = 0;
    const wc = this;
    if (typeof wc.close === "function" && !this[CLOSED])
      wc.close();
    if (er)
      this.emit("error", er);
    else
      this.emit(DESTROYED);
    return this;
  }
  /**
   * Alias for {@link isStream}
   *
   * Former export location, maintained for backwards compatibility.
   *
   * @deprecated
   */
  static get isStream() {
    return isStream;
  }
};

// node_modules/path-scurry/dist/esm/index.js
var realpathSync = import_fs.realpathSync.native;
var defaultFS = {
  lstatSync: import_fs.lstatSync,
  readdir: import_fs.readdir,
  readdirSync: import_fs.readdirSync,
  readlinkSync: import_fs.readlinkSync,
  realpathSync,
  promises: {
    lstat: import_promises.lstat,
    readdir: import_promises.readdir,
    readlink: import_promises.readlink,
    realpath: import_promises.realpath
  }
};
var fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ? defaultFS : {
  ...defaultFS,
  ...fsOption,
  promises: {
    ...defaultFS.promises,
    ...fsOption.promises || {}
  }
};
var uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
var uncToDrive = (rootPath) => rootPath.replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
var eitherSep = /[\\\/]/;
var UNKNOWN = 0;
var IFIFO = 1;
var IFCHR = 2;
var IFDIR = 4;
var IFBLK = 6;
var IFREG = 8;
var IFLNK = 10;
var IFSOCK = 12;
var IFMT = 15;
var IFMT_UNKNOWN = ~IFMT;
var READDIR_CALLED = 16;
var LSTAT_CALLED = 32;
var ENOTDIR = 64;
var ENOENT = 128;
var ENOREADLINK = 256;
var ENOREALPATH = 512;
var ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
var TYPEMASK = 1023;
var entToType = (s) => s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN;
var normalizeCache = /* @__PURE__ */ new Map();
var normalize = (s) => {
  const c = normalizeCache.get(s);
  if (c)
    return c;
  const n = s.normalize("NFKD");
  normalizeCache.set(s, n);
  return n;
};
var normalizeNocaseCache = /* @__PURE__ */ new Map();
var normalizeNocase = (s) => {
  const c = normalizeNocaseCache.get(s);
  if (c)
    return c;
  const n = normalize(s.toLowerCase());
  normalizeNocaseCache.set(s, n);
  return n;
};
var ResolveCache = class extends LRUCache {
  constructor() {
    super({ max: 256 });
  }
};
var ChildrenCache = class extends LRUCache {
  constructor(maxSize = 16 * 1024) {
    super({
      maxSize,
      // parent + children
      sizeCalculation: (a) => a.length + 1
    });
  }
};
var setAsCwd = Symbol("PathScurry setAsCwd");
var PathBase = class {
  /**
   * the basename of this path
   *
   * **Important**: *always* test the path name against any test string
   * usingthe {@link isNamed} method, and not by directly comparing this
   * string. Otherwise, unicode path strings that the system sees as identical
   * will not be properly treated as the same path, leading to incorrect
   * behavior and possible security issues.
   */
  name;
  /**
   * the Path entry corresponding to the path root.
   *
   * @internal
   */
  root;
  /**
   * All roots found within the current PathScurry family
   *
   * @internal
   */
  roots;
  /**
   * a reference to the parent path, or undefined in the case of root entries
   *
   * @internal
   */
  parent;
  /**
   * boolean indicating whether paths are compared case-insensitively
   * @internal
   */
  nocase;
  /**
   * boolean indicating that this path is the current working directory
   * of the PathScurry collection that contains it.
   */
  isCWD = false;
  // potential default fs override
  #fs;
  // Stats fields
  #dev;
  get dev() {
    return this.#dev;
  }
  #mode;
  get mode() {
    return this.#mode;
  }
  #nlink;
  get nlink() {
    return this.#nlink;
  }
  #uid;
  get uid() {
    return this.#uid;
  }
  #gid;
  get gid() {
    return this.#gid;
  }
  #rdev;
  get rdev() {
    return this.#rdev;
  }
  #blksize;
  get blksize() {
    return this.#blksize;
  }
  #ino;
  get ino() {
    return this.#ino;
  }
  #size;
  get size() {
    return this.#size;
  }
  #blocks;
  get blocks() {
    return this.#blocks;
  }
  #atimeMs;
  get atimeMs() {
    return this.#atimeMs;
  }
  #mtimeMs;
  get mtimeMs() {
    return this.#mtimeMs;
  }
  #ctimeMs;
  get ctimeMs() {
    return this.#ctimeMs;
  }
  #birthtimeMs;
  get birthtimeMs() {
    return this.#birthtimeMs;
  }
  #atime;
  get atime() {
    return this.#atime;
  }
  #mtime;
  get mtime() {
    return this.#mtime;
  }
  #ctime;
  get ctime() {
    return this.#ctime;
  }
  #birthtime;
  get birthtime() {
    return this.#birthtime;
  }
  #matchName;
  #depth;
  #fullpath;
  #fullpathPosix;
  #relative;
  #relativePosix;
  #type;
  #children;
  #linkTarget;
  #realpath;
  /**
   * This property is for compatibility with the Dirent class as of
   * Node v20, where Dirent['parentPath'] refers to the path of the
   * directory that was passed to readdir. For root entries, it's the path
   * to the entry itself.
   */
  get parentPath() {
    return (this.parent || this).fullpath();
  }
  /**
   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
   * this property refers to the *parent* path, not the path object itself.
   */
  get path() {
    return this.parentPath;
  }
  /**
   * Do not create new Path objects directly.  They should always be accessed
   * via the PathScurry class or other methods on the Path class.
   *
   * @internal
   */
  constructor(name, type = UNKNOWN, root2, roots, nocase, children, opts) {
    this.name = name;
    this.#matchName = nocase ? normalizeNocase(name) : normalize(name);
    this.#type = type & TYPEMASK;
    this.nocase = nocase;
    this.roots = roots;
    this.root = root2 || this;
    this.#children = children;
    this.#fullpath = opts.fullpath;
    this.#relative = opts.relative;
    this.#relativePosix = opts.relativePosix;
    this.parent = opts.parent;
    if (this.parent) {
      this.#fs = this.parent.#fs;
    } else {
      this.#fs = fsFromOption(opts.fs);
    }
  }
  /**
   * Returns the depth of the Path object from its root.
   *
   * For example, a path at `/foo/bar` would have a depth of 2.
   */
  depth() {
    if (this.#depth !== void 0)
      return this.#depth;
    if (!this.parent)
      return this.#depth = 0;
    return this.#depth = this.parent.depth() + 1;
  }
  /**
   * @internal
   */
  childrenCache() {
    return this.#children;
  }
  /**
   * Get the Path object referenced by the string path, resolved from this Path
   */
  resolve(path3) {
    if (!path3) {
      return this;
    }
    const rootPath = this.getRootString(path3);
    const dir = path3.substring(rootPath.length);
    const dirParts = dir.split(this.splitSep);
    const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
    return result;
  }
  #resolveParts(dirParts) {
    let p = this;
    for (const part of dirParts) {
      p = p.child(part);
    }
    return p;
  }
  /**
   * Returns the cached children Path objects, if still available.  If they
   * have fallen out of the cache, then returns an empty array, and resets the
   * READDIR_CALLED bit, so that future calls to readdir() will require an fs
   * lookup.
   *
   * @internal
   */
  children() {
    const cached = this.#children.get(this);
    if (cached) {
      return cached;
    }
    const children = Object.assign([], { provisional: 0 });
    this.#children.set(this, children);
    this.#type &= ~READDIR_CALLED;
    return children;
  }
  /**
   * Resolves a path portion and returns or creates the child Path.
   *
   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
   * `'..'`.
   *
   * This should not be called directly.  If `pathPart` contains any path
   * separators, it will lead to unsafe undefined behavior.
   *
   * Use `Path.resolve()` instead.
   *
   * @internal
   */
  child(pathPart, opts) {
    if (pathPart === "" || pathPart === ".") {
      return this;
    }
    if (pathPart === "..") {
      return this.parent || this;
    }
    const children = this.children();
    const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart);
    for (const p of children) {
      if (p.#matchName === name) {
        return p;
      }
    }
    const s = this.parent ? this.sep : "";
    const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : void 0;
    const pchild = this.newChild(pathPart, UNKNOWN, {
      ...opts,
      parent: this,
      fullpath
    });
    if (!this.canReaddir()) {
      pchild.#type |= ENOENT;
    }
    children.push(pchild);
    return pchild;
  }
  /**
   * The relative path from the cwd. If it does not share an ancestor with
   * the cwd, then this ends up being equivalent to the fullpath()
   */
  relative() {
    if (this.isCWD)
      return "";
    if (this.#relative !== void 0) {
      return this.#relative;
    }
    const name = this.name;
    const p = this.parent;
    if (!p) {
      return this.#relative = this.name;
    }
    const pv = p.relative();
    return pv + (!pv || !p.parent ? "" : this.sep) + name;
  }
  /**
   * The relative path from the cwd, using / as the path separator.
   * If it does not share an ancestor with
   * the cwd, then this ends up being equivalent to the fullpathPosix()
   * On posix systems, this is identical to relative().
   */
  relativePosix() {
    if (this.sep === "/")
      return this.relative();
    if (this.isCWD)
      return "";
    if (this.#relativePosix !== void 0)
      return this.#relativePosix;
    const name = this.name;
    const p = this.parent;
    if (!p) {
      return this.#relativePosix = this.fullpathPosix();
    }
    const pv = p.relativePosix();
    return pv + (!pv || !p.parent ? "" : "/") + name;
  }
  /**
   * The fully resolved path string for this Path entry
   */
  fullpath() {
    if (this.#fullpath !== void 0) {
      return this.#fullpath;
    }
    const name = this.name;
    const p = this.parent;
    if (!p) {
      return this.#fullpath = this.name;
    }
    const pv = p.fullpath();
    const fp = pv + (!p.parent ? "" : this.sep) + name;
    return this.#fullpath = fp;
  }
  /**
   * On platforms other than windows, this is identical to fullpath.
   *
   * On windows, this is overridden to return the forward-slash form of the
   * full UNC path.
   */
  fullpathPosix() {
    if (this.#fullpathPosix !== void 0)
      return this.#fullpathPosix;
    if (this.sep === "/")
      return this.#fullpathPosix = this.fullpath();
    if (!this.parent) {
      const p2 = this.fullpath().replace(/\\/g, "/");
      if (/^[a-z]:\//i.test(p2)) {
        return this.#fullpathPosix = `//?/${p2}`;
      } else {
        return this.#fullpathPosix = p2;
      }
    }
    const p = this.parent;
    const pfpp = p.fullpathPosix();
    const fpp = pfpp + (!pfpp || !p.parent ? "" : "/") + this.name;
    return this.#fullpathPosix = fpp;
  }
  /**
   * Is the Path of an unknown type?
   *
   * Note that we might know *something* about it if there has been a previous
   * filesystem operation, for example that it does not exist, or is not a
   * link, or whether it has child entries.
   */
  isUnknown() {
    return (this.#type & IFMT) === UNKNOWN;
  }
  isType(type) {
    return this[`is${type}`]();
  }
  getType() {
    return this.isUnknown() ? "Unknown" : this.isDirectory() ? "Directory" : this.isFile() ? "File" : this.isSymbolicLink() ? "SymbolicLink" : this.isFIFO() ? "FIFO" : this.isCharacterDevice() ? "CharacterDevice" : this.isBlockDevice() ? "BlockDevice" : (
      /* c8 ignore start */
      this.isSocket() ? "Socket" : "Unknown"
    );
  }
  /**
   * Is the Path a regular file?
   */
  isFile() {
    return (this.#type & IFMT) === IFREG;
  }
  /**
   * Is the Path a directory?
   */
  isDirectory() {
    return (this.#type & IFMT) === IFDIR;
  }
  /**
   * Is the path a character device?
   */
  isCharacterDevice() {
    return (this.#type & IFMT) === IFCHR;
  }
  /**
   * Is the path a block device?
   */
  isBlockDevice() {
    return (this.#type & IFMT) === IFBLK;
  }
  /**
   * Is the path a FIFO pipe?
   */
  isFIFO() {
    return (this.#type & IFMT) === IFIFO;
  }
  /**
   * Is the path a socket?
   */
  isSocket() {
    return (this.#type & IFMT) === IFSOCK;
  }
  /**
   * Is the path a symbolic link?
   */
  isSymbolicLink() {
    return (this.#type & IFLNK) === IFLNK;
  }
  /**
   * Return the entry if it has been subject of a successful lstat, or
   * undefined otherwise.
   *
   * Does not read the filesystem, so an undefined result *could* simply
   * mean that we haven't called lstat on it.
   */
  lstatCached() {
    return this.#type & LSTAT_CALLED ? this : void 0;
  }
  /**
   * Return the cached link target if the entry has been the subject of a
   * successful readlink, or undefined otherwise.
   *
   * Does not read the filesystem, so an undefined result *could* just mean we
   * don't have any cached data. Only use it if you are very sure that a
   * readlink() has been called at some point.
   */
  readlinkCached() {
    return this.#linkTarget;
  }
  /**
   * Returns the cached realpath target if the entry has been the subject
   * of a successful realpath, or undefined otherwise.
   *
   * Does not read the filesystem, so an undefined result *could* just mean we
   * don't have any cached data. Only use it if you are very sure that a
   * realpath() has been called at some point.
   */
  realpathCached() {
    return this.#realpath;
  }
  /**
   * Returns the cached child Path entries array if the entry has been the
   * subject of a successful readdir(), or [] otherwise.
   *
   * Does not read the filesystem, so an empty array *could* just mean we
   * don't have any cached data. Only use it if you are very sure that a
   * readdir() has been called recently enough to still be valid.
   */
  readdirCached() {
    const children = this.children();
    return children.slice(0, children.provisional);
  }
  /**
   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have
   * any indication that readlink will definitely fail.
   *
   * Returns false if the path is known to not be a symlink, if a previous
   * readlink failed, or if the entry does not exist.
   */
  canReadlink() {
    if (this.#linkTarget)
      return true;
    if (!this.parent)
      return false;
    const ifmt = this.#type & IFMT;
    return !(ifmt !== UNKNOWN && ifmt !== IFLNK || this.#type & ENOREADLINK || this.#type & ENOENT);
  }
  /**
   * Return true if readdir has previously been successfully called on this
   * path, indicating that cachedReaddir() is likely valid.
   */
  calledReaddir() {
    return !!(this.#type & READDIR_CALLED);
  }
  /**
   * Returns true if the path is known to not exist. That is, a previous lstat
   * or readdir failed to verify its existence when that would have been
   * expected, or a parent entry was marked either enoent or enotdir.
   */
  isENOENT() {
    return !!(this.#type & ENOENT);
  }
  /**
   * Return true if the path is a match for the given path name.  This handles
   * case sensitivity and unicode normalization.
   *
   * Note: even on case-sensitive systems, it is **not** safe to test the
   * equality of the `.name` property to determine whether a given pathname
   * matches, due to unicode normalization mismatches.
   *
   * Always use this method instead of testing the `path.name` property
   * directly.
   */
  isNamed(n) {
    return !this.nocase ? this.#matchName === normalize(n) : this.#matchName === normalizeNocase(n);
  }
  /**
   * Return the Path object corresponding to the target of a symbolic link.
   *
   * If the Path is not a symbolic link, or if the readlink call fails for any
   * reason, `undefined` is returned.
   *
   * Result is cached, and thus may be outdated if the filesystem is mutated.
   */
  async readlink() {
    var _a2;
    const target = this.#linkTarget;
    if (target) {
      return target;
    }
    if (!this.canReadlink()) {
      return void 0;
    }
    if (!this.parent) {
      return void 0;
    }
    try {
      const read = await this.#fs.promises.readlink(this.fullpath());
      const linkTarget = (_a2 = await this.parent.realpath()) == null ? void 0 : _a2.resolve(read);
      if (linkTarget) {
        return this.#linkTarget = linkTarget;
      }
    } catch (er) {
      this.#readlinkFail(er.code);
      return void 0;
    }
  }
  /**
   * Synchronous {@link PathBase.readlink}
   */
  readlinkSync() {
    var _a2;
    const target = this.#linkTarget;
    if (target) {
      return target;
    }
    if (!this.canReadlink()) {
      return void 0;
    }
    if (!this.parent) {
      return void 0;
    }
    try {
      const read = this.#fs.readlinkSync(this.fullpath());
      const linkTarget = (_a2 = this.parent.realpathSync()) == null ? void 0 : _a2.resolve(read);
      if (linkTarget) {
        return this.#linkTarget = linkTarget;
      }
    } catch (er) {
      this.#readlinkFail(er.code);
      return void 0;
    }
  }
  #readdirSuccess(children) {
    this.#type |= READDIR_CALLED;
    for (let p = children.provisional; p < children.length; p++) {
      const c = children[p];
      if (c)
        c.#markENOENT();
    }
  }
  #markENOENT() {
    if (this.#type & ENOENT)
      return;
    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN;
    this.#markChildrenENOENT();
  }
  #markChildrenENOENT() {
    const children = this.children();
    children.provisional = 0;
    for (const p of children) {
      p.#markENOENT();
    }
  }
  #markENOREALPATH() {
    this.#type |= ENOREALPATH;
    this.#markENOTDIR();
  }
  // save the information when we know the entry is not a dir
  #markENOTDIR() {
    if (this.#type & ENOTDIR)
      return;
    let t = this.#type;
    if ((t & IFMT) === IFDIR)
      t &= IFMT_UNKNOWN;
    this.#type = t | ENOTDIR;
    this.#markChildrenENOENT();
  }
  #readdirFail(code = "") {
    if (code === "ENOTDIR" || code === "EPERM") {
      this.#markENOTDIR();
    } else if (code === "ENOENT") {
      this.#markENOENT();
    } else {
      this.children().provisional = 0;
    }
  }
  #lstatFail(code = "") {
    if (code === "ENOTDIR") {
      const p = this.parent;
      p.#markENOTDIR();
    } else if (code === "ENOENT") {
      this.#markENOENT();
    }
  }
  #readlinkFail(code = "") {
    let ter = this.#type;
    ter |= ENOREADLINK;
    if (code === "ENOENT")
      ter |= ENOENT;
    if (code === "EINVAL" || code === "UNKNOWN") {
      ter &= IFMT_UNKNOWN;
    }
    this.#type = ter;
    if (code === "ENOTDIR" && this.parent) {
      this.parent.#markENOTDIR();
    }
  }
  #readdirAddChild(e, c) {
    return this.#readdirMaybePromoteChild(e, c) || this.#readdirAddNewChild(e, c);
  }
  #readdirAddNewChild(e, c) {
    const type = entToType(e);
    const child = this.newChild(e.name, type, { parent: this });
    const ifmt = child.#type & IFMT;
    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
      child.#type |= ENOTDIR;
    }
    c.unshift(child);
    c.provisional++;
    return child;
  }
  #readdirMaybePromoteChild(e, c) {
    for (let p = c.provisional; p < c.length; p++) {
      const pchild = c[p];
      const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name);
      if (name !== pchild.#matchName) {
        continue;
      }
      return this.#readdirPromoteChild(e, pchild, p, c);
    }
  }
  #readdirPromoteChild(e, p, index, c) {
    const v = p.name;
    p.#type = p.#type & IFMT_UNKNOWN | entToType(e);
    if (v !== e.name)
      p.name = e.name;
    if (index !== c.provisional) {
      if (index === c.length - 1)
        c.pop();
      else
        c.splice(index, 1);
      c.unshift(p);
    }
    c.provisional++;
    return p;
  }
  /**
   * Call lstat() on this Path, and update all known information that can be
   * determined.
   *
   * Note that unlike `fs.lstat()`, the returned value does not contain some
   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
   * information is required, you will need to call `fs.lstat` yourself.
   *
   * If the Path refers to a nonexistent file, or if the lstat call fails for
   * any reason, `undefined` is returned.  Otherwise the updated Path object is
   * returned.
   *
   * Results are cached, and thus may be out of date if the filesystem is
   * mutated.
   */
  async lstat() {
    if ((this.#type & ENOENT) === 0) {
      try {
        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()));
        return this;
      } catch (er) {
        this.#lstatFail(er.code);
      }
    }
  }
  /**
   * synchronous {@link PathBase.lstat}
   */
  lstatSync() {
    if ((this.#type & ENOENT) === 0) {
      try {
        this.#applyStat(this.#fs.lstatSync(this.fullpath()));
        return this;
      } catch (er) {
        this.#lstatFail(er.code);
      }
    }
  }
  #applyStat(st) {
    const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid } = st;
    this.#atime = atime;
    this.#atimeMs = atimeMs;
    this.#birthtime = birthtime;
    this.#birthtimeMs = birthtimeMs;
    this.#blksize = blksize;
    this.#blocks = blocks;
    this.#ctime = ctime;
    this.#ctimeMs = ctimeMs;
    this.#dev = dev;
    this.#gid = gid;
    this.#ino = ino;
    this.#mode = mode;
    this.#mtime = mtime;
    this.#mtimeMs = mtimeMs;
    this.#nlink = nlink;
    this.#rdev = rdev;
    this.#size = size;
    this.#uid = uid;
    const ifmt = entToType(st);
    this.#type = this.#type & IFMT_UNKNOWN | ifmt | LSTAT_CALLED;
    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
      this.#type |= ENOTDIR;
    }
  }
  #onReaddirCB = [];
  #readdirCBInFlight = false;
  #callOnReaddirCB(children) {
    this.#readdirCBInFlight = false;
    const cbs = this.#onReaddirCB.slice();
    this.#onReaddirCB.length = 0;
    cbs.forEach((cb) => cb(null, children));
  }
  /**
   * Standard node-style callback interface to get list of directory entries.
   *
   * If the Path cannot or does not contain any children, then an empty array
   * is returned.
   *
   * Results are cached, and thus may be out of date if the filesystem is
   * mutated.
   *
   * @param cb The callback called with (er, entries).  Note that the `er`
   * param is somewhat extraneous, as all readdir() errors are handled and
   * simply result in an empty set of entries being returned.
   * @param allowZalgo Boolean indicating that immediately known results should
   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
   * zalgo at your peril, the dark pony lord is devious and unforgiving.
   */
  readdirCB(cb, allowZalgo = false) {
    if (!this.canReaddir()) {
      if (allowZalgo)
        cb(null, []);
      else
        queueMicrotask(() => cb(null, []));
      return;
    }
    const children = this.children();
    if (this.calledReaddir()) {
      const c = children.slice(0, children.provisional);
      if (allowZalgo)
        cb(null, c);
      else
        queueMicrotask(() => cb(null, c));
      return;
    }
    this.#onReaddirCB.push(cb);
    if (this.#readdirCBInFlight) {
      return;
    }
    this.#readdirCBInFlight = true;
    const fullpath = this.fullpath();
    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {
      if (er) {
        this.#readdirFail(er.code);
        children.provisional = 0;
      } else {
        for (const e of entries) {
          this.#readdirAddChild(e, children);
        }
        this.#readdirSuccess(children);
      }
      this.#callOnReaddirCB(children.slice(0, children.provisional));
      return;
    });
  }
  #asyncReaddirInFlight;
  /**
   * Return an array of known child entries.
   *
   * If the Path cannot or does not contain any children, then an empty array
   * is returned.
   *
   * Results are cached, and thus may be out of date if the filesystem is
   * mutated.
   */
  async readdir() {
    if (!this.canReaddir()) {
      return [];
    }
    const children = this.children();
    if (this.calledReaddir()) {
      return children.slice(0, children.provisional);
    }
    const fullpath = this.fullpath();
    if (this.#asyncReaddirInFlight) {
      await this.#asyncReaddirInFlight;
    } else {
      let resolve6 = () => {
      };
      this.#asyncReaddirInFlight = new Promise((res) => resolve6 = res);
      try {
        for (const e of await this.#fs.promises.readdir(fullpath, {
          withFileTypes: true
        })) {
          this.#readdirAddChild(e, children);
        }
        this.#readdirSuccess(children);
      } catch (er) {
        this.#readdirFail(er.code);
        children.provisional = 0;
      }
      this.#asyncReaddirInFlight = void 0;
      resolve6();
    }
    return children.slice(0, children.provisional);
  }
  /**
   * synchronous {@link PathBase.readdir}
   */
  readdirSync() {
    if (!this.canReaddir()) {
      return [];
    }
    const children = this.children();
    if (this.calledReaddir()) {
      return children.slice(0, children.provisional);
    }
    const fullpath = this.fullpath();
    try {
      for (const e of this.#fs.readdirSync(fullpath, {
        withFileTypes: true
      })) {
        this.#readdirAddChild(e, children);
      }
      this.#readdirSuccess(children);
    } catch (er) {
      this.#readdirFail(er.code);
      children.provisional = 0;
    }
    return children.slice(0, children.provisional);
  }
  canReaddir() {
    if (this.#type & ENOCHILD)
      return false;
    const ifmt = IFMT & this.#type;
    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
      return false;
    }
    return true;
  }
  shouldWalk(dirs, walkFilter) {
    return (this.#type & IFDIR) === IFDIR && !(this.#type & ENOCHILD) && !dirs.has(this) && (!walkFilter || walkFilter(this));
  }
  /**
   * Return the Path object corresponding to path as resolved
   * by realpath(3).
   *
   * If the realpath call fails for any reason, `undefined` is returned.
   *
   * Result is cached, and thus may be outdated if the filesystem is mutated.
   * On success, returns a Path object.
   */
  async realpath() {
    if (this.#realpath)
      return this.#realpath;
    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
      return void 0;
    try {
      const rp = await this.#fs.promises.realpath(this.fullpath());
      return this.#realpath = this.resolve(rp);
    } catch (_) {
      this.#markENOREALPATH();
    }
  }
  /**
   * Synchronous {@link realpath}
   */
  realpathSync() {
    if (this.#realpath)
      return this.#realpath;
    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type)
      return void 0;
    try {
      const rp = this.#fs.realpathSync(this.fullpath());
      return this.#realpath = this.resolve(rp);
    } catch (_) {
      this.#markENOREALPATH();
    }
  }
  /**
   * Internal method to mark this Path object as the scurry cwd,
   * called by {@link PathScurry#chdir}
   *
   * @internal
   */
  [setAsCwd](oldCwd) {
    if (oldCwd === this)
      return;
    oldCwd.isCWD = false;
    this.isCWD = true;
    const changed = /* @__PURE__ */ new Set([]);
    let rp = [];
    let p = this;
    while (p && p.parent) {
      changed.add(p);
      p.#relative = rp.join(this.sep);
      p.#relativePosix = rp.join("/");
      p = p.parent;
      rp.push("..");
    }
    p = oldCwd;
    while (p && p.parent && !changed.has(p)) {
      p.#relative = void 0;
      p.#relativePosix = void 0;
      p = p.parent;
    }
  }
};
var PathWin32 = class _PathWin32 extends PathBase {
  /**
   * Separator for generating path strings.
   */
  sep = "\\";
  /**
   * Separator for parsing path strings.
   */
  splitSep = eitherSep;
  /**
   * Do not create new Path objects directly.  They should always be accessed
   * via the PathScurry class or other methods on the Path class.
   *
   * @internal
   */
  constructor(name, type = UNKNOWN, root2, roots, nocase, children, opts) {
    super(name, type, root2, roots, nocase, children, opts);
  }
  /**
   * @internal
   */
  newChild(name, type = UNKNOWN, opts = {}) {
    return new _PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
  }
  /**
   * @internal
   */
  getRootString(path3) {
    return import_node_path.win32.parse(path3).root;
  }
  /**
   * @internal
   */
  getRoot(rootPath) {
    rootPath = uncToDrive(rootPath.toUpperCase());
    if (rootPath === this.root.name) {
      return this.root;
    }
    for (const [compare, root2] of Object.entries(this.roots)) {
      if (this.sameRoot(rootPath, compare)) {
        return this.roots[rootPath] = root2;
      }
    }
    return this.roots[rootPath] = new PathScurryWin32(rootPath, this).root;
  }
  /**
   * @internal
   */
  sameRoot(rootPath, compare = this.root.name) {
    rootPath = rootPath.toUpperCase().replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
    return rootPath === compare;
  }
};
var PathPosix = class _PathPosix extends PathBase {
  /**
   * separator for parsing path strings
   */
  splitSep = "/";
  /**
   * separator for generating path strings
   */
  sep = "/";
  /**
   * Do not create new Path objects directly.  They should always be accessed
   * via the PathScurry class or other methods on the Path class.
   *
   * @internal
   */
  constructor(name, type = UNKNOWN, root2, roots, nocase, children, opts) {
    super(name, type, root2, roots, nocase, children, opts);
  }
  /**
   * @internal
   */
  getRootString(path3) {
    return path3.startsWith("/") ? "/" : "";
  }
  /**
   * @internal
   */
  getRoot(_rootPath) {
    return this.root;
  }
  /**
   * @internal
   */
  newChild(name, type = UNKNOWN, opts = {}) {
    return new _PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
  }
};
var PathScurryBase = class {
  /**
   * The root Path entry for the current working directory of this Scurry
   */
  root;
  /**
   * The string path for the root of this Scurry's current working directory
   */
  rootPath;
  /**
   * A collection of all roots encountered, referenced by rootPath
   */
  roots;
  /**
   * The Path entry corresponding to this PathScurry's current working directory.
   */
  cwd;
  #resolveCache;
  #resolvePosixCache;
  #children;
  /**
   * Perform path comparisons case-insensitively.
   *
   * Defaults true on Darwin and Windows systems, false elsewhere.
   */
  nocase;
  #fs;
  /**
   * This class should not be instantiated directly.
   *
   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
   *
   * @internal
   */
  constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs4 = defaultFS } = {}) {
    this.#fs = fsFromOption(fs4);
    if (cwd instanceof URL || cwd.startsWith("file://")) {
      cwd = (0, import_node_url.fileURLToPath)(cwd);
    }
    const cwdPath = pathImpl.resolve(cwd);
    this.roots = /* @__PURE__ */ Object.create(null);
    this.rootPath = this.parseRootPath(cwdPath);
    this.#resolveCache = new ResolveCache();
    this.#resolvePosixCache = new ResolveCache();
    this.#children = new ChildrenCache(childrenCacheSize);
    const split = cwdPath.substring(this.rootPath.length).split(sep2);
    if (split.length === 1 && !split[0]) {
      split.pop();
    }
    if (nocase === void 0) {
      throw new TypeError("must provide nocase setting to PathScurryBase ctor");
    }
    this.nocase = nocase;
    this.root = this.newRoot(this.#fs);
    this.roots[this.rootPath] = this.root;
    let prev = this.root;
    let len = split.length - 1;
    const joinSep = pathImpl.sep;
    let abs = this.rootPath;
    let sawFirst = false;
    for (const part of split) {
      const l = len--;
      prev = prev.child(part, {
        relative: new Array(l).fill("..").join(joinSep),
        relativePosix: new Array(l).fill("..").join("/"),
        fullpath: abs += (sawFirst ? "" : joinSep) + part
      });
      sawFirst = true;
    }
    this.cwd = prev;
  }
  /**
   * Get the depth of a provided path, string, or the cwd
   */
  depth(path3 = this.cwd) {
    if (typeof path3 === "string") {
      path3 = this.cwd.resolve(path3);
    }
    return path3.depth();
  }
  /**
   * Return the cache of child entries.  Exposed so subclasses can create
   * child Path objects in a platform-specific way.
   *
   * @internal
   */
  childrenCache() {
    return this.#children;
  }
  /**
   * Resolve one or more path strings to a resolved string
   *
   * Same interface as require('path').resolve.
   *
   * Much faster than path.resolve() when called multiple times for the same
   * path, because the resolved Path objects are cached.  Much slower
   * otherwise.
   */
  resolve(...paths) {
    let r = "";
    for (let i = paths.length - 1; i >= 0; i--) {
      const p = paths[i];
      if (!p || p === ".")
        continue;
      r = r ? `${p}/${r}` : p;
      if (this.isAbsolute(p)) {
        break;
      }
    }
    const cached = this.#resolveCache.get(r);
    if (cached !== void 0) {
      return cached;
    }
    const result = this.cwd.resolve(r).fullpath();
    this.#resolveCache.set(r, result);
    return result;
  }
  /**
   * Resolve one or more path strings to a resolved string, returning
   * the posix path.  Identical to .resolve() on posix systems, but on
   * windows will return a forward-slash separated UNC path.
   *
   * Same interface as require('path').resolve.
   *
   * Much faster than path.resolve() when called multiple times for the same
   * path, because the resolved Path objects are cached.  Much slower
   * otherwise.
   */
  resolvePosix(...paths) {
    let r = "";
    for (let i = paths.length - 1; i >= 0; i--) {
      const p = paths[i];
      if (!p || p === ".")
        continue;
      r = r ? `${p}/${r}` : p;
      if (this.isAbsolute(p)) {
        break;
      }
    }
    const cached = this.#resolvePosixCache.get(r);
    if (cached !== void 0) {
      return cached;
    }
    const result = this.cwd.resolve(r).fullpathPosix();
    this.#resolvePosixCache.set(r, result);
    return result;
  }
  /**
   * find the relative path from the cwd to the supplied path string or entry
   */
  relative(entry = this.cwd) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    }
    return entry.relative();
  }
  /**
   * find the relative path from the cwd to the supplied path string or
   * entry, using / as the path delimiter, even on Windows.
   */
  relativePosix(entry = this.cwd) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    }
    return entry.relativePosix();
  }
  /**
   * Return the basename for the provided string or Path object
   */
  basename(entry = this.cwd) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    }
    return entry.name;
  }
  /**
   * Return the dirname for the provided string or Path object
   */
  dirname(entry = this.cwd) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    }
    return (entry.parent || entry).fullpath();
  }
  async readdir(entry = this.cwd, opts = {
    withFileTypes: true
  }) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      opts = entry;
      entry = this.cwd;
    }
    const { withFileTypes } = opts;
    if (!entry.canReaddir()) {
      return [];
    } else {
      const p = await entry.readdir();
      return withFileTypes ? p : p.map((e) => e.name);
    }
  }
  readdirSync(entry = this.cwd, opts = {
    withFileTypes: true
  }) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      opts = entry;
      entry = this.cwd;
    }
    const { withFileTypes = true } = opts;
    if (!entry.canReaddir()) {
      return [];
    } else if (withFileTypes) {
      return entry.readdirSync();
    } else {
      return entry.readdirSync().map((e) => e.name);
    }
  }
  /**
   * Call lstat() on the string or Path object, and update all known
   * information that can be determined.
   *
   * Note that unlike `fs.lstat()`, the returned value does not contain some
   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
   * information is required, you will need to call `fs.lstat` yourself.
   *
   * If the Path refers to a nonexistent file, or if the lstat call fails for
   * any reason, `undefined` is returned.  Otherwise the updated Path object is
   * returned.
   *
   * Results are cached, and thus may be out of date if the filesystem is
   * mutated.
   */
  async lstat(entry = this.cwd) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    }
    return entry.lstat();
  }
  /**
   * synchronous {@link PathScurryBase.lstat}
   */
  lstatSync(entry = this.cwd) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    }
    return entry.lstatSync();
  }
  async readlink(entry = this.cwd, { withFileTypes } = {
    withFileTypes: false
  }) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      withFileTypes = entry.withFileTypes;
      entry = this.cwd;
    }
    const e = await entry.readlink();
    return withFileTypes ? e : e == null ? void 0 : e.fullpath();
  }
  readlinkSync(entry = this.cwd, { withFileTypes } = {
    withFileTypes: false
  }) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      withFileTypes = entry.withFileTypes;
      entry = this.cwd;
    }
    const e = entry.readlinkSync();
    return withFileTypes ? e : e == null ? void 0 : e.fullpath();
  }
  async realpath(entry = this.cwd, { withFileTypes } = {
    withFileTypes: false
  }) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      withFileTypes = entry.withFileTypes;
      entry = this.cwd;
    }
    const e = await entry.realpath();
    return withFileTypes ? e : e == null ? void 0 : e.fullpath();
  }
  realpathSync(entry = this.cwd, { withFileTypes } = {
    withFileTypes: false
  }) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      withFileTypes = entry.withFileTypes;
      entry = this.cwd;
    }
    const e = entry.realpathSync();
    return withFileTypes ? e : e == null ? void 0 : e.fullpath();
  }
  async walk(entry = this.cwd, opts = {}) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      opts = entry;
      entry = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    const results = [];
    if (!filter2 || filter2(entry)) {
      results.push(withFileTypes ? entry : entry.fullpath());
    }
    const dirs = /* @__PURE__ */ new Set();
    const walk = (dir, cb) => {
      dirs.add(dir);
      dir.readdirCB((er, entries) => {
        if (er) {
          return cb(er);
        }
        let len = entries.length;
        if (!len)
          return cb();
        const next = () => {
          if (--len === 0) {
            cb();
          }
        };
        for (const e of entries) {
          if (!filter2 || filter2(e)) {
            results.push(withFileTypes ? e : e.fullpath());
          }
          if (follow && e.isSymbolicLink()) {
            e.realpath().then((r) => (r == null ? void 0 : r.isUnknown()) ? r.lstat() : r).then((r) => (r == null ? void 0 : r.shouldWalk(dirs, walkFilter)) ? walk(r, next) : next());
          } else {
            if (e.shouldWalk(dirs, walkFilter)) {
              walk(e, next);
            } else {
              next();
            }
          }
        }
      }, true);
    };
    const start = entry;
    return new Promise((res, rej) => {
      walk(start, (er) => {
        if (er)
          return rej(er);
        res(results);
      });
    });
  }
  walkSync(entry = this.cwd, opts = {}) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      opts = entry;
      entry = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    const results = [];
    if (!filter2 || filter2(entry)) {
      results.push(withFileTypes ? entry : entry.fullpath());
    }
    const dirs = /* @__PURE__ */ new Set([entry]);
    for (const dir of dirs) {
      const entries = dir.readdirSync();
      for (const e of entries) {
        if (!filter2 || filter2(e)) {
          results.push(withFileTypes ? e : e.fullpath());
        }
        let r = e;
        if (e.isSymbolicLink()) {
          if (!(follow && (r = e.realpathSync())))
            continue;
          if (r.isUnknown())
            r.lstatSync();
        }
        if (r.shouldWalk(dirs, walkFilter)) {
          dirs.add(r);
        }
      }
    }
    return results;
  }
  /**
   * Support for `for await`
   *
   * Alias for {@link PathScurryBase.iterate}
   *
   * Note: As of Node 19, this is very slow, compared to other methods of
   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead
   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.
   */
  [Symbol.asyncIterator]() {
    return this.iterate();
  }
  iterate(entry = this.cwd, options = {}) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      options = entry;
      entry = this.cwd;
    }
    return this.stream(entry, options)[Symbol.asyncIterator]();
  }
  /**
   * Iterating over a PathScurry performs a synchronous walk.
   *
   * Alias for {@link PathScurryBase.iterateSync}
   */
  [Symbol.iterator]() {
    return this.iterateSync();
  }
  *iterateSync(entry = this.cwd, opts = {}) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      opts = entry;
      entry = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    if (!filter2 || filter2(entry)) {
      yield withFileTypes ? entry : entry.fullpath();
    }
    const dirs = /* @__PURE__ */ new Set([entry]);
    for (const dir of dirs) {
      const entries = dir.readdirSync();
      for (const e of entries) {
        if (!filter2 || filter2(e)) {
          yield withFileTypes ? e : e.fullpath();
        }
        let r = e;
        if (e.isSymbolicLink()) {
          if (!(follow && (r = e.realpathSync())))
            continue;
          if (r.isUnknown())
            r.lstatSync();
        }
        if (r.shouldWalk(dirs, walkFilter)) {
          dirs.add(r);
        }
      }
    }
  }
  stream(entry = this.cwd, opts = {}) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      opts = entry;
      entry = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    const results = new Minipass({ objectMode: true });
    if (!filter2 || filter2(entry)) {
      results.write(withFileTypes ? entry : entry.fullpath());
    }
    const dirs = /* @__PURE__ */ new Set();
    const queue = [entry];
    let processing = 0;
    const process3 = () => {
      let paused = false;
      while (!paused) {
        const dir = queue.shift();
        if (!dir) {
          if (processing === 0)
            results.end();
          return;
        }
        processing++;
        dirs.add(dir);
        const onReaddir = (er, entries, didRealpaths = false) => {
          if (er)
            return results.emit("error", er);
          if (follow && !didRealpaths) {
            const promises2 = [];
            for (const e of entries) {
              if (e.isSymbolicLink()) {
                promises2.push(e.realpath().then((r) => (r == null ? void 0 : r.isUnknown()) ? r.lstat() : r));
              }
            }
            if (promises2.length) {
              Promise.all(promises2).then(() => onReaddir(null, entries, true));
              return;
            }
          }
          for (const e of entries) {
            if (e && (!filter2 || filter2(e))) {
              if (!results.write(withFileTypes ? e : e.fullpath())) {
                paused = true;
              }
            }
          }
          processing--;
          for (const e of entries) {
            const r = e.realpathCached() || e;
            if (r.shouldWalk(dirs, walkFilter)) {
              queue.push(r);
            }
          }
          if (paused && !results.flowing) {
            results.once("drain", process3);
          } else if (!sync2) {
            process3();
          }
        };
        let sync2 = true;
        dir.readdirCB(onReaddir, true);
        sync2 = false;
      }
    };
    process3();
    return results;
  }
  streamSync(entry = this.cwd, opts = {}) {
    if (typeof entry === "string") {
      entry = this.cwd.resolve(entry);
    } else if (!(entry instanceof PathBase)) {
      opts = entry;
      entry = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    const results = new Minipass({ objectMode: true });
    const dirs = /* @__PURE__ */ new Set();
    if (!filter2 || filter2(entry)) {
      results.write(withFileTypes ? entry : entry.fullpath());
    }
    const queue = [entry];
    let processing = 0;
    const process3 = () => {
      let paused = false;
      while (!paused) {
        const dir = queue.shift();
        if (!dir) {
          if (processing === 0)
            results.end();
          return;
        }
        processing++;
        dirs.add(dir);
        const entries = dir.readdirSync();
        for (const e of entries) {
          if (!filter2 || filter2(e)) {
            if (!results.write(withFileTypes ? e : e.fullpath())) {
              paused = true;
            }
          }
        }
        processing--;
        for (const e of entries) {
          let r = e;
          if (e.isSymbolicLink()) {
            if (!(follow && (r = e.realpathSync())))
              continue;
            if (r.isUnknown())
              r.lstatSync();
          }
          if (r.shouldWalk(dirs, walkFilter)) {
            queue.push(r);
          }
        }
      }
      if (paused && !results.flowing)
        results.once("drain", process3);
    };
    process3();
    return results;
  }
  chdir(path3 = this.cwd) {
    const oldCwd = this.cwd;
    this.cwd = typeof path3 === "string" ? this.cwd.resolve(path3) : path3;
    this.cwd[setAsCwd](oldCwd);
  }
};
var PathScurryWin32 = class extends PathScurryBase {
  /**
   * separator for generating path strings
   */
  sep = "\\";
  constructor(cwd = process.cwd(), opts = {}) {
    const { nocase = true } = opts;
    super(cwd, import_node_path.win32, "\\", { ...opts, nocase });
    this.nocase = nocase;
    for (let p = this.cwd; p; p = p.parent) {
      p.nocase = this.nocase;
    }
  }
  /**
   * @internal
   */
  parseRootPath(dir) {
    return import_node_path.win32.parse(dir).root.toUpperCase();
  }
  /**
   * @internal
   */
  newRoot(fs4) {
    return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs4 });
  }
  /**
   * Return true if the provided path string is an absolute path
   */
  isAbsolute(p) {
    return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
  }
};
var PathScurryPosix = class extends PathScurryBase {
  /**
   * separator for generating path strings
   */
  sep = "/";
  constructor(cwd = process.cwd(), opts = {}) {
    const { nocase = false } = opts;
    super(cwd, import_node_path.posix, "/", { ...opts, nocase });
    this.nocase = nocase;
  }
  /**
   * @internal
   */
  parseRootPath(_dir) {
    return "/";
  }
  /**
   * @internal
   */
  newRoot(fs4) {
    return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs4 });
  }
  /**
   * Return true if the provided path string is an absolute path
   */
  isAbsolute(p) {
    return p.startsWith("/");
  }
};
var PathScurryDarwin = class extends PathScurryPosix {
  constructor(cwd = process.cwd(), opts = {}) {
    const { nocase = true } = opts;
    super(cwd, { ...opts, nocase });
  }
};
var Path = process.platform === "win32" ? PathWin32 : PathPosix;
var PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;

// node_modules/rimraf/node_modules/glob/dist/mjs/glob.js
var import_url = require("url");

// node_modules/rimraf/node_modules/glob/dist/mjs/pattern.js
var isPatternList = (pl) => pl.length >= 1;
var isGlobList = (gl) => gl.length >= 1;
var Pattern = class _Pattern {
  #patternList;
  #globList;
  #index;
  length;
  #platform;
  #rest;
  #globString;
  #isDrive;
  #isUNC;
  #isAbsolute;
  #followGlobstar = true;
  constructor(patternList, globList, index, platform) {
    if (!isPatternList(patternList)) {
      throw new TypeError("empty pattern list");
    }
    if (!isGlobList(globList)) {
      throw new TypeError("empty glob list");
    }
    if (globList.length !== patternList.length) {
      throw new TypeError("mismatched pattern list and glob list lengths");
    }
    this.length = patternList.length;
    if (index < 0 || index >= this.length) {
      throw new TypeError("index out of range");
    }
    this.#patternList = patternList;
    this.#globList = globList;
    this.#index = index;
    this.#platform = platform;
    if (this.#index === 0) {
      if (this.isUNC()) {
        const [p0, p1, p2, p3, ...prest] = this.#patternList;
        const [g0, g1, g2, g3, ...grest] = this.#globList;
        if (prest[0] === "") {
          prest.shift();
          grest.shift();
        }
        const p = [p0, p1, p2, p3, ""].join("/");
        const g = [g0, g1, g2, g3, ""].join("/");
        this.#patternList = [p, ...prest];
        this.#globList = [g, ...grest];
        this.length = this.#patternList.length;
      } else if (this.isDrive() || this.isAbsolute()) {
        const [p1, ...prest] = this.#patternList;
        const [g1, ...grest] = this.#globList;
        if (prest[0] === "") {
          prest.shift();
          grest.shift();
        }
        const p = p1 + "/";
        const g = g1 + "/";
        this.#patternList = [p, ...prest];
        this.#globList = [g, ...grest];
        this.length = this.#patternList.length;
      }
    }
  }
  /**
   * The first entry in the parsed list of patterns
   */
  pattern() {
    return this.#patternList[this.#index];
  }
  /**
   * true of if pattern() returns a string
   */
  isString() {
    return typeof this.#patternList[this.#index] === "string";
  }
  /**
   * true of if pattern() returns GLOBSTAR
   */
  isGlobstar() {
    return this.#patternList[this.#index] === GLOBSTAR;
  }
  /**
   * true if pattern() returns a regexp
   */
  isRegExp() {
    return this.#patternList[this.#index] instanceof RegExp;
  }
  /**
   * The /-joined set of glob parts that make up this pattern
   */
  globString() {
    return this.#globString = this.#globString || (this.#index === 0 ? this.isAbsolute() ? this.#globList[0] + this.#globList.slice(1).join("/") : this.#globList.join("/") : this.#globList.slice(this.#index).join("/"));
  }
  /**
   * true if there are more pattern parts after this one
   */
  hasMore() {
    return this.length > this.#index + 1;
  }
  /**
   * The rest of the pattern after this part, or null if this is the end
   */
  rest() {
    if (this.#rest !== void 0)
      return this.#rest;
    if (!this.hasMore())
      return this.#rest = null;
    this.#rest = new _Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
    this.#rest.#isAbsolute = this.#isAbsolute;
    this.#rest.#isUNC = this.#isUNC;
    this.#rest.#isDrive = this.#isDrive;
    return this.#rest;
  }
  /**
   * true if the pattern represents a //unc/path/ on windows
   */
  isUNC() {
    const pl = this.#patternList;
    return this.#isUNC !== void 0 ? this.#isUNC : this.#isUNC = this.#platform === "win32" && this.#index === 0 && pl[0] === "" && pl[1] === "" && typeof pl[2] === "string" && !!pl[2] && typeof pl[3] === "string" && !!pl[3];
  }
  // pattern like C:/...
  // split = ['C:', ...]
  // XXX: would be nice to handle patterns like `c:*` to test the cwd
  // in c: for *, but I don't know of a way to even figure out what that
  // cwd is without actually chdir'ing into it?
  /**
   * True if the pattern starts with a drive letter on Windows
   */
  isDrive() {
    const pl = this.#patternList;
    return this.#isDrive !== void 0 ? this.#isDrive : this.#isDrive = this.#platform === "win32" && this.#index === 0 && this.length > 1 && typeof pl[0] === "string" && /^[a-z]:$/i.test(pl[0]);
  }
  // pattern = '/' or '/...' or '/x/...'
  // split = ['', ''] or ['', ...] or ['', 'x', ...]
  // Drive and UNC both considered absolute on windows
  /**
   * True if the pattern is rooted on an absolute path
   */
  isAbsolute() {
    const pl = this.#patternList;
    return this.#isAbsolute !== void 0 ? this.#isAbsolute : this.#isAbsolute = pl[0] === "" && pl.length > 1 || this.isDrive() || this.isUNC();
  }
  /**
   * consume the root of the pattern, and return it
   */
  root() {
    const p = this.#patternList[0];
    return typeof p === "string" && this.isAbsolute() && this.#index === 0 ? p : "";
  }
  /**
   * Check to see if the current globstar pattern is allowed to follow
   * a symbolic link.
   */
  checkFollowGlobstar() {
    return !(this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar);
  }
  /**
   * Mark that the current globstar pattern is following a symbolic link
   */
  markFollowGlobstar() {
    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
      return false;
    this.#followGlobstar = false;
    return true;
  }
};

// node_modules/rimraf/node_modules/minipass/index.mjs
var import_events = __toESM(require("events"), 1);
var import_stream = __toESM(require("stream"), 1);
var import_string_decoder = __toESM(require("string_decoder"), 1);
var proc2 = typeof process === "object" && process ? process : {
  stdout: null,
  stderr: null
};
var SD = import_string_decoder.default.StringDecoder;
var EOF2 = Symbol("EOF");
var MAYBE_EMIT_END2 = Symbol("maybeEmitEnd");
var EMITTED_END2 = Symbol("emittedEnd");
var EMITTING_END2 = Symbol("emittingEnd");
var EMITTED_ERROR2 = Symbol("emittedError");
var CLOSED2 = Symbol("closed");
var READ2 = Symbol("read");
var FLUSH2 = Symbol("flush");
var FLUSHCHUNK2 = Symbol("flushChunk");
var ENCODING2 = Symbol("encoding");
var DECODER2 = Symbol("decoder");
var FLOWING2 = Symbol("flowing");
var PAUSED2 = Symbol("paused");
var RESUME2 = Symbol("resume");
var BUFFER2 = Symbol("buffer");
var PIPES2 = Symbol("pipes");
var BUFFERLENGTH2 = Symbol("bufferLength");
var BUFFERPUSH2 = Symbol("bufferPush");
var BUFFERSHIFT2 = Symbol("bufferShift");
var OBJECTMODE2 = Symbol("objectMode");
var DESTROYED2 = Symbol("destroyed");
var ERROR2 = Symbol("error");
var EMITDATA2 = Symbol("emitData");
var EMITEND3 = Symbol("emitEnd");
var EMITEND22 = Symbol("emitEnd2");
var ASYNC2 = Symbol("async");
var ABORT2 = Symbol("abort");
var ABORTED2 = Symbol("aborted");
var SIGNAL2 = Symbol("signal");
var defer2 = (fn) => Promise.resolve().then(fn);
var doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== "1";
var ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol("asyncIterator not implemented");
var ITERATOR = doIter && Symbol.iterator || Symbol("iterator not implemented");
var isEndish2 = (ev) => ev === "end" || ev === "finish" || ev === "prefinish";
var isArrayBuffer = (b) => b instanceof ArrayBuffer || typeof b === "object" && b.constructor && b.constructor.name === "ArrayBuffer" && b.byteLength >= 0;
var isArrayBufferView2 = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
var Pipe2 = class {
  constructor(src, dest, opts) {
    this.src = src;
    this.dest = dest;
    this.opts = opts;
    this.ondrain = () => src[RESUME2]();
    dest.on("drain", this.ondrain);
  }
  unpipe() {
    this.dest.removeListener("drain", this.ondrain);
  }
  // istanbul ignore next - only here for the prototype
  proxyErrors() {
  }
  end() {
    this.unpipe();
    if (this.opts.end)
      this.dest.end();
  }
};
var PipeProxyErrors2 = class extends Pipe2 {
  unpipe() {
    this.src.removeListener("error", this.proxyErrors);
    super.unpipe();
  }
  constructor(src, dest, opts) {
    super(src, dest, opts);
    this.proxyErrors = (er) => dest.emit("error", er);
    src.on("error", this.proxyErrors);
  }
};
var Minipass2 = class _Minipass extends import_stream.default {
  constructor(options) {
    super();
    this[FLOWING2] = false;
    this[PAUSED2] = false;
    this[PIPES2] = [];
    this[BUFFER2] = [];
    this[OBJECTMODE2] = options && options.objectMode || false;
    if (this[OBJECTMODE2])
      this[ENCODING2] = null;
    else
      this[ENCODING2] = options && options.encoding || null;
    if (this[ENCODING2] === "buffer")
      this[ENCODING2] = null;
    this[ASYNC2] = options && !!options.async || false;
    this[DECODER2] = this[ENCODING2] ? new SD(this[ENCODING2]) : null;
    this[EOF2] = false;
    this[EMITTED_END2] = false;
    this[EMITTING_END2] = false;
    this[CLOSED2] = false;
    this[EMITTED_ERROR2] = null;
    this.writable = true;
    this.readable = true;
    this[BUFFERLENGTH2] = 0;
    this[DESTROYED2] = false;
    if (options && options.debugExposeBuffer === true) {
      Object.defineProperty(this, "buffer", { get: () => this[BUFFER2] });
    }
    if (options && options.debugExposePipes === true) {
      Object.defineProperty(this, "pipes", { get: () => this[PIPES2] });
    }
    this[SIGNAL2] = options && options.signal;
    this[ABORTED2] = false;
    if (this[SIGNAL2]) {
      this[SIGNAL2].addEventListener("abort", () => this[ABORT2]());
      if (this[SIGNAL2].aborted) {
        this[ABORT2]();
      }
    }
  }
  get bufferLength() {
    return this[BUFFERLENGTH2];
  }
  get encoding() {
    return this[ENCODING2];
  }
  set encoding(enc) {
    if (this[OBJECTMODE2])
      throw new Error("cannot set encoding in objectMode");
    if (this[ENCODING2] && enc !== this[ENCODING2] && (this[DECODER2] && this[DECODER2].lastNeed || this[BUFFERLENGTH2]))
      throw new Error("cannot change encoding");
    if (this[ENCODING2] !== enc) {
      this[DECODER2] = enc ? new SD(enc) : null;
      if (this[BUFFER2].length)
        this[BUFFER2] = this[BUFFER2].map((chunk) => this[DECODER2].write(chunk));
    }
    this[ENCODING2] = enc;
  }
  setEncoding(enc) {
    this.encoding = enc;
  }
  get objectMode() {
    return this[OBJECTMODE2];
  }
  set objectMode(om) {
    this[OBJECTMODE2] = this[OBJECTMODE2] || !!om;
  }
  get ["async"]() {
    return this[ASYNC2];
  }
  set ["async"](a) {
    this[ASYNC2] = this[ASYNC2] || !!a;
  }
  // drop everything and get out of the flow completely
  [ABORT2]() {
    this[ABORTED2] = true;
    this.emit("abort", this[SIGNAL2].reason);
    this.destroy(this[SIGNAL2].reason);
  }
  get aborted() {
    return this[ABORTED2];
  }
  set aborted(_) {
  }
  write(chunk, encoding, cb) {
    if (this[ABORTED2])
      return false;
    if (this[EOF2])
      throw new Error("write after end");
    if (this[DESTROYED2]) {
      this.emit(
        "error",
        Object.assign(
          new Error("Cannot call write after a stream was destroyed"),
          { code: "ERR_STREAM_DESTROYED" }
        )
      );
      return true;
    }
    if (typeof encoding === "function")
      cb = encoding, encoding = "utf8";
    if (!encoding)
      encoding = "utf8";
    const fn = this[ASYNC2] ? defer2 : (f) => f();
    if (!this[OBJECTMODE2] && !Buffer.isBuffer(chunk)) {
      if (isArrayBufferView2(chunk))
        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
      else if (isArrayBuffer(chunk))
        chunk = Buffer.from(chunk);
      else if (typeof chunk !== "string")
        this.objectMode = true;
    }
    if (this[OBJECTMODE2]) {
      if (this.flowing && this[BUFFERLENGTH2] !== 0)
        this[FLUSH2](true);
      if (this.flowing)
        this.emit("data", chunk);
      else
        this[BUFFERPUSH2](chunk);
      if (this[BUFFERLENGTH2] !== 0)
        this.emit("readable");
      if (cb)
        fn(cb);
      return this.flowing;
    }
    if (!chunk.length) {
      if (this[BUFFERLENGTH2] !== 0)
        this.emit("readable");
      if (cb)
        fn(cb);
      return this.flowing;
    }
    if (typeof chunk === "string" && // unless it is a string already ready for us to use
    !(encoding === this[ENCODING2] && !this[DECODER2].lastNeed)) {
      chunk = Buffer.from(chunk, encoding);
    }
    if (Buffer.isBuffer(chunk) && this[ENCODING2])
      chunk = this[DECODER2].write(chunk);
    if (this.flowing && this[BUFFERLENGTH2] !== 0)
      this[FLUSH2](true);
    if (this.flowing)
      this.emit("data", chunk);
    else
      this[BUFFERPUSH2](chunk);
    if (this[BUFFERLENGTH2] !== 0)
      this.emit("readable");
    if (cb)
      fn(cb);
    return this.flowing;
  }
  read(n) {
    if (this[DESTROYED2])
      return null;
    if (this[BUFFERLENGTH2] === 0 || n === 0 || n > this[BUFFERLENGTH2]) {
      this[MAYBE_EMIT_END2]();
      return null;
    }
    if (this[OBJECTMODE2])
      n = null;
    if (this[BUFFER2].length > 1 && !this[OBJECTMODE2]) {
      if (this.encoding)
        this[BUFFER2] = [this[BUFFER2].join("")];
      else
        this[BUFFER2] = [Buffer.concat(this[BUFFER2], this[BUFFERLENGTH2])];
    }
    const ret = this[READ2](n || null, this[BUFFER2][0]);
    this[MAYBE_EMIT_END2]();
    return ret;
  }
  [READ2](n, chunk) {
    if (n === chunk.length || n === null)
      this[BUFFERSHIFT2]();
    else {
      this[BUFFER2][0] = chunk.slice(n);
      chunk = chunk.slice(0, n);
      this[BUFFERLENGTH2] -= n;
    }
    this.emit("data", chunk);
    if (!this[BUFFER2].length && !this[EOF2])
      this.emit("drain");
    return chunk;
  }
  end(chunk, encoding, cb) {
    if (typeof chunk === "function")
      cb = chunk, chunk = null;
    if (typeof encoding === "function")
      cb = encoding, encoding = "utf8";
    if (chunk)
      this.write(chunk, encoding);
    if (cb)
      this.once("end", cb);
    this[EOF2] = true;
    this.writable = false;
    if (this.flowing || !this[PAUSED2])
      this[MAYBE_EMIT_END2]();
    return this;
  }
  // don't let the internal resume be overwritten
  [RESUME2]() {
    if (this[DESTROYED2])
      return;
    this[PAUSED2] = false;
    this[FLOWING2] = true;
    this.emit("resume");
    if (this[BUFFER2].length)
      this[FLUSH2]();
    else if (this[EOF2])
      this[MAYBE_EMIT_END2]();
    else
      this.emit("drain");
  }
  resume() {
    return this[RESUME2]();
  }
  pause() {
    this[FLOWING2] = false;
    this[PAUSED2] = true;
  }
  get destroyed() {
    return this[DESTROYED2];
  }
  get flowing() {
    return this[FLOWING2];
  }
  get paused() {
    return this[PAUSED2];
  }
  [BUFFERPUSH2](chunk) {
    if (this[OBJECTMODE2])
      this[BUFFERLENGTH2] += 1;
    else
      this[BUFFERLENGTH2] += chunk.length;
    this[BUFFER2].push(chunk);
  }
  [BUFFERSHIFT2]() {
    if (this[OBJECTMODE2])
      this[BUFFERLENGTH2] -= 1;
    else
      this[BUFFERLENGTH2] -= this[BUFFER2][0].length;
    return this[BUFFER2].shift();
  }
  [FLUSH2](noDrain) {
    do {
    } while (this[FLUSHCHUNK2](this[BUFFERSHIFT2]()) && this[BUFFER2].length);
    if (!noDrain && !this[BUFFER2].length && !this[EOF2])
      this.emit("drain");
  }
  [FLUSHCHUNK2](chunk) {
    this.emit("data", chunk);
    return this.flowing;
  }
  pipe(dest, opts) {
    if (this[DESTROYED2])
      return;
    const ended = this[EMITTED_END2];
    opts = opts || {};
    if (dest === proc2.stdout || dest === proc2.stderr)
      opts.end = false;
    else
      opts.end = opts.end !== false;
    opts.proxyErrors = !!opts.proxyErrors;
    if (ended) {
      if (opts.end)
        dest.end();
    } else {
      this[PIPES2].push(
        !opts.proxyErrors ? new Pipe2(this, dest, opts) : new PipeProxyErrors2(this, dest, opts)
      );
      if (this[ASYNC2])
        defer2(() => this[RESUME2]());
      else
        this[RESUME2]();
    }
    return dest;
  }
  unpipe(dest) {
    const p = this[PIPES2].find((p2) => p2.dest === dest);
    if (p) {
      this[PIPES2].splice(this[PIPES2].indexOf(p), 1);
      p.unpipe();
    }
  }
  addListener(ev, fn) {
    return this.on(ev, fn);
  }
  on(ev, fn) {
    const ret = super.on(ev, fn);
    if (ev === "data" && !this[PIPES2].length && !this.flowing)
      this[RESUME2]();
    else if (ev === "readable" && this[BUFFERLENGTH2] !== 0)
      super.emit("readable");
    else if (isEndish2(ev) && this[EMITTED_END2]) {
      super.emit(ev);
      this.removeAllListeners(ev);
    } else if (ev === "error" && this[EMITTED_ERROR2]) {
      if (this[ASYNC2])
        defer2(() => fn.call(this, this[EMITTED_ERROR2]));
      else
        fn.call(this, this[EMITTED_ERROR2]);
    }
    return ret;
  }
  get emittedEnd() {
    return this[EMITTED_END2];
  }
  [MAYBE_EMIT_END2]() {
    if (!this[EMITTING_END2] && !this[EMITTED_END2] && !this[DESTROYED2] && this[BUFFER2].length === 0 && this[EOF2]) {
      this[EMITTING_END2] = true;
      this.emit("end");
      this.emit("prefinish");
      this.emit("finish");
      if (this[CLOSED2])
        this.emit("close");
      this[EMITTING_END2] = false;
    }
  }
  emit(ev, data, ...extra) {
    if (ev !== "error" && ev !== "close" && ev !== DESTROYED2 && this[DESTROYED2])
      return;
    else if (ev === "data") {
      return !this[OBJECTMODE2] && !data ? false : this[ASYNC2] ? defer2(() => this[EMITDATA2](data)) : this[EMITDATA2](data);
    } else if (ev === "end") {
      return this[EMITEND3]();
    } else if (ev === "close") {
      this[CLOSED2] = true;
      if (!this[EMITTED_END2] && !this[DESTROYED2])
        return;
      const ret2 = super.emit("close");
      this.removeAllListeners("close");
      return ret2;
    } else if (ev === "error") {
      this[EMITTED_ERROR2] = data;
      super.emit(ERROR2, data);
      const ret2 = !this[SIGNAL2] || this.listeners("error").length ? super.emit("error", data) : false;
      this[MAYBE_EMIT_END2]();
      return ret2;
    } else if (ev === "resume") {
      const ret2 = super.emit("resume");
      this[MAYBE_EMIT_END2]();
      return ret2;
    } else if (ev === "finish" || ev === "prefinish") {
      const ret2 = super.emit(ev);
      this.removeAllListeners(ev);
      return ret2;
    }
    const ret = super.emit(ev, data, ...extra);
    this[MAYBE_EMIT_END2]();
    return ret;
  }
  [EMITDATA2](data) {
    for (const p of this[PIPES2]) {
      if (p.dest.write(data) === false)
        this.pause();
    }
    const ret = super.emit("data", data);
    this[MAYBE_EMIT_END2]();
    return ret;
  }
  [EMITEND3]() {
    if (this[EMITTED_END2])
      return;
    this[EMITTED_END2] = true;
    this.readable = false;
    if (this[ASYNC2])
      defer2(() => this[EMITEND22]());
    else
      this[EMITEND22]();
  }
  [EMITEND22]() {
    if (this[DECODER2]) {
      const data = this[DECODER2].end();
      if (data) {
        for (const p of this[PIPES2]) {
          p.dest.write(data);
        }
        super.emit("data", data);
      }
    }
    for (const p of this[PIPES2]) {
      p.end();
    }
    const ret = super.emit("end");
    this.removeAllListeners("end");
    return ret;
  }
  // const all = await stream.collect()
  collect() {
    const buf = [];
    if (!this[OBJECTMODE2])
      buf.dataLength = 0;
    const p = this.promise();
    this.on("data", (c) => {
      buf.push(c);
      if (!this[OBJECTMODE2])
        buf.dataLength += c.length;
    });
    return p.then(() => buf);
  }
  // const data = await stream.concat()
  concat() {
    return this[OBJECTMODE2] ? Promise.reject(new Error("cannot concat in objectMode")) : this.collect().then(
      (buf) => this[OBJECTMODE2] ? Promise.reject(new Error("cannot concat in objectMode")) : this[ENCODING2] ? buf.join("") : Buffer.concat(buf, buf.dataLength)
    );
  }
  // stream.promise().then(() => done, er => emitted error)
  promise() {
    return new Promise((resolve6, reject) => {
      this.on(DESTROYED2, () => reject(new Error("stream destroyed")));
      this.on("error", (er) => reject(er));
      this.on("end", () => resolve6());
    });
  }
  // for await (let chunk of stream)
  [ASYNCITERATOR]() {
    let stopped = false;
    const stop = () => {
      this.pause();
      stopped = true;
      return Promise.resolve({ done: true });
    };
    const next = () => {
      if (stopped)
        return stop();
      const res = this.read();
      if (res !== null)
        return Promise.resolve({ done: false, value: res });
      if (this[EOF2])
        return stop();
      let resolve6 = null;
      let reject = null;
      const onerr = (er) => {
        this.removeListener("data", ondata);
        this.removeListener("end", onend);
        this.removeListener(DESTROYED2, ondestroy);
        stop();
        reject(er);
      };
      const ondata = (value) => {
        this.removeListener("error", onerr);
        this.removeListener("end", onend);
        this.removeListener(DESTROYED2, ondestroy);
        this.pause();
        resolve6({ value, done: !!this[EOF2] });
      };
      const onend = () => {
        this.removeListener("error", onerr);
        this.removeListener("data", ondata);
        this.removeListener(DESTROYED2, ondestroy);
        stop();
        resolve6({ done: true });
      };
      const ondestroy = () => onerr(new Error("stream destroyed"));
      return new Promise((res2, rej) => {
        reject = rej;
        resolve6 = res2;
        this.once(DESTROYED2, ondestroy);
        this.once("error", onerr);
        this.once("end", onend);
        this.once("data", ondata);
      });
    };
    return {
      next,
      throw: stop,
      return: stop,
      [ASYNCITERATOR]() {
        return this;
      }
    };
  }
  // for (let chunk of stream)
  [ITERATOR]() {
    let stopped = false;
    const stop = () => {
      this.pause();
      this.removeListener(ERROR2, stop);
      this.removeListener(DESTROYED2, stop);
      this.removeListener("end", stop);
      stopped = true;
      return { done: true };
    };
    const next = () => {
      if (stopped)
        return stop();
      const value = this.read();
      return value === null ? stop() : { value };
    };
    this.once("end", stop);
    this.once(ERROR2, stop);
    this.once(DESTROYED2, stop);
    return {
      next,
      throw: stop,
      return: stop,
      [ITERATOR]() {
        return this;
      }
    };
  }
  destroy(er) {
    if (this[DESTROYED2]) {
      if (er)
        this.emit("error", er);
      else
        this.emit(DESTROYED2);
      return this;
    }
    this[DESTROYED2] = true;
    this[BUFFER2].length = 0;
    this[BUFFERLENGTH2] = 0;
    if (typeof this.close === "function" && !this[CLOSED2])
      this.close();
    if (er)
      this.emit("error", er);
    else
      this.emit(DESTROYED2);
    return this;
  }
  static isStream(s) {
    return !!s && (s instanceof _Minipass || s instanceof import_stream.default || s instanceof import_events.default && // readable
    (typeof s.pipe === "function" || // writable
    typeof s.write === "function" && typeof s.end === "function"));
  }
};
var minipass_default = Minipass2;

// node_modules/rimraf/node_modules/glob/dist/mjs/ignore.js
var defaultPlatform2 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
var Ignore = class {
  relative;
  relativeChildren;
  absolute;
  absoluteChildren;
  constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform2 }) {
    this.relative = [];
    this.absolute = [];
    this.relativeChildren = [];
    this.absoluteChildren = [];
    const mmopts = {
      dot: true,
      nobrace,
      nocase,
      noext,
      noglobstar,
      optimizationLevel: 2,
      platform,
      nocomment: true,
      nonegate: true
    };
    for (const ign of ignored) {
      const mm = new Minimatch(ign, mmopts);
      for (let i = 0; i < mm.set.length; i++) {
        const parsed = mm.set[i];
        const globParts = mm.globParts[i];
        const p = new Pattern(parsed, globParts, 0, platform);
        const m = new Minimatch(p.globString(), mmopts);
        const children = globParts[globParts.length - 1] === "**";
        const absolute = p.isAbsolute();
        if (absolute)
          this.absolute.push(m);
        else
          this.relative.push(m);
        if (children) {
          if (absolute)
            this.absoluteChildren.push(m);
          else
            this.relativeChildren.push(m);
        }
      }
    }
  }
  ignored(p) {
    const fullpath = p.fullpath();
    const fullpaths = `${fullpath}/`;
    const relative = p.relative() || ".";
    const relatives = `${relative}/`;
    for (const m of this.relative) {
      if (m.match(relative) || m.match(relatives))
        return true;
    }
    for (const m of this.absolute) {
      if (m.match(fullpath) || m.match(fullpaths))
        return true;
    }
    return false;
  }
  childrenIgnored(p) {
    const fullpath = p.fullpath() + "/";
    const relative = (p.relative() || ".") + "/";
    for (const m of this.relativeChildren) {
      if (m.match(relative))
        return true;
    }
    for (const m of this.absoluteChildren) {
      if (m.match(fullpath))
        true;
    }
    return false;
  }
};

// node_modules/rimraf/node_modules/glob/dist/mjs/processor.js
var HasWalkedCache = class _HasWalkedCache {
  store;
  constructor(store = /* @__PURE__ */ new Map()) {
    this.store = store;
  }
  copy() {
    return new _HasWalkedCache(new Map(this.store));
  }
  hasWalked(target, pattern) {
    var _a2;
    return (_a2 = this.store.get(target.fullpath())) == null ? void 0 : _a2.has(pattern.globString());
  }
  storeWalked(target, pattern) {
    const fullpath = target.fullpath();
    const cached = this.store.get(fullpath);
    if (cached)
      cached.add(pattern.globString());
    else
      this.store.set(fullpath, /* @__PURE__ */ new Set([pattern.globString()]));
  }
};
var MatchRecord = class {
  store = /* @__PURE__ */ new Map();
  add(target, absolute, ifDir) {
    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
    const current = this.store.get(target);
    this.store.set(target, current === void 0 ? n : n & current);
  }
  // match, absolute, ifdir
  entries() {
    return [...this.store.entries()].map(([path3, n]) => [
      path3,
      !!(n & 2),
      !!(n & 1)
    ]);
  }
};
var SubWalks = class {
  store = /* @__PURE__ */ new Map();
  add(target, pattern) {
    if (!target.canReaddir()) {
      return;
    }
    const subs = this.store.get(target);
    if (subs) {
      if (!subs.find((p) => p.globString() === pattern.globString())) {
        subs.push(pattern);
      }
    } else
      this.store.set(target, [pattern]);
  }
  get(target) {
    const subs = this.store.get(target);
    if (!subs) {
      throw new Error("attempting to walk unknown path");
    }
    return subs;
  }
  entries() {
    return this.keys().map((k) => [k, this.store.get(k)]);
  }
  keys() {
    return [...this.store.keys()].filter((t) => t.canReaddir());
  }
};
var Processor = class _Processor {
  hasWalkedCache;
  matches = new MatchRecord();
  subwalks = new SubWalks();
  patterns;
  follow;
  dot;
  opts;
  constructor(opts, hasWalkedCache) {
    this.opts = opts;
    this.follow = !!opts.follow;
    this.dot = !!opts.dot;
    this.hasWalkedCache = hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
  }
  processPatterns(target, patterns) {
    this.patterns = patterns;
    const processingSet = patterns.map((p) => [target, p]);
    for (let [t, pattern] of processingSet) {
      this.hasWalkedCache.storeWalked(t, pattern);
      const root2 = pattern.root();
      const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
      if (root2) {
        t = t.resolve(root2 === "/" && this.opts.root !== void 0 ? this.opts.root : root2);
        const rest2 = pattern.rest();
        if (!rest2) {
          this.matches.add(t, true, false);
          continue;
        } else {
          pattern = rest2;
        }
      }
      if (t.isENOENT())
        continue;
      let p;
      let rest;
      let changed = false;
      while (typeof (p = pattern.pattern()) === "string" && (rest = pattern.rest())) {
        const c = t.resolve(p);
        if (c.isUnknown() && p !== "..")
          break;
        t = c;
        pattern = rest;
        changed = true;
      }
      p = pattern.pattern();
      rest = pattern.rest();
      if (changed) {
        if (this.hasWalkedCache.hasWalked(t, pattern))
          continue;
        this.hasWalkedCache.storeWalked(t, pattern);
      }
      if (typeof p === "string") {
        if (!rest) {
          const ifDir = p === ".." || p === "" || p === ".";
          this.matches.add(t.resolve(p), absolute, ifDir);
        } else {
          this.subwalks.add(t, pattern);
        }
        continue;
      } else if (p === GLOBSTAR) {
        if (!t.isSymbolicLink() || this.follow || pattern.checkFollowGlobstar()) {
          this.subwalks.add(t, pattern);
        }
        const rp = rest == null ? void 0 : rest.pattern();
        const rrest = rest == null ? void 0 : rest.rest();
        if (!rest || (rp === "" || rp === ".") && !rrest) {
          this.matches.add(t, absolute, rp === "" || rp === ".");
        } else {
          if (rp === "..") {
            const tp = t.parent || t;
            if (!rrest)
              this.matches.add(tp, absolute, true);
            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
              this.subwalks.add(tp, rrest);
            }
          }
        }
      } else if (p instanceof RegExp) {
        this.subwalks.add(t, pattern);
      }
    }
    return this;
  }
  subwalkTargets() {
    return this.subwalks.keys();
  }
  child() {
    return new _Processor(this.opts, this.hasWalkedCache);
  }
  // return a new Processor containing the subwalks for each
  // child entry, and a set of matches, and
  // a hasWalkedCache that's a copy of this one
  // then we're going to call
  filterEntries(parent, entries) {
    const patterns = this.subwalks.get(parent);
    const results = this.child();
    for (const e of entries) {
      for (const pattern of patterns) {
        const absolute = pattern.isAbsolute();
        const p = pattern.pattern();
        const rest = pattern.rest();
        if (p === GLOBSTAR) {
          results.testGlobstar(e, pattern, rest, absolute);
        } else if (p instanceof RegExp) {
          results.testRegExp(e, p, rest, absolute);
        } else {
          results.testString(e, p, rest, absolute);
        }
      }
    }
    return results;
  }
  testGlobstar(e, pattern, rest, absolute) {
    if (this.dot || !e.name.startsWith(".")) {
      if (!pattern.hasMore()) {
        this.matches.add(e, absolute, false);
      }
      if (e.canReaddir()) {
        if (this.follow || !e.isSymbolicLink()) {
          this.subwalks.add(e, pattern);
        } else if (e.isSymbolicLink()) {
          if (rest && pattern.checkFollowGlobstar()) {
            this.subwalks.add(e, rest);
          } else if (pattern.markFollowGlobstar()) {
            this.subwalks.add(e, pattern);
          }
        }
      }
    }
    if (rest) {
      const rp = rest.pattern();
      if (typeof rp === "string" && // dots and empty were handled already
      rp !== ".." && rp !== "" && rp !== ".") {
        this.testString(e, rp, rest.rest(), absolute);
      } else if (rp === "..") {
        const ep = e.parent || e;
        this.subwalks.add(ep, rest);
      } else if (rp instanceof RegExp) {
        this.testRegExp(e, rp, rest.rest(), absolute);
      }
    }
  }
  testRegExp(e, p, rest, absolute) {
    if (!p.test(e.name))
      return;
    if (!rest) {
      this.matches.add(e, absolute, false);
    } else {
      this.subwalks.add(e, rest);
    }
  }
  testString(e, p, rest, absolute) {
    if (!e.isNamed(p))
      return;
    if (!rest) {
      this.matches.add(e, absolute, false);
    } else {
      this.subwalks.add(e, rest);
    }
  }
};

// node_modules/rimraf/node_modules/glob/dist/mjs/walker.js
var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore;
var GlobUtil = class {
  path;
  patterns;
  opts;
  seen = /* @__PURE__ */ new Set();
  paused = false;
  aborted = false;
  #onResume = [];
  #ignore;
  #sep;
  signal;
  maxDepth;
  constructor(patterns, path3, opts) {
    this.patterns = patterns;
    this.path = path3;
    this.opts = opts;
    this.#sep = opts.platform === "win32" ? "\\" : "/";
    if (opts.ignore) {
      this.#ignore = makeIgnore(opts.ignore, opts);
    }
    this.maxDepth = opts.maxDepth || Infinity;
    if (opts.signal) {
      this.signal = opts.signal;
      this.signal.addEventListener("abort", () => {
        this.#onResume.length = 0;
      });
    }
  }
  #ignored(path3) {
    var _a2, _b;
    return this.seen.has(path3) || !!((_b = (_a2 = this.#ignore) == null ? void 0 : _a2.ignored) == null ? void 0 : _b.call(_a2, path3));
  }
  #childrenIgnored(path3) {
    var _a2, _b;
    return !!((_b = (_a2 = this.#ignore) == null ? void 0 : _a2.childrenIgnored) == null ? void 0 : _b.call(_a2, path3));
  }
  // backpressure mechanism
  pause() {
    this.paused = true;
  }
  resume() {
    var _a2;
    if ((_a2 = this.signal) == null ? void 0 : _a2.aborted)
      return;
    this.paused = false;
    let fn = void 0;
    while (!this.paused && (fn = this.#onResume.shift())) {
      fn();
    }
  }
  onResume(fn) {
    var _a2;
    if ((_a2 = this.signal) == null ? void 0 : _a2.aborted)
      return;
    if (!this.paused) {
      fn();
    } else {
      this.#onResume.push(fn);
    }
  }
  // do the requisite realpath/stat checking, and return the path
  // to add or undefined to filter it out.
  async matchCheck(e, ifDir) {
    if (ifDir && this.opts.nodir)
      return void 0;
    let rpc;
    if (this.opts.realpath) {
      rpc = e.realpathCached() || await e.realpath();
      if (!rpc)
        return void 0;
      e = rpc;
    }
    const needStat = e.isUnknown() || this.opts.stat;
    return this.matchCheckTest(needStat ? await e.lstat() : e, ifDir);
  }
  matchCheckTest(e, ifDir) {
    return e && (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && (!ifDir || e.canReaddir()) && (!this.opts.nodir || !e.isDirectory()) && !this.#ignored(e) ? e : void 0;
  }
  matchCheckSync(e, ifDir) {
    if (ifDir && this.opts.nodir)
      return void 0;
    let rpc;
    if (this.opts.realpath) {
      rpc = e.realpathCached() || e.realpathSync();
      if (!rpc)
        return void 0;
      e = rpc;
    }
    const needStat = e.isUnknown() || this.opts.stat;
    return this.matchCheckTest(needStat ? e.lstatSync() : e, ifDir);
  }
  matchFinish(e, absolute) {
    if (this.#ignored(e))
      return;
    const abs = this.opts.absolute === void 0 ? absolute : this.opts.absolute;
    this.seen.add(e);
    const mark = this.opts.mark && e.isDirectory() ? this.#sep : "";
    if (this.opts.withFileTypes) {
      this.matchEmit(e);
    } else if (abs) {
      this.matchEmit(e.fullpath() + mark);
    } else {
      const rel = e.relative();
      const pre = this.opts.dotRelative && !rel.startsWith(".." + this.#sep) ? "." + this.#sep : "";
      this.matchEmit(!rel && mark ? "." + mark : pre + rel + mark);
    }
  }
  async match(e, absolute, ifDir) {
    const p = await this.matchCheck(e, ifDir);
    if (p)
      this.matchFinish(p, absolute);
  }
  matchSync(e, absolute, ifDir) {
    const p = this.matchCheckSync(e, ifDir);
    if (p)
      this.matchFinish(p, absolute);
  }
  walkCB(target, patterns, cb) {
    var _a2;
    if ((_a2 = this.signal) == null ? void 0 : _a2.aborted)
      cb();
    this.walkCB2(target, patterns, new Processor(this.opts), cb);
  }
  walkCB2(target, patterns, processor, cb) {
    var _a2;
    if (this.#childrenIgnored(target))
      return cb();
    if ((_a2 = this.signal) == null ? void 0 : _a2.aborted)
      cb();
    if (this.paused) {
      this.onResume(() => this.walkCB2(target, patterns, processor, cb));
      return;
    }
    processor.processPatterns(target, patterns);
    let tasks = 1;
    const next = () => {
      if (--tasks === 0)
        cb();
    };
    for (const [m, absolute, ifDir] of processor.matches.entries()) {
      if (this.#ignored(m))
        continue;
      tasks++;
      this.match(m, absolute, ifDir).then(() => next());
    }
    for (const t of processor.subwalkTargets()) {
      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
        continue;
      }
      tasks++;
      const childrenCached = t.readdirCached();
      if (t.calledReaddir())
        this.walkCB3(t, childrenCached, processor, next);
      else {
        t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true);
      }
    }
    next();
  }
  walkCB3(target, entries, processor, cb) {
    processor = processor.filterEntries(target, entries);
    let tasks = 1;
    const next = () => {
      if (--tasks === 0)
        cb();
    };
    for (const [m, absolute, ifDir] of processor.matches.entries()) {
      if (this.#ignored(m))
        continue;
      tasks++;
      this.match(m, absolute, ifDir).then(() => next());
    }
    for (const [target2, patterns] of processor.subwalks.entries()) {
      tasks++;
      this.walkCB2(target2, patterns, processor.child(), next);
    }
    next();
  }
  walkCBSync(target, patterns, cb) {
    var _a2;
    if ((_a2 = this.signal) == null ? void 0 : _a2.aborted)
      cb();
    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb);
  }
  walkCB2Sync(target, patterns, processor, cb) {
    var _a2;
    if (this.#childrenIgnored(target))
      return cb();
    if ((_a2 = this.signal) == null ? void 0 : _a2.aborted)
      cb();
    if (this.paused) {
      this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
      return;
    }
    processor.processPatterns(target, patterns);
    let tasks = 1;
    const next = () => {
      if (--tasks === 0)
        cb();
    };
    for (const [m, absolute, ifDir] of processor.matches.entries()) {
      if (this.#ignored(m))
        continue;
      this.matchSync(m, absolute, ifDir);
    }
    for (const t of processor.subwalkTargets()) {
      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
        continue;
      }
      tasks++;
      const children = t.readdirSync();
      this.walkCB3Sync(t, children, processor, next);
    }
    next();
  }
  walkCB3Sync(target, entries, processor, cb) {
    processor = processor.filterEntries(target, entries);
    let tasks = 1;
    const next = () => {
      if (--tasks === 0)
        cb();
    };
    for (const [m, absolute, ifDir] of processor.matches.entries()) {
      if (this.#ignored(m))
        continue;
      this.matchSync(m, absolute, ifDir);
    }
    for (const [target2, patterns] of processor.subwalks.entries()) {
      tasks++;
      this.walkCB2Sync(target2, patterns, processor.child(), next);
    }
    next();
  }
};
var GlobWalker = class extends GlobUtil {
  matches;
  constructor(patterns, path3, opts) {
    super(patterns, path3, opts);
    this.matches = /* @__PURE__ */ new Set();
  }
  matchEmit(e) {
    this.matches.add(e);
  }
  async walk() {
    var _a2;
    if ((_a2 = this.signal) == null ? void 0 : _a2.aborted)
      throw this.signal.reason;
    if (this.path.isUnknown()) {
      await this.path.lstat();
    }
    await new Promise((res, rej) => {
      this.walkCB(this.path, this.patterns, () => {
        var _a3;
        if ((_a3 = this.signal) == null ? void 0 : _a3.aborted) {
          rej(this.signal.reason);
        } else {
          res(this.matches);
        }
      });
    });
    return this.matches;
  }
  walkSync() {
    var _a2;
    if ((_a2 = this.signal) == null ? void 0 : _a2.aborted)
      throw this.signal.reason;
    if (this.path.isUnknown()) {
      this.path.lstatSync();
    }
    this.walkCBSync(this.path, this.patterns, () => {
      var _a3;
      if ((_a3 = this.signal) == null ? void 0 : _a3.aborted)
        throw this.signal.reason;
    });
    return this.matches;
  }
};
var GlobStream = class extends GlobUtil {
  results;
  constructor(patterns, path3, opts) {
    super(patterns, path3, opts);
    this.results = new minipass_default({
      signal: this.signal,
      objectMode: true
    });
    this.results.on("drain", () => this.resume());
    this.results.on("resume", () => this.resume());
  }
  matchEmit(e) {
    this.results.write(e);
    if (!this.results.flowing)
      this.pause();
  }
  stream() {
    const target = this.path;
    if (target.isUnknown()) {
      target.lstat().then(() => {
        this.walkCB(target, this.patterns, () => this.results.end());
      });
    } else {
      this.walkCB(target, this.patterns, () => this.results.end());
    }
    return this.results;
  }
  streamSync() {
    if (this.path.isUnknown()) {
      this.path.lstatSync();
    }
    this.walkCBSync(this.path, this.patterns, () => this.results.end());
    return this.results;
  }
};

// node_modules/rimraf/node_modules/glob/dist/mjs/glob.js
var defaultPlatform3 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
var Glob = class {
  absolute;
  cwd;
  root;
  dot;
  dotRelative;
  follow;
  ignore;
  magicalBraces;
  mark;
  matchBase;
  maxDepth;
  nobrace;
  nocase;
  nodir;
  noext;
  noglobstar;
  pattern;
  platform;
  realpath;
  scurry;
  stat;
  signal;
  windowsPathsNoEscape;
  withFileTypes;
  /**
   * The options provided to the constructor.
   */
  opts;
  /**
   * An array of parsed immutable {@link Pattern} objects.
   */
  patterns;
  /**
   * All options are stored as properties on the `Glob` object.
   *
   * See {@link GlobOptions} for full options descriptions.
   *
   * Note that a previous `Glob` object can be passed as the
   * `GlobOptions` to another `Glob` instantiation to re-use settings
   * and caches with a new pattern.
   *
   * Traversal functions can be called multiple times to run the walk
   * again.
   */
  constructor(pattern, opts) {
    this.withFileTypes = !!opts.withFileTypes;
    this.signal = opts.signal;
    this.follow = !!opts.follow;
    this.dot = !!opts.dot;
    this.dotRelative = !!opts.dotRelative;
    this.nodir = !!opts.nodir;
    this.mark = !!opts.mark;
    if (!opts.cwd) {
      this.cwd = "";
    } else if (opts.cwd instanceof URL || opts.cwd.startsWith("file://")) {
      opts.cwd = (0, import_url.fileURLToPath)(opts.cwd);
    }
    this.cwd = opts.cwd || "";
    this.root = opts.root;
    this.magicalBraces = !!opts.magicalBraces;
    this.nobrace = !!opts.nobrace;
    this.noext = !!opts.noext;
    this.realpath = !!opts.realpath;
    this.absolute = opts.absolute;
    this.noglobstar = !!opts.noglobstar;
    this.matchBase = !!opts.matchBase;
    this.maxDepth = typeof opts.maxDepth === "number" ? opts.maxDepth : Infinity;
    this.stat = !!opts.stat;
    this.ignore = opts.ignore;
    if (this.withFileTypes && this.absolute !== void 0) {
      throw new Error("cannot set absolute and withFileTypes:true");
    }
    if (typeof pattern === "string") {
      pattern = [pattern];
    }
    this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false;
    if (this.windowsPathsNoEscape) {
      pattern = pattern.map((p) => p.replace(/\\/g, "/"));
    }
    if (this.matchBase) {
      if (opts.noglobstar) {
        throw new TypeError("base matching requires globstar");
      }
      pattern = pattern.map((p) => p.includes("/") ? p : `./**/${p}`);
    }
    this.pattern = pattern;
    this.platform = opts.platform || defaultPlatform3;
    this.opts = { ...opts, platform: this.platform };
    if (opts.scurry) {
      this.scurry = opts.scurry;
      if (opts.nocase !== void 0 && opts.nocase !== opts.scurry.nocase) {
        throw new Error("nocase option contradicts provided scurry option");
      }
    } else {
      const Scurry = opts.platform === "win32" ? PathScurryWin32 : opts.platform === "darwin" ? PathScurryDarwin : opts.platform ? PathScurryPosix : PathScurry;
      this.scurry = new Scurry(this.cwd, {
        nocase: opts.nocase,
        fs: opts.fs
      });
    }
    this.nocase = this.scurry.nocase;
    const mmo = {
      // default nocase based on platform
      ...opts,
      dot: this.dot,
      matchBase: this.matchBase,
      nobrace: this.nobrace,
      nocase: this.nocase,
      nocaseMagicOnly: true,
      nocomment: true,
      noext: this.noext,
      nonegate: true,
      optimizationLevel: 2,
      platform: this.platform,
      windowsPathsNoEscape: this.windowsPathsNoEscape,
      debug: !!this.opts.debug
    };
    const mms = this.pattern.map((p) => new Minimatch(p, mmo));
    const [matchSet, globParts] = mms.reduce((set, m) => {
      set[0].push(...m.set);
      set[1].push(...m.globParts);
      return set;
    }, [[], []]);
    this.patterns = matchSet.map((set, i) => {
      return new Pattern(set, globParts[i], 0, this.platform);
    });
  }
  async walk() {
    return [
      ...await new GlobWalker(this.patterns, this.scurry.cwd, {
        ...this.opts,
        maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
        platform: this.platform,
        nocase: this.nocase
      }).walk()
    ];
  }
  walkSync() {
    return [
      ...new GlobWalker(this.patterns, this.scurry.cwd, {
        ...this.opts,
        maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
        platform: this.platform,
        nocase: this.nocase
      }).walkSync()
    ];
  }
  stream() {
    return new GlobStream(this.patterns, this.scurry.cwd, {
      ...this.opts,
      maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
      platform: this.platform,
      nocase: this.nocase
    }).stream();
  }
  streamSync() {
    return new GlobStream(this.patterns, this.scurry.cwd, {
      ...this.opts,
      maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
      platform: this.platform,
      nocase: this.nocase
    }).streamSync();
  }
  /**
   * Default sync iteration function. Returns a Generator that
   * iterates over the results.
   */
  iterateSync() {
    return this.streamSync()[Symbol.iterator]();
  }
  [Symbol.iterator]() {
    return this.iterateSync();
  }
  /**
   * Default async iteration function. Returns an AsyncGenerator that
   * iterates over the results.
   */
  iterate() {
    return this.stream()[Symbol.asyncIterator]();
  }
  [Symbol.asyncIterator]() {
    return this.iterate();
  }
};

// node_modules/rimraf/node_modules/glob/dist/mjs/has-magic.js
var hasMagic = (pattern, options = {}) => {
  if (!Array.isArray(pattern)) {
    pattern = [pattern];
  }
  for (const p of pattern) {
    if (new Minimatch(p, options).hasMagic())
      return true;
  }
  return false;
};

// node_modules/rimraf/node_modules/glob/dist/mjs/index.js
function globStreamSync(pattern, options = {}) {
  return new Glob(pattern, options).streamSync();
}
function globStream(pattern, options = {}) {
  return new Glob(pattern, options).stream();
}
function globSync(pattern, options = {}) {
  return new Glob(pattern, options).walkSync();
}
async function glob(pattern, options = {}) {
  return new Glob(pattern, options).walk();
}
function globIterateSync(pattern, options = {}) {
  return new Glob(pattern, options).iterateSync();
}
function globIterate(pattern, options = {}) {
  return new Glob(pattern, options).iterate();
}
var streamSync = globStreamSync;
var stream = Object.assign(globStream, { sync: globStreamSync });
var iterateSync = globIterateSync;
var iterate = Object.assign(globIterate, {
  sync: globIterateSync
});
var sync = Object.assign(globSync, {
  stream: globStreamSync,
  iterate: globIterateSync
});
var mjs_default = Object.assign(glob, {
  glob,
  globSync,
  sync,
  globStream,
  stream,
  globStreamSync,
  streamSync,
  globIterate,
  iterate,
  globIterateSync,
  iterateSync,
  Glob,
  hasMagic,
  escape,
  unescape
});

// node_modules/rimraf/dist/mjs/fs.js
var import_fs2 = __toESM(require("fs"), 1);
var import_fs3 = require("fs");
var import_fs4 = require("fs");
var readdirSync2 = (path3) => (0, import_fs4.readdirSync)(path3, { withFileTypes: true });
var chmod = (path3, mode) => new Promise((res, rej) => import_fs2.default.chmod(path3, mode, (er, ...d) => er ? rej(er) : res(...d)));
var mkdir = (path3, options) => new Promise((res, rej) => import_fs2.default.mkdir(path3, options, (er, made) => er ? rej(er) : res(made)));
var readdir2 = (path3) => new Promise((res, rej) => import_fs2.default.readdir(path3, { withFileTypes: true }, (er, data) => er ? rej(er) : res(data)));
var rename = (oldPath, newPath) => new Promise((res, rej) => import_fs2.default.rename(oldPath, newPath, (er, ...d) => er ? rej(er) : res(...d)));
var rm = (path3, options) => new Promise((res, rej) => import_fs2.default.rm(path3, options, (er, ...d) => er ? rej(er) : res(...d)));
var rmdir = (path3) => new Promise((res, rej) => import_fs2.default.rmdir(path3, (er, ...d) => er ? rej(er) : res(...d)));
var stat = (path3) => new Promise((res, rej) => import_fs2.default.stat(path3, (er, data) => er ? rej(er) : res(data)));
var lstat2 = (path3) => new Promise((res, rej) => import_fs2.default.lstat(path3, (er, data) => er ? rej(er) : res(data)));
var unlink = (path3) => new Promise((res, rej) => import_fs2.default.unlink(path3, (er, ...d) => er ? rej(er) : res(...d)));
var promises = {
  chmod,
  mkdir,
  readdir: readdir2,
  rename,
  rm,
  rmdir,
  stat,
  lstat: lstat2,
  unlink
};

// node_modules/rimraf/dist/mjs/rimraf-posix.js
var import_path2 = require("path");

// node_modules/rimraf/dist/mjs/readdir-or-error.js
var { readdir: readdir3 } = promises;
var readdirOrError = (path3) => readdir3(path3).catch((er) => er);
var readdirOrErrorSync = (path3) => {
  try {
    return readdirSync2(path3);
  } catch (er) {
    return er;
  }
};

// node_modules/rimraf/dist/mjs/ignore-enoent.js
var ignoreENOENT = async (p) => p.catch((er) => {
  if (er.code !== "ENOENT") {
    throw er;
  }
});
var ignoreENOENTSync = (fn) => {
  try {
    return fn();
  } catch (er) {
    if ((er == null ? void 0 : er.code) !== "ENOENT") {
      throw er;
    }
  }
};

// node_modules/rimraf/dist/mjs/rimraf-posix.js
var { lstat: lstat3, rmdir: rmdir2, unlink: unlink2 } = promises;
var rimrafPosix = async (path3, opt) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  try {
    return await rimrafPosixDir(path3, opt, await lstat3(path3));
  } catch (er) {
    if ((er == null ? void 0 : er.code) === "ENOENT")
      return true;
    throw er;
  }
};
var rimrafPosixSync = (path3, opt) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  try {
    return rimrafPosixDirSync(path3, opt, (0, import_fs3.lstatSync)(path3));
  } catch (er) {
    if ((er == null ? void 0 : er.code) === "ENOENT")
      return true;
    throw er;
  }
};
var rimrafPosixDir = async (path3, opt, ent) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  const entries = ent.isDirectory() ? await readdirOrError(path3) : null;
  if (!Array.isArray(entries)) {
    if (entries) {
      if (entries.code === "ENOENT") {
        return true;
      }
      if (entries.code !== "ENOTDIR") {
        throw entries;
      }
    }
    if (opt.filter && !await opt.filter(path3, ent)) {
      return false;
    }
    await ignoreENOENT(unlink2(path3));
    return true;
  }
  const removedAll = (await Promise.all(entries.map((ent2) => rimrafPosixDir((0, import_path2.resolve)(path3, ent2.name), opt, ent2)))).reduce((a, b) => a && b, true);
  if (!removedAll) {
    return false;
  }
  if (opt.preserveRoot === false && path3 === (0, import_path2.parse)(path3).root) {
    return false;
  }
  if (opt.filter && !await opt.filter(path3, ent)) {
    return false;
  }
  await ignoreENOENT(rmdir2(path3));
  return true;
};
var rimrafPosixDirSync = (path3, opt, ent) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  const entries = ent.isDirectory() ? readdirOrErrorSync(path3) : null;
  if (!Array.isArray(entries)) {
    if (entries) {
      if (entries.code === "ENOENT") {
        return true;
      }
      if (entries.code !== "ENOTDIR") {
        throw entries;
      }
    }
    if (opt.filter && !opt.filter(path3, ent)) {
      return false;
    }
    ignoreENOENTSync(() => (0, import_fs3.unlinkSync)(path3));
    return true;
  }
  let removedAll = true;
  for (const ent2 of entries) {
    const p = (0, import_path2.resolve)(path3, ent2.name);
    removedAll = rimrafPosixDirSync(p, opt, ent2) && removedAll;
  }
  if (opt.preserveRoot === false && path3 === (0, import_path2.parse)(path3).root) {
    return false;
  }
  if (!removedAll) {
    return false;
  }
  if (opt.filter && !opt.filter(path3, ent)) {
    return false;
  }
  ignoreENOENTSync(() => (0, import_fs3.rmdirSync)(path3));
  return true;
};

// node_modules/rimraf/dist/mjs/rimraf-windows.js
var import_path5 = require("path");

// node_modules/rimraf/dist/mjs/fix-eperm.js
var { chmod: chmod2 } = promises;
var fixEPERM = (fn) => async (path3) => {
  try {
    return await fn(path3);
  } catch (er) {
    const fer = er;
    if ((fer == null ? void 0 : fer.code) === "ENOENT") {
      return;
    }
    if ((fer == null ? void 0 : fer.code) === "EPERM") {
      try {
        await chmod2(path3, 438);
      } catch (er2) {
        const fer2 = er2;
        if ((fer2 == null ? void 0 : fer2.code) === "ENOENT") {
          return;
        }
        throw er;
      }
      return await fn(path3);
    }
    throw er;
  }
};
var fixEPERMSync = (fn) => (path3) => {
  try {
    return fn(path3);
  } catch (er) {
    const fer = er;
    if ((fer == null ? void 0 : fer.code) === "ENOENT") {
      return;
    }
    if ((fer == null ? void 0 : fer.code) === "EPERM") {
      try {
        (0, import_fs3.chmodSync)(path3, 438);
      } catch (er2) {
        const fer2 = er2;
        if ((fer2 == null ? void 0 : fer2.code) === "ENOENT") {
          return;
        }
        throw er;
      }
      return fn(path3);
    }
    throw er;
  }
};

// node_modules/rimraf/dist/mjs/retry-busy.js
var MAXBACKOFF = 200;
var RATE = 1.2;
var MAXRETRIES = 10;
var codes = /* @__PURE__ */ new Set(["EMFILE", "ENFILE", "EBUSY"]);
var retryBusy = (fn) => {
  const method = async (path3, opt, backoff = 1, total = 0) => {
    const mbo = opt.maxBackoff || MAXBACKOFF;
    const rate = opt.backoff || RATE;
    const max2 = opt.maxRetries || MAXRETRIES;
    let retries = 0;
    while (true) {
      try {
        return await fn(path3);
      } catch (er) {
        const fer = er;
        if ((fer == null ? void 0 : fer.path) === path3 && (fer == null ? void 0 : fer.code) && codes.has(fer.code)) {
          backoff = Math.ceil(backoff * rate);
          total = backoff + total;
          if (total < mbo) {
            return new Promise((res, rej) => {
              setTimeout(() => {
                method(path3, opt, backoff, total).then(res, rej);
              }, backoff);
            });
          }
          if (retries < max2) {
            retries++;
            continue;
          }
        }
        throw er;
      }
    }
  };
  return method;
};
var retryBusySync = (fn) => {
  const method = (path3, opt) => {
    const max2 = opt.maxRetries || MAXRETRIES;
    let retries = 0;
    while (true) {
      try {
        return fn(path3);
      } catch (er) {
        const fer = er;
        if ((fer == null ? void 0 : fer.path) === path3 && (fer == null ? void 0 : fer.code) && codes.has(fer.code) && retries < max2) {
          retries++;
          continue;
        }
        throw er;
      }
    }
  };
  return method;
};

// node_modules/rimraf/dist/mjs/rimraf-move-remove.js
var import_path4 = require("path");

// node_modules/rimraf/dist/mjs/default-tmp.js
var import_os = require("os");
var import_path3 = require("path");
var { stat: stat2 } = promises;
var isDirSync = (path3) => {
  try {
    return (0, import_fs3.statSync)(path3).isDirectory();
  } catch (er) {
    return false;
  }
};
var isDir = (path3) => stat2(path3).then((st) => st.isDirectory(), () => false);
var win32DefaultTmp = async (path3) => {
  const { root: root2 } = (0, import_path3.parse)(path3);
  const tmp = (0, import_os.tmpdir)();
  const { root: tmpRoot } = (0, import_path3.parse)(tmp);
  if (root2.toLowerCase() === tmpRoot.toLowerCase()) {
    return tmp;
  }
  const driveTmp = (0, import_path3.resolve)(root2, "/temp");
  if (await isDir(driveTmp)) {
    return driveTmp;
  }
  return root2;
};
var win32DefaultTmpSync = (path3) => {
  const { root: root2 } = (0, import_path3.parse)(path3);
  const tmp = (0, import_os.tmpdir)();
  const { root: tmpRoot } = (0, import_path3.parse)(tmp);
  if (root2.toLowerCase() === tmpRoot.toLowerCase()) {
    return tmp;
  }
  const driveTmp = (0, import_path3.resolve)(root2, "/temp");
  if (isDirSync(driveTmp)) {
    return driveTmp;
  }
  return root2;
};
var posixDefaultTmp = async () => (0, import_os.tmpdir)();
var posixDefaultTmpSync = () => (0, import_os.tmpdir)();
var defaultTmp = platform_default === "win32" ? win32DefaultTmp : posixDefaultTmp;
var defaultTmpSync = platform_default === "win32" ? win32DefaultTmpSync : posixDefaultTmpSync;

// node_modules/rimraf/dist/mjs/rimraf-move-remove.js
var { lstat: lstat4, rename: rename2, unlink: unlink3, rmdir: rmdir3, chmod: chmod3 } = promises;
var uniqueFilename = (path3) => `.${(0, import_path4.basename)(path3)}.${Math.random()}`;
var unlinkFixEPERM = async (path3) => unlink3(path3).catch((er) => {
  if (er.code === "EPERM") {
    return chmod3(path3, 438).then(() => unlink3(path3), (er2) => {
      if (er2.code === "ENOENT") {
        return;
      }
      throw er;
    });
  } else if (er.code === "ENOENT") {
    return;
  }
  throw er;
});
var unlinkFixEPERMSync = (path3) => {
  try {
    (0, import_fs3.unlinkSync)(path3);
  } catch (er) {
    if ((er == null ? void 0 : er.code) === "EPERM") {
      try {
        return (0, import_fs3.chmodSync)(path3, 438);
      } catch (er2) {
        if ((er2 == null ? void 0 : er2.code) === "ENOENT") {
          return;
        }
        throw er;
      }
    } else if ((er == null ? void 0 : er.code) === "ENOENT") {
      return;
    }
    throw er;
  }
};
var rimrafMoveRemove = async (path3, opt) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  try {
    return await rimrafMoveRemoveDir(path3, opt, await lstat4(path3));
  } catch (er) {
    if ((er == null ? void 0 : er.code) === "ENOENT")
      return true;
    throw er;
  }
};
var rimrafMoveRemoveDir = async (path3, opt, ent) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  if (!opt.tmp) {
    return rimrafMoveRemoveDir(path3, { ...opt, tmp: await defaultTmp(path3) }, ent);
  }
  if (path3 === opt.tmp && (0, import_path4.parse)(path3).root !== path3) {
    throw new Error("cannot delete temp directory used for deletion");
  }
  const entries = ent.isDirectory() ? await readdirOrError(path3) : null;
  if (!Array.isArray(entries)) {
    if (entries) {
      if (entries.code === "ENOENT") {
        return true;
      }
      if (entries.code !== "ENOTDIR") {
        throw entries;
      }
    }
    if (opt.filter && !await opt.filter(path3, ent)) {
      return false;
    }
    await ignoreENOENT(tmpUnlink(path3, opt.tmp, unlinkFixEPERM));
    return true;
  }
  const removedAll = (await Promise.all(entries.map((ent2) => rimrafMoveRemoveDir((0, import_path4.resolve)(path3, ent2.name), opt, ent2)))).reduce((a, b) => a && b, true);
  if (!removedAll) {
    return false;
  }
  if (opt.preserveRoot === false && path3 === (0, import_path4.parse)(path3).root) {
    return false;
  }
  if (opt.filter && !await opt.filter(path3, ent)) {
    return false;
  }
  await ignoreENOENT(tmpUnlink(path3, opt.tmp, rmdir3));
  return true;
};
var tmpUnlink = async (path3, tmp, rm3) => {
  const tmpFile = (0, import_path4.resolve)(tmp, uniqueFilename(path3));
  await rename2(path3, tmpFile);
  return await rm3(tmpFile);
};
var rimrafMoveRemoveSync = (path3, opt) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  try {
    return rimrafMoveRemoveDirSync(path3, opt, (0, import_fs3.lstatSync)(path3));
  } catch (er) {
    if ((er == null ? void 0 : er.code) === "ENOENT")
      return true;
    throw er;
  }
};
var rimrafMoveRemoveDirSync = (path3, opt, ent) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  if (!opt.tmp) {
    return rimrafMoveRemoveDirSync(path3, { ...opt, tmp: defaultTmpSync(path3) }, ent);
  }
  const tmp = opt.tmp;
  if (path3 === opt.tmp && (0, import_path4.parse)(path3).root !== path3) {
    throw new Error("cannot delete temp directory used for deletion");
  }
  const entries = ent.isDirectory() ? readdirOrErrorSync(path3) : null;
  if (!Array.isArray(entries)) {
    if (entries) {
      if (entries.code === "ENOENT") {
        return true;
      }
      if (entries.code !== "ENOTDIR") {
        throw entries;
      }
    }
    if (opt.filter && !opt.filter(path3, ent)) {
      return false;
    }
    ignoreENOENTSync(() => tmpUnlinkSync(path3, tmp, unlinkFixEPERMSync));
    return true;
  }
  let removedAll = true;
  for (const ent2 of entries) {
    const p = (0, import_path4.resolve)(path3, ent2.name);
    removedAll = rimrafMoveRemoveDirSync(p, opt, ent2) && removedAll;
  }
  if (!removedAll) {
    return false;
  }
  if (opt.preserveRoot === false && path3 === (0, import_path4.parse)(path3).root) {
    return false;
  }
  if (opt.filter && !opt.filter(path3, ent)) {
    return false;
  }
  ignoreENOENTSync(() => tmpUnlinkSync(path3, tmp, import_fs3.rmdirSync));
  return true;
};
var tmpUnlinkSync = (path3, tmp, rmSync2) => {
  const tmpFile = (0, import_path4.resolve)(tmp, uniqueFilename(path3));
  (0, import_fs3.renameSync)(path3, tmpFile);
  return rmSync2(tmpFile);
};

// node_modules/rimraf/dist/mjs/rimraf-windows.js
var { unlink: unlink4, rmdir: rmdir4, lstat: lstat5 } = promises;
var rimrafWindowsFile = retryBusy(fixEPERM(unlink4));
var rimrafWindowsFileSync = retryBusySync(fixEPERMSync(import_fs3.unlinkSync));
var rimrafWindowsDirRetry = retryBusy(fixEPERM(rmdir4));
var rimrafWindowsDirRetrySync = retryBusySync(fixEPERMSync(import_fs3.rmdirSync));
var rimrafWindowsDirMoveRemoveFallback = async (path3, opt) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  const { filter: filter2, ...options } = opt;
  try {
    return await rimrafWindowsDirRetry(path3, options);
  } catch (er) {
    if ((er == null ? void 0 : er.code) === "ENOTEMPTY") {
      return await rimrafMoveRemove(path3, options);
    }
    throw er;
  }
};
var rimrafWindowsDirMoveRemoveFallbackSync = (path3, opt) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  const { filter: filter2, ...options } = opt;
  try {
    return rimrafWindowsDirRetrySync(path3, options);
  } catch (er) {
    const fer = er;
    if ((fer == null ? void 0 : fer.code) === "ENOTEMPTY") {
      return rimrafMoveRemoveSync(path3, options);
    }
    throw er;
  }
};
var START = Symbol("start");
var CHILD = Symbol("child");
var FINISH = Symbol("finish");
var rimrafWindows = async (path3, opt) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  try {
    return await rimrafWindowsDir(path3, opt, await lstat5(path3), START);
  } catch (er) {
    if ((er == null ? void 0 : er.code) === "ENOENT")
      return true;
    throw er;
  }
};
var rimrafWindowsSync = (path3, opt) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  try {
    return rimrafWindowsDirSync(path3, opt, (0, import_fs3.lstatSync)(path3), START);
  } catch (er) {
    if ((er == null ? void 0 : er.code) === "ENOENT")
      return true;
    throw er;
  }
};
var rimrafWindowsDir = async (path3, opt, ent, state = START) => {
  var _a2;
  if ((_a2 = opt == null ? void 0 : opt.signal) == null ? void 0 : _a2.aborted) {
    throw opt.signal.reason;
  }
  const entries = ent.isDirectory() ? await readdirOrError(path3) : null;
  if (!Array.isArray(entries)) {
    if (entries) {
      if (entries.code === "ENOENT") {
        return true;
      }
      if (entries.code !== "ENOTDIR") {
        throw entries;
      }
    }
    if (opt.filter && !await opt.filter(path3, ent)) {
      return false;
    }
    await ignoreENOENT(rimrafWindowsFile(path3, opt));
    return true;
  }
  const s = state === START ? CHILD : state;
  const removedAll = (await Promise.all(entries.map((ent2) => rimrafWindowsDir((0, import_path5.resolve)(path3, ent2.name), opt, ent2, s)))).reduce((a, b) => a && b, true);
  if (state === START) {
    return rimrafWindowsDir(path3, opt, ent, FINISH);
  } else if (state === FINISH) {
    if (opt.preserveRoot === false && path3 === (0, import_path5.parse)(path3).root) {
      return false;
    }
    if (!removedAll) {
      return false;
    }
    if (opt.filter && !await opt.filter(path3, ent)) {
      return false;
    }
    await ignoreENOENT(rimrafWindowsDirMoveRemoveFallback(path3, opt));
  }
  return true;
};
var rimrafWindowsDirSync = (path3, opt, ent, state = START) => {
  const entries = ent.isDirectory() ? readdirOrErrorSync(path3) : null;
  if (!Array.isArray(entries)) {
    if (entries) {
      if (entries.code === "ENOENT") {
        return true;
      }
      if (entries.code !== "ENOTDIR") {
        throw entries;
      }
    }
    if (opt.filter && !opt.filter(path3, ent)) {
      return false;
    }
    ignoreENOENTSync(() => rimrafWindowsFileSync(path3, opt));
    return true;
  }
  let removedAll = true;
  for (const ent2 of entries) {
    const s = state === START ? CHILD : state;
    const p = (0, import_path5.resolve)(path3, ent2.name);
    removedAll = rimrafWindowsDirSync(p, opt, ent2, s) && removedAll;
  }
  if (state === START) {
    return rimrafWindowsDirSync(path3, opt, ent, FINISH);
  } else if (state === FINISH) {
    if (opt.preserveRoot === false && path3 === (0, import_path5.parse)(path3).root) {
      return false;
    }
    if (!removedAll) {
      return false;
    }
    if (opt.filter && !opt.filter(path3, ent)) {
      return false;
    }
    ignoreENOENTSync(() => {
      rimrafWindowsDirMoveRemoveFallbackSync(path3, opt);
    });
  }
  return true;
};

// node_modules/rimraf/dist/mjs/rimraf-manual.js
var rimrafManual = platform_default === "win32" ? rimrafWindows : rimrafPosix;
var rimrafManualSync = platform_default === "win32" ? rimrafWindowsSync : rimrafPosixSync;

// node_modules/rimraf/dist/mjs/rimraf-native.js
var { rm: rm2 } = promises;
var rimrafNative = async (path3, opt) => {
  await rm2(path3, {
    ...opt,
    force: true,
    recursive: true
  });
  return true;
};
var rimrafNativeSync = (path3, opt) => {
  (0, import_fs3.rmSync)(path3, {
    ...opt,
    force: true,
    recursive: true
  });
  return true;
};

// node_modules/rimraf/dist/mjs/use-native.js
var version2 = process.env.__TESTING_RIMRAF_NODE_VERSION__ || process.version;
var versArr = version2.replace(/^v/, "").split(".");
var hasNative = +versArr[0] > 14 || +versArr[0] === 14 && +versArr[1] >= 14;
var useNative = !hasNative || platform_default === "win32" ? () => false : (opt) => !(opt == null ? void 0 : opt.signal) && !(opt == null ? void 0 : opt.filter);
var useNativeSync = !hasNative || platform_default === "win32" ? () => false : (opt) => !(opt == null ? void 0 : opt.signal) && !(opt == null ? void 0 : opt.filter);

// node_modules/rimraf/dist/mjs/index.js
var typeOrUndef = (val, t) => typeof val === "undefined" || typeof val === t;
var isRimrafOptions = (o) => !!o && typeof o === "object" && typeOrUndef(o.preserveRoot, "boolean") && typeOrUndef(o.tmp, "string") && typeOrUndef(o.maxRetries, "number") && typeOrUndef(o.retryDelay, "number") && typeOrUndef(o.backoff, "number") && typeOrUndef(o.maxBackoff, "number") && (typeOrUndef(o.glob, "boolean") || o.glob && typeof o.glob === "object") && typeOrUndef(o.filter, "function");
var assertRimrafOptions = (o) => {
  if (!isRimrafOptions(o)) {
    throw new Error("invalid rimraf options");
  }
};
var wrap = (fn) => async (path3, opt) => {
  const options = optArg(opt);
  if (options.glob) {
    path3 = await glob(path3, options.glob);
  }
  if (Array.isArray(path3)) {
    return !!(await Promise.all(path3.map((p) => fn(path_arg_default(p, options), options)))).reduce((a, b) => a && b, true);
  } else {
    return !!await fn(path_arg_default(path3, options), options);
  }
};
var wrapSync = (fn) => (path3, opt) => {
  const options = optArgSync(opt);
  if (options.glob) {
    path3 = globSync(path3, options.glob);
  }
  if (Array.isArray(path3)) {
    return !!path3.map((p) => fn(path_arg_default(p, options), options)).reduce((a, b) => a && b, true);
  } else {
    return !!fn(path_arg_default(path3, options), options);
  }
};
var nativeSync = wrapSync(rimrafNativeSync);
var native = Object.assign(wrap(rimrafNative), { sync: nativeSync });
var manualSync = wrapSync(rimrafManualSync);
var manual = Object.assign(wrap(rimrafManual), { sync: manualSync });
var windowsSync = wrapSync(rimrafWindowsSync);
var windows = Object.assign(wrap(rimrafWindows), { sync: windowsSync });
var posixSync = wrapSync(rimrafPosixSync);
var posix2 = Object.assign(wrap(rimrafPosix), { sync: posixSync });
var moveRemoveSync = wrapSync(rimrafMoveRemoveSync);
var moveRemove = Object.assign(wrap(rimrafMoveRemove), {
  sync: moveRemoveSync
});
var rimrafSync = wrapSync((path3, opt) => useNativeSync(opt) ? rimrafNativeSync(path3, opt) : rimrafManualSync(path3, opt));
var rimraf = Object.assign(wrap((path3, opt) => useNative(opt) ? rimrafNative(path3, opt) : rimrafManual(path3, opt)), {
  // this weirdness because it's easier than explicitly declaring
  rimraf: manual,
  sync: rimrafSync,
  rimrafSync,
  manual,
  manualSync,
  native,
  nativeSync,
  posix: posix2,
  posixSync,
  windows,
  windowsSync,
  moveRemove,
  moveRemoveSync
});
rimraf.rimraf = rimraf;

// src/util/fs.ts
var import_util11 = require("util");

// src/util/cli.ts
var import_child_process = require("child_process");
var import_which = __toESM(require_lib());
var execCmd = (name, args, options) => {
  const streams = (0, import_child_process.spawn)(name, args, options);
  let output = "";
  streams.stdout.on("data", (data) => {
    output += data.toString();
  });
  return new Promise((resolve6, reject) => {
    streams.stdout.on("error", (error) => {
      reject(error);
    });
    streams.stdout.on("end", () => {
      resolve6(output);
    });
  });
};
var execCmdLine = (command, options) => {
  return new Promise((resolve6, reject) => {
    (0, import_child_process.exec)(command, options, (error, stdout) => {
      if (error) {
        return reject(error);
      }
      resolve6(stdout.toString("utf8"));
    });
  });
};
function shellescape(s) {
  if (process.platform === "win32") {
    return `"${s.replace(/"/g, '\\"')}"`;
  }
  if (/[^A-Za-z0-9_/:=-]/.test(s)) {
    s = `'${s.replace(/'/g, "'\\''")}'`;
    s = s.replace(/^(?:'')+/g, "").replace(/\\'''/g, "\\'");
    return s;
  }
  return s;
}
var executable = async (cmd) => {
  try {
    await (0, import_which.default)(cmd);
  } catch (e) {
    return false;
  }
  return true;
};

// src/util/platform.ts
var isWindows2 = process.platform === "win32";
var isMacos = process.platform === "darwin";
var isLinux2 = process.platform === "linux";

// src/util/trash.ts
var import_path6 = __toESM(require("path"));

// src/config.ts
var import_coc16 = require("coc.nvim");
var config = import_coc16.workspace.getConfiguration("explorer");
var configLocal = (resource = generateUri2(import_coc16.workspace.cwd)) => import_coc16.workspace.getConfiguration("explorer", resource);
var bufferTabOnly = () => {
  return config.get("buffer.tabOnly");
};
var getRevealWhenOpen = (config4, revealWhenOpenArg) => {
  if (revealWhenOpenArg !== void 0) {
    return revealWhenOpenArg;
  }
  return config4.get("file.reveal.whenOpen");
};
function buildExplorerConfig(config4) {
  return {
    get config() {
      return config4;
    },
    get(section, defaultValue) {
      return this.config.get(section, defaultValue);
    }
  };
}

// src/util/trash.ts
var nodejsModuleTrash = async (paths) => {
  const nodePath = process.argv[0];
  if (!nodePath)
    return;
  const scriptPath = import_path6.default.join(__dirname, "../cli/trash.mjs");
  const pathArgs = paths.map((p) => shellescape(p)).join(" ");
  const cmd = `${shellescape(nodePath)} ${shellescape(scriptPath)} ${pathArgs}`;
  await execCmdLine(cmd);
};
var TrashTemplateCmd = class {
  constructor() {
    this.inited = false;
    this.placeholders = {
      list: "%l",
      sourceFile: "%s"
    };
    this.exec_ = async () => {
    };
  }
  async init() {
    if (this.inited) {
      return;
    }
    const configTrashCommand = config.get("trash.command");
    if (configTrashCommand === "nodejs:module") {
      this.exec_ = async (paths) => {
        await nodejsModuleTrash(paths);
      };
      return;
    }
    const m = configTrashCommand.match(/^([^\s]+)/);
    const cmd = m == null ? void 0 : m[1];
    if (!cmd) {
      this.exec_ = async () => {
        throw new Error("'explorer.trash.command' must not be empty");
      };
      return;
    }
    const checkCmd = async (cmd2) => {
      if (!await executable(cmd2)) {
        throw new Error(`command(${cmd2}) does not exist`);
      }
    };
    if (configTrashCommand.includes(this.placeholders.list)) {
      this.exec_ = async (paths) => {
        await checkCmd(cmd);
        const pathArgs = paths.map((p) => shellescape(p)).join(" ");
        await execCmdLine(
          configTrashCommand.replace(
            new RegExp(this.placeholders.list, "g"),
            pathArgs
          )
        );
      };
    } else if (configTrashCommand.includes(this.placeholders.sourceFile)) {
      this.exec_ = async (paths) => {
        await checkCmd(cmd);
        for (const path3 of paths.map((p) => shellescape(p))) {
          await execCmdLine(
            configTrashCommand.replace(
              new RegExp(this.placeholders.sourceFile, "g"),
              path3
            )
          );
        }
      };
    }
    this.inited = true;
  }
  async exec(paths) {
    await this.init();
    await this.exec_(paths);
  }
};
var trashCmd = new TrashTemplateCmd();

// src/util/fs.ts
var import_minimatch8 = __toESM(require_minimatch());
var fsOpen = (0, import_util11.promisify)(import_fs12.default.open);
var fsClose = (0, import_util11.promisify)(import_fs12.default.close);
var fsTouch = async (path3) => await fsClose(await fsOpen(path3, "w"));
var fsMkdirp = import_make_dir.default;
var fsReaddir = (0, import_util11.promisify)(import_fs12.default.readdir);
var fsReadlink = (0, import_util11.promisify)(import_fs12.default.readlink);
var fsAccess = (path3, mode) => new Promise((resolve6) => {
  import_fs12.default.access(path3, mode, (err) => {
    err ? resolve6(false) : resolve6(true);
  });
});
var fsWriteFile = (0, import_util11.promisify)(import_fs12.default.writeFile);
var fsReadFile = (0, import_util11.promisify)(import_fs12.default.readFile);
var fsExists = fsAccess;
var fsStat = (0, import_util11.promisify)(import_fs12.default.stat);
var fsLstat = (0, import_util11.promisify)(import_fs12.default.lstat);
var fsCopyFile = (0, import_util11.promisify)(import_fs12.default.copyFile);
var fsRename = (0, import_util11.promisify)(import_fs12.default.rename);
var fsRemove = rimraf;
var fsTrash = async (paths) => {
  await trashCmd.exec(typeof paths === "string" ? [paths] : paths);
};
async function fsCopyFileRecursive(sourcePath, targetPath) {
  const lstat6 = await fsLstat(sourcePath);
  if (lstat6.isDirectory()) {
    await fsMkdirp(targetPath);
    const filenames = await fsReaddir(sourcePath);
    for (const filename of filenames) {
      await fsCopyFileRecursive(
        import_path7.default.join(sourcePath, filename),
        import_path7.default.join(targetPath, filename)
      );
    }
  } else {
    await fsCopyFile(sourcePath, targetPath);
  }
}
async function fsMergeDirectory(sourceDir, targetDir, action) {
  const filenames = await fsReaddir(sourceDir);
  for (const filename of filenames) {
    const sourcePath = import_path7.default.join(sourceDir, filename);
    const targetPath = import_path7.default.join(targetDir, filename);
    if (await fsExists(targetPath)) {
      const sourceLstat = await fsLstat(sourcePath);
      const targetLstat = await fsLstat(targetPath);
      if (sourceLstat.isDirectory() && targetLstat.isDirectory()) {
        await fsMergeDirectory(sourcePath, targetPath, action);
      } else {
        await fsTrash(targetPath);
        await action(sourcePath, targetPath);
      }
    } else {
      await action(sourcePath, targetPath);
    }
  }
}
async function overwritePrompt(promptText, paths, action) {
  const endFullpaths = [];
  const finalAction = async (source, target) => {
    await fsMkdirp(import_path7.default.dirname(target));
    await action(source, target);
    endFullpaths.push(target);
  };
  for (let i = 0, len = paths.length; i < len; i++) {
    const sourcePath = paths[i].source;
    const targetPath = paths[i].target;
    if (!await fsExists(targetPath)) {
      await finalAction(sourcePath, targetPath);
      continue;
    }
    const sourceLstat = typeof sourcePath === "string" ? await fsLstat(sourcePath) : void 0;
    const targetLstat = await fsLstat(targetPath);
    const rename3 = async function() {
      const newTargetPath = await input(
        `Rename: ${targetPath} ->`,
        targetPath,
        "file"
      );
      if (!newTargetPath) {
        i -= 1;
        return;
      }
      return finalAction(sourcePath, newTargetPath);
    };
    const replace = async function() {
      await fsTrash(targetPath);
      return finalAction(sourcePath, targetPath);
    };
    const quit = function() {
      i = len;
    };
    const prompt_ = async function(choices = {}) {
      var _a2, _b;
      choices = {
        skip: void 0,
        rename: rename3,
        "force replace": replace,
        ...choices,
        quit
      };
      const answer = await prompt(
        `${((_a2 = promptText[0]) == null ? void 0 : _a2.toUpperCase()) ?? ""}${promptText.slice(
          1
        )}: ${targetPath} already exists.`,
        Object.keys(choices)
      );
      if (answer && answer in choices) {
        return (_b = choices[answer]) == null ? void 0 : _b.call(choices);
      }
    };
    if (sourcePath && (sourceLstat == null ? void 0 : sourceLstat.isDirectory())) {
      if (targetLstat.isDirectory()) {
        await prompt_({
          merge: () => fsMergeDirectory(sourcePath, targetPath, finalAction),
          "one by one": async () => {
            const files = await fsReaddir(sourcePath);
            const paths2 = files.map((source) => ({
              source,
              target: import_path7.default.join(targetPath, import_path7.default.basename(source))
            }));
            await overwritePrompt(promptText, paths2, action);
          }
        });
      } else {
        await prompt_();
      }
    } else {
      if (targetLstat.isDirectory()) {
        await prompt_();
      } else {
        await prompt_();
      }
    }
  }
  return { endFullpaths };
}
function readFileLines(fullpath, start, end) {
  if (!import_fs12.default.existsSync(fullpath)) {
    return Promise.reject(new Error(`file does not exist: ${fullpath}`));
  }
  const res = [];
  const stream2 = import_fs12.default.createReadStream(fullpath, { encoding: "utf8" });
  const rl = import_readline.default.createInterface({
    input: stream2,
    crlfDelay: Infinity,
    terminal: false
  });
  let n = 0;
  return new Promise((resolve6, reject) => {
    stream2.on("error", reject);
    rl.on("line", (line) => {
      if (n === 0 && line.startsWith("\uFEFF")) {
        line = line.slice(1);
      }
      if (n >= start && n <= end) {
        res.push(line);
      }
      if (n === end) {
        rl.close();
      }
      n = n + 1;
    });
    rl.on("close", () => {
      resolve6(res);
    });
    rl.on("error", reject);
  });
}
async function inDirectory(dir, patterns) {
  try {
    const files = await fsReaddir(dir);
    for (const pattern of patterns) {
      const isWildcard = pattern.includes("*");
      const ret = isWildcard ? import_minimatch8.default.match(files, pattern, {
        nobrace: true,
        noext: true,
        nocomment: true,
        nonegate: true,
        dot: true
      }).length !== 0 : files.includes(pattern);
      if (ret)
        return true;
    }
  } catch {
  }
  return false;
}
function displayedFullpath(s) {
  const homePath = import_os2.default.homedir();
  if (s.startsWith(homePath)) {
    return `~${s.slice(homePath.length)}`;
  }
  return s;
}
async function listDrive() {
  if (isWindows2) {
    const content = await execCmd("wmic", ["logicaldisk", "get", "name"]);
    const list = content.split("\n").map((d) => d.trim()).filter((d) => d.endsWith(":")).map((d) => `${d}\\`);
    return list;
  } else {
    throw new Error(`not support listDrive in ${process.platform}`);
  }
}

// src/util/path.ts
var import_os3 = __toESM(require("os"));
var import_path8 = __toESM(require("path"));
function getExtensions(filename) {
  const parts = import_path8.default.basename(filename).split(".");
  const [basename2, ...extensions3] = parts;
  if (basename2) {
    return { basename: basename2, extensions: extensions3 };
  } else {
    const [basename22, ...extensions22] = extensions3;
    return {
      basename: [basename2, basename22].join("."),
      extensions: extensions22
    };
  }
}
function normalizePath(path3) {
  var _a2;
  let _path = import_path8.default.normalize(path3);
  if (_path[0] === "~") {
    _path = import_path8.default.join(import_os3.default.homedir(), _path.slice(1));
  }
  if (isWindows2 && /[a-z]:/.test(_path)) {
    const driveChar = ((_a2 = _path[0]) == null ? void 0 : _a2.toUpperCase()) ?? "";
    _path = driveChar + _path.slice(1);
  }
  return _path;
}
function isParentFolder(folder, filepath) {
  let finalFolder = normalizePath(import_path8.default.resolve(folder));
  const finalFilepath = normalizePath(import_path8.default.resolve(filepath));
  if (finalFolder === "//")
    finalFolder = "/";
  if (finalFolder.endsWith(import_path8.default.sep))
    return finalFilepath.startsWith(finalFolder);
  return finalFilepath.startsWith(finalFolder) && finalFilepath[finalFolder.length] === import_path8.default.sep;
}

// src/util/vim.ts
var import_coc17 = require("coc.nvim");
var import_color_convert = __toESM(require_color_convert());
function supportedFloat() {
  return import_coc17.workspace.floatSupported;
}
function supportedNvimFloating() {
  return import_coc17.workspace.isNvim && supportedFloat();
}
async function enableWrapscan() {
  const wrapscan = await import_coc17.workspace.nvim.getOption("wrapscan");
  return !!wrapscan;
}
function generateHighlightFg(groupName, hl) {
  if (!hl) {
    return;
  }
  const guifg = hl.guifg;
  if (guifg) {
    const ctermfg = hl.ctermfg ?? import_color_convert.default.rgb.ansi256([guifg.red, guifg.green, guifg.blue]);
    return `highlight default ${groupName} ctermfg=${ctermfg} guifg=#${toHex(
      guifg
    )}`;
  } else if (hl.ctermfg) {
    return `highlight default ${groupName} ctermfg=${hl.ctermfg}`;
  }
}
async function displayWidth2(str) {
  return import_coc17.workspace.nvim.strWidth(str);
}
async function displaySlice(str, start, end) {
  return await import_coc17.workspace.nvim.call("coc_explorer#util#strdisplayslice", [
    str,
    start,
    end ?? void 0
  ]);
}
function closeWinByBufnrNotifier(bufnrs) {
  return Notifier.create(() => {
    import_coc17.workspace.nvim.call("coc_explorer#util#close_win_by_bufnr", bufnrs, true);
  });
}
async function winnrByBufnr(bufnr) {
  if (!bufnr) {
    return void 0;
  }
  return import_coc17.workspace.nvim.call("bufwinnr", bufnr).then((winnr) => {
    if (winnr > 0) {
      return winnr;
    } else {
      return void 0;
    }
  });
}
async function winidByWinnr(winnr) {
  if (!winnr) {
    return void 0;
  }
  const winid = await import_coc17.workspace.nvim.call("win_getid", winnr);
  if (winid >= 0) {
    return winid;
  } else {
    return void 0;
  }
}
async function winidByBufnr(bufnr) {
  if (!bufnr) {
    return void 0;
  }
  const winnr = await winnrByBufnr(bufnr);
  if (winnr) {
    return winidByWinnr(winnr);
  }
  const winid = await import_coc17.workspace.nvim.call("bufwinid", [bufnr]);
  if (winid === -1) {
    return void 0;
  }
}
async function winByWinid(winid) {
  if (winid) {
    return import_coc17.workspace.nvim.createWindow(winid);
  } else {
    return void 0;
  }
}
async function bufnrByWinnrOrWinid(winnrOrWinid) {
  if (!winnrOrWinid) {
    return void 0;
  }
  const bufnr = await import_coc17.workspace.nvim.call("winbufnr", winnrOrWinid);
  if (bufnr >= 0) {
    return bufnr;
  } else {
    return void 0;
  }
}
async function winidsByBufnr(bufnr) {
  return await import_coc17.workspace.nvim.call("win_findbuf", [bufnr]);
}
async function winidsByBufnrInCurTab(bufnr) {
  const tabpage = await import_coc17.workspace.nvim.tabpage;
  const wins = await tabpage.windows;
  const winidsOfTab = wins.map((win) => win.id);
  const allWinids = await import_coc17.workspace.nvim.call("win_findbuf", [
    bufnr
  ]);
  return allWinids.filter((winid) => winidsOfTab.includes(winid));
}
async function leaveEmptyInWinids(winids) {
  const curWinid = await import_coc17.workspace.nvim.call("win_getid", []);
  if (!winids.length) {
    return;
  }
  import_coc17.workspace.nvim.pauseNotification();
  for (const winid of winids) {
    import_coc17.workspace.nvim.call("win_gotoid", [winid], true);
    import_coc17.workspace.nvim.command("enew", true);
    if (import_coc17.workspace.isVim) {
      import_coc17.workspace.nvim.command("redraw", true);
    }
  }
  import_coc17.workspace.nvim.call("win_gotoid", [curWinid], true);
  await import_coc17.workspace.nvim.resumeNotification();
}
async function currentBufnr() {
  return import_coc17.workspace.nvim.call("bufnr");
}

// src/util/ui.ts
var import_coc18 = require("coc.nvim");
var floatInputExt;
async function getFloatInputApi() {
  if (!floatInputExt) {
    floatInputExt = import_coc18.extensions.all.find((e) => e.id === "coc-floatinput");
  }
  return floatInputExt == null ? void 0 : floatInputExt.exports;
}
async function getFloatUI() {
  var _a2;
  if (!config.get("enableFloatinput")) {
    return void 0;
  }
  return (_a2 = await getFloatInputApi()) == null ? void 0 : _a2.FloatingUI;
}
async function vimPrompt(msg, choices, defaultChoice) {
  if (!choices) {
    choices = ["yes", "no"];
    defaultChoice = "no";
  }
  const defaultNumber = defaultChoice ? choices.indexOf(defaultChoice) : -1;
  const result = await import_coc18.workspace.nvim.call("confirm", [
    msg,
    choices.map((choice) => {
      var _a2;
      let index = [...choice].findIndex((ch) => /[A-Z]/.test(ch));
      if (index === -1) {
        index = 0;
      }
      return `${choice.slice(0, index)}&${(_a2 = choice[index]) == null ? void 0 : _a2.toUpperCase()}${choice.slice(index + 1)}`;
    }).join("\n"),
    defaultNumber + 1
  ]);
  if (result !== 0) {
    return choices[result - 1];
  }
}
async function prompt(msg, choices, defaultChoice) {
  const FloatUI = await getFloatUI();
  if (FloatUI) {
    return FloatUI.confirm({
      prompt: msg,
      values: choices,
      defaultValue: defaultChoice
    });
  } else {
    return vimPrompt(msg, choices, defaultChoice);
  }
}
async function vimInput(prompt2, defaultInput = "", completion = void 0) {
  return import_coc18.workspace.nvim.callAsync("coc#util#with_callback", [
    "input",
    [`${prompt2} `, defaultInput, completion]
  ]);
}
async function input(prompt2, defaultInput = "", completion = void 0) {
  const FloatUI = await getFloatUI();
  if (FloatUI) {
    return await FloatUI.stringInput({
      prompt: prompt2,
      defaultValue: defaultInput
      // TODO completion
    }) ?? "";
  } else {
    return vimInput(prompt2, defaultInput, completion);
  }
}
async function selectWindowsUI(config4, sourceType, {
  onSelect,
  noChoice,
  onCancel
}) {
  let filterOption = config4.get("openAction.select.filter");
  const chars = config4.get("openAction.select.chars");
  if (filterOption.sources) {
    const sourceFilterOption = filterOption.sources[sourceType];
    if (sourceFilterOption) {
      filterOption = {
        ...filterOption,
        ...sourceFilterOption
      };
    }
  }
  const winnr = await import_coc18.workspace.nvim.call("coc_explorer#select_wins#start", [
    chars,
    filterOption.buftypes ?? [],
    filterOption.filetypes ?? [],
    filterOption.floatingWindows ?? true
  ]);
  if (winnr > 0) {
    await Promise.resolve(onSelect(winnr));
  } else if (winnr === 0) {
    await Promise.resolve(noChoice == null ? void 0 : noChoice());
  } else {
    await Promise.resolve(onCancel == null ? void 0 : onCancel());
  }
}

// src/util/uri.ts
function generateUri2(path3, scheme = "file") {
  if (scheme === "file" && isWindows2 && /^[A-Za-z]:/.test(path3)) {
    path3 = `/${path3}`;
  }
  return `${scheme}://${path3}`;
}

// src/util/color.ts
var import_color_convert2 = __toESM(require_color_convert());
function createColor(red, green, blue, alpha) {
  return { red, green, blue, alpha };
}
function colorDistance(c1, c2) {
  const rmean = (c1.red + c2.red) / 2;
  const r = c1.red - c2.red;
  const g = c1.green - c2.green;
  const b = c1.blue - c2.blue;
  return Math.sqrt(
    ((512 + rmean) * r * r >> 8) + 4 * g * g + ((767 - rmean) * b * b >> 8)
  );
}
function findNearestColor(color, list, getColor = (it) => it) {
  return minBy_default(list, (it) => colorDistance(getColor(it), color));
}
function parseColor(str) {
  str = str.trim();
  if (str[0] === "#") {
    str = str.slice(1);
  }
  const m = str.match(/.{1,2}/g);
  if (!m)
    return;
  const [r = "0", g = "0", b = "0"] = m;
  const ri = parseInt(r, 16);
  if (isNaN(ri))
    return;
  const gi = parseInt(g, 16);
  if (isNaN(gi))
    return;
  const bi = parseInt(b, 16);
  if (isNaN(bi))
    return;
  return createColor(ri, gi, bi, 1);
}
function toHex(color) {
  return import_color_convert2.default.rgb.hex(color.red, color.green, color.blue);
}

// src/util/rx.ts
var import_coc19 = require("coc.nvim");

// node_modules/rxjs/dist/esm/internal/util/isFunction.js
function isFunction2(value) {
  return typeof value === "function";
}

// node_modules/rxjs/dist/esm/internal/util/createErrorClass.js
function createErrorClass(createImpl) {
  const _super = (instance) => {
    Error.call(instance);
    instance.stack = new Error().stack;
  };
  const ctorFunc = createImpl(_super);
  ctorFunc.prototype = Object.create(Error.prototype);
  ctorFunc.prototype.constructor = ctorFunc;
  return ctorFunc;
}

// node_modules/rxjs/dist/esm/internal/util/UnsubscriptionError.js
var UnsubscriptionError = createErrorClass((_super) => function UnsubscriptionErrorImpl(errors) {
  _super(this);
  this.message = errors ? `${errors.length} errors occurred during unsubscription:
${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join("\n  ")}` : "";
  this.name = "UnsubscriptionError";
  this.errors = errors;
});

// node_modules/rxjs/dist/esm/internal/util/arrRemove.js
function arrRemove(arr, item) {
  if (arr) {
    const index = arr.indexOf(item);
    0 <= index && arr.splice(index, 1);
  }
}

// node_modules/rxjs/dist/esm/internal/Subscription.js
var Subscription = class _Subscription {
  constructor(initialTeardown) {
    this.initialTeardown = initialTeardown;
    this.closed = false;
    this._parentage = null;
    this._finalizers = null;
  }
  unsubscribe() {
    let errors;
    if (!this.closed) {
      this.closed = true;
      const { _parentage } = this;
      if (_parentage) {
        this._parentage = null;
        if (Array.isArray(_parentage)) {
          for (const parent of _parentage) {
            parent.remove(this);
          }
        } else {
          _parentage.remove(this);
        }
      }
      const { initialTeardown: initialFinalizer } = this;
      if (isFunction2(initialFinalizer)) {
        try {
          initialFinalizer();
        } catch (e) {
          errors = e instanceof UnsubscriptionError ? e.errors : [e];
        }
      }
      const { _finalizers } = this;
      if (_finalizers) {
        this._finalizers = null;
        for (const finalizer of _finalizers) {
          try {
            execFinalizer(finalizer);
          } catch (err) {
            errors = errors !== null && errors !== void 0 ? errors : [];
            if (err instanceof UnsubscriptionError) {
              errors = [...errors, ...err.errors];
            } else {
              errors.push(err);
            }
          }
        }
      }
      if (errors) {
        throw new UnsubscriptionError(errors);
      }
    }
  }
  add(teardown) {
    var _a2;
    if (teardown && teardown !== this) {
      if (this.closed) {
        execFinalizer(teardown);
      } else {
        if (teardown instanceof _Subscription) {
          if (teardown.closed || teardown._hasParent(this)) {
            return;
          }
          teardown._addParent(this);
        }
        (this._finalizers = (_a2 = this._finalizers) !== null && _a2 !== void 0 ? _a2 : []).push(teardown);
      }
    }
  }
  _hasParent(parent) {
    const { _parentage } = this;
    return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
  }
  _addParent(parent) {
    const { _parentage } = this;
    this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
  }
  _removeParent(parent) {
    const { _parentage } = this;
    if (_parentage === parent) {
      this._parentage = null;
    } else if (Array.isArray(_parentage)) {
      arrRemove(_parentage, parent);
    }
  }
  remove(teardown) {
    const { _finalizers } = this;
    _finalizers && arrRemove(_finalizers, teardown);
    if (teardown instanceof _Subscription) {
      teardown._removeParent(this);
    }
  }
};
Subscription.EMPTY = (() => {
  const empty = new Subscription();
  empty.closed = true;
  return empty;
})();
var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
function isSubscription(value) {
  return value instanceof Subscription || value && "closed" in value && isFunction2(value.remove) && isFunction2(value.add) && isFunction2(value.unsubscribe);
}
function execFinalizer(finalizer) {
  if (isFunction2(finalizer)) {
    finalizer();
  } else {
    finalizer.unsubscribe();
  }
}

// node_modules/rxjs/dist/esm/internal/config.js
var config2 = {
  onUnhandledError: null,
  onStoppedNotification: null,
  Promise: void 0,
  useDeprecatedSynchronousErrorHandling: false,
  useDeprecatedNextContext: false
};

// node_modules/rxjs/dist/esm/internal/scheduler/timeoutProvider.js
var timeoutProvider = {
  setTimeout(handler, timeout, ...args) {
    const { delegate } = timeoutProvider;
    if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
      return delegate.setTimeout(handler, timeout, ...args);
    }
    return setTimeout(handler, timeout, ...args);
  },
  clearTimeout(handle) {
    const { delegate } = timeoutProvider;
    return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
  },
  delegate: void 0
};

// node_modules/rxjs/dist/esm/internal/util/reportUnhandledError.js
function reportUnhandledError(err) {
  timeoutProvider.setTimeout(() => {
    const { onUnhandledError } = config2;
    if (onUnhandledError) {
      onUnhandledError(err);
    } else {
      throw err;
    }
  });
}

// node_modules/rxjs/dist/esm/internal/util/noop.js
function noop2() {
}

// node_modules/rxjs/dist/esm/internal/NotificationFactories.js
var COMPLETE_NOTIFICATION = (() => createNotification("C", void 0, void 0))();
function errorNotification(error) {
  return createNotification("E", void 0, error);
}
function nextNotification(value) {
  return createNotification("N", value, void 0);
}
function createNotification(kind, value, error) {
  return {
    kind,
    value,
    error
  };
}

// node_modules/rxjs/dist/esm/internal/util/errorContext.js
var context = null;
function errorContext(cb) {
  if (config2.useDeprecatedSynchronousErrorHandling) {
    const isRoot = !context;
    if (isRoot) {
      context = { errorThrown: false, error: null };
    }
    cb();
    if (isRoot) {
      const { errorThrown, error } = context;
      context = null;
      if (errorThrown) {
        throw error;
      }
    }
  } else {
    cb();
  }
}
function captureError(err) {
  if (config2.useDeprecatedSynchronousErrorHandling && context) {
    context.errorThrown = true;
    context.error = err;
  }
}

// node_modules/rxjs/dist/esm/internal/Subscriber.js
var Subscriber = class extends Subscription {
  constructor(destination) {
    super();
    this.isStopped = false;
    if (destination) {
      this.destination = destination;
      if (isSubscription(destination)) {
        destination.add(this);
      }
    } else {
      this.destination = EMPTY_OBSERVER;
    }
  }
  static create(next, error, complete) {
    return new SafeSubscriber(next, error, complete);
  }
  next(value) {
    if (this.isStopped) {
      handleStoppedNotification(nextNotification(value), this);
    } else {
      this._next(value);
    }
  }
  error(err) {
    if (this.isStopped) {
      handleStoppedNotification(errorNotification(err), this);
    } else {
      this.isStopped = true;
      this._error(err);
    }
  }
  complete() {
    if (this.isStopped) {
      handleStoppedNotification(COMPLETE_NOTIFICATION, this);
    } else {
      this.isStopped = true;
      this._complete();
    }
  }
  unsubscribe() {
    if (!this.closed) {
      this.isStopped = true;
      super.unsubscribe();
      this.destination = null;
    }
  }
  _next(value) {
    this.destination.next(value);
  }
  _error(err) {
    try {
      this.destination.error(err);
    } finally {
      this.unsubscribe();
    }
  }
  _complete() {
    try {
      this.destination.complete();
    } finally {
      this.unsubscribe();
    }
  }
};
var _bind = Function.prototype.bind;
function bind(fn, thisArg) {
  return _bind.call(fn, thisArg);
}
var ConsumerObserver = class {
  constructor(partialObserver) {
    this.partialObserver = partialObserver;
  }
  next(value) {
    const { partialObserver } = this;
    if (partialObserver.next) {
      try {
        partialObserver.next(value);
      } catch (error) {
        handleUnhandledError(error);
      }
    }
  }
  error(err) {
    const { partialObserver } = this;
    if (partialObserver.error) {
      try {
        partialObserver.error(err);
      } catch (error) {
        handleUnhandledError(error);
      }
    } else {
      handleUnhandledError(err);
    }
  }
  complete() {
    const { partialObserver } = this;
    if (partialObserver.complete) {
      try {
        partialObserver.complete();
      } catch (error) {
        handleUnhandledError(error);
      }
    }
  }
};
var SafeSubscriber = class extends Subscriber {
  constructor(observerOrNext, error, complete) {
    super();
    let partialObserver;
    if (isFunction2(observerOrNext) || !observerOrNext) {
      partialObserver = {
        next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
        error: error !== null && error !== void 0 ? error : void 0,
        complete: complete !== null && complete !== void 0 ? complete : void 0
      };
    } else {
      let context2;
      if (this && config2.useDeprecatedNextContext) {
        context2 = Object.create(observerOrNext);
        context2.unsubscribe = () => this.unsubscribe();
        partialObserver = {
          next: observerOrNext.next && bind(observerOrNext.next, context2),
          error: observerOrNext.error && bind(observerOrNext.error, context2),
          complete: observerOrNext.complete && bind(observerOrNext.complete, context2)
        };
      } else {
        partialObserver = observerOrNext;
      }
    }
    this.destination = new ConsumerObserver(partialObserver);
  }
};
function handleUnhandledError(error) {
  if (config2.useDeprecatedSynchronousErrorHandling) {
    captureError(error);
  } else {
    reportUnhandledError(error);
  }
}
function defaultErrorHandler(err) {
  throw err;
}
function handleStoppedNotification(notification, subscriber) {
  const { onStoppedNotification } = config2;
  onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));
}
var EMPTY_OBSERVER = {
  closed: true,
  next: noop2,
  error: defaultErrorHandler,
  complete: noop2
};

// node_modules/rxjs/dist/esm/internal/symbol/observable.js
var observable = (() => typeof Symbol === "function" && Symbol.observable || "@@observable")();

// node_modules/rxjs/dist/esm/internal/util/identity.js
function identity2(x) {
  return x;
}

// node_modules/rxjs/dist/esm/internal/util/pipe.js
function pipeFromArray(fns) {
  if (fns.length === 0) {
    return identity2;
  }
  if (fns.length === 1) {
    return fns[0];
  }
  return function piped(input2) {
    return fns.reduce((prev, fn) => fn(prev), input2);
  };
}

// node_modules/rxjs/dist/esm/internal/Observable.js
var Observable = class _Observable {
  constructor(subscribe) {
    if (subscribe) {
      this._subscribe = subscribe;
    }
  }
  lift(operator) {
    const observable2 = new _Observable();
    observable2.source = this;
    observable2.operator = operator;
    return observable2;
  }
  subscribe(observerOrNext, error, complete) {
    const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
    errorContext(() => {
      const { operator, source } = this;
      subscriber.add(operator ? operator.call(subscriber, source) : source ? this._subscribe(subscriber) : this._trySubscribe(subscriber));
    });
    return subscriber;
  }
  _trySubscribe(sink) {
    try {
      return this._subscribe(sink);
    } catch (err) {
      sink.error(err);
    }
  }
  forEach(next, promiseCtor) {
    promiseCtor = getPromiseCtor(promiseCtor);
    return new promiseCtor((resolve6, reject) => {
      const subscriber = new SafeSubscriber({
        next: (value) => {
          try {
            next(value);
          } catch (err) {
            reject(err);
            subscriber.unsubscribe();
          }
        },
        error: reject,
        complete: resolve6
      });
      this.subscribe(subscriber);
    });
  }
  _subscribe(subscriber) {
    var _a2;
    return (_a2 = this.source) === null || _a2 === void 0 ? void 0 : _a2.subscribe(subscriber);
  }
  [observable]() {
    return this;
  }
  pipe(...operations) {
    return pipeFromArray(operations)(this);
  }
  toPromise(promiseCtor) {
    promiseCtor = getPromiseCtor(promiseCtor);
    return new promiseCtor((resolve6, reject) => {
      let value;
      this.subscribe((x) => value = x, (err) => reject(err), () => resolve6(value));
    });
  }
};
Observable.create = (subscribe) => {
  return new Observable(subscribe);
};
function getPromiseCtor(promiseCtor) {
  var _a2;
  return (_a2 = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config2.Promise) !== null && _a2 !== void 0 ? _a2 : Promise;
}
function isObserver(value) {
  return value && isFunction2(value.next) && isFunction2(value.error) && isFunction2(value.complete);
}
function isSubscriber(value) {
  return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
}

// node_modules/rxjs/dist/esm/internal/util/lift.js
function hasLift(source) {
  return isFunction2(source === null || source === void 0 ? void 0 : source.lift);
}
function operate(init) {
  return (source) => {
    if (hasLift(source)) {
      return source.lift(function(liftedSource) {
        try {
          return init(liftedSource, this);
        } catch (err) {
          this.error(err);
        }
      });
    }
    throw new TypeError("Unable to lift unknown Observable type");
  };
}

// node_modules/rxjs/dist/esm/internal/operators/OperatorSubscriber.js
function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
  return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
}
var OperatorSubscriber = class extends Subscriber {
  constructor(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
    super(destination);
    this.onFinalize = onFinalize;
    this.shouldUnsubscribe = shouldUnsubscribe;
    this._next = onNext ? function(value) {
      try {
        onNext(value);
      } catch (err) {
        destination.error(err);
      }
    } : super._next;
    this._error = onError ? function(err) {
      try {
        onError(err);
      } catch (err2) {
        destination.error(err2);
      } finally {
        this.unsubscribe();
      }
    } : super._error;
    this._complete = onComplete ? function() {
      try {
        onComplete();
      } catch (err) {
        destination.error(err);
      } finally {
        this.unsubscribe();
      }
    } : super._complete;
  }
  unsubscribe() {
    var _a2;
    if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
      const { closed } = this;
      super.unsubscribe();
      !closed && ((_a2 = this.onFinalize) === null || _a2 === void 0 ? void 0 : _a2.call(this));
    }
  }
};

// node_modules/rxjs/dist/esm/internal/util/ObjectUnsubscribedError.js
var ObjectUnsubscribedError = createErrorClass((_super) => function ObjectUnsubscribedErrorImpl() {
  _super(this);
  this.name = "ObjectUnsubscribedError";
  this.message = "object unsubscribed";
});

// node_modules/rxjs/dist/esm/internal/Subject.js
var Subject = class extends Observable {
  constructor() {
    super();
    this.closed = false;
    this.currentObservers = null;
    this.observers = [];
    this.isStopped = false;
    this.hasError = false;
    this.thrownError = null;
  }
  lift(operator) {
    const subject = new AnonymousSubject(this, this);
    subject.operator = operator;
    return subject;
  }
  _throwIfClosed() {
    if (this.closed) {
      throw new ObjectUnsubscribedError();
    }
  }
  next(value) {
    errorContext(() => {
      this._throwIfClosed();
      if (!this.isStopped) {
        if (!this.currentObservers) {
          this.currentObservers = Array.from(this.observers);
        }
        for (const observer of this.currentObservers) {
          observer.next(value);
        }
      }
    });
  }
  error(err) {
    errorContext(() => {
      this._throwIfClosed();
      if (!this.isStopped) {
        this.hasError = this.isStopped = true;
        this.thrownError = err;
        const { observers } = this;
        while (observers.length) {
          observers.shift().error(err);
        }
      }
    });
  }
  complete() {
    errorContext(() => {
      this._throwIfClosed();
      if (!this.isStopped) {
        this.isStopped = true;
        const { observers } = this;
        while (observers.length) {
          observers.shift().complete();
        }
      }
    });
  }
  unsubscribe() {
    this.isStopped = this.closed = true;
    this.observers = this.currentObservers = null;
  }
  get observed() {
    var _a2;
    return ((_a2 = this.observers) === null || _a2 === void 0 ? void 0 : _a2.length) > 0;
  }
  _trySubscribe(subscriber) {
    this._throwIfClosed();
    return super._trySubscribe(subscriber);
  }
  _subscribe(subscriber) {
    this._throwIfClosed();
    this._checkFinalizedStatuses(subscriber);
    return this._innerSubscribe(subscriber);
  }
  _innerSubscribe(subscriber) {
    const { hasError, isStopped, observers } = this;
    if (hasError || isStopped) {
      return EMPTY_SUBSCRIPTION;
    }
    this.currentObservers = null;
    observers.push(subscriber);
    return new Subscription(() => {
      this.currentObservers = null;
      arrRemove(observers, subscriber);
    });
  }
  _checkFinalizedStatuses(subscriber) {
    const { hasError, thrownError, isStopped } = this;
    if (hasError) {
      subscriber.error(thrownError);
    } else if (isStopped) {
      subscriber.complete();
    }
  }
  asObservable() {
    const observable2 = new Observable();
    observable2.source = this;
    return observable2;
  }
};
Subject.create = (destination, source) => {
  return new AnonymousSubject(destination, source);
};
var AnonymousSubject = class extends Subject {
  constructor(destination, source) {
    super();
    this.destination = destination;
    this.source = source;
  }
  next(value) {
    var _a2, _b;
    (_b = (_a2 = this.destination) === null || _a2 === void 0 ? void 0 : _a2.next) === null || _b === void 0 ? void 0 : _b.call(_a2, value);
  }
  error(err) {
    var _a2, _b;
    (_b = (_a2 = this.destination) === null || _a2 === void 0 ? void 0 : _a2.error) === null || _b === void 0 ? void 0 : _b.call(_a2, err);
  }
  complete() {
    var _a2, _b;
    (_b = (_a2 = this.destination) === null || _a2 === void 0 ? void 0 : _a2.complete) === null || _b === void 0 ? void 0 : _b.call(_a2);
  }
  _subscribe(subscriber) {
    var _a2, _b;
    return (_b = (_a2 = this.source) === null || _a2 === void 0 ? void 0 : _a2.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
  }
};

// node_modules/rxjs/dist/esm/internal/scheduler/dateTimestampProvider.js
var dateTimestampProvider = {
  now() {
    return (dateTimestampProvider.delegate || Date).now();
  },
  delegate: void 0
};

// node_modules/rxjs/dist/esm/internal/scheduler/Action.js
var Action = class extends Subscription {
  constructor(scheduler, work) {
    super();
  }
  schedule(state, delay = 0) {
    return this;
  }
};

// node_modules/rxjs/dist/esm/internal/scheduler/intervalProvider.js
var intervalProvider = {
  setInterval(handler, timeout, ...args) {
    const { delegate } = intervalProvider;
    if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
      return delegate.setInterval(handler, timeout, ...args);
    }
    return setInterval(handler, timeout, ...args);
  },
  clearInterval(handle) {
    const { delegate } = intervalProvider;
    return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
  },
  delegate: void 0
};

// node_modules/rxjs/dist/esm/internal/scheduler/AsyncAction.js
var AsyncAction = class extends Action {
  constructor(scheduler, work) {
    super(scheduler, work);
    this.scheduler = scheduler;
    this.work = work;
    this.pending = false;
  }
  schedule(state, delay = 0) {
    var _a2;
    if (this.closed) {
      return this;
    }
    this.state = state;
    const id = this.id;
    const scheduler = this.scheduler;
    if (id != null) {
      this.id = this.recycleAsyncId(scheduler, id, delay);
    }
    this.pending = true;
    this.delay = delay;
    this.id = (_a2 = this.id) !== null && _a2 !== void 0 ? _a2 : this.requestAsyncId(scheduler, this.id, delay);
    return this;
  }
  requestAsyncId(scheduler, _id, delay = 0) {
    return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
  }
  recycleAsyncId(_scheduler, id, delay = 0) {
    if (delay != null && this.delay === delay && this.pending === false) {
      return id;
    }
    if (id != null) {
      intervalProvider.clearInterval(id);
    }
    return void 0;
  }
  execute(state, delay) {
    if (this.closed) {
      return new Error("executing a cancelled action");
    }
    this.pending = false;
    const error = this._execute(state, delay);
    if (error) {
      return error;
    } else if (this.pending === false && this.id != null) {
      this.id = this.recycleAsyncId(this.scheduler, this.id, null);
    }
  }
  _execute(state, _delay) {
    let errored = false;
    let errorValue;
    try {
      this.work(state);
    } catch (e) {
      errored = true;
      errorValue = e ? e : new Error("Scheduled action threw falsy error");
    }
    if (errored) {
      this.unsubscribe();
      return errorValue;
    }
  }
  unsubscribe() {
    if (!this.closed) {
      const { id, scheduler } = this;
      const { actions } = scheduler;
      this.work = this.state = this.scheduler = null;
      this.pending = false;
      arrRemove(actions, this);
      if (id != null) {
        this.id = this.recycleAsyncId(scheduler, id, null);
      }
      this.delay = null;
      super.unsubscribe();
    }
  }
};

// node_modules/rxjs/dist/esm/internal/Scheduler.js
var Scheduler = class _Scheduler {
  constructor(schedulerActionCtor, now = _Scheduler.now) {
    this.schedulerActionCtor = schedulerActionCtor;
    this.now = now;
  }
  schedule(work, delay = 0, state) {
    return new this.schedulerActionCtor(this, work).schedule(state, delay);
  }
};
Scheduler.now = dateTimestampProvider.now;

// node_modules/rxjs/dist/esm/internal/scheduler/AsyncScheduler.js
var AsyncScheduler = class extends Scheduler {
  constructor(SchedulerAction, now = Scheduler.now) {
    super(SchedulerAction, now);
    this.actions = [];
    this._active = false;
  }
  flush(action) {
    const { actions } = this;
    if (this._active) {
      actions.push(action);
      return;
    }
    let error;
    this._active = true;
    do {
      if (error = action.execute(action.state, action.delay)) {
        break;
      }
    } while (action = actions.shift());
    this._active = false;
    if (error) {
      while (action = actions.shift()) {
        action.unsubscribe();
      }
      throw error;
    }
  }
};

// node_modules/rxjs/dist/esm/internal/scheduler/async.js
var asyncScheduler = new AsyncScheduler(AsyncAction);
var async = asyncScheduler;

// node_modules/rxjs/dist/esm/internal/util/isScheduler.js
function isScheduler(value) {
  return value && isFunction2(value.schedule);
}

// node_modules/tslib/tslib.es6.mjs
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve6) {
      resolve6(value);
    });
  }
  return new (P || (P = Promise))(function(resolve6, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m)
    return m.call(o);
  if (o && typeof o.length === "number")
    return {
      next: function() {
        if (o && i >= o.length)
          o = void 0;
        return { value: o && o[i++], done: !o };
      }
    };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i;
  function verb(n) {
    if (g[n])
      i[n] = function(v) {
        return new Promise(function(a, b) {
          q.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e) {
      settle(q[0][3], e);
    }
  }
  function step(r) {
    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f, v) {
    if (f(v), q.shift(), q.length)
      resume(q[0][0], q[0][1]);
  }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n) {
    i[n] = o[n] && function(v) {
      return new Promise(function(resolve6, reject) {
        v = o[n](v), settle(resolve6, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve6, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve6({ value: v2, done: d });
    }, reject);
  }
}

// node_modules/rxjs/dist/esm/internal/util/isArrayLike.js
var isArrayLike2 = (x) => x && typeof x.length === "number" && typeof x !== "function";

// node_modules/rxjs/dist/esm/internal/util/isPromise.js
function isPromise(value) {
  return isFunction2(value === null || value === void 0 ? void 0 : value.then);
}

// node_modules/rxjs/dist/esm/internal/util/isInteropObservable.js
function isInteropObservable(input2) {
  return isFunction2(input2[observable]);
}

// node_modules/rxjs/dist/esm/internal/util/isAsyncIterable.js
function isAsyncIterable(obj) {
  return Symbol.asyncIterator && isFunction2(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
}

// node_modules/rxjs/dist/esm/internal/util/throwUnobservableError.js
function createInvalidObservableTypeError(input2) {
  return new TypeError(`You provided ${input2 !== null && typeof input2 === "object" ? "an invalid object" : `'${input2}'`} where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`);
}

// node_modules/rxjs/dist/esm/internal/symbol/iterator.js
function getSymbolIterator() {
  if (typeof Symbol !== "function" || !Symbol.iterator) {
    return "@@iterator";
  }
  return Symbol.iterator;
}
var iterator = getSymbolIterator();

// node_modules/rxjs/dist/esm/internal/util/isIterable.js
function isIterable(input2) {
  return isFunction2(input2 === null || input2 === void 0 ? void 0 : input2[iterator]);
}

// node_modules/rxjs/dist/esm/internal/util/isReadableStreamLike.js
function readableStreamLikeToAsyncGenerator(readableStream) {
  return __asyncGenerator(this, arguments, function* readableStreamLikeToAsyncGenerator_1() {
    const reader = readableStream.getReader();
    try {
      while (true) {
        const { value, done } = yield __await(reader.read());
        if (done) {
          return yield __await(void 0);
        }
        yield yield __await(value);
      }
    } finally {
      reader.releaseLock();
    }
  });
}
function isReadableStreamLike(obj) {
  return isFunction2(obj === null || obj === void 0 ? void 0 : obj.getReader);
}

// node_modules/rxjs/dist/esm/internal/observable/innerFrom.js
function innerFrom(input2) {
  if (input2 instanceof Observable) {
    return input2;
  }
  if (input2 != null) {
    if (isInteropObservable(input2)) {
      return fromInteropObservable(input2);
    }
    if (isArrayLike2(input2)) {
      return fromArrayLike(input2);
    }
    if (isPromise(input2)) {
      return fromPromise(input2);
    }
    if (isAsyncIterable(input2)) {
      return fromAsyncIterable(input2);
    }
    if (isIterable(input2)) {
      return fromIterable(input2);
    }
    if (isReadableStreamLike(input2)) {
      return fromReadableStreamLike(input2);
    }
  }
  throw createInvalidObservableTypeError(input2);
}
function fromInteropObservable(obj) {
  return new Observable((subscriber) => {
    const obs = obj[observable]();
    if (isFunction2(obs.subscribe)) {
      return obs.subscribe(subscriber);
    }
    throw new TypeError("Provided object does not correctly implement Symbol.observable");
  });
}
function fromArrayLike(array) {
  return new Observable((subscriber) => {
    for (let i = 0; i < array.length && !subscriber.closed; i++) {
      subscriber.next(array[i]);
    }
    subscriber.complete();
  });
}
function fromPromise(promise) {
  return new Observable((subscriber) => {
    promise.then((value) => {
      if (!subscriber.closed) {
        subscriber.next(value);
        subscriber.complete();
      }
    }, (err) => subscriber.error(err)).then(null, reportUnhandledError);
  });
}
function fromIterable(iterable) {
  return new Observable((subscriber) => {
    for (const value of iterable) {
      subscriber.next(value);
      if (subscriber.closed) {
        return;
      }
    }
    subscriber.complete();
  });
}
function fromAsyncIterable(asyncIterable) {
  return new Observable((subscriber) => {
    process2(asyncIterable, subscriber).catch((err) => subscriber.error(err));
  });
}
function fromReadableStreamLike(readableStream) {
  return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
}
function process2(asyncIterable, subscriber) {
  var asyncIterable_1, asyncIterable_1_1;
  var e_1, _a2;
  return __awaiter(this, void 0, void 0, function* () {
    try {
      for (asyncIterable_1 = __asyncValues(asyncIterable); asyncIterable_1_1 = yield asyncIterable_1.next(), !asyncIterable_1_1.done; ) {
        const value = asyncIterable_1_1.value;
        subscriber.next(value);
        if (subscriber.closed) {
          return;
        }
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (asyncIterable_1_1 && !asyncIterable_1_1.done && (_a2 = asyncIterable_1.return))
          yield _a2.call(asyncIterable_1);
      } finally {
        if (e_1)
          throw e_1.error;
      }
    }
    subscriber.complete();
  });
}

// node_modules/rxjs/dist/esm/internal/util/EmptyError.js
var EmptyError = createErrorClass((_super) => function EmptyErrorImpl() {
  _super(this);
  this.name = "EmptyError";
  this.message = "no elements in sequence";
});

// node_modules/rxjs/dist/esm/internal/firstValueFrom.js
function firstValueFrom(source, config4) {
  const hasConfig = typeof config4 === "object";
  return new Promise((resolve6, reject) => {
    const subscriber = new SafeSubscriber({
      next: (value) => {
        resolve6(value);
        subscriber.unsubscribe();
      },
      error: reject,
      complete: () => {
        if (hasConfig) {
          resolve6(config4.defaultValue);
        } else {
          reject(new EmptyError());
        }
      }
    });
    source.subscribe(subscriber);
  });
}

// node_modules/rxjs/dist/esm/internal/util/isDate.js
function isValidDate(value) {
  return value instanceof Date && !isNaN(value);
}

// node_modules/rxjs/dist/esm/internal/observable/timer.js
function timer(dueTime = 0, intervalOrScheduler, scheduler = async) {
  let intervalDuration = -1;
  if (intervalOrScheduler != null) {
    if (isScheduler(intervalOrScheduler)) {
      scheduler = intervalOrScheduler;
    } else {
      intervalDuration = intervalOrScheduler;
    }
  }
  return new Observable((subscriber) => {
    let due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
    if (due < 0) {
      due = 0;
    }
    let n = 0;
    return scheduler.schedule(function() {
      if (!subscriber.closed) {
        subscriber.next(n++);
        if (0 <= intervalDuration) {
          this.schedule(void 0, intervalDuration);
        } else {
          subscriber.complete();
        }
      }
    }, due);
  });
}

// node_modules/rxjs/dist/esm/internal/operators/buffer.js
function buffer(closingNotifier) {
  return operate((source, subscriber) => {
    let currentBuffer = [];
    source.subscribe(createOperatorSubscriber(subscriber, (value) => currentBuffer.push(value), () => {
      subscriber.next(currentBuffer);
      subscriber.complete();
    }));
    innerFrom(closingNotifier).subscribe(createOperatorSubscriber(subscriber, () => {
      const b = currentBuffer;
      currentBuffer = [];
      subscriber.next(b);
    }, noop2));
    return () => {
      currentBuffer = null;
    };
  });
}

// node_modules/rxjs/dist/esm/internal/operators/debounceTime.js
function debounceTime(dueTime, scheduler = asyncScheduler) {
  return operate((source, subscriber) => {
    let activeTask = null;
    let lastValue = null;
    let lastTime = null;
    const emit = () => {
      if (activeTask) {
        activeTask.unsubscribe();
        activeTask = null;
        const value = lastValue;
        lastValue = null;
        subscriber.next(value);
      }
    };
    function emitWhenIdle() {
      const targetTime = lastTime + dueTime;
      const now = scheduler.now();
      if (now < targetTime) {
        activeTask = this.schedule(void 0, targetTime - now);
        subscriber.add(activeTask);
        return;
      }
      emit();
    }
    source.subscribe(createOperatorSubscriber(subscriber, (value) => {
      lastValue = value;
      lastTime = scheduler.now();
      if (!activeTask) {
        activeTask = scheduler.schedule(emitWhenIdle, dueTime);
        subscriber.add(activeTask);
      }
    }, () => {
      emit();
      subscriber.complete();
    }, void 0, () => {
      lastValue = activeTask = null;
    }));
  });
}

// node_modules/rxjs/dist/esm/internal/operators/switchMap.js
function switchMap(project, resultSelector) {
  return operate((source, subscriber) => {
    let innerSubscriber = null;
    let index = 0;
    let isComplete = false;
    const checkComplete = () => isComplete && !innerSubscriber && subscriber.complete();
    source.subscribe(createOperatorSubscriber(subscriber, (value) => {
      innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
      let innerIndex = 0;
      const outerIndex = index++;
      innerFrom(project(value, outerIndex)).subscribe(innerSubscriber = createOperatorSubscriber(subscriber, (innerValue) => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue), () => {
        innerSubscriber = null;
        checkComplete();
      }));
    }, () => {
      isComplete = true;
      checkComplete();
    }));
  });
}

// node_modules/rxjs/dist/esm/internal/operators/throttle.js
function throttle(durationSelector, config4) {
  return operate((source, subscriber) => {
    const { leading = true, trailing = false } = config4 !== null && config4 !== void 0 ? config4 : {};
    let hasValue = false;
    let sendValue = null;
    let throttled = null;
    let isComplete = false;
    const endThrottling = () => {
      throttled === null || throttled === void 0 ? void 0 : throttled.unsubscribe();
      throttled = null;
      if (trailing) {
        send();
        isComplete && subscriber.complete();
      }
    };
    const cleanupThrottling = () => {
      throttled = null;
      isComplete && subscriber.complete();
    };
    const startThrottle = (value) => throttled = innerFrom(durationSelector(value)).subscribe(createOperatorSubscriber(subscriber, endThrottling, cleanupThrottling));
    const send = () => {
      if (hasValue) {
        hasValue = false;
        const value = sendValue;
        sendValue = null;
        subscriber.next(value);
        !isComplete && startThrottle(value);
      }
    };
    source.subscribe(createOperatorSubscriber(subscriber, (value) => {
      hasValue = true;
      sendValue = value;
      !(throttled && !throttled.closed) && (leading ? send() : startThrottle(value));
    }, () => {
      isComplete = true;
      !(trailing && hasValue && throttled && !throttled.closed) && subscriber.complete();
    }));
  });
}

// node_modules/rxjs/dist/esm/internal/operators/throttleTime.js
function throttleTime(duration, scheduler = asyncScheduler, config4) {
  const duration$ = timer(duration, scheduler);
  return throttle(() => duration$, config4);
}

// src/util/rx.ts
function subjectToHook(observable2) {
  return (fn) => {
    const sub = observable2.subscribe(logger.asyncCatch(fn));
    return import_coc19.Disposable.create(() => sub.unsubscribe());
  };
}
function createSubject(builder) {
  const sub = new Subject();
  const obs = builder(sub);
  obs.subscribe({
    error: logger.error
  });
  return sub;
}
function fromHelperEvent(events6, key) {
  const sub = new Subject();
  events6.once(key, (v) => {
    sub.next(v);
  });
  return sub.asObservable();
}
function fromEmitter(emitter) {
  const sub = new Subject();
  emitter.event((value) => {
    sub.next(value);
  });
  return sub.asObservable();
}
function debounceFn(dueTime, fn) {
  const sub = new Subject();
  sub.pipe(
    debounceTime(dueTime),
    switchMap(async (args) => fn(...args))
  ).subscribe({ error: logger.error });
  const wrappedFn = (...args) => sub.next(args);
  wrappedFn.dispose = () => sub.unsubscribe();
  return wrappedFn;
}
function throttleFn(dueTime, fn, config4) {
  const sub = new Subject();
  sub.pipe(
    throttleTime(dueTime, void 0, config4),
    switchMap(async (args) => fn(...args))
  ).subscribe({
    error: logger.error
  });
  const wrappedFn = (...args) => sub.next(args);
  wrappedFn.dispose = () => sub.unsubscribe();
  return wrappedFn;
}

// src/util/object.ts
function hasOwnProperty11(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}

// src/util/index.ts
var logger = new HelperLogger("explorer");

// src/lists/runner.ts
var import_coc20 = require("coc.nvim");
var argSym = Symbol("arg");
var ProxyList = class extends import_coc20.BasicList {
  #loadItems;
  constructor(init) {
    super(import_coc20.workspace.nvim);
    this.name = init.name;
    this.#loadItems = (context2, token) => init.loadItems(this[argSym], context2, token);
    if (init.doHighlight) {
      this.doHighlight = init.doHighlight;
    }
    if (init.defaultAction) {
      this.defaultAction = init.defaultAction;
    }
    const initContext = {
      addAction: (name, fn, options) => this.addAction(
        name,
        (item, context2) => fn({
          arg: this[argSym],
          item,
          context: context2
        }),
        options
      ),
      addLocationActions: () => this.addLocationActions(),
      convertLocation: (location) => this.convertLocation(location)
    };
    init.init.call(initContext, initContext);
  }
  loadItems(context2, token) {
    return this.#loadItems(context2, token);
  }
};
argSym;
function registerList(init) {
  return new ProxyList(init);
}
async function startCocList(explorer, list, arg, listArgs = []) {
  list[argSym] = arg;
  const config4 = explorer.config;
  const nvim = explorer.nvim;
  const bufManager = explorer.explorerManager.bufManager;
  const floatingHideOnCocList = config4.get(
    "floating.hideOnCocList",
    true
  );
  let isExplorerShown = true;
  if (explorer.isFloating && floatingHideOnCocList) {
    await explorer.hide();
    isExplorerShown = false;
  }
  const shownExplorerEmitter = new import_coc20.Emitter();
  const listDisposable = import_coc20.listManager.registerList(list);
  await nvim.command(`CocList ${listArgs.join(" ")} ${list.name}`);
  listDisposable.dispose();
  return {
    async waitExplorerShow() {
      await bufManager.waitReload();
      const eventDisposable = import_coc20.events.on("BufEnter", async () => {
        const buf = bufManager.getBufferNode(`list:///${list.name}`);
        if (buf && await winnrByBufnr(buf.bufnr)) {
          return;
        }
        eventDisposable.dispose();
        if (explorer.isFloating && !isExplorerShown) {
          await sleep2(200);
          await explorer.show();
          shownExplorerEmitter.fire();
        }
      });
      if (isExplorerShown) {
        return;
      }
      return new Promise((resolve6) => {
        shownExplorerEmitter.event(() => {
          isExplorerShown = true;
          resolve6(void 0);
        });
      });
    }
  };
}

// src/lists/actions.ts
function score(list, key) {
  const idx = list.indexOf(key);
  return idx === -1 ? -1 : list.length - idx;
}
var actionListMru = import_coc21.workspace.createMru("explorer-actions");
var explorerActionList = registerList({
  name: "explorerActionList",
  defaultAction: "do",
  async loadItems(actions) {
    const mruList = await actionListMru.load();
    const items = actions.map((actionData) => ({
      label: `${actionData.name} [${actionData.key || ""}] ${actionData.description}`,
      data: {
        ...actionData,
        score: score(mruList, actionData.name)
      }
    }));
    items.sort((a, b) => b.data.score - a.data.score);
    return items;
  },
  doHighlight() {
    const { nvim } = import_coc21.workspace;
    nvim.pauseNotification();
    nvim.command(
      "syntax match CocExplorerActionName /\\v^[a-zA-Z0-9:|<>]+/",
      true
    );
    nvim.command("syntax match CocExplorerActionKey /\\v\\[.*\\]/", true);
    nvim.command(
      "syntax match CocExplorerActionDescription /\\v\\] \\zs.*/",
      true
    );
    nvim.command("highlight default link CocExplorerActionName PreProc", true);
    nvim.command(
      "highlight default link CocExplorerActionKey Identifier",
      true
    );
    nvim.command(
      "highlight default link CocExplorerActionDescription Comment",
      true
    );
    nvim.resumeNotification().catch(logger.error);
  },
  init() {
    this.addAction("do", ({ item }) => {
      logger.asyncCatch(async () => {
        const data = item.data;
        await data.callback();
        await actionListMru.add(data.name);
      })();
    });
  }
});

// src/mappings/index.ts
var import_coc22 = require("coc.nvim");

// src/actions/special.ts
var conditionActionRules = {
  "expandable?": {
    filter: (_s, n) => n.expandable,
    getHelpDescription: () => "expandable?"
  },
  "expanded?": {
    filter: (s, n) => s.view.isExpanded(n),
    getHelpDescription: () => "expanded?"
  },
  "type?": {
    filter: (_s, n, args) => n.type === args[0],
    getHelpDescription: (args) => `type is ${args[0]}`
  }
};
var waitAction = {
  name: "wait",
  helpDescription: "<wait>"
};
var noopAction = {
  name: "noop",
  helpDescription: "<noop>"
};

// src/mappings/index.ts
function parseOriginalAction(originalAction) {
  if (typeof originalAction !== "string") {
    return originalAction;
  }
  const [name = "", ...args] = originalAction.split(/:/);
  return {
    name,
    args
  };
}
function toOriginalAction(action) {
  const { name, args } = action;
  return [name, ...args].join(":");
}
function parseMappingKey(key) {
  return key.includes("<dot>") ? key.replace(/<dot>/g, ".") : key;
}
function parseOriginalActionExp(originalActionExp) {
  if (Array.isArray(originalActionExp)) {
    return originalActionExp.map(parseOriginalActionExp);
  } else {
    return parseOriginalAction(originalActionExp);
  }
}
function parseOriginalMappings(originalMappings) {
  const mappings2 = {};
  for (const [key, originalActionExp] of Object.entries(originalMappings)) {
    if (originalActionExp)
      mappings2[parseMappingKey(key)] = parseOriginalActionExp(originalActionExp);
  }
  return mappings2;
}
function mixAndParseMappings(defaultMappings, userMappings) {
  const mappings2 = parseOriginalMappings(defaultMappings);
  for (const [key, originalActionExp] of Object.entries(userMappings)) {
    if (originalActionExp === false) {
      delete mappings2[key];
      continue;
    }
    mappings2[parseMappingKey(key)] = parseOriginalActionExp(originalActionExp);
  }
  return mappings2;
}
function getSingleAction(actionExp) {
  if (!Array.isArray(actionExp)) {
    return actionExp;
  } else {
    const actions = actionExp.map((action) => getSingleAction(action)).filter(
      (action) => action && !(action.name in conditionActionRules) && action.name !== waitAction.name && action.name !== noopAction.name
    );
    return actions[0];
  }
}
var KeyMapping = class {
  constructor() {
    this.mode = config.get("keyMappingMode", "default");
    this.mouseMappings = {
      none: {},
      singleclick: {
        "<LeftRelease>": [
          "expandable?",
          ["expanded?", "collapse", "expand"],
          "open"
        ]
      },
      doubleclick: {
        "<2-LeftMouse>": [
          "expandable?",
          ["expanded?", "collapse", "expand"],
          "open"
        ]
      }
    }[config.get("mouseMode")];
    this.configByModes = {
      none: {
        global: {},
        vmap: {},
        sources: {}
      },
      default: {
        global: {
          "*": "toggleSelection",
          "<tab>": "actionMenu",
          h: ["wait", "collapse"],
          l: ["wait", "expandable?", "expand", "open"],
          J: ["wait", "toggleSelection", "normal:j"],
          K: ["wait", "toggleSelection", "normal:k"],
          gl: ["wait", "expand:recursive"],
          gh: ["wait", "collapse:recursive"],
          ...this.mouseMappings,
          o: ["wait", "expanded?", "collapse", "expand"],
          "<cr>": ["wait", "expandable?", "cd", "open"],
          e: "open",
          s: "open:split",
          E: "open:vsplit",
          t: "open:tab",
          "<bs>": ["wait", "gotoParent"],
          gs: ["wait", "reveal:select"],
          il: "preview:labeling",
          ic: "preview:content",
          Il: "previewOnHover:toggle:labeling",
          Ic: "previewOnHover:toggle:content",
          II: "previewOnHover:disable",
          yp: "copyFilepath",
          yn: "copyFilename",
          yy: "copyFile",
          yt: "copyFile:toggle",
          ya: "copyFile:append",
          "y<space>": "clearCopyOrCut",
          dd: "cutFile",
          dt: "cutFile:toggle",
          da: "cutFile:append",
          "d<space>": "clearCopyOrCut",
          p: ["pasteFile", "clearCopyOrCut"],
          P: "pasteFile",
          df: "delete",
          dF: "deleteForever",
          a: "addFile",
          A: "addDirectory",
          r: "rename",
          zh: "toggleHidden",
          "g<dot>": "toggleHidden",
          R: "refresh",
          "?": "help",
          q: "quit",
          "<esc>": "esc",
          X: "systemExecute",
          gd: "listDrive",
          f: "search",
          F: "search:recursive",
          gf: "gotoSource:file",
          gb: "gotoSource:buffer",
          "[[": ["wait", "sourcePrev"],
          "]]": ["wait", "sourceNext"],
          "[i": ["wait", "indentPrev"],
          "]i": ["wait", "indentNext"],
          "[m": ["wait", "markPrev:modified"],
          "]m": ["wait", "markNext:modified"],
          "[d": ["wait", "markPrev:diagnosticError:diagnosticWarning"],
          "]d": ["wait", "markNext:diagnosticError:diagnosticWarning"],
          "[D": ["wait", "markPrev:diagnosticError"],
          "]D": ["wait", "markNext:diagnosticError"],
          "[c": ["wait", "markPrev:gitUnstaged:gitStaged"],
          "]c": ["wait", "markNext:gitUnstaged:gitStaged"],
          "[C": ["wait", "markPrev:gitUnstaged"],
          "]C": ["wait", "markNext:gitUnstaged"],
          "<<": "gitStage",
          ">>": "gitUnstage"
        },
        vmap: {
          il: "textobj:line:i",
          al: "textobj:line:a",
          ii: "textobj:indent:i",
          ai: "textobj:indent:a"
        },
        sources: {}
      }
    };
  }
  get config() {
    return this.configByModes[this.mode];
  }
  globalMappings() {
    if (!this.globalMappings_) {
      this.globalMappings_ = mixAndParseMappings(this.config.global, {
        ...config.get("keyMappings.global", {})
      });
    }
    return this.globalMappings_;
  }
  vmapMappings() {
    if (!this.vmapMappings_) {
      this.vmapMappings_ = mixAndParseMappings(this.config.vmap, {
        ...config.get("keyMappings.vmap", {})
      });
    }
    return this.vmapMappings_;
  }
  allSourceMappings() {
    if (!this.allSourceMappings_) {
      const defaultSources = this.config.sources ?? {};
      const userSources = config.get(
        "keyMappings.sources",
        {}
      );
      this.allSourceMappings_ = /* @__PURE__ */ new Map();
      for (const [type, sourceMappings] of Object.entries(defaultSources)) {
        this.allSourceMappings_.set(type, {
          ...parseOriginalMappings(sourceMappings)
        });
      }
      for (const [type, sourceMappings] of Object.entries(userSources)) {
        const mappings2 = this.allSourceMappings_.get(type);
        if (mappings2) {
          this.allSourceMappings_.set(
            type,
            mixAndParseMappings(mappings2, sourceMappings)
          );
        } else {
          this.allSourceMappings_.set(
            type,
            mixAndParseMappings({}, sourceMappings)
          );
        }
      }
    }
    return this.allSourceMappings_;
  }
  sourceMappings(sourceType) {
    return this.allSourceMappings().get(sourceType);
  }
  async filterEscForVim(keys2) {
    if (import_coc22.workspace.isVim && !await import_coc22.workspace.nvim.call("has", ["gui_running"])) {
      keys2.delete("<esc>");
    }
  }
  async getCommonKeys() {
    const keys2 = /* @__PURE__ */ new Set();
    for (const key of Object.keys(this.globalMappings())) {
      keys2.add(key);
    }
    for (const sourceMappings of this.allSourceMappings().values()) {
      for (const key of Object.keys(sourceMappings)) {
        keys2.add(key);
      }
    }
    await this.filterEscForVim(keys2);
    return keys2;
  }
  async getVisualKeys() {
    const keys2 = /* @__PURE__ */ new Set();
    for (const key of Object.keys(this.vmapMappings())) {
      keys2.add(key);
    }
    return keys2;
  }
  getActionExp(sourceType, key, mode) {
    const vmapMappings = this.vmapMappings();
    const globalMappings = this.globalMappings();
    const sourceMappings = this.sourceMappings(sourceType);
    if (mode === "v") {
      return vmapMappings[key] ?? (sourceMappings == null ? void 0 : sourceMappings[key]) ?? globalMappings[key];
    }
    return (sourceMappings == null ? void 0 : sourceMappings[key]) ?? globalMappings[key];
  }
  async getMappings(sourceType) {
    const globalMappings = this.globalMappings();
    const vmapMappings = this.vmapMappings();
    const sourceMappings = this.sourceMappings(sourceType);
    const mappings2 = { ...globalMappings, ...sourceMappings };
    if (import_coc22.workspace.isVim && !await import_coc22.workspace.nvim.call("has", ["gui_running"])) {
      delete mappings2["<esc>"];
    }
    return {
      nmap: mappings2,
      vmap: vmapMappings
    };
  }
  async getReversedMappings(sourceType) {
    const mappings2 = await this.getMappings(sourceType);
    const reverseMappings = /* @__PURE__ */ new Map();
    Object.entries(mappings2.nmap).forEach(([key, actionExp]) => {
      const action = getSingleAction(actionExp);
      if (!action)
        return;
      const orgAction = toOriginalAction(action);
      let mapping = reverseMappings.get(orgAction);
      mapping ?? (mapping = {});
      mapping.nmap = key;
      reverseMappings.set(orgAction, mapping);
    });
    Object.entries(mappings2.vmap).forEach(([key, actionExp]) => {
      const action = getSingleAction(actionExp);
      if (!action)
        return;
      const orgAction = toOriginalAction(action);
      let mapping = reverseMappings.get(orgAction);
      mapping ?? (mapping = {});
      mapping.vmap = key;
      reverseMappings.set(orgAction, mapping);
    });
    return reverseMappings;
  }
};
var keyMapping = new KeyMapping();

// src/actions/menu.ts
var ActionMenu;
((ActionMenu2) => {
  function getNormalizeMenus(menus) {
    return Object.entries(menus).map(([key, value]) => {
      const actionArgs = async () => {
        return key.split(/:/);
      };
      return typeof value === "string" ? {
        description: value,
        args: key,
        actionArgs
      } : Object.assign(
        {
          args: key,
          actionArgs
        },
        value
      );
    });
  }
  ActionMenu2.getNormalizeMenus = getNormalizeMenus;
})(ActionMenu || (ActionMenu = {}));

// src/actions/codeActionProider.ts
function score2(list, key) {
  const idx = list.indexOf(key);
  return idx === -1 ? -1 : list.length - idx;
}
var ActionMenuCodeActionProvider = class {
  constructor(explorerManager) {
    this.explorerManager = explorerManager;
  }
  async provideCodeActions(_document, _range, _context, _token) {
    const explorer = await this.explorerManager.currentExplorer();
    if (!explorer) {
      return [];
    }
    const source = await explorer.view.currentSource();
    if (!source) {
      return [];
    }
    const reverseMappings = await keyMapping.getReversedMappings(
      source.sourceType
    );
    const actions = source.action.registeredActions();
    const mruList = await actionListMru.load();
    return [...actions.entries()].filter(([actionName]) => actionName !== "actionMenu").sort(([aName], [bName]) => aName.localeCompare(bName)).sort(([aName], [bName]) => aName.localeCompare(bName)).map(([actionName, { options }]) => {
      const keys2 = reverseMappings.get(actionName);
      const key = keys2 ? keys2.vmap ?? keys2.nmap : "";
      const list = [
        {
          title: `${actionName} [${key}]`,
          name: actionName,
          command: "explorer.doCodeAction",
          arguments: [actionName, actionName, async () => []],
          score: score2(mruList, actionName)
        }
      ];
      if (options.menus) {
        list.push(
          ...ActionMenu.getNormalizeMenus(options.menus).map((menu) => {
            const fullActionName = `${actionName}:${menu.args}`;
            const keys3 = reverseMappings.get(fullActionName);
            const key2 = keys3 ? keys3.vmap ?? keys3.nmap : "";
            return {
              title: `${fullActionName} [${key2}]`,
              name: fullActionName,
              command: "explorer.doCodeAction",
              arguments: [
                fullActionName,
                actionName,
                () => menu.actionArgs()
              ],
              score: score2(mruList, fullActionName)
            };
          })
        );
      }
      return list;
    }).flat().sort((a, b) => b.score - a.score);
  }
};

// src/bufManager.ts
var import_coc25 = require("coc.nvim");
var import_path9 = __toESM(require("path"));

// src/container.ts
var import_coc23 = require("coc.nvim");
var TabContainer = class {
  constructor() {
    this.bufnrs = /* @__PURE__ */ new Set();
  }
  getExplorer(position) {
    return this[position.name];
  }
  setExplorer(position, explorer) {
    this[position.name] = explorer;
  }
  all() {
    const explorers = [];
    if (this.left) {
      explorers.push(this.left);
    }
    if (this.right) {
      explorers.push(this.right);
    }
    if (this.tab) {
      explorers.push(this.tab);
    }
    if (this.floating) {
      explorers.push(this.floating);
    }
    return explorers;
  }
};
var TabContainerManager = class {
  constructor() {
    this.initedEmitter = new import_coc23.Emitter();
    this.tabContainerMap = /* @__PURE__ */ new Map();
    this.waitInited = firstValueFrom(fromEmitter(this.initedEmitter));
  }
  get(id) {
    const c = this.tabContainerMap.get(id);
    if (c) {
      return c;
    } else {
      const c2 = new TabContainer();
      this.tabContainerMap.set(id, c2);
      return c2;
    }
  }
  async register() {
    const bufnrs = await import_coc23.workspace.nvim.call("tabpagebuflist");
    await tabContainerManager.curTabAddBufnr(...bufnrs);
  }
  values() {
    return Array.from(this.tabContainerMap.values());
  }
  async currentTabId() {
    await this.waitInited;
    return await import_coc23.workspace.nvim.call("coc_explorer#tab#current_id");
  }
  async currentTabMaxId() {
    await this.waitInited;
    return await import_coc23.workspace.nvim.call("coc_explorer#tab#max_id");
  }
  async currentTabContainer() {
    return this.get(await this.currentTabId());
  }
  existBufnr(bufnr) {
    return this.values().some((c) => c.bufnrs.has(bufnr));
  }
  async curTabAddBufnr(...bufnrs) {
    const id = await this.currentTabId();
    const c = this.get(id);
    bufnrs.forEach((bufnr) => c.bufnrs.add(bufnr));
  }
  async curTabDelBufnr(...bufnrs) {
    const id = await this.currentTabId();
    const c = this.get(id);
    bufnrs.forEach((bufnr) => c.bufnrs.delete(bufnr));
  }
};
var tabContainerManager = new TabContainerManager();

// src/events.ts
var import_coc24 = require("coc.nvim");
var onEvent = (event, listener, thisArgs, disposables) => {
  const disposable = import_coc24.events.on(event, logger.asyncCatch(listener), thisArgs);
  const finalDisposable = import_coc24.Disposable.create(() => {
    if (typeof listener.cancel === "function") {
      listener.cancel();
    }
    if (typeof listener.dispose === "function") {
      listener.dispose();
    }
    disposable.dispose();
  });
  if (disposables) {
    disposables.push(finalDisposable);
  }
  return finalDisposable;
};
function onBufEnter(listener, delay, disposables) {
  let prevBufnr = 0;
  const handler = delay !== 0 ? debounceFn(delay, (bufnr) => {
    if (bufnr !== prevBufnr) {
      prevBufnr = bufnr;
      return listener(bufnr);
    }
  }) : listener;
  return onEvent("BufEnter", handler, void 0, disposables);
}
function onCursorMoved(listener, delay, disposables) {
  const handler = throttleFn(delay, listener, {
    leading: false,
    trailing: true
  });
  return onEvent("CursorMoved", handler, void 0, disposables);
}
function registerInternalEvents(context2) {
  const eventList = [
    [false, "BufDelete", ['+expand("<abuf>")']],
    [false, "BufWipeout", ['+expand("<abuf>")']],
    [false, "TabEnter", ['+expand("<abuf>")']],
    [false, "ColorScheme", ["g:colors_name"]],
    [true, "CocDiagnosticChange", []],
    [true, "CocGitStatusChange", []],
    [true, "FugitiveChanged", []],
    [true, "CocBookmarkChange", []]
  ];
  context2.subscriptions.push(
    ...eventList.map(
      ([user, event, arglist]) => import_coc24.workspace.registerAutocmd({
        event: user ? `User ${event}` : event,
        arglist,
        callback: async (...args) => {
          await internalEvents.fire(event, ...args);
        }
      })
    )
  );
}
var internalEvents = new HelperEventEmitter(logger);
var cocListCloseEmitter = new import_coc24.Emitter();
function doUserAutocmdNotifier(name) {
  return Notifier.create(() => {
    import_coc24.workspace.nvim.call("coc_explorer#util#do_autocmd", [name], true);
  });
}
async function doUserAutocmd(name) {
  await doUserAutocmdNotifier(name).run();
}

// src/bufManager.ts
var regex = /^\s*(\d+)(.+?)"(.+?)".*/;
var BufManager = class {
  constructor(context2) {
    this.bufferNodeMapByFullpath = /* @__PURE__ */ new Map();
    this.bufferNodeMapById = /* @__PURE__ */ new Map();
    this.nvim = import_coc25.workspace.nvim;
    this.reloadSubject = new Subject();
    this.modifiedSubject = new Subject();
    this.bufferNodes = [];
    this.onReload = subjectToHook(this.reloadSubject);
    this.onReloadDebounce = subjectToHook(this.reloadSubject.pipe(debounceTime(500)));
    this.onModifiedDebounce = subjectToHook(
      this.modifiedSubject.pipe(
        buffer(this.modifiedSubject.pipe(debounceTime(500)))
      )
    );
    this.registerEvents(context2).catch(logger.error);
  }
  async registerEvents(context2) {
    context2.subscriptions.push(
      onEvent(
        ["BufCreate", "BufHidden", "BufUnload", "BufWinEnter", "BufWinLeave"],
        throttleFn(100, () => this.reload(), {
          leading: false,
          trailing: true
        })
      ),
      internalEvents.on("BufDelete", () => this.reload()),
      internalEvents.on("BufWipeout", () => this.reload())
    );
    context2.subscriptions.push(
      onEvent(
        "BufWinEnter",
        (bufnr) => tabContainerManager.curTabAddBufnr(bufnr)
      ),
      internalEvents.on(
        "TabEnter",
        (bufnr) => tabContainerManager.curTabAddBufnr(bufnr)
      )
    );
    const refreshBufModified = async (bufnr) => {
      const bufNode = this.bufferNodeMapById.get(bufnr);
      if (!bufNode) {
        return;
      }
      const modified = await import_coc25.workspace.nvim.eval(
        // avoid error when buffer is not loaded
        `bufloaded(${bufnr}) ? getbufvar(${bufnr}, '&modified') : v:null`
      );
      if (modified === null || bufNode.modified === modified) {
        return;
      }
      bufNode.modified = modified;
      this.modifiedSubject.next(bufNode.fullpath);
    };
    context2.subscriptions.push(
      onEvent("BufWritePost", async (bufnr) => {
        await refreshBufModified(bufnr);
      }),
      ...["TextChanged", "TextChangedI", "TextChangedP"].map(
        (event) => onEvent(event, async (bufnr) => {
          await refreshBufModified(bufnr);
        })
      )
    );
  }
  async removeBufNode(bufNode, options) {
    if (!options.skipModified && bufNode.modified) {
      throw new Error("The content of buffer has not been saved!");
    }
    const winids = await winidsByBufnr(bufNode.bufnr);
    await leaveEmptyInWinids(winids);
    if (options.bwipeout) {
      await this.nvim.command(`bwipeout! ${bufNode.bufnr}`);
    } else {
      await this.nvim.command(`bdelete! ${bufNode.bufnr}`);
    }
  }
  async removePrefix(prefixFullpath, options) {
    for (const [fullpath, bufNode] of this.bufferNodeMapByFullpath) {
      if (fullpath.startsWith(prefixFullpath)) {
        await this.removeBufNode(bufNode, options);
      }
    }
  }
  async remove(fullpath, options) {
    if (options.directory) {
      return this.removePrefix(fullpath + import_path9.default.sep, options);
    } else {
      const bufNode = this.bufferNodeMapByFullpath.get(fullpath);
      if (!bufNode) {
        return;
      }
      await this.removeBufNode(bufNode, options);
    }
  }
  async replaceBufNode(bufNode, targetFullpath, options) {
    if (!options.skipModified && bufNode.modified) {
      throw new Error("The content of buffer has not been saved!");
    }
    const { nvim } = this;
    const curWinid = await nvim.call("win_getid", []);
    const winids = await winidsByBufnr(bufNode.bufnr);
    if (winids.length) {
      const escapedPath = await nvim.call("fnameescape", [
        targetFullpath
      ]);
      nvim.pauseNotification();
      for (const winid of winids) {
        nvim.call("win_gotoid", [winid], true);
        nvim.command(`edit ${escapedPath}`, true);
        if (import_coc25.workspace.isVim) {
          nvim.command("redraw", true);
        }
      }
      nvim.call("win_gotoid", [curWinid], true);
      await nvim.resumeNotification();
    }
    if (options.bwipeout) {
      await nvim.command(`bwipeout! ${bufNode.bufnr}`);
    } else {
      await nvim.command(`bdelete! ${bufNode.bufnr}`);
    }
  }
  async replacePrefix(sourceFullpath, targetFullpath, options) {
    for (const [fullpath, bufNode] of this.bufferNodeMapByFullpath) {
      if (fullpath.startsWith(sourceFullpath)) {
        const newTargetFullpath = bufNode.fullpath.replace(
          sourceFullpath,
          targetFullpath
        );
        await this.replaceBufNode(bufNode, newTargetFullpath, options);
      }
    }
  }
  async replace(sourceFullpath, targetFullpath, options) {
    return this.replacePrefix(sourceFullpath, targetFullpath, options);
  }
  /**
   * Return the whether fullpath is modified
   */
  modified(fullpath, options) {
    var _a2;
    if (options.directory) {
      return this.modifiedPrefix(fullpath + import_path9.default.sep);
    } else {
      return ((_a2 = this.bufferNodeMapByFullpath.get(fullpath)) == null ? void 0 : _a2.modified) ?? false;
    }
  }
  modifiedPrefix(prefixFullpath) {
    for (const [fullpath, bufNode] of this.bufferNodeMapByFullpath) {
      if (fullpath.startsWith(prefixFullpath)) {
        if (bufNode.modified) {
          return true;
        }
      }
    }
    return false;
  }
  getBufferNode(bufnrOrFullpath) {
    if (typeof bufnrOrFullpath === "number") {
      return this.bufferNodeMapById.get(bufnrOrFullpath);
    } else {
      return this.bufferNodeMapByFullpath.get(bufnrOrFullpath);
    }
  }
  async waitReload() {
    return new Promise((resolve6) => {
      const disposable = this.onReload(() => {
        disposable.dispose();
        resolve6();
      });
      setTimeout(resolve6, 100);
    });
  }
  async reload() {
    const lsCommand = "ls!";
    const content = await this.nvim.call("execute", lsCommand);
    this.bufferNodes = compactI2(
      await Promise.all(
        content.split(/\n/).map(async (line) => {
          const matches = line.match(regex);
          if (!matches) {
            return;
          }
          const bufnr = matches[1];
          const flags = matches[2];
          const bufname = matches[3];
          const fullpath = await import_coc25.workspace.nvim.call("expand", [
            `#${bufnr}:p`,
            1
          ]);
          return {
            type: "child",
            uid: bufnr,
            level: 1,
            bufnr: parseInt(bufnr),
            bufnrStr: bufnr,
            bufname,
            fullpath,
            name: import_path9.default.basename(bufname),
            unlisted: flags.includes("u"),
            current: flags.includes("%"),
            previous: flags.includes("#"),
            visible: flags.includes("a"),
            hidden: flags.includes("h"),
            modifiable: !flags.includes("-"),
            readonly: flags.includes("="),
            terminal: flags.includes("R") || flags.includes("F") || flags.includes("?"),
            modified: flags.includes("+"),
            readErrors: flags.includes("x")
          };
        })
      )
    );
    this.bufferNodeMapByFullpath = this.bufferNodes.reduce((map, node) => {
      map.set(node.fullpath, node);
      return map;
    }, /* @__PURE__ */ new Map());
    this.bufferNodeMapById = this.bufferNodes.reduce((map, node) => {
      map.set(node.bufnr, node);
      return map;
    }, /* @__PURE__ */ new Map());
    this.reloadSubject.next();
  }
};

// src/explorerManager.ts
var import_coc65 = require("coc.nvim");

// src/arg/parseArgs.ts
var import_coc27 = require("coc.nvim");

// src/presets.ts
var import_coc26 = require("coc.nvim");
async function getPresets(config4) {
  const presets = await import_coc26.workspace.nvim.eval(
    'get(g:, "coc_explorer_global_presets", {})'
  );
  return new Map(
    Object.entries({
      ...presets,
      ...config4.get("presets")
    }).map(([k, v]) => [k, new Map(Object.entries(v))])
  );
}

// src/arg/parseArgs.ts
var _Args = class _Args {
  constructor(args) {
    this.args = args;
    this.optionValues = /* @__PURE__ */ new Map();
  }
  static registerOption(name, options = {}) {
    const option = {
      type: options.position === void 0 ? "string" : "positional",
      name,
      ...options
    };
    this.registeredOptions.set(name, option);
    return option;
  }
  static registerBoolOption(name, defaultValue) {
    const option = {
      type: "boolean",
      name,
      getDefault: typeof defaultValue === "boolean" ? () => defaultValue : defaultValue
    };
    this.registeredOptions.set(name, option);
    this.registeredOptions.set(`no-${name}`, option);
    return option;
  }
  static async parse(strArgs, config4) {
    var _a2;
    const self2 = new _Args(strArgs);
    const args = [...strArgs];
    let position = 1;
    while (args.length > 0) {
      const arg = args.shift();
      if (arg.startsWith("--")) {
        let key, value;
        if (/^--[\w-]+=/.test(arg)) {
          [key = "", value] = splitCount(arg.slice(2), "=", 2);
        } else {
          key = arg.slice(2);
        }
        const option = this.registeredOptions.get(key);
        if (!option) {
          throw Error(`coc-explorer command no support option(${key})`);
        }
        if (value === void 0) {
          if (option.type === "boolean") {
            self2.optionValues.set(option.name, !key.startsWith("no-"));
            continue;
          } else {
            value = args.shift();
            if (value === void 0) {
              continue;
            }
          }
        }
        self2.optionValues.set(
          option.name,
          option.parseArg ? await option.parseArg(value) : value
        );
        continue;
      }
      const positional = Array.from(this.registeredOptions.values()).find(
        (option) => option.position === position
      );
      if (positional) {
        self2.optionValues.set(
          positional.name,
          positional.parseArg ? await positional.parseArg(arg) : arg
        );
      }
      position += 1;
    }
    const presetName = self2.optionValues.get("preset");
    if (!presetName) {
      return self2;
    }
    const presets = await getPresets(config4);
    const preset = presets.get(presetName);
    if (!preset) {
      await import_coc27.window.showWarningMessage(
        `coc-explorer preset(${presetName}) not found`
      );
      return self2;
    }
    for (const [argName, argValue] of preset) {
      if (self2.optionValues.has(argName) || argValue === void 0) {
        continue;
      }
      const option = this.registeredOptions.get(argName);
      if (option) {
        self2.optionValues.set(
          argName,
          ((_a2 = option.parsePreset) == null ? void 0 : _a2.call(option, argValue)) ?? argValue
        );
      }
    }
    return self2;
  }
  has(option) {
    return this.optionValues.has(option.name);
  }
  async value(option) {
    var _a2, _b, _c, _d;
    let result;
    if (this.optionValues.has(option.name)) {
      result = this.optionValues.get(option.name);
    } else {
      if (!_Args.registeredOptions.has(option.name)) {
        throw new Error(`Argument(${option.name}) not found`);
      } else {
        result = await ((_b = (_a2 = _Args.registeredOptions.get(option.name)) == null ? void 0 : _a2.getDefault) == null ? void 0 : _b.call(_a2));
      }
    }
    return ((_d = (_c = _Args.registeredOptions.get(option.name)) == null ? void 0 : _c.handler) == null ? void 0 : _d.call(_c, result)) ?? result;
  }
  async values(options) {
    const entries = await Promise.all(
      Object.entries(options).map(
        async ([key, option]) => [key, await this.value(option)]
      )
    );
    return entries.reduce((ret, [key, value]) => {
      ret[key] = value;
      return ret;
    }, {});
  }
};
_Args.registeredOptions = /* @__PURE__ */ new Map();
var Args = _Args;

// src/arg/argOptions.ts
var argOptions = {
  rootUri: Args.registerOption("root-uri", {
    position: 1
  }),
  rootStrategies: Args.registerOption("root-strategies", {
    parseArg: (originalStrategies) => originalStrategies.split(","),
    getDefault: () => config.get("root.strategies")
  }),
  toggle: Args.registerBoolOption(
    "toggle",
    () => config.get("toggle")
  ),
  openActionStrategy: Args.registerOption(
    "open-action-strategy",
    {
      getDefault: () => config.get("openAction.strategy")
    }
  ),
  focus: Args.registerBoolOption("focus", () => config.get("focus")),
  quit: Args.registerBoolOption("quit", false),
  quitOnOpen: Args.registerBoolOption(
    "quit-on-open",
    () => config.get("quitOnOpen")
  ),
  reveal: Args.registerOption("reveal", {
    handler: (path3) => path3 ? normalizePath(path3) : path3
  }),
  revealWhenOpen: Args.registerBoolOption("reveal-when-open"),
  preset: Args.registerOption("preset"),
  sources: Args.registerOption("sources", {
    parseArg: (sources) => sources.split(",").map((source) => {
      let expand2 = false;
      let name;
      if (source.endsWith("+")) {
        expand2 = true;
        name = source.slice(0, source.length - 1);
      } else if (source.endsWith("-")) {
        expand2 = false;
        name = source.slice(0, source.length - 1);
      } else {
        name = source;
      }
      return {
        name,
        expand: expand2
      };
    }),
    getDefault: () => config.get("sources")
  }),
  position: Args.registerOption(
    "position",
    {
      parseArg: (s) => {
        const [name, arg] = s.split(":");
        return { name, arg };
      },
      parsePreset: (pos) => {
        if (Array.isArray(pos)) {
          return { name: pos[0], arg: pos[0] };
        } else if (typeof pos === "string") {
          return { name: pos };
        } else {
          return pos;
        }
      },
      getDefault: () => {
        const pos = config.get("position");
        if (Array.isArray(pos)) {
          return { name: pos[0], arg: pos[1] };
        } else {
          return { name: pos };
        }
      }
    }
  ),
  width: Args.registerOption("width", {
    parseArg: (s) => parseInt(s, 10),
    getDefault: () => config.get("width")
  }),
  contentWidth: Args.registerOption("content-width", {
    parseArg: (s) => parseInt(s, 10),
    getDefault: () => config.get("contentWidth")
  }),
  contentWidthType: Args.registerOption("content-width-type", {
    getDefault: () => config.get("contentWidthType")
  }),
  floatingPosition: Args.registerOption("floating-position", {
    parseArg: (s) => {
      if (["left-center", "right-center", "center", "center-top"].includes(s)) {
        return s;
      } else {
        return s.split(",").map((i) => parseInt(i, 10));
      }
    },
    getDefault: () => config.get("floating.position")
  }),
  floatingWidth: Args.registerOption("floating-width", {
    parseArg: (s) => parseInt(s, 10),
    getDefault: () => config.get("floating.width")
  }),
  floatingHeight: Args.registerOption("floating-height", {
    parseArg: (s) => parseInt(s, 10),
    getDefault: () => config.get("floating.height")
  }),
  floatingContentWidth: Args.registerOption("floating-content-width", {
    parseArg: (s) => parseInt(s, 10),
    getDefault: () => config.get("floating.contentWidth")
  })
};

// src/contextVariables.ts
var import_coc28 = require("coc.nvim");
var variableName = "coc_explorer_context";
var ContextVars = class {
  constructor(name) {
    this.name = name;
  }
  async set(value) {
    const obj = await this.read();
    if (value === void 0) {
      Reflect.deleteProperty(obj, this.name);
    } else {
      Reflect.set(obj, this.name, value);
    }
    await this.write(obj);
  }
  async get() {
    const obj = await this.read();
    return Reflect.get(obj, this.name);
  }
};
var BuffuerContextVars = class extends ContextVars {
  constructor(name, buffer2) {
    super(name);
    this.name = name;
    this.buffer = buffer2;
  }
  async read() {
    return await this.buffer.getVar(variableName) || {};
  }
  async write(obj) {
    await this.buffer.setVar(variableName, obj);
  }
};
var GlobalContextVars = class extends ContextVars {
  constructor() {
    super(...arguments);
    this.nvim = import_coc28.workspace.nvim;
  }
  async read() {
    return await this.nvim.getVar(variableName) ?? {};
  }
  async write(obj) {
    await this.nvim.setVar(variableName, obj);
  }
};

// src/explorer.ts
var import_coc63 = require("coc.nvim");
var import_p_filter2 = __toESM(require_p_filter());

// src/actions/actionExplorer.ts
var import_coc29 = require("coc.nvim");

// src/actions/registrar.ts
var ActionRegistrar = class {
  constructor(owner) {
    this.owner = owner;
    this.actions = /* @__PURE__ */ new Map();
  }
  /**
   * add an action that uses the selected node and clear it
   */
  addNodesAction(name, callback, description, options = {}) {
    this.actions.set(name, {
      callback,
      description,
      options: {
        select: true,
        ...options
      }
    });
  }
  /**
   * add an action
   */
  addNodeAction(name, callback, description, options = {}) {
    this.actions.set(name, {
      callback: async ({ source, nodes, args, mode }) => {
        for (const node of nodes) {
          await callback.call(source, { source, node, args, mode });
        }
      },
      description,
      options
    });
  }
};

// src/actions/actionExplorer.ts
var ActionExplorer = class extends ActionRegistrar {
  constructor(owner) {
    super(owner);
    this.waitActionMutex = new import_coc29.Mutex();
    this.explorer = this.owner;
  }
  get locator() {
    return this.explorer.locator;
  }
  async doActionByKey(key, mode, count = 1) {
    for (let c = 0; c < count; c++) {
      const selectedLineIndexes = await this.explorer.getSelectedOrCursorLineIndexes(mode);
      const lineIndexesGroups = this.explorer.lineIndexesGroupBySource(selectedLineIndexes);
      for (const { source, lineIndexes } of lineIndexesGroups) {
        const actionExp = keyMapping.getActionExp(source.sourceType, key, mode);
        if (actionExp) {
          await this.doActionExp(actionExp, {
            mode,
            lineIndexes
          });
        }
      }
    }
    await this.explorer.view.emitRequestRenderNodes();
  }
  async doActionExp(actionExp, options = {}) {
    const count = options.count ?? 1;
    const mode = options.mode ?? "n";
    const firstLineIndexes = options.lineIndexes ? new Set(options.lineIndexes) : await this.explorer.getSelectedOrCursorLineIndexes(mode);
    try {
      for (let c = 0; c < count; c++) {
        const lineIndexes = c === 0 ? firstLineIndexes : await this.explorer.getSelectedOrCursorLineIndexes(mode);
        const nodesGroup = /* @__PURE__ */ new Map();
        for (const lineIndex of lineIndexes) {
          const { source } = this.explorer.findSourceByLineIndex(lineIndex);
          if (!nodesGroup.has(source)) {
            nodesGroup.set(source, []);
          }
          const relativeLineIndex = lineIndex - source.view.startLineIndex;
          nodesGroup.get(source).push(source.view.flattenedNodes[relativeLineIndex]);
        }
        for (const [source, nodes] of nodesGroup) {
          await source.action.doActionExp(actionExp, nodes, { mode });
        }
      }
    } catch (error) {
      await import_coc29.window.showErrorMessage(
        `Error when do action(${JSON.stringify(actionExp)})`
      );
      logger.error(error);
    }
  }
  async nodePrev(moveStrategy = "default", condition) {
    const gotoPrev = async (nodes, lineIndex, startLineIndex) => {
      const relativeIndex = scanIndexPrev(
        nodes,
        lineIndex,
        await enableWrapscan(),
        condition
      );
      if (relativeIndex === void 0) {
        return;
      }
      await this.locator.gotoLineIndex(startLineIndex + relativeIndex);
    };
    if (moveStrategy === "insideSource") {
      const source = await this.explorer.view.currentSource();
      if (!source) {
        return;
      }
      await gotoPrev(
        source.view.flattenedNodes,
        source.view.currentLineIndex,
        source.view.startLineIndex
      );
    } else {
      await gotoPrev(
        this.explorer.view.flattenedNodes,
        this.explorer.view.currentLineIndex,
        0
      );
    }
  }
  async nodeNext(moveStrategy = "default", condition) {
    const gotoNext = async (nodes, lineIndex, startLineIndex) => {
      const relativeIndex = scanIndexNext(
        nodes,
        lineIndex,
        await enableWrapscan(),
        condition
      );
      if (relativeIndex === void 0) {
        return;
      }
      await this.locator.gotoLineIndex(startLineIndex + relativeIndex);
    };
    if (moveStrategy === "insideSource") {
      const source = await this.explorer.view.currentSource();
      if (!source) {
        return;
      }
      await gotoNext(
        source.view.flattenedNodes,
        source.view.currentLineIndex,
        source.view.startLineIndex
      );
    } else {
      await gotoNext(
        this.explorer.view.flattenedNodes,
        this.explorer.view.currentLineIndex,
        0
      );
    }
  }
};

// src/actions/globalActions.ts
var import_coc34 = require("coc.nvim");
var import_path13 = __toESM(require("path"));

// src/git/manager.ts
var import_coc32 = require("coc.nvim");
var import_path12 = __toESM(require("path"));

// src/git/binder.ts
var import_coc30 = require("coc.nvim");
var import_path10 = __toESM(require("path"));

// src/git/types.ts
var GitFormat = /* @__PURE__ */ ((GitFormat2) => {
  GitFormat2["mixed"] = "*";
  GitFormat2["unmodified"] = " ";
  GitFormat2["modified"] = "M";
  GitFormat2["added"] = "A";
  GitFormat2["deleted"] = "D";
  GitFormat2["renamed"] = "R";
  GitFormat2["copied"] = "C";
  GitFormat2["unmerged"] = "U";
  GitFormat2["untracked"] = "?";
  GitFormat2["ignored"] = "!";
  return GitFormat2;
})(GitFormat || {});

// src/git/binder.ts
var statusEqual = (a, b) => {
  return a.x === b.x && a.y === b.y;
};
var rootStatusEqual = (a, b) => {
  if (a.allStaged !== b.allStaged) {
    return false;
  }
  return a.formats.join(",") === b.formats.join(",");
};
var GitBinder = class {
  constructor() {
    this.sourcesBinding = /* @__PURE__ */ new Map();
    /**
     * prevStatusesMapInRoot[root][path] = GitMixedStatus
     */
    this.prevStatusesMapInRoot = /* @__PURE__ */ new Map();
    /**
     * prevIgnoresMapInRoot[root][path] = GitRootStatus
     */
    this.prevIgnoresMapInRoot = /* @__PURE__ */ new Map();
    /**
     * prevRootStatuses[root] = GitRootStatus
     */
    this.prevRootStatuses = /* @__PURE__ */ new Map();
    this.registerForSourceDisposables = [];
    this.registerDisposables = [];
    this.inited = false;
    this.reloadDebounceSubject = createSubject(
      (sub) => sub.pipe(
        buffer(sub.pipe(debounceTime(200))),
        switchMap(async (list) => {
          const sources = new Set(list.map((it) => it.sources).flat());
          const directories = new Set(list.map((it) => it.directory));
          await this.reload([...sources], [...directories]);
        })
      )
    );
  }
  get explorerManager() {
    if (!this.explorerManager_) {
      throw new Error("ExplorerSource(explorerManager) is not bound yet");
    }
    return this.explorerManager_;
  }
  get sources() {
    return Array.from(this.sourcesBinding.keys());
  }
  get refTotalCount() {
    return sum_default(Array.from(this.sourcesBinding.values()).map((b) => b.refCount));
  }
  init_(source) {
    if (!this.inited) {
      this.inited = true;
      this.explorerManager_ = source.explorer.explorerManager;
    }
  }
  bind(source) {
    this.init_(source);
    const binding = mapGetWithDefault(this.sourcesBinding, source, () => ({
      refCount: 0
    }));
    binding.refCount += 1;
    if (binding.refCount === 1) {
      this.registerForSourceDisposables = this.registerForSource(source);
    }
    if (this.refTotalCount === 1) {
      this.registerDisposables = this.register();
    }
    return import_coc30.Disposable.create(() => {
      binding.refCount -= 1;
      if (binding.refCount === 0) {
        (0, import_coc30.disposeAll)(this.registerForSourceDisposables);
        this.registerForSourceDisposables = [];
      }
      if (this.refTotalCount === 0) {
        (0, import_coc30.disposeAll)(this.registerDisposables);
        this.registerDisposables = [];
      }
    });
  }
  register() {
    return [
      ...["CocGitStatusChange", "FugitiveChanged"].map(
        (event) => internalEvents.on(event, async () => {
          this.reloadDebounceSubject.next({
            sources: this.sources,
            directory: import_coc30.workspace.cwd
          });
        })
      ),
      onEvent("BufWritePost", async (bufnr) => {
        var _a2;
        const fullpath = (_a2 = this.explorerManager.bufManager.getBufferNode(bufnr)) == null ? void 0 : _a2.fullpath;
        if (fullpath) {
          const dirname = import_path10.default.dirname(fullpath);
          this.reloadDebounceSubject.next({
            sources: this.sources,
            directory: dirname
          });
        }
      })
    ];
  }
  registerForSource(source) {
    return [
      source.events.on("loaded", async (node) => {
        const directory = "isRoot" in node ? source.root : node.expandable ? node.fullpath : node.fullpath && import_path10.default.dirname(node.fullpath);
        if (directory) {
          this.reloadDebounceSubject.next({ sources: [source], directory });
        }
      })
    ];
  }
  async reload(sources, directories) {
    const roots = await gitManager.getGitRoots(directories);
    if (!roots.length) {
      return;
    }
    const updatePaths = /* @__PURE__ */ new Set();
    const updateDirs = /* @__PURE__ */ new Set();
    for (const root2 of roots) {
      await gitManager.reload(root2);
      const statuses = gitManager.getMixedStatusesByRoot(root2);
      const ignores = gitManager.getIgnoreByRoot(root2);
      const rootStatus = gitManager.getRootStatus(root2) || {
        allStaged: false,
        formats: []
      };
      let prevStatusMap = this.prevStatusesMapInRoot.get(root2);
      if (!prevStatusMap) {
        prevStatusMap = /* @__PURE__ */ new Map();
        this.prevStatusesMapInRoot.set(root2, prevStatusMap);
      }
      let prevIgnoreMap = this.prevIgnoresMapInRoot.get(root2);
      if (!prevIgnoreMap) {
        prevIgnoreMap = /* @__PURE__ */ new Map();
        this.prevIgnoresMapInRoot.set(root2, prevIgnoreMap);
      }
      let prevRootStatus = this.prevRootStatuses.get(root2);
      if (!prevRootStatus) {
        prevRootStatus = {
          allStaged: false,
          formats: []
        };
        this.prevRootStatuses.set(root2, prevRootStatus);
      }
      const addGitIgnore = (fullpath, gitIgnore) => {
        if (gitIgnore === 0 /* directory */) {
          updateDirs.add(fullpath.replace(/[\\/]$/, ""));
        } else {
          updatePaths.add(fullpath);
        }
      };
      for (const [fullpath, status] of statuses) {
        const prevStatus = prevStatusMap.get(fullpath);
        if (prevStatus) {
          if (statusEqual(prevStatus, status)) {
            prevStatusMap.delete(fullpath);
            continue;
          }
        }
        updatePaths.add(fullpath);
      }
      for (const fullpath of prevStatusMap.keys()) {
        updatePaths.add(fullpath);
      }
      for (const [fullpath, gitIgnore] of ignores) {
        const prevIgnore = prevIgnoreMap.get(fullpath);
        if (prevIgnore === gitIgnore) {
          prevIgnoreMap.delete(fullpath);
          continue;
        }
        addGitIgnore(fullpath, gitIgnore);
      }
      for (const [fullpath, gitIgnore] of prevIgnoreMap) {
        addGitIgnore(fullpath, gitIgnore);
      }
      if (!rootStatusEqual(prevRootStatus, rootStatus)) {
        updatePaths.add(root2);
      }
      this.prevStatusesMapInRoot.set(root2, statuses);
      this.prevIgnoresMapInRoot.set(root2, ignores);
      this.prevRootStatuses.set(root2, rootStatus);
    }
    for (const source of sources) {
      await source.view.renderPaths([
        ...updatePaths,
        {
          paths: updateDirs,
          withChildren: true
        }
      ]);
    }
  }
};

// src/git/command.ts
var import_coc31 = require("coc.nvim");
var import_command_exists = __toESM(require_command_exists2());
var import_path11 = __toESM(require("path"));
var _GitCommand = class _GitCommand {
  static get binPath() {
    return config.get("git.command");
  }
  static async waitLoaded() {
    if (this.loaded) {
      return;
    }
    return new Promise((resolve6) => {
      this.onLoaded(resolve6);
    });
  }
  static async preload() {
    try {
      await (0, import_command_exists.default)(this.binPath);
      this.available = true;
    } catch (e) {
      this.available = false;
    } finally {
      this.loaded = true;
      this.loadedEmitter.fire();
    }
  }
  get binPath() {
    return _GitCommand.binPath;
  }
  async available() {
    await _GitCommand.waitLoaded();
    return _GitCommand.available;
  }
  spawn(args, { cwd } = {}) {
    return execCmd(this.binPath, args, {
      cwd
    });
  }
  async getRoot(filepath) {
    const stat3 = await fsStat(filepath).catch(() => void 0);
    const cwd = (stat3 == null ? void 0 : stat3.isDirectory()) ? filepath : import_path11.default.dirname(filepath);
    const output = await this.spawn(["rev-parse", "--show-toplevel"], {
      cwd
    });
    return normalizePath(output.trim());
  }
  parseStatusFormat(format2) {
    return Object.values(GitFormat).find((it) => it.toString() === format2) ?? " " /* unmodified */;
  }
  parsePath(str, hasArrow) {
    let index = 0;
    let path3 = "";
    let inPath = false;
    let inQuote = false;
    let inEscape = false;
    const paths = [];
    while (index < str.length) {
      const ch = str[index];
      if (!inPath && !inQuote) {
        if (ch === '"') {
          inQuote = true;
          index += 1;
        }
        path3 = "";
        inPath = true;
        continue;
      } else {
        if (inQuote) {
          if (inEscape) {
            path3 += ch === "t" ? "	" : ch;
            inEscape = false;
          } else {
            if (ch === '"') {
              paths.push(path3);
              inQuote = false;
              inPath = false;
            } else if (ch === "\\") {
              inEscape = true;
            } else {
              path3 += ch;
            }
          }
        } else {
          if (ch === " ") {
            if (hasArrow && str.slice(index, index + 4) === " -> ") {
              if (path3.length) {
                paths.push(path3);
              }
              index += 3;
              inPath = false;
            } else {
              path3 += ch;
            }
          } else {
            path3 += ch;
          }
        }
      }
      index += 1;
    }
    if (inPath) {
      paths.push(path3);
      inPath = false;
    }
    return paths;
  }
  parseStatusLine(gitRoot, line) {
    const xFormat = this.parseStatusFormat(line[0] ?? "");
    const yFormat = this.parseStatusFormat(line[1] ?? "");
    const rawPath = line.slice(3);
    const hasArrow = ["R" /* renamed */, "C" /* copied */].includes(xFormat) || ["R" /* renamed */, "C" /* copied */].includes(yFormat);
    const paths = this.parsePath(rawPath, hasArrow);
    return [
      xFormat,
      yFormat,
      ...paths.map((p) => import_path11.default.join(gitRoot, p))
    ];
  }
  async status(root2, {
    showUntrackedFiles = "system",
    showIgnored = true
  } = {}) {
    const gitStatus = /* @__PURE__ */ new Map();
    const args = ["status", "--porcelain"];
    if (showUntrackedFiles === true) {
      args.push("-u");
    } else if (showUntrackedFiles === false) {
      args.push("-uno");
    }
    if (showIgnored) {
      args.push("--ignored=matching");
    }
    const output = await this.spawn(args, { cwd: root2 });
    const lines = output.split("\n");
    lines.forEach((line) => {
      if (!line) {
        return;
      }
      const [x_, y_, leftpath, rightpath] = this.parseStatusLine(root2, line);
      const x = x_ === "?" /* untracked */ ? " " /* unmodified */ : x_;
      const y = y_ === "!" /* ignored */ ? " " /* unmodified */ : y_;
      const changedList = [
        "M" /* modified */,
        "A" /* added */,
        "D" /* deleted */,
        "R" /* renamed */,
        "C" /* copied */
      ];
      const added = x === "A" /* added */ || y === "A" /* added */;
      const modified = x === "M" /* modified */ || y === "M" /* modified */;
      const deleted = x === "D" /* deleted */ || y === "D" /* deleted */;
      const renamed = x === "R" /* renamed */ || y === "R" /* renamed */;
      const copied = x === "C" /* copied */ || y === "C" /* copied */;
      const staged = changedList.includes(x) && y === " " /* unmodified */;
      const unmerged = x === "D" /* deleted */ && y === "D" /* deleted */ || x === "A" /* added */ && y === "A" /* added */ || x === "U" /* unmerged */ || y === "U" /* unmerged */;
      const ignored = x === "!" /* ignored */;
      const untracked = y === "?" /* untracked */;
      const fullpath = rightpath ? rightpath : leftpath;
      gitStatus.set(fullpath, {
        fullpath,
        x,
        y,
        added,
        modified,
        deleted,
        renamed,
        copied,
        staged,
        unmerged,
        untracked,
        ignored
      });
    });
    return gitStatus;
  }
  async stage(paths) {
    if (paths.length) {
      const root2 = await this.getRoot(paths[0] ?? "");
      await this.spawn(["add", ...paths], { cwd: root2 });
    }
  }
  async unstage(paths) {
    if (paths.length) {
      const root2 = await this.getRoot(paths[0] ?? "");
      await this.spawn(["reset", ...paths], { cwd: root2 });
    }
  }
  async fetch(root2) {
    await this.spawn(["fetch"], { cwd: root2 });
  }
  async hasPull(root2) {
    const count = await this.spawn(["rev-list", "--count", "@..@{upstream}"], {
      cwd: root2
    });
    return parseInt(count);
  }
  async hasPush(root2) {
    const count = await this.spawn(["rev-list", "--count", "@{upstream}..@"], {
      cwd: root2
    });
    return parseInt(count);
  }
  async hasStashed(root2) {
    const list = await this.spawn(["stash", "list"], {
      cwd: root2
    });
    return list.split(/\n/g).length - 1;
  }
  async checkIgnore(paths) {
    if (!paths.length) {
      return [];
    }
    const root2 = await this.getRoot(paths[0] ?? "");
    const output = await this.spawn(["check-ignore", ...paths], { cwd: root2 });
    return output.split(/\n/g);
  }
};
_GitCommand.available = false;
_GitCommand.loadedEmitter = new import_coc31.Emitter();
_GitCommand.loaded = false;
_GitCommand.onLoaded = _GitCommand.loadedEmitter.event;
var GitCommand = _GitCommand;

// src/git/manager.ts
var GitManager = class {
  constructor() {
    this.cmd = new GitCommand();
    /**
     * rootCache[fullpath] = rootPath
     **/
    this.rootCache = /* @__PURE__ */ new Map();
    /**
     * mixedStatusMapCacheInRoot[rootPath][filepath] = GitStatus
     **/
    this.mixedStatusMapCacheInRoot = /* @__PURE__ */ new Map();
    /**
     * ignoreMapCacheInRoot[rootPath][filepath] = GitIgnore
     **/
    this.ignoreMapCacheInRoot = /* @__PURE__ */ new Map();
    /**
     * rootStatusCache[rootPath] = GitRootStatus
     */
    this.rootStatusCache = /* @__PURE__ */ new Map();
    this.binder = new GitBinder();
    this.showIgnored = config.get("git.showIgnored");
    this.showUntrackedFiles = config.get(
      "file.git.showUntrackedFiles"
    );
  }
  async getGitRoots(directories) {
    const directorySet = [...new Set(directories)];
    const roots = await Promise.all(
      directorySet.map((directory) => this.getGitRoot(directory))
    );
    return compactI2(roots);
  }
  async getGitRoot(directory) {
    const root2 = this.rootCache.get(directory);
    if (root2)
      return root2;
    const parts = directory.split(import_path12.default.sep);
    const idx = parts.indexOf(".git");
    if (idx !== -1) {
      const root3 = parts.slice(0, idx).join(import_path12.default.sep);
      this.rootCache.set(directory, root3);
    } else {
      try {
        const gitRoot = await this.cmd.getRoot(directory);
        if (import_path12.default.isAbsolute(gitRoot)) {
          this.rootCache.set(directory, gitRoot);
        } else {
          import_path12.default.join(directory, gitRoot);
        }
      } catch (error) {
        logger.error(error);
        return;
      }
    }
    return this.rootCache.get(directory);
  }
  async reload(directory, options = {}) {
    const root2 = await this.getGitRoot(directory);
    if (root2) {
      const statusOptions = {
        showIgnored: options.showIgnored ?? this.showIgnored,
        showUntrackedFiles: options.showUntrackedFiles ?? this.showUntrackedFiles
      };
      const statusRecord = await this.cmd.status(root2, statusOptions);
      const statusArray = [...statusRecord.values()];
      const rootStatus = {
        allStaged: true,
        formats: []
      };
      this.rootStatusCache.set(root2, rootStatus);
      if (await this.cmd.hasStashed(root2)) {
        rootStatus.formats.push(5 /* stashed */);
      }
      if (await this.cmd.hasPull(root2)) {
        rootStatus.formats.push(2 /* behind */);
      }
      if (await this.cmd.hasPush(root2)) {
        rootStatus.formats.push(1 /* ahead */);
      }
      if (statusArray.some((s) => s.y === "U" /* unmerged */)) {
        rootStatus.formats.push(3 /* conflicted */);
      }
      if (statusArray.some((s) => s.y === "?" /* untracked */)) {
        rootStatus.formats.push(4 /* untracked */);
      }
      if (statusArray.some(
        (s) => s.x === "M" /* modified */ || s.y === "M" /* modified */
      )) {
        rootStatus.formats.push(6 /* modified */);
      }
      if (statusArray.some((s) => s.x === "A" /* added */)) {
        rootStatus.formats.push(7 /* added */);
      }
      if (statusArray.some((s) => s.x === "R" /* renamed */)) {
        rootStatus.formats.push(8 /* renamed */);
      }
      if (statusArray.some(
        (s) => s.x === "D" /* deleted */ || s.y === "D" /* deleted */
      )) {
        rootStatus.formats.push(9 /* deleted */);
      }
      if (statusArray.some((s) => s.y !== " " /* unmodified */)) {
        rootStatus.allStaged = false;
      }
      const mixedStatusMap = /* @__PURE__ */ new Map();
      const ignoreMap = /* @__PURE__ */ new Map();
      this.mixedStatusMapCacheInRoot.set(root2, mixedStatusMap);
      this.ignoreMapCacheInRoot.set(root2, ignoreMap);
      statusRecord.forEach((status, fullpath) => {
        if (status.x === "!" /* ignored */) {
          if (["/", "\\"].includes(fullpath[fullpath.length - 1])) {
            ignoreMap.set(fullpath, 0 /* directory */);
          } else {
            ignoreMap.set(fullpath, 1 /* file */);
          }
          return;
        }
        const relativePath = import_path12.default.relative(root2, fullpath);
        const parts = relativePath.split(import_path12.default.sep);
        for (let i = 1; i <= parts.length; i++) {
          const frontalPath = import_path12.default.join(
            root2,
            import_path12.default.join(...parts.slice(0, i))
          );
          const cache = mixedStatusMap.get(frontalPath);
          if (cache) {
            if (cache.x !== "*" /* mixed */) {
              if (cache.x !== status.x) {
                if (cache.x === " " /* unmodified */) {
                  cache.x = status.x;
                } else if (status.x !== " " /* unmodified */) {
                  cache.x = "*" /* mixed */;
                }
              }
            }
            if (cache.y !== "*" /* mixed */) {
              if (cache.y !== status.y) {
                if (cache.y === " " /* unmodified */) {
                  cache.y = status.y;
                } else if (status.y !== " " /* unmodified */) {
                  cache.y = "*" /* mixed */;
                }
              }
            }
          } else {
            mixedStatusMap.set(frontalPath, {
              x: status.x,
              y: status.y
            });
          }
        }
      });
    }
    return root2;
  }
  /**
   * Automatically update column, when git reload
   *
   * @example
   * ```typescript
   * columnRegistrar.registerColumn(
   *   'columnType',
   *   'columnName',
   *   ({ source, subscriptions }) => {
   *     return {
   *       async init() {
   *         subscriptions.push(gitManager.bindColumn(source));
   *       },
   *       async draw() {
   *         ...
   *       },
   *     };
   *   },
   * );
   * ```
   */
  bindColumn(source) {
    const enabled = config.get("git.enable");
    if (!enabled) {
      return import_coc32.Disposable.create(() => {
      });
    }
    return this.binder.bind(source);
  }
  getMixedStatusesByRoot(rootPath) {
    return this.mixedStatusMapCacheInRoot.get(rootPath) || /* @__PURE__ */ new Map();
  }
  getIgnoreByRoot(rootPath) {
    return this.ignoreMapCacheInRoot.get(rootPath) || /* @__PURE__ */ new Map();
  }
  getMixedStatus(fullpath, isDirectory) {
    const statusPair = [...this.mixedStatusMapCacheInRoot.entries()].sort((a, b) => b[0].localeCompare(a[0])).find(([rootPath]) => fullpath.startsWith(rootPath));
    if (statusPair) {
      const pathStatus = statusPair[1].get(fullpath);
      if (pathStatus) {
        return pathStatus;
      }
    }
    const ignorePair = [...this.ignoreMapCacheInRoot.entries()].sort((a, b) => b[0].localeCompare(a[0])).find(([rootPath]) => fullpath.startsWith(rootPath));
    if (ignorePair) {
      const gitIgnores = ignorePair[1];
      const isIgnore = [...gitIgnores.entries()].some(
        ([ignorePath, gitIgnore]) => {
          if (gitIgnore === 1 /* file */) {
            return ignorePath === fullpath;
          } else {
            const directoryPath = isDirectory ? fullpath + import_path12.default.sep : fullpath;
            return directoryPath.startsWith(ignorePath);
          }
        }
      );
      if (isIgnore) {
        return { x: "!" /* ignored */, y: " " /* unmodified */ };
      }
    }
  }
  getRootStatus(root2) {
    return this.rootStatusCache.get(root2);
  }
};
var gitManager = new GitManager();

// src/types/index.ts
var textobjTargetList = ["line", "indent"];
var textobjTypeList = ["i", "a"];
var moveStrategyList = ["default", "insideSource"];
var revealStrategyList = [
  "select",
  "previousBuffer",
  "previousWindow",
  "sourceWindow",
  "path"
];
var openStrategyList = [
  "select",
  "split",
  "split.plain",
  "split.intelligent",
  "vsplit",
  "vsplit.plain",
  "vsplit.intelligent",
  "tab",
  "previousBuffer",
  "previousWindow",
  "sourceWindow"
];
var quickfixActions = ["add", "replace"];
var copyOrCutFileTypeList = ["toggle", "append", "replace"];
var previewOnHoverActionList = [
  "toggle",
  "enable",
  "disable"
];
var previewStrategyList = [
  "labeling",
  "content"
];
var rootStrategyList = [
  "keep",
  "workspace",
  "cwd",
  "sourceBuffer",
  "reveal"
];
var searchOptionList = ["recursive", "noIgnore", "strict"];
var expandOptionList = [
  "recursive",
  "compact",
  "uncompact",
  "recursiveSingle"
];
var collapseOptionList = ["recursive", "all"];

// src/actions/openAction.ts
var import_coc33 = require("coc.nvim");
var OpenActionContext = class {
  constructor(explorer, source, cursorPosition, getFullpath, quitOnOpenNotifier, explorerWinid) {
    this.explorer = explorer;
    this.source = source;
    this.cursorPosition = cursorPosition;
    this.getFullpath = getFullpath;
    this.quitOnOpenNotifier = quitOnOpenNotifier;
    this.explorerWinid = explorerWinid;
    this.nvim = import_coc33.workspace.nvim;
    this.explorerPosition = explorer.argValues.position;
  }
  async openByWinnr(winnr) {
    const openNotifier = await this.openFilepathNotifier("edit");
    await this.openWrap(() => {
      this.nvim.command(`${winnr}wincmd w`, true);
      openNotifier.notify();
      if (import_coc33.workspace.isVim) {
        this.nvim.command("redraw", true);
      }
    });
  }
  async openByWinid(winid) {
    const openNotifier = await this.openFilepathNotifier("edit");
    await this.openWrap(() => {
      this.nvim.call("win_gotoid", [winid], true);
      openNotifier.notify();
      if (import_coc33.workspace.isVim) {
        this.nvim.command("redraw", true);
      }
    });
  }
  jumpToNotify() {
    if (this.cursorPosition === "keep") {
      if (!this.explorerWinid) {
        return;
      }
      this.nvim.call("win_gotoid", [this.explorerWinid], true);
    } else if (this.cursorPosition) {
      this.nvim.call(
        "cursor",
        [
          this.cursorPosition.lineIndex + 1,
          (this.cursorPosition.columnIndex ?? 0) + 1
        ],
        true
      );
    }
  }
  async openWrap(callback, options) {
    const earlyQuit = (options == null ? void 0 : options.earlyQuit) ?? false;
    const notifiers = [];
    if (earlyQuit)
      await this.explorer.tryQuitOnOpen();
    else
      notifiers.push(await this.quitOnOpenNotifier());
    const lastWinnr = await this.nvim.call("winnr", ["$"]);
    const resizeIt = lastWinnr === 1 && this.explorerPosition.name !== "floating";
    this.nvim.pauseNotification();
    callback();
    Notifier.notifyAll(notifiers);
    this.jumpToNotify();
    if (resizeIt)
      this.explorer.resizeNotifier().notify();
    await this.nvim.resumeNotification();
  }
  async openFilepathNotifier(cmd) {
    const fullpath = await this.getFullpath();
    const isRel = this.explorer.config.get("openAction.relativePath");
    return Notifier.create(() => {
      this.nvim.call(
        "coc_explorer#util#open_file",
        [cmd, fullpath, isRel],
        true
      );
    });
  }
  async tryResize() {
    await this.explorer.resize();
  }
};
var OpenActions = class {
  constructor(ctx) {
    this.ctx = ctx;
  }
  async select() {
    const ctx = this.ctx;
    if (ctx.explorerPosition.name === "floating") {
      await ctx.explorer.hide();
    }
    await selectWindowsUI(ctx.explorer.config, ctx.source.sourceType, {
      onSelect: async (winnr) => {
        await ctx.openByWinnr(winnr);
      },
      noChoice: async () => {
        await this.vsplit();
      },
      onCancel: async () => {
        if (ctx.explorerPosition.name === "floating") {
          await ctx.explorer.show();
        }
      }
    });
  }
  async splitIntelligent(command, fallbackStrategy) {
    const ctx = this.ctx;
    const explWinid = await ctx.explorer.winid;
    if (!explWinid) {
      return;
    }
    const winFinder = await WinLayoutFinder.create();
    const node = winFinder.findWinid(explWinid);
    if (node) {
      if (node.parent && node.parent.group.type === "row") {
        const target = node.parent.group.children[node.parent.indexInParent + (ctx.explorerPosition.name === "left" ? 1 : -1)];
        if (target) {
          const targetWinid = WinLayoutFinder.getFirstLeafWinid(target);
          const openNotifier = await ctx.openFilepathNotifier(command);
          await ctx.openWrap(() => {
            ctx.nvim.call("win_gotoid", [targetWinid], true);
            openNotifier.notify();
          });
        }
      } else {
        await this["vsplit.plain"]();
      }
    } else {
      await this[fallbackStrategy]();
    }
  }
  async split() {
    await this["split.intelligent"]();
  }
  async "split.plain"() {
    const ctx = this.ctx;
    const openNotifier = await ctx.openFilepathNotifier("split");
    await ctx.openWrap(() => {
      openNotifier.notify();
    });
  }
  async "split.intelligent"() {
    const ctx = this.ctx;
    if (ctx.explorerPosition.name === "floating") {
      await this["split.plain"]();
      return;
    } else if (ctx.explorerPosition.name === "tab") {
      await this.vsplit();
      return;
    }
    await this.splitIntelligent("split", "split.plain");
  }
  async vsplit() {
    await this["vsplit.intelligent"]();
  }
  async "vsplit.plain"() {
    const ctx = this.ctx;
    const openNotifier = await ctx.openFilepathNotifier("vsplit");
    await ctx.openWrap(() => {
      openNotifier.notify();
    });
  }
  async "vsplit.intelligent"() {
    const ctx = this.ctx;
    if (ctx.explorerPosition.name === "floating") {
      await this["vsplit.plain"]();
      return;
    } else if (ctx.explorerPosition.name === "tab") {
      await this["vsplit.plain"]();
      return;
    }
    await this.splitIntelligent("vsplit", "vsplit.plain");
  }
  async dropOr(fallback) {
    const ctx = this.ctx;
    const fullpath = await ctx.getFullpath();
    const bufManager = ctx.explorer.explorerManager.bufManager;
    const buf = bufManager.getBufferNode(fullpath);
    if (buf) {
      const winid = await winidByBufnr(buf.bufnr);
      if (winid) {
        await ctx.openByWinid(winid);
        return;
      }
    }
    await fallback();
  }
  async "drop.select"() {
    await this.dropOr(() => this.select());
  }
  async "drop.tab"() {
    await this.dropOr(() => this.tab());
  }
  async tab() {
    const ctx = this.ctx;
    const openNotifier = await ctx.openFilepathNotifier("tabedit");
    await ctx.openWrap(
      () => {
        openNotifier.notify();
      },
      { earlyQuit: true }
    );
  }
  async previousBuffer() {
    const ctx = this.ctx;
    const prevWinnr = await ctx.explorer.explorerManager.prevWinnrByPrevBufnr();
    if (prevWinnr) {
      await ctx.openByWinnr(prevWinnr);
    } else {
      await this.vsplit();
    }
  }
  async previousWindow() {
    const ctx = this.ctx;
    const prevWinnr = await ctx.explorer.explorerManager.prevWinnrByPrevWindowID();
    if (prevWinnr) {
      await ctx.openByWinnr(prevWinnr);
    } else {
      await this.vsplit();
    }
  }
  async sourceWindow() {
    const ctx = this.ctx;
    const srcWinnr = await ctx.explorer.sourceWinnr();
    if (srcWinnr) {
      await ctx.openByWinnr(srcWinnr);
    } else {
      await this.vsplit();
    }
  }
};
async function openAction(explorer, source, node, getFullpath, {
  openStrategy,
  cursorPosition
}) {
  if (node.expandable) {
    return;
  }
  let explorerWinid;
  let quitOnOpenNotifier;
  if (cursorPosition === "keep") {
    explorerWinid = await explorer.winid;
    quitOnOpenNotifier = () => Notifier.noop();
  } else {
    quitOnOpenNotifier = () => explorer.tryQuitOnOpenNotifier();
  }
  const context2 = new OpenActionContext(
    explorer,
    source,
    cursorPosition,
    getFullpath,
    quitOnOpenNotifier,
    explorerWinid
  );
  const actions = new OpenActions(context2);
  if (!openStrategy) {
    openStrategy = await explorer.args.value(argOptions.openActionStrategy);
  }
  if (!hasOwnProperty11(actions, openStrategy)) {
    new Error(`openStrategy(${openStrategy}) is not supported`);
  }
  await actions[openStrategy]();
}

// src/actions/globalActions.ts
function loadGlobalActions(action) {
  const explorer = action.owner;
  const locator = explorer.locator;
  const { nvim } = import_coc34.workspace;
  const openActionArgs = [
    {
      name: "open strategy",
      description: openStrategyList.join(" | ")
    },
    {
      name: "open with position",
      description: "line-number,column-number | keep"
    }
  ];
  const openActionMenu = {
    select: "use select window UI",
    "select:keep": "use select window UI, but keep cursor in explorer",
    "split.plain": "use vim split",
    "split.intelligent": "use split like vscode",
    "vsplit.plain": "use vim vsplit",
    "vsplit.intelligent": "use vim vsplit, but keep the explorer in the original position",
    tab: "vim tab",
    "drop.select": "use vim drop, fall back to select strategy",
    "drop.tab": "use vim drop, fall back to tab strategy",
    previousBuffer: "use last used buffer",
    previousWindow: "use last used window",
    sourceWindow: "use the window where explorer opened"
  };
  action.addNodeAction(
    "open",
    async ({ source, node, args, mode }) => {
      if (node.expandable) {
        const directoryActionExp = explorer.config.get(
          "openAction.for.directory"
        );
        if (directoryActionExp) {
          await explorer.action.doActionExp(
            parseOriginalActionExp(directoryActionExp),
            { mode, lineIndexes: [explorer.view.flattenedNodes.indexOf(node)] }
          );
        }
        return;
      }
      const [openStrategy, positionRaw] = args;
      let cursorPosition;
      if (positionRaw === "keep") {
        cursorPosition = positionRaw;
      } else if (positionRaw) {
        const [lineIndex = 0, column] = positionRaw.split(",").map((n) => parseInt(n, 10));
        cursorPosition = {
          lineIndex
        };
        if (column) {
          cursorPosition.columnIndex = column;
        }
      } else if (node.location) {
        const { range } = node.location;
        cursorPosition = { lineIndex: range.start.line - 1 };
      }
      await openAction(explorer, source, node, () => node.fullpath, {
        openStrategy,
        cursorPosition
      });
    },
    "open file or directory",
    {
      select: true,
      args: openActionArgs,
      menus: openActionMenu
    }
  );
  action.addNodeAction(
    "expand",
    async ({ source, node, args }) => {
      if (node.expandable) {
        const options = (args[0] ?? "").split("|");
        const recursive = options.includes("recursive") || void 0;
        const compact = options.includes("compact") || void 0;
        const uncompact = options.includes("uncompact") || void 0;
        const recursiveSingle = options.includes("recursiveSingle") || void 0;
        await source.view.expand(node, {
          recursive,
          compact,
          uncompact,
          recursiveSingle
        });
      }
    },
    "expand node",
    {
      select: true,
      args: [
        {
          name: "expand options",
          description: expandOptionList.join(" | ")
        }
      ],
      menus: {
        recursive: "recursively",
        compact: "single child folders will be compressed in a combined node",
        uncompact: "reset the combined node",
        "compact|uncompact": "compact or uncompact",
        recursiveSingle: "expand single child folder recursively"
      }
    }
  );
  action.addNodeAction(
    "collapse",
    async ({ source, node, args }) => {
      const options = (args[0] ?? "").split("|");
      const all = options.includes("all");
      const recursive = options.includes("recursive");
      if (all && source.view.rootNode.children) {
        for (const subNode of source.view.rootNode.children) {
          if (subNode.expandable && source.view.isExpanded(subNode)) {
            await source.action.doAction(
              "collapse",
              subNode,
              options.filter((op) => op !== "all")
            );
          }
        }
      } else {
        if (node.expandable && source.view.isExpanded(node)) {
          await source.view.collapse(node, { recursive });
        } else if (node.parent) {
          await source.view.collapse(node.parent, { recursive });
        }
      }
    },
    "collapse node",
    {
      select: true,
      args: [
        {
          name: "collapse options",
          description: collapseOptionList.join(" | ")
        }
      ],
      menus: {
        recursive: "recursively",
        all: "for all nodes"
      }
    }
  );
  action.addNodesAction(
    "gitStage",
    async ({ nodes, source }) => {
      const fullpaths = compactI(nodes.map((node) => node.fullpath));
      if (!fullpaths.length) {
        return;
      }
      await gitManager.cmd.stage(fullpaths);
      const roots = await gitManager.getGitRoots(fullpaths);
      for (const root2 of roots) {
        await gitManager.reload(root2);
      }
      source.view.requestRenderNodes([
        { nodes, withParents: true, withChildren: true }
      ]);
    },
    "add file to git index"
  );
  action.addNodesAction(
    "gitUnstage",
    async ({ nodes, source }) => {
      const fullpaths = compactI(nodes.map((node) => node.fullpath));
      if (!fullpaths.length) {
        return;
      }
      await gitManager.cmd.unstage(fullpaths);
      const roots = await gitManager.getGitRoots(fullpaths);
      for (const root2 of roots) {
        await gitManager.reload(root2);
      }
      source.view.requestRenderNodes([
        { nodes, withParents: true, withChildren: true }
      ]);
    },
    "reset file from git index"
  );
  const moveActionArgs = [
    {
      name: "move action options",
      description: moveStrategyList.join(" | ")
    }
  ];
  const moveActionMenu = {
    insideSource: "move inside current source"
  };
  action.addNodeAction(
    "nodePrev",
    async ({ args }) => {
      const moveStrategy = args[0];
      if (moveStrategy === "insideSource") {
        const source = await explorer.view.currentSource();
        if (!source) {
          return;
        }
        await source.locator.gotoLineIndex(source.view.currentLineIndex - 1);
      } else {
        const line = explorer.view.currentLineIndex;
        await locator.gotoLineIndex(line - 1);
      }
    },
    "previous node",
    {
      args: moveActionArgs,
      menus: moveActionMenu
    }
  );
  action.addNodeAction(
    "nodeNext",
    async ({ args }) => {
      const moveStrategy = args[0];
      if (moveStrategy === "insideSource") {
        const source = await explorer.view.currentSource();
        if (!source) {
          return;
        }
        await source.locator.gotoLineIndex(source.view.currentLineIndex + 1);
      } else {
        const line = explorer.view.currentLineIndex;
        await locator.gotoLineIndex(line + 1);
      }
    },
    "next node",
    {
      args: moveActionArgs,
      menus: moveActionMenu
    }
  );
  action.addNodeAction(
    "expandablePrev",
    async ({ args }) => {
      await explorer.action.nodePrev(
        args[0],
        (node) => !!node.expandable
      );
    },
    "previous expandable node",
    {
      args: moveActionArgs,
      menus: moveActionMenu
    }
  );
  action.addNodeAction(
    "expandableNext",
    async ({ args }) => {
      await action.nodeNext(
        args[0],
        (node) => !!node.expandable
      );
    },
    "next expandable node",
    {
      args: moveActionArgs,
      menus: moveActionMenu
    }
  );
  action.addNodeAction(
    "indentPrev",
    async ({ node, args }) => {
      const level = node.level ?? 0;
      await action.nodePrev(
        args[0],
        (node2) => node2.level !== level
      );
    },
    "previous indent node",
    {
      args: moveActionArgs,
      menus: moveActionMenu
    }
  );
  action.addNodeAction(
    "indentNext",
    async ({ node, args }) => {
      const level = node.level ?? 0;
      await action.nodeNext(
        args[0],
        (node2) => node2.level !== level
      );
    },
    "next indent node",
    {
      args: moveActionArgs,
      menus: moveActionMenu
    }
  );
  action.addNodeAction(
    "gotoSource",
    async ({ args }) => {
      const source = explorer.sources.find((s) => s.sourceType === args[0]);
      if (source) {
        await source.locator.gotoLineIndex(0);
      }
    },
    "go to source",
    {
      args: [
        {
          name: "source name",
          description: "buffer | file | ..."
        }
      ]
    }
  );
  action.addNodeAction(
    "sourceNext",
    async () => {
      var _a2;
      const nextSource = explorer.sources[await explorer.view.currentSourceIndex() + 1];
      if (nextSource) {
        await nextSource.locator.gotoLineIndex(0);
      } else if (await enableWrapscan()) {
        await ((_a2 = explorer.sources[0]) == null ? void 0 : _a2.locator.gotoLineIndex(0));
      }
    },
    "go to next source"
  );
  action.addNodeAction(
    "sourcePrev",
    async () => {
      var _a2;
      const prevSource = explorer.sources[await explorer.view.currentSourceIndex() - 1];
      if (prevSource) {
        await prevSource.locator.gotoLineIndex(0);
      } else if (await enableWrapscan()) {
        await ((_a2 = explorer.sources[explorer.sources.length - 1]) == null ? void 0 : _a2.locator.gotoLineIndex(0));
      }
    },
    "go to previous source"
  );
  action.addNodeAction(
    "modifiedPrev",
    async () => {
      await locator.gotoPrevMark("modified");
    },
    "go to previous modified"
  );
  action.addNodeAction(
    "modifiedNext",
    async () => {
      await locator.gotoNextMark("modified");
    },
    "go to next modified"
  );
  action.addNodeAction(
    "diagnosticPrev",
    async () => {
      await locator.gotoPrevMark("diagnosticError", "diagnosticWarning");
    },
    "go to previous diagnostic"
  );
  action.addNodeAction(
    "diagnosticNext",
    async () => {
      await locator.gotoNextMark("diagnosticError", "diagnosticWarning");
    },
    "go to next diagnostic"
  );
  action.addNodeAction(
    "gitPrev",
    async () => {
      await locator.gotoPrevMark("git");
    },
    "go to previous git changed"
  );
  action.addNodeAction(
    "gitNext",
    async () => {
      await locator.gotoNextMark("git");
    },
    "go to next git changed"
  );
  const markOptions = {
    args: [
      {
        name: "mark name",
        description: "string"
      }
    ],
    menus: {
      modified: "modified",
      diagnosticWarning: "diagnosticWarning",
      diagnosticError: "diagnosticError",
      git: "git"
    }
  };
  action.addNodeAction(
    "markPrev",
    async ({ args }) => {
      await locator.gotoPrevMark(...args);
    },
    "go to previous mark",
    markOptions
  );
  action.addNodeAction(
    "markNext",
    async ({ args }) => {
      await locator.gotoNextMark(...args);
    },
    "go to next mark",
    markOptions
  );
  action.addNodeAction(
    "preview",
    async ({ source, node, args }) => {
      const previewStrategy = args[0];
      if (!previewStrategy) {
        return;
      }
      const nodeIndex = source.view.getLineByNode(node);
      if (nodeIndex === void 0) {
        return;
      }
      await explorer.floatingPreview.previewNode(
        previewStrategy,
        source,
        node,
        nodeIndex
      );
    },
    "preview",
    {
      args: [
        {
          name: "preview strategy",
          description: previewStrategyList.join(" | ")
        }
      ],
      menus: {
        labeling: "preview for node labeling",
        content: "preview for node content"
      }
    }
  );
  action.addNodeAction(
    "previewOnHover",
    async ({ args }) => {
      const previewOnHoverAction = args[0];
      if (!previewOnHoverAction) {
        return;
      }
      const previewStrategy = args[1];
      if (!previewStrategy) {
        if (previewOnHoverAction === "disable") {
          explorer.floatingPreview.unregisterOnHover();
        }
        return;
      }
      const delay = args[2] ? parseInt(args[2]) : 0;
      if (previewOnHoverAction === "toggle") {
        explorer.floatingPreview.toggleOnHover(previewStrategy, delay);
      } else if (previewOnHoverAction === "enable") {
        explorer.floatingPreview.registerOnHover(previewStrategy, delay);
      } else {
        explorer.floatingPreview.unregisterOnHover();
      }
    },
    "preview on hover",
    {
      args: [
        {
          name: "sub action",
          description: previewOnHoverActionList.join(" | ")
        },
        {
          name: "preview strategy",
          description: previewStrategyList.join(" | ")
        },
        {
          name: "delay",
          description: "delay millisecond"
        }
      ],
      menus: {
        "toggle:labeling": "toggle labeling",
        "toggle:labeling:200": "toggle labeling with debounce",
        "toggle:content": "toggle content",
        "enable:content": "enable with content",
        "enable:labeling": "enable with labeling"
      }
    }
  );
  action.addNodeAction(
    "textobj",
    async ({ node: currentNode, args }) => {
      const currentIndex = explorer.view.currentLineIndex;
      const textobjTarget = args[0] ?? "line";
      switch (textobjTarget) {
        case "line":
          await nvim.command("normal! V");
          break;
        case "indent": {
          const flattenedNodes = explorer.view.flattenedNodes;
          const begin = scanIndexPrev(
            flattenedNodes,
            currentIndex,
            false,
            (node) => {
              return (currentNode.level ?? 0) > (node.level ?? 0);
            }
          );
          if (begin === void 0) {
            return;
          }
          const end = scanIndexNext(
            flattenedNodes,
            currentIndex,
            false,
            (node) => {
              return (currentNode.level ?? 0) > (node.level ?? 0);
            }
          );
          if (end === void 0) {
            return;
          }
          await nvim.command(`normal! ${begin + 2}GV${end}G`);
          break;
        }
      }
    },
    "use visual mode selects",
    {
      args: [
        {
          name: "target",
          description: textobjTargetList.join(" | ")
        },
        {
          name: "type",
          description: textobjTypeList.join(" | ")
        }
      ],
      menus: {
        "line:i": "line:i",
        "line:a": "line:a",
        "indent:i": "indent:i",
        "indent:a": "indent:a"
      }
    }
  );
  action.addNodeAction(
    "select",
    async ({ source, node }) => {
      source.selectedNodes.add(node);
      source.view.requestRenderNodes([node]);
    },
    "select node",
    { select: "visual" }
  );
  action.addNodeAction(
    "unselect",
    async ({ source, node }) => {
      source.selectedNodes.delete(node);
      source.view.requestRenderNodes([node]);
    },
    "unselect node",
    { select: "visual" }
  );
  action.addNodeAction(
    "toggleSelection",
    async ({ source, node }) => {
      if (source.selectedNodes.has(node)) {
        await source.action.doAction("unselect", node);
      } else {
        await source.action.doAction("select", node);
      }
    },
    "toggle node selection",
    {
      select: "visual"
    }
  );
  action.addNodeAction(
    "toggleHidden",
    async ({ source }) => {
      source.showHidden = !source.showHidden;
    },
    "toggle visibility of hidden node",
    {
      reload: true
    }
  );
  const parseSize = (sizeStr) => {
    const [widthStr, heightStr] = sizeStr.split(/,|x/).map((it) => it.trim());
    return [
      widthStr ? parseInt(widthStr) : void 0,
      heightStr ? parseInt(heightStr) : void 0
    ];
  };
  action.addNodeAction(
    "resize",
    async ({ args }) => {
      const [sizeStr] = args;
      if (!sizeStr)
        return;
      const [width, height] = parseSize(sizeStr);
      if (explorer.isFloating) {
        await explorer.resize([width, height]);
      } else {
        await explorer.resize([width]);
      }
      await explorer.render();
    },
    "resize",
    {
      args: [
        {
          name: "size",
          description: "{WIDTH}x{HEIGHT} | {WIDTH},{HEIGHT}"
        }
      ],
      menus: {
        path: {
          description: "resize the explorer window",
          args: "[size]",
          async actionArgs() {
            return [await input("input a the size:", "20,10", "file")];
          }
        }
      }
    }
  );
  action.addNodeAction(
    "adjustSize",
    async ({ args }) => {
      const [sizeStr] = args;
      if (!sizeStr)
        return;
      const [width, height] = parseSize(sizeStr);
      if (explorer.isFloating) {
        await explorer.adjustSize([width, height]);
      } else {
        await explorer.adjustSize([width]);
      }
      await explorer.render();
    },
    "adjust window size",
    {
      args: [
        {
          name: "size",
          description: "+-{WIDTH}x+-{HEIGHT} | +-{WIDTH},+-{HEIGHT}"
        }
      ],
      menus: {
        path: {
          description: "resize the explorer window",
          args: "[size]",
          async actionArgs() {
            return [await input("input a the size:", "+20,-10", "file")];
          }
        }
      }
    }
  );
  action.addNodeAction(
    "refresh",
    async ({ source }) => {
      source.selectedNodes.clear();
      await explorer.view.sync(async (r) => {
        const loadNotifier = await explorer.loadAllNotifier(r);
        nvim.pauseNotification();
        source.highlight.clearHighlightsNotify();
        loadNotifier.notify();
        await nvim.resumeNotification();
      });
    },
    "refresh"
  );
  action.addNodeAction(
    "render",
    async ({ source, node }) => {
      await source.view.render({ node });
    },
    "render"
  );
  action.addNodeAction(
    "help",
    async ({ source }) => {
      await source.explorer.showHelp(source);
    },
    "show help"
  );
  action.addNodesAction(
    "actionMenu",
    async ({ source, nodes }) => {
      await source.action.listActionMenu(nodes);
    },
    "show actions in coc-list",
    {
      select: "visual"
    }
  );
  action.addNodesAction(
    "quickfix",
    async ({ args, nodes, source }) => {
      const argAction = args[0] ?? "replace";
      const action2 = { add: "a", replace: "r" }[argAction];
      const list = await nvim.call("getqflist");
      const existFullpaths = list.map((it) => {
        var _a2;
        return (_a2 = source.bufManager.getBufferNode(it.bufnr)) == null ? void 0 : _a2.fullpath;
      }).filter(Boolean);
      await nvim.call("setqflist", [
        nodes.reduce(
          (acc, it) => {
            if (it.fullpath && !it.expandable && !existFullpaths.includes(it.fullpath)) {
              const relative = import_path13.default.relative(source.root, it.fullpath);
              acc.push({
                filename: it.fullpath,
                text: relative,
                lnum: 1
              });
            }
            return acc;
          },
          []
        ),
        action2
      ]);
      const openCommand = await nvim.getVar(
        "coc_quickfix_open_command"
      );
      await nvim.command(
        typeof openCommand === "string" ? openCommand : "copen"
      );
    },
    "push nodes to quickfix list",
    {
      select: true,
      args: [
        {
          name: "action",
          description: `action for quickfix, ${quickfixActions.join(" | ")}`
        }
      ],
      menus: {
        add: "add nodes to quickfix list",
        replace: "replace nodes in quickfix list"
      }
    }
  );
  action.addNodeAction(
    "normal",
    async ({ args }) => {
      if (args[0]) {
        await nvim.command(`execute "normal ${args[0]}"`);
      }
    },
    "execute vim normal mode commands",
    {
      args: [
        {
          name: "normal commands"
        }
      ],
      menus: {
        zz: "execute normal zz"
      }
    }
  );
  action.addNodeAction(
    "normal!",
    async ({ args }) => {
      if (args[0]) {
        await nvim.command(`execute "normal! ${args[0]}"`);
      }
    },
    "execute vim normal mode commands without using mappings",
    {
      args: [
        {
          name: "normal! commands"
        }
      ],
      menus: {
        zz: "execute normal! zz"
      }
    }
  );
  action.addNodeAction(
    "esc",
    async ({ source, mode }) => {
      if (source.explorer.isFloating && mode === "n") {
        await source.explorer.quit();
      } else {
        source.view.requestRenderNodes(Array.from(source.selectedNodes));
        source.selectedNodes.clear();
      }
    },
    "esc action"
  );
  action.addNodeAction(
    "quit",
    async () => {
      await explorer.quit();
    },
    "quit explorer"
  );
}

// src/floating/floatingPreview.ts
var import_coc36 = require("coc.nvim");
var import_isbinaryfile = __toESM(require_lib2());

// src/floating/floatingWindow.ts
var import_coc35 = require("coc.nvim");
var FloatingWindow2 = class _FloatingWindow {
  constructor(win) {
    this.win = win;
    this.bufnr = this.win.bufnr;
  }
  static async create(options = {}) {
    const win = await FloatingWindow.create({
      mode: "show",
      name: options.name
    });
    return new _FloatingWindow(win);
  }
  dispose() {
    this.win.dispose();
  }
  async open(lines, highlights, options) {
    if (this.closeTimer) {
      clearTimeout(this.closeTimer);
    }
    await this.win.open({
      top: options.top,
      left: options.left,
      width: options.width,
      height: options.height,
      winHl: "CocExplorerNormalFloat",
      winHlNC: "CocExplorerNormalFloat",
      borderWinHl: "CocExplorerNormalFloatBorder",
      lines,
      highlights,
      focus: false,
      initedExecute: ({ winid }) => {
        const scripts = [];
        if (import_coc35.workspace.isNvim) {
          scripts.push(`
            let store_winid = win_getid(winnr())
            if store_winid != ${winid}
              noau let successful = win_gotoid(${winid})
              if !successful
                return
              endif
            endif
          `);
          scripts.push("set filetype=");
          if (options.focusLineIndex) {
            scripts.push(`call nvim_win_set_cursor(${options.focusLineIndex})`);
          }
          if (!options.filetype && options.filepath) {
            scripts.push(
              `execute 'doautocmd filetypedetect BufRead ' . fnameescape('${options.filepath}')`
            );
          }
          if (options.filetype) {
            scripts.push(`set filetype=${options.filetype}`);
          }
          scripts.push(`
            if store_winid != ${winid}
              noau call win_gotoid(store_winid)
            endif
          `);
        } else {
          scripts.push(`call win_execute(${winid}, 'set filetype=')`);
          if (options.focusLineIndex) {
            scripts.push(
              `call win_execute(${winid}, 'call cursor(${options.focusLineIndex}, 1)')`
            );
          }
          if (!options.filetype && options.filepath) {
            scripts.push(
              `call win_execute(${winid}, 'doautocmd filetypedetect BufRead ' . fnameescape('${options.filepath}'))`
            );
          }
          if (options.filetype) {
            scripts.push(
              `call win_execute(${winid}, 'set filetype=${options.filetype}')`
            );
          }
        }
        return scripts.join("\n");
      }
    });
  }
  async closeDelay(ms) {
    if (this.closeTimer) {
      clearTimeout(this.closeTimer);
    }
    this.closeTimer = setTimeout(() => {
      this.win.close().catch(logger.error);
    }, ms);
  }
  async close() {
    await this.win.close();
  }
};

// src/floating/floatingPreview.ts
var FloatingPreview = class {
  constructor(explorer) {
    this.explorer = explorer;
    this.shown = false;
    this.disposables = [];
    this.preferTop = false;
    this.onHoverStrategy = false;
    this.nvim = import_coc36.workspace.nvim;
    this.onHoverDisposables = [];
    this.registeredPreviewActions = /* @__PURE__ */ new Map();
    this.maxHeight = explorer.config.get("previewAction.content.maxHeight");
    this.registerActions();
    this.disposables.push(
      explorer.events.on("first-open-post", () => {
        this.disposables.push(
          onEvent("BufWinLeave", async (bufnr) => {
            if (bufnr === this.explorer.bufnr) {
              await this.close();
            }
          }),
          onBufEnter(async (bufnr) => {
            var _a2;
            if (bufnr !== this.explorer.bufnr && bufnr !== ((_a2 = this.previewWindow) == null ? void 0 : _a2.bufnr)) {
              await this.closeDelay(200);
            }
          }, 0),
          onCursorMoved(async (bufnr) => {
            if (this.onHoverStrategy || bufnr !== this.explorer.bufnr) {
              return;
            }
            await this.closeDelay(200);
          }, 0),
          import_coc36.Disposable.create(() => {
            (0, import_coc36.disposeAll)(this.onHoverDisposables);
          })
        );
        const onHover = explorer.config.get("previewAction.onHover");
        if (!onHover) {
          return;
        }
        if (Array.isArray(onHover)) {
          this.registerOnHover(onHover[0], onHover[1]);
        } else {
          this.registerOnHover(onHover);
        }
      })
    );
  }
  dispose() {
    var _a2;
    (_a2 = this.previewWindow) == null ? void 0 : _a2.dispose();
  }
  async getPreviewWindow() {
    if (!this.previewWindow) {
      this.previewWindow = await FloatingWindow2.create();
    }
    return this.previewWindow;
  }
  async closeDelay(ms) {
    var _a2;
    await ((_a2 = this.previewWindow) == null ? void 0 : _a2.closeDelay(ms));
  }
  async close() {
    var _a2;
    await ((_a2 = this.previewWindow) == null ? void 0 : _a2.close());
  }
  toggleOnHover(onHoverStrategy, delay) {
    if (this.onHoverStrategy === onHoverStrategy) {
      this.unregisterOnHover();
    } else {
      this.registerOnHover(onHoverStrategy, delay);
    }
  }
  registerOnHover(onHoverStrategy, delay = 300) {
    if (this.onHoverStrategy === onHoverStrategy) {
      return;
    }
    this.onHoverStrategy = onHoverStrategy;
    (0, import_coc36.disposeAll)(this.onHoverDisposables);
    this.onHoverDisposables = [];
    const onHover = async (bufnr) => {
      if (this.explorer.view.isHelpUI) {
        await this.close();
        return;
      }
      if (bufnr !== this.explorer.bufnr) {
        return;
      }
      await this.explorer.view.refreshLineIndex();
      const source = await this.explorer.view.currentSource();
      if (!source) {
        return;
      }
      const node = source.view.currentNode();
      if (!node) {
        return;
      }
      const nodeIndex = source.view.getLineByNode(node);
      if (nodeIndex === void 0) {
        return;
      }
      await this.previewNode(onHoverStrategy, source, node, nodeIndex);
    };
    this.onHoverDisposables.push(
      onCursorMoved(onHover, delay),
      onBufEnter(onHover, delay)
    );
    currentBufnr().then(onHover).catch(logger.error);
    void import_coc36.window.showInformationMessage(`Preview ${onHoverStrategy} enabled`);
  }
  unregisterOnHover() {
    if (!this.onHoverStrategy) {
      return;
    }
    this.onHoverStrategy = false;
    (0, import_coc36.disposeAll)(this.onHoverDisposables);
    this.onHoverDisposables = [];
    this.close().catch(logger.error);
    void import_coc36.window.showInformationMessage("Preview disabled ");
  }
  registerAction(name, action) {
    this.registeredPreviewActions.set(name, action);
  }
  registerActions() {
    this.registerAction("labeling", async ({ source, node, nodeIndex }) => {
      const drawnList = await source.view.sourcePainters.drawNodeLabeling(node, nodeIndex);
      if (!await this.explorer.explorerManager.inExplorer()) {
        return;
      }
      return {
        lines: drawnList.map((d) => d.content),
        highlights: drawnList.map(
          (d, index) => d.highlightPositions.map((hl) => ({
            hlGroup: hl.group,
            line: index,
            colStart: hl.start,
            colEnd: hl.start + hl.size
          }))
        ).flat(),
        options: {
          filetype: "coc-explorer-labeling"
        }
      };
    });
    this.registerAction("content", async ({ node }) => {
      if (node.expandable) {
        return;
      }
      let location;
      if (node.location) {
        location = node.location;
      } else if (node.fullpath) {
        location = import_coc36.Location.create(node.fullpath, import_coc36.Range.create(0, 0, 0, 0));
      } else {
        return;
      }
      const { uri, range } = location;
      if (await (0, import_isbinaryfile.isBinaryFile)(uri)) {
        await import_coc36.window.showInformationMessage("Preview content skip binary");
        return;
      }
      const doc = import_coc36.workspace.getDocument(uri);
      const lines = doc ? doc.getLines(0, range.end.line + this.maxHeight) : await readFileLines(uri, 0, range.end.line + this.maxHeight);
      return {
        lines,
        highlights: [],
        options: {
          filepath: uri,
          focusLineIndex: range.start.line
        }
      };
    });
  }
  borderOptions() {
    return {
      border_enable: false,
      border_chars: [],
      title: ""
    };
  }
  getDimension(lines, maxWidth, maxHeight) {
    if (maxWidth === 0 || maxHeight === 0) {
      return { width: 0, height: 0 };
    }
    const lineLens = [];
    for (const line of lines) {
      lineLens.push(byteLength(line.replace(/\t/g, "  ")));
    }
    const width = min_default([max_default(lineLens), maxWidth]);
    if (width === void 0 || width === 0) {
      return { width: 0, height: 0 };
    }
    let height = 0;
    for (const lineLen of lineLens) {
      height = height + Math.max(Math.ceil(lineLen / width), 1);
    }
    return { width, height: Math.min(height, maxHeight) };
  }
  async getFloatOptions(lines) {
    const env = import_coc36.workspace.env;
    const vimColumns = env.columns;
    const vimLines = env.lines - env.cmdheight - 1;
    const position = this.explorer.argValues.position;
    const isFloating = position.name === "floating";
    const floatingPosition = await this.explorer.args.value(
      argOptions.floatingPosition
    );
    const win = await this.explorer.win;
    if (!win) {
      return;
    }
    let alignTop = false;
    const bufnr = await currentBufnr();
    let winline = bufnr === this.explorer.bufnr ? await this.nvim.call("winline") : 1;
    winline -= 1;
    const containerWin = isFloating && this.explorer.config.get("floating.border.enable") ? await this.explorer.borderWin : await this.explorer.win;
    if (!containerWin) {
      return;
    }
    let [winTop, winLeft] = await this.nvim.call(
      "win_screenpos",
      [containerWin.id]
    );
    winTop -= 1;
    winLeft -= 1;
    const containerWidth = await containerWin.width;
    const maxWidth = vimColumns - containerWidth - (isFloating ? 0 : 1) - 2;
    const maxHeight = min_default([this.maxHeight, vimLines]);
    const { width, height } = this.getDimension(lines, maxWidth, maxHeight);
    if (!this.preferTop) {
      if (vimLines - winline < height && winline > height) {
        alignTop = true;
      }
    } else {
      if (winline >= maxHeight || winline >= vimLines - winline) {
        alignTop = true;
      }
    }
    const top = winTop + (alignTop ? winline - height + 1 : winline);
    let left;
    if (position.name === "left") {
      left = winLeft + containerWidth + 2;
    } else if (position.name === "right") {
      left = winLeft - width - 2;
    } else if (isFloating && floatingPosition === "left-center") {
      left = winLeft + containerWidth + 1;
    } else if (isFloating && floatingPosition === "right-center") {
      left = winLeft - width - 1;
    } else {
      return;
    }
    return {
      top,
      left,
      width,
      height,
      ...this.borderOptions()
    };
  }
  async previewNode(previewStrategy, source, node, nodeIndex) {
    if (!supportedFloat()) {
      return;
    }
    const registeredActions = this.registeredPreviewActions.get(previewStrategy);
    if (!registeredActions) {
      await import_coc36.window.showInformationMessage(
        `coc-explorer no support preview strategy(${previewStrategy})`
      );
      return;
    }
    const openArgs = await registeredActions({
      source,
      node,
      nodeIndex
    });
    if (!openArgs) {
      await this.close();
      return;
    }
    const previewWindow = await this.getPreviewWindow();
    const floatOptions = await this.getFloatOptions(openArgs.lines);
    if (!floatOptions) {
      await this.close();
      return;
    }
    await previewWindow.open(openArgs.lines, openArgs.highlights ?? [], {
      ...floatOptions,
      ...openArgs.options
    });
  }
};

// src/help.ts
var import_coc39 = require("coc.nvim");

// src/highlight/manager.ts
var import_coc37 = require("coc.nvim");
var HighlightManager = class {
  constructor() {
    this.nvim = import_coc37.workspace.nvim;
    this.highlights = [];
  }
  /**
   * Link highlight group to another one
   */
  linkGroup(groupName, targetGroup) {
    const group = `CocExplorer${groupName}`;
    const commands4 = [`highlight default link ${group} ${targetGroup}`];
    const highlight = {
      group,
      commands: commands4
    };
    this.highlights.push(highlight);
    return highlight;
  }
  /**
   * Create a new highlight group
   */
  createGroup(groupName, hlCommand) {
    const group = `CocExplorer${groupName}`;
    const commands4 = [`highlight default ${group} ${hlCommand}`];
    const highlight = {
      group,
      commands: commands4
    };
    this.highlights.push(highlight);
    return highlight;
  }
  async watchColorScheme(disposables, update, immediate = true) {
    disposables.push(internalEvents.on("ColorScheme", update));
    if (immediate) {
      await update();
    }
  }
  clearHighlightsNotify(explorer, hlSrcId, lineStart, lineEnd) {
    explorer.buffer.clearNamespace(-1, lineStart, lineEnd);
  }
  addHighlightsNotify(explorer, hlSrcId, highlights) {
    for (const hl of highlights) {
      if (hl.size === 0) {
        continue;
      }
      explorer.buffer.highlightRanges(-1, hl.group, [
        import_coc37.Range.create(
          import_coc37.Position.create(hl.lineIndex, hl.start),
          import_coc37.Position.create(hl.lineIndex, hl.start + hl.size)
        )
      ]);
    }
  }
  bootHighlightSyntaxNotify() {
    const commands4 = [];
    for (const hl of this.highlights) {
      this.nvim.command(`silent! syntax clear ${hl.group}`, true);
      commands4.push(...hl.commands);
    }
    this.nvim.call("coc_explorer#util#execute_commands", [commands4], true);
  }
};
var hlGroupManager = new HighlightManager();

// src/painter/util.ts
function drawnWithIndexRange(drawnList) {
  if (!drawnList.length) {
    return [];
  }
  const sortedDrawnList = drawnList.sort((a, b) => a.nodeIndex - b.nodeIndex);
  const drawnRangeList = [];
  let drawnRangeCur;
  for (let i = 0, len = sortedDrawnList.length; i < len; i++) {
    const drawn = sortedDrawnList[i];
    if (!drawnRangeCur) {
      drawnRangeCur = {
        nodeIndexStart: drawn.nodeIndex,
        nodeIndexEnd: drawn.nodeIndex,
        drawnList: [drawn]
      };
    } else if (drawnRangeCur.nodeIndexEnd + 1 === drawn.nodeIndex) {
      drawnRangeCur.drawnList.push(drawn);
      drawnRangeCur.nodeIndexEnd = drawn.nodeIndex;
    } else {
      drawnRangeList.push(drawnRangeCur);
      i--;
      drawnRangeCur = void 0;
    }
  }
  if (drawnRangeCur) {
    drawnRangeList.push(drawnRangeCur);
  }
  return drawnRangeList;
}
var isEmptyDrawableList = (drawableList) => sum_default(
  drawableList.map(
    (p) => p.type === "content" ? p.content.length : p.type === "group" ? sum_default(
      p.contents.map(
        (c) => c.type === "content" ? c.content.length : 0
      )
    ) : 0
  )
) === 0;
async function fetchDisplayWidth(drawableList) {
  async function getDrawContentWith(drawable) {
    return {
      ...drawable,
      width: drawable.unicode && !isASCII(drawable.content) ? await displayWidth2(drawable.content) : drawable.content.length
    };
  }
  const list = await Promise.all(
    drawableList.map(async (it) => {
      if (it.type === "content") {
        return await getDrawContentWith(it);
      } else if (it.type === "group") {
        return {
          ...it,
          contents: await Promise.all(
            compactI2(
              it.contents.map(
                (c) => c.type === "content" ? getDrawContentWith(c) : void 0
              )
            )
          )
        };
      } else {
        return it;
      }
    })
  );
  return compactI2(list.flat());
}
function divideVolumeBy(totalWidth, volumes, widthLimits) {
  let unit = totalWidth / sum_default(volumes);
  const widths = new Array(volumes.length);
  if (widthLimits) {
    for (let i = 0; i < volumes.length; i++) {
      const volume = volumes[i];
      const widthLimit = widthLimits[i];
      if (!volume || !widthLimit)
        continue;
      const width = Math.ceil(volume * unit);
      if (width > widthLimit) {
        widths[i] = widthLimit;
        totalWidth -= widthLimit;
        volumes[i] = 0;
      }
    }
    unit = totalWidth / sum_default(volumes);
  }
  for (let i = 0; i < volumes.length; i++) {
    if (widths[i] === void 0) {
      const volume = volumes[i];
      if (!volume)
        continue;
      const width = Math.ceil(volume * unit);
      if (width <= totalWidth) {
        totalWidth -= width;
        widths[i] = width;
      } else {
        widths[i] = totalWidth;
      }
    }
  }
  return widths;
}
async function handlePadding(drawableList) {
  return drawableList.map((it) => {
    var _a2;
    if (it.type === "group" && ((_a2 = it.flexible) == null ? void 0 : _a2.padding) && it.flexible.paddingVolume) {
      const width = sum_default(
        it.contents.map((c) => c.type === "content" ? c.width : 0)
      );
      if (it.flexible.paddingVolume > width) {
        const width2 = it.flexible.paddingVolume;
        switch (it.flexible.padding) {
          case "left":
            return {
              ...it,
              contents: [
                {
                  type: "content",
                  content: " ".repeat(width2),
                  width: width2
                },
                ...it.contents
              ]
            };
          case "right":
            return {
              ...it,
              contents: [
                ...it.contents,
                {
                  type: "content",
                  content: " ".repeat(width2),
                  width: width2
                }
              ]
            };
          case "center": {
            const left = Math.ceil(width2 / 2);
            const right = width2 - left;
            return {
              ...it,
              contents: [
                {
                  type: "content",
                  content: " ".repeat(left),
                  width: left
                },
                ...it.contents,
                {
                  type: "content",
                  content: " ".repeat(right),
                  width: right
                }
              ]
            };
          }
          default:
            return it;
        }
      } else {
        return it;
      }
    } else {
      return it;
    }
  });
}
async function handleGrow(fullwidth, usedWidth, drawableList) {
  const allSpaceWidth = fullwidth - usedWidth;
  const spaceWidths = divideVolumeBy(
    allSpaceWidth,
    drawableList.map(
      (c) => {
        var _a2;
        return c.type === "group" && ((_a2 = c.flexible) == null ? void 0 : _a2.grow) ? c.flexible.growVolume ?? 1 : 0;
      }
    )
  );
  const list = await Promise.all(
    drawableList.map(
      async (item, idx) => {
        var _a2;
        if (item.type === "content") {
          return item;
        } else if (item.type === "group") {
          if (!((_a2 = item.flexible) == null ? void 0 : _a2.grow)) {
            return item.contents;
          }
          const spaceWidth = spaceWidths[idx];
          if (!spaceWidth)
            return;
          switch (item.flexible.grow) {
            case "left":
              return [
                {
                  type: "content",
                  content: " ".repeat(spaceWidth),
                  width: spaceWidth
                },
                ...item.contents
              ];
            case "right":
              return [
                ...item.contents,
                {
                  type: "content",
                  content: " ".repeat(spaceWidth),
                  width: spaceWidth
                }
              ];
            case "center": {
              const leftSpace = Math.floor(spaceWidth / 2);
              const rightSpace = spaceWidth - leftSpace;
              return [
                {
                  type: "content",
                  content: " ".repeat(leftSpace),
                  width: leftSpace
                },
                ...item.contents,
                {
                  type: "content",
                  content: " ".repeat(rightSpace),
                  width: rightSpace
                }
              ];
            }
            default:
              return item.contents;
          }
        }
      }
    )
  );
  return compactI2(list.flat());
}
var omitSymbolHighlight = hlGroupManager.linkGroup(
  "OmitSymbol",
  "SpecialComment"
);
async function handleOmit(fullwidth, usedWidth, drawableList) {
  const allOmitWidth = usedWidth - fullwidth;
  const omitWidths = divideVolumeBy(
    allOmitWidth,
    drawableList.map(
      (c) => {
        var _a2;
        return c.type === "group" && ((_a2 = c.flexible) == null ? void 0 : _a2.omit) ? c.flexible.omitVolume ?? 1 : 0;
      }
    ),
    drawableList.map((c) => {
      if (c.type === "content") {
        return c.width;
      } else if (c.type === "group") {
        return sum_default(
          c.contents.map((cc) => cc.type === "content" ? cc.width : 0)
        );
      } else {
        return 0;
      }
    })
  );
  const list = await Promise.all(
    drawableList.map(
      async (item, idx) => {
        var _a2;
        if (item.type === "content") {
          return item;
        } else if (item.type === "group") {
          if (!((_a2 = item.flexible) == null ? void 0 : _a2.omit)) {
            return item.contents;
          }
          const omitWidth = omitWidths[idx];
          if (!omitWidth)
            return;
          const contents = [];
          switch (item.flexible.omit) {
            case "left": {
              const cutWidth = omitWidth + 1;
              let remainCutWidth = cutWidth;
              for (const c of item.contents) {
                if (c.type !== "content") {
                  contents.push(c);
                  continue;
                }
                if (remainCutWidth < 0) {
                  contents.push(c);
                } else if (remainCutWidth < c.width) {
                  contents.push({
                    type: "content",
                    content: "\u2025",
                    width: 1,
                    group: omitSymbolHighlight.group
                  });
                  if (remainCutWidth > 0) {
                    contents.push({
                      ...c,
                      content: await displaySlice(c.content, remainCutWidth),
                      width: c.width - remainCutWidth
                    });
                  }
                }
                remainCutWidth -= c.width;
              }
              return contents;
            }
            case "right": {
              const cutWidth = omitWidth + 1;
              const contentWidth = sum_default(
                item.contents.map((c) => c.type === "content" ? c.width : 0)
              );
              let remainWidth = contentWidth - cutWidth;
              for (const c of item.contents) {
                if (c.type !== "content") {
                  contents.push(c);
                  continue;
                }
                if (remainWidth >= c.width) {
                  contents.push(c);
                } else if (remainWidth < c.width) {
                  if (remainWidth > 0) {
                    contents.push({
                      ...c,
                      content: await displaySlice(c.content, 0, remainWidth),
                      width: remainWidth
                    });
                  }
                  contents.push({
                    type: "content",
                    content: "\u2025",
                    width: 1,
                    group: omitSymbolHighlight.group
                  });
                  break;
                }
                remainWidth -= c.width;
              }
              return contents;
            }
            case "center": {
              const contentWidth = sum_default(
                item.contents.map((c) => c.type === "content" ? c.width : 0)
              );
              const cutWidth = omitWidth + 1;
              const remainWidth = contentWidth - cutWidth;
              const leftCutPos = Math.floor(remainWidth / 2);
              const rightCutPos = contentWidth - (remainWidth - leftCutPos);
              let itemStartPos = 0;
              let itemEndPos = 0;
              const contents2 = [];
              for (const c of item.contents) {
                if (c.type !== "content") {
                  contents2.push(c);
                  continue;
                }
                itemEndPos += c.width;
                if (itemStartPos < leftCutPos) {
                  if (itemEndPos <= leftCutPos) {
                    contents2.push(c);
                  } else if (itemEndPos <= rightCutPos) {
                    const width = leftCutPos - itemStartPos;
                    contents2.push({
                      ...c,
                      content: await displaySlice(c.content, 0, width),
                      width
                    });
                    contents2.push({
                      type: "content",
                      content: "\u2025",
                      width: 1,
                      group: omitSymbolHighlight.group
                    });
                  } else {
                    const leftWidth = leftCutPos - itemStartPos;
                    contents2.push({
                      ...c,
                      content: await displaySlice(c.content, 0, leftWidth),
                      width: leftWidth
                    });
                    contents2.push({
                      type: "content",
                      content: "\u2025",
                      width: 1,
                      group: omitSymbolHighlight.group
                    });
                    const rightWidth = itemEndPos - rightCutPos;
                    contents2.push({
                      ...c,
                      content: await displaySlice(
                        c.content,
                        c.width - rightWidth
                      ),
                      width: rightWidth
                    });
                  }
                } else if (itemEndPos > rightCutPos) {
                  if (itemStartPos >= rightCutPos) {
                    contents2.push(c);
                  } else {
                    const width = itemEndPos - rightCutPos;
                    contents2.push({
                      ...c,
                      content: await displaySlice(c.content, c.width - width),
                      width
                    });
                  }
                }
                itemStartPos = itemEndPos;
              }
              return contents2;
            }
          }
        }
      }
    )
  );
  return compactI2(list.flat());
}

// src/source/viewPainter.ts
var ViewPainter = class {
  constructor(explorer) {
    this.explorer = explorer;
  }
  get width() {
    return this.explorer.contentWidth;
  }
  async drawRow(draw) {
    const row = new ViewRowPainter(this);
    await draw(row);
    return row;
  }
};
var ViewRowPainter = class {
  constructor(view) {
    this.view = view;
    this.drawableList = [];
  }
  /**
   * Draw the `ViewRowPainter` to `Drawn`
   */
  async draw({ flexible = true } = {}) {
    const drawableList = await handlePadding(
      await fetchDisplayWidth(this.drawableList)
    );
    let drawContents = [];
    const fullwidth = this.view.width;
    const usedWidth = sum_default(
      drawableList.map((c) => {
        switch (c.type) {
          case "content":
            return c.width;
          case "group":
            return sum_default(
              c.contents.map((cc) => cc.type === "content" ? cc.width : 0)
            );
          default:
            return 0;
        }
      })
    );
    if (!flexible || usedWidth === fullwidth) {
      drawContents = compactI2(
        drawableList.map(
          (item) => {
            switch (item.type) {
              case "group":
                return item.contents;
              case "content":
                return item;
            }
          }
        ).flat()
      );
    } else if (usedWidth < fullwidth) {
      drawContents = await handleGrow(fullwidth, usedWidth, drawableList);
    } else if (usedWidth > fullwidth) {
      drawContents = await handleOmit(fullwidth, usedWidth, drawableList);
    }
    const highlightPositions = [];
    let content = "";
    let col = 0;
    for (const drawContent of drawContents) {
      if (drawContent.type !== "content")
        continue;
      const size = drawContent.content.length;
      if (drawContent.group) {
        highlightPositions.push({
          group: drawContent.group,
          start: col,
          size
        });
      }
      content += drawContent.content;
      col += size;
    }
    return {
      content,
      highlightPositions
    };
  }
  /**
   * Add a string to `ViewRowPainter`
   */
  add(content, {
    hl,
    width,
    drawGroup,
    unicode = false
  } = {}) {
    const group = hl ? typeof hl === "string" ? hl : hl.group : void 0;
    const drawContent = {
      type: "content",
      content,
      unicode,
      group,
      width
    };
    if (drawGroup) {
      drawGroup.contents.push(drawContent);
    } else {
      this.drawableList.push(drawContent);
    }
  }
  /**
   * Get `Drawable` list from a `DrawBlock`
   */
  async drawBlockToList(drawBlock) {
    const storeList = this.drawableList;
    this.drawableList = [];
    await drawBlock(this);
    const drawableList = this.drawableList;
    this.drawableList = storeList;
    return drawableList;
  }
  async flexible(flexible, drawBlock) {
    const list = await this.drawBlockToList(drawBlock);
    this.drawableList.push(this.flexibleForList(flexible, list));
  }
  /**
   * Apply the flexible to the `Drawable` list
   */
  flexibleForList(flexible, drawableList) {
    return {
      type: "group",
      contents: drawableList.map((c) => {
        switch (c.type) {
          case "content":
            return c;
          case "group":
            return c.contents;
          default:
            return c;
        }
      }).flat(),
      flexible
    };
  }
  /**
   * Add a `Column` to `ViewRowPainter`
   */
  async addColumn(node, nodeIndex, column, isLabeling = false) {
    this.drawableList.push(
      ...await this.columnToList(node, nodeIndex, column, isLabeling)
    );
  }
  /**
   * Get `Drawable` list from a `Column` and node
   */
  async columnToList(node, nodeIndex, column, isLabeling = false) {
    return await this.drawBlockToList(async () => {
      var _a2;
      if (typeof column === "number") {
        this.add(" ".repeat(column));
        return;
      }
      await ((_a2 = column.drawHandle) == null ? void 0 : _a2.drawNode(this, {
        node,
        nodeIndex,
        isLabeling
      }));
    });
  }
  /**
   * Add a `TemplatePart` to `ViewRowPainter`
   */
  async addTemplatePart(node, nodeIndex, part, isLabeling = false) {
    if (typeof part === "string") {
      this.add(part);
      return;
    }
    const drawableList = [];
    const column = part.column;
    drawableList.push(
      ...await this.columnToList(node, nodeIndex, column, isLabeling)
    );
    const flexible = {};
    const getVolume = (c) => typeof c === "number" ? c : 1;
    if (part.modifiers) {
      for (const modifier of part.modifiers) {
        if (modifier.name === "|") {
          if (isEmptyDrawableList(drawableList)) {
            drawableList.push(
              ...await this.columnToList(
                node,
                nodeIndex,
                modifier.column,
                isLabeling
              )
            );
          }
        } else if (modifier.name === "&") {
          if (!isEmptyDrawableList(drawableList)) {
            drawableList.push(
              ...await this.columnToList(
                node,
                nodeIndex,
                modifier.column,
                isLabeling
              )
            );
          }
        } else if (modifier.name === "growLeft") {
          flexible.grow = "left";
          flexible.growVolume = getVolume(modifier.column);
        } else if (modifier.name === "growCenter") {
          flexible.grow = "center";
          flexible.growVolume = getVolume(modifier.column);
        } else if (modifier.name === "growRight") {
          flexible.grow = "right";
          flexible.growVolume = getVolume(modifier.column);
        } else if (modifier.name === "omitLeft") {
          flexible.omit = "left";
          flexible.omitVolume = getVolume(modifier.column);
        } else if (modifier.name === "omitCenter") {
          flexible.omit = "center";
          flexible.omitVolume = getVolume(modifier.column);
        } else if (modifier.name === "omitRight") {
          flexible.omit = "right";
          flexible.omitVolume = getVolume(modifier.column);
        }
      }
    }
    if (flexible.omit || flexible.grow) {
      this.drawableList.push(this.flexibleForList(flexible, drawableList));
    } else {
      this.drawableList.push(...drawableList);
    }
  }
};

// src/mappings/manager.ts
var import_coc38 = require("coc.nvim");
var mappings = {};
async function registerMappings(context2, explorerManager) {
  const commonKeys = [...await keyMapping.getCommonKeys()];
  const keysModes = [
    ["n", commonKeys],
    ["v", [...commonKeys, ...await keyMapping.getVisualKeys()]]
  ];
  for (const [mode, keys2] of keysModes) {
    const mappingsMode = {};
    mappings[mode] = mappingsMode;
    for (const key of keys2) {
      if (mappingsMode[key]) {
        continue;
      }
      if (mode === "v" && ["o", "j", "k"].includes(key)) {
        continue;
      }
      const plugKey = `explorer-key-${mode}-${key.replace(/<(.*)>/, "[$1]")}`;
      context2.subscriptions.push(
        import_coc38.workspace.registerKeymap([mode], plugKey, async () => {
          const count = await import_coc38.workspace.nvim.eval("v:count");
          const explorer = await explorerManager.currentExplorer();
          explorer == null ? void 0 : explorer.action.doActionByKey(key, mode, count || 1).catch(logger.error);
        })
      );
      mappingsMode[key] = `<Plug>(coc-${plugKey})`;
    }
  }
  await import_coc38.workspace.nvim.call("coc_explorer#mappings#register", [mappings]);
}
async function executeMappings() {
  await import_coc38.workspace.nvim.call("coc_explorer#mappings#execute", [mappings]);
}
async function clearMappings() {
  await import_coc38.workspace.nvim.call("coc_explorer#mappings#clear", [mappings]);
}

// src/help.ts
var hlg = hlGroupManager.linkGroup.bind(hlGroupManager);
var helpHightlights = {
  line: hlg("HelpLine", "Operator"),
  hint: hlg("HelpHint", "Comment"),
  title: hlg("HelpTitle", "Boolean"),
  subtitle: hlg("HelpSubTitle", "Label"),
  mappingKey: hlg("HelpMappingKey", "PreProc"),
  action: hlg("HelpAction", "Identifier"),
  column: hlg("HelpColumn", "Identifier"),
  arg: hlg("HelpArg", "Identifier"),
  description: hlg("HelpDescription", "Comment"),
  type: hlg("HelperType", "Type"),
  conditional: hlg("HelpConditional", "Conditional")
};
var helpHlSrcId = "coc-explorer-help";
var HelpPainter = class {
  constructor(explorer, source, width) {
    this.explorer = explorer;
    this.source = source;
    this.width = width;
    this.drawnResults = [];
    this.painter = new ViewPainter(explorer);
    this.registeredActions = this.source.action.registeredActions();
  }
  async drawRow(drawBlock) {
    const row = await this.painter.drawRow(drawBlock);
    this.drawnResults.push(await row.draw());
  }
  async drawHr() {
    await this.drawRow((row) => {
      row.add("\u2014".repeat(this.width), { hl: helpHightlights.line });
    });
  }
  async drawHead() {
    await this.drawRow((row) => {
      row.add("Help ");
      row.add("(use q, ? or <esc> return to explorer)", {
        hl: helpHightlights.hint
      });
    });
    await this.drawHr();
  }
  drawActionForMapping(row, action) {
    row.add(action.name, { hl: helpHightlights.action });
    if (action.args.length) {
      row.add(`(${action.args.join(",")})`, { hl: helpHightlights.arg });
    }
    row.add(" ");
    const registeredAction = this.registeredActions.get(action.name);
    if (registeredAction) {
      row.add(registeredAction.description, {
        hl: helpHightlights.description
      });
    }
  }
  anyAction(actionExp, callback) {
    if (Array.isArray(actionExp)) {
      return actionExp.some((action) => this.anyAction(action, callback));
    } else {
      return callback(actionExp);
    }
  }
  drawMappingsPrefix(indent, row, ctx) {
    if (!ctx.isFirstLine) {
      row.add(indent);
      return;
    }
    ctx.isFirstLine = false;
    if (ctx.key) {
      row.add(" ");
      row.add(ctx.key, { hl: helpHightlights.mappingKey });
      row.add(" - ");
    }
    if (ctx.isWait) {
      row.add(`${waitAction.helpDescription} `, { hl: helpHightlights.type });
    }
  }
  async drawMappingsAction(indent, action, ctx) {
    await this.drawRow((row) => {
      this.drawMappingsPrefix(indent, row, ctx);
      if (action.name === noopAction.name) {
        row.add(noopAction.helpDescription, { hl: helpHightlights.type });
        return;
      }
      row.add(action.name, { hl: helpHightlights.action });
      if (action.args.length) {
        row.add(`(${action.args.join(",")})`, { hl: helpHightlights.arg });
      }
      row.add(" ");
      const registeredAction = this.registeredActions.get(action.name);
      if (registeredAction) {
        row.add(registeredAction.description, {
          hl: helpHightlights.description
        });
      }
    });
  }
  async drawMappingsActionExp(indent, actionExp, ctx) {
    if (Array.isArray(actionExp)) {
      for (let i = 0; i < actionExp.length; i++) {
        const action = actionExp[i];
        if (!action)
          continue;
        if (Array.isArray(action)) {
          await this.drawMappingsActionExp(indent, action, ctx);
          continue;
        }
        if (action.name === waitAction.name) {
          if (ctx.isFirstLine) {
            ctx.isWait = true;
          }
          continue;
        }
        const rule = conditionActionRules[action.name];
        if (rule) {
          await this.drawRow((row) => {
            this.drawMappingsPrefix(indent, row, ctx);
            row.add(`if ${rule.getHelpDescription(action.args)}`, {
              hl: helpHightlights.conditional
            });
          });
          const [trueAction, falseAction] = [
            actionExp[i + 1],
            actionExp[i + 2]
          ];
          if (!trueAction || !falseAction)
            continue;
          await this.drawMappingsActionExp(`${indent}  `, trueAction, ctx);
          await this.drawRow((row) => {
            row.add(indent);
            row.add("else", {
              hl: helpHightlights.conditional
            });
          });
          await this.drawMappingsActionExp(`${indent}  `, falseAction, ctx);
          i += 2;
          continue;
        }
        await this.drawMappingsAction(indent, action, ctx);
      }
    } else {
      await this.drawMappingsAction(indent, actionExp, ctx);
    }
  }
  /**
   * <cr> - <wait> if expandable?
   *          if expanded?
   *            expand() expand a directory
   *          else
   *            collapse() collapse a directory
   *        else
   *          open() open file or directory
   */
  async drawMappings() {
    await this.drawRow((row) => {
      row.add(`Mappings for source(${this.source.sourceType})`, {
        hl: helpHightlights.title
      });
    });
    const drawMappings = async (mappings3) => {
      for (const [key, actionExp] of Object.entries(mappings3)) {
        if (!this.anyAction(
          actionExp,
          (action) => this.registeredActions.has(action.name) || action.name === noopAction.name
        )) {
          continue;
        }
        await this.drawMappingsActionExp(
          " ".repeat(key.length + 4),
          actionExp,
          {
            key,
            isFirstLine: true,
            isWait: false
          }
        );
      }
    };
    const mappings2 = await keyMapping.getMappings(this.source.sourceType);
    await drawMappings(mappings2.nmap);
    await drawMappings(mappings2.vmap);
  }
  async drawActions() {
    await this.drawRow((row) => {
      row.add(`Actions for source(${this.source.sourceType})`, {
        hl: helpHightlights.title
      });
    });
    for (const [name, action] of this.registeredActions) {
      await this.drawRow((row) => {
        row.add(" ");
        row.add(name, { hl: helpHightlights.action });
        row.add(" ");
        row.add(action.description, { hl: helpHightlights.description });
      });
      if (action.options.args) {
        await this.drawRow((row) => {
          row.add("   ");
          row.add("args:", { hl: helpHightlights.subtitle });
        });
        for (const arg of action.options.args) {
          await this.drawRow((row) => {
            row.add("     - ");
            row.add(arg.name, { hl: helpHightlights.arg });
            if (arg.description) {
              row.add(" ");
              row.add(arg.description, { hl: helpHightlights.description });
            }
          });
        }
      }
      if (action.options.menus) {
        await this.drawRow((row) => {
          row.add("   ");
          row.add("menus:", { hl: helpHightlights.subtitle });
        });
        for (const menu of ActionMenu.getNormalizeMenus(action.options.menus)) {
          await this.drawRow((row) => {
            row.add("     - ");
            row.add(`${name}:${menu.args}`, { hl: helpHightlights.action });
            row.add(" ");
            row.add(menu.description, { hl: helpHightlights.description });
          });
        }
      }
    }
  }
  async drawColumns() {
    await this.drawRow((row) => {
      row.add(`Columns for source(${this.source.sourceType})`, {
        hl: helpHightlights.title
      });
    });
    const allColumns = this.source.view.sourcePainters.columnRegistrar.registeredColumns;
    for (const [type, columns] of allColumns) {
      await this.drawRow((row) => {
        row.add(`  Type: ${type}`, { hl: helpHightlights.subtitle });
      });
      for (const [name] of columns) {
        await this.drawRow((row) => {
          row.add("   - ");
          row.add(name, { hl: helpHightlights.column });
        });
      }
    }
  }
  async render() {
    import_coc39.workspace.nvim.pauseNotification();
    this.explorer.setLinesNotifier(
      this.drawnResults.map((n) => n.content),
      0,
      -1
    ).notify();
    const highlightPositions = [];
    for (const [i, drawn] of this.drawnResults.entries()) {
      highlightPositions.push(
        ...drawn.highlightPositions.map((hl) => ({
          lineIndex: i,
          ...hl
        }))
      );
    }
    this.explorer.highlight.addHighlightsNotify(
      helpHlSrcId,
      highlightPositions
    );
    await import_coc39.workspace.nvim.resumeNotification();
  }
};
async function showHelp(explorer, source) {
  var _a2;
  explorer.view.isHelpUI = true;
  const storeNode = await explorer.view.currentNode();
  const width = await ((_a2 = await explorer.win) == null ? void 0 : _a2.width) ?? 80;
  const helpPainter = new HelpPainter(explorer, source, width);
  await helpPainter.drawHead();
  await helpPainter.drawMappings();
  await helpPainter.drawHr();
  await helpPainter.drawActions();
  await helpPainter.drawHr();
  await helpPainter.drawColumns();
  await helpPainter.render();
  await clearMappings();
  const disposables = [];
  ["<esc>", "q", "?"].forEach((key) => {
    disposables.push(
      import_coc39.workspace.registerLocalKeymap(
        "n",
        key,
        async () => {
          (0, import_coc39.disposeAll)(disposables);
          await quitHelp(explorer);
          await explorer.view.sync(async (r) => {
            await Notifier.runAll([
              await r.renderAllNotifier(),
              await source.locator.gotoNodeNotifier(storeNode)
            ]);
          });
        },
        true
      )
    );
  });
}
async function quitHelp(explorer) {
  await executeMappings();
  explorer.view.isHelpUI = false;
}

// src/highlight/highlightExplorer.ts
var import_coc40 = require("coc.nvim");
var HighlightExplorer = class {
  constructor(explorer) {
    this.explorer = explorer;
  }
  clearHighlightsNotify(hlSrcId, lineStart, lineEnd) {
    hlGroupManager.clearHighlightsNotify(
      this.explorer,
      hlSrcId,
      lineStart,
      lineEnd
    );
  }
  addHighlightsNotify(hlSrcId, highlights) {
    hlGroupManager.addHighlightsNotify(this.explorer, hlSrcId, highlights);
  }
  async bootSyntax() {
    const winnr = await this.explorer.winnr;
    const curWinnr = await import_coc40.workspace.nvim.call("winnr");
    if (winnr) {
      import_coc40.workspace.nvim.pauseNotification();
      if (winnr !== curWinnr) {
        import_coc40.workspace.nvim.command(`${winnr}wincmd w`, true);
      }
      hlGroupManager.bootHighlightSyntaxNotify();
      if (winnr !== curWinnr) {
        import_coc40.workspace.nvim.command(`${curWinnr}wincmd w`, true);
      }
      await import_coc40.workspace.nvim.resumeNotification();
    }
  }
};

// src/locator/locatorExplorer.ts
var import_coc41 = require("coc.nvim");

// src/locator/markExplorer.ts
var MarkExplorer = class {
  constructor(explorer) {
    this.explorer = explorer;
    this.marksGroupByType = /* @__PURE__ */ new Map();
  }
  add(type, lineIndex) {
    if (!this.marksGroupByType.has(type)) {
      this.marksGroupByType.set(type, /* @__PURE__ */ new Set());
    }
    const lines = this.marksGroupByType.get(type);
    lines.add(lineIndex);
  }
  remove(type, lineIndex) {
    if (!this.marksGroupByType.has(type)) {
      this.marksGroupByType.set(type, /* @__PURE__ */ new Set());
    }
    const lines = this.marksGroupByType.get(type);
    lines.delete(lineIndex);
  }
  removeAll() {
    this.marksGroupByType.clear();
  }
  removeLines(startLineOrLines, endLine = Infinity) {
    if (Array.isArray(startLineOrLines)) {
      this.marksGroupByType.forEach((lines) => {
        startLineOrLines.forEach((line) => {
          lines.delete(line);
        });
      });
    } else {
      const startLine = startLineOrLines;
      this.marksGroupByType.forEach((lines) => {
        lines.forEach((line) => {
          if (startLine <= line && line <= endLine) {
            lines.delete(line);
          }
        });
      });
    }
  }
  offsetLines(offset, startLine, endLine = Infinity) {
    if (offset === 0) {
      return;
    }
    this.marksGroupByType.forEach((lines, name) => {
      const newLines = /* @__PURE__ */ new Set();
      lines.forEach((line) => {
        newLines.add(
          startLine <= line && line <= endLine ? line + offset : line
        );
      });
      this.marksGroupByType.set(name, newLines);
    });
  }
  async prevLineIndex(...names) {
    let mergeLines = [];
    for (const name of names) {
      const lines = this.marksGroupByType.get(name);
      mergeLines = mergeLines.concat(lines ? Array.from(lines) : []);
    }
    if (mergeLines.length) {
      const curLine = this.explorer.view.currentLineIndex;
      const sortedLines = mergeLines.sort((a, b) => b - a);
      const prevLine = sortedLines.find((line) => line < curLine);
      if (prevLine) {
        return prevLine;
      } else if (await enableWrapscan()) {
        return sortedLines[0];
      }
    }
  }
  async nextLineIndex(...names) {
    let mergeLines = [];
    for (const name of names) {
      const lines = this.marksGroupByType.get(name);
      mergeLines = mergeLines.concat(lines ? Array.from(lines) : []);
    }
    if (mergeLines.length) {
      const curLine = this.explorer.view.currentLineIndex;
      const sortedLines = mergeLines.sort((a, b) => a - b);
      const nextLine = sortedLines.find((line) => line > curLine);
      if (nextLine) {
        return nextLine;
      } else if (await enableWrapscan()) {
        return sortedLines[0];
      }
    }
  }
};

// src/locator/locatorExplorer.ts
var LocatorExplorer = class {
  constructor(explorer) {
    this.explorer = explorer;
    this.mark = new MarkExplorer(this.explorer);
    this.view = this.explorer.view;
  }
  async gotoPrevMark(...names) {
    const lineIndex = await this.mark.prevLineIndex(...names);
    if (lineIndex) {
      await this.gotoLineIndex(lineIndex);
      return true;
    }
    return false;
  }
  async gotoNextMark(...names) {
    const lineIndex = await this.mark.nextLineIndex(...names);
    if (lineIndex) {
      await this.gotoLineIndex(lineIndex);
      return true;
    }
    return false;
  }
  async gotoLineIndex(lineIndex) {
    return (await this.gotoLineIndexNotifier(lineIndex)).run();
  }
  async gotoLineIndexNotifier(lineIndex, col) {
    const win = await this.explorer.win;
    return Notifier.create(() => {
      if (win) {
        const height = this.explorer.height;
        if (lineIndex < 0) {
          lineIndex = 0;
        } else if (lineIndex >= height) {
          lineIndex = height - 1;
        }
        this.view.currentLineIndex = lineIndex;
        win.setCursor([lineIndex + 1, col ?? 0], true);
        if (import_coc41.workspace.isVim) {
          import_coc41.workspace.nvim.command("redraw", true);
        } else {
          import_coc41.workspace.nvim.command("redraw!", true);
        }
      }
    });
  }
};

// src/highlight/internalColors.ts
var import_coc43 = require("coc.nvim");

// src/highlight/extractColors.ts
var import_coc42 = require("coc.nvim");
async function extractHighlightsColor(highlightGroups) {
  const hlColorStrs = await import_coc42.workspace.nvim.call("coc_explorer#highlight#extract_colors", [
    highlightGroups
  ]);
  return Object.entries(hlColorStrs).map(([group, hl]) => {
    const newHl = {};
    if (hl.ctermfg) {
      newHl.ctermfg = hl.ctermfg;
    }
    if (hl.ctermbg) {
      newHl.ctermbg = hl.ctermbg;
    }
    if (hl.guifg) {
      newHl.guifg = parseColor(hl.guifg);
    }
    if (hl.guibg) {
      newHl.guibg = parseColor(hl.guibg);
    }
    return [group, newHl];
  }).reduce((ret, [group, hl]) => {
    ret[group] = hl;
    return ret;
  }, {});
}

// src/highlight/internalColors.ts
var groupConfigs = {
  Error: "ErrorColor",
  Comment: "CommentColor",
  Normal: "NormalColor",
  CocErrorSign: "CocErrorSignColor",
  CocWarningSign: "CocWarningSignColor"
};
var registerInternalColors = (disposables) => {
  hlGroupManager.watchColorScheme(disposables, async () => {
    const groups = Object.keys(groupConfigs);
    const highlights = await extractHighlightsColor(groups);
    const { nvim } = import_coc43.workspace;
    nvim.pauseNotification();
    for (const group of groups) {
      const hl = highlights[group];
      const cmd = generateHighlightFg(
        `CocExplorer${groupConfigs[group]}_Internal`,
        hl
      );
      if (!cmd) {
        continue;
      }
      nvim.command(cmd, true);
    }
    await nvim.resumeNotification();
  }).catch(logger.error);
};
var internalHighlightGroups = {};
Object.values(groupConfigs).forEach((group) => {
  internalHighlightGroups[group] = `CocExplorer${group}_Internal`;
});

// src/view/viewSource.ts
var import_coc46 = require("coc.nvim");

// src/source/sourcePainters.ts
var import_p_filter = __toESM(require_p_filter());

// src/parser/parser.ts
var ParserSource = class {
  constructor(s, i) {
    this.s = s;
    this.i = i;
  }
  ch() {
    return this.s[this.i];
  }
  skip(n) {
    this.i += n;
  }
  next() {
    this.i += 1;
  }
  forwardString(length) {
    return this.s.slice(this.i, this.i + length);
  }
  match(str, options = {}) {
    if (this.forwardString(str.length) === str) {
      if (options.skip ?? false) {
        this.skip(str.length);
      }
      return true;
    }
    return false;
  }
  end() {
    return this.i >= this.s.length;
  }
};
var ParserError = class extends Error {
  constructor(source, message2) {
    super(message2);
    this.source = source;
  }
};

// src/source/parseTemplate.ts
function parseKeyword(name, s, endWith) {
  let keyword = "";
  while (!s.end()) {
    const ch = s.ch();
    if (!ch)
      break;
    if (!endWith.includes(ch)) {
      keyword += ch;
      s.next();
    } else {
      return keyword;
    }
  }
  throw new ParserError(s, `Unexpected end when parse ${name}`);
}
function parseModifierName(s) {
  return parseKeyword("modifier name", s, [" "]);
}
function parseModifierColumn(s) {
  return parseKeyword("modifier value", s, [" ", "]"]);
}
function parseModifier(s) {
  const name = parseModifierName(s);
  s.next();
  const column = parseModifierColumn(s);
  return { name, column };
}
function parseModifiers(s) {
  const modifiers = [];
  do {
    const ch = s.ch();
    if (ch === " ") {
      s.next();
      modifiers.push(parseModifier(s));
    } else if (ch === "]") {
      return modifiers;
    }
  } while (true);
}
function parseColumnName(s) {
  return parseKeyword("column name", s, [" ", "]"]);
}
function parseColumn(s) {
  s.next();
  const parsedColumn = {
    column: parseColumnName(s)
  };
  do {
    const ch = s.ch();
    if (ch === "]") {
      s.next();
      return parsedColumn;
    } else if (ch === " ") {
      parsedColumn.modifiers = parseModifiers(s);
    }
  } while (!s.end());
  throw new ParserError(s, "Unexpected end when parse column block");
}
function parsePlainString(s) {
  let str = "";
  while (!s.end()) {
    const ch = s.ch();
    if (ch === "\\") {
      s.next();
      str += s.ch();
    } else if (ch === "[") {
      return str;
    } else {
      str += ch;
    }
    s.next();
  }
  return str;
}
function parseTemplate(str) {
  const s = new ParserSource(str, 0);
  const parts = [];
  while (!s.end()) {
    const ch = s.ch();
    if (ch === "[") {
      parts.push(parseColumn(s));
    } else {
      parts.push(parsePlainString(s));
    }
  }
  return parts;
}

// src/source/sourcePainters.ts
var labelHighlight = hlGroupManager.linkGroup("Label", "Label");
var SourcePainter = class {
  constructor(type, painters, source, columnRegistrar) {
    this.type = type;
    this.painters = painters;
    this.source = source;
    this.columnRegistrar = columnRegistrar;
    this.columns = /* @__PURE__ */ new Set();
    this.parts = [];
    this.labelingParts = [];
  }
  dispose() {
    this.clearParts(this.parts);
  }
  clearColumn(column) {
    if (typeof column !== "number") {
      column.subscriptions.map((s) => s.dispose());
    }
  }
  clearParts(parts) {
    parts.forEach((part) => {
      var _a2;
      if (typeof part !== "string") {
        this.clearColumn(part.column);
        (_a2 = part.modifiers) == null ? void 0 : _a2.forEach((m) => this.clearColumn(m.column));
      }
    });
  }
  async parseTemplate(template, labelingTemplate) {
    let needUpdateColumns = false;
    if (this.templateStr !== template) {
      this.templateStr = template;
      const initedParts = [];
      for (const parsedPart of parseTemplate(template)) {
        const part = await this.initPart(parsedPart);
        if (part) {
          initedParts.push(part);
        }
      }
      this.clearParts(this.parts);
      this.parts = initedParts;
      needUpdateColumns = true;
    }
    if (labelingTemplate) {
      if (this.labelingTemplateStr !== labelingTemplate) {
        this.labelingTemplateStr = labelingTemplate;
        const initedLabelingParts = [];
        for (const parsedPart of parseTemplate(labelingTemplate)) {
          const part = await this.initPart(parsedPart);
          if (part) {
            initedLabelingParts.push(part);
          }
        }
        this.clearParts(this.labelingParts);
        this.labelingParts = initedLabelingParts;
        needUpdateColumns = true;
      }
    }
    if (needUpdateColumns) {
      const columnSet = /* @__PURE__ */ new Set();
      const initedParts = [...this.parts, ...this.labelingParts];
      for (const item of initedParts) {
        if (typeof item !== "string") {
          if (typeof item.column !== "number") {
            columnSet.add(item.column);
          }
          if (item.modifiers) {
            for (const modifier of item.modifiers) {
              if (typeof modifier.column !== "number") {
                columnSet.add(modifier.column);
              }
            }
          }
        }
      }
      this.columns = columnSet;
    }
  }
  async initPart(part) {
    if (typeof part === "string") {
      return part;
    }
    const column = await this.columnRegistrar.initColumn(
      this.type,
      this.source,
      part.column
    );
    if (!column) {
      return void 0;
    }
    const block = {
      column
    };
    if (part.modifiers) {
      const modifiers = await Promise.all(
        part.modifiers.map(async (modifier) => {
          const column2 = await this.columnRegistrar.initColumn(
            this.type,
            this.source,
            modifier.column
          );
          if (!column2) {
            return void 0;
          }
          return {
            name: modifier.name,
            column: column2
          };
        })
      );
      block.modifiers = compactI2(modifiers);
    }
    return block;
  }
};
var SourcePainters = class {
  constructor(source, columnRegistrar) {
    this.source = source;
    this.columnRegistrar = columnRegistrar;
    this.painters = /* @__PURE__ */ new Map();
    this.viewPainter = new ViewPainter(this.source.explorer);
  }
  dispose() {
    this.painters.forEach((painter) => painter.dispose());
  }
  getPainter(type) {
    if (!this.painters.has(type)) {
      this.painters.set(
        type,
        new SourcePainter(type, this, this.source, this.columnRegistrar)
      );
    }
    return this.painters.get(type);
  }
  async parseTemplate(type, template, labelingTemplate) {
    return await this.getPainter(type).parseTemplate(
      template,
      labelingTemplate
    );
  }
  async load(parentNode) {
    for (const painter of this.painters.values()) {
      for (const column of painter.columns) {
        await (column.load && column.load(parentNode));
      }
    }
  }
  async drawPre(nodes, {
    draw,
    drawAll,
    abort,
    force = false
  } = {}) {
    class DrawAll extends Error {
    }
    class Abort extends Error {
    }
    const nodesGroup = groupBy_default(nodes, (n) => n.type);
    const types2 = Object.keys(nodesGroup);
    for (const type of types2) {
      const painter = this.getPainter(type);
      for (const column of painter.columns) {
        try {
          const nodes2 = nodesGroup[type];
          if (nodes2)
            column.drawHandle = await column.draw(nodes2, {
              drawAll() {
                if (drawAll) {
                  throw new DrawAll();
                }
              },
              abort() {
                throw new Abort();
              },
              force
            });
        } catch (err) {
          if (err instanceof DrawAll) {
            return drawAll();
          } else if (err instanceof Abort) {
            if (abort) {
              return abort();
            }
          } else {
            throw err;
          }
        }
      }
    }
    return draw == null ? void 0 : draw();
  }
  async drawNode(node, nodeIndex, {
    isLabeling = false
  } = {}) {
    const row = await this.viewPainter.drawRow(async (row2) => {
      for (const part of this.getPainter(node.type).parts) {
        await row2.addTemplatePart(node, nodeIndex, part, isLabeling);
      }
    });
    const drawn = await row.draw();
    return {
      nodeIndex,
      nodeUid: node.uid,
      content: drawn.content,
      highlightPositions: drawn.highlightPositions
    };
  }
  async drawNodeLabeling(node, nodeIndex) {
    var _a2;
    const drawnList = [];
    for (const part of this.getPainter(node.type).labelingParts) {
      if (typeof part === "string") {
        drawnList.push({
          content: part,
          highlightPositions: []
        });
        continue;
      }
      const columns = [
        part.column,
        ...((_a2 = part.modifiers) == null ? void 0 : _a2.map((m) => m.name === "&" ? m.column : "")) ?? []
      ].filter((c) => typeof c !== "string");
      const visibleColumns = await (0, import_p_filter.default)(
        columns,
        async (c) => {
          var _a3;
          return !((_a3 = c.drawHandle) == null ? void 0 : _a3.labelVisible) || await c.drawHandle.labelVisible({ node, nodeIndex });
        }
      );
      if (!visibleColumns.length) {
        continue;
      }
      const isAllLabelOnly = visibleColumns.every(
        (c) => {
          var _a3;
          return (_a3 = c.drawHandle) == null ? void 0 : _a3.labelOnly;
        }
      );
      const contentColumns = visibleColumns.filter(
        async (c) => {
          var _a3;
          return !((_a3 = c.drawHandle) == null ? void 0 : _a3.labelOnly);
        }
      );
      const row = await this.viewPainter.drawRow(async (row2) => {
        row2.add(
          visibleColumns.map((column) => column.label).join(" & ") + (isAllLabelOnly ? "" : ":"),
          { hl: labelHighlight }
        );
        row2.add(" ");
        for (const column of contentColumns) {
          await row2.addColumn(node, nodeIndex, column, true);
        }
      });
      const { highlightPositions, content } = await row.draw({
        flexible: false
      });
      drawnList.push({
        content,
        highlightPositions
      });
    }
    return drawnList;
  }
};

// src/view/rendererExplorer.ts
var import_coc45 = require("coc.nvim");

// src/view/rendererSource.ts
var import_coc44 = require("coc.nvim");
var rendererSourceSymbol = Symbol("rendererSource");
var RendererSource = class {
  constructor(view, explorer = view.explorer, source = view.source) {
    this.view = view;
    this.explorer = explorer;
    this.source = source;
    this.requestedRenderNodes = /* @__PURE__ */ new Set();
  }
  nodeAndChildrenRange(node) {
    const startIndex = this.view.flattenedNodes.findIndex(
      (it) => it.uid === node.uid
    );
    if (startIndex === -1) {
      return;
    }
    const parentLevel = node.level ?? 0;
    let endIndex = this.view.flattenedNodes.length - 1;
    for (let i = startIndex + 1, len = this.view.flattenedNodes.length; i < len; i++) {
      if ((this.view.flattenedNodes[i].level ?? 0) <= parentLevel) {
        endIndex = i - 1;
        break;
      }
    }
    return { startIndex, endIndex };
  }
  async drawNodes(nodes) {
    const drawnList = compactI2(
      await Promise.all(
        nodes.map(async (node) => {
          const nodeIndex = this.view.flattenedNodes.findIndex(
            (it) => it.uid === node.uid
          );
          if (nodeIndex < 0) {
            return;
          }
          const finalNode = this.view.flattenedNodes.at(nodeIndex);
          if (!finalNode) {
            return;
          }
          return this.view.sourcePainters.drawNode(finalNode, nodeIndex);
        })
      )
    );
    const startLineIndex = this.view.startLineIndex;
    return {
      drawnList,
      get contents() {
        return drawnList.map((d) => d.content);
      },
      get highlightPositions() {
        return drawnList.map(
          (d) => d.highlightPositions.map((hl) => ({
            lineIndex: startLineIndex + d.nodeIndex,
            ...hl
          }))
        ).flat();
      }
    };
  }
  async emitRequestRenderNodesNotifier() {
    if (this.requestedRenderNodes.size <= 0) {
      return;
    }
    const nodes = Array.from(this.requestedRenderNodes);
    this.requestedRenderNodes.clear();
    return this.renderNodesNotifier(nodes);
  }
  async renderPathsNotifier(paths) {
    if (this.view.isHelpUI) {
      return Notifier.noop();
    }
    const pathArr = paths instanceof Set ? Array.from(paths) : paths;
    if (!pathArr.length) {
      return Notifier.noop();
    }
    const getNodes = (paths2) => this.view.flattenedNodes.filter(
      (n) => n.fullpath && paths2.includes(n.fullpath)
    );
    const renderNodes = pathArr.map(
      (o) => {
        if (typeof o === "string") {
          return {
            nodes: getNodes([o])
          };
        } else {
          return {
            nodes: getNodes([...o.paths]),
            withParents: o.withParents,
            withChildren: o.withChildren
          };
        }
      }
    );
    return this.renderNodesNotifier(renderNodes);
  }
  async renderNodesNotifier(nodes) {
    const nodeArr = nodes instanceof Set ? Array.from(nodes) : nodes;
    const nodeItems = nodeArr.map((o) => {
      if ("uid" in o) {
        return {
          nodes: [o],
          withParents: false,
          withChildren: false
        };
      } else {
        return {
          nodes: [...o.nodes],
          withParents: o.withParents ?? false,
          withChildren: o.withChildren ?? false
        };
      }
    });
    const finalNodes = [];
    for (const node of nodeItems) {
      finalNodes.push(...node.nodes);
      if (node.withParents) {
        for (const n of node.nodes) {
          finalNodes.push(...this.view.flattenParents(n));
        }
      }
      if (node.withChildren) {
        for (const n of node.nodes) {
          finalNodes.push(...this.view.flattenNode(n));
        }
      }
    }
    if (!finalNodes.length) {
      return Notifier.noop();
    }
    return await this.view.sourcePainters.drawPre(finalNodes, {
      draw: async () => {
        const { drawnList, highlightPositions } = await this.drawNodes(finalNodes);
        const drawnRangeList = drawnWithIndexRange(drawnList);
        await this.source.events.fire("drawn");
        return Notifier.create(() => {
          drawnRangeList.forEach((dr) => {
            this.view.setLinesNotifier(
              dr.drawnList.map((d) => d.content),
              dr.nodeIndexStart,
              dr.nodeIndexEnd + 1
            ).notify();
          });
          this.source.highlight.addHighlightsNotify(highlightPositions);
          if (import_coc44.workspace.isVim) {
            import_coc44.workspace.nvim.command("redraw", true);
          }
        });
      },
      drawAll: () => this.renderNotifier(),
      abort: () => Notifier.noop()
    });
  }
  async renderNotifier({
    node = this.view.rootNode,
    force = false
  } = {}) {
    if (this.view.isHelpUI) {
      return Notifier.noop();
    }
    const range = this.nodeAndChildrenRange(node);
    if (!range && !node.isRoot) {
      return Notifier.noop();
    }
    const { startIndex: nodeIndex, endIndex } = range ? range : { startIndex: 0, endIndex: this.view.flattenedNodes.length - 1 };
    const oldHeight = endIndex - nodeIndex + 1;
    const needDrawNodes = this.view.flattenNode(node);
    const newHeight = needDrawNodes.length;
    this.view.flattenedNodes = this.view.flattenedNodes.slice(0, nodeIndex).concat(needDrawNodes).concat(this.view.flattenedNodes.slice(endIndex + 1));
    if (newHeight < oldHeight) {
      this.explorer.locator.mark.removeLines(
        this.view.startLineIndex + newHeight + 1,
        this.view.startLineIndex + oldHeight + 1
      );
    }
    this.source.locator.mark.offsetAfterLine(
      newHeight - oldHeight,
      this.view.endLineIndex
    );
    await this.view.sourcePainters.drawPre(needDrawNodes, { force });
    const { contents, highlightPositions } = await this.drawNodes(needDrawNodes);
    await this.source.events.fire("drawn");
    const sourceIndex = this.view.currentSourceIndex();
    const isLastSource = this.explorer.sources.length - 1 === sourceIndex;
    return Notifier.create(() => {
      this.explorer.setLinesNotifier(
        contents,
        this.view.startLineIndex + nodeIndex,
        isLastSource && node.isRoot ? -1 : this.view.startLineIndex + nodeIndex + oldHeight
      ).notify();
      this.source.highlight.addHighlightsNotify(highlightPositions);
      if (import_coc44.workspace.isVim) {
        import_coc44.workspace.nvim.command("redraw", true);
      }
    });
  }
};

// src/view/rendererExplorer.ts
var rendererExplorerSymbol = Symbol("rendererExplorer");
var RendererExplorer = class {
  constructor(view, explorer = view.explorer) {
    this.view = view;
    this.explorer = explorer;
    this.renderMutex = new import_coc45.Mutex();
  }
  async runQueue(fn) {
    let release = await this.renderMutex.acquire();
    setTimeout(() => {
      if (release) {
        release();
        release = void 0;
        logger.error(
          "view.sync timeout, force render, view.sync may cause deadlock due to recursive calls"
        );
      }
    }, 5e3);
    try {
      return await fn();
    } finally {
      if (release) {
        release();
        release = void 0;
      }
    }
  }
  rendererSources() {
    return this.explorer.sources.map((s) => s.view[rendererSourceSymbol]);
  }
  async renderAllNotifier() {
    const notifiers = await Promise.all(
      this.rendererSources().map((s) => s.renderNotifier({ force: true }))
    );
    return Notifier.combine(notifiers);
  }
};

// src/view/viewNodeStores.ts
var ViewNodeStores = class {
  constructor(viewSource) {
    this.viewSource = viewSource;
    this.internal = /* @__PURE__ */ (() => {
      const internal = {
        records: /* @__PURE__ */ new Map(),
        store(node) {
          if (!internal.records.has(node.uid)) {
            internal.records.set(node.uid, {
              expanded: false,
              compact: "uncompact"
            });
          }
          return internal.records.get(node.uid);
        },
        clear() {
          internal.records.clear();
        },
        get(node, key) {
          return internal.store(node)[key];
        },
        set(node, key, value) {
          internal.store(node)[key] = value;
        }
      };
      return internal;
    })();
    const context2 = viewSource.source.context;
    const stores = viewSource.config.get("expandStores", true);
    if (typeof stores === "boolean") {
      this.enabled = stores;
    } else if ("includes" in stores) {
      this.enabled = stores.includes.includes(
        this.viewSource.source.sourceType
      );
    } else if ("excludes" in stores) {
      this.enabled = !stores.excludes.includes(
        this.viewSource.source.sourceType
      );
    } else {
      this.enabled = true;
    }
    context2.subscriptions.push(
      viewSource.source.explorer.events.on("open-pre", () => {
        if (!this.enabled) {
          this.internal.clear();
        }
      })
    );
  }
  setExpanded(node, expanded) {
    expanded ? this.expand(node) : this.collapse(node);
  }
  expand(node) {
    this.internal.set(node, "expanded", true);
  }
  collapse(node) {
    this.internal.set(node, "expanded", false);
  }
  isExpanded(node) {
    return this.internal.get(node, "expanded");
  }
  setCompact(node, compact) {
    this.internal.set(node, "compact", compact);
  }
  getCompact(node) {
    return this.internal.get(node, "compact");
  }
};

// src/view/viewSource.ts
var ViewSource = class {
  constructor(source, columnRegistrar, rootNode) {
    this.source = source;
    this.columnRegistrar = columnRegistrar;
    this.rootNode = rootNode;
    /**
     * rendered nodes
     */
    this.flattenedNodes = [];
    this.startLineIndex = 0;
    this.endLineIndex = 0;
    this.rootExpandedForOpen = false;
    this.explorer = this.source.explorer;
    this.nodeStores = new ViewNodeStores(this);
    this.sourcePainters = new SourcePainters(
      this.source,
      this.columnRegistrar
    );
    this[rendererSourceSymbol] = new RendererSource(this);
  }
  get isHelpUI() {
    return this.explorer.view.isHelpUI;
  }
  get config() {
    return this.source.config;
  }
  async sync(block) {
    return await this.explorer.view[rendererExplorerSymbol].runQueue(
      () => block(this[rendererSourceSymbol])
    );
  }
  /**
   * request render nodes, it will render the node when finished the action
   */
  requestRenderNodes(nodes) {
    for (const node of nodes) {
      this[rendererSourceSymbol].requestedRenderNodes.add(node);
    }
  }
  dispose() {
    this.sourcePainters.dispose();
  }
  bootInit(rootExpandedForOpen) {
    this.rootExpandedForOpen = rootExpandedForOpen;
  }
  bootOpen() {
    this.nodeStores.setExpanded(this.rootNode, this.rootExpandedForOpen);
  }
  async load(node) {
    await this.sourcePainters.load(node);
  }
  async parseTemplate(type, template, labelingTemplate) {
    return await this.sourcePainters.parseTemplate(
      type,
      template,
      labelingTemplate
    );
  }
  /**
   * Relative line index for source
   */
  get currentLineIndex() {
    return this.explorer.view.currentLineIndex - this.startLineIndex;
  }
  currentNode() {
    return this.flattenedNodes[this.currentLineIndex];
  }
  currentSourceIndex() {
    const indexOf = this.explorer.sources.indexOf(this.source);
    return indexOf === -1 ? void 0 : indexOf;
  }
  getNodeByLine(lineIndex) {
    return this.flattenedNodes[lineIndex];
  }
  /**
   * Get relative line index for source by node
   */
  getLineByNode(node) {
    const line = this.flattenedNodes.findIndex((it) => it.uid === node.uid);
    return line === -1 ? void 0 : line;
  }
  setLinesNotifier(lines, startIndex, endIndex) {
    return this.explorer.setLinesNotifier(
      lines,
      this.startLineIndex + startIndex,
      this.startLineIndex + endIndex
    );
  }
  replaceNodeInSibling(oldNode, newNode) {
    var _a2;
    if ((_a2 = oldNode.parent) == null ? void 0 : _a2.children) {
      const index = oldNode.parent.children.indexOf(oldNode);
      if (index !== -1) {
        oldNode.parent.children.splice(index, 1, newNode);
        newNode.level = oldNode.level;
        newNode.parent = oldNode.parent;
        newNode.prevSiblingNode = oldNode.prevSiblingNode;
        newNode.nextSiblingNode = oldNode.nextSiblingNode;
      }
    }
  }
  /**
   * get all parents
   */
  flattenParents(node) {
    let currentNode = node;
    const result = [];
    while (true) {
      if (currentNode.parent) {
        result.push(currentNode.parent);
        currentNode = currentNode.parent;
      } else {
        break;
      }
    }
    return result;
  }
  /**
   * get current node and all children flattened nodes
   */
  flattenNode(node) {
    var _a2, _b, _c, _d;
    const result = [];
    const stack = [node];
    while (stack.length) {
      let node2 = stack.shift();
      if (!node2.isRoot) {
        const compactStatus = this.nodeStores.getCompact(node2);
        switch (compactStatus) {
          case "compact":
            if (!node2.compactedNodes && ((_a2 = node2.children) == null ? void 0 : _a2.length) === 1 && ((_b = node2.children[0]) == null ? void 0 : _b.expandable)) {
              let tail = node2.children[0];
              const compactedNodes = [node2, tail];
              while (((_c = tail.children) == null ? void 0 : _c.length) === 1 && ((_d = tail.children[0]) == null ? void 0 : _d.expandable)) {
                this.nodeStores.setCompact(tail, "compact");
                tail = tail.children[0];
                compactedNodes.push(tail);
              }
              this.nodeStores.setCompact(tail, "compact");
              const compactedNode = { ...tail };
              compactedNode.name = compactedNodes.map((n) => n.name).join("/");
              compactedNode.compactedNodes = compactedNodes;
              compactedNode.compactedLastNode = tail;
              this.replaceNodeInSibling(node2, compactedNode);
              node2 = compactedNode;
            }
            break;
          case "uncompact":
            if (node2.compactedNodes) {
              const topNode = node2.compactedNodes[0];
              for (const n of node2.compactedNodes) {
                this.nodeStores.setCompact(n, "uncompact");
              }
              this.replaceNodeInSibling(node2, topNode);
              node2 = topNode;
            }
            break;
        }
      }
      result.push(node2);
      if (node2.children) {
        for (let i = node2.children.length - 1; i >= 0; i--) {
          node2.children[i].parent = node2;
          node2.children[i].level = (node2.level ?? 0) + 1;
          stack.unshift(node2.children[i]);
        }
      }
    }
    return result;
  }
  isExpanded(node) {
    return this.nodeStores.isExpanded(node);
  }
  // render
  async expandRender(node) {
    if (this.isHelpUI) {
      return;
    }
    if (!this.isExpanded(node) || !node.children) {
      return;
    }
    await this.sync(async (r) => {
      const range = r.nodeAndChildrenRange(node);
      if (!range) {
        return;
      }
      const { startIndex, endIndex } = range;
      const needDrawNodes = this.flattenNode(node);
      await this.sourcePainters.drawPre(needDrawNodes, {
        draw: async () => {
          this.flattenedNodes = this.flattenedNodes.slice(0, startIndex).concat(needDrawNodes).concat(this.flattenedNodes.slice(endIndex + 1));
          this.source.locator.mark.offsetAfterLine(
            needDrawNodes.length - 1 - (endIndex - startIndex),
            startIndex
          );
          const { contents, highlightPositions } = await r.drawNodes(needDrawNodes);
          await this.source.events.fire("drawn");
          import_coc46.workspace.nvim.pauseNotification();
          this.setLinesNotifier(contents, startIndex, endIndex + 1).notify();
          this.source.highlight.addHighlightsNotify(highlightPositions);
          if (import_coc46.workspace.isVim) {
            import_coc46.workspace.nvim.command("redraw", true);
          }
          await import_coc46.workspace.nvim.resumeNotification();
        },
        drawAll: async () => (await r.renderNotifier()).run()
      });
    });
  }
  async expandRecursive(node, options) {
    var _a2;
    const autoExpandOptions = this.config.get("autoExpandOptions") ?? [
      "compact",
      "uncompact"
    ];
    const compact = options.compact ?? autoExpandOptions.includes("compact");
    const uncompact = options.uncompact ?? autoExpandOptions.includes("uncompact");
    const recursiveSingle = options.recursiveSingle ?? (autoExpandOptions.includes("recursiveSingle") || compact);
    if (node.expandable) {
      const depth = options.depth ?? 1;
      const isExpanded = this.isExpanded(node);
      this.nodeStores.expand(node);
      if (!node.children) {
        node.children = await this.source.loadInitedChildren(node, {
          recursiveExpanded: true
        });
      }
      if (depth > this.config.get("autoExpandMaxDepth")) {
        return;
      }
      const singleExpandableNode = node.children.length === 1 && ((_a2 = node.children[0]) == null ? void 0 : _a2.expandable);
      const compactStatus = this.nodeStores.getCompact(node);
      switch (compactStatus) {
        case "uncompact":
          if (singleExpandableNode && compact) {
            this.nodeStores.setCompact(node, "compact");
          }
          break;
        case "compact":
          if (isExpanded && uncompact) {
            this.nodeStores.setCompact(node, "uncompact");
          } else {
            this.nodeStores.setCompact(node, "compact");
          }
          break;
      }
      if (options.recursive || singleExpandableNode && recursiveSingle) {
        await Promise.all(
          node.children.map(async (child) => {
            await this.expandRecursive(child, {
              ...options,
              depth: depth + 1
            });
          })
        );
      }
    }
  }
  /**
   * expand node
   */
  async expand(node, options = {}) {
    await this.expandRecursive(node, options);
    if (options.render ?? true) {
      await this.expandRender(node);
    }
  }
  async collapseRender(node) {
    if (this.isHelpUI || this.isExpanded(node)) {
      return;
    }
    await this.sync(async (r) => {
      const range = r.nodeAndChildrenRange(node);
      if (!range) {
        return;
      }
      await this.sourcePainters.drawPre([node], {
        draw: async () => {
          const { startIndex, endIndex } = range;
          this.flattenedNodes.splice(startIndex + 1, endIndex - startIndex);
          this.explorer.locator.mark.removeLines(
            this.startLineIndex + startIndex + 1,
            this.startLineIndex + endIndex
          );
          this.source.locator.mark.offsetAfterLine(
            -(endIndex - startIndex),
            endIndex
          );
          const gotoNotifier = await this.source.locator.gotoLineIndexNotifier(
            startIndex,
            0
          );
          const { contents, highlightPositions } = await r.drawNodes([node]);
          await this.source.events.fire("drawn");
          import_coc46.workspace.nvim.pauseNotification();
          this.setLinesNotifier(contents, startIndex, endIndex + 1).notify();
          this.source.highlight.addHighlightsNotify(highlightPositions);
          gotoNotifier.notify();
          if (import_coc46.workspace.isVim) {
            import_coc46.workspace.nvim.command("redraw", true);
          }
          await import_coc46.workspace.nvim.resumeNotification();
        },
        drawAll: async () => (await r.renderNotifier()).run()
      });
    });
  }
  async collapseRecursive(node, recursive) {
    if (node.expandable) {
      this.nodeStores.collapse(node);
      const children = node.children;
      if (!children) {
        return;
      }
      node.children = void 0;
      if (recursive || this.config.get("autoCollapseOptions").includes("recursive")) {
        for (const child of children) {
          await this.collapseRecursive(child, recursive);
        }
      }
    }
  }
  /**
   * collapse node
   */
  async collapse(node, { recursive = false } = {}) {
    await this.collapseRecursive(node, recursive);
    await this.collapseRender(node);
  }
  async renderNodes(nodes) {
    return await this.sync(async (r) => {
      await (await r.renderNodesNotifier(nodes)).run();
    });
  }
  async renderPaths(paths) {
    await this.sync(async (r) => {
      await (await r.renderPathsNotifier(paths)).run();
    });
  }
  async render(options) {
    await this.sync(async (r) => {
      await (await r.renderNotifier(options)).run();
    });
  }
};
rendererSourceSymbol;

// src/source/source.ts
var import_coc47 = require("coc.nvim");

// src/actions/actionSource.ts
var ActionSource = class extends ActionRegistrar {
  constructor(owner, globalActionRegistrar) {
    super(owner);
    this.owner = owner;
    this.source = this.owner;
    this.global = globalActionRegistrar;
  }
  registeredActions() {
    return new Map([
      ...this.global.actions,
      ...this.actions
    ]);
  }
  registeredAction(name) {
    return this.actions.get(name) || this.global.actions.get(name);
  }
  async doActionExp(actionExp, nodes, options = {}) {
    const mode = options.mode ?? "n";
    const isSubAction = options.isSubAction ?? false;
    let waitRelease;
    let curNodes = nodes;
    const subOptions = {
      mode,
      isSubAction: true
    };
    try {
      if (Array.isArray(actionExp)) {
        for (let i = 0; i < actionExp.length; i++) {
          if (i !== 0) {
            const curNode = this.source.view.currentNode();
            curNodes = curNode ? [curNode] : [];
          }
          const action = actionExp[i];
          if (!action)
            continue;
          if (Array.isArray(action)) {
            await this.doActionExp(action, curNodes, subOptions);
            continue;
          }
          if (action.name === waitAction.name) {
            const timeout = this.source.config.get(
              "mapping.action.wait.timeout"
            );
            if (timeout === 0 || waitRelease || isSubAction) {
              continue;
            }
            waitRelease = await this.global.waitActionMutex.acquire();
            setTimeout(() => {
              if (waitRelease) {
                logger.warn(`action(${JSON.stringify(actionExp)}) timeout`);
                waitRelease();
                waitRelease = void 0;
              }
            }, timeout);
            continue;
          }
          const rule = conditionActionRules[action.name];
          if (rule) {
            const [trueNodes, falseNodes] = partition_default(
              curNodes,
              (node) => rule.filter(this.source, node, action.args)
            );
            const [trueAction, falseAction] = [
              actionExp[i + 1],
              actionExp[i + 2]
            ];
            i += 2;
            if (trueAction && trueNodes.length) {
              await this.doActionExp(trueAction, trueNodes, subOptions);
            }
            if (falseAction && falseNodes.length) {
              await this.doActionExp(falseAction, falseNodes, subOptions);
            }
          } else {
            await this.doActionExp(action, curNodes, subOptions);
          }
        }
      } else {
        if (actionExp.name !== noopAction.name) {
          await this.doAction(actionExp.name, curNodes, actionExp.args, mode);
        }
      }
    } finally {
      waitRelease == null ? void 0 : waitRelease();
      waitRelease = void 0;
    }
  }
  async doAction(name, nodes, args = [], mode = "n") {
    const action = this.registeredAction(name);
    if (!action) {
      return;
    }
    const { select = false, render = false, reload = false } = action.options;
    const finalNodes = Array.isArray(nodes) ? nodes : [nodes];
    const source = this.source;
    try {
      switch (select) {
        case true: {
          const allNodes = uniq_default([
            ...finalNodes,
            ...source.selectedNodes
          ]);
          source.selectedNodes.clear();
          source.view.requestRenderNodes(allNodes);
          await action.callback.call(source, {
            source,
            nodes: allNodes,
            args,
            mode
          });
          break;
        }
        case false:
          if (finalNodes[0])
            await action.callback.call(source, {
              source,
              nodes: [finalNodes[0]],
              args,
              mode
            });
          break;
        case "visual":
          await action.callback.call(source, {
            source,
            nodes: finalNodes,
            args,
            mode
          });
          break;
        case "keep": {
          const allNodes = uniq_default([...finalNodes, ...source.selectedNodes]);
          await action.callback.call(source, {
            source,
            nodes: allNodes,
            args,
            mode
          });
          break;
        }
      }
    } finally {
      if (reload) {
        await source.load(source.view.rootNode);
      } else if (render) {
        await source.view.render();
      }
    }
  }
  async listActionMenu(nodes) {
    const actions = this.registeredActions();
    const source = this.source;
    const reverseMappings = await keyMapping.getReversedMappings(
      source.sourceType
    );
    const task = await startCocList(
      this.source.explorer,
      explorerActionList,
      [...actions.entries()].filter(([actionName]) => actionName !== "actionMenu").sort(([aName], [bName]) => aName.localeCompare(bName)).map(([actionName, { options, description }]) => {
        const keys2 = reverseMappings.get(actionName);
        const key = keys2 ? keys2.vmap ?? keys2.nmap : "";
        const list = [
          {
            name: actionName,
            key,
            description,
            callback: async () => {
              await task.waitExplorerShow();
              await source.action.doAction(actionName, nodes, [], "n");
            }
          }
        ];
        if (options.menus) {
          list.push(
            ...ActionMenu.getNormalizeMenus(options.menus).map((menu) => {
              const fullActionName = `${actionName}:${menu.args}`;
              const keys3 = reverseMappings.get(fullActionName);
              const key2 = keys3 ? keys3.vmap ?? keys3.nmap : "";
              return {
                name: fullActionName,
                key: key2,
                description: `${description} ${menu.description}`,
                callback: async () => {
                  await task.waitExplorerShow();
                  await source.action.doAction(
                    actionName,
                    nodes,
                    await menu.actionArgs(),
                    "n"
                  );
                }
              };
            })
          );
        }
        return list;
      }).flat()
    );
    task.waitExplorerShow().catch(logger.error);
  }
};

// src/highlight/highlightSource.ts
var HighlightSource = class {
  constructor(source, hlSrcId) {
    this.source = source;
    this.hlSrcId = hlSrcId;
  }
  addHighlightsNotify(highlights) {
    this.source.explorer.highlight.addHighlightsNotify(
      this.hlSrcId,
      highlights
    );
  }
  clearHighlightsNotify(lineStart, lineEnd) {
    this.source.explorer.highlight.clearHighlightsNotify(
      this.hlSrcId,
      lineStart,
      lineEnd
    );
  }
};

// src/locator/markSource.ts
var MarkSource = class {
  constructor(source) {
    this.source = source;
    this.explorer = source.explorer;
  }
  get view() {
    return this.source.view;
  }
  add(type, relativeLineIndex) {
    this.explorer.locator.mark.add(
      type,
      this.view.startLineIndex + relativeLineIndex
    );
  }
  remove(type, relativeLineIndex) {
    this.explorer.locator.mark.remove(
      type,
      this.view.startLineIndex + relativeLineIndex
    );
  }
  offsetAfterLine(offset, afterLine) {
    this.explorer.locator.mark.offsetLines(
      offset,
      this.view.startLineIndex + afterLine + 1
    );
    this.view.endLineIndex += offset;
    const sourceIndex = this.view.currentSourceIndex();
    if (sourceIndex === void 0) {
      return;
    }
    this.explorer.sources.slice(sourceIndex + 1).forEach(({ view }) => {
      view.startLineIndex += offset;
      view.endLineIndex += offset;
    });
  }
};

// src/locator/locatorSource.ts
var LocatorSource = class {
  constructor(source) {
    this.source = source;
    this.explorer = this.source.explorer;
    this.mark = new MarkSource(source);
  }
  get view() {
    return this.source.view;
  }
  async gotoLineIndex(lineIndex, col) {
    return (await this.gotoLineIndexNotifier(lineIndex, col)).run();
  }
  gotoLineIndexNotifier(lineIndex, col) {
    if (lineIndex < 0) {
      lineIndex = 0;
    }
    if (lineIndex >= this.source.height) {
      lineIndex = this.source.height - 1;
    }
    return this.explorer.locator.gotoLineIndexNotifier(
      this.view.startLineIndex + lineIndex,
      col
    );
  }
  async gotoRoot({ col } = {}) {
    return (await this.gotoLineIndexNotifier(0, col)).run();
  }
  gotoRootNotifier({ col } = {}) {
    return this.gotoLineIndexNotifier(0, col);
  }
  async gotoNode(node, options = {}) {
    return (await this.gotoNodeNotifier(node, options)).run();
  }
  async gotoNodeNotifier(node, options = {}) {
    return this.gotoNodeUidNotifier(node.uid, options);
  }
  async gotoNodeUid(nodeUid, options = {}) {
    return (await this.gotoNodeUidNotifier(nodeUid, options)).run();
  }
  async gotoNodeUidNotifier(nodeUid, {
    lineIndex: fallbackLineIndex,
    col = 0
  } = {}) {
    const lineIndex = this.view.flattenedNodes.findIndex(
      (it) => it.uid === nodeUid
    );
    if (lineIndex !== -1) {
      return this.gotoLineIndexNotifier(lineIndex, col);
    } else if (fallbackLineIndex !== void 0) {
      return this.gotoLineIndexNotifier(fallbackLineIndex, col);
    } else {
      return Notifier.noop();
    }
  }
};

// src/source/source.ts
var ExplorerSource = class {
  constructor(sourceType, explorer) {
    this.sourceType = sourceType;
    this.explorer = explorer;
    this.width = 0;
    this.showHidden = false;
    this.selectedNodes = /* @__PURE__ */ new Set();
    this.nvim = import_coc47.workspace.nvim;
    this.bufManager = this.explorer.explorerManager.bufManager;
    this.events = new HelperEventEmitter(logger);
    this.action = new ActionSource(this, this.explorer.action);
    this.locator = new LocatorSource(this);
    this.disposables = [];
    this.isDisposed = false;
    this.config = this.explorer.config;
    this.icons = /* @__PURE__ */ ((source) => ({
      get expanded() {
        return source.config.get("icon.expanded") || (source.config.get("icon.enableNerdfont") ? "\uF44B" : "-");
      },
      get collapsed() {
        return source.config.get("icon.collapsed") || (source.config.get("icon.enableNerdfont") ? "\uF44A" : "+");
      },
      get selected() {
        return source.config.get("icon.selected");
      },
      get hidden() {
        return source.config.get("icon.hidden");
      },
      get link() {
        return source.config.get("icon.link");
      },
      get readonly() {
        return source.config.get("icon.readonly") || (source.config.get("icon.enableNerdfont") ? "\uF023" : "RO");
      }
    }))(this);
    this.helper = /* @__PURE__ */ ((source) => ({
      getUid(uid) {
        return generateUri2(uid.toString(), source.sourceType);
      }
    }))(this);
    this.context = this.explorer.context;
    this.highlight = new HighlightSource(
      this,
      // workspace.createNameSpace(`coc-explorer-${sourceType}`),
      `coc-explorer-${sourceType}`
    );
  }
  get root() {
    return import_coc47.workspace.cwd;
  }
  set root(_root) {
  }
  static get enabled() {
    return true;
  }
  dispose() {
    this.isDisposed = true;
    this.view.dispose();
    this.disposables.forEach((s) => s.dispose());
  }
  get height() {
    return this.view.flattenedNodes.length;
  }
  bootInit(rootExpandedForOpen) {
    Promise.resolve(this.init()).catch(logger.error);
    this.view.bootInit(rootExpandedForOpen);
  }
  async bootOpen(isFirst) {
    await this.open(isFirst);
    this.view.bootOpen();
  }
  async openedNotifier(renderer, _isFirst) {
    return Notifier.noop();
  }
  async copyToClipboard(content) {
    await this.nvim.call("setreg", ["+", content]);
    await this.nvim.call("setreg", ['"', content]);
  }
  isSelectedAny() {
    return this.selectedNodes.size !== 0;
  }
  isSelectedNode(node) {
    return this.selectedNodes.has(node);
  }
  async loadInitedChildren(parentNode, options) {
    const children = await this.loadChildren(parentNode, options);
    await Promise.all(
      children.map(async (node, i) => {
        node.level = (parentNode.level ?? 0) + 1;
        node.parent = parentNode;
        node.prevSiblingNode = children[i - 1];
        node.nextSiblingNode = children[i + 1];
        if ((options == null ? void 0 : options.recursiveExpanded) && node.expandable && this.view.isExpanded(node)) {
          node.children = await this.loadInitedChildren(node, options);
        }
      })
    );
    return children;
  }
  async load(node, options) {
    await this.view.sync(async (r) => {
      return (await this.loadNotifier(r, node, options)).run();
    });
  }
  async loadNotifier(renderer, node, { render = true, force = false } = {}) {
    if (this.isDisposed) {
      return Notifier.noop();
    }
    await this.explorer.refreshWidth();
    this.selectedNodes = /* @__PURE__ */ new Set();
    if (this.view.isExpanded(node)) {
      node.children = await this.loadInitedChildren(node, {
        recursiveExpanded: true,
        force
      });
    } else {
      node.children = void 0;
    }
    await this.events.fire("loaded", node);
    await this.view.load(node);
    if (render) {
      return renderer.renderNotifier({ node, force });
    }
    return Notifier.noop();
  }
};

// src/source/sourceManager.ts
var import_coc48 = require("coc.nvim");
var SourceManager = class {
  constructor() {
    this.registeredSources = {};
  }
  registerSource(name, source) {
    this.registeredSources[name] = source;
    return import_coc48.Disposable.create(() => {
      delete this.registeredSources[name];
    });
  }
  async enabled(name) {
    const sourceClass = this.registeredSources[name];
    if (!sourceClass) {
      return false;
    }
    return await sourceClass.enabled;
  }
  createSource(name, explorer, expanded) {
    const sourceClass = this.registeredSources[name];
    if (!sourceClass) {
      throw new Error(`explorer source(${name}) not found`);
    }
    const source = new sourceClass(name, explorer);
    source.bootInit(expanded);
    return source;
  }
};
var sourceManager = new SourceManager();

// src/source/sources/buffer/argOptions.ts
var bufferArgOptions = {
  bufferRootTemplate: Args.registerOption("buffer-root-template", {
    getDefault: () => config.get("buffer.root.template")
  }),
  bufferChildTemplate: Args.registerOption("buffer-child-template", {
    getDefault: () => config.get("buffer.child.template")
  }),
  bufferChildLabelingTemplate: Args.registerOption(
    "buffer-child-labeling-template",
    {
      getDefault: () => config.get("buffer.child.labelingTemplate")
    }
  )
};

// src/source/sources/buffer/bufferActions.ts
var import_coc49 = require("coc.nvim");
function loadBufferActions(action) {
  const { nvim } = import_coc49.workspace;
  const buffer2 = action.owner;
  action.addNodeAction(
    "drop",
    async ({ node }) => {
      if (!node.hidden) {
        const info = await nvim.call("getbufinfo", node.bufnr);
        if (info.length && info[0].windows.length) {
          const quitNotifier2 = await buffer2.explorer.tryQuitOnOpenNotifier();
          const winid = info[0].windows[0];
          nvim.pauseNotification();
          nvim.call("win_gotoid", winid, true);
          quitNotifier2.notify();
          await nvim.resumeNotification();
          return;
        }
      }
      const quitNotifier = await buffer2.explorer.tryQuitOnOpenNotifier();
      nvim.pauseNotification();
      nvim.command(`buffer ${node.bufnr}`, true);
      quitNotifier.notify();
      await nvim.resumeNotification();
    },
    "open buffer by drop command",
    { select: true }
  );
  action.addNodeAction(
    "delete",
    async ({ node }) => {
      if (bufferTabOnly()) {
        await tabContainerManager.curTabDelBufnr(node.bufnr);
        if (tabContainerManager.existBufnr(node.bufnr)) {
          const winids = await winidsByBufnrInCurTab(node.bufnr);
          await leaveEmptyInWinids(winids);
          return;
        }
      }
      if (buffer2.bufManager.modified(node.fullpath, {
        directory: false
      }) && await prompt("Buffer is being modified, delete it?") !== "yes") {
        return;
      }
      await buffer2.bufManager.removeBufNode(node, {
        skipModified: true,
        bwipeout: false,
        directory: false
      });
      await buffer2.load(node, { force: true });
    },
    "delete buffer",
    { select: true }
  );
  action.addNodeAction(
    "deleteForever",
    async ({ node }) => {
      if (buffer2.bufManager.modified(node.fullpath, {
        directory: false
      }) && await prompt("Buffer is being modified, wipeout it?") !== "yes") {
        return;
      }
      await buffer2.bufManager.removeBufNode(node, {
        skipModified: true,
        bwipeout: true,
        directory: false
      });
      await buffer2.load(node, { force: true });
    },
    "bwipeout buffer",
    { select: true }
  );
}

// src/source/columnRegistrar.ts
var import_coc50 = require("coc.nvim");
var ColumnRegistrar = class {
  constructor() {
    this.registeredColumns = /* @__PURE__ */ new Map();
  }
  /**
   * Get ColumnRequired by column name
   */
  async initColumn(type, source, columnName) {
    var _a2, _b;
    if (/\d+/.test(columnName)) {
      return parseInt(columnName, 10);
    }
    const registeredColumn = (_a2 = this.registeredColumns.get(type)) == null ? void 0 : _a2.get(columnName);
    if (!registeredColumn) {
      throw Error(`column(${columnName}) not found`);
    }
    const column = { label: columnName };
    const subscriptions = [];
    Object.assign(
      column,
      registeredColumn.createColumn({
        source,
        column,
        subscriptions
      }),
      { subscriptions }
    );
    if (column.inited) {
      return column;
    }
    if (column.available && !await column.available()) {
      return void 0;
    }
    await ((_b = column.init) == null ? void 0 : _b.call(column));
    column.inited = true;
    return column;
  }
  registerColumn(type, name, createColumn) {
    if (!this.registeredColumns.has(type)) {
      this.registeredColumns.set(type, /* @__PURE__ */ new Map());
    }
    this.registeredColumns.get(type).set(name, {
      createColumn
    });
    return import_coc50.Disposable.create(() => {
      this.registeredColumns.get(type).delete(name);
    });
  }
};

// src/source/sources/buffer/bufferColumnRegistrar.ts
var BufferColumnRegistrar = class extends ColumnRegistrar {
};
var bufferColumnRegistrar = new BufferColumnRegistrar();

// src/source/sources/buffer/root-columns/icon.ts
bufferColumnRegistrar.registerColumn("root", "icon", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(
          source.view.isExpanded(node) ? source.icons.expanded : source.icons.collapsed,
          { hl: bufferHighlights.expandIcon }
        );
      }
    };
  }
}));

// src/source/sources/buffer/root-columns/title.ts
bufferColumnRegistrar.registerColumn("root", "title", () => ({
  draw() {
    return {
      drawNode(row) {
        row.add("[BUFFER]", {
          hl: bufferHighlights.title
        });
      }
    };
  }
}));

// src/source/sources/buffer/root-columns/hidden.ts
bufferColumnRegistrar.registerColumn("root", "hidden", ({ source }) => ({
  draw() {
    return {
      drawNode(row) {
        row.add(source.showHidden ? source.icons.hidden : "", {
          hl: bufferHighlights.hidden
        });
      }
    };
  }
}));

// src/git/config.ts
var getRootStatusIcons = (config4) => {
  const getRootIconConf = (name) => {
    const icon = config4.get(`git.icon.rootStatus.${name}`);
    return {
      icon,
      name
    };
  };
  return {
    [0 /* staged */]: {
      icon: "",
      name: "staged"
    },
    [5 /* stashed */]: getRootIconConf("stashed"),
    [1 /* ahead */]: getRootIconConf("ahead"),
    [2 /* behind */]: getRootIconConf("behind"),
    [3 /* conflicted */]: getRootIconConf("conflicted"),
    [4 /* untracked */]: getRootIconConf("untracked"),
    [6 /* modified */]: getRootIconConf("modified"),
    [7 /* added */]: getRootIconConf("added"),
    [8 /* renamed */]: getRootIconConf("renamed"),
    [9 /* deleted */]: getRootIconConf("deleted")
  };
};
var getStatusIcons = (config4) => {
  const getIconConf = (name) => {
    const icon = config4.get(`git.icon.status.${name}`);
    return {
      icon,
      name
    };
  };
  return {
    ["*" /* mixed */]: getIconConf("mixed"),
    [" " /* unmodified */]: getIconConf("unmodified"),
    ["M" /* modified */]: getIconConf("modified"),
    ["A" /* added */]: getIconConf("added"),
    ["D" /* deleted */]: getIconConf("deleted"),
    ["R" /* renamed */]: getIconConf("renamed"),
    ["C" /* copied */]: getIconConf("copied"),
    ["U" /* unmerged */]: getIconConf("unmerged"),
    ["?" /* untracked */]: getIconConf("untracked"),
    ["!" /* ignored */]: getIconConf("ignored")
  };
};

// src/git/highlights.ts
var import_coc51 = require("coc.nvim");
var import_color_convert3 = __toESM(require_color_convert());
var hlg2 = hlGroupManager.linkGroup.bind(hlGroupManager);
var registerGitHighlights = (disposables) => {
  hlGroupManager.watchColorScheme(disposables, async () => {
    const groups = [
      "String",
      "Character",
      "Number",
      "Boolean",
      "Float",
      "Identifier",
      "Function",
      "Statement",
      "Conditional",
      "Repeat",
      "Label",
      "Operator",
      "Keyword",
      "Exception",
      "PreProc",
      "Include",
      "Define",
      "Macro",
      "PreCondit",
      "Type",
      "StorageClass",
      "Structure",
      "Typedef",
      "Special",
      "SpecialChar",
      "Tag",
      "Delimiter",
      "SpecialComment",
      "Debug",
      "Todo"
    ];
    const highlights = await extractHighlightsColor(groups);
    const fgs = compactI2(
      Object.values(highlights).map((h) => {
        const guifg = h.guifg;
        if (!guifg) {
          return;
        }
        const ctermfg = h.ctermfg ?? import_color_convert3.default.rgb.ansi256([guifg.red, guifg.green, guifg.blue]).toString();
        return {
          guifg,
          ctermfg
        };
      })
    );
    const { nvim } = import_coc51.workspace;
    nvim.pauseNotification();
    const green = findNearestColor(
      createColor(18, 204, 90, 1),
      fgs,
      (it) => it.guifg
    );
    if (green) {
      nvim.command(
        `highlight default CocExplorerGitPathChange_Internal ctermfg=${green.ctermfg} guifg=#${toHex(green.guifg)}`,
        true
      );
    }
    const yellow = findNearestColor(
      createColor(209, 177, 15, 1),
      fgs,
      (it) => it.guifg
    );
    if (yellow) {
      nvim.command(
        `highlight default CocExplorerGitContentChange_Internal ctermfg=${yellow.ctermfg} guifg=#${toHex(yellow.guifg)}`,
        true
      );
    }
    await nvim.resumeNotification();
  }).catch(logger.error);
};
var gitChangedPath = hlg2(
  "GitPathChange",
  "CocExplorerGitPathChange_Internal"
);
var gitContentChange = hlg2(
  "GitContentChange",
  "CocExplorerGitContentChange_Internal"
);
var gitHighlights = {
  renamed: hlg2("GitRenamed", gitChangedPath.group),
  copied: hlg2("GitCopied", gitChangedPath.group),
  added: hlg2("GitAdded", gitChangedPath.group),
  untracked: hlg2("GitUntracked", gitChangedPath.group),
  unmerged: hlg2("GitUnmerged", gitChangedPath.group),
  mixed: hlg2("GitMixed", gitContentChange.group),
  modified: hlg2("GitModified", gitContentChange.group),
  deleted: hlg2("GitDeleted", internalHighlightGroups.ErrorColor),
  ignored: hlg2("GitIgnored", internalHighlightGroups.CommentColor),
  staged: hlg2("GitStaged", internalHighlightGroups.CommentColor),
  unstaged: hlg2("GitUnstaged", "Operator")
};
var getGitFormatHighlight = (format2) => {
  switch (format2) {
    case "*" /* mixed */:
      return gitHighlights.mixed;
    case "M" /* modified */:
      return gitHighlights.modified;
    case "A" /* added */:
      return gitHighlights.added;
    case "D" /* deleted */:
      return gitHighlights.deleted;
    case "R" /* renamed */:
      return gitHighlights.renamed;
    case "C" /* copied */:
      return gitHighlights.copied;
    case "U" /* unmerged */:
      return gitHighlights.unmerged;
    case "?" /* untracked */:
      return gitHighlights.untracked;
  }
};

// src/diagnostic/manager.ts
var import_coc53 = require("coc.nvim");
var import_path15 = __toESM(require("path"));

// src/diagnostic/binder.ts
var import_coc52 = require("coc.nvim");
var import_path14 = __toESM(require("path"));
var DiagnosticBinder = class {
  constructor() {
    this.sourcesBinding = /* @__PURE__ */ new Map();
    this.prevErrorMixedCount = /* @__PURE__ */ new Map();
    this.prevWarningMixedCount = /* @__PURE__ */ new Map();
    this.reloadDebounceSubject = createSubject(
      (sub) => sub.pipe(
        buffer(sub.pipe(debounceTime(500))),
        switchMap(async (list) => {
          const sources = new Set(list.flat());
          await this.reload([...sources]);
        })
      )
    );
  }
  get sources() {
    return [...this.sourcesBinding.keys()];
  }
  get refTotalCount() {
    return sum_default([...this.sourcesBinding.values()].map((b) => b.refCount.total));
  }
  get diagnosticTypes() {
    const types2 = [];
    const refs = [...this.sourcesBinding.values()].map((ref) => ref.refCount);
    if (refs.some((ref) => ref.error > 0)) {
      types2.push("error");
    }
    if (refs.some((ref) => ref.warning > 0)) {
      types2.push("warning");
    }
    return types2;
  }
  bind(source, type) {
    const binding = mapGetWithDefault(this.sourcesBinding, source, () => ({
      refCount: {
        error: 0,
        warning: 0,
        total: 0
      }
    }));
    binding.refCount[type] += 1;
    binding.refCount.total += 1;
    if (binding.refCount.total === 1) {
      this.registeredForSourceDisposable = this.registerForSource(source);
    }
    if (this.refTotalCount === 1) {
      this.registeredDisposable = this.register();
    }
    return import_coc52.Disposable.create(() => {
      var _a2, _b;
      binding.refCount[type] -= 1;
      binding.refCount.total -= 1;
      if (binding.refCount.total === 0) {
        (_a2 = this.registeredForSourceDisposable) == null ? void 0 : _a2.dispose();
        this.registeredForSourceDisposable = void 0;
      }
      if (this.refTotalCount === 0) {
        (_b = this.registeredDisposable) == null ? void 0 : _b.dispose();
        this.registeredDisposable = void 0;
      }
    });
  }
  register() {
    return internalEvents.on("CocDiagnosticChange", () => {
      this.reloadDebounceSubject.next(this.sources);
    });
  }
  registerForSource(source) {
    const reload = source.events.on("loaded", async (node) => {
      const directory = "isRoot" in node ? source.root : node.expandable ? node.fullpath : node.fullpath && import_path14.default.dirname(node.fullpath);
      if (directory) {
        this.reloadDebounceSubject.next([source]);
      }
    });
    const updateMark = source.events.on("drawn", () => {
      for (const [nodeIndex, node] of source.view.flattenedNodes.entries()) {
        if (!node.fullpath) {
          continue;
        }
        const errorCount = diagnosticManager.getMixedError(node.fullpath);
        const warningCount = diagnosticManager.getMixedWarning(node.fullpath);
        let errorMark = false;
        let warningMark = false;
        if (errorCount || warningCount) {
          const display = !(node.expandable && source.view.isExpanded(node));
          if (errorCount && display) {
            errorMark = true;
          }
          if (warningCount && display) {
            warningMark = true;
          }
        }
        if (errorMark) {
          source.locator.mark.add("diagnosticError", nodeIndex);
        } else {
          source.locator.mark.remove("diagnosticError", nodeIndex);
        }
        if (warningMark) {
          source.locator.mark.add("diagnosticWarning", nodeIndex);
        } else {
          source.locator.mark.remove("diagnosticWarning", nodeIndex);
        }
      }
    });
    return import_coc52.Disposable.create(() => {
      reload.dispose();
      updateMark.dispose();
    });
  }
  async reload(sources) {
    const types2 = this.diagnosticTypes;
    await diagnosticManager.reload(types2);
    const updatePaths = /* @__PURE__ */ new Set();
    if (types2.includes("error")) {
      for (const [fullpath] of this.prevErrorMixedCount) {
        updatePaths.add(fullpath);
      }
      const newErrorMixedCount = new Map(diagnosticManager.getMixedErrors());
      for (const [fullpath] of newErrorMixedCount) {
        updatePaths.add(fullpath);
      }
      this.prevErrorMixedCount = newErrorMixedCount;
    }
    if (types2.includes("warning")) {
      for (const [fullpath] of this.prevWarningMixedCount) {
        updatePaths.add(fullpath);
      }
      const newWarningMixedCount = new Map(
        diagnosticManager.getMixedWarnings()
      );
      for (const [fullpath] of newWarningMixedCount) {
        updatePaths.add(fullpath);
      }
      this.prevWarningMixedCount = newWarningMixedCount;
    }
    for (const source of sources) {
      await source.view.renderPaths(updatePaths);
    }
  }
};

// src/diagnostic/manager.ts
var DiagnosticManager = class {
  constructor() {
    /**
     * errorMixedCountCache[filepath] = count
     **/
    this.errorMixedCountCache = /* @__PURE__ */ new Map();
    /**
     * warningMixedCountCache[filepath] = count
     **/
    this.warningMixedCountCache = /* @__PURE__ */ new Map();
    this.binder = new DiagnosticBinder();
  }
  /**
   * Automatically update column, when diagnostics changed
   *
   * @example
   * ```typescript
   * columnRegistrar.registerColumn(
   *   'columnType',
   *   'columnName',
   *   ({ source, subscriptions }) => {
   *     return {
   *       async init() {
   *         subscriptions.push(diagnosticManager.bindColumn(
   *           source,
   *           ['error', 'warning']
   *         ));
   *       },
   *       async draw() {
   *         ...
   *       },
   *     };
   *   },
   * );
   * ```
   */
  bindColumn(source, types2) {
    const typeSet = new Set(types2);
    const disposables = [];
    for (const type of typeSet) {
      disposables.push(this.binder.bind(source, type));
    }
    return import_coc53.Disposable.create(() => {
      (0, import_coc53.disposeAll)(disposables);
    });
  }
  async reload(types2) {
    const typeSet = new Set(types2);
    const errorPathCount = /* @__PURE__ */ new Map();
    const warningPathCount = /* @__PURE__ */ new Map();
    for (const diagnostic of await import_coc53.diagnosticManager.getDiagnosticList()) {
      const uri = diagnostic.location.uri;
      const path3 = normalizePath(import_coc53.Uri.parse(uri).fsPath);
      if (diagnostic.severity === "Error") {
        const count = errorPathCount.get(path3);
        errorPathCount.set(path3, (count ?? 0) + 1);
      } else {
        const count = warningPathCount.get(path3);
        warningPathCount.set(path3, (count ?? 0) + 1);
      }
    }
    if (typeSet.has("error")) {
      this.reloadMixedErrors(errorPathCount);
    }
    if (typeSet.has("warning")) {
      this.reloadMixedWarnings(warningPathCount);
    }
  }
  reloadMixedErrors(errorPathCount) {
    const errorMixedCount = /* @__PURE__ */ new Map();
    for (const [fullpath, count] of errorPathCount) {
      const parts = fullpath.split(import_path15.default.sep);
      for (let i = 1; i <= parts.length; i++) {
        const frontalPath = parts.slice(0, i).join(import_path15.default.sep);
        const existCount = errorMixedCount.get(frontalPath);
        errorMixedCount.set(frontalPath, (existCount ?? 0) + count);
      }
    }
    this.errorMixedCountCache = errorMixedCount;
  }
  reloadMixedWarnings(warningPathCount) {
    const warningMixedCount = /* @__PURE__ */ new Map();
    for (const [fullpath, count] of warningPathCount) {
      const parts = fullpath.split(import_path15.default.sep);
      for (let i = 1; i <= parts.length; i++) {
        const frontalPath = parts.slice(0, i).join(import_path15.default.sep);
        const existCount = warningMixedCount.get(frontalPath);
        warningMixedCount.set(frontalPath, (existCount ?? 0) + count);
      }
    }
    this.warningMixedCountCache = warningMixedCount;
  }
  getMixedErrors() {
    return this.errorMixedCountCache;
  }
  getMixedWarnings() {
    return this.warningMixedCountCache;
  }
  getMixedError(fullpath) {
    return this.errorMixedCountCache.get(fullpath);
  }
  getMixedWarning(fullpath) {
    return this.warningMixedCountCache.get(fullpath);
  }
};
var diagnosticManager = new DiagnosticManager();

// src/source/sources/file/fileSource.ts
var import_coc61 = require("coc.nvim");
var import_fs13 = __toESM(require("fs"));
var import_os4 = require("os");
var import_path20 = __toESM(require("path"));

// src/diagnostic/highlights.ts
var hlg3 = hlGroupManager.linkGroup.bind(hlGroupManager);
var diagnosticHighlights = {
  diagnosticError: hlg3(
    "DiagnosticError",
    internalHighlightGroups.CocErrorSignColor
  ),
  diagnosticWarning: hlg3(
    "DiagnosticWarning",
    internalHighlightGroups.CocWarningSignColor
  )
};

// src/lists/files.ts
var import_child_process2 = require("child_process");
var import_coc54 = require("coc.nvim");
var import_events7 = require("events");
var import_minimatch9 = __toESM(require_minimatch());
var import_path16 = __toESM(require("path"));
var import_readline2 = __toESM(require("readline"));
var Task = class extends import_events7.EventEmitter {
  constructor() {
    super(...arguments);
    this.processes = [];
  }
  start(cmd, args, cwds, excludePatterns) {
    let remain = cwds.length;
    for (const cwd of cwds) {
      const process3 = (0, import_child_process2.spawn)(cmd, args, { cwd });
      this.processes.push(process3);
      process3.on("error", (e) => {
        this.emit("error", e.message);
      });
      const rl = import_readline2.default.createInterface(process3.stdout);
      const range = import_coc54.Range.create(0, 0, 0, 0);
      const hasPattern = excludePatterns.length > 0;
      process3.stderr.on("data", (chunk) => {
        console.error(chunk.toString("utf8"));
      });
      rl.on("line", (line) => {
        const file = import_path16.default.join(cwd, line);
        if (hasPattern && excludePatterns.some((p) => (0, import_minimatch9.default)(file, p))) {
          return;
        }
        const finalPath = file.replace(/\/$/, "");
        const location = import_coc54.Location.create(import_coc54.Uri.file(finalPath).toString(), range);
        this.emit("data", {
          label: line,
          location
        });
      });
      rl.on("close", () => {
        remain -= 1;
        if (remain === 0) {
          this.emit("end");
        }
      });
    }
  }
  dispose() {
    for (const process3 of this.processes) {
      if (!process3.killed) {
        process3.kill();
      }
    }
  }
};
var config3 = import_coc54.workspace.getConfiguration("list.source.files");
async function getCommand(arg) {
  const args = [];
  if (await executable("fd")) {
    args.push("--color", "never");
    if (arg.showIgnores) {
      args.push("--no-ignore");
    }
    if (arg.showHidden) {
      args.push("--hidden");
    }
    if (!arg.recursive) {
      args.push("--max-depth", "1");
    }
    return { name: "fd", args };
  } else if (isWindows2) {
    args.push("/a-D", "/B");
    if (arg.recursive) {
      args.push("/S");
    }
    return { name: "dir", args };
  } else if (await executable("find")) {
    args.push(".");
    if (!arg.recursive) {
      args.push("-maxdepth", "1");
    }
    return { name: "find", args };
  } else {
    throw new Error("Unable to find command for files list.");
  }
}
var fileList = registerList({
  name: "explorerFiles",
  defaultAction: "reveal",
  async loadItems(arg) {
    if (!arg.rootPath) {
      return;
    }
    const cmd = await getCommand(arg);
    logger.info(`file list task cmd: ${cmd.name}`);
    const task = new Task();
    const excludePatterns = config3.get("excludePatterns", []);
    task.start(cmd.name, cmd.args, [arg.rootPath], excludePatterns);
    return task;
  },
  init() {
    this.addLocationActions();
    this.addAction("reveal", async ({ arg, item: { location } }) => {
      const loc = await this.convertLocation(location);
      if (arg.revealCallback) {
        await arg.revealCallback(loc);
      }
    });
  }
});

// src/source/sources/file/argOptions.ts
var fileArgOptions = {
  fileRootTemplate: Args.registerOption("file-root-template", {
    getDefault: () => config.get("file.root.template")
  }),
  fileRootLabelingTemplate: Args.registerOption(
    "file-root-labeling-template",
    {
      getDefault: () => config.get("file.root.labelingTemplate")
    }
  ),
  fileChildTemplate: Args.registerOption("file-child-template", {
    getDefault: () => config.get("file.child.template")
  }),
  fileChildLabelingTemplate: Args.registerOption(
    "file-child-labeling-template",
    {
      getDefault: () => config.get("file.child.labelingTemplate")
    }
  )
};

// src/source/sources/file/fileActions.ts
var import_coc57 = require("coc.nvim");
var import_open = __toESM(require_open());
var import_path17 = __toESM(require("path"));

// src/lists/drives.ts
var import_coc55 = require("coc.nvim");
var driveList = registerList({
  name: "explorerDrives",
  defaultAction: "do",
  async loadItems(drives) {
    return drives.map((drive) => ({
      label: drive.name,
      data: drive
    }));
  },
  doHighlight() {
    const { nvim } = import_coc55.workspace;
    nvim.pauseNotification();
    nvim.command("syntax match CocExplorerDriveName /\\v^[\\w:]+/", true);
    nvim.command("highlight default link CocExplorerDriveName PreProc", true);
    nvim.resumeNotification().catch(logger.error);
  },
  init() {
    this.addAction("do", async ({ item }) => {
      await item.data.callback(item.data.name);
    });
  }
});

// src/lists/workspaceFolders.ts
var import_coc56 = require("coc.nvim");
var explorerWorkspaceFolderList = registerList({
  defaultAction: "do",
  name: "ExplorerWorkspaceFolders",
  async loadItems(fileSource) {
    return import_coc56.workspace.folderPaths.map((path3) => ({
      label: path3,
      data: {
        path: path3,
        callback: () => {
          fileSource.action.doAction("cd", [], [path3]).catch(logger.error);
        }
      }
    }));
  },
  init() {
    this.addAction("do", ({ item }) => {
      item.data.callback();
    });
  },
  doHighlight() {
    const { nvim } = import_coc56.workspace;
    nvim.pauseNotification();
    nvim.command("syntax match CocExplorerWorkspaceFolder /\\v^.*/", true);
    nvim.command(
      "highlight default link CocExplorerWorkspaceFolder PreProc",
      true
    );
    nvim.resumeNotification().catch(logger.error);
  }
});

// src/source/sources/file/fileActions.ts
function loadFileActions(action) {
  const { nvim } = import_coc57.workspace;
  const file = action.owner;
  action.addNodeAction(
    "gotoParent",
    async () => {
      var _a2;
      if (file.root === "") {
        return;
      }
      const nodeUid = (_a2 = file.view.currentNode()) == null ? void 0 : _a2.uid;
      if (/^[A-Za-z]:[\\/]$/.test(file.root)) {
        file.root = "";
      } else {
        file.root = import_path17.default.dirname(file.root);
        await file.cd(file.root);
      }
      await file.view.expand(file.view.rootNode);
      if (nodeUid) {
        await file.locator.gotoNodeUid(nodeUid);
      }
    },
    "change directory to parent directory"
  );
  action.addNodeAction(
    "rootStrategies",
    ({ args }) => {
      const originalRootStrategies = args[0];
      if (originalRootStrategies)
        file.rootStrategies = originalRootStrategies.split(",");
    },
    "change root strategies",
    {
      args: [
        {
          name: "root strategies",
          description: `root strategies of ${rootStrategyList.join(" | ")}`
        }
      ],
      menus: {
        "workspace,cwd,sourceBuffer,reveal": "default",
        keep: "keep current root"
      }
    }
  );
  action.addNodeAction(
    "resolveRoot",
    async ({ args, node }) => {
      var _a2;
      const targetPath = args[0];
      const root2 = await ((_a2 = file.explorer.rooter) == null ? void 0 : _a2.resolveRoot(
        targetPath,
        file.rootStrategies
      ));
      if (root2)
        await action.doAction("cd", node, [root2]);
    },
    "resolve and change directory to root",
    {
      args: [
        {
          name: "reveal path",
          description: "path string"
        }
      ],
      menus: {
        path: {
          description: "use custom path",
          args: "<reveal-path>",
          async actionArgs() {
            var _a2;
            return [
              await input(
                "input a reveal path:",
                ((_a2 = file.view.currentNode()) == null ? void 0 : _a2.fullpath) ?? "",
                "file"
              )
            ];
          }
        }
      }
    }
  );
  action.addNodeAction(
    "reveal",
    async ({ node, args }) => {
      var _a2;
      const target = args.at(0) ?? "previousWindow";
      let targetBufnr;
      let targetPath = "";
      if (/\d+/.test(target)) {
        targetBufnr = parseInt(target, 10);
        if (targetBufnr === 0) {
          targetBufnr = await currentBufnr();
        }
      } else {
        const revealStrategy = target;
        const actions = {
          select: async () => {
            await selectWindowsUI(file.explorer.config, file.sourceType, {
              onSelect: async (winnr) => {
                targetBufnr = await bufnrByWinnrOrWinid(winnr);
              }
            });
          },
          sourceWindow: async () => {
            targetBufnr = await bufnrByWinnrOrWinid(
              await file.explorer.sourceWinnr()
            );
          },
          previousBuffer: async () => {
            targetBufnr = await file.explorer.explorerManager.previousBufnr.get();
          },
          previousWindow: async () => {
            targetBufnr = await bufnrByWinnrOrWinid(
              await file.explorer.explorerManager.prevWinnrByPrevWindowID()
            );
          },
          path: async () => {
            var _a3;
            const tPath = args[1];
            targetPath = tPath ? tPath : await input(
              "Input a reveal path:",
              ((_a3 = file.view.currentNode()) == null ? void 0 : _a3.fullpath) ?? "",
              "file"
            );
          }
        };
        await ((_a2 = actions[revealStrategy]) == null ? void 0 : _a2.call(actions));
      }
      if (targetBufnr) {
        const bufinfo = await nvim.call("getbufinfo", [targetBufnr]);
        if (!bufinfo[0] || !bufinfo[0].name) {
          return;
        }
        targetPath = bufinfo[0].name;
      }
      if (!targetPath) {
        return;
      }
      if (!isParentFolder(file.root, targetPath)) {
        await action.doAction("resolveRoot", node, [targetPath]);
      }
      await file.view.sync(async (r) => {
        const expandOptions = args[1] ?? "";
        const compact = expandOptions.includes("compact") || void 0;
        const [revealNode, notifiers] = await file.revealNodeByPathNotifier(
          r,
          targetPath,
          {
            compact
          }
        );
        if (revealNode) {
          await Notifier.runAll(notifiers);
        }
      });
    },
    "reveal buffer in explorer",
    {
      args: [
        {
          name: "target",
          description: `bufnr number | ${revealStrategyList.join(" | ")}`
        }
      ],
      menus: {
        "0": "use current buffer",
        "0:compact": "use current buffer and compact",
        select: "use select windows UI",
        previousBuffer: "use last used buffer",
        previousWindow: "use last used window",
        sourceWindow: "use the window where explorer opened",
        path: {
          description: "use custom path",
          args: "path:<path>",
          async actionArgs() {
            return ["path"];
          }
        }
      }
    }
  );
  action.addNodeAction(
    "cd",
    async ({ node, args }) => {
      const cdTo = async (fullpath) => {
        await file.cd(fullpath);
        file.root = fullpath;
        await file.view.expand(file.view.rootNode);
      };
      const path3 = args.at(0);
      if (path3 !== void 0) {
        await cdTo(path3);
      } else {
        if (node.directory) {
          await cdTo(node.fullpath);
        }
      }
    },
    "change directory to current node",
    {
      args: [
        {
          name: "path"
        }
      ],
      menus: {
        path: {
          description: "",
          args: "<path>",
          async actionArgs() {
            var _a2;
            return [
              await input(
                "input a cd path:",
                ((_a2 = file.view.currentNode()) == null ? void 0 : _a2.fullpath) ?? "",
                "file"
              )
            ];
          }
        }
      }
    }
  );
  action.addNodeAction(
    "workspaceFolders",
    async () => {
      await startCocList(file.explorer, explorerWorkspaceFolderList, file, [
        "--normal"
      ]);
    },
    "change directory to current node"
  );
  action.addNodeAction(
    "drop",
    async ({ node }) => {
      if (!node.directory) {
        const quitNotifier = await file.explorer.tryQuitOnOpenNotifier();
        nvim.pauseNotification();
        nvim.command(`drop ${node.fullpath}`, true);
        quitNotifier.notify();
        await nvim.resumeNotification();
      }
    },
    "open file by drop command",
    { select: true }
  );
  action.addNodesAction(
    "copyFilepath",
    async ({ nodes }) => {
      await file.copyToClipboard(nodes.map((it) => it.fullpath).join("\n"));
      await import_coc57.window.showInformationMessage("Copy filepath to clipboard");
    },
    "copy full filepath to clipboard"
  );
  action.addNodesAction(
    "copyRelativeFilepath",
    async ({ nodes }) => {
      await file.copyToClipboard(
        nodes.map((it) => import_path17.default.relative(file.root, it.fullpath)).join("\n")
      );
      await import_coc57.window.showInformationMessage(
        "Copy relative filepath to clipboard"
      );
    },
    "copy relative filepath to clipboard"
  );
  action.addNodesAction(
    "copyFilename",
    async ({ nodes }) => {
      await file.copyToClipboard(nodes.map((it) => it.name).join("\n"));
      await import_coc57.window.showInformationMessage("Copy filename to clipboard");
    },
    "copy filename to clipboard"
  );
  const copyOrCutFileOptions = {
    args: [
      {
        name: "type",
        description: `${copyOrCutFileTypeList.join(" | ")}, default: replace`
      }
    ],
    menus: {
      toggle: "toggle copy/cut",
      append: "append to copy/cut",
      replace: "replace copy/cut "
    }
  };
  action.addNodesAction(
    "copyFile",
    async ({ nodes, args }) => {
      const type = args[0] ?? "replace";
      const clipboardStorage = file.explorer.explorerManager.clipboardStorage;
      switch (type) {
        case "replace": {
          const content = await clipboardStorage.getFiles();
          const oldNodes = file.getNodesByPaths(content.fullpaths);
          file.view.requestRenderNodes(oldNodes);
          await clipboardStorage.setFiles(
            "copy",
            nodes.map((it) => it.fullpath)
          );
          break;
        }
        case "toggle": {
          const content = await clipboardStorage.getFiles();
          const fullpathSet = new Set(content.fullpaths);
          for (const node of nodes) {
            if (fullpathSet.has(node.fullpath)) {
              fullpathSet.delete(node.fullpath);
            } else {
              fullpathSet.add(node.fullpath);
            }
          }
          await clipboardStorage.setFiles("copy", [...fullpathSet]);
          break;
        }
        case "append": {
          const content = await clipboardStorage.getFiles();
          const fullpathSet = new Set(content.fullpaths);
          for (const node of nodes) {
            fullpathSet.add(node.fullpath);
          }
          await clipboardStorage.setFiles("copy", [...fullpathSet]);
          break;
        }
      }
      file.view.requestRenderNodes(nodes);
    },
    "copy file for paste",
    copyOrCutFileOptions
  );
  action.addNodesAction(
    "cutFile",
    async ({ nodes, args }) => {
      const type = args[0] ?? "replace";
      const clipboardStorage = file.explorer.explorerManager.clipboardStorage;
      switch (type) {
        case "replace": {
          const content = await clipboardStorage.getFiles();
          const oldNodes = file.getNodesByPaths(content.fullpaths);
          file.view.requestRenderNodes(oldNodes);
          await clipboardStorage.setFiles(
            "cut",
            nodes.map((it) => it.fullpath)
          );
          break;
        }
        case "toggle": {
          const content = await clipboardStorage.getFiles();
          const fullpathSet = new Set(content.fullpaths);
          for (const node of nodes) {
            if (fullpathSet.has(node.fullpath)) {
              fullpathSet.delete(node.fullpath);
            } else {
              fullpathSet.add(node.fullpath);
            }
          }
          await clipboardStorage.setFiles("cut", [...fullpathSet]);
          break;
        }
        case "append": {
          const content = await clipboardStorage.getFiles();
          const fullpathSet = new Set(content.fullpaths);
          for (const node of nodes) {
            fullpathSet.add(node.fullpath);
          }
          await clipboardStorage.setFiles("cut", [...fullpathSet]);
          break;
        }
      }
      file.view.requestRenderNodes(nodes);
    },
    "cut file for paste",
    copyOrCutFileOptions
  );
  action.addNodeAction(
    "clearCopyOrCut",
    async () => {
      const clipboardStorage = file.explorer.explorerManager.clipboardStorage;
      const content = await clipboardStorage.getFiles();
      await clipboardStorage.clear();
      file.view.requestRenderNodes(file.getNodesByPaths(content.fullpaths));
    },
    "clear cut/copy clipboard of files"
  );
  action.addNodeAction(
    "pasteFile",
    async ({ node }) => {
      const clipboardStorage = file.explorer.explorerManager.clipboardStorage;
      const content = await clipboardStorage.getFiles();
      if (content.type === "none" || content.fullpaths.length <= 0) {
        await import_coc57.window.showInformationMessage(
          "Copied or cut files is empty",
          "error"
        );
        return;
      }
      const fullpaths = content.fullpaths;
      const targetNode = file.getPutTargetNode(node);
      const targetDir = targetNode.fullpath;
      let overwriteResult;
      switch (content.type) {
        case "copy":
          overwriteResult = await overwritePrompt(
            "paste",
            fullpaths.map((fullpath2) => ({
              source: fullpath2,
              target: import_path17.default.join(targetDir, import_path17.default.basename(fullpath2))
            })),
            fsCopyFileRecursive
          );
          break;
        case "cut":
          overwriteResult = await overwritePrompt(
            "paste",
            fullpaths.map((fullpath2) => ({
              source: fullpath2,
              target: import_path17.default.join(targetDir, import_path17.default.basename(fullpath2))
            })),
            fsRename
          );
          await clipboardStorage.setFiles("cut", overwriteResult.endFullpaths);
          break;
      }
      await file.load(file.view.rootNode);
      const fullpath = fullpaths[0];
      if (fullpath)
        await file.view.sync(async (r) => {
          await file.revealNodeByPathNotifier(r, fullpath, {
            startNode: targetNode
          });
        });
    },
    "paste files to here"
  );
  action.addNodesAction(
    "delete",
    async ({ nodes }) => {
      if (nodes.some(
        (node) => file.bufManager.modified(node.fullpath, {
          directory: node.directory
        })
      ) && await prompt("Buffer is being modified, discard it?") !== "yes") {
        return;
      }
      const list = nodes.map((node) => node.fullpath).join("\n");
      if (await prompt(`Move these files or directories to trash?
${list}`) !== "yes") {
        return;
      }
      await fsTrash(nodes.map((node) => node.fullpath));
      for (const node of nodes) {
        await file.bufManager.remove(node.fullpath, {
          skipModified: true,
          bwipeout: true,
          directory: node.directory
        });
      }
    },
    "move file or directory to trash",
    { reload: true }
  );
  action.addNodesAction(
    "deleteForever",
    async ({ nodes }) => {
      if (nodes.some(
        (node) => file.bufManager.modified(node.fullpath, {
          directory: node.directory
        })
      ) && await prompt("Buffer is being modified, discard it?") !== "yes") {
        return;
      }
      const list = nodes.map((node) => node.fullpath).join("\n");
      if (await prompt(
        `Delete these files or directories permanently?
${list}`
      ) !== "yes") {
        return;
      }
      for (const node of nodes) {
        await fsRemove(node.fullpath, void 0);
        await file.bufManager.remove(node.fullpath, {
          skipModified: true,
          bwipeout: true,
          directory: node.directory
        });
      }
    },
    "delete file or directory permanently",
    { reload: true }
  );
  action.addNodeAction(
    "addFile",
    async ({ node, args }) => {
      let filename;
      const promptText = "Input a new filename:";
      if (args[0]) {
        filename = args[0];
      } else {
        filename = await input(promptText, "", "file");
      }
      filename = filename.trim();
      if (!filename) {
        return;
      }
      if (["/", "\\"].includes(filename[filename.length - 1])) {
        await action.doAction("addDirectory", node, [filename]);
        return;
      }
      const putTargetNode = file.getPutTargetNode(node);
      const targetPath = import_path17.default.join(putTargetNode.fullpath, filename);
      await overwritePrompt(
        "add file",
        [
          {
            source: void 0,
            target: targetPath
          }
        ],
        async (_source, target) => {
          await fsTouch(target);
        }
      );
      await file.view.sync(async (r) => {
        const loadNode = putTargetNode.parent ?? putTargetNode;
        const reloadNotifier = await file.loadNotifier(r, loadNode);
        const [, notifiers] = await file.revealNodeByPathNotifier(
          r,
          targetPath.replace(/(\/|\\)$/, ""),
          {
            startNode: loadNode
          }
        );
        await Notifier.runAll([reloadNotifier, ...notifiers]);
      });
    },
    "add a new file"
  );
  action.addNodeAction(
    "addDirectory",
    async ({ node, args }) => {
      let directoryName = args[0] ?? await input("Input a new directory name:", "", "file");
      directoryName = directoryName.trim().replace(/(\/|\\)*$/g, "");
      if (!directoryName) {
        return;
      }
      const putTargetNode = file.getPutTargetNode(node);
      const targetPath = import_path17.default.join(putTargetNode.fullpath, directoryName);
      await overwritePrompt(
        "add directory",
        [
          {
            source: void 0,
            target: targetPath
          }
        ],
        async (_source, target) => {
          await fsMkdirp(target);
        }
      );
      await file.view.sync(async (r) => {
        const revealRoot = putTargetNode.parent ?? putTargetNode;
        const reloadNotifier = await file.loadNotifier(r, revealRoot);
        const [, revealNotifiers] = await file.revealNodeByPathNotifier(
          r,
          targetPath,
          {
            startNode: revealRoot
          }
        );
        await Notifier.runAll([reloadNotifier, ...revealNotifiers]);
      });
    },
    "add a new directory"
  );
  action.addNodeAction(
    "rename",
    async ({ node }) => {
      if (file.bufManager.modified(node.fullpath, {
        directory: node.directory
      }) && await prompt("Buffer is being modified, discard it?") !== "yes") {
        return;
      }
      const dir = import_path17.default.dirname(node.fullpath);
      const basename2 = import_path17.default.basename(node.fullpath);
      let targetBasename = await input(`Rename: `, basename2, "file");
      targetBasename = targetBasename.trim();
      if (!targetBasename)
        return;
      const targetPath = import_path17.default.join(dir, targetBasename);
      await overwritePrompt(
        "rename",
        [
          {
            source: node.fullpath,
            target: targetPath
          }
        ],
        fsRename
      );
      await file.bufManager.replace(node.fullpath, targetPath, {
        skipModified: true,
        bwipeout: true,
        directory: node.directory
      });
    },
    "rename a file or directory",
    { reload: true }
  );
  action.addNodesAction(
    "systemExecute",
    async ({ nodes }) => {
      await Promise.all(nodes.map((node) => (0, import_open.default)(node.fullpath)));
    },
    "use system application open file or directory"
  );
  if (isWindows2) {
    action.addNodeAction(
      "listDrive",
      async () => {
        const drives = await listDrive();
        await startCocList(
          file.explorer,
          driveList,
          drives.map((drive) => ({
            name: drive,
            callback: async (drive2) => {
              file.root = drive2;
              await file.view.expand(file.view.rootNode);
            }
          })),
          ["--normal", "--number-select"]
        );
      },
      "list drives"
    );
  }
  action.addNodeAction(
    "search",
    async ({ node, args }) => {
      const searchOptions = (args[0] ?? "").split("|");
      const recursive = searchOptions.includes("recursive");
      const strict = searchOptions.includes("strict");
      const noIgnore = searchOptions.includes("noIgnore");
      await file.searchByCocList(
        node.isRoot ? node.fullpath : import_path17.default.dirname(node.fullpath),
        { recursive, noIgnore, strict }
      );
    },
    "search by coc-list, the ignore function requires the fd command",
    {
      args: [
        {
          name: "search options",
          description: searchOptionList.join(" | ")
        }
      ],
      menus: {
        noIgnore: "no ignore",
        recursive: "recursively",
        "recursive|noIgnore": "recursively and no ignore",
        strict: "exact match",
        "recursive|strict": "recursively and strict"
      }
    }
  );
  action.addNodeAction(
    "toggleOnlyGitChange",
    async () => {
      file.showOnlyGitChange = !file.showOnlyGitChange;
      await file.view.sync(async (r) => {
        const loadNotifier = await file.loadNotifier(r, file.view.rootNode, {
          force: true
        });
        nvim.pauseNotification();
        file.highlight.clearHighlightsNotify();
        loadNotifier.notify();
        await nvim.resumeNotification();
      });
    },
    "toggle visibility of git change node",
    { reload: true }
  );
}

// src/source/sources/file/fileColumnRegistrar.ts
var FileColumnRegistrar = class extends ColumnRegistrar {
};
var fileColumnRegistrar = new FileColumnRegistrar();

// src/source/sources/file/root-columns/icon.ts
fileColumnRegistrar.registerColumn("root", "icon", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(
          source.view.isExpanded(node) ? source.icons.expanded : source.icons.collapsed,
          { hl: fileHighlights.expandIcon }
        );
      }
    };
  }
}));

// src/source/sources/file/root-columns/git.ts
fileColumnRegistrar.registerColumn(
  "root",
  "git",
  ({ source, subscriptions }) => {
    const icons = getRootStatusIcons(source.config);
    return {
      init() {
        subscriptions.push(gitManager.bindColumn(source));
      },
      async draw() {
        return {
          labelVisible({ node }) {
            var _a2;
            return !!((_a2 = gitManager.getRootStatus(node.fullpath)) == null ? void 0 : _a2.formats.length);
          },
          async available() {
            return await gitManager.cmd.available();
          },
          drawNode(row, { node, isLabeling }) {
            const status = gitManager.getRootStatus(node.fullpath);
            if (status == null ? void 0 : status.formats.length) {
              const statusChars = [];
              for (const f of status.formats) {
                if (isLabeling) {
                  statusChars.push(`${icons[f].name}(${icons[f].icon})`);
                } else {
                  statusChars.push(icons[f].icon);
                }
              }
              const hl = status.allStaged ? gitHighlights.staged : gitHighlights.unstaged;
              if (isLabeling) {
                row.add(statusChars.join(" & "), {
                  hl
                });
              } else {
                row.add(`{${statusChars.join("")}}`, {
                  hl
                });
              }
            }
          }
        };
      }
    };
  }
);

// src/source/sources/file/root-columns/title.ts
fileColumnRegistrar.registerColumn("root", "title", () => ({
  draw() {
    return {
      drawNode(row) {
        row.add("[FILE]", {
          hl: fileHighlights.title
        });
      }
    };
  }
}));

// src/source/sources/file/root-columns/hidden.ts
fileColumnRegistrar.registerColumn("root", "hidden", ({ source }) => ({
  draw() {
    return {
      drawNode(row) {
        row.add(source.showHidden ? source.icons.hidden : "", {
          hl: fileHighlights.hidden
        });
      }
    };
  }
}));

// src/source/sources/file/root-columns/root.ts
var import_path18 = __toESM(require("path"));
fileColumnRegistrar.registerColumn("root", "root", ({ source }) => ({
  draw() {
    return {
      drawNode(row) {
        row.add(import_path18.default.basename(source.root), { hl: fileHighlights.rootName });
      }
    };
  }
}));

// src/source/sources/file/root-columns/fullpath.ts
fileColumnRegistrar.registerColumn("root", "fullpath", () => ({
  draw() {
    return {
      drawNode(row, { node, isLabeling }) {
        row.add(displayedFullpath(node.fullpath), {
          hl: isLabeling ? fileHighlights.directory : fileHighlights.fullpath
        });
      }
    };
  }
}));

// src/source/sources/file/child-columns/git.ts
fileColumnRegistrar.registerColumn(
  "child",
  "git",
  ({ source, subscriptions }) => {
    const filenameHighlight = new FilenameHighlight(source.config);
    const icons = getStatusIcons(source.config);
    const getHighlight = (fullpath, staged, isDirectory) => {
      if (staged) {
        return gitHighlights.staged;
      } else {
        return filenameHighlight.getHighlight(fullpath, isDirectory, ["git"]) ?? gitHighlights.unstaged;
      }
    };
    return {
      init() {
        subscriptions.push(gitManager.bindColumn(source));
      },
      async available() {
        return await gitManager.cmd.available();
      },
      async draw() {
        return {
          async labelVisible({ node }) {
            const status = gitManager.getMixedStatus(
              node.fullpath,
              node.directory
            );
            if (!status) {
              return false;
            }
            return status.x !== " " /* unmodified */ || status.y !== " " /* unmodified */;
          },
          drawNode(row, { node, nodeIndex, isLabeling }) {
            const showFormat = (f, staged) => {
              const hl = getHighlight(node.fullpath, staged, node.directory);
              if (isLabeling) {
                row.add(`${icons[f].name}(${icons[f].icon})`, {
                  hl
                });
              } else {
                row.add(icons[f].icon, {
                  hl
                });
              }
            };
            const status = gitManager.getMixedStatus(
              node.fullpath,
              node.directory
            );
            if (status) {
              showFormat(status.x, true);
              if (isLabeling) {
                row.add(" ");
              }
              showFormat(status.y, false);
              if (status.x === "!" /* ignored */) {
                source.locator.mark.remove("git", nodeIndex);
                source.locator.mark.remove("gitStaged", nodeIndex);
                source.locator.mark.remove("gitUnstaged", nodeIndex);
              } else {
                source.locator.mark.add("git", nodeIndex);
                if (status.x !== " " /* unmodified */) {
                  source.locator.mark.add("gitStaged", nodeIndex);
                } else {
                  source.locator.mark.remove("gitStaged", nodeIndex);
                }
                if (status.y !== " " /* unmodified */) {
                  source.locator.mark.add("gitUnstaged", nodeIndex);
                } else {
                  source.locator.mark.remove("gitUnstaged", nodeIndex);
                }
              }
            } else {
              source.locator.mark.remove("git", nodeIndex);
              source.locator.mark.remove("gitStaged", nodeIndex);
              source.locator.mark.remove("gitUnstaged", nodeIndex);
            }
          }
        };
      }
    };
  }
);

// src/source/sources/file/child-columns/selection.ts
fileColumnRegistrar.registerColumn("child", "selection", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (source.isSelectedNode(node)) {
          row.add(source.icons.selected);
        }
      }
    };
  }
}));

// src/icon/loader.ts
var IconLoader = class {
};
var getLoaders = /* @__PURE__ */ new Map();
function registerLoader(iconSourceType, getLoader2) {
  getLoaders.set(iconSourceType, getLoader2);
}
var loadersCache = /* @__PURE__ */ new Map();
function getLoader(source) {
  if (!loadersCache.has(source)) {
    const getLoader2 = getLoaders.get(source);
    if (!getLoader2) {
      return;
    }
    loadersCache.set(source, getLoader2());
  }
  return loadersCache.get(source);
}

// src/icon/nerdfont.ts
var import_color_convert4 = __toESM(require_color_convert());

// src/icon/icons.nerdfont.json
var icons_nerdfont_default = {
  $schema: "./icons.nerdfont.schema.json",
  icons: {
    folderClosed: {
      code: "\uE5FF",
      color: "#00afaf"
    },
    folderOpened: {
      code: "\uE5FE",
      color: "#00afaf"
    },
    folderSymlink: {
      code: "\uEAED",
      color: "#00afaf"
    },
    folderNpm: {
      code: "\uE5FA",
      color: "#00afaf"
    },
    file: {
      code: "\uF15B",
      color: "#999999"
    },
    fileSymlink: {
      code: "\uF481",
      color: "#999999"
    },
    fileHidden: {
      code: "\uF016",
      color: "#999999"
    },
    excel: {
      code: "\uF1C3",
      color: "#207245"
    },
    word: {
      code: "\uF1C2",
      color: "#185abd"
    },
    ppt: {
      code: "\uF1C4",
      color: "#cb4a32"
    },
    stylus: {
      code: "\uE600",
      color: "#8dc149"
    },
    sass: {
      code: "\uE603",
      color: "#f55385"
    },
    html: {
      code: "\uE60E",
      color: "#e37933"
    },
    xml: {
      code: "\uE60E",
      "code.origin": "\uE619",
      color: "#e37933"
    },
    ejs: {
      code: "\uE618",
      color: "#cbcb41"
    },
    css: {
      code: "\uE614",
      color: "#519aba"
    },
    webpack: {
      code: "\uE6A3",
      color: "#519aba"
    },
    markdown: {
      code: "\uE609",
      color: "#519aba"
    },
    json: {
      code: "\uE60B",
      color: "#cbcb41"
    },
    javascript: {
      code: "\uE60C",
      color: "#cbcb41"
    },
    javascriptreact: {
      code: "\uE7BA",
      color: "#519aba"
    },
    ruby: {
      code: "\uE791",
      color: "#cc3e44"
    },
    php: {
      code: "\uE608",
      color: "#a074c4"
    },
    python: {
      code: "\uE606",
      color: "#519aba"
    },
    coffee: {
      code: "\uE61B",
      color: "#cbcb41"
    },
    mustache: {
      code: "\uE60F",
      color: "#e37933"
    },
    conf: {
      code: "\uE615",
      color: "#6d8086"
    },
    video: {
      code: "\uEAD9",
      color: "#dc5285"
    },
    audio: {
      code: "\uE638",
      color: "#a074c4"
    },
    photoshop: {
      code: "\uE67F",
      color: "#001d34"
    },
    image: {
      code: "\uE60D",
      color: "#a074c4"
    },
    ai: {
      code: "\uE7B4",
      color: "#cbcb41"
    },
    psd: {
      code: "\uE7B8",
      color: "#519aba"
    },
    ico: {
      code: "\uE60D",
      color: "#cbcb41"
    },
    twig: {
      code: "\uE61C",
      color: "#8dc149"
    },
    c: {
      code: "\uE61E",
      color: "#a074c4"
    },
    cpp: {
      code: "\uE61D",
      color: "#519aba"
    },
    h: {
      code: "\uF0FD",
      color: "#a074c4"
    },
    haskell: {
      code: "\uE61F",
      color: "#a074c4"
    },
    lua: {
      code: "\uE620",
      color: "#519aba"
    },
    java: {
      code: "\uE738",
      color: "#cc3e44"
    },
    kotlin: {
      code: "\u0138",
      color: "#5674d4"
    },
    terminal: {
      code: "\uE795",
      color: "#4d5a5e"
    },
    ml: {
      code: "\u03BB",
      color: "#e37933"
    },
    diff: {
      code: "\uE728",
      color: "#41535b"
    },
    sql: {
      code: "\uE706",
      color: "#f55385"
    },
    clojure: {
      code: "\uE768",
      color: "#8dc149"
    },
    edn: {
      code: "\uE76A",
      color: "#519aba"
    },
    scala: {
      code: "\uE737",
      color: "#cc3e44"
    },
    go: {
      code: "\uE627",
      color: "#519aba"
    },
    dart: {
      code: "\uE798",
      color: "#03589C"
    },
    firefox: {
      code: "\uE745",
      color: "#e37933"
    },
    vs: {
      code: "\uE70C",
      color: "#854CC7"
    },
    perl: {
      code: "\uE769",
      color: "#519aba"
    },
    rss: {
      code: "\uE619",
      color: "#fb9d3b"
    },
    csharp: {
      code: "\uE648",
      color: "#519aba"
    },
    fsharp: {
      code: "\uE7A7",
      color: "#519aba"
    },
    rust: {
      code: "\uE7A8",
      color: "#519aba"
    },
    dlang: {
      code: "\uE7AF",
      color: "#cc3e44"
    },
    erlang: {
      code: "\uE7B1",
      color: "#A90533"
    },
    elixir: {
      code: "\uE62D",
      color: "#a074c4"
    },
    elm: {
      code: "\uE62C",
      color: "#519aba"
    },
    mix: {
      code: "\uE62D",
      color: "#cc3e44"
    },
    vim: {
      code: "\uE62B",
      color: "#019833"
    },
    typescript: {
      code: "\uE628",
      color: "#519aba"
    },
    typescriptreact: {
      code: "\uE7BA",
      color: "#519aba"
    },
    julia: {
      code: "\uE624",
      color: "#a074c4"
    },
    puppet: {
      code: "\uF499",
      color: "#cbcb41"
    },
    vue: {
      code: "\uE6A0",
      color: "#8dc149"
    },
    swift: {
      code: "\uE755",
      color: "#e37933"
    },
    git: {
      code: "\uE725",
      color: "#41535b"
    },
    bashrc: {
      code: "\uE615",
      color: "#4d5a5e"
    },
    favicon: {
      code: "\uE623",
      color: "#cbcb41"
    },
    docker: {
      code: "\uE7B0",
      color: "#519aba"
    },
    gruntfile: {
      code: "\uE611",
      color: "#e37933"
    },
    gulpfile: {
      code: "\uE610",
      color: "#cc3e44"
    },
    dropbox: {
      code: "\uE707",
      color: "#0061FE"
    },
    license: {
      code: "\uE60A",
      color: "#cbcb41"
    },
    procfile: {
      code: "\uE607",
      color: "#a074c4"
    },
    jquery: {
      code: "\uE750",
      color: "#1B75BB"
    },
    angular: {
      code: "\uE753",
      color: "#E23237"
    },
    backbone: {
      code: "\uE752",
      color: "#0071B5"
    },
    requirejs: {
      code: "\uE770",
      color: "#F44A41"
    },
    materialize: {
      code: "\uE7B6",
      color: "#EE6E73"
    },
    mootools: {
      code: "\uE78F",
      color: "#ECECEC"
    },
    vagrant: {
      code: "\uF2B8",
      color: "#1563FF"
    },
    svg: {
      code: "\uE698",
      color: "#FFB13B"
    },
    font: {
      code: "\uF031",
      color: "#999999"
    },
    text: {
      code: "\uF15C",
      color: "#999999"
    },
    archive: {
      code: "\uF1C6",
      color: "#cc3e44"
    },
    lock: {
      code: "\uF023",
      color: "#999999"
    }
  },
  extensions: {
    styl: "stylus",
    sass: "sass",
    scss: "sass",
    htm: "html",
    html: "html",
    slim: "html",
    xml: "xml",
    xaml: "xml",
    ejs: "ejs",
    css: "css",
    less: "css",
    md: "markdown",
    mdx: "markdown",
    markdown: "markdown",
    rmd: "markdown",
    lock: "lock",
    json: "json",
    js: "javascript",
    cjs: "javascript",
    mjs: "javascript",
    es6: "javascript",
    jsx: "javascriptreact",
    rb: "ruby",
    ru: "ruby",
    php: "php",
    py: "python",
    pyc: "python",
    pyo: "python",
    pyd: "python",
    coffee: "coffee",
    mustache: "mustache",
    hbs: "mustache",
    config: "conf",
    conf: "conf",
    ini: "conf",
    yml: "conf",
    yaml: "conf",
    toml: "conf",
    avi: "video",
    flv: "video",
    m1v: "video",
    m2v: "video",
    mk3d: "video",
    mks: "video",
    mkv: "video",
    mov: "video",
    movie: "video",
    mp4: "video",
    mp4v: "video",
    mpe: "video",
    mpeg: "video",
    mpg: "video",
    mpg4: "video",
    ogv: "video",
    qt: "video",
    webm: "video",
    wmv: "video",
    aac: "audio",
    m2a: "audio",
    m3a: "audio",
    mid: "audio",
    midi: "audio",
    mp2: "audio",
    mp2a: "audio",
    mp3: "audio",
    mp4a: "audio",
    mpga: "audio",
    oga: "audio",
    ogg: "audio",
    opus: "audio",
    spx: "audio",
    wav: "audio",
    wma: "audio",
    jpg: "image",
    jpe: "image",
    jpeg: "image",
    bmp: "image",
    png: "image",
    gif: "image",
    webp: "image",
    tga: "image",
    tif: "image",
    tiff: "image",
    ai: "ai",
    psd: "psd",
    psb: "psd",
    ico: "ico",
    twig: "twig",
    cpp: "cpp",
    "c++": "cpp",
    cxx: "cpp",
    cc: "cpp",
    cp: "cpp",
    c: "c",
    h: "h",
    hh: "h",
    hpp: "h",
    hxx: "h",
    hs: "haskell",
    lhs: "haskell",
    lua: "lua",
    java: "java",
    jar: "java",
    kt: "kotlin",
    kts: "kotlin",
    sh: "terminal",
    fish: "terminal",
    bash: "terminal",
    zsh: "terminal",
    ksh: "terminal",
    csh: "terminal",
    awk: "terminal",
    ps1: "terminal",
    bat: "terminal",
    cmd: "terminal",
    ml: "ml",
    mli: "ml",
    diff: "diff",
    db: "sql",
    sql: "sql",
    dump: "sql",
    accdb: "sql",
    clj: "clojure",
    cljc: "clojure",
    cljs: "clojure",
    edn: "edn",
    scala: "scala",
    go: "go",
    dart: "dart",
    xul: "firefox",
    pl: "perl",
    pm: "perl",
    t: "perl",
    rss: "rss",
    sln: "vs",
    suo: "vs",
    csproj: "vs",
    cs: "csharp",
    fsscript: "fsharp",
    fsx: "fsharp",
    fs: "fsharp",
    fsi: "fsharp",
    rs: "rust",
    rlib: "rust",
    d: "dlang",
    erl: "erlang",
    hrl: "erlang",
    ex: "elixir",
    eex: "elixir",
    exs: "elixir",
    exx: "elixir",
    leex: "elixir",
    vim: "vim",
    ts: "typescript",
    mts: "typescript",
    tsx: "javascriptreact",
    jl: "julia",
    pp: "puppet",
    vue: "vue",
    elm: "elm",
    swift: "swift",
    xcplayground: "swift",
    svg: "svg",
    otf: "font",
    ttf: "font",
    fnt: "font",
    txt: "text",
    text: "text",
    zip: "archive",
    tar: "archive",
    gz: "archive",
    gzip: "archive",
    rar: "archive",
    "7z": "archive",
    iso: "archive",
    doc: "word",
    docx: "word",
    docm: "word",
    csv: "excel",
    xls: "excel",
    xlsx: "excel",
    xlsm: "excel",
    ppt: "ppt",
    pptx: "ppt",
    pptm: "ppt"
  },
  filenames: {
    gruntfile: "gruntfile",
    gulpfile: "gulpfile",
    gemfile: "ruby",
    guardfile: "ruby",
    capfile: "ruby",
    rakefile: "ruby",
    gradlew: "terminal",
    mix: "mix",
    dropbox: "dropbox",
    vimrc: "vim",
    ".vimrc": "vim",
    ".gvimrc": "vim",
    _vimrc: "vim",
    _gvimrc: "vim",
    license: "license",
    procfile: "procfile",
    Vagrantfile: "vagrant",
    "docker-compose.yml": "docker",
    ".gitconfig": "git",
    ".gitignore": "git",
    webpack: "webpack",
    ".bashrc": "bashrc",
    ".zshrc": "bashrc",
    ".bashprofile": "bashrc",
    "favicon.ico": "favicon",
    dockerfile: "docker",
    ".dockerignore": "docker"
  },
  patternMatches: {
    ".*jquery.*.js$": "jquery",
    ".*angular.*.js$": "angular",
    ".*backbone.*.js$": "backbone",
    ".*require.*.js$": "requirejs",
    ".*materialize.*.js$": "materialize",
    ".*materialize.*.css$": "materialize",
    ".*mootools.*.js$": "mootools"
  },
  dirnames: {
    ".git": "git",
    node_modules: "javascript"
  },
  dirPatternMatches: {}
};

// src/icon/nerdfont.ts
var nerdfont = icons_nerdfont_default;
var customIcon = config.get("icon.customIcons", {});
Object.assign(nerdfont.icons, customIcon.icons);
Object.assign(nerdfont.extensions, customIcon.extensions);
Object.assign(nerdfont.filenames, customIcon.filenames);
Object.assign(nerdfont.dirnames, customIcon.dirnames);
Object.assign(nerdfont.patternMatches, customIcon.patternMatches);
Object.assign(nerdfont.dirPatternMatches, customIcon.dirPatternMatches);
var nerdfontHighlights = /* @__PURE__ */ new Map();
Object.entries(nerdfont.icons).forEach(([name, icon]) => {
  if (!icon)
    return;
  const color = parseColor(icon.color);
  if (!color)
    return;
  const ansiColor = import_color_convert4.default.rgb.ansi256([color.red, color.green, color.blue]);
  const hlExpr = `ctermfg=${ansiColor} guifg=${icon.color}`;
  nerdfontHighlights.set(
    name,
    hlGroupManager.createGroup(`FileIconNerdfont_${name}`, hlExpr)
  );
});

// src/icon/loaders/builtin-icons.ts
var BuiltinIconLoader = class extends IconLoader {
  async loadIcons(targets) {
    var _a2;
    const loaded = [];
    for (const target of targets) {
      const icon = target.isDirectory ? this.getDirectoryIcon(target) : this.getFileIcon(target);
      if (icon) {
        icon.highlight = (_a2 = nerdfontHighlights.get(icon.name)) == null ? void 0 : _a2.group;
        loaded.push({
          icon,
          target
        });
      }
    }
    return loaded;
  }
  nerdfontToIcon(name) {
    if (!name)
      return;
    const icon = nerdfont.icons[name];
    if (icon)
      return {
        name,
        ...icon
      };
  }
  getFileIcon(target) {
    const { fullname, basename: basename2, extensions: extensions3 } = target;
    const extname = extensions3[extensions3.length - 1];
    if (hasOwnProperty11(nerdfont.filenames, basename2)) {
      const name = nerdfont.filenames[basename2];
      return this.nerdfontToIcon(name);
    }
    if (hasOwnProperty11(nerdfont.filenames, fullname)) {
      const name = nerdfont.filenames[fullname];
      return this.nerdfontToIcon(name);
    }
    const matched = Object.entries(nerdfont.patternMatches).find(
      ([pattern]) => new RegExp(pattern).test(fullname)
    );
    if (matched) {
      const name = matched[1];
      return this.nerdfontToIcon(name);
    }
    if (extname && hasOwnProperty11(nerdfont.extensions, extname)) {
      const name = nerdfont.extensions[extname];
      return this.nerdfontToIcon(name);
    }
  }
  getDirectoryIcon(target) {
    const { basename: basename2, fullname: dirname } = target;
    if (hasOwnProperty11(nerdfont.dirnames, basename2)) {
      const name = nerdfont.dirnames[basename2];
      return this.nerdfontToIcon(name);
    }
    if (hasOwnProperty11(nerdfont.dirnames, dirname)) {
      const name = nerdfont.dirnames[dirname];
      return this.nerdfontToIcon(name);
    }
    const matched = Object.entries(nerdfont.dirPatternMatches).find(
      ([pattern]) => new RegExp(pattern).test(dirname)
    );
    if (matched) {
      const name = matched[1];
      return this.nerdfontToIcon(name);
    }
  }
};
registerLoader("builtin", () => new BuiltinIconLoader());

// src/icon/loaders/nvim-web-devicons.ts
var import_coc58 = require("coc.nvim");
var NvimWebDeviconsLoader = class extends IconLoader {
  escapeLuaString(name, qoute = "'") {
    return name ? name.replace(/\\/g, "\\").replace(new RegExp(qoute, "g"), "\\'") : name;
  }
  async loadIcons(targets) {
    const loaded = [];
    for (const target of targets) {
      if (target.isDirectory) {
        continue;
      }
      const ext2 = target.extensions[target.extensions.length - 1];
      const result = await import_coc58.workspace.nvim.call("luaeval", [
        "{require'nvim-web-devicons'.get_icon(_A[1], _A[2])}",
        [target.fullname, ext2]
      ]);
      const [code, highlight] = result;
      if (!code) {
        continue;
      }
      loaded.push({
        target,
        icon: {
          code,
          highlight
        }
      });
    }
    return loaded;
  }
};
registerLoader("nvim-web-devicons", () => new NvimWebDeviconsLoader());

// src/icon/loaders/vim-devicons.ts
var import_coc59 = require("coc.nvim");
var VimDeviconsLoader = class extends IconLoader {
  async loadIcons(targets) {
    const loaded = [];
    await Promise.all(
      targets.map(async (target) => {
        if (target.isDirectory) {
          return;
        }
        const code = await import_coc59.workspace.nvim.call("WebDevIconsGetFileTypeSymbol", [
          target.fullname,
          false
        ]);
        if (!code) {
          return;
        }
        loaded.push({
          target,
          icon: {
            code
          }
        });
      })
    );
    return loaded;
  }
};
registerLoader("vim-devicons", () => new VimDeviconsLoader());

// src/icon/loaders/nerdfont.vim.ts
var import_coc60 = require("coc.nvim");
var NerdfontVimLoader = class extends IconLoader {
  async loadIcons(targets) {
    const loaded = [];
    await Promise.all(
      targets.map(async (target) => {
        const code = await import_coc60.workspace.nvim.call("nerdfont#find", [
          target.fullname,
          target.isDirectory
        ]);
        if (!code) {
          return;
        }
        loaded.push({
          target,
          icon: {
            code
          }
        });
      })
    );
    return loaded;
  }
};
registerLoader("nerdfont.vim", () => new NerdfontVimLoader());

// src/icon/icons.ts
function parseTargets(targets) {
  return targets.map((target) => {
    return {
      fullname: target.fullname,
      ...getExtensions(target.fullname.toLowerCase()),
      isDirectory: target.isDirectory,
      hidden: target.hidden,
      expanded: target.expanded
    };
  });
}
async function loadIcons(sourceType, targets) {
  var _a2, _b, _c, _d;
  const parsedTargets = parseTargets(targets);
  const loader = getLoader(sourceType);
  if (!loader) {
    return;
  }
  const loadedIcons = await loader.loadIcons(parsedTargets);
  const [directoryIcons, fileIcons] = partition_default(
    loadedIcons,
    (it) => it.target.isDirectory
  );
  const fullname2directoryIcon = keyBy_default(
    directoryIcons,
    (it) => it.target.fullname
  );
  const fullname2fileIcon = keyBy_default(fileIcons, (it) => it.target.fullname);
  const result = {
    files: /* @__PURE__ */ new Map(),
    directories: /* @__PURE__ */ new Map()
  };
  for (const target of targets) {
    if (hasOwnProperty11(fullname2directoryIcon, target.fullname)) {
      const item = fullname2directoryIcon[target.fullname];
      if (item)
        result.directories.set(target.fullname, item.icon);
    } else if (hasOwnProperty11(fullname2fileIcon, target.fullname)) {
      const item = fullname2fileIcon[target.fullname];
      if (item)
        result.files.set(target.fullname, item.icon);
    } else if (target.isDirectory) {
      const code = target.expanded ? (_a2 = nerdfont.icons.folderOpened) == null ? void 0 : _a2.code : (_b = nerdfont.icons.folderClosed) == null ? void 0 : _b.code;
      if (code)
        result.directories.set(target.fullname, {
          code
        });
    } else {
      const code = target.hidden ? (_c = nerdfont.icons.fileHidden) == null ? void 0 : _c.code : (_d = nerdfont.icons.file) == null ? void 0 : _d.code;
      if (code)
        result.files.set(target.fullname, { code });
    }
  }
  return result;
}
async function loadIconsByConfig(config4, targets) {
  const enabledNerdFont = config4.get("icon.enableNerdfont");
  if (!enabledNerdFont) {
    return;
  }
  const source = config4.get("icon.source");
  return loadIcons(source, targets);
}

// src/source/sources/file/child-columns/icon.ts
fileColumnRegistrar.registerColumn("child", "icon", ({ source }) => ({
  async draw(nodes) {
    const iconTargets = nodes.map((node) => {
      var _a2;
      return {
        fullname: ((_a2 = node.compactedLastNode) == null ? void 0 : _a2.name) ?? node.name,
        hidden: node.hidden,
        isDirectory: node.directory,
        expanded: node.directory ? source.view.isExpanded(node) : void 0
      };
    });
    const icons = await loadIconsByConfig(source.config, iconTargets);
    return {
      async drawNode(row, { node }) {
        var _a2;
        if (node.directory) {
          const hl = source.view.isExpanded(node) ? fileHighlights.directoryExpanded : fileHighlights.directoryCollapsed;
          const icon = icons == null ? void 0 : icons.directories.get(
            ((_a2 = node.compactedLastNode) == null ? void 0 : _a2.name) ?? node.name
          );
          if (icon) {
            row.add(icon.code, { hl });
          } else {
            row.add(
              source.view.isExpanded(node) ? source.icons.expanded : source.icons.collapsed,
              { hl }
            );
          }
        } else {
          const icon = icons == null ? void 0 : icons.files.get(node.name);
          if (icon) {
            row.add(icon.code, {
              hl: icon.highlight ?? nerdfontHighlights.get("file")
            });
          }
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/filename.ts
fileColumnRegistrar.registerColumn(
  "child",
  "filename",
  ({ source, subscriptions }) => {
    const filenameHighlight = new FilenameHighlight(source.config);
    const getHighlight = (fullpath, isDirectory) => {
      return filenameHighlight.getHighlight(fullpath, isDirectory, [
        "diagnosticError",
        "diagnosticWarning",
        "git"
      ]) ?? (isDirectory ? fileHighlights.directory : fileHighlights.filename);
    };
    const diagnosticTypes = [];
    if (filenameHighlight.enabledErrorStatus) {
      diagnosticTypes.push("error");
    }
    if (filenameHighlight.enabledWarningStatus) {
      diagnosticTypes.push("warning");
    }
    return {
      init() {
        subscriptions.push(
          diagnosticManager.bindColumn(source, diagnosticTypes),
          gitManager.bindColumn(source)
        );
      },
      draw() {
        return {
          async drawNode(row, { node }) {
            row.add(node.name, {
              hl: getHighlight(node.fullpath, node.directory),
              unicode: true
            });
          }
        };
      }
    };
  }
);

// src/source/sources/file/child-columns/linkIcon.ts
fileColumnRegistrar.registerColumn("child", "linkIcon", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (node.symbolicLink) {
          row.add(source.icons.link, { hl: fileHighlights.linkTarget });
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/link.ts
fileColumnRegistrar.registerColumn("child", "link", () => ({
  draw() {
    return {
      labelVisible: ({ node }) => node.symbolicLink,
      async drawNode(row, { node }) {
        const linkTarget = node.symbolicLink ? await fsReadlink(node.fullpath).then((link) => link).catch(() => "") : "";
        if (linkTarget) {
          row.add(linkTarget, { hl: fileHighlights.linkTarget, unicode: true });
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/fullpath.ts
var import_path19 = __toESM(require("path"));
fileColumnRegistrar.registerColumn("child", "fullpath", () => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (node.directory) {
          row.add(displayedFullpath(node.fullpath) + import_path19.default.sep, {
            hl: fileHighlights.directory
          });
        } else {
          row.add(node.fullpath);
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/indent.ts
function printIndentLine(node) {
  var _a2, _b;
  let row = "";
  if ((_a2 = node.parent) == null ? void 0 : _a2.isRoot) {
    return row;
  }
  if (node.nextSiblingNode === void 0) {
    row = "\u2514 ";
  } else {
    row = "\u2502 ";
  }
  let curNode = node.parent;
  while (curNode) {
    if ((_b = curNode.parent) == null ? void 0 : _b.isRoot) {
      break;
    }
    if (curNode.nextSiblingNode === void 0) {
      row = `  ${row}`;
    } else {
      row = `\u2502 ${row}`;
    }
    curNode = curNode.parent;
  }
  return row;
}
fileColumnRegistrar.registerColumn("child", "indent", ({ source }) => ({
  draw() {
    const enabledNerdFont = source.config.get("icon.enableNerdfont");
    const enableIndentLine = (() => {
      const indentLine = source.getColumnConfig(
        "indent.indentLine"
      );
      if (enabledNerdFont && indentLine === void 0) {
        return true;
      } else {
        return indentLine;
      }
    })();
    return {
      drawNode(row, { node }) {
        if (enableIndentLine) {
          row.add(printIndentLine(node), { hl: fileHighlights.indentLine });
        } else {
          row.add(
            source.getColumnConfig("indent.chars").repeat((node.level ?? 0) - 1)
          );
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/clip.ts
fileColumnRegistrar.registerColumn("child", "clip", ({ source }) => ({
  async draw() {
    let copy = source.getColumnConfig("clip.copy");
    let cut = source.getColumnConfig("clip.cut");
    if (source.config.get("icon.enableNerdfont")) {
      copy = copy ?? "\uF0C5";
      cut = cut ?? "\uF0C4";
    } else {
      copy = copy ?? "C";
      cut = cut ?? "X";
    }
    const clipboardStorage = source.explorer.explorerManager.clipboardStorage;
    const content = await clipboardStorage.getFiles();
    const fullpathSet = new Set(content.fullpaths);
    return {
      drawNode(row, { node }) {
        if (content.type === "none") {
          return;
        }
        const ch = fullpathSet.has(node.fullpath) ? content.type === "cut" ? cut : copy : "";
        if (ch) {
          row.add(ch, { hl: fileHighlights.clip });
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/size.ts
var import_pretty_bytes = __toESM(require_pretty_bytes());
fileColumnRegistrar.registerColumn("child", "size", () => ({
  draw() {
    return {
      labelVisible: ({ node }) => !node.directory,
      drawNode(row, { node }) {
        if (node.lstat) {
          row.add((0, import_pretty_bytes.default)(node.lstat.size), { hl: fileHighlights.size });
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/readonly.ts
fileColumnRegistrar.registerColumn("child", "readonly", ({ source }) => ({
  draw() {
    return {
      labelOnly: true,
      labelVisible: ({ node }) => node.readonly,
      drawNode(row, { node }) {
        if (node.readonly) {
          row.add(source.icons.readonly, {
            hl: fileHighlights.readonly
          });
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/modified.ts
fileColumnRegistrar.registerColumn(
  "child",
  "modified",
  ({ source, subscriptions }) => {
    return {
      async init() {
        if (!source.explorer.isFloating) {
          subscriptions.push(
            source.bufManager.onModifiedDebounce(
              (fullpaths) => source.view.renderPaths(fullpaths)
            )
          );
        }
      },
      draw() {
        return {
          labelOnly: true,
          labelVisible: ({ node }) => source.bufManager.modified(node.fullpath, {
            directory: node.directory
          }),
          drawNode(row, { node, nodeIndex }) {
            const modified = source.bufManager.modified(
              node.fullpath,
              {
                directory: node.directory && !source.view.isExpanded(node)
              }
            );
            row.add(modified ? "+" : "", {
              hl: fileHighlights.readonly
            });
            modified ? source.locator.mark.add("modified", nodeIndex) : source.locator.mark.remove("modified", nodeIndex);
          }
        };
      }
    };
  }
);

// node_modules/date-fns/toDate.mjs
function toDate(argument) {
  const argStr = Object.prototype.toString.call(argument);
  if (argument instanceof Date || typeof argument === "object" && argStr === "[object Date]") {
    return new argument.constructor(+argument);
  } else if (typeof argument === "number" || argStr === "[object Number]" || typeof argument === "string" || argStr === "[object String]") {
    return new Date(argument);
  } else {
    return /* @__PURE__ */ new Date(NaN);
  }
}

// node_modules/date-fns/constructFrom.mjs
function constructFrom(date, value) {
  if (date instanceof Date) {
    return new date.constructor(value);
  } else {
    return new Date(value);
  }
}

// node_modules/date-fns/constants.mjs
var daysInYear = 365.2425;
var maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1e3;
var minTime = -maxTime;
var millisecondsInWeek = 6048e5;
var millisecondsInDay = 864e5;
var secondsInHour = 3600;
var secondsInDay = secondsInHour * 24;
var secondsInWeek = secondsInDay * 7;
var secondsInYear = secondsInDay * daysInYear;
var secondsInMonth = secondsInYear / 12;
var secondsInQuarter = secondsInMonth * 3;

// node_modules/date-fns/_lib/defaultOptions.mjs
var defaultOptions = {};
function getDefaultOptions() {
  return defaultOptions;
}

// node_modules/date-fns/startOfWeek.mjs
function startOfWeek(date, options) {
  var _a2, _b, _c, _d;
  const defaultOptions2 = getDefaultOptions();
  const weekStartsOn = (options == null ? void 0 : options.weekStartsOn) ?? ((_b = (_a2 = options == null ? void 0 : options.locale) == null ? void 0 : _a2.options) == null ? void 0 : _b.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.weekStartsOn) ?? 0;
  const _date = toDate(date);
  const day = _date.getDay();
  const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
  _date.setDate(_date.getDate() - diff);
  _date.setHours(0, 0, 0, 0);
  return _date;
}

// node_modules/date-fns/startOfISOWeek.mjs
function startOfISOWeek(date) {
  return startOfWeek(date, { weekStartsOn: 1 });
}

// node_modules/date-fns/getISOWeekYear.mjs
function getISOWeekYear(date) {
  const _date = toDate(date);
  const year = _date.getFullYear();
  const fourthOfJanuaryOfNextYear = constructFrom(date, 0);
  fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
  fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
  const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
  const fourthOfJanuaryOfThisYear = constructFrom(date, 0);
  fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
  fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
  const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
  if (_date.getTime() >= startOfNextYear.getTime()) {
    return year + 1;
  } else if (_date.getTime() >= startOfThisYear.getTime()) {
    return year;
  } else {
    return year - 1;
  }
}

// node_modules/date-fns/startOfDay.mjs
function startOfDay(date) {
  const _date = toDate(date);
  _date.setHours(0, 0, 0, 0);
  return _date;
}

// node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.mjs
function getTimezoneOffsetInMilliseconds(date) {
  const _date = toDate(date);
  const utcDate = new Date(
    Date.UTC(
      _date.getFullYear(),
      _date.getMonth(),
      _date.getDate(),
      _date.getHours(),
      _date.getMinutes(),
      _date.getSeconds(),
      _date.getMilliseconds()
    )
  );
  utcDate.setUTCFullYear(_date.getFullYear());
  return +date - +utcDate;
}

// node_modules/date-fns/differenceInCalendarDays.mjs
function differenceInCalendarDays(dateLeft, dateRight) {
  const startOfDayLeft = startOfDay(dateLeft);
  const startOfDayRight = startOfDay(dateRight);
  const timestampLeft = +startOfDayLeft - getTimezoneOffsetInMilliseconds(startOfDayLeft);
  const timestampRight = +startOfDayRight - getTimezoneOffsetInMilliseconds(startOfDayRight);
  return Math.round((timestampLeft - timestampRight) / millisecondsInDay);
}

// node_modules/date-fns/startOfISOWeekYear.mjs
function startOfISOWeekYear(date) {
  const year = getISOWeekYear(date);
  const fourthOfJanuary = constructFrom(date, 0);
  fourthOfJanuary.setFullYear(year, 0, 4);
  fourthOfJanuary.setHours(0, 0, 0, 0);
  return startOfISOWeek(fourthOfJanuary);
}

// node_modules/date-fns/isDate.mjs
function isDate(value) {
  return value instanceof Date || typeof value === "object" && Object.prototype.toString.call(value) === "[object Date]";
}

// node_modules/date-fns/isValid.mjs
function isValid(date) {
  if (!isDate(date) && typeof date !== "number") {
    return false;
  }
  const _date = toDate(date);
  return !isNaN(Number(_date));
}

// node_modules/date-fns/startOfYear.mjs
function startOfYear(date) {
  const cleanDate = toDate(date);
  const _date = constructFrom(date, 0);
  _date.setFullYear(cleanDate.getFullYear(), 0, 1);
  _date.setHours(0, 0, 0, 0);
  return _date;
}

// node_modules/date-fns/locale/en-US/_lib/formatDistance.mjs
var formatDistanceLocale = {
  lessThanXSeconds: {
    one: "less than a second",
    other: "less than {{count}} seconds"
  },
  xSeconds: {
    one: "1 second",
    other: "{{count}} seconds"
  },
  halfAMinute: "half a minute",
  lessThanXMinutes: {
    one: "less than a minute",
    other: "less than {{count}} minutes"
  },
  xMinutes: {
    one: "1 minute",
    other: "{{count}} minutes"
  },
  aboutXHours: {
    one: "about 1 hour",
    other: "about {{count}} hours"
  },
  xHours: {
    one: "1 hour",
    other: "{{count}} hours"
  },
  xDays: {
    one: "1 day",
    other: "{{count}} days"
  },
  aboutXWeeks: {
    one: "about 1 week",
    other: "about {{count}} weeks"
  },
  xWeeks: {
    one: "1 week",
    other: "{{count}} weeks"
  },
  aboutXMonths: {
    one: "about 1 month",
    other: "about {{count}} months"
  },
  xMonths: {
    one: "1 month",
    other: "{{count}} months"
  },
  aboutXYears: {
    one: "about 1 year",
    other: "about {{count}} years"
  },
  xYears: {
    one: "1 year",
    other: "{{count}} years"
  },
  overXYears: {
    one: "over 1 year",
    other: "over {{count}} years"
  },
  almostXYears: {
    one: "almost 1 year",
    other: "almost {{count}} years"
  }
};
var formatDistance = (token, count, options) => {
  let result;
  const tokenValue = formatDistanceLocale[token];
  if (typeof tokenValue === "string") {
    result = tokenValue;
  } else if (count === 1) {
    result = tokenValue.one;
  } else {
    result = tokenValue.other.replace("{{count}}", count.toString());
  }
  if (options == null ? void 0 : options.addSuffix) {
    if (options.comparison && options.comparison > 0) {
      return "in " + result;
    } else {
      return result + " ago";
    }
  }
  return result;
};

// node_modules/date-fns/locale/_lib/buildFormatLongFn.mjs
function buildFormatLongFn(args) {
  return (options = {}) => {
    const width = options.width ? String(options.width) : args.defaultWidth;
    const format2 = args.formats[width] || args.formats[args.defaultWidth];
    return format2;
  };
}

// node_modules/date-fns/locale/en-US/_lib/formatLong.mjs
var dateFormats = {
  full: "EEEE, MMMM do, y",
  long: "MMMM do, y",
  medium: "MMM d, y",
  short: "MM/dd/yyyy"
};
var timeFormats = {
  full: "h:mm:ss a zzzz",
  long: "h:mm:ss a z",
  medium: "h:mm:ss a",
  short: "h:mm a"
};
var dateTimeFormats = {
  full: "{{date}} 'at' {{time}}",
  long: "{{date}} 'at' {{time}}",
  medium: "{{date}}, {{time}}",
  short: "{{date}}, {{time}}"
};
var formatLong = {
  date: buildFormatLongFn({
    formats: dateFormats,
    defaultWidth: "full"
  }),
  time: buildFormatLongFn({
    formats: timeFormats,
    defaultWidth: "full"
  }),
  dateTime: buildFormatLongFn({
    formats: dateTimeFormats,
    defaultWidth: "full"
  })
};

// node_modules/date-fns/locale/en-US/_lib/formatRelative.mjs
var formatRelativeLocale = {
  lastWeek: "'last' eeee 'at' p",
  yesterday: "'yesterday at' p",
  today: "'today at' p",
  tomorrow: "'tomorrow at' p",
  nextWeek: "eeee 'at' p",
  other: "P"
};
var formatRelative = (token, _date, _baseDate, _options) => formatRelativeLocale[token];

// node_modules/date-fns/locale/_lib/buildLocalizeFn.mjs
function buildLocalizeFn(args) {
  return (value, options) => {
    const context2 = (options == null ? void 0 : options.context) ? String(options.context) : "standalone";
    let valuesArray;
    if (context2 === "formatting" && args.formattingValues) {
      const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
      const width = (options == null ? void 0 : options.width) ? String(options.width) : defaultWidth;
      valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
    } else {
      const defaultWidth = args.defaultWidth;
      const width = (options == null ? void 0 : options.width) ? String(options.width) : args.defaultWidth;
      valuesArray = args.values[width] || args.values[defaultWidth];
    }
    const index = args.argumentCallback ? args.argumentCallback(value) : value;
    return valuesArray[index];
  };
}

// node_modules/date-fns/locale/en-US/_lib/localize.mjs
var eraValues = {
  narrow: ["B", "A"],
  abbreviated: ["BC", "AD"],
  wide: ["Before Christ", "Anno Domini"]
};
var quarterValues = {
  narrow: ["1", "2", "3", "4"],
  abbreviated: ["Q1", "Q2", "Q3", "Q4"],
  wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
};
var monthValues = {
  narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
  abbreviated: [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ],
  wide: [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ]
};
var dayValues = {
  narrow: ["S", "M", "T", "W", "T", "F", "S"],
  short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
  abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  wide: [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ]
};
var dayPeriodValues = {
  narrow: {
    am: "a",
    pm: "p",
    midnight: "mi",
    noon: "n",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  },
  abbreviated: {
    am: "AM",
    pm: "PM",
    midnight: "midnight",
    noon: "noon",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  },
  wide: {
    am: "a.m.",
    pm: "p.m.",
    midnight: "midnight",
    noon: "noon",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  }
};
var formattingDayPeriodValues = {
  narrow: {
    am: "a",
    pm: "p",
    midnight: "mi",
    noon: "n",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  },
  abbreviated: {
    am: "AM",
    pm: "PM",
    midnight: "midnight",
    noon: "noon",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  },
  wide: {
    am: "a.m.",
    pm: "p.m.",
    midnight: "midnight",
    noon: "noon",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  }
};
var ordinalNumber = (dirtyNumber, _options) => {
  const number = Number(dirtyNumber);
  const rem100 = number % 100;
  if (rem100 > 20 || rem100 < 10) {
    switch (rem100 % 10) {
      case 1:
        return number + "st";
      case 2:
        return number + "nd";
      case 3:
        return number + "rd";
    }
  }
  return number + "th";
};
var localize = {
  ordinalNumber,
  era: buildLocalizeFn({
    values: eraValues,
    defaultWidth: "wide"
  }),
  quarter: buildLocalizeFn({
    values: quarterValues,
    defaultWidth: "wide",
    argumentCallback: (quarter) => quarter - 1
  }),
  month: buildLocalizeFn({
    values: monthValues,
    defaultWidth: "wide"
  }),
  day: buildLocalizeFn({
    values: dayValues,
    defaultWidth: "wide"
  }),
  dayPeriod: buildLocalizeFn({
    values: dayPeriodValues,
    defaultWidth: "wide",
    formattingValues: formattingDayPeriodValues,
    defaultFormattingWidth: "wide"
  })
};

// node_modules/date-fns/locale/_lib/buildMatchFn.mjs
function buildMatchFn(args) {
  return (string, options = {}) => {
    const width = options.width;
    const matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
    const matchResult = string.match(matchPattern);
    if (!matchResult) {
      return null;
    }
    const matchedString = matchResult[0];
    const parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
    const key = Array.isArray(parsePatterns) ? findIndex2(parsePatterns, (pattern) => pattern.test(matchedString)) : (
      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type
      findKey(parsePatterns, (pattern) => pattern.test(matchedString))
    );
    let value;
    value = args.valueCallback ? args.valueCallback(key) : key;
    value = options.valueCallback ? (
      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type
      options.valueCallback(value)
    ) : value;
    const rest = string.slice(matchedString.length);
    return { value, rest };
  };
}
function findKey(object, predicate) {
  for (const key in object) {
    if (Object.prototype.hasOwnProperty.call(object, key) && predicate(object[key])) {
      return key;
    }
  }
  return void 0;
}
function findIndex2(array, predicate) {
  for (let key = 0; key < array.length; key++) {
    if (predicate(array[key])) {
      return key;
    }
  }
  return void 0;
}

// node_modules/date-fns/locale/_lib/buildMatchPatternFn.mjs
function buildMatchPatternFn(args) {
  return (string, options = {}) => {
    const matchResult = string.match(args.matchPattern);
    if (!matchResult)
      return null;
    const matchedString = matchResult[0];
    const parseResult = string.match(args.parsePattern);
    if (!parseResult)
      return null;
    let value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
    value = options.valueCallback ? options.valueCallback(value) : value;
    const rest = string.slice(matchedString.length);
    return { value, rest };
  };
}

// node_modules/date-fns/locale/en-US/_lib/match.mjs
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
  narrow: /^(b|a)/i,
  abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
  wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
  any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
  narrow: /^[1234]/i,
  abbreviated: /^q[1234]/i,
  wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
  any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
  narrow: /^[jfmasond]/i,
  abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
  wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
  narrow: [
    /^j/i,
    /^f/i,
    /^m/i,
    /^a/i,
    /^m/i,
    /^j/i,
    /^j/i,
    /^a/i,
    /^s/i,
    /^o/i,
    /^n/i,
    /^d/i
  ],
  any: [
    /^ja/i,
    /^f/i,
    /^mar/i,
    /^ap/i,
    /^may/i,
    /^jun/i,
    /^jul/i,
    /^au/i,
    /^s/i,
    /^o/i,
    /^n/i,
    /^d/i
  ]
};
var matchDayPatterns = {
  narrow: /^[smtwf]/i,
  short: /^(su|mo|tu|we|th|fr|sa)/i,
  abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
  wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
  narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
  any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
  narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
  any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
  any: {
    am: /^a/i,
    pm: /^p/i,
    midnight: /^mi/i,
    noon: /^no/i,
    morning: /morning/i,
    afternoon: /afternoon/i,
    evening: /evening/i,
    night: /night/i
  }
};
var match2 = {
  ordinalNumber: buildMatchPatternFn({
    matchPattern: matchOrdinalNumberPattern,
    parsePattern: parseOrdinalNumberPattern,
    valueCallback: (value) => parseInt(value, 10)
  }),
  era: buildMatchFn({
    matchPatterns: matchEraPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseEraPatterns,
    defaultParseWidth: "any"
  }),
  quarter: buildMatchFn({
    matchPatterns: matchQuarterPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseQuarterPatterns,
    defaultParseWidth: "any",
    valueCallback: (index) => index + 1
  }),
  month: buildMatchFn({
    matchPatterns: matchMonthPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseMonthPatterns,
    defaultParseWidth: "any"
  }),
  day: buildMatchFn({
    matchPatterns: matchDayPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseDayPatterns,
    defaultParseWidth: "any"
  }),
  dayPeriod: buildMatchFn({
    matchPatterns: matchDayPeriodPatterns,
    defaultMatchWidth: "any",
    parsePatterns: parseDayPeriodPatterns,
    defaultParseWidth: "any"
  })
};

// node_modules/date-fns/locale/en-US.mjs
var enUS = {
  code: "en-US",
  formatDistance,
  formatLong,
  formatRelative,
  localize,
  match: match2,
  options: {
    weekStartsOn: 0,
    firstWeekContainsDate: 1
  }
};

// node_modules/date-fns/getDayOfYear.mjs
function getDayOfYear(date) {
  const _date = toDate(date);
  const diff = differenceInCalendarDays(_date, startOfYear(_date));
  const dayOfYear = diff + 1;
  return dayOfYear;
}

// node_modules/date-fns/getISOWeek.mjs
function getISOWeek(date) {
  const _date = toDate(date);
  const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);
  return Math.round(diff / millisecondsInWeek) + 1;
}

// node_modules/date-fns/getWeekYear.mjs
function getWeekYear(date, options) {
  var _a2, _b, _c, _d;
  const _date = toDate(date);
  const year = _date.getFullYear();
  const defaultOptions2 = getDefaultOptions();
  const firstWeekContainsDate = (options == null ? void 0 : options.firstWeekContainsDate) ?? ((_b = (_a2 = options == null ? void 0 : options.locale) == null ? void 0 : _a2.options) == null ? void 0 : _b.firstWeekContainsDate) ?? defaultOptions2.firstWeekContainsDate ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.firstWeekContainsDate) ?? 1;
  const firstWeekOfNextYear = constructFrom(date, 0);
  firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);
  firstWeekOfNextYear.setHours(0, 0, 0, 0);
  const startOfNextYear = startOfWeek(firstWeekOfNextYear, options);
  const firstWeekOfThisYear = constructFrom(date, 0);
  firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);
  firstWeekOfThisYear.setHours(0, 0, 0, 0);
  const startOfThisYear = startOfWeek(firstWeekOfThisYear, options);
  if (_date.getTime() >= startOfNextYear.getTime()) {
    return year + 1;
  } else if (_date.getTime() >= startOfThisYear.getTime()) {
    return year;
  } else {
    return year - 1;
  }
}

// node_modules/date-fns/startOfWeekYear.mjs
function startOfWeekYear(date, options) {
  var _a2, _b, _c, _d;
  const defaultOptions2 = getDefaultOptions();
  const firstWeekContainsDate = (options == null ? void 0 : options.firstWeekContainsDate) ?? ((_b = (_a2 = options == null ? void 0 : options.locale) == null ? void 0 : _a2.options) == null ? void 0 : _b.firstWeekContainsDate) ?? defaultOptions2.firstWeekContainsDate ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.firstWeekContainsDate) ?? 1;
  const year = getWeekYear(date, options);
  const firstWeek = constructFrom(date, 0);
  firstWeek.setFullYear(year, 0, firstWeekContainsDate);
  firstWeek.setHours(0, 0, 0, 0);
  const _date = startOfWeek(firstWeek, options);
  return _date;
}

// node_modules/date-fns/getWeek.mjs
function getWeek(date, options) {
  const _date = toDate(date);
  const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);
  return Math.round(diff / millisecondsInWeek) + 1;
}

// node_modules/date-fns/_lib/addLeadingZeros.mjs
function addLeadingZeros(number, targetLength) {
  const sign = number < 0 ? "-" : "";
  const output = Math.abs(number).toString().padStart(targetLength, "0");
  return sign + output;
}

// node_modules/date-fns/_lib/format/lightFormatters.mjs
var lightFormatters = {
  // Year
  y(date, token) {
    const signedYear = date.getFullYear();
    const year = signedYear > 0 ? signedYear : 1 - signedYear;
    return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
  },
  // Month
  M(date, token) {
    const month = date.getMonth();
    return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
  },
  // Day of the month
  d(date, token) {
    return addLeadingZeros(date.getDate(), token.length);
  },
  // AM or PM
  a(date, token) {
    const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? "pm" : "am";
    switch (token) {
      case "a":
      case "aa":
        return dayPeriodEnumValue.toUpperCase();
      case "aaa":
        return dayPeriodEnumValue;
      case "aaaaa":
        return dayPeriodEnumValue[0];
      case "aaaa":
      default:
        return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
    }
  },
  // Hour [1-12]
  h(date, token) {
    return addLeadingZeros(date.getHours() % 12 || 12, token.length);
  },
  // Hour [0-23]
  H(date, token) {
    return addLeadingZeros(date.getHours(), token.length);
  },
  // Minute
  m(date, token) {
    return addLeadingZeros(date.getMinutes(), token.length);
  },
  // Second
  s(date, token) {
    return addLeadingZeros(date.getSeconds(), token.length);
  },
  // Fraction of second
  S(date, token) {
    const numberOfDigits = token.length;
    const milliseconds = date.getMilliseconds();
    const fractionalSeconds = Math.trunc(
      milliseconds * Math.pow(10, numberOfDigits - 3)
    );
    return addLeadingZeros(fractionalSeconds, token.length);
  }
};

// node_modules/date-fns/_lib/format/formatters.mjs
var dayPeriodEnum = {
  am: "am",
  pm: "pm",
  midnight: "midnight",
  noon: "noon",
  morning: "morning",
  afternoon: "afternoon",
  evening: "evening",
  night: "night"
};
var formatters = {
  // Era
  G: function(date, token, localize2) {
    const era = date.getFullYear() > 0 ? 1 : 0;
    switch (token) {
      case "G":
      case "GG":
      case "GGG":
        return localize2.era(era, { width: "abbreviated" });
      case "GGGGG":
        return localize2.era(era, { width: "narrow" });
      case "GGGG":
      default:
        return localize2.era(era, { width: "wide" });
    }
  },
  // Year
  y: function(date, token, localize2) {
    if (token === "yo") {
      const signedYear = date.getFullYear();
      const year = signedYear > 0 ? signedYear : 1 - signedYear;
      return localize2.ordinalNumber(year, { unit: "year" });
    }
    return lightFormatters.y(date, token);
  },
  // Local week-numbering year
  Y: function(date, token, localize2, options) {
    const signedWeekYear = getWeekYear(date, options);
    const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
    if (token === "YY") {
      const twoDigitYear = weekYear % 100;
      return addLeadingZeros(twoDigitYear, 2);
    }
    if (token === "Yo") {
      return localize2.ordinalNumber(weekYear, { unit: "year" });
    }
    return addLeadingZeros(weekYear, token.length);
  },
  // ISO week-numbering year
  R: function(date, token) {
    const isoWeekYear = getISOWeekYear(date);
    return addLeadingZeros(isoWeekYear, token.length);
  },
  // Extended year. This is a single number designating the year of this calendar system.
  // The main difference between `y` and `u` localizers are B.C. years:
  // | Year | `y` | `u` |
  // |------|-----|-----|
  // | AC 1 |   1 |   1 |
  // | BC 1 |   1 |   0 |
  // | BC 2 |   2 |  -1 |
  // Also `yy` always returns the last two digits of a year,
  // while `uu` pads single digit years to 2 characters and returns other years unchanged.
  u: function(date, token) {
    const year = date.getFullYear();
    return addLeadingZeros(year, token.length);
  },
  // Quarter
  Q: function(date, token, localize2) {
    const quarter = Math.ceil((date.getMonth() + 1) / 3);
    switch (token) {
      case "Q":
        return String(quarter);
      case "QQ":
        return addLeadingZeros(quarter, 2);
      case "Qo":
        return localize2.ordinalNumber(quarter, { unit: "quarter" });
      case "QQQ":
        return localize2.quarter(quarter, {
          width: "abbreviated",
          context: "formatting"
        });
      case "QQQQQ":
        return localize2.quarter(quarter, {
          width: "narrow",
          context: "formatting"
        });
      case "QQQQ":
      default:
        return localize2.quarter(quarter, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Stand-alone quarter
  q: function(date, token, localize2) {
    const quarter = Math.ceil((date.getMonth() + 1) / 3);
    switch (token) {
      case "q":
        return String(quarter);
      case "qq":
        return addLeadingZeros(quarter, 2);
      case "qo":
        return localize2.ordinalNumber(quarter, { unit: "quarter" });
      case "qqq":
        return localize2.quarter(quarter, {
          width: "abbreviated",
          context: "standalone"
        });
      case "qqqqq":
        return localize2.quarter(quarter, {
          width: "narrow",
          context: "standalone"
        });
      case "qqqq":
      default:
        return localize2.quarter(quarter, {
          width: "wide",
          context: "standalone"
        });
    }
  },
  // Month
  M: function(date, token, localize2) {
    const month = date.getMonth();
    switch (token) {
      case "M":
      case "MM":
        return lightFormatters.M(date, token);
      case "Mo":
        return localize2.ordinalNumber(month + 1, { unit: "month" });
      case "MMM":
        return localize2.month(month, {
          width: "abbreviated",
          context: "formatting"
        });
      case "MMMMM":
        return localize2.month(month, {
          width: "narrow",
          context: "formatting"
        });
      case "MMMM":
      default:
        return localize2.month(month, { width: "wide", context: "formatting" });
    }
  },
  // Stand-alone month
  L: function(date, token, localize2) {
    const month = date.getMonth();
    switch (token) {
      case "L":
        return String(month + 1);
      case "LL":
        return addLeadingZeros(month + 1, 2);
      case "Lo":
        return localize2.ordinalNumber(month + 1, { unit: "month" });
      case "LLL":
        return localize2.month(month, {
          width: "abbreviated",
          context: "standalone"
        });
      case "LLLLL":
        return localize2.month(month, {
          width: "narrow",
          context: "standalone"
        });
      case "LLLL":
      default:
        return localize2.month(month, { width: "wide", context: "standalone" });
    }
  },
  // Local week of year
  w: function(date, token, localize2, options) {
    const week = getWeek(date, options);
    if (token === "wo") {
      return localize2.ordinalNumber(week, { unit: "week" });
    }
    return addLeadingZeros(week, token.length);
  },
  // ISO week of year
  I: function(date, token, localize2) {
    const isoWeek = getISOWeek(date);
    if (token === "Io") {
      return localize2.ordinalNumber(isoWeek, { unit: "week" });
    }
    return addLeadingZeros(isoWeek, token.length);
  },
  // Day of the month
  d: function(date, token, localize2) {
    if (token === "do") {
      return localize2.ordinalNumber(date.getDate(), { unit: "date" });
    }
    return lightFormatters.d(date, token);
  },
  // Day of year
  D: function(date, token, localize2) {
    const dayOfYear = getDayOfYear(date);
    if (token === "Do") {
      return localize2.ordinalNumber(dayOfYear, { unit: "dayOfYear" });
    }
    return addLeadingZeros(dayOfYear, token.length);
  },
  // Day of week
  E: function(date, token, localize2) {
    const dayOfWeek = date.getDay();
    switch (token) {
      case "E":
      case "EE":
      case "EEE":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "EEEEE":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "EEEEEE":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "EEEE":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Local day of week
  e: function(date, token, localize2, options) {
    const dayOfWeek = date.getDay();
    const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
    switch (token) {
      case "e":
        return String(localDayOfWeek);
      case "ee":
        return addLeadingZeros(localDayOfWeek, 2);
      case "eo":
        return localize2.ordinalNumber(localDayOfWeek, { unit: "day" });
      case "eee":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "eeeee":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "eeeeee":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "eeee":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Stand-alone local day of week
  c: function(date, token, localize2, options) {
    const dayOfWeek = date.getDay();
    const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
    switch (token) {
      case "c":
        return String(localDayOfWeek);
      case "cc":
        return addLeadingZeros(localDayOfWeek, token.length);
      case "co":
        return localize2.ordinalNumber(localDayOfWeek, { unit: "day" });
      case "ccc":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "standalone"
        });
      case "ccccc":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "standalone"
        });
      case "cccccc":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "standalone"
        });
      case "cccc":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "standalone"
        });
    }
  },
  // ISO day of week
  i: function(date, token, localize2) {
    const dayOfWeek = date.getDay();
    const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
    switch (token) {
      case "i":
        return String(isoDayOfWeek);
      case "ii":
        return addLeadingZeros(isoDayOfWeek, token.length);
      case "io":
        return localize2.ordinalNumber(isoDayOfWeek, { unit: "day" });
      case "iii":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "iiiii":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "iiiiii":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "iiii":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // AM or PM
  a: function(date, token, localize2) {
    const hours = date.getHours();
    const dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
    switch (token) {
      case "a":
      case "aa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "aaa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        }).toLowerCase();
      case "aaaaa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "aaaa":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // AM, PM, midnight, noon
  b: function(date, token, localize2) {
    const hours = date.getHours();
    let dayPeriodEnumValue;
    if (hours === 12) {
      dayPeriodEnumValue = dayPeriodEnum.noon;
    } else if (hours === 0) {
      dayPeriodEnumValue = dayPeriodEnum.midnight;
    } else {
      dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
    }
    switch (token) {
      case "b":
      case "bb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "bbb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        }).toLowerCase();
      case "bbbbb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "bbbb":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // in the morning, in the afternoon, in the evening, at night
  B: function(date, token, localize2) {
    const hours = date.getHours();
    let dayPeriodEnumValue;
    if (hours >= 17) {
      dayPeriodEnumValue = dayPeriodEnum.evening;
    } else if (hours >= 12) {
      dayPeriodEnumValue = dayPeriodEnum.afternoon;
    } else if (hours >= 4) {
      dayPeriodEnumValue = dayPeriodEnum.morning;
    } else {
      dayPeriodEnumValue = dayPeriodEnum.night;
    }
    switch (token) {
      case "B":
      case "BB":
      case "BBB":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "BBBBB":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "BBBB":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Hour [1-12]
  h: function(date, token, localize2) {
    if (token === "ho") {
      let hours = date.getHours() % 12;
      if (hours === 0)
        hours = 12;
      return localize2.ordinalNumber(hours, { unit: "hour" });
    }
    return lightFormatters.h(date, token);
  },
  // Hour [0-23]
  H: function(date, token, localize2) {
    if (token === "Ho") {
      return localize2.ordinalNumber(date.getHours(), { unit: "hour" });
    }
    return lightFormatters.H(date, token);
  },
  // Hour [0-11]
  K: function(date, token, localize2) {
    const hours = date.getHours() % 12;
    if (token === "Ko") {
      return localize2.ordinalNumber(hours, { unit: "hour" });
    }
    return addLeadingZeros(hours, token.length);
  },
  // Hour [1-24]
  k: function(date, token, localize2) {
    let hours = date.getHours();
    if (hours === 0)
      hours = 24;
    if (token === "ko") {
      return localize2.ordinalNumber(hours, { unit: "hour" });
    }
    return addLeadingZeros(hours, token.length);
  },
  // Minute
  m: function(date, token, localize2) {
    if (token === "mo") {
      return localize2.ordinalNumber(date.getMinutes(), { unit: "minute" });
    }
    return lightFormatters.m(date, token);
  },
  // Second
  s: function(date, token, localize2) {
    if (token === "so") {
      return localize2.ordinalNumber(date.getSeconds(), { unit: "second" });
    }
    return lightFormatters.s(date, token);
  },
  // Fraction of second
  S: function(date, token) {
    return lightFormatters.S(date, token);
  },
  // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
  X: function(date, token, _localize) {
    const timezoneOffset = date.getTimezoneOffset();
    if (timezoneOffset === 0) {
      return "Z";
    }
    switch (token) {
      case "X":
        return formatTimezoneWithOptionalMinutes(timezoneOffset);
      case "XXXX":
      case "XX":
        return formatTimezone(timezoneOffset);
      case "XXXXX":
      case "XXX":
      default:
        return formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
  x: function(date, token, _localize) {
    const timezoneOffset = date.getTimezoneOffset();
    switch (token) {
      case "x":
        return formatTimezoneWithOptionalMinutes(timezoneOffset);
      case "xxxx":
      case "xx":
        return formatTimezone(timezoneOffset);
      case "xxxxx":
      case "xxx":
      default:
        return formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (GMT)
  O: function(date, token, _localize) {
    const timezoneOffset = date.getTimezoneOffset();
    switch (token) {
      case "O":
      case "OO":
      case "OOO":
        return "GMT" + formatTimezoneShort(timezoneOffset, ":");
      case "OOOO":
      default:
        return "GMT" + formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (specific non-location)
  z: function(date, token, _localize) {
    const timezoneOffset = date.getTimezoneOffset();
    switch (token) {
      case "z":
      case "zz":
      case "zzz":
        return "GMT" + formatTimezoneShort(timezoneOffset, ":");
      case "zzzz":
      default:
        return "GMT" + formatTimezone(timezoneOffset, ":");
    }
  },
  // Seconds timestamp
  t: function(date, token, _localize) {
    const timestamp = Math.trunc(date.getTime() / 1e3);
    return addLeadingZeros(timestamp, token.length);
  },
  // Milliseconds timestamp
  T: function(date, token, _localize) {
    const timestamp = date.getTime();
    return addLeadingZeros(timestamp, token.length);
  }
};
function formatTimezoneShort(offset, delimiter = "") {
  const sign = offset > 0 ? "-" : "+";
  const absOffset = Math.abs(offset);
  const hours = Math.trunc(absOffset / 60);
  const minutes = absOffset % 60;
  if (minutes === 0) {
    return sign + String(hours);
  }
  return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, delimiter) {
  if (offset % 60 === 0) {
    const sign = offset > 0 ? "-" : "+";
    return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
  }
  return formatTimezone(offset, delimiter);
}
function formatTimezone(offset, delimiter = "") {
  const sign = offset > 0 ? "-" : "+";
  const absOffset = Math.abs(offset);
  const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);
  const minutes = addLeadingZeros(absOffset % 60, 2);
  return sign + hours + delimiter + minutes;
}

// node_modules/date-fns/_lib/format/longFormatters.mjs
var dateLongFormatter = (pattern, formatLong2) => {
  switch (pattern) {
    case "P":
      return formatLong2.date({ width: "short" });
    case "PP":
      return formatLong2.date({ width: "medium" });
    case "PPP":
      return formatLong2.date({ width: "long" });
    case "PPPP":
    default:
      return formatLong2.date({ width: "full" });
  }
};
var timeLongFormatter = (pattern, formatLong2) => {
  switch (pattern) {
    case "p":
      return formatLong2.time({ width: "short" });
    case "pp":
      return formatLong2.time({ width: "medium" });
    case "ppp":
      return formatLong2.time({ width: "long" });
    case "pppp":
    default:
      return formatLong2.time({ width: "full" });
  }
};
var dateTimeLongFormatter = (pattern, formatLong2) => {
  const matchResult = pattern.match(/(P+)(p+)?/) || [];
  const datePattern = matchResult[1];
  const timePattern = matchResult[2];
  if (!timePattern) {
    return dateLongFormatter(pattern, formatLong2);
  }
  let dateTimeFormat;
  switch (datePattern) {
    case "P":
      dateTimeFormat = formatLong2.dateTime({ width: "short" });
      break;
    case "PP":
      dateTimeFormat = formatLong2.dateTime({ width: "medium" });
      break;
    case "PPP":
      dateTimeFormat = formatLong2.dateTime({ width: "long" });
      break;
    case "PPPP":
    default:
      dateTimeFormat = formatLong2.dateTime({ width: "full" });
      break;
  }
  return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2));
};
var longFormatters = {
  p: timeLongFormatter,
  P: dateTimeLongFormatter
};

// node_modules/date-fns/_lib/protectedTokens.mjs
var dayOfYearTokenRE = /^D+$/;
var weekYearTokenRE = /^Y+$/;
var throwTokens = ["D", "DD", "YY", "YYYY"];
function isProtectedDayOfYearToken(token) {
  return dayOfYearTokenRE.test(token);
}
function isProtectedWeekYearToken(token) {
  return weekYearTokenRE.test(token);
}
function warnOrThrowProtectedError(token, format2, input2) {
  const _message = message(token, format2, input2);
  console.warn(_message);
  if (throwTokens.includes(token))
    throw new RangeError(_message);
}
function message(token, format2, input2) {
  const subject = token[0] === "Y" ? "years" : "days of the month";
  return `Use \`${token.toLowerCase()}\` instead of \`${token}\` (in \`${format2}\`) for formatting ${subject} to the input \`${input2}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;
}

// node_modules/date-fns/format.mjs
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'([^]*?)'?$/;
var doubleQuoteRegExp = /''/g;
var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
function format(date, formatStr, options) {
  var _a2, _b, _c, _d, _e, _f, _g, _h;
  const defaultOptions2 = getDefaultOptions();
  const locale = (options == null ? void 0 : options.locale) ?? defaultOptions2.locale ?? enUS;
  const firstWeekContainsDate = (options == null ? void 0 : options.firstWeekContainsDate) ?? ((_b = (_a2 = options == null ? void 0 : options.locale) == null ? void 0 : _a2.options) == null ? void 0 : _b.firstWeekContainsDate) ?? defaultOptions2.firstWeekContainsDate ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.firstWeekContainsDate) ?? 1;
  const weekStartsOn = (options == null ? void 0 : options.weekStartsOn) ?? ((_f = (_e = options == null ? void 0 : options.locale) == null ? void 0 : _e.options) == null ? void 0 : _f.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_h = (_g = defaultOptions2.locale) == null ? void 0 : _g.options) == null ? void 0 : _h.weekStartsOn) ?? 0;
  const originalDate = toDate(date);
  if (!isValid(originalDate)) {
    throw new RangeError("Invalid time value");
  }
  let parts = formatStr.match(longFormattingTokensRegExp).map((substring) => {
    const firstCharacter = substring[0];
    if (firstCharacter === "p" || firstCharacter === "P") {
      const longFormatter = longFormatters[firstCharacter];
      return longFormatter(substring, locale.formatLong);
    }
    return substring;
  }).join("").match(formattingTokensRegExp).map((substring) => {
    if (substring === "''") {
      return { isToken: false, value: "'" };
    }
    const firstCharacter = substring[0];
    if (firstCharacter === "'") {
      return { isToken: false, value: cleanEscapedString(substring) };
    }
    if (formatters[firstCharacter]) {
      return { isToken: true, value: substring };
    }
    if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
      throw new RangeError(
        "Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"
      );
    }
    return { isToken: false, value: substring };
  });
  if (locale.localize.preprocessor) {
    parts = locale.localize.preprocessor(originalDate, parts);
  }
  const formatterOptions = {
    firstWeekContainsDate,
    weekStartsOn,
    locale
  };
  return parts.map((part) => {
    if (!part.isToken)
      return part.value;
    const token = part.value;
    if (!(options == null ? void 0 : options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(token) || !(options == null ? void 0 : options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(token)) {
      warnOrThrowProtectedError(token, formatStr, String(date));
    }
    const formatter = formatters[token[0]];
    return formatter(originalDate, token, locale.localize, formatterOptions);
  }).join("");
}
function cleanEscapedString(input2) {
  const matched = input2.match(escapedStringRegExp);
  if (!matched) {
    return input2;
  }
  return matched[1].replace(doubleQuoteRegExp, "'");
}

// src/source/sources/file/child-columns/timeModified.ts
fileColumnRegistrar.registerColumn("child", "timeModified", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (node.lstat) {
          row.add(
            format(node.lstat.mtime, source.config.get("datetime.format")),
            {
              hl: fileHighlights.timeModified
            }
          );
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/timeCreated.ts
fileColumnRegistrar.registerColumn("child", "timeCreated", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (node.lstat) {
          row.add(
            format(node.lstat.birthtime, source.config.get("datetime.format")),
            {
              hl: fileHighlights.timeCreated
            }
          );
        }
      }
    };
  }
}));

// src/source/sources/file/child-columns/timeAccessed.ts
fileColumnRegistrar.registerColumn("child", "timeAccessed", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (node.lstat) {
          row.add(
            format(node.lstat.atime, source.config.get("datetime.format")),
            {
              hl: fileHighlights.timeAccessed
            }
          );
        } else {
          row.add("                 ");
        }
      }
    };
  }
}));

// src/diagnostic/config.ts
var getDiagnosticConfig = (config4) => {
  const diagnosticConfig = {
    displayMax: config4.get("diagnostic.displayMax"),
    enableSubscriptNumber: config4.get(
      "diagnostic.enableSubscriptNumber"
    )
  };
  return diagnosticConfig;
};
var printDiagnosticCount = (count, config4) => {
  if (count > config4.displayMax) {
    return "\u2717";
  } else if (config4.enableSubscriptNumber) {
    return toSubscriptNumbers(count);
  } else {
    return count.toString();
  }
};

// src/source/sources/file/child-columns/diagnosticError.ts
fileColumnRegistrar.registerColumn(
  "child",
  "diagnosticError",
  ({ source, subscriptions }) => {
    const diagnosticConfig = getDiagnosticConfig(source.config);
    return {
      init() {
        subscriptions.push(diagnosticManager.bindColumn(source, ["error"]));
      },
      draw() {
        return {
          labelVisible: ({ node }) => !!diagnosticManager.getMixedError(node.fullpath),
          drawNode(row, { node, isLabeling }) {
            const errorCount = diagnosticManager.getMixedError(node.fullpath);
            if (isLabeling) {
              row.add((errorCount ?? 0).toString(), {
                hl: fileHighlights.diagnosticError
              });
              return;
            }
            if (!errorCount) {
              return;
            }
            if (node.directory && source.view.isExpanded(node)) {
              return;
            }
            row.add(printDiagnosticCount(errorCount, diagnosticConfig), {
              hl: fileHighlights.diagnosticError
            });
          }
        };
      }
    };
  }
);

// src/source/sources/file/child-columns/diagnosticWarning.ts
fileColumnRegistrar.registerColumn(
  "child",
  "diagnosticWarning",
  ({ source, subscriptions }) => {
    const diagnosticConfig = getDiagnosticConfig(source.config);
    return {
      init() {
        subscriptions.push(diagnosticManager.bindColumn(source, ["warning"]));
      },
      draw() {
        return {
          labelVisible: ({ node }) => !!diagnosticManager.getMixedWarning(node.fullpath),
          drawNode(row, { node, isLabeling }) {
            const warningCount = diagnosticManager.getMixedWarning(
              node.fullpath
            );
            if (isLabeling) {
              row.add((warningCount ?? 0).toString(), {
                hl: fileHighlights.diagnosticWarning
              });
              return;
            }
            if (!warningCount) {
              return;
            }
            if (node.expandable && source.view.isExpanded(node)) {
              return;
            }
            row.add(printDiagnosticCount(warningCount, diagnosticConfig), {
              hl: fileHighlights.diagnosticWarning
            });
          }
        };
      }
    };
  }
);

// src/source/sources/file/fileSource.ts
var hlg4 = hlGroupManager.linkGroup.bind(hlGroupManager);
var directoryHighlight = hlg4("FileDirectory", "Directory");
var fileHighlights = {
  title: hlg4("FileRoot", "Constant"),
  hidden: hlg4("FileHidden", internalHighlightGroups.CommentColor),
  rootName: hlg4("FileRootName", "Identifier"),
  expandIcon: hlg4("FileExpandIcon", "Directory"),
  fullpath: hlg4("FileFullpath", internalHighlightGroups.CommentColor),
  filename: hlg4("FileFilename", "None"),
  directory: directoryHighlight,
  directoryExpanded: hlg4("FileDirectoryExpanded", directoryHighlight.group),
  directoryCollapsed: hlg4("FileDirectoryCollapsed", directoryHighlight.group),
  linkTarget: hlg4("FileLinkTarget", internalHighlightGroups.CommentColor),
  indentLine: hlg4("IndentLine", internalHighlightGroups.CommentColor),
  clip: hlg4("FileClip", "Statement"),
  size: hlg4("FileSize", "Constant"),
  readonly: hlg4("FileReadonly", "Operator"),
  modified: hlg4("FileModified", "Operator"),
  timeAccessed: hlg4("TimeAccessed", "Identifier"),
  timeModified: hlg4("TimeModified", "Identifier"),
  timeCreated: hlg4("TimeCreated", "Identifier"),
  diagnosticError: hlg4(
    "FileDiagnosticError",
    diagnosticHighlights.diagnosticError.group
  ),
  diagnosticWarning: hlg4(
    "FileDiagnosticWarning",
    diagnosticHighlights.diagnosticWarning.group
  ),
  filenameDiagnosticError: hlg4("FileFilenameDiagnosticError", "CocErrorSign"),
  filenameDiagnosticWarning: hlg4(
    "FileFilenameDiagnosticWarning",
    "CocWarningSign"
  )
};
var FileSource = class extends ExplorerSource {
  constructor() {
    super(...arguments);
    this.scheme = "file";
    this.showHidden = this.config.get("file.showHiddenFiles");
    this.showOnlyGitChange = false;
    this.view = new ViewSource(
      this,
      fileColumnRegistrar,
      {
        type: "root",
        isRoot: true,
        uid: this.helper.getUid(import_path20.default.sep),
        name: "root",
        fullpath: (0, import_os4.homedir)(),
        expandable: true,
        directory: true,
        readonly: true,
        executable: false,
        readable: true,
        writable: true,
        hidden: false,
        symbolicLink: true,
        lstat: void 0
      }
    );
    this.rootStrategies = [];
  }
  get root() {
    return this.view.rootNode.fullpath;
  }
  set root(root2) {
    this.view.rootNode.uid = this.helper.getUid(root2);
    this.view.rootNode.fullpath = root2;
    this.view.rootNode.children = void 0;
  }
  getHiddenRules() {
    return this.config.get("file.hiddenRules");
  }
  isHidden(filename) {
    const hiddenRules = this.getHiddenRules();
    if (hiddenRules.patternMatches.some(
      (pattern) => new RegExp(pattern).test(filename)
    ))
      return true;
    const { basename: basename2, extensions: extensions3 } = getExtensions(filename);
    if (hiddenRules.filenames.includes(basename2))
      return true;
    const extname = extensions3[extensions3.length - 1];
    if (!extname)
      return false;
    return hiddenRules.extensions.includes(extname);
  }
  getNodesByPaths(fullpaths) {
    const fullpathSet = new Set(fullpaths);
    return this.view.flattenedNodes.filter(
      (node) => fullpathSet.has(node.fullpath)
    );
  }
  isGitChange(parentNode, filename) {
    return !!gitManager.getMixedStatus(
      `${parentNode.fullpath}/${filename}`,
      false
    );
  }
  getColumnConfig(name, defaultValue) {
    return this.config.get(`file.column.${name}`, defaultValue);
  }
  async init() {
    if (config.get("file.reveal.auto")) {
      this.disposables.push(
        onBufEnter(async (bufnr) => {
          if (bufnr === this.explorer.bufnr) {
            return;
          }
          if (!this.explorer.visible()) {
            return;
          }
          if (this.explorer.isFloating) {
            return;
          }
          await this.view.sync(async (r) => {
            var _a2;
            const fullpath = (_a2 = this.bufManager.getBufferNode(bufnr)) == null ? void 0 : _a2.fullpath;
            if (!fullpath) {
              return;
            }
            const [revealNode, notifiers] = await this.revealNodeByPathNotifier(
              r,
              fullpath
            );
            if (revealNode) {
              await Notifier.runAll(notifiers);
            }
          });
        }, 200)
      );
    }
    loadFileActions(this.action);
  }
  async open() {
    await this.view.parseTemplate(
      "root",
      await this.explorer.args.value(fileArgOptions.fileRootTemplate),
      await this.explorer.args.value(fileArgOptions.fileRootLabelingTemplate)
    );
    await this.view.parseTemplate(
      "child",
      await this.explorer.args.value(fileArgOptions.fileChildTemplate),
      await this.explorer.args.value(fileArgOptions.fileChildLabelingTemplate)
    );
    this.root = this.explorer.root;
    this.rootStrategies = this.explorer.argValues.rootStrategies;
  }
  async cd(fullpath) {
    const { nvim } = this;
    const escapePath = await nvim.call("fnameescape", fullpath);
    const cdCmd = this.config.get("file.cdCommand");
    if (cdCmd === "tcd") {
      if (import_coc61.workspace.isNvim || await nvim.call("exists", [":tcd"])) {
        await nvim.command(`tcd ${escapePath}`);
        await import_coc61.window.showInformationMessage(`Tab's CWD is: ${fullpath}`);
      }
    } else if (cdCmd === "cd") {
      await nvim.command(`cd ${escapePath}`);
      await import_coc61.window.showInformationMessage(`CWD is: ${fullpath}`);
    }
  }
  async openedNotifier(renderer, isFirst) {
    const args = this.explorer.args;
    const revealPath = await this.explorer.revealPath();
    if (!revealPath) {
      if (isFirst) {
        return this.locator.gotoRootNotifier({ col: 1 });
      }
      return Notifier.noop();
    }
    const hasRevealPath = args.has(argOptions.reveal);
    if (config.get("file.reveal.auto") || getRevealWhenOpen(this.config, this.explorer.argValues.revealWhenOpen) || hasRevealPath) {
      const [revealNode, notifiers] = await this.revealNodeByPathNotifier(
        renderer,
        revealPath
      );
      if (revealNode !== void 0) {
        return Notifier.combine(notifiers);
      } else if (isFirst) {
        return Notifier.combine([
          ...notifiers,
          await this.locator.gotoRootNotifier({ col: 1 })
        ]);
      }
    } else if (isFirst) {
      return this.locator.gotoRootNotifier({ col: 1 });
    }
    return Notifier.noop();
  }
  getPutTargetNode(node) {
    if (node.isRoot) {
      return this.view.rootNode;
    } else if (node.expandable && this.view.isExpanded(node)) {
      return node;
    } else if (node.parent) {
      return node.parent;
    } else {
      return this.view.rootNode;
    }
  }
  async searchByCocList(path3, {
    recursive,
    noIgnore,
    strict
  }) {
    const listArgs = strict ? ["--strict"] : [];
    const task = await startCocList(
      this.explorer,
      fileList,
      {
        showHidden: this.showHidden,
        showIgnores: noIgnore,
        rootPath: path3,
        recursive,
        revealCallback: async (loc) => {
          await task.waitExplorerShow();
          await this.view.sync(async (r) => {
            const [, notifiers] = await this.revealNodeByPathNotifier(
              r,
              import_coc61.Uri.parse(loc.uri).fsPath
            );
            await Notifier.runAll(notifiers);
          });
        }
      },
      listArgs
    );
    task.waitExplorerShow().catch(logger.error);
  }
  filterForReveal(path3, root2) {
    const filter2 = this.config.get("file.reveal.filter");
    const relativePath = path3.slice(root2.length);
    for (const literal of filter2.literals ?? []) {
      if (relativePath.includes(literal)) {
        return true;
      }
    }
    for (const pattern of filter2.patterns ?? []) {
      if (new RegExp(pattern).test(relativePath)) {
        return true;
      }
    }
    return false;
  }
  async revealNodeByPathNotifier(renderer, path3, {
    startNode = this.view.rootNode,
    goto = true,
    render = true,
    compact
  } = {}) {
    path3 = normalizePath(path3);
    if (this.filterForReveal(path3, startNode.fullpath)) {
      return [void 0, []];
    }
    const notifiers = [];
    const revealRecursive = async (path4, {
      startNode: startNode2,
      goto: goto2,
      render: render2
    }) => {
      if (path4 === startNode2.fullpath) {
        return startNode2;
      } else if (startNode2.directory && path4.startsWith(startNode2.fullpath + import_path20.default.sep)) {
        let foundNode2 = void 0;
        const isRender = render2 && !this.view.isExpanded(startNode2);
        if (!startNode2.children) {
          startNode2.children = await this.loadInitedChildren(startNode2);
        }
        for (const child of startNode2.children) {
          const childFoundNode = await revealRecursive(path4, {
            startNode: child,
            goto: false,
            render: isRender ? false : render2
          });
          foundNode2 = childFoundNode;
          if (foundNode2) {
            await this.view.expand(startNode2, {
              compact,
              uncompact: false,
              render: false
            });
            break;
          }
        }
        if (foundNode2) {
          if (isRender) {
            const renderNotifier = await renderer.renderNotifier({
              node: startNode2
            });
            notifiers.push(renderNotifier);
          }
          if (goto2) {
            notifiers.push(await this.locator.gotoNodeNotifier(foundNode2));
            notifiers.push(
              Notifier.create(() => this.nvim.command("redraw!", true))
            );
          }
        }
        return foundNode2;
      }
    };
    const foundNode = await revealRecursive(path3, {
      startNode,
      goto,
      render
    });
    return [foundNode, notifiers];
  }
  sortFiles(files) {
    return files.sort((a, b) => {
      if (a.directory && !b.directory) {
        return -1;
      } else if (b.directory && !a.directory) {
        return 1;
      } else {
        return a.name.localeCompare(b.name);
      }
    });
  }
  async loadChildren(parentNode) {
    let filenames;
    if (isWindows2 && parentNode.fullpath === "") {
      filenames = await listDrive();
    } else {
      filenames = await fsReaddir(parentNode.fullpath);
    }
    const files = await Promise.all(
      filenames.map(async (filename) => {
        try {
          if (this.showOnlyGitChange && !this.isGitChange(parentNode, filename)) {
            return;
          }
          const hidden = this.isHidden(filename);
          if (!this.showHidden && hidden) {
            return;
          }
          const fullpath = normalizePath(
            import_path20.default.join(parentNode.fullpath, filename)
          );
          const stat3 = await fsStat(fullpath).catch(() => {
          });
          const lstat6 = await fsLstat(fullpath).catch(() => {
          });
          const executable2 = await fsAccess(fullpath, import_fs13.default.constants.X_OK);
          const writable = await fsAccess(fullpath, import_fs13.default.constants.W_OK);
          const readable = await fsAccess(fullpath, import_fs13.default.constants.R_OK);
          const directory = isWindows2 && /^[A-Za-z]:[\\/]$/.test(fullpath) ? true : stat3 ? stat3.isDirectory() : false;
          const child = {
            type: "child",
            uid: this.helper.getUid(fullpath),
            expandable: directory,
            name: filename,
            fullpath,
            directory,
            readonly: !writable && readable,
            executable: executable2,
            readable,
            writable,
            hidden,
            symbolicLink: lstat6 ? lstat6.isSymbolicLink() : false,
            lstat: lstat6 || void 0
          };
          return child;
        } catch (error) {
          logger.error(error);
        }
      })
    );
    return this.sortFiles(files.filter((r) => !!r));
  }
};
sourceManager.registerSource("file", FileSource);

// src/highlight/filename.ts
var FilenameHighlight = class {
  constructor(config4) {
    const configKey = "filename.colored.enable";
    const enabledCompletely = config4.get(
      configKey,
      false
      // This check because it might be an object, which is truthy
    ) === true;
    this.enabledGitStatus = enabledCompletely || config4.get(`${configKey}.git`, false);
    this.enabledErrorStatus = enabledCompletely || config4.get(`${configKey}.diagnosticError`, false);
    this.enabledWarningStatus = enabledCompletely || config4.get(`${configKey}.diagnosticWarning`, false);
  }
  getGitHighlight(status) {
    return status.x === "!" /* ignored */ ? gitHighlights.ignored : getGitFormatHighlight(status.y);
  }
  getHighlight(fullpath, isDirectory, highlightOrder) {
    for (const type of highlightOrder) {
      switch (type) {
        case "diagnosticWarning":
          if (this.enabledWarningStatus) {
            const warning = diagnosticManager.getMixedWarning(fullpath);
            if (warning) {
              return fileHighlights.diagnosticWarning;
            }
          }
          break;
        case "diagnosticError":
          if (this.enabledErrorStatus) {
            const error = diagnosticManager.getMixedError(fullpath);
            if (error) {
              return fileHighlights.diagnosticError;
            }
          }
          break;
        case "git":
          if (this.enabledGitStatus) {
            const status = gitManager.getMixedStatus(fullpath, isDirectory);
            if (status) {
              return this.getGitHighlight(status);
            }
          }
          break;
      }
    }
  }
};

// src/source/sources/buffer/child-columns/git.ts
bufferColumnRegistrar.registerColumn(
  "child",
  "git",
  ({ source, subscriptions }) => {
    const filenameHighlight = new FilenameHighlight(source.config);
    const icons = getStatusIcons(source.config);
    const getHighlight = (fullpath, staged) => {
      if (staged) {
        return gitHighlights.staged;
      } else {
        return filenameHighlight.getHighlight(fullpath, false, ["git"]) ?? gitHighlights.unstaged;
      }
    };
    return {
      init() {
        subscriptions.push(gitManager.bindColumn(source));
      },
      async available() {
        return await gitManager.cmd.available();
      },
      async draw() {
        return {
          async labelVisible({ node }) {
            const status = gitManager.getMixedStatus(node.fullpath, false);
            if (!status) {
              return false;
            }
            return status.x !== " " /* unmodified */ || status.y !== " " /* unmodified */;
          },
          drawNode(row, { node, nodeIndex, isLabeling }) {
            const showFormat = (f, staged) => {
              const hl = getHighlight(node.fullpath, staged);
              if (isLabeling) {
                row.add(`${icons[f].name}(${icons[f].icon})`, {
                  hl
                });
              } else {
                row.add(icons[f].icon, {
                  hl
                });
              }
            };
            const status = gitManager.getMixedStatus(node.fullpath, false);
            if (status) {
              showFormat(status.x, true);
              if (isLabeling) {
                row.add(" ");
              }
              showFormat(status.y, false);
              if (status.x === "!" /* ignored */) {
                source.locator.mark.remove("git", nodeIndex);
                source.locator.mark.remove("gitStaged", nodeIndex);
                source.locator.mark.remove("gitUnstaged", nodeIndex);
              } else {
                source.locator.mark.add("git", nodeIndex);
                if (status.x !== " " /* unmodified */) {
                  source.locator.mark.add("gitStaged", nodeIndex);
                } else {
                  source.locator.mark.remove("gitStaged", nodeIndex);
                }
                if (status.y !== " " /* unmodified */) {
                  source.locator.mark.add("gitUnstaged", nodeIndex);
                } else {
                  source.locator.mark.remove("gitUnstaged", nodeIndex);
                }
              }
            } else {
              source.locator.mark.remove("git", nodeIndex);
              source.locator.mark.remove("gitStaged", nodeIndex);
              source.locator.mark.remove("gitUnstaged", nodeIndex);
            }
          }
        };
      }
    };
  }
);

// src/source/sources/buffer/child-columns/selection.ts
bufferColumnRegistrar.registerColumn("child", "selection", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (source.isSelectedNode(node)) {
          row.add(source.icons.selected);
        }
      }
    };
  }
}));

// src/source/sources/buffer/child-columns/name.ts
bufferColumnRegistrar.registerColumn("child", "name", ({ source }) => {
  const filenameHighlight = new FilenameHighlight(source.config);
  const getHighlight = (fullpath, visible) => {
    return filenameHighlight.getHighlight(fullpath, false, [
      "diagnosticError",
      "diagnosticWarning",
      "git"
    ]) ?? (visible ? bufferHighlights.nameVisible : void 0);
  };
  return {
    draw() {
      return {
        drawNode(row, { node }) {
          row.add(node.name, {
            hl: getHighlight(node.fullpath, node.visible)
          });
        }
      };
    }
  };
});

// src/source/sources/buffer/child-columns/bufname.ts
bufferColumnRegistrar.registerColumn("child", "bufname", () => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(node.bufname, { hl: bufferHighlights.bufname });
      }
    };
  }
}));

// src/source/sources/buffer/child-columns/modified.ts
bufferColumnRegistrar.registerColumn("child", "modified", ({ source }) => ({
  draw() {
    return {
      labelVisible({ node }) {
        return node.modified || !node.modifiable;
      },
      drawNode(row, { node, nodeIndex }) {
        const ch = node.modified ? "+" : node.modifiable ? "" : "-";
        if (ch) {
          row.add(ch, { hl: bufferHighlights.modified });
        }
        node.modified ? source.locator.mark.add("modified", nodeIndex) : source.locator.mark.remove("modified", nodeIndex);
      }
    };
  }
}));

// src/source/sources/buffer/child-columns/bufnr.ts
bufferColumnRegistrar.registerColumn("child", "bufnr", () => {
  let prevMaxBufnrWidth = 0;
  return {
    draw(nodes, { drawAll, abort }) {
      const maxBufnrWidth = max_default(nodes.map((node) => node.bufnrStr.length));
      if (!maxBufnrWidth) {
        return abort();
      }
      if (prevMaxBufnrWidth !== maxBufnrWidth) {
        prevMaxBufnrWidth = maxBufnrWidth;
        drawAll();
      }
      return {
        drawNode(row, { node }) {
          row.add(node.bufnrStr.padStart(prevMaxBufnrWidth), {
            hl: bufferHighlights.bufnr
          });
        }
      };
    }
  };
});

// src/source/sources/buffer/child-columns/diagnosticError.ts
bufferColumnRegistrar.registerColumn(
  "child",
  "diagnosticError",
  ({ source, subscriptions }) => {
    const diagnosticConfig = getDiagnosticConfig(source.config);
    return {
      init() {
        subscriptions.push(diagnosticManager.bindColumn(source, ["error"]));
      },
      draw() {
        return {
          labelVisible: ({ node }) => !!diagnosticManager.getMixedError(node.fullpath),
          drawNode(row, { node, isLabeling }) {
            const errorCount = diagnosticManager.getMixedError(node.fullpath);
            if (isLabeling) {
              row.add((errorCount ?? 0).toString(), {
                hl: diagnosticHighlights.diagnosticError
              });
              return;
            }
            if (!errorCount) {
              return;
            }
            row.add(printDiagnosticCount(errorCount, diagnosticConfig), {
              hl: diagnosticHighlights.diagnosticError
            });
          }
        };
      }
    };
  }
);

// src/source/sources/buffer/child-columns/diagnosticWarning.ts
bufferColumnRegistrar.registerColumn(
  "child",
  "diagnosticWarning",
  ({ source, subscriptions }) => {
    const diagnosticConfig = getDiagnosticConfig(source.config);
    return {
      init() {
        subscriptions.push(diagnosticManager.bindColumn(source, ["warning"]));
      },
      draw() {
        return {
          labelVisible: ({ node }) => !!diagnosticManager.getMixedWarning(node.fullpath),
          drawNode(row, { node, isLabeling }) {
            const warningCount = diagnosticManager.getMixedWarning(
              node.fullpath
            );
            if (isLabeling) {
              row.add((warningCount ?? 0).toString(), {
                hl: diagnosticHighlights.diagnosticWarning
              });
              return;
            }
            if (!warningCount) {
              return;
            }
            row.add(printDiagnosticCount(warningCount, diagnosticConfig), {
              hl: diagnosticHighlights.diagnosticWarning
            });
          }
        };
      }
    };
  }
);

// src/source/sources/buffer/child-columns/readonly.ts
bufferColumnRegistrar.registerColumn("child", "readonly", ({ source }) => ({
  draw() {
    return {
      labelOnly: true,
      labelVisible: ({ node }) => node.readonly,
      drawNode(row, { node }) {
        if (node.readonly) {
          row.add(source.icons.readonly, {
            hl: bufferHighlights.readonly
          });
        }
      }
    };
  }
}));

// src/source/sources/buffer/child-columns/fullpath.ts
bufferColumnRegistrar.registerColumn("child", "fullpath", () => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(displayedFullpath(node.fullpath), {
          hl: bufferHighlights.fullpath
        });
      }
    };
  }
}));

// src/source/sources/buffer/child-columns/relativePath.ts
var import_path21 = __toESM(require("path"));
bufferColumnRegistrar.registerColumn("child", "relativePath", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        const relativePath = import_path21.default.relative(source.root, node.fullpath);
        row.add(relativePath, {
          hl: bufferHighlights.fullpath
        });
      }
    };
  }
}));

// src/source/sources/buffer/bufferSource.ts
var hlg5 = hlGroupManager.linkGroup.bind(hlGroupManager);
var bufferHighlights = {
  title: hlg5("BufferRoot", "Constant"),
  hidden: hlg5("BufferHidden", internalHighlightGroups.CommentColor),
  expandIcon: hlg5("BufferExpandIcon", "Directory"),
  nameVisible: hlg5("BufferNameVisible", "String"),
  bufname: hlg5("BufferBufname", internalHighlightGroups.CommentColor),
  modified: hlg5("BufferModified", "Operator"),
  bufnr: hlg5("BufferBufnr", "Special"),
  readonly: hlg5("BufferReadonly", "Operator"),
  fullpath: hlg5("BufferFullpath", internalHighlightGroups.CommentColor)
};
var BufferSource = class extends ExplorerSource {
  constructor() {
    super(...arguments);
    this.showHidden = this.config.get("file.showHiddenBuffers");
    this.view = new ViewSource(
      this,
      bufferColumnRegistrar,
      {
        type: "root",
        isRoot: true,
        expandable: true,
        uid: this.helper.getUid("0"),
        bufnr: 0,
        bufnrStr: "0",
        bufname: "",
        fullpath: "",
        name: "",
        unlisted: true,
        current: false,
        previous: false,
        visible: false,
        hidden: false,
        modifiable: false,
        readonly: true,
        terminal: false,
        modified: false,
        readErrors: false
      }
    );
  }
  async init() {
    this.disposables.push(
      this.bufManager.onReloadDebounce(async () => {
        if (!this.explorer.visible()) {
          return;
        }
        await this.load(this.view.rootNode);
      }),
      this.bufManager.onModifiedDebounce(async () => {
        if (!this.explorer.visible()) {
          return;
        }
        await this.load(this.view.rootNode);
      })
    );
    this.tabId = await tabContainerManager.currentTabId();
    loadBufferActions(this.action);
  }
  async open() {
    await this.view.parseTemplate(
      "root",
      await this.explorer.args.value(bufferArgOptions.bufferRootTemplate)
    );
    await this.view.parseTemplate(
      "child",
      await this.explorer.args.value(bufferArgOptions.bufferChildTemplate),
      await this.explorer.args.value(
        bufferArgOptions.bufferChildLabelingTemplate
      )
    );
  }
  async loadChildren(_parentNode, { force = false } = {}) {
    if (force) {
      await this.bufManager.reload();
    }
    const tabOnly = bufferTabOnly();
    const bufferNodes = this.bufManager.bufferNodes;
    if (this.showHidden) {
      return [...bufferNodes];
    } else {
      if (tabOnly) {
        const tabContainer = this.tabId ? tabContainerManager.get(this.tabId) : await tabContainerManager.currentTabContainer();
        let bufnrs = [];
        if (tabContainer == null ? void 0 : tabContainer.bufnrs) {
          bufnrs = [...tabContainer.bufnrs];
        }
        return bufferNodes.filter(
          (it) => bufnrs.includes(it.bufnr) && !it.unlisted
        );
      } else {
        return bufferNodes.filter((it) => !it.unlisted);
      }
    }
  }
};
sourceManager.registerSource("buffer", BufferSource);

// src/source/sources/bookmark/bookmarkSource.ts
var import_coc62 = require("coc.nvim");
var import_path23 = __toESM(require("path"));

// src/source/sources/bookmark/argOptions.ts
var bookmarkArgOptions = {
  bookmarkRootTemplate: Args.registerOption("bookmark-root-template", {
    getDefault: () => config.get("bookmark.root.template")
  }),
  bookmarkChildTemplate: Args.registerOption(
    "bookmark-child-template",
    {
      getDefault: () => config.get("bookmark.child.template")
    }
  ),
  bookmarkChildLabelingTemplate: Args.registerOption(
    "bookmark-child-labeling-template",
    {
      getDefault: () => config.get("bookmark.child.labelingTemplate")
    }
  )
};

// src/source/sources/bookmark/bookmarkColumnRegistrar.ts
var BookmarkColumnRegistrar = class extends ColumnRegistrar {
};
var bookmarkColumnRegistrar = new BookmarkColumnRegistrar();

// src/source/sources/bookmark/root-columns/icon.ts
bookmarkColumnRegistrar.registerColumn("root", "icon", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(
          source.view.isExpanded(node) ? source.icons.expanded : source.icons.collapsed,
          { hl: bookmarkHighlights.expandIcon }
        );
      }
    };
  }
}));

// src/source/sources/bookmark/root-columns/title.ts
bookmarkColumnRegistrar.registerColumn("root", "title", () => ({
  draw() {
    return {
      drawNode(row) {
        row.add("[BOOKMARK]", {
          hl: bookmarkHighlights.title
        });
      }
    };
  }
}));

// src/source/sources/bookmark/root-columns/hidden.ts
bookmarkColumnRegistrar.registerColumn("root", "hidden", ({ source }) => ({
  draw() {
    return {
      drawNode(row) {
        row.add(source.showHidden ? source.icons.hidden : "", {
          hl: bookmarkHighlights.hidden
        });
      }
    };
  }
}));

// src/source/sources/bookmark/child-columns/selection.ts
bookmarkColumnRegistrar.registerColumn("child", "selection", ({ source }) => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (source.isSelectedNode(node)) {
          row.add(source.icons.selected);
        }
      }
    };
  }
}));

// src/source/sources/bookmark/child-columns/position.ts
bookmarkColumnRegistrar.registerColumn("child", "position", () => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(`line: ${node.lnum}`, { hl: bookmarkHighlights.position });
      }
    };
  }
}));

// src/source/sources/bookmark/child-columns/filename.ts
bookmarkColumnRegistrar.registerColumn("child", "filename", () => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(node.name, { hl: bookmarkHighlights.filename });
      }
    };
  }
}));

// src/source/sources/bookmark/child-columns/fullpath.ts
bookmarkColumnRegistrar.registerColumn("child", "fullpath", () => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(displayedFullpath(node.fullpath), {
          hl: bookmarkHighlights.fullpath
        });
      }
    };
  }
}));

// src/source/sources/bookmark/child-columns/line.ts
bookmarkColumnRegistrar.registerColumn("child", "line", () => ({
  draw() {
    return {
      drawNode(row, { node }) {
        row.add(node.line, { hl: bookmarkHighlights.line });
      }
    };
  }
}));

// src/source/sources/bookmark/child-columns/annotation.ts
bookmarkColumnRegistrar.registerColumn("child", "annotation", () => ({
  draw() {
    return {
      drawNode(row, { node }) {
        if (node.annotation) {
          row.add(node.annotation, { hl: bookmarkHighlights.annotation });
        }
      }
    };
  }
}));

// src/source/sources/bookmark/util/db.ts
var import_path22 = __toESM(require("path"));
var BookmarkDB = class {
  constructor(filepath) {
    this.filepath = filepath;
  }
  async load() {
    const dir = import_path22.default.dirname(this.filepath);
    const stat3 = await fsStat(dir).catch(() => null);
    if (!stat3 || !stat3.isDirectory()) {
      return {};
    }
    try {
      const content = await fsReadFile(this.filepath, { encoding: "utf8" });
      return JSON.parse(content.trim());
    } catch {
      return {};
    }
  }
  async fetch(key) {
    let obj = await this.load();
    if (!key) {
      return obj;
    }
    const parts = key.split(".");
    for (const part of parts) {
      if (typeof obj[part] === "undefined") {
        return void 0;
      }
      obj = obj[part];
    }
    return obj;
  }
  async exists(key) {
    let obj = await this.load();
    const parts = key.split(".");
    for (const part of parts) {
      if (typeof obj[part] === "undefined") {
        return false;
      }
      obj = obj[part];
    }
    return true;
  }
  async push(key, data) {
    const origin = await this.load() || {};
    let obj = origin;
    const parts = key.split(".");
    const len = parts.length;
    if (obj === null) {
      const dir = import_path22.default.dirname(this.filepath);
      await fsMkdirp(dir);
      obj = origin;
    }
    for (let i = 0; i < len; i++) {
      const key2 = parts[i];
      if (i === len - 1) {
        obj[key2] = data;
        await fsWriteFile(this.filepath, JSON.stringify(origin, null, 2));
        break;
      }
      if (typeof obj[key2] === "undefined") {
        obj[key2] = {};
        obj = obj[key2];
      } else {
        obj = obj[key2];
      }
    }
  }
  async delete(key) {
    let obj = await this.load();
    const origin = obj;
    const parts = key.split(".");
    const len = parts.length;
    for (let i = 0; i < len; i++) {
      if (typeof obj[parts[i]] === "undefined") {
        break;
      }
      if (i === len - 1) {
        delete obj[parts[i]];
        await fsWriteFile(this.filepath, JSON.stringify(origin, null, 2));
        break;
      }
      obj = obj[parts[i]];
    }
  }
  async clear() {
    const stat3 = await fsStat(this.filepath).catch(() => null);
    if (!stat3 || !stat3.isFile()) {
      return;
    }
    await fsWriteFile(this.filepath, "{}");
  }
};

// src/source/sources/bookmark/util/encodeDecode.ts
function decode(text) {
  return decodeURIComponent(text);
}

// src/source/sources/bookmark/bookmarkSource.ts
var hlg6 = hlGroupManager.linkGroup.bind(hlGroupManager);
var bookmarkHighlights = {
  title: hlg6("BookmarkRoot", "Constant"),
  hidden: hlg6("BookmarkHidden", "Commment"),
  expandIcon: hlg6("BookmarkExpandIcon", "Directory"),
  filename: hlg6("BookmarkFilename", "String"),
  fullpath: hlg6("BookmarkFullpath", "Special"),
  position: hlg6("BookmarkPosition", "Comment"),
  line: hlGroupManager.createGroup(
    "BookmarkLine",
    "ctermbg=27 ctermfg=0 guibg=#1593e5 guifg=#ffffff"
  ),
  annotation: hlg6("BookmarkAnnotation", "Comment")
};
var BookmarkSource = class extends ExplorerSource {
  constructor() {
    super(...arguments);
    this.view = new ViewSource(
      this,
      bookmarkColumnRegistrar,
      {
        type: "root",
        isRoot: true,
        expandable: true,
        uid: this.helper.getUid("0"),
        name: "",
        fullpath: "",
        lnum: -1,
        line: "",
        annotation: void 0
      }
    );
  }
  static get enabled() {
    return import_coc62.extensions.getExtensionState("coc-bookmark") === "activated";
  }
  async init() {
    this.disposables.push(
      internalEvents.on(
        "CocBookmarkChange",
        debounceFn(500, async () => {
          await this.load(this.view.rootNode);
        })
      )
    );
  }
  async open() {
    await this.view.parseTemplate(
      "root",
      await this.explorer.args.value(bookmarkArgOptions.bookmarkRootTemplate)
    );
    await this.view.parseTemplate(
      "child",
      await this.explorer.args.value(bookmarkArgOptions.bookmarkChildTemplate),
      await this.explorer.args.value(
        bookmarkArgOptions.bookmarkChildLabelingTemplate
      )
    );
    this.view.rootNode.fullpath = this.explorer.root;
  }
  async loadChildren(parentNode) {
    var _a2;
    const extRoot = import_coc62.workspace.env.extensionRoot;
    const bookmarkPath = import_path23.default.join(
      extRoot,
      "coc-bookmark-data/bookmark.json"
    );
    const db = new BookmarkDB(bookmarkPath);
    const data = await db.load();
    const bookmarkNodes = [];
    for (const [filepath, bookmarks] of Object.entries(data)) {
      const fullpath = normalizePath(decode(filepath));
      if (!this.showHidden && !fullpath.startsWith(parentNode.fullpath) || !await fsExists(fullpath)) {
        continue;
      }
      for (const lnum of Object.keys(bookmarks).map((l) => Number(l)).sort((l1, l2) => l1 - l2)) {
        const bookmark = bookmarks[lnum];
        if (bookmark)
          bookmarkNodes.push({
            type: "child",
            uid: this.helper.getUid(`${fullpath}:${lnum}`),
            fullpath,
            name: import_path23.default.basename(fullpath),
            lnum,
            location: import_coc62.Location.create(
              fullpath,
              import_coc62.Range.create(lnum, -1, lnum, -1)
            ),
            line: bookmark.line,
            annotation: (_a2 = bookmark.annotation) == null ? void 0 : _a2.toString()
          });
      }
    }
    return bookmarkNodes;
  }
};
sourceManager.registerSource("bookmark", BookmarkSource);

// src/view/viewExplorer.ts
var ViewExplorer = class {
  constructor(explorer) {
    this.explorer = explorer;
    this.isHelpUI = false;
    this.currentLineIndex = 0;
    this[rendererExplorerSymbol] = new RendererExplorer(this);
  }
  async sync(block) {
    return await block(this[rendererExplorerSymbol]);
  }
  get flattenedNodes() {
    return this.explorer.sources.reduce((ret, cur) => {
      return ret.concat(cur.view.flattenedNodes);
    }, []);
  }
  async refreshLineIndex() {
    const win = await this.explorer.win;
    if (win) {
      const cursor = await win.cursor;
      this.currentLineIndex = cursor[0] - 1;
    }
  }
  async currentSource() {
    return this.explorer.sources[await this.currentSourceIndex()];
  }
  async currentSourceIndex() {
    const lineIndex = this.currentLineIndex;
    return this.explorer.sources.findIndex(
      (source) => lineIndex >= source.view.startLineIndex && lineIndex < source.view.endLineIndex
    );
  }
  async currentNode() {
    const source = await this.currentSource();
    if (source) {
      const nodeIndex = this.currentLineIndex - source.view.startLineIndex;
      return source.view.flattenedNodes[nodeIndex];
    }
  }
  async emitRequestRenderNodes() {
    await this.sync(async (r) => {
      const notifiers = await Promise.all(
        r.rendererSources().map((s) => s.emitRequestRenderNodesNotifier())
      );
      await Notifier.runAll(notifiers);
    });
  }
};
rendererExplorerSymbol;

// src/explorer.ts
var Explorer = class _Explorer {
  constructor(explorerID, explorerManager, bufnr, borderBufnr, config4) {
    this.explorerID = explorerID;
    this.explorerManager = explorerManager;
    this.bufnr = bufnr;
    this.borderBufnr = borderBufnr;
    this.config = config4;
    this.nvim = import_coc63.workspace.nvim;
    this.contentWidth = 0;
    this.action = new ActionExplorer(this);
    this.highlight = new HighlightExplorer(this);
    this.view = new ViewExplorer(this);
    this.locator = new LocatorExplorer(this);
    this.events = new HelperEventEmitter(logger);
    this.firstOpened = false;
    this.disposables = [];
    this.isHide = false;
    this.context = explorerManager.context;
    this.buffer = this.nvim.createBuffer(this.bufnr);
    this.inited = new BuffuerContextVars("inited", this.buffer);
    this.sourceWinid = new BuffuerContextVars(
      "sourceWinid",
      this.buffer
    );
    this.sourceBufnr = new BuffuerContextVars(
      "sourceBufnr",
      this.buffer
    );
    this.floatingPreview = new FloatingPreview(this);
    if (borderBufnr) {
      this.disposables.push(
        onEvent("BufWinLeave", async (curBufnr) => {
          if (curBufnr === bufnr) {
            await closeWinByBufnrNotifier([borderBufnr]).run();
          }
        })
      );
    }
    loadGlobalActions(this.action);
  }
  static genExplorerPosition(args, specialSize) {
    let width = 0;
    let height = 0;
    let left = 0;
    let top = 0;
    if (args.position.name !== "floating") {
      width = (specialSize == null ? void 0 : specialSize.width) ?? args.width;
    } else {
      width = (specialSize == null ? void 0 : specialSize.width) ?? args.floatingWidth;
      height = (specialSize == null ? void 0 : specialSize.height) ?? args.floatingHeight;
      const [vimWidth, vimHeight] = [
        import_coc63.workspace.env.columns,
        import_coc63.workspace.env.lines - import_coc63.workspace.env.cmdheight
      ];
      if (width <= 0) {
        width = vimWidth + width;
      }
      if (height <= 0) {
        height = vimHeight + height;
      }
      const floatingPosition = args.floatingPosition;
      if (floatingPosition === "left-center") {
        left = 0;
        top = (vimHeight - height) / 2;
      } else if (floatingPosition === "center") {
        left = (vimWidth - width) / 2;
        top = (vimHeight - height) / 2;
      } else if (floatingPosition === "right-center") {
        left = vimWidth - width;
        top = (vimHeight - height) / 2;
      } else if (floatingPosition === "center-top") {
        left = (vimWidth - width) / 2;
        top = 0;
      } else {
        [left, top] = floatingPosition;
      }
    }
    return { width, height, top, left };
  }
  static async create(explorerManager, argValues, config4) {
    explorerManager.maxExplorerID += 1;
    const { width, height, top, left } = this.genExplorerPosition(argValues);
    const [bufnr, borderBufnr] = await import_coc63.workspace.nvim.call("coc_explorer#open_explorer", [
      explorerManager.maxExplorerID,
      argValues.position,
      {
        width,
        height,
        left,
        top,
        focus: argValues.focus,
        border_enable: config4.get("floating.border.enable"),
        border_chars: config4.get("floating.border.chars"),
        title: config4.get("floating.border.title")
      }
    ]);
    const explorer = new _Explorer(
      explorerManager.maxExplorerID,
      explorerManager,
      bufnr,
      borderBufnr,
      config4
    );
    await explorer.inited.set(true);
    return explorer;
  }
  dispose() {
    this.floatingPreview.dispose();
    this.disposables.forEach((s) => s.dispose());
  }
  get root() {
    if (!this.root_) {
      throw Error("Explorer root not initialized yet");
    }
    return this.root_;
  }
  get args() {
    if (!this.args_) {
      throw Error("Explorer args not initialized yet");
    }
    return this.args_;
  }
  get argValues() {
    if (!this.argValues_) {
      throw Error("Explorer argValues not initialized yet");
    }
    return this.argValues_;
  }
  get isFloating() {
    if (this.isFloating_ === void 0) {
      throw Error("Explorer isFloating not initialized yet");
    }
    return this.isFloating_;
  }
  get sources() {
    if (!this.sources_) {
      throw Error("Explorer sources not initialized yet");
    }
    return this.sources_;
  }
  get height() {
    return sum_default(this.sources.map((s) => s.height));
  }
  get win() {
    return this.winid.then(winByWinid);
  }
  /**
   * vim winnr of explorer
   */
  get winnr() {
    return winnrByBufnr(this.bufnr);
  }
  /**
   * vim winid of explorer
   */
  get winid() {
    return this.winnr.then(winidByWinnr);
  }
  get borderWin() {
    return this.borderWinid.then(winByWinid);
  }
  get borderWinnr() {
    return winnrByBufnr(this.borderBufnr);
  }
  get borderWinid() {
    return this.borderWinnr.then(winidByWinnr);
  }
  async sourceWinnr() {
    const winid = await this.sourceWinid.get();
    if (!winid) {
      return void 0;
    }
    const winnr = await this.nvim.call("win_id2win", [winid]);
    if (winnr <= 0 || (await this.explorerManager.winnrs()).includes(winnr)) {
      return;
    }
    return winnr;
  }
  async sourceBufnrBySourceWinid() {
    const winid = await this.sourceWinid.get();
    if (!winid) {
      return;
    }
    const bufnr = await this.nvim.call("winbufnr", [winid]);
    if (bufnr <= 0) {
      return;
    }
    return bufnr;
  }
  async sourceBuffer() {
    const bufnr = await this.sourceBufnr.get();
    if (!bufnr) {
      return;
    }
    return this.nvim.createBuffer(bufnr);
  }
  visible() {
    const node = this.explorerManager.bufManager.getBufferNode(this.bufnr);
    return node == null ? void 0 : node.visible;
  }
  async refreshWidth() {
    const window9 = await this.win;
    if (!window9) {
      return;
    }
    const setWidth = async (contentWidthType, contentWidth) => {
      if (contentWidth <= 0) {
        let contentBaseWidth;
        switch (contentWidthType) {
          case "win-width":
            contentBaseWidth = await window9.width;
            if (await window9.getOption("relativenumber") || await window9.getOption("number")) {
              contentBaseWidth -= await window9.getOption(
                "numberwidth"
              );
            }
            break;
          case "vim-width":
            contentBaseWidth = await import_coc63.workspace.nvim.eval(
              "&columns"
            );
            break;
        }
        if (contentBaseWidth) {
          this.contentWidth = contentBaseWidth + contentWidth;
          return true;
        }
      } else {
        this.contentWidth = contentWidth;
        return true;
      }
      return false;
    };
    if (this.isFloating) {
      if (await setWidth("win-width", this.argValues.floatingContentWidth)) {
        return;
      }
    }
    await setWidth(
      this.argValues.contentWidthType,
      this.argValues.contentWidth
    );
  }
  resizeNotifier(size) {
    return Notifier.create(() => {
      var _a2, _b;
      const dimension = _Explorer.genExplorerPosition(this.argValues, {
        width: (size == null ? void 0 : size[0]) ?? ((_a2 = this.storedSize) == null ? void 0 : _a2.width),
        height: (size == null ? void 0 : size[1]) ?? ((_b = this.storedSize) == null ? void 0 : _b.height)
      });
      const { top, left, width, height } = dimension;
      this.storedSize = {
        width,
        height
      };
      this.nvim.call(
        "coc_explorer#resize",
        [
          this.bufnr,
          this.argValues.position,
          {
            width,
            height,
            left,
            top,
            border_bufnr: this.borderBufnr,
            border_enable: this.config.get("floating.border.enable"),
            border_chars: this.config.get("floating.border.chars"),
            title: this.config.get("floating.border.title")
          }
        ],
        true
      );
    });
  }
  async resize(size) {
    await this.resizeNotifier(size).run();
  }
  async adjustSize(sizeOffset) {
    var _a2, _b;
    const [widthOff = 0, heightOff = 0] = sizeOffset ?? [0, 0];
    const dimension = _Explorer.genExplorerPosition(this.argValues, {
      width: (_a2 = this.storedSize) == null ? void 0 : _a2.width,
      height: (_b = this.storedSize) == null ? void 0 : _b.height
    });
    const { width, height } = dimension;
    await this.resize([width + widthOff, height + heightOff]);
  }
  /**
   * Focus on explorer window
   * @returns Whether the focus is successful
   */
  async focus() {
    const win = await this.win;
    if (win) {
      await this.nvim.command(`${await win.number}wincmd w`);
      await this.resize();
      return true;
    }
    return false;
  }
  async resume(argValues) {
    const { width, height, top, left } = _Explorer.genExplorerPosition(
      argValues,
      this.storedSize
    );
    await this.nvim.call("coc_explorer#resume", [
      this.bufnr,
      argValues.position,
      {
        width,
        height,
        left,
        top,
        focus: argValues.focus,
        border_bufnr: this.borderBufnr,
        border_enable: this.config.get("floating.border.enable"),
        border_chars: this.config.get("floating.border.chars"),
        title: this.config.get("floating.border.title")
      }
    ]);
  }
  async open(args, rooter, isFirst) {
    let firstOpen;
    if (!this.firstOpened) {
      firstOpen = true;
      this.firstOpened = true;
    } else {
      firstOpen = false;
    }
    if (firstOpen) {
      await this.events.fire("first-open-pre");
    }
    await this.events.fire("open-pre");
    await doUserAutocmd("CocExplorerOpenPre");
    this.rooter = rooter.open(this);
    if (this.view.isHelpUI) {
      await this.quitHelp();
    }
    await this.highlight.bootSyntax();
    const sourcesChanged = await this.initArgs(args, this.rooter);
    for (const source of this.sources) {
      await source.bootOpen(isFirst);
    }
    await this.view.sync(async (r) => {
      const notifiers = [];
      if (sourcesChanged) {
        notifiers.push(this.clearLinesNotifier());
      }
      notifiers.push(
        await this.loadAllNotifier(r),
        ...await Promise.all(
          r.rendererSources().map((rs) => rs.source.openedNotifier(rs, isFirst))
        )
      );
      await Notifier.runAll(notifiers);
      await doUserAutocmd("CocExplorerOpenPost");
      await this.events.fire("open-post");
      if (firstOpen) {
        await this.events.fire("first-open-post");
      }
    });
  }
  async tryQuitOnOpenNotifier() {
    if (this.argValues.quitOnOpen || this.isFloating) {
      return this.quitNotifier();
    }
    return Notifier.noop();
  }
  async tryQuitOnOpen() {
    return Notifier.run(this.tryQuitOnOpenNotifier());
  }
  async hide() {
    this.isHide = true;
    await this.quit(true);
  }
  async show() {
    if (this.isHide) {
      this.isHide = false;
      await this.resume(this.argValues);
    }
  }
  async quitNotifier(isHide = false) {
    if (!isHide) {
      await doUserAutocmd("CocExplorerQuitPre");
    }
    const sourceWinnr = await this.sourceWinnr();
    const bufnr = await currentBufnr();
    return Notifier.create(() => {
      if (sourceWinnr && this.bufnr === bufnr) {
        this.nvim.command(`${sourceWinnr}wincmd w`, true);
      }
      closeWinByBufnrNotifier([this.bufnr]).notify();
      if (!isHide) {
        doUserAutocmdNotifier("CocExplorerQuitPost").notify();
      }
    });
  }
  async quit(isHide = false) {
    return Notifier.run(await this.quitNotifier(isHide));
  }
  /**
   * initialize root
   */
  async initRoot(argValues, rooter) {
    const root2 = argValues.rootUri;
    if (root2) {
      this.root_ = normalizePath(root2);
      return;
    }
    let reveal;
    if (getRevealWhenOpen(this.config, this.argValues.revealWhenOpen)) {
      reveal = await this.revealPath();
    }
    const resolvedRoot = await rooter.resolveRoot(
      reveal,
      this.argValues.rootStrategies
    );
    if (resolvedRoot) {
      this.root_ = normalizePath(resolvedRoot);
      return;
    }
    this.root_ = normalizePath(import_coc63.workspace.cwd);
  }
  /**
   * initialize arguments
   *
   * @return sources changed
   */
  async initArgs(args, rooter) {
    this.args_ = args;
    this.argValues_ = await args.values(argOptions);
    await this.initRoot(this.argValues_, rooter);
    const argSources = await args.value(argOptions.sources);
    const enabledArgSources = await (0, import_p_filter2.default)(
      argSources,
      (s) => sourceManager.enabled(s.name)
    );
    const argSourcesEnabledJson = JSON.stringify(enabledArgSources);
    if (this.prevArgSourcesEnabledJson && this.prevArgSourcesEnabledJson === argSourcesEnabledJson) {
      return false;
    }
    this.prevArgSourcesEnabledJson = argSourcesEnabledJson;
    (0, import_coc63.disposeAll)(this.sources_ ?? []);
    this.sources_ = enabledArgSources.map(
      (sourceArg) => sourceManager.createSource(sourceArg.name, this, sourceArg.expand)
    );
    const position = await this.args_.value(argOptions.position);
    this.isFloating_ = position.name === "floating";
    return true;
  }
  async revealPath() {
    var _a2;
    const revealPath = await this.args.value(argOptions.reveal);
    if (revealPath) {
      return revealPath;
    } else {
      const buf = await this.sourceBuffer();
      if (buf) {
        return ((_a2 = this.explorerManager.bufManager.getBufferNode(buf.id)) == null ? void 0 : _a2.fullpath) ?? void 0;
      }
    }
  }
  async getSelectedOrCursorLineIndexes(mode) {
    await this.view.refreshLineIndex();
    const lineIndexes = /* @__PURE__ */ new Set();
    if (mode === "v") {
      const range = await import_coc63.window.getSelectedRange("v");
      if (range) {
        const startLine = range.start.line;
        const endLine = range.end.character !== 0 ? range.end.line : range.end.line - 1;
        for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) {
          lineIndexes.add(lineIndex);
        }
        return lineIndexes;
      }
    }
    lineIndexes.add(this.view.currentLineIndex);
    return lineIndexes;
  }
  findSourceByLineIndex(lineIndex) {
    if (!this.sources.length)
      throw new Error("No explorer sources");
    const [sourceIndex, source] = findPair(
      this.sources,
      (source2) => lineIndex < source2.view.endLineIndex
    );
    if (source)
      return { source, sourceIndex };
    else {
      const sourceIndex2 = this.sources.length - 1;
      const source2 = this.sources[sourceIndex2];
      return { source: source2, sourceIndex: sourceIndex2 };
    }
  }
  lineIndexesGroupBySource(lineIndexes) {
    const groups = /* @__PURE__ */ new Map();
    for (const line of lineIndexes) {
      const { source, sourceIndex } = this.findSourceByLineIndex(line);
      let group = groups.get(sourceIndex);
      if (!group) {
        group = {
          source,
          lineIndexes: [line]
        };
        groups.set(sourceIndex, group);
      }
      group.lineIndexes.push(line);
    }
    return [...groups.values()];
  }
  setLinesNotifier(lines, start, end) {
    return Notifier.create(() => {
      this.nvim.call(
        "coc_explorer#util#buf_set_lines_skip_cursor",
        [this.bufnr, start, end, false, lines],
        true
      );
    });
  }
  clearLinesNotifier() {
    return this.setLinesNotifier([], 0, -1);
  }
  async loadAllNotifier(renderer, { render = true } = {}) {
    this.locator.mark.removeAll();
    const notifiers = await Promise.all(
      renderer.rendererSources().map(
        (r) => r.source.loadNotifier(r, r.view.rootNode, { render: false })
      )
    );
    if (render) {
      notifiers.push(await renderer.renderAllNotifier());
    }
    return Notifier.combine(notifiers);
  }
  async render() {
    return this.view.sync(
      (renderer) => Notifier.run(renderer.renderAllNotifier())
    );
  }
  async showHelp(source) {
    return showHelp(this, source);
  }
  async quitHelp() {
    return quitHelp(this);
  }
};

// src/rooter.ts
var import_coc64 = require("coc.nvim");
var import_path24 = __toESM(require("path"));
var Rooter = class {
  constructor(workspaceRoot) {
    this.workspaceRoot = workspaceRoot;
  }
  open(explorer) {
    return new RooterOpened(this.workspaceRoot, explorer);
  }
};
var RooterOpened = class {
  constructor(workspaceRoot, explorer) {
    this.workspaceRoot = workspaceRoot;
    this.explorer = explorer;
    this.customRoots = {};
    const self2 = this;
    let sourceBufFullpath_ = null;
    const getSourceBufFullpath = async () => {
      if (sourceBufFullpath_ === null)
        sourceBufFullpath_ = await self2.resolveBufFullpath();
      return sourceBufFullpath_;
    };
    this.roots = {
      keep: () => void 0,
      workspace: () => workspaceRoot,
      cwd: () => import_coc64.workspace.cwd,
      sourceBuffer: () => {
        return getSourceBufFullpath();
      },
      reveal: (revealPath) => revealPath ? import_path24.default.dirname(revealPath) : void 0
    };
  }
  async resolveRootByPatterns(dir, patterns, bottomUp) {
    const ndir = normalizePath(dir);
    const parts = ndir.split(import_path24.default.sep);
    if (bottomUp) {
      while (parts.length > 0) {
        const dir2 = parts.join(import_path24.default.sep);
        if (await inDirectory(dir2, patterns)) {
          return dir2;
        }
        parts.pop();
      }
      return void 0;
    } else {
      const curr = [parts.shift()];
      for (const part of parts) {
        curr.push(part);
        const dir2 = curr.join(import_path24.default.sep);
        if (await inDirectory(dir2, patterns)) {
          return dir2;
        }
      }
      return void 0;
    }
  }
  async resolveRootBy(revealPath, strategyStr) {
    const strategy = strategyStr;
    const customPrefix = "custom:";
    if (rootStrategyList.includes(strategy)) {
      return this.roots[strategy](revealPath);
    } else if (strategy.startsWith(customPrefix)) {
      const customStrategy = strategy.slice(customPrefix.length);
      const customRules = this.explorer.config.get("root.customRules");
      const customRule = customRules[customStrategy];
      let dir = import_coc64.workspace.cwd;
      const sourceBufFullpath = await this.roots.sourceBuffer();
      if (sourceBufFullpath) {
        dir = sourceBufFullpath.endsWith(import_path24.default.sep) ? sourceBufFullpath : import_path24.default.dirname(sourceBufFullpath);
      }
      if (customRule) {
        return await this.resolveRootByPatterns(
          dir,
          customRule.patterns,
          customRule.bottomUp ?? false
        );
      }
    }
    logger.error(`${strategyStr} is not supported`);
    return void 0;
  }
  async resolveRoot(reveal, strategies) {
    if (strategies.includes("keep")) {
      return;
    }
    for (const strategy of strategies) {
      const root2 = await this.resolveRootBy(reveal, strategy);
      if (!root2) {
        continue;
      }
      if (!reveal) {
        return root2;
      }
      if (isParentFolder(root2, reveal)) {
        return root2;
      }
    }
  }
  async resolveBufFullpath() {
    var _a2;
    const buf = await this.explorer.sourceBuffer();
    if (!buf) {
      return void 0;
    }
    const buftype = await buf.getVar("&buftype");
    if (buftype === "nofile") {
      return void 0;
    }
    const fullpath = (_a2 = this.explorer.explorerManager.bufManager.getBufferNode(
      buf.id
    )) == null ? void 0 : _a2.fullpath;
    if (!fullpath) {
      return void 0;
    }
    return normalizePath(import_path24.default.dirname(fullpath));
  }
};

// src/source/sources/file/clipboard/base.ts
var ClipboardStorage = class {
  constructor(explorerManager) {
    this.explorerManager = explorerManager;
  }
};

// src/source/sources/file/clipboard/global-state.ts
var GlobalStateStorage = class extends ClipboardStorage {
  context() {
    return this.explorerManager.context;
  }
  async setFiles(type, fullpaths) {
    const newClip = {
      type,
      fullpaths
    };
    if (newClip.fullpaths.length === 0) {
      await this.clear();
    } else {
      await this.context().globalState.update("clipboard", newClip);
    }
  }
  async getFiles() {
    const content = this.context().globalState.get("clipboard");
    if (!content)
      return {
        type: "none",
        fullpaths: []
      };
    return content;
  }
  async clear() {
    await this.context().globalState.update("clipboard", void 0);
  }
};

// src/source/sources/file/clipboard/clipboard.ts
function getClipboard(explorerManager) {
  return new GlobalStateStorage(explorerManager);
}

// src/explorerManager.ts
var ExplorerManager = class {
  constructor(context2, bufManager) {
    this.context = context2;
    this.bufManager = bufManager;
    this.filetype = "coc-explorer";
    this.previousBufnr = new GlobalContextVars("previousBufnr");
    this.previousWindowID = new GlobalContextVars("previousWindowID");
    this.maxExplorerID = 0;
    this.nvim = import_coc65.workspace.nvim;
    this.events = new HelperEventEmitter(logger);
    this.waitInited = firstValueFrom(fromHelperEvent(this.events, "inited"));
    this.clipboardStorage = getClipboard(this);
    currentBufnr().then(this.updatePrevCtxVars.bind(this)).catch(logger.error);
    this.context.subscriptions.push(
      onBufEnter(async (bufnr) => {
        await this.updatePrevCtxVars(bufnr);
      }, 0)
    );
    this.context.subscriptions.push(
      import_coc65.Disposable.create(() => (0, import_coc65.disposeAll)(this.explorers()))
    );
  }
  async updatePrevCtxVars(bufnr) {
    if (isTest)
      return;
    if (!this.bufnrs().includes(bufnr)) {
      const bufname = await this.nvim.call("bufname");
      if (bufname.startsWith("list://") || bufname.startsWith("[coc-explorer]")) {
        return;
      }
      const filetype = await this.nvim.getVar("&filetype");
      if (filetype !== this.filetype) {
        await this.previousBufnr.set(bufnr);
        const winid = await this.nvim.call("win_getid");
        await this.previousWindowID.set(winid === -1 ? void 0 : winid);
      }
    }
  }
  async prevWinnrByPrevBufnr() {
    const previousBufnr = await this.previousBufnr.get();
    if (!previousBufnr) {
      return;
    }
    const winnr = await this.nvim.call("bufwinnr", [previousBufnr]);
    if (winnr <= 0 || (await this.winnrs()).includes(winnr)) {
      return;
    }
    return winnr;
  }
  async prevWinnrByPrevWindowID() {
    const previousWindowID = await this.previousWindowID.get();
    if (!previousWindowID) {
      return;
    }
    const winnr = await this.nvim.call("win_id2win", [
      previousWindowID
    ]);
    if (winnr <= 0 || (await this.winnrs()).includes(winnr)) {
      return;
    }
    return winnr;
  }
  bufnrs() {
    return this.explorers().map((explorer) => explorer.bufnr);
  }
  async winids() {
    return compactI2(
      await Promise.all(this.explorers().map((explorer) => explorer.winid))
    );
  }
  /**
   * Get all winnrs from explorers
   */
  async winnrs() {
    const container = await tabContainerManager.currentTabContainer();
    const explorers = container == null ? void 0 : container.all();
    if (explorers) {
      const winnrs = await Promise.all(
        explorers.map((explorer) => explorer.winnr)
      );
      return winnrs.filter((winnr) => winnr !== void 0);
    } else {
      return [];
    }
  }
  /**
   * Get all explorers
   */
  explorers() {
    const explorers = [];
    for (const container of tabContainerManager.values()) {
      explorers.push(...container.all());
    }
    return explorers;
  }
  async currentExplorer() {
    return this.explorerByBufnr(await currentBufnr());
  }
  async explorerByWinid(winid) {
    for (const e of this.explorers()) {
      if (await e.winid === winid) {
        return e;
      }
    }
  }
  explorerByBufnr(bufnr) {
    return this.explorers().find((e) => e.bufnr === bufnr);
  }
  async inExplorer() {
    return await this.currentExplorer() !== void 0;
  }
  async checkResume(explorer, argValues) {
    var _a2;
    if (argValues.position.name !== "floating") {
      return true;
    }
    if (!await ((_a2 = await explorer.sourceBuffer()) == null ? void 0 : _a2.loaded)) {
      await this.nvim.command(`bwipeout! ${explorer.bufnr}`);
      return false;
    }
    if (!await explorer.buffer.valid) {
      return false;
    }
    if (!await this.nvim.call("bufexists", [explorer.borderBufnr])) {
      await this.nvim.command(`bwipeout! ${explorer.bufnr}`);
      return false;
    }
    return true;
  }
  async open(argStrs) {
    await this.waitInited;
    let isFirst = true;
    const config4 = configLocal();
    const explorerConfig = buildExplorerConfig(config4);
    const args = await Args.parse(argStrs, config4);
    const argValues = await args.values(argOptions);
    const position = argValues.position;
    if (position.name === "floating") {
      if (!supportedNvimFloating()) {
        throw new Error("not support floating position in vim");
      }
    }
    const quit = argValues.quit;
    const tabid = position.name === "tab" ? await tabContainerManager.currentTabMaxId() + 1 : await tabContainerManager.currentTabId();
    const tabContainer = tabContainerManager.get(tabid);
    let explorer = tabContainer.getExplorer(position);
    if (explorer && quit) {
      await explorer.quit();
      return;
    }
    const sourceWinid = await this.nvim.call("win_getid");
    const sourceBufnr = await currentBufnr();
    const rooter = new Rooter(import_coc65.workspace.root);
    if (!explorer || !await this.nvim.call("bufexists", [explorer.bufnr])) {
      explorer = await Explorer.create(this, argValues, explorerConfig);
      tabContainer.setExplorer(position, explorer);
    } else if (!await explorer.inited.get()) {
      await this.nvim.command(`bwipeout! ${explorer.bufnr}`);
      explorer = await Explorer.create(this, argValues, explorerConfig);
      tabContainer.setExplorer(position, explorer);
    } else {
      const win = await explorer.win;
      if (!win) {
        if (await this.checkResume(explorer, argValues)) {
          await explorer.resume(argValues);
        } else {
          explorer = await Explorer.create(this, argValues, explorerConfig);
          tabContainer.setExplorer(position, explorer);
        }
      } else {
        if (await args.value(argOptions.toggle)) {
          await explorer.quit();
          return;
        }
        if (await args.value(argOptions.focus)) {
          await explorer.focus();
          return;
        }
      }
      isFirst = false;
    }
    await explorer.sourceWinid.set(sourceWinid);
    await explorer.sourceBufnr.set(sourceBufnr);
    await explorer.open(args, rooter, isFirst);
  }
};

// src/lists/presets.ts
var import_coc66 = require("coc.nvim");
var PresetList = class extends import_coc66.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "explPresets";
    this.defaultAction = "do";
    this.description = "explorer presets";
    this.addAction("do", async ({ data }) => {
      this.nvim.command(`CocCommand explorer --preset ${data.name}`).catch(logger.error);
    });
  }
  async loadItems(_context) {
    const presets = await getPresets(configLocal());
    return [...presets.keys()].map((name) => ({
      label: name,
      data: {
        name
      }
    }));
  }
  doHighlight() {
    const { nvim } = this;
    nvim.pauseNotification();
    nvim.command("syntax match CocExplorerPreset /.*/", true);
    nvim.command("highlight default link CocExplorerPreset PreProc", true);
    nvim.resumeNotification().catch(logger.error);
  }
};

// src/vimApi.ts
var import_coc67 = require("coc.nvim");
var import_path25 = __toESM(require("path"));
function registerApi(id, execute) {
  return import_coc67.commands.registerCommand(
    id,
    logger.asyncCatch(execute),
    void 0,
    true
  );
}
async function getExplorer(explorerFinder, explorerManager) {
  if (explorerFinder === "closest") {
    const winFinder = await WinLayoutFinder.create();
    const curWinid = await import_coc67.workspace.nvim.eval(
      "win_getid(winnr())"
    );
    if (curWinid <= -1) {
      return;
    }
    const curNode = winFinder.findWinid(curWinid);
    if (!curNode) {
      return;
    }
    const winids = await explorerManager.winids();
    if (!winids.length) {
      return;
    }
    const node = winFinder.findClosest(curNode, winids);
    if (node) {
      return explorerManager.explorerByWinid(node.winid);
    } else {
      const current = await tabContainerManager.currentTabContainer();
      const explorer = current == null ? void 0 : current.floating;
      if (await (explorer == null ? void 0 : explorer.winnr) !== void 0) {
        return explorer;
      }
    }
  } else {
    return explorerFinder === 0 ? explorerManager.currentExplorer() : explorerManager.explorerByBufnr(explorerFinder);
  }
}
async function getLineIndexByPosition(position, explorer) {
  if (position === "current") {
    return explorer.view.currentLineIndex;
  } else if (typeof position === "number") {
    return position;
  } else if (Array.isArray(position)) {
    const [mode, lineIndex, type] = position;
    if (mode === "relative") {
      const source = type ? explorer.sources.find((s) => s.sourceType === type) : await explorer.view.currentSource();
      if (source) {
        return source.view.startLineIndex + lineIndex;
      }
    }
  }
}
async function getSourceAndNodeByPosition(position, explorer) {
  const lineIndex = await getLineIndexByPosition(position, explorer);
  if (!lineIndex) {
    return [void 0, void 0];
  }
  const source = explorer.sources.find(
    (source2) => lineIndex >= source2.view.startLineIndex && lineIndex < source2.view.endLineIndex
  );
  if (!source) {
    return [void 0, void 0];
  }
  const nodeIndex = lineIndex - source.view.startLineIndex;
  return [source, source.view.flattenedNodes[nodeIndex] ?? void 0];
}
function registerVimApi(context2, explorerManager) {
  async function doAction(explorerFinder, actionExp, positions = ["current"], mode = "n", count = 1) {
    const explorer = await getExplorer(explorerFinder, explorerManager);
    if (!explorer) {
      return;
    }
    await explorer.view.refreshLineIndex();
    const lineIndexes = compactI2(
      await Promise.all(
        positions.map(
          async (position) => await getLineIndexByPosition(position, explorer)
        )
      )
    );
    await explorer.action.doActionExp(parseOriginalActionExp(actionExp), {
      mode,
      count,
      lineIndexes
    }).catch(logger.error);
  }
  context2.subscriptions.push(
    registerApi("explorer.doAction", doAction),
    registerApi(
      "explorer.doCodeAction",
      async (name, action, getArgs) => {
        const result = await doAction(0, {
          name: action,
          args: await getArgs()
        });
        await actionListMru.add(name);
        return result;
      }
    ),
    registerApi(
      "explorer.getNodeInfo",
      async (explorerFinder, position = "current") => {
        const explorer = await getExplorer(explorerFinder, explorerManager);
        if (!explorer) {
          return void 0;
        }
        await explorer.view.refreshLineIndex();
        const [, node] = await getSourceAndNodeByPosition(position, explorer);
        if (!node) {
          return void 0;
        }
        return {
          ...node,
          compactedNodes: void 0,
          parent: void 0,
          children: void 0,
          prevSiblingNode: void 0,
          nextSiblingNode: void 0
        };
      }
    ),
    registerApi(
      "explorer.getIcon",
      async (filepath, isDirectory = false, isExpanded) => {
        const basename2 = import_path25.default.basename(filepath);
        const type = isDirectory ? "directories" : "files";
        const nodes = [
          {
            fullname: basename2,
            isDirectory,
            expanded: isExpanded,
            hidden: false
          }
        ];
        const icons = await loadIcons("builtin", nodes);
        return icons == null ? void 0 : icons[type].get(basename2);
      }
    ),
    registerApi(
      "explorer.getIcons",
      async (paths) => {
        const fullname2filepath = {};
        const targets = paths.map((it) => {
          const fullname = import_path25.default.basename(it.filepath);
          fullname2filepath[fullname] = it.filepath;
          return {
            fullname,
            isDirectory: it.isDirectory,
            expanded: it.isExpanded,
            hidden: false
          };
        });
        const icons = await loadIcons("builtin", targets);
        if (!icons) {
          return;
        }
        const result = {
          files: {},
          directories: {}
        };
        for (const [fullname, file] of icons.files) {
          const filepath = fullname2filepath[fullname];
          if (filepath)
            result.files[filepath] = file;
        }
        for (const [fullname, directory] of icons.directories) {
          const filepath = fullname2filepath[fullname];
          if (filepath)
            result.directories[filepath] = directory;
        }
        return result;
      }
    )
  );
}

// src/index.ts
var activate = (context2) => {
  const { subscriptions } = context2;
  const { nvim } = import_coc68.workspace;
  const debug = config.get("debug");
  logger.level = debug ? "debug" : "info";
  hlGroupManager.createGroup(
    "SelectUI",
    "ctermbg=27 ctermfg=0 guibg=#1593e5 guifg=#ffffff"
  );
  const normalFloat = hlGroupManager.linkGroup("NormalFloat", "NormalFloat");
  hlGroupManager.linkGroup("NormalFloatBorder", normalFloat.group);
  import_coc68.listManager.registerList(new PresetList(nvim));
  const bufManager = new BufManager(context2);
  const explorerManager = new ExplorerManager(context2, bufManager);
  registerVimApi(context2, explorerManager);
  GitCommand.preload().catch(logger.error);
  subscriptions.push(
    import_coc68.commands.registerCommand(
      "explorer",
      logger.asyncCatch((...args) => {
        explorerManager.open(args).catch(logger.error);
      })
    ),
    import_coc68.languages.registerCodeActionProvider(
      ["coc-explorer"],
      new ActionMenuCodeActionProvider(explorerManager),
      "coc-explorer"
    )
  );
  (async () => {
    await activateHelper(context2);
    registerInternalEvents(context2);
    await registerRuntimepath(context2);
    await nvim.command("runtime plugin/coc_explorer.vim");
    registerGitHighlights(subscriptions);
    registerInternalColors(subscriptions);
    await registerMappings(context2, explorerManager);
    await explorerManager.events.fire("inited");
    await tabContainerManager.initedEmitter.fire();
    bufManager.reload().catch(logger.error);
    await tabContainerManager.register();
  })().catch(logger.error);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  activate
});
/*! Bundled license information:

lodash-es/lodash.js:
  (**
   * @license
   * Lodash (Custom Build) <https://lodash.com/>
   * Build: `lodash modularize exports="es" -o ./`
   * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
   * Released under MIT license <https://lodash.com/license>
   * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
   * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
   *)
*/
