import { commandSpec as commandSpec$f } from '../chunk-BVTQWPPV.js';
import { commandSpec as commandSpec$8 } from '../chunk-H2LBNWH6.js';
import { commandSpec as commandSpec$9 } from '../chunk-HRKY75S6.js';
import { commandSpec as commandSpec$7 } from '../chunk-5CY4FMLS.js';
import { commandSpec as commandSpec$a } from '../chunk-SIXH3GKD.js';
import { commandSpec as commandSpec$c } from '../chunk-WDJR3BMV.js';
import { commandSpec as commandSpec$d } from '../chunk-JE6B7XUX.js';
import '../chunk-KPFLSGGP.js';
import { commandSpec as commandSpec$b } from '../chunk-N3LH752M.js';
import { commandSpec as commandSpec$e } from '../chunk-7MSOSZ6B.js';
import { commandSpec } from '../chunk-G6QZTET7.js';
import { fmt } from '../chunk-NEWKASA7.js';
import '../chunk-C5ZGZA3T.js';
import { commandSpec as commandSpec$1 } from '../chunk-VNJH4XWX.js';
import { commandSpec as commandSpec$2 } from '../chunk-UYYR74JF.js';
import { commandSpec as commandSpec$3 } from '../chunk-H6XEWY2M.js';
import { commandSpec as commandSpec$4 } from '../chunk-YJPO5TYV.js';
import { commandSpec as commandSpec$5 } from '../chunk-5QPV7UIW.js';
import { commandSpec as commandSpec$6 } from '../chunk-RWAWPDLS.js';
import { gracefulExit, asyncExitHook } from '../chunk-XQSWW35O.js';
import { cli } from '../chunk-WIL4LMMA.js';
import { checkBunVersion } from '../chunk-TZU7BNR4.js';
import { InvalidEnvError } from '../chunk-4MCNC4YY.js';
import '../chunk-5SI4EGRL.js';
import { CliExitError } from '../chunk-7M6WZ65V.js';
import '../chunk-VT7SXRVK.js';
import { ansis_default } from '../chunk-LTYLEVHC.js';
import '../chunk-7OJKCWSO.js';
import '../chunk-TMF4AFL6.js';
import '../chunk-223S32SW.js';
import '../chunk-Y2ROUSC3.js';
import { getUserVarlockDir } from '../chunk-JE2IMKMO.js';
import '../chunk-DRL5U3PK.js';
import { createDebug } from '../chunk-QGM3LRUO.js';
import '../chunk-IQ226IPZ.js';
import '../chunk-UWUBFNLX.js';
import { __commonJS, __name, __toESM } from '../chunk-IBAHCH6O.js';
import i2 from 'assert';
import os2 from 'os';
import crypto, { createHash } from 'crypto';
import { join, dirname } from 'path';
import fs, { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
import process2 from 'process';

// ../../node_modules/.bun/ci-info@4.4.0/node_modules/ci-info/vendors.json
var require_vendors = __commonJS({
  "../../node_modules/.bun/ci-info@4.4.0/node_modules/ci-info/vendors.json"(exports, module) {
    module.exports = [
      {
        name: "Agola CI",
        constant: "AGOLA",
        env: "AGOLA_GIT_REF",
        pr: "AGOLA_PULL_REQUEST_ID"
      },
      {
        name: "Alpic",
        constant: "ALPIC",
        env: "ALPIC_HOST"
      },
      {
        name: "Appcircle",
        constant: "APPCIRCLE",
        env: "AC_APPCIRCLE",
        pr: {
          env: "AC_GIT_PR",
          ne: "false"
        }
      },
      {
        name: "AppVeyor",
        constant: "APPVEYOR",
        env: "APPVEYOR",
        pr: "APPVEYOR_PULL_REQUEST_NUMBER"
      },
      {
        name: "AWS CodeBuild",
        constant: "CODEBUILD",
        env: "CODEBUILD_BUILD_ARN",
        pr: {
          env: "CODEBUILD_WEBHOOK_EVENT",
          any: [
            "PULL_REQUEST_CREATED",
            "PULL_REQUEST_UPDATED",
            "PULL_REQUEST_REOPENED"
          ]
        }
      },
      {
        name: "Azure Pipelines",
        constant: "AZURE_PIPELINES",
        env: "TF_BUILD",
        pr: {
          BUILD_REASON: "PullRequest"
        }
      },
      {
        name: "Bamboo",
        constant: "BAMBOO",
        env: "bamboo_planKey"
      },
      {
        name: "Bitbucket Pipelines",
        constant: "BITBUCKET",
        env: "BITBUCKET_COMMIT",
        pr: "BITBUCKET_PR_ID"
      },
      {
        name: "Bitrise",
        constant: "BITRISE",
        env: "BITRISE_IO",
        pr: "BITRISE_PULL_REQUEST"
      },
      {
        name: "Buddy",
        constant: "BUDDY",
        env: "BUDDY_WORKSPACE_ID",
        pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
      },
      {
        name: "Buildkite",
        constant: "BUILDKITE",
        env: "BUILDKITE",
        pr: {
          env: "BUILDKITE_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "CircleCI",
        constant: "CIRCLE",
        env: "CIRCLECI",
        pr: "CIRCLE_PULL_REQUEST"
      },
      {
        name: "Cirrus CI",
        constant: "CIRRUS",
        env: "CIRRUS_CI",
        pr: "CIRRUS_PR"
      },
      {
        name: "Cloudflare Pages",
        constant: "CLOUDFLARE_PAGES",
        env: "CF_PAGES"
      },
      {
        name: "Cloudflare Workers",
        constant: "CLOUDFLARE_WORKERS",
        env: "WORKERS_CI"
      },
      {
        name: "Codefresh",
        constant: "CODEFRESH",
        env: "CF_BUILD_ID",
        pr: {
          any: [
            "CF_PULL_REQUEST_NUMBER",
            "CF_PULL_REQUEST_ID"
          ]
        }
      },
      {
        name: "Codemagic",
        constant: "CODEMAGIC",
        env: "CM_BUILD_ID",
        pr: "CM_PULL_REQUEST"
      },
      {
        name: "Codeship",
        constant: "CODESHIP",
        env: {
          CI_NAME: "codeship"
        }
      },
      {
        name: "Drone",
        constant: "DRONE",
        env: "DRONE",
        pr: {
          DRONE_BUILD_EVENT: "pull_request"
        }
      },
      {
        name: "dsari",
        constant: "DSARI",
        env: "DSARI"
      },
      {
        name: "Earthly",
        constant: "EARTHLY",
        env: "EARTHLY_CI"
      },
      {
        name: "Expo Application Services",
        constant: "EAS",
        env: "EAS_BUILD"
      },
      {
        name: "Gerrit",
        constant: "GERRIT",
        env: "GERRIT_PROJECT"
      },
      {
        name: "Gitea Actions",
        constant: "GITEA_ACTIONS",
        env: "GITEA_ACTIONS"
      },
      {
        name: "GitHub Actions",
        constant: "GITHUB_ACTIONS",
        env: "GITHUB_ACTIONS",
        pr: {
          GITHUB_EVENT_NAME: "pull_request"
        }
      },
      {
        name: "GitLab CI",
        constant: "GITLAB",
        env: "GITLAB_CI",
        pr: "CI_MERGE_REQUEST_ID"
      },
      {
        name: "GoCD",
        constant: "GOCD",
        env: "GO_PIPELINE_LABEL"
      },
      {
        name: "Google Cloud Build",
        constant: "GOOGLE_CLOUD_BUILD",
        env: "BUILDER_OUTPUT"
      },
      {
        name: "Harness CI",
        constant: "HARNESS",
        env: "HARNESS_BUILD_ID"
      },
      {
        name: "Heroku",
        constant: "HEROKU",
        env: {
          env: "NODE",
          includes: "/app/.heroku/node/bin/node"
        }
      },
      {
        name: "Hudson",
        constant: "HUDSON",
        env: "HUDSON_URL"
      },
      {
        name: "Jenkins",
        constant: "JENKINS",
        env: [
          "JENKINS_URL",
          "BUILD_ID"
        ],
        pr: {
          any: [
            "ghprbPullId",
            "CHANGE_ID"
          ]
        }
      },
      {
        name: "LayerCI",
        constant: "LAYERCI",
        env: "LAYERCI",
        pr: "LAYERCI_PULL_REQUEST"
      },
      {
        name: "Magnum CI",
        constant: "MAGNUM",
        env: "MAGNUM"
      },
      {
        name: "Netlify CI",
        constant: "NETLIFY",
        env: "NETLIFY",
        pr: {
          env: "PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Nevercode",
        constant: "NEVERCODE",
        env: "NEVERCODE",
        pr: {
          env: "NEVERCODE_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Prow",
        constant: "PROW",
        env: "PROW_JOB_ID"
      },
      {
        name: "ReleaseHub",
        constant: "RELEASEHUB",
        env: "RELEASE_BUILD_ID"
      },
      {
        name: "Render",
        constant: "RENDER",
        env: "RENDER",
        pr: {
          IS_PULL_REQUEST: "true"
        }
      },
      {
        name: "Sail CI",
        constant: "SAIL",
        env: "SAILCI",
        pr: "SAIL_PULL_REQUEST_NUMBER"
      },
      {
        name: "Screwdriver",
        constant: "SCREWDRIVER",
        env: "SCREWDRIVER",
        pr: {
          env: "SD_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Semaphore",
        constant: "SEMAPHORE",
        env: "SEMAPHORE",
        pr: "PULL_REQUEST_NUMBER"
      },
      {
        name: "Sourcehut",
        constant: "SOURCEHUT",
        env: {
          CI_NAME: "sourcehut"
        }
      },
      {
        name: "Strider CD",
        constant: "STRIDER",
        env: "STRIDER"
      },
      {
        name: "TaskCluster",
        constant: "TASKCLUSTER",
        env: [
          "TASK_ID",
          "RUN_ID"
        ]
      },
      {
        name: "TeamCity",
        constant: "TEAMCITY",
        env: "TEAMCITY_VERSION"
      },
      {
        name: "Travis CI",
        constant: "TRAVIS",
        env: "TRAVIS",
        pr: {
          env: "TRAVIS_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Vela",
        constant: "VELA",
        env: "VELA",
        pr: {
          VELA_PULL_REQUEST: "1"
        }
      },
      {
        name: "Vercel",
        constant: "VERCEL",
        env: {
          any: [
            "NOW_BUILDER",
            "VERCEL"
          ]
        },
        pr: "VERCEL_GIT_PULL_REQUEST_ID"
      },
      {
        name: "Visual Studio App Center",
        constant: "APPCENTER",
        env: "APPCENTER_BUILD_ID"
      },
      {
        name: "Woodpecker",
        constant: "WOODPECKER",
        env: {
          CI: "woodpecker"
        },
        pr: {
          CI_BUILD_EVENT: "pull_request"
        }
      },
      {
        name: "Xcode Cloud",
        constant: "XCODE_CLOUD",
        env: "CI_XCODE_PROJECT",
        pr: "CI_PULL_REQUEST_NUMBER"
      },
      {
        name: "Xcode Server",
        constant: "XCODE_SERVER",
        env: "XCS"
      }
    ];
  }
});

// ../../node_modules/.bun/ci-info@4.4.0/node_modules/ci-info/index.js
var require_ci_info = __commonJS({
  "../../node_modules/.bun/ci-info@4.4.0/node_modules/ci-info/index.js"(exports) {
    var vendors = require_vendors();
    var env = process.env;
    Object.defineProperty(exports, "_vendors", {
      value: vendors.map(function(v) {
        return v.constant;
      })
    });
    exports.name = null;
    exports.isPR = null;
    exports.id = null;
    if (env.CI !== "false") {
      vendors.forEach(function(vendor) {
        const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
        const isCI2 = envs.every(function(obj) {
          return checkEnv(obj);
        });
        exports[vendor.constant] = isCI2;
        if (!isCI2) {
          return;
        }
        exports.name = vendor.name;
        exports.isPR = checkPR(vendor);
        exports.id = vendor.constant;
      });
    }
    exports.isCI = !!(env.CI !== "false" && // Bypass all checks if CI env is explicitly set to 'false'
    (env.BUILD_ID || // Jenkins, Cloudbees
    env.BUILD_NUMBER || // Jenkins, TeamCity
    env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari, Cloudflare Pages/Workers
    env.CI_APP_ID || // Appflow
    env.CI_BUILD_ID || // Appflow
    env.CI_BUILD_NUMBER || // Appflow
    env.CI_NAME || // Codeship and others
    env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
    env.RUN_ID || // TaskCluster, dsari
    exports.name || false));
    function checkEnv(obj) {
      if (typeof obj === "string") return !!env[obj];
      if ("env" in obj) {
        return env[obj.env] && env[obj.env].includes(obj.includes);
      }
      if ("any" in obj) {
        return obj.any.some(function(k) {
          return !!env[k];
        });
      }
      return Object.keys(obj).every(function(k) {
        return env[k] === obj[k];
      });
    }
    __name(checkEnv, "checkEnv");
    function checkPR(vendor) {
      switch (typeof vendor.pr) {
        case "string":
          return !!env[vendor.pr];
        case "object":
          if ("env" in vendor.pr) {
            if ("any" in vendor.pr) {
              return vendor.pr.any.some(function(key) {
                return env[vendor.pr.env] === key;
              });
            } else {
              return vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne;
            }
          } else if ("any" in vendor.pr) {
            return vendor.pr.any.some(function(key) {
              return !!env[key];
            });
          } else {
            return checkEnv(vendor.pr);
          }
        default:
          return null;
      }
    }
    __name(checkPR, "checkPR");
  }
});

// ../../node_modules/.bun/@bomb.sh+tab@0.0.15+d2aa7bd88f16ef93/node_modules/@bomb.sh/tab/dist/powershell-CHePOaos.mjs
function t(t2, n2) {
  return `#compdef ${t2}
compdef _${t2} ${t2}

# zsh completion for ${t2} -*- shell-script -*-

__${t2}_debug() {
    local file="$BASH_COMP_DEBUG_FILE"
    if [[ -n \${file} ]]; then
        echo "$*" >> "\${file}"
    fi
}

_${t2}() {
    local shellCompDirectiveError=${a.ShellCompDirectiveError}
    local shellCompDirectiveNoSpace=${a.ShellCompDirectiveNoSpace}
    local shellCompDirectiveNoFileComp=${a.ShellCompDirectiveNoFileComp}
    local shellCompDirectiveFilterFileExt=${a.ShellCompDirectiveFilterFileExt}
    local shellCompDirectiveFilterDirs=${a.ShellCompDirectiveFilterDirs}
    local shellCompDirectiveKeepOrder=${a.ShellCompDirectiveKeepOrder}

    local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder
    local -a completions

    __${t2}_debug "\\n========= starting completion logic =========="
    __${t2}_debug "CURRENT: \${CURRENT}, words[*]: \${words[*]}"

    # The user could have moved the cursor backwards on the command-line.
    # We need to trigger completion from the $CURRENT location, so we need
    # to truncate the command-line ($words) up to the $CURRENT location.
    # (We cannot use $CURSOR as its value does not work when a command is an alias.)
    words=( "\${=words[1,CURRENT]}" )
    __${t2}_debug "Truncated words[*]: \${words[*]},"

    lastParam=\${words[-1]}
    lastChar=\${lastParam[-1]}
    __${t2}_debug "lastParam: \${lastParam}, lastChar: \${lastChar}"

    # For zsh, when completing a flag with an = (e.g., ${t2} -n=<TAB>)
    # completions must be prefixed with the flag
    setopt local_options BASH_REMATCH
    if [[ "\${lastParam}" =~ '-.*=' ]]; then
        # We are dealing with a flag with an =
        flagPrefix="-P \${BASH_REMATCH}"
    fi

    # Prepare the command to obtain completions, ensuring arguments are quoted for eval
    local -a args_to_quote=("\${(@)words[2,-1]}")
    if [ "\${lastChar}" = "" ]; then
        # If the last parameter is complete (there is a space following it)
        # We add an extra empty parameter so we can indicate this to the go completion code.
        __${t2}_debug "Adding extra empty parameter"
        args_to_quote+=("")
    fi

    # Use Zsh's (q) flag to quote each argument safely for eval
    local quoted_args=("\${(@q)args_to_quote}")

    # Join the main command and the quoted arguments into a single string for eval
    requestComp="${n2} complete -- \${quoted_args[*]}"

    __${t2}_debug "About to call: eval \${requestComp}"

    # Use eval to handle any environment variables and such
    out=$(eval \${requestComp} 2>/dev/null)
    __${t2}_debug "completion output: \${out}"

    # Extract the directive integer following a : from the last line
    local lastLine
    while IFS='
' read -r line; do
        lastLine=\${line}
    done < <(printf "%s
" "\${out[@]}")
    __${t2}_debug "last line: \${lastLine}"

    if [ "\${lastLine[1]}" = : ]; then
        directive=\${lastLine[2,-1]}
        # Remove the directive including the : and the newline
        local suffix
        (( suffix=\${#lastLine}+2))
        out=\${out[1,-$suffix]}
    else
        # There is no directive specified.  Leave $out as is.
        __${t2}_debug "No directive found.  Setting to default"
        directive=0
    fi

    __${t2}_debug "directive: \${directive}"
    __${t2}_debug "completions: \${out}"
    __${t2}_debug "flagPrefix: \${flagPrefix}"

    if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
        __${t2}_debug "Completion received error. Ignoring completions."
        return
    fi

    local activeHelpMarker="%"
    local endIndex=\${#activeHelpMarker}
    local startIndex=$((\${#activeHelpMarker}+1))
    local hasActiveHelp=0
    while IFS='
' read -r comp; do
        # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
        if [ "\${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
            __${t2}_debug "ActiveHelp found: $comp"
            comp="\${comp[$startIndex,-1]}"
            if [ -n "$comp" ]; then
                compadd -x "\${comp}"
                __${t2}_debug "ActiveHelp will need delimiter"
                hasActiveHelp=1
            fi
            continue
        fi

        if [ -n "$comp" ]; then
            # If requested, completions are returned with a description.
            # The description is preceded by a TAB character.
            # For zsh's _describe, we need to use a : instead of a TAB.
            # We first need to escape any : as part of the completion itself.
            comp=\${comp//:/\\:}

            local tab="$(printf '\\t')"
            comp=\${comp//$tab/:}

            __${t2}_debug "Adding completion: \${comp}"
            completions+=\${comp}
            lastComp=$comp
        fi
    done < <(printf "%s
" "\${out[@]}")

    # Add a delimiter after the activeHelp statements, but only if:
    # - there are completions following the activeHelp statements, or
    # - file completion will be performed (so there will be choices after the activeHelp)
    if [ $hasActiveHelp -eq 1 ]; then
        if [ \${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
            __${t2}_debug "Adding activeHelp delimiter"
            compadd -x "--"
            hasActiveHelp=0
        fi
    fi

    if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
        __${t2}_debug "Activating nospace."
        noSpace="-S ''"
    fi

    if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
        __${t2}_debug "Activating keep order."
        keepOrder="-V"
    fi

    if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
        # File extension filtering
        local filteringCmd
        filteringCmd='_files'
        for filter in \${completions[@]}; do
            if [ \${filter[1]} != '*' ]; then
                # zsh requires a glob pattern to do file filtering
                filter="\\*.$filter"
            fi
            filteringCmd+=" -g $filter"
        done
        filteringCmd+=" \${flagPrefix}"

        __${t2}_debug "File filtering command: $filteringCmd"
        _arguments '*:filename:'"$filteringCmd"
    elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
        # File completion for directories only
        local subdir
        subdir="\${completions[1]}"
        if [ -n "$subdir" ]; then
            __${t2}_debug "Listing directories in $subdir"
            pushd "\${subdir}" >/dev/null 2>&1
        else
            __${t2}_debug "Listing directories in ."
        fi

        local result
        _arguments '*:dirname:_files -/'" \${flagPrefix}"
        result=$?
        if [ -n "$subdir" ]; then
            popd >/dev/null 2>&1
        fi
        return $result
    else
        __${t2}_debug "Calling _describe"
        if eval _describe $keepOrder "completions" completions -Q \${flagPrefix} \${noSpace}; then
            __${t2}_debug "_describe found some completions"

            # Return the success of having called _describe
            return 0
        else
            __${t2}_debug "_describe did not find completions."
            __${t2}_debug "Checking if we should do file completion."
            if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
                __${t2}_debug "deactivating file completion"

                # Return 0 to indicate completion is finished and prevent zsh from
                # trying other completion algorithms (which could cause hanging).
                # We use NoFileComp directive to explicitly disable file completion.
                return 0
            else
                # Perform file completion
                __${t2}_debug "Activating file completion"

                # We must return the result of this command, so it must be the
                # last command, or else we must store its result to return it.
                _arguments '*:filename:_files'" \${flagPrefix}"
            fi
        fi
    fi
}

# don't run the completion function when being sourced or eval-ed
if [ "\${funcstack[1]}" = "_${t2}" ]; then
    _${t2}
fi
`;
}
__name(t, "t");
function n(t2, n2) {
  let r2 = t2.replace(/[-:]/g, `_`);
  return `# bash completion for ${t2}

# Define shell completion directives
readonly ShellCompDirectiveError=${a.ShellCompDirectiveError}
readonly ShellCompDirectiveNoSpace=${a.ShellCompDirectiveNoSpace}
readonly ShellCompDirectiveNoFileComp=${a.ShellCompDirectiveNoFileComp}
readonly ShellCompDirectiveFilterFileExt=${a.ShellCompDirectiveFilterFileExt}
readonly ShellCompDirectiveFilterDirs=${a.ShellCompDirectiveFilterDirs}
readonly ShellCompDirectiveKeepOrder=${a.ShellCompDirectiveKeepOrder}

# Function to debug completion
__${r2}_debug() {
    if [[ -n \${BASH_COMP_DEBUG_FILE:-} ]]; then
        echo "$*" >> "\${BASH_COMP_DEBUG_FILE}"
    fi
}

# Function to handle completions
__${r2}_complete() {
    local cur prev words cword
    _get_comp_words_by_ref -n "=:" cur prev words cword

    local requestComp out directive
    
    # Build the command to get completions
    requestComp="${n2} complete -- \${words[@]:1}"
    
    # Add an empty parameter if the last parameter is complete
    if [[ -z "$cur" ]]; then
        requestComp="$requestComp ''"
    fi
    
    # Get completions from the program
    out=$(eval "$requestComp" 2>/dev/null)
    
    # Extract directive if present
    directive=0
    if [[ "$out" == *:* ]]; then
        directive=\${out##*:}
        out=\${out%:*}
    fi
    
    # Process completions based on directive
    if [[ $((directive & $ShellCompDirectiveError)) -ne 0 ]]; then
        # Error, no completion
        return
    fi
    
    # Apply directives
    if [[ $((directive & $ShellCompDirectiveNoSpace)) -ne 0 ]]; then
        compopt -o nospace
    fi
    if [[ $((directive & $ShellCompDirectiveKeepOrder)) -ne 0 ]]; then
        compopt -o nosort
    fi
    if [[ $((directive & $ShellCompDirectiveNoFileComp)) -ne 0 ]]; then
        compopt +o default
    fi
    
    # Handle file extension filtering
    if [[ $((directive & $ShellCompDirectiveFilterFileExt)) -ne 0 ]]; then
        local filter=""
        for ext in $out; do
            filter="$filter|$ext"
        done
        filter="\\.($filter)"
        compopt -o filenames
        COMPREPLY=( $(compgen -f -X "!$filter" -- "$cur") )
        return
    fi
    
    # Handle directory filtering
    if [[ $((directive & $ShellCompDirectiveFilterDirs)) -ne 0 ]]; then
        compopt -o dirnames
        COMPREPLY=( $(compgen -d -- "$cur") )
        return
    fi
    
    # Process completions
    local IFS=$'\\n'
    local tab=$(printf '\\t')
    
    # Parse completions with descriptions
    local completions=()
    while read -r comp; do
        if [[ "$comp" == *$tab* ]]; then
            # Split completion and description
            local value=\${comp%%$tab*}
            local desc=\${comp#*$tab}
            completions+=("$value")
        else
            completions+=("$comp")
        fi
    done <<< "$out"
    
    # Return completions
    COMPREPLY=( $(compgen -W "\${completions[*]}" -- "$cur") )
}

# Register completion function
complete -F __${r2}_complete ${t2}
`;
}
__name(n, "n");
function r(t2, n2) {
  let r2 = t2.replace(/[-:]/g, `_`), i3 = a.ShellCompDirectiveError, a2 = a.ShellCompDirectiveNoSpace, o2 = a.ShellCompDirectiveNoFileComp, s2 = a.ShellCompDirectiveFilterFileExt, c2 = a.ShellCompDirectiveFilterDirs;
  return `# fish completion for ${t2} -*- shell-script -*-

function __${r2}_debug
    set -l file "$BASH_COMP_DEBUG_FILE"
    if test -n "$file"
        echo "$argv" >> $file
    end
end

function __${r2}_perform_completion
    __${r2}_debug "Starting __${r2}_perform_completion"

    # Extract all args except the last one
    set -l args (commandline -opc)
    # Extract the last arg and escape it in case it is a space or wildcard
    set -l lastArg (string escape -- (commandline -ct))

    __${r2}_debug "args: $args"
    __${r2}_debug "last arg: $lastArg"

    # Build the completion request command
    set -l requestComp "${n2} complete -- (string join ' ' -- (string escape -- $args[2..-1])) $lastArg"

    __${r2}_debug "Calling $requestComp"
    set -l results (eval $requestComp 2> /dev/null)

    # Some programs may output extra empty lines after the directive.
    # Let's ignore them or else it will break completion.
    # Ref: https://github.com/spf13/cobra/issues/1279
    for line in $results[-1..1]
        if test (string trim -- $line) = ""
            # Found an empty line, remove it
            set results $results[1..-2]
        else
            # Found non-empty line, we have our proper output
            break
        end
    end

    set -l comps $results[1..-2]
    set -l directiveLine $results[-1]

    # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)
    # completions must be prefixed with the flag
    set -l flagPrefix (string match -r -- '-.*=' "$lastArg")

    __${r2}_debug "Comps: $comps"
    __${r2}_debug "DirectiveLine: $directiveLine"
    __${r2}_debug "flagPrefix: $flagPrefix"

    for comp in $comps
        printf "%s%s\\n" "$flagPrefix" "$comp"
    end

    printf "%s\\n" "$directiveLine"
end

# This function limits calls to __${r2}_perform_completion, by caching the result
function __${r2}_perform_completion_once
    __${r2}_debug "Starting __${r2}_perform_completion_once"

    if test -n "$__${r2}_perform_completion_once_result"
        __${r2}_debug "Seems like a valid result already exists, skipping __${r2}_perform_completion"
        return 0
    end

    set --global __${r2}_perform_completion_once_result (__${r2}_perform_completion)
    if test -z "$__${r2}_perform_completion_once_result"
        __${r2}_debug "No completions, probably due to a failure"
        return 1
    end

    __${r2}_debug "Performed completions and set __${r2}_perform_completion_once_result"
    return 0
end

# This function is used to clear the cached result after completions are run
function __${r2}_clear_perform_completion_once_result
    __${r2}_debug ""
    __${r2}_debug "========= clearing previously set __${r2}_perform_completion_once_result variable =========="
    set --erase __${r2}_perform_completion_once_result
    __${r2}_debug "Successfully erased the variable __${r2}_perform_completion_once_result"
end

function __${r2}_requires_order_preservation
    __${r2}_debug ""
    __${r2}_debug "========= checking if order preservation is required =========="

    __${r2}_perform_completion_once
    if test -z "$__${r2}_perform_completion_once_result"
        __${r2}_debug "Error determining if order preservation is required"
        return 1
    end

    set -l directive (string sub --start 2 $__${r2}_perform_completion_once_result[-1])
    __${r2}_debug "Directive is: $directive"

    set -l shellCompDirectiveKeepOrder ${a.ShellCompDirectiveKeepOrder}
    set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) % 2)
    __${r2}_debug "Keeporder is: $keeporder"

    if test $keeporder -ne 0
        __${r2}_debug "This does require order preservation"
        return 0
    end

    __${r2}_debug "This doesn't require order preservation"
    return 1
end

# This function does two things:
# - Obtain the completions and store them in the global __${r2}_comp_results
# - Return false if file completion should be performed
function __${r2}_prepare_completions
    __${r2}_debug ""
    __${r2}_debug "========= starting completion logic =========="

    # Start fresh
    set --erase __${r2}_comp_results

    __${r2}_perform_completion_once
    __${r2}_debug "Completion results: $__${r2}_perform_completion_once_result"

    if test -z "$__${r2}_perform_completion_once_result"
        __${r2}_debug "No completion, probably due to a failure"
        # Might as well do file completion, in case it helps
        return 1
    end

    set -l directive (string sub --start 2 $__${r2}_perform_completion_once_result[-1])
    set --global __${r2}_comp_results $__${r2}_perform_completion_once_result[1..-2]

    __${r2}_debug "Completions are: $__${r2}_comp_results"
    __${r2}_debug "Directive is: $directive"

    set -l shellCompDirectiveError ${i3}
    set -l shellCompDirectiveNoSpace ${a2}
    set -l shellCompDirectiveNoFileComp ${o2}
    set -l shellCompDirectiveFilterFileExt ${s2}
    set -l shellCompDirectiveFilterDirs ${c2}

    if test -z "$directive"
        set directive 0
    end

    set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) % 2)
    if test $compErr -eq 1
        __${r2}_debug "Received error directive: aborting."
        # Might as well do file completion, in case it helps
        return 1
    end

    set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) % 2)
    set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) % 2)
    if test $filefilter -eq 1; or test $dirfilter -eq 1
        __${r2}_debug "File extension filtering or directory filtering not supported"
        # Do full file completion instead
        return 1
    end

    set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) % 2)
    set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) % 2)

    __${r2}_debug "nospace: $nospace, nofiles: $nofiles"

    # If we want to prevent a space, or if file completion is NOT disabled,
    # we need to count the number of valid completions.
    # To do so, we will filter on prefix as the completions we have received
    # may not already be filtered so as to allow fish to match on different
    # criteria than the prefix.
    if test $nospace -ne 0; or test $nofiles -eq 0
        set -l prefix (commandline -t | string escape --style=regex)
        __${r2}_debug "prefix: $prefix"

        set -l completions (string match -r -- "^$prefix.*" $__${r2}_comp_results)
        set --global __${r2}_comp_results $completions
        __${r2}_debug "Filtered completions are: $__${r2}_comp_results"

        # Important not to quote the variable for count to work
        set -l numComps (count $__${r2}_comp_results)
        __${r2}_debug "numComps: $numComps"

        if test $numComps -eq 1; and test $nospace -ne 0
            # We must first split on \\t to get rid of the descriptions to be
            # able to check what the actual completion will be.
            # We don't need descriptions anyway since there is only a single
            # real completion which the shell will expand immediately.
            set -l split (string split --max 1 "\\t" $__${r2}_comp_results[1])

            # Fish won't add a space if the completion ends with any
            # of the following characters: @=/:.,
            set -l lastChar (string sub -s -1 -- $split)
            if not string match -r -q "[@=/:.,]" -- "$lastChar"
                # In other cases, to support the "nospace" directive we trick the shell
                # by outputting an extra, longer completion.
                __${r2}_debug "Adding second completion to perform nospace directive"
                set --global __${r2}_comp_results $split[1] $split[1].
                __${r2}_debug "Completions are now: $__${r2}_comp_results"
            end
        end

        if test $numComps -eq 0; and test $nofiles -eq 0
            # To be consistent with bash and zsh, we only trigger file
            # completion when there are no other completions
            __${r2}_debug "Requesting file completion"
            return 1
        end
    end

    return 0
end

# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves
# so we can properly delete any completions provided by another script.
# Only do this if the program can be found, or else fish may print some errors; besides,
# the existing completions will only be loaded if the program can be found.
if type -q "${t2}"
    # The space after the program name is essential to trigger completion for the program
    # and not completion of the program name itself.
    # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.
    complete --do-complete "${t2} " > /dev/null 2>&1
end

# Remove any pre-existing completions for the program since we will be handling all of them.
complete -c ${t2} -e

# This will get called after the two calls below and clear the cached result
complete -c ${t2} -n '__${r2}_clear_perform_completion_once_result'
# The call to __${r2}_prepare_completions will setup __${r2}_comp_results
# which provides the program's completion choices.
# If this doesn't require order preservation, we don't use the -k flag
complete -c ${t2} -n 'not __${r2}_requires_order_preservation && __${r2}_prepare_completions' -f -a '$__${r2}_comp_results'
# Otherwise we use the -k flag
complete -k -c ${t2} -n '__${r2}_requires_order_preservation && __${r2}_prepare_completions' -f -a '$__${r2}_comp_results'
`;
}
__name(r, "r");
function i(t2, n2) {
  let r2 = t2.replace(/[-:]/g, `_`);
  return `# powershell completion for ${t2} -*- shell-script -*-

  [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
    function __${t2}_debug {
        if ($env:BASH_COMP_DEBUG_FILE) {
            "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
        }
    }

    filter __${t2}_escapeStringWithSpecialChars {
        $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|"|\\||<|>|&','\`$&'
    }

[scriptblock]$__${r2}CompleterBlock = {
    param(
            $WordToComplete,
            $CommandAst,
            $CursorPosition
        )

    # Get the current command line and convert into a string
    $Command = $CommandAst.CommandElements
    $Command = "$Command"

    __${t2}_debug ""
    __${t2}_debug "========= starting completion logic =========="
    __${t2}_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"

    # The user could have moved the cursor backwards on the command-line.
    # We need to trigger completion from the $CursorPosition location, so we need
    # to truncate the command-line ($Command) up to the $CursorPosition location.
    # Make sure the $Command is longer then the $CursorPosition before we truncate.
    # This happens because the $Command does not include the last space.
    if ($Command.Length -gt $CursorPosition) {
        $Command = $Command.Substring(0, $CursorPosition)
    }
    __${t2}_debug "Truncated command: $Command"

    $ShellCompDirectiveError=${a.ShellCompDirectiveError}
    $ShellCompDirectiveNoSpace=${a.ShellCompDirectiveNoSpace}
    $ShellCompDirectiveNoFileComp=${a.ShellCompDirectiveNoFileComp}
    $ShellCompDirectiveFilterFileExt=${a.ShellCompDirectiveFilterFileExt}
    $ShellCompDirectiveFilterDirs=${a.ShellCompDirectiveFilterDirs}
    $ShellCompDirectiveKeepOrder=${a.ShellCompDirectiveKeepOrder}

    # Prepare the command to request completions for the program.
    # Split the command at the first space to separate the program and arguments.
    $Program, $Arguments = $Command.Split(" ", 2)

    $QuotedArgs = ($Arguments -split ' ' | ForEach-Object { "'" + ($_ -replace "'", "''") + "'" }) -join ' '
    __${t2}_debug "QuotedArgs: $QuotedArgs"

    $RequestComp = "& ${n2} complete '--' $QuotedArgs"
    __${t2}_debug "RequestComp: $RequestComp"

    # we cannot use $WordToComplete because it
    # has the wrong values if the cursor was moved
    # so use the last argument
    if ($WordToComplete -ne "" ) {
        $WordToComplete = $Arguments.Split(" ")[-1]
    }
    __${t2}_debug "New WordToComplete: $WordToComplete"


    # Check for flag with equal sign
    $IsEqualFlag = ($WordToComplete -Like "--*=*" )
    if ( $IsEqualFlag ) {
        __${t2}_debug "Completing equal sign flag"
        # Remove the flag part
        $Flag, $WordToComplete = $WordToComplete.Split("=", 2)
    }

    if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
        # If the last parameter is complete (there is a space following it)
        # We add an extra empty parameter so we can indicate this to the go method.
        __${t2}_debug "Adding extra empty parameter"
        # PowerShell 7.2+ changed the way how the arguments are passed to executables,
        # so for pre-7.2 or when Legacy argument passing is enabled we need to use
        if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
            ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
            (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
              $PSNativeCommandArgumentPassing -eq 'Legacy')) {
             $RequestComp="$RequestComp" + ' \`"\`"'
        } else {
             $RequestComp = "$RequestComp" + ' ""'
        }
    }

    __${t2}_debug "Calling $RequestComp"
    # First disable ActiveHelp which is not supported for Powershell
    $env:ActiveHelp = 0

    # call the command store the output in $out and redirect stderr and stdout to null
    # $Out is an array contains each line per element
    Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null

    # get directive from last line
    [int]$Directive = $Out[-1].TrimStart(':')
    if ($Directive -eq "") {
        # There is no directive specified
        $Directive = 0
    }
    __${t2}_debug "The completion directive is: $Directive"

    # remove directive (last element) from out
    $Out = $Out | Where-Object { $_ -ne $Out[-1] }
    __${t2}_debug "The completions are: $Out"

    if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
        # Error code.  No completion.
        __${t2}_debug "Received error from custom completion go code"
        return
    }

    $Longest = 0
    [Array]$Values = $Out | ForEach-Object {
        # Split the output in name and description
        $Name, $Description = $_.Split("\`t", 2)
        __${t2}_debug "Name: $Name Description: $Description"

        # Look for the longest completion so that we can format things nicely
        if ($Longest -lt $Name.Length) {
            $Longest = $Name.Length
        }

        # Set the description to a one space string if there is none set.
        # This is needed because the CompletionResult does not accept an empty string as argument
        if (-Not $Description) {
            $Description = " "
        }
        @{ Name = "$Name"; Description = "$Description" }
    }


    $Space = " "
    if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
        # remove the space here
        __${t2}_debug "ShellCompDirectiveNoSpace is called"
        $Space = ""
    }

    if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
       (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 ))  {
        __${t2}_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"

        # return here to prevent the completion of the extensions
        return
    }

    $Values = $Values | Where-Object {
        # filter the result
        $_.Name -like "$WordToComplete*"

        # Join the flag back if we have an equal sign flag
        if ( $IsEqualFlag ) {
            __${t2}_debug "Join the equal sign flag back to the completion value"
            $_.Name = $Flag + "=" + $_.Name
        }
    }

    # we sort the values in ascending order by name if keep order isn't passed
    if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
        $Values = $Values | Sort-Object -Property Name
    }

    if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
        __${t2}_debug "ShellCompDirectiveNoFileComp is called"

        if ($Values.Length -eq 0) {
            # Just print an empty string here so the
            # shell does not start to complete paths.
            # We cannot use CompletionResult here because
            # it does not accept an empty string as argument.
            ""
            return
        }
    }

    # Get the current mode
    $Mode = (Get-PSReadLineKeyHandler | Where-Object { $_.Key -eq "Tab" }).Function
    __${t2}_debug "Mode: $Mode"

    $Values | ForEach-Object {

        # store temporary because switch will overwrite $_
        $comp = $_

        # PowerShell supports three different completion modes
        # - TabCompleteNext (default windows style - on each key press the next option is displayed)
        # - Complete (works like bash)
        # - MenuComplete (works like zsh)
        # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>

        # CompletionResult Arguments:
        # 1) CompletionText text to be used as the auto completion result
        # 2) ListItemText   text to be displayed in the suggestion list
        # 3) ResultType     type of completion result
        # 4) ToolTip        text for the tooltip with details about the object

        switch ($Mode) {

            # bash like
            "Complete" {

                if ($Values.Length -eq 1) {
                    __${t2}_debug "Only one completion left"

                    # insert space after value
                    [System.Management.Automation.CompletionResult]::new($($comp.Name | __${t2}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")

                } else {
                    # Add the proper number of spaces to align the descriptions
                    while($comp.Name.Length -lt $Longest) {
                        $comp.Name = $comp.Name + " "
                    }

                    # Check for empty description and only add parentheses if needed
                    if ($($comp.Description) -eq " " ) {
                        $Description = ""
                    } else {
                        $Description = "  ($($comp.Description))"
                    }

                    [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
                }
             }

            # zsh like
            "MenuComplete" {
                # insert space after value
                # MenuComplete will automatically show the ToolTip of
                # the highlighted value at the bottom of the suggestions.
                [System.Management.Automation.CompletionResult]::new($($comp.Name | __${t2}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
            }

            # TabCompleteNext and in case we get something unknown
            Default {
                # Like MenuComplete but we don't want to add a space here because
                # the user need to press space anyway to get the completion.
                # Description will not be shown because that's not possible with TabCompleteNext
                [System.Management.Automation.CompletionResult]::new($($comp.Name | __${t2}_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
            }
        }

    }
}

Register-ArgumentCompleter -CommandName '${t2}' -ScriptBlock $__${r2}CompleterBlock
`;
}
__name(i, "i");
var a = { ShellCompDirectiveError: 1, ShellCompDirectiveNoSpace: 2, ShellCompDirectiveNoFileComp: 4, ShellCompDirectiveFilterFileExt: 8, ShellCompDirectiveFilterDirs: 16, ShellCompDirectiveKeepOrder: 32, ShellCompDirectiveDefault: 0 };
var o = class {
  static {
    __name(this, "o");
  }
  name;
  variadic;
  command;
  handler;
  constructor(e, t2, n2, r2 = false) {
    this.command = e, this.name = t2, this.handler = n2, this.variadic = r2;
  }
};
var s = class {
  static {
    __name(this, "s");
  }
  value;
  description;
  command;
  handler;
  alias;
  isBoolean;
  constructor(e, t2, n2, r2, i3, a2) {
    this.command = e, this.value = t2, this.description = n2, this.handler = r2, this.alias = i3, this.isBoolean = a2;
  }
};
var c = class {
  static {
    __name(this, "c");
  }
  value;
  description;
  options = /* @__PURE__ */ new Map();
  arguments = /* @__PURE__ */ new Map();
  parent;
  constructor(e, t2) {
    this.value = e, this.description = t2;
  }
  option(e, t2, n2, r2) {
    let i3, a2, o2;
    typeof n2 == `function` ? (i3 = n2, a2 = r2, o2 = false) : typeof n2 == `string` ? (i3 = void 0, a2 = n2, o2 = true) : (i3 = void 0, a2 = void 0, o2 = true);
    let c2 = new s(this, e, t2, i3, a2, o2);
    return this.options.set(e, c2), this;
  }
  argument(e, t2, n2 = false) {
    let r2 = new o(this, e, t2, n2);
    return this.arguments.set(e, r2), this;
  }
};
var l = class extends c {
  static {
    __name(this, "l");
  }
  commands = /* @__PURE__ */ new Map();
  completions = [];
  directive = a.ShellCompDirectiveDefault;
  constructor() {
    super(``, ``);
  }
  command(e, t2) {
    let n2 = new c(e, t2);
    return this.commands.set(e, n2), n2;
  }
  stripOptions(e) {
    let t2 = [], n2 = 0;
    for (; n2 < e.length; ) {
      let r2 = e[n2];
      if (r2.startsWith(`-`)) {
        n2++;
        let t3 = false, i3 = this.findOption(this, r2);
        if (i3) t3 = i3.isBoolean ?? false;
        else for (let [, e2] of this.commands) {
          let n3 = this.findOption(e2, r2);
          if (n3) {
            t3 = n3.isBoolean ?? false;
            break;
          }
        }
        !t3 && n2 < e.length && !e[n2].startsWith(`-`) && n2++;
      } else t2.push(r2), n2++;
    }
    return t2;
  }
  matchCommand(e) {
    e = this.stripOptions(e);
    let t2 = [], n2 = [], r2 = null;
    for (let i3 = 0; i3 < e.length; i3++) {
      let a2 = e[i3];
      t2.push(a2);
      let o2 = this.commands.get(t2.join(` `));
      if (o2) r2 = o2;
      else {
        n2 = e.slice(i3, e.length);
        break;
      }
    }
    return [r2 || this, n2];
  }
  shouldCompleteFlags(e, t2) {
    if (t2.startsWith(`-`)) return true;
    if (e?.startsWith(`-`)) {
      let t3 = this.findOption(this, e);
      if (!t3) {
        for (let [, n2] of this.commands) if (t3 = this.findOption(n2, e), t3) break;
      }
      return !(t3 && t3.isBoolean);
    }
    return false;
  }
  shouldCompleteCommands(e) {
    return !e.startsWith(`-`);
  }
  handleFlagCompletion(e, t2, n2, r2) {
    let i3;
    if (n2.includes(`=`)) {
      let [e2] = n2.split(`=`);
      i3 = e2;
    } else if (r2?.startsWith(`-`)) {
      let t3 = this.findOption(e, r2);
      t3 && !t3.isBoolean && (i3 = r2);
    }
    if (i3) {
      let t3 = this.findOption(e, i3);
      if (t3?.handler) {
        let n3 = [];
        t3.handler.call(t3, (e2, t4) => n3.push({ value: e2, description: t4 }), e.options), this.completions = n3;
      }
      return;
    }
    if (n2.startsWith(`-`)) {
      let t3 = n2.startsWith(`-`) && !n2.startsWith(`--`), r3 = n2.replace(/^-+/, ``);
      for (let [i4, a2] of e.options) t3 && a2.alias && `-${a2.alias}`.startsWith(n2) ? this.completions.push({ value: `-${a2.alias}`, description: a2.description }) : !t3 && i4.startsWith(r3) && this.completions.push({ value: `--${i4}`, description: a2.description });
    }
  }
  findOption(e, t2) {
    let n2 = e.options.get(t2);
    if (n2 || (n2 = e.options.get(t2.replace(/^-+/, ``)), n2)) return n2;
    for (let [n3, r2] of e.options) if (r2.alias && `-${r2.alias}` === t2) return r2;
  }
  handleCommandCompletion(e, t2) {
    let n2 = this.stripOptions(e);
    for (let [e2, r2] of this.commands) {
      if (e2 === ``) continue;
      let i3 = e2.split(` `);
      i3.slice(0, n2.length).every((e3, t3) => e3 === n2[t3]) && i3[n2.length]?.startsWith(t2) && this.completions.push({ value: i3[n2.length], description: r2.description });
    }
  }
  handlePositionalCompletion(e, t2) {
    let n2 = this.stripOptions(t2), r2 = e.value.split(` `).length, i3 = Math.max(0, n2.length - r2), a2 = Array.from(e.arguments.entries());
    if (a2.length > 0) {
      let t3;
      if (i3 < a2.length) {
        let [e2, n3] = a2[i3];
        t3 = n3;
      } else {
        let e2 = a2[a2.length - 1][1];
        e2.variadic && (t3 = e2);
      }
      if (t3 && t3.handler && typeof t3.handler == `function`) {
        let n3 = [];
        t3.handler.call(t3, (e2, t4) => n3.push({ value: e2, description: t4 }), e.options), this.completions.push(...n3);
      }
    }
  }
  complete(e) {
    this.directive = a.ShellCompDirectiveNoFileComp;
    let t2 = /* @__PURE__ */ new Set();
    this.completions.filter((e2) => t2.has(e2.value) ? false : (t2.add(e2.value), true)).filter((t3) => {
      if (e.includes(`=`)) {
        let [, n2] = e.split(`=`);
        return t3.value.startsWith(n2);
      }
      return t3.value.startsWith(e);
    }).forEach((e2) => console.log(`${e2.value}	${e2.description ?? ``}`)), console.log(`:${this.directive}`);
  }
  parse(e) {
    this.completions = [];
    let t2 = e[e.length - 1] === ``;
    t2 && e.pop();
    let n2 = e[e.length - 1] || ``, r2 = e.slice(0, -1);
    t2 && (n2 !== `` && r2.push(n2), n2 = ``);
    let [i3] = this.matchCommand(r2), a2 = r2[r2.length - 1];
    this.shouldCompleteFlags(a2, n2) ? this.handleFlagCompletion(i3, r2, n2, a2) : (this.shouldCompleteCommands(n2) && this.handleCommandCompletion(r2, n2), i3 && i3.arguments.size > 0 && this.handlePositionalCompletion(i3, r2)), this.complete(n2);
  }
  setup(a2, o2, s2) {
    switch (i2(s2 === `zsh` || s2 === `bash` || s2 === `fish` || s2 === `powershell`, `Unsupported shell`), s2) {
      case `zsh`: {
        let t2 = t(a2, o2);
        console.log(t2);
        break;
      }
      case `bash`: {
        let e = n(a2, o2);
        console.log(e);
        break;
      }
      case `fish`: {
        let e = r(a2, o2);
        console.log(e);
        break;
      }
      case `powershell`: {
        let e = i(a2, o2);
        console.log(e);
        break;
      }
    }
  }
};
new l();

// ../../node_modules/.bun/@gunshi+plugin@0.32.0/node_modules/@gunshi/plugin/lib/index.js
var ANONYMOUS_COMMAND_NAME = "(anonymous)";
var NOOP = /* @__PURE__ */ __name(() => {
}, "NOOP");
var CLI_OPTIONS_DEFAULT = {
  name: void 0,
  description: void 0,
  version: void 0,
  cwd: void 0,
  usageSilent: false,
  subCommands: void 0,
  leftMargin: 2,
  middleMargin: 10,
  usageOptionType: false,
  usageOptionValue: true,
  renderHeader: void 0,
  renderUsage: void 0,
  renderValidationErrors: void 0,
  plugins: void 0,
  fallbackToEntry: false
};
function isLazyCommand(cmd) {
  return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
}
__name(isLazyCommand, "isLazyCommand");
function create(obj = null) {
  return Object.create(obj);
}
__name(create, "create");
function log(...args) {
  console.log(...args);
}
__name(log, "log");
function deepFreeze(obj, ignores = []) {
  if (obj === null || typeof obj !== "object") return obj;
  for (const key of Object.keys(obj)) {
    const value = obj[key];
    if (ignores.includes(key)) continue;
    if (typeof value === "object" && value !== null) deepFreeze(value, ignores);
  }
  return Object.freeze(obj);
}
__name(deepFreeze, "deepFreeze");
async function createCommandContext({ args = {}, explicit = {}, values = {}, positionals = [], rest = [], argv = [], tokens = [], command = {}, extensions = {}, cliOptions = {}, callMode = "entry", commandPath = [], omitted = false, validationError }) {
  const _args = Object.entries(args).reduce((acc, [key, value]) => {
    acc[key] = Object.assign(create(), value);
    return acc;
  }, create());
  const env = Object.assign(create(), CLI_OPTIONS_DEFAULT, cliOptions);
  if (command.rendering) {
    const { header, usage, validationErrors } = command.rendering;
    if (header !== void 0) env.renderHeader = header;
    if (usage !== void 0) env.renderUsage = usage;
    if (validationErrors !== void 0) env.renderValidationErrors = validationErrors;
  }
  const core = Object.assign(create(), {
    name: getCommandName(command),
    description: command.description,
    omitted,
    callMode,
    commandPath,
    env,
    args: _args,
    explicit,
    values,
    positionals,
    rest,
    _: argv,
    tokens,
    toKebab: command.toKebab,
    log: cliOptions.usageSilent ? NOOP : log,
    validationError
  });
  if (Object.keys(extensions).length > 0) {
    const ext = create(null);
    Object.defineProperty(core, "extensions", {
      value: ext,
      writable: false,
      enumerable: true,
      configurable: true
    });
    for (const [key, extension] of Object.entries(extensions)) {
      ext[key] = await extension.factory(core, command);
      if (extension.onFactory) await extension.onFactory(core, command);
    }
  }
  return deepFreeze(core, ["extensions"]);
}
__name(createCommandContext, "createCommandContext");
function getCommandName(cmd) {
  if (isLazyCommand(cmd)) return cmd.commandName || cmd.name || "(anonymous)";
  else if (typeof cmd === "object") return cmd.name || "(anonymous)";
  else return ANONYMOUS_COMMAND_NAME;
}
__name(getCommandName, "getCommandName");
var NOOP_EXTENSION = /* @__PURE__ */ __name(() => {
  return /* @__PURE__ */ Object.create(null);
}, "NOOP_EXTENSION");
function plugin(options = {}) {
  const { id, name, setup, onExtension, dependencies: dependencies2 } = options;
  const extension = options.extension || NOOP_EXTENSION;
  const pluginFn = /* @__PURE__ */ __name(async (ctx) => {
    if (setup) await setup(ctx);
  }, "pluginFn");
  const props = {
    writable: false,
    enumerable: true,
    configurable: true
  };
  return Object.defineProperties(pluginFn, {
    id: {
      value: id,
      ...props
    },
    ...name && { name: {
      value: name,
      ...props
    } },
    ...dependencies2 && { dependencies: {
      value: dependencies2,
      ...props
    } },
    ...extension && { extension: {
      value: {
        key: Symbol(id),
        factory: extension,
        onFactory: onExtension
      },
      ...props
    } }
  });
}
__name(plugin, "plugin");

// ../../node_modules/.bun/@gunshi+plugin-completion@0.32.0+42f10d8c7c361fb1/node_modules/@gunshi/plugin-completion/lib/index.js
function kebabnize(str) {
  return str.replace(/[A-Z]/g, (match, offset) => (offset > 0 ? "-" : "") + match.toLowerCase());
}
__name(kebabnize, "kebabnize");
function isLazyCommand2(cmd) {
  return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
}
__name(isLazyCommand2, "isLazyCommand");
async function resolveLazyCommand(cmd, name, needRunResolving = false) {
  let command;
  if (isLazyCommand2(cmd)) {
    const baseCommand = {
      name: cmd.commandName,
      description: cmd.description,
      args: cmd.args,
      examples: cmd.examples,
      internal: cmd.internal,
      entry: cmd.entry,
      subCommands: cmd.subCommands
    };
    if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
    command = Object.assign(create2(), baseCommand);
    if (needRunResolving) {
      const loaded = await cmd();
      if (typeof loaded === "function") command.run = loaded;
      else if (typeof loaded === "object") {
        if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
        command.run = loaded.run;
        command.name = loaded.name;
        command.description = loaded.description;
        command.args = loaded.args;
        command.examples = loaded.examples;
        command.internal = loaded.internal;
        command.entry = loaded.entry;
        command.subCommands = loaded.subCommands || cmd.subCommands;
        if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
      } else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
    }
  } else command = Object.assign(create2(), cmd);
  if (command.name == null && name) command.name = name;
  return deepFreeze2(command);
}
__name(resolveLazyCommand, "resolveLazyCommand");
function create2(obj = null) {
  return Object.create(obj);
}
__name(create2, "create");
function deepFreeze2(obj, ignores = []) {
  if (obj === null || typeof obj !== "object") return obj;
  for (const key of Object.keys(obj)) {
    const value = obj[key];
    if (ignores.includes(key)) continue;
    if (typeof value === "object" && value !== null) deepFreeze2(value, ignores);
  }
  return Object.freeze(obj);
}
__name(deepFreeze2, "deepFreeze");
var BUILD_IN_PREFIX_AND_KEY_SEPARATOR = `_:`;
var ARG_PREFIX_AND_KEY_SEPARATOR = `arg:`;
var NEGATABLE = "Negatable of";
var en_US_default = {
  COMMAND: "COMMAND",
  COMMANDS: "COMMANDS",
  SUBCOMMAND: "SUBCOMMAND",
  USAGE: "USAGE",
  ARGUMENTS: "ARGUMENTS",
  OPTIONS: "OPTIONS",
  EXAMPLES: "EXAMPLES",
  FORMORE: "For more info, run any command with the `--help` flag",
  NEGATABLE,
  DEFAULT: "default",
  CHOICES: "choices",
  help: "Display this help message",
  version: "Display this version"
};
function resolveArgKey(key, name) {
  return `${name ? `${name}:` : ""}arg:${key}`;
}
__name(resolveArgKey, "resolveArgKey");
function resolveKey(key, name) {
  return `${name ? `${name}:` : ""}${key}`;
}
__name(resolveKey, "resolveKey");
async function resolveExamples(ctx, examples) {
  return typeof examples === "string" ? examples : typeof examples === "function" ? await examples(ctx) : "";
}
__name(resolveExamples, "resolveExamples");
function namespacedId(id) {
  return `g:${id}`;
}
__name(namespacedId, "namespacedId");
function makeShortLongOptionPair(schema, name, toKebab) {
  let key = `--${toKebab || schema.toKebab ? kebabnize(name) : name}`;
  if (schema.short) key = `-${schema.short}, ${key}`;
  return key;
}
__name(makeShortLongOptionPair, "makeShortLongOptionPair");
function localizable(ctx, cmd, translate) {
  async function localize(key, values) {
    if (translate) return translate(key, values);
    if (key.startsWith(BUILD_IN_PREFIX_AND_KEY_SEPARATOR)) return en_US_default[key.slice(BUILD_IN_PREFIX_AND_KEY_SEPARATOR.length)] || key;
    const namaspacedArgKey = resolveKey(ARG_PREFIX_AND_KEY_SEPARATOR, ctx.name);
    if (key.startsWith(namaspacedArgKey)) {
      let argKey = key.slice(namaspacedArgKey.length);
      let negatable = false;
      if (argKey.startsWith("no-")) {
        argKey = argKey.slice(3);
        negatable = true;
      }
      const schema = ctx.args[argKey];
      if (!schema) return argKey;
      return negatable && schema.type === "boolean" && schema.negatable ? `${NEGATABLE} ${makeShortLongOptionPair(schema, argKey, ctx.toKebab)}` : schema.description || "";
    }
    if (key === resolveKey("description", ctx.name)) return "";
    else if (key === resolveKey("examples", ctx.name)) return await resolveExamples(ctx, cmd.examples);
    else return key;
  }
  __name(localize, "localize");
  return localize;
}
__name(localizable, "localizable");
var pluginId = namespacedId("completion");
function getRuntimeGlobals() {
  return globalThis;
}
__name(getRuntimeGlobals, "getRuntimeGlobals");
function detectRuntime() {
  return detectRuntimeFromGlobals(getRuntimeGlobals());
}
__name(detectRuntime, "detectRuntime");
function detectRuntimeFromGlobals(globals) {
  if (globals.Bun !== void 0) return "bun";
  if (globals.Deno !== void 0) return "deno";
  if (globals.process !== void 0 && globals.process.release?.name === "node") return "node";
  return "unknown";
}
__name(detectRuntimeFromGlobals, "detectRuntimeFromGlobals");
function shellQuote(value) {
  if (value.length === 0) return "''";
  if (/^[\w%+,./:=@-]+$/.test(value)) return value;
  return `'${value.replaceAll(`'`, `'\\''`)}'`;
}
__name(shellQuote, "shellQuote");
function escapeDoubleQuotedShellString(value) {
  return value.replaceAll(/[$`"\\]/g, "\\$&");
}
__name(escapeDoubleQuotedShellString, "escapeDoubleQuotedShellString");
function basename(path2) {
  const slash = path2.lastIndexOf("/");
  const backslash = path2.lastIndexOf("\\");
  return path2.slice(Math.max(slash, backslash) + 1);
}
__name(basename, "basename");
function isBunVirtualEntry(entry) {
  return entry?.startsWith("/$bunfs/") === true || entry?.startsWith("B:\\~BUN\\") === true || entry?.startsWith("B:/~BUN/") === true;
}
__name(isBunVirtualEntry, "isBunVirtualEntry");
function isLikelyBunSingleBinary(execPath, entry) {
  const name = basename(execPath).toLowerCase();
  if (name !== "bun" && name !== "bun.exe") return true;
  return isBunVirtualEntry(entry);
}
__name(isLikelyBunSingleBinary, "isLikelyBunSingleBinary");
function resolveNodeExecParts(process3) {
  const entry = process3.argv[1];
  return [
    process3.execPath,
    ...process3.execArgv ?? [],
    ...entry ? [entry] : []
  ];
}
__name(resolveNodeExecParts, "resolveNodeExecParts");
function resolveBunExecParts(process3) {
  const entry = process3.argv[1];
  if (isLikelyBunSingleBinary(process3.execPath, entry)) return [process3.execPath];
  return [
    process3.execPath,
    ...process3.execArgv ?? [],
    ...entry ? [entry] : []
  ];
}
__name(resolveBunExecParts, "resolveBunExecParts");
function joinExecParts(parts) {
  return escapeDoubleQuotedShellString(parts.map(shellQuote).join(" "));
}
__name(joinExecParts, "joinExecParts");
function quoteExec() {
  const globals = getRuntimeGlobals();
  switch (detectRuntime()) {
    case "node":
      return joinExecParts(resolveNodeExecParts(globals.process));
    case "deno":
      throw new Error("Deno runtime is not supported for completion script generation yet.");
    case "bun":
      return joinExecParts(resolveBunExecParts(globals.process));
    default:
      throw new Error("Unsupported JavaScript runtime for completion script generation.");
  }
}
__name(quoteExec, "quoteExec");
var TERMINATOR = "--";
var NOOP_HANDLER = /* @__PURE__ */ __name(() => {
  return [];
}, "NOOP_HANDLER");
var i18nPluginId = namespacedId("i18n");
var dependencies = [{
  id: i18nPluginId,
  optional: true
}];
function completion(options = {}) {
  const config = options.config || {};
  const t2 = new l();
  return plugin({
    id: pluginId,
    name: "completion",
    dependencies,
    setup(ctx) {
      const completeName = "complete";
      ctx.addCommand(completeName, {
        name: completeName,
        description: "Generate shell completion script",
        rendering: { header: null },
        run: /* @__PURE__ */ __name((cmdCtx) => {
          if (!cmdCtx.env.name) throw new Error("your cli name is not defined.");
          let shell = cmdCtx._[1];
          if (shell === TERMINATOR) shell = void 0;
          if (shell === void 0) t2.parse(cmdCtx._.slice(cmdCtx._.indexOf(TERMINATOR) + 1));
          else if ([
            "zsh",
            "bash",
            "fish",
            "powershell"
          ].includes(shell)) t2.setup(cmdCtx.env.name, quoteExec(), shell);
        }, "run")
      });
    },
    /**
    * setup bombshell completion with `onExtension` hook
    */
    onExtension: /* @__PURE__ */ __name(async (ctx, cmd) => {
      const i18n = ctx.extensions[i18nPluginId];
      const subCommands2 = ctx.env.subCommands;
      await registerCompletion({
        name: "entry",
        cmd: [...subCommands2].map(([_, cmd2]) => cmd2).find((cmd2) => cmd2.entry) || cmd,
        config,
        i18nPluginId,
        i18n,
        t: t2,
        isBombshellRoot: true
      });
      await handleSubCommands(t2, subCommands2, i18nPluginId, config.subCommands, i18n);
    }, "onExtension")
  });
}
__name(completion, "completion");
async function registerCompletion({ name, cmd, config, i18nPluginId: i18nPluginId2, i18n, t: t2, isBombshellRoot = false }) {
  const resolvedCmd = await resolveLazyCommand(cmd);
  const extensions = /* @__PURE__ */ Object.create(null);
  if (i18n) extensions[i18nPluginId2] = {
    key: Symbol(i18nPluginId2),
    factory: /* @__PURE__ */ __name(() => i18n, "factory")
  };
  const ctx = await createCommandContext({
    args: resolvedCmd.args || /* @__PURE__ */ Object.create(null),
    command: resolvedCmd,
    callMode: resolvedCmd.entry ? "entry" : "subCommand",
    extensions
  });
  if (i18n) {
    if (!await i18n.loadResource(i18n.locale, ctx, resolvedCmd)) console.warn(`Failed to load i18n resources for command: ${name} (${i18n.locale.toString()})`);
  }
  const localizeDescription = localizable(ctx, resolvedCmd, i18n ? i18n.translate : void 0);
  const commandTab = isBombshellRoot ? t2 : t2.command(name, await localizeDescription(resolveKey("description", ctx.name)) || resolvedCmd.description || "");
  const args = resolvedCmd.args || /* @__PURE__ */ Object.create(null);
  for (const [key, schema] of Object.entries(args)) if (schema.type === "positional") commandTab.argument(key, resolveCompletionHandler(name, key, config, i18n), schema.multiple);
  else commandTab.option(key, await localizeDescription(resolveArgKey(key, ctx.name)) || schema.description || "", resolveCompletionHandler(name, key, config, i18n), schema.short);
}
__name(registerCompletion, "registerCompletion");
function resolveCompletionHandler(name, optionOrArgKey, config, i18n) {
  return function(complete) {
    const handler = config[name]?.args?.[optionOrArgKey]?.handler || NOOP_HANDLER;
    for (const item of handler({ locale: i18n?.locale })) complete(item.value, item.description || "");
  };
}
__name(resolveCompletionHandler, "resolveCompletionHandler");
async function handleSubCommands(t2, subCommands2, i18nPluginId2, config = {}, i18n, parentPath = "") {
  for (const [name, cmd] of subCommands2) {
    if (cmd.internal || cmd.entry || name === "complete") continue;
    const fullName = parentPath ? `${parentPath} ${name}` : name;
    await registerCompletion({
      name: fullName,
      cmd,
      config,
      i18nPluginId: i18nPluginId2,
      i18n,
      t: t2
    });
    const nestedSubCommands = getNestedSubCommands(cmd);
    if (nestedSubCommands && nestedSubCommands.size > 0) await handleSubCommands(t2, nestedSubCommands, i18nPluginId2, config, i18n, fullName);
  }
}
__name(handleSubCommands, "handleSubCommands");
function getNestedSubCommands(cmd) {
  const subCommands2 = typeof cmd === "function" ? cmd.subCommands : cmd.subCommands;
  if (!subCommands2) return;
  if (subCommands2 instanceof Map) return subCommands2.size > 0 ? subCommands2 : void 0;
  if (typeof subCommands2 === "object") {
    const entries = Object.entries(subCommands2);
    if (entries.length === 0) return;
    const map = /* @__PURE__ */ new Map();
    for (const [name, c2] of entries) map.set(name, c2);
    return map;
  }
}
__name(getNestedSubCommands, "getNestedSubCommands");
var VARLOCK_BANNER = [
  "",
  " \u2588\u2588\u2592   \u2588\u2593 \u2584\u2584\u2584       \u2588\u2588\u2580\u2588\u2588\u2588   \u2588\u2588\u2593     \u2592\u2588\u2588\u2588\u2588\u2588   \u2584\u2588\u2588\u2588\u2588\u2584   \u2588\u2588 \u2584\u2588\u2580",
  " \u2593\u2588\u2588\u2591   \u2588\u2592\u2592\u2588\u2588\u2588\u2588\u2584    \u2593\u2588\u2588 \u2592 \u2588\u2588\u2592\u2593\u2588\u2588\u2592    \u2592\u2588\u2588\u2592  \u2588\u2588\u2592\u2592\u2588\u2588\u2580 \u2580\u2588   \u2588\u2588\u2584\u2588\u2592 ",
  "  \u2593\u2588\u2588  \u2588\u2592\u2591\u2592\u2588\u2588  \u2580\u2588\u2584  \u2593\u2588\u2588 \u2591\u2584\u2588 \u2592\u2592\u2588\u2588\u2591    \u2592\u2588\u2588\u2591  \u2588\u2588\u2592\u2592\u2588\u2588    \u2584 \u2593\u2588\u2588\u2588\u2584\u2591 ",
  "   \u2592\u2588\u2588 \u2588\u2591\u2591\u2591\u2588\u2588\u2584\u2584\u2584\u2584\u2588\u2588 \u2592\u2588\u2588\u2580\u2580\u2588\u2584  \u2592\u2588\u2588\u2591    \u2592\u2588\u2588   \u2588\u2588\u2591\u2592\u2588\u2588\u2584 \u2584\u2588\u2588\u2592\u2593\u2588\u2588 \u2588\u2584 ",
  "    \u2592\u2580\u2588\u2591   \u2593\u2588   \u2593\u2588\u2588\u2592\u2591\u2588\u2588\u2593 \u2592\u2588\u2588\u2592\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2592\u2591 \u2588\u2588\u2588\u2588\u2588\u2592\u2591\u2592 \u2588\u2588\u2588\u2588\u2580 \u2591\u2592\u2588\u2588\u2592 \u2588\u2584",
  "    \u2591 \u2590\u2591   \u2592\u2592   \u2593\u2592\u2588\u2591\u2591 \u2592\u2593 \u2591\u2592\u2593\u2591\u2591 \u2592\u2591\u2593  \u2591\u2591 \u2592\u2591\u2592\u2591\u2592\u2591 \u2591 \u2591\u2592 \u2592  \u2591\u2592 \u2592\u2592 \u2593\u2592",
  "    \u2591 \u2591\u2591    \u2592   \u2592\u2592 \u2591  \u2591\u2592 \u2591 \u2592\u2591\u2591 \u2591 \u2592  \u2591  \u2591 \u2592 \u2592\u2591   \u2591  \u2592   \u2591 \u2591\u2592 \u2592\u2591",
  "      \u2591\u2591    \u2591   \u2592     \u2591\u2591   \u2591   \u2591 \u2591   \u2591 \u2591 \u2591 \u2592  \u2591        \u2591 \u2591\u2591 \u2591 ",
  "       \u2591        \u2591  \u2591   \u2591         \u2591  \u2591    \u2591 \u2591  \u2591 \u2591      \u2591  \u2591   "
  // '      ░                                       ░               ',
].join("\n");
var VARLOCK_BANNER_COLOR = VARLOCK_BANNER.replaceAll(/([▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐▔▕▖▗▘▙▚▛▜▝▞▟]+)/g, (m) => ansis_default.hex("#DD0000")(m)).replaceAll(/([▓░▒]+)/g, (m) => ansis_default.blue(m));
var import_ci_info = __toESM(require_ci_info(), 1);
var isDockerCached;
function hasDockerEnv() {
  try {
    fs.statSync("/.dockerenv");
    return true;
  } catch {
    return false;
  }
}
__name(hasDockerEnv, "hasDockerEnv");
function hasDockerCGroup() {
  try {
    return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
  } catch {
    return false;
  }
}
__name(hasDockerCGroup, "hasDockerCGroup");
function hasDockerMountInfo() {
  try {
    return fs.readFileSync("/proc/self/mountinfo", "utf8").includes("/docker/containers/");
  } catch {
    return false;
  }
}
__name(hasDockerMountInfo, "hasDockerMountInfo");
function isDocker() {
  isDockerCached ??= hasDockerEnv() || hasDockerCGroup() || hasDockerMountInfo();
  return isDockerCached;
}
__name(isDocker, "isDocker");
var isDockerCached2;
function hasDockerEnv2() {
  try {
    fs.statSync("/.dockerenv");
    return true;
  } catch {
    return false;
  }
}
__name(hasDockerEnv2, "hasDockerEnv");
function hasDockerCGroup2() {
  try {
    return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
  } catch {
    return false;
  }
}
__name(hasDockerCGroup2, "hasDockerCGroup");
function isDocker2() {
  if (isDockerCached2 === void 0) {
    isDockerCached2 = hasDockerEnv2() || hasDockerCGroup2();
  }
  return isDockerCached2;
}
__name(isDocker2, "isDocker");

// ../../node_modules/.bun/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
var cachedResult;
var hasContainerEnv = /* @__PURE__ */ __name(() => {
  try {
    fs.statSync("/run/.containerenv");
    return true;
  } catch {
    return false;
  }
}, "hasContainerEnv");
function isInsideContainer() {
  if (cachedResult === void 0) {
    cachedResult = hasContainerEnv() || isDocker2();
  }
  return cachedResult;
}
__name(isInsideContainer, "isInsideContainer");

// ../../node_modules/.bun/is-wsl@3.1.1/node_modules/is-wsl/index.js
var isWsl = /* @__PURE__ */ __name(() => {
  if (process2.platform !== "linux") {
    return false;
  }
  if (os2.release().toLowerCase().includes("microsoft")) {
    if (isInsideContainer()) {
      return false;
    }
    return true;
  }
  try {
    if (fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) {
      return !isInsideContainer();
    }
  } catch {
  }
  if (fs.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs.existsSync("/run/WSL")) {
    return !isInsideContainer();
  }
  return false;
}, "isWsl");
var is_wsl_default = process2.env.__IS_WSL_TEST__ ? isWsl : isWsl();

// package.json
var package_default = {
  name: "varlock",
  version: "1.7.0",
  description: "AI-safe .env files: Schemas for agents, Secrets for humans.",
  main: "index.js",
  type: "module",
  author: "dmno-dev",
  license: "MIT",
  homepage: "https://varlock.dev",
  bugs: "https://github.com/dmno-dev/varlock/issues",
  repository: {
    type: "git",
    url: "https://github.com/dmno-dev/varlock.git",
    directory: "packages/varlock"
  },
  scripts: {
    build: "tsup",
    "build:binary": "bun run scripts/build-binaries.ts --dev",
    "build:binaries": "bun run scripts/build-binaries.ts",
    "test:local-encrypt:reset": "bun run scripts/reset-local-encrypt-state.ts",
    "test:local-encrypt:reset:dry": "bun run scripts/reset-local-encrypt-state.ts --dry-run",
    "test:local-encrypt:fresh": "bun run scripts/reset-local-encrypt-state.ts --status",
    "test:local-encrypt:fresh:dry": "bun run scripts/reset-local-encrypt-state.ts --dry-run --status",
    "pack:local": "bun run scripts/pack-local-package.ts",
    "test:binary:local": "bun run scripts/test-local-binary.ts",
    dev: "tsup",
    test: "vitest",
    "test:ci": "vitest --run",
    lint: "eslint .",
    "lint:fix": "bun run lint --fix",
    typecheck: "tsc --noEmit"
  },
  keywords: [
    "varlock",
    "secrets",
    "secret-management",
    "env",
    ".env",
    "dotenv",
    "environment variables",
    "env vars",
    "config",
    "1password",
    "bitwarden",
    "infisical",
    "aws",
    "azure",
    "google-cloud",
    "secrets-manager"
  ],
  files: [
    "/bin",
    "/dist",
    "/native-bins"
  ],
  bin: {
    varlock: "./bin/cli.js"
  },
  engines: {
    node: ">=22",
    bun: ">=1.3.3"
  },
  dependencies: {},
  exports: {
    ".": {
      "ts-src": "./src/index.ts",
      types: "./dist/index.d.ts",
      default: "./dist/index.js"
    },
    "./env": {
      "ts-src": "./src/runtime/env.ts",
      types: "./dist/runtime/env.d.ts",
      default: "./dist/runtime/env.js"
    },
    "./auto-load": {
      "ts-src": "./src/auto-load.ts",
      types: "./dist/auto-load.d.ts",
      default: "./dist/auto-load.js"
    },
    "./patch-console": {
      "ts-src": "./src/runtime/patch-console.ts",
      types: "./dist/runtime/patch-console.d.ts",
      default: "./dist/runtime/patch-console.js"
    },
    "./patch-response": {
      "ts-src": "./src/runtime/patch-response.ts",
      types: "./dist/runtime/patch-response.d.ts",
      default: "./dist/runtime/patch-response.js"
    },
    "./patch-server-response": {
      "ts-src": "./src/runtime/patch-server-response.ts",
      types: "./dist/runtime/patch-server-response.d.ts",
      default: "./dist/runtime/patch-server-response.js"
    },
    "./init-server": {
      "ts-src": "./src/runtime/init-server.ts",
      types: "./dist/runtime/init-server.d.cts",
      default: "./dist/runtime/init-server.cjs"
    },
    "./init-edge": {
      "ts-src": "./src/runtime/init-edge.ts",
      types: "./dist/runtime/init-edge.d.cts",
      default: "./dist/runtime/init-edge.cjs"
    },
    "./encrypt-env": {
      "ts-src": "./src/runtime/crypto.ts",
      types: "./dist/runtime/crypto.d.ts",
      default: "./dist/runtime/crypto.js"
    },
    "./exec-sync-varlock": {
      "ts-src": "./src/lib/exec-sync-varlock.ts",
      types: "./dist/lib/exec-sync-varlock.d.ts",
      default: "./dist/lib/exec-sync-varlock.js"
    },
    "./config": {
      "ts-src": "./src/config.ts",
      types: "./dist/dotenv-compat.d.ts",
      default: "./dist/dotenv-compat.js"
    },
    "./config.js": {
      "ts-src": "./src/config.ts",
      types: "./dist/dotenv-compat.d.ts",
      default: "./dist/dotenv-compat.js"
    },
    "./plugin-lib": {
      "ts-src": "./src/plugin-lib.ts",
      types: "./dist/plugin-lib.d.ts",
      default: "./dist/plugin-lib.js"
    },
    "./test-helpers": {
      "ts-src": "./src/test-helpers/plugin-test.ts",
      default: "./src/test-helpers/plugin-test.ts"
    }
  },
  devDependencies: {
    "@clack/core": "^1.0.0",
    "@clack/prompts": "^1.0.0",
    "@env-spec/parser": "workspace:*",
    "@env-spec/utils": "workspace:*",
    "@gunshi/plugin-completion": "^0.32.0",
    "@sindresorhus/is": "catalog:",
    "@types/bun": "catalog:",
    "@types/node": "catalog:",
    "@types/semver": "^7.7.1",
    "@varlock/ci-env-info": "workspace:^",
    "@vitest/coverage-v8": "^4.1.8",
    ansis: "catalog:",
    "browser-or-node": "^3.0.0",
    "ci-info": "^4.3.1",
    "exit-hook": "^5.1.0",
    gunshi: "^0.32.0",
    "is-docker": "^4.0.0",
    "is-unicode-supported": "^2.1.0",
    "is-wsl": "^3.1.0",
    outdent: "catalog:",
    semver: "^7.7.4",
    tsup: "catalog:",
    vitest: "catalog:"
  }
};

// src/config.ts
var CONFIG = {
  // varlock.dev app
  POSTHOG_API_KEY: "phc_bfzH97VIta8yQa8HrsgmitqS6rTydjMISs0m8aqJTnq",
  POSTHOG_HOST: "https://ph.varlock.dev"
};

// src/cli/helpers/telemetry.ts
var debug = createDebug("varlock:telemetry");
var TRUE_ENV_VAR_VALUES = ["true", "1", "t"];
var userVarlockDirPath = getUserVarlockDir();
var userVarlockConfigFilePath = join(userVarlockDirPath, "config.json");
var userVarlockConfig;
var projectVarlockConfig;
var mergedVarlockConfigFileContents;
var _gitDirPath;
var _varlockDirPath;
var _projectRootDirPath;
var _foundProjectRoot = false;
function findProjectDirs() {
  if (!_foundProjectRoot) {
    let currentDir = process.cwd();
    while (currentDir) {
      const possibleGitDirPath = join(currentDir, ".git");
      if (!_gitDirPath && existsSync(possibleGitDirPath)) {
        _gitDirPath = possibleGitDirPath;
      }
      const possibleVarlockDirPath = join(currentDir, ".varlock");
      if (!_varlockDirPath && possibleVarlockDirPath !== userVarlockDirPath && existsSync(possibleVarlockDirPath)) {
        _varlockDirPath = possibleVarlockDirPath;
      }
      const parentDir = dirname(currentDir);
      if (parentDir === currentDir) break;
      currentDir = parentDir;
    }
    if (_gitDirPath) _projectRootDirPath = dirname(_gitDirPath);
    else if (_varlockDirPath) _projectRootDirPath = dirname(_varlockDirPath);
    else _projectRootDirPath = process.cwd();
    _foundProjectRoot = true;
  }
  return {
    gitDirPath: _gitDirPath,
    varlockDirPath: _varlockDirPath,
    projectRootDirPath: _projectRootDirPath
  };
}
__name(findProjectDirs, "findProjectDirs");
function loadVarlockConfig() {
  if (mergedVarlockConfigFileContents) return mergedVarlockConfigFileContents;
  try {
    const userConfigStr = readFileSync(userVarlockConfigFilePath, "utf-8");
    userVarlockConfig = userConfigStr.trim() ? JSON.parse(userConfigStr) : void 0;
  } catch (err) {
    if (err instanceof Error && "code" in err && err.code === "ENOENT") {
      debug(`User varlock config file not found - ${userVarlockConfigFilePath}`);
    } else if (err instanceof SyntaxError) {
      throw new Error(`Invalid JSON in project varlock config - ${userVarlockConfigFilePath}`, { cause: err });
    } else {
      throw new Error(`Problem reading project varlock config - ${userVarlockConfigFilePath}`, { cause: err });
    }
  }
  const { varlockDirPath } = findProjectDirs();
  if (varlockDirPath) {
    const projectVarlockConfigPath = join(varlockDirPath, "config.json");
    try {
      const projectConfigStr = readFileSync(projectVarlockConfigPath, "utf-8");
      projectVarlockConfig = projectConfigStr.trim() ? JSON.parse(projectConfigStr) : void 0;
    } catch (err) {
      if (err instanceof Error && "code" in err && err.code === "ENOENT") {
        debug(`Project varlock config file not found - ${projectVarlockConfigPath}`);
      } else if (err instanceof SyntaxError) {
        throw new Error(`Invalid JSON in project varlock config - ${projectVarlockConfigPath}`, { cause: err });
      } else {
        throw new Error(`Problem reading project varlock config - ${projectVarlockConfigPath}`, { cause: err });
      }
    }
  }
  mergedVarlockConfigFileContents = {
    ...userVarlockConfig,
    ...projectVarlockConfig
  };
  return mergedVarlockConfigFileContents;
}
__name(loadVarlockConfig, "loadVarlockConfig");
var cachedAnonymousId;
function getAnonymousId() {
  if (cachedAnonymousId) return cachedAnonymousId;
  const varlockConfig = loadVarlockConfig();
  if (varlockConfig?.anonymousId) {
    cachedAnonymousId = varlockConfig.anonymousId;
    return varlockConfig.anonymousId;
  }
  const newAnonymousId = `${import_ci_info.isCI ? "ci-" : ""}${crypto.randomUUID()}`;
  try {
    if (!existsSync(userVarlockDirPath)) {
      mkdirSync(userVarlockDirPath, { recursive: true });
    }
    writeFileSync(
      userVarlockConfigFilePath,
      JSON.stringify({
        ...userVarlockConfig,
        anonymousId: newAnonymousId
      }, null, 2),
      { flag: "w" }
    );
  } catch (err) {
    if (os2.homedir() === "/dev/null") {
      debug("HOME directory is not set (probably running in Docker without HOME configured). Cannot persist anonymous ID.");
    } else {
      debug(`Cannot write to varlock config folder (${userVarlockDirPath}): ${err.message}`);
    }
  }
  cachedAnonymousId = newAnonymousId;
  return newAnonymousId;
}
__name(getAnonymousId, "getAnonymousId");
function checkIsOptedOut() {
  if (process.env.PH_OPT_OUT === "true" || process.env.VARLOCK_TELEMETRY_DISABLED && TRUE_ENV_VAR_VALUES.includes(process.env.VARLOCK_TELEMETRY_DISABLED.toLowerCase())) {
    debug("telemetry opted out - env var");
    return true;
  }
  const varlockConfig = loadVarlockConfig();
  if (varlockConfig?.analytics_opt_out || varlockConfig?.telemetryDisabled) {
    debug(`telemetry opted out - config file (${projectVarlockConfig?.telemetryDisabled ? "project" : "user"} config)`);
    return true;
  }
  return false;
}
__name(checkIsOptedOut, "checkIsOptedOut");
function anonymizeValue(payload) {
  if (payload === "") {
    return payload;
  }
  const hash = createHash("sha256");
  hash.update(payload);
  return hash.digest("hex");
}
__name(anonymizeValue, "anonymizeValue");
function getProjectGitRemoteUrl() {
  findProjectDirs();
  if (!_gitDirPath) return void 0;
  try {
    const gitConfigContents = readFileSync(join(_gitDirPath, "config"), "utf-8");
    const remoteUpstreamPos = gitConfigContents.indexOf('[remote "upstream"]');
    if (remoteUpstreamPos !== -1) {
      const remoteUpstreamUrl = gitConfigContents.slice(remoteUpstreamPos).match(/url = (.+)/)?.[1];
      return remoteUpstreamUrl;
    }
    const remoteOriginPos = gitConfigContents.indexOf('[remote "origin"]');
    if (remoteOriginPos === -1) return void 0;
    const remoteOriginUrl = gitConfigContents.slice(remoteOriginPos).match(/url = (.+)/)?.[1];
    return remoteOriginUrl;
  } catch (err) {
    return void 0;
  }
}
__name(getProjectGitRemoteUrl, "getProjectGitRemoteUrl");
function getAnonymousProjectId() {
  const gitRemoteUrl = getProjectGitRemoteUrl();
  if (!gitRemoteUrl) return null;
  return anonymizeValue(gitRemoteUrl);
}
__name(getAnonymousProjectId, "getAnonymousProjectId");
var cachedTelemetryMetadata;
function getTelemetryMeta() {
  if (cachedTelemetryMetadata) return cachedTelemetryMetadata;
  const cpus = os2.cpus() || [];
  let versionIdentifier = package_default.version;
  cachedTelemetryMetadata = {
    anonymous_project_id: getAnonymousProjectId(),
    node_version: process.version.replace(/^v?/, ""),
    varlock_version: versionIdentifier,
    // TODO: pass through version info for specific integrations/plugins?
    system_platform: os2.platform(),
    system_release: os2.release(),
    system_architecture: os2.arch(),
    cpu_count: cpus.length,
    cpu_model: cpus.length ? cpus[0].model : null,
    cpu_speed: cpus.length ? cpus[0].speed : null,
    memory_mb: Math.trunc(os2.totalmem() / 1024 ** 2),
    is_docker: isDocker(),
    is_tty: process.stdout.isTTY,
    is_wsl: is_wsl_default,
    is_ci: import_ci_info.isCI,
    ci_name: import_ci_info.name,
    is_sea: false
  };
  return cachedTelemetryMetadata;
}
__name(getTelemetryMeta, "getTelemetryMeta");
var isOptedOut = checkIsOptedOut();
var lastTelemetryReq;
async function posthogCapture(event, properties) {
  const telemetryMeta = getTelemetryMeta();
  const payload = {
    api_key: CONFIG.POSTHOG_API_KEY,
    event,
    properties: {
      $process_person_profile: false,
      ...telemetryMeta,
      ...properties
    },
    distinct_id: isOptedOut ? "---" : getAnonymousId()
  };
  debug(`track${isOptedOut ? " (disabled)" : ""}`, payload);
  if (isOptedOut) return;
  const removeExitHook = asyncExitHook(async () => {
    await lastTelemetryReq;
  }, { wait: 500 });
  lastTelemetryReq = fetch(`${CONFIG.POSTHOG_HOST}/i/v0/e/`, {
    method: "POST",
    body: JSON.stringify(payload),
    headers: {
      "Content-Type": "application/json"
    }
  }).then((res) => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.text();
  }).then((text) => debug("telemetry response:", text)).catch((error) => {
    debug("telemetry error:", error);
  }).finally(() => {
    removeExitHook();
  });
}
__name(posthogCapture, "posthogCapture");
async function trackCommand(command, properties) {
  await posthogCapture("cli_command_executed", {
    command,
    ...properties
  });
}
__name(trackCommand, "trackCommand");

// src/cli/cli-executable.ts
var versionId = package_default.version;
function buildLazyCommand(commandSpec17, loadCommandFn) {
  const commandName = commandSpec17.name;
  return {
    ...commandSpec17,
    run: /* @__PURE__ */ __name(async (...args) => {
      await trackCommand(commandName, { command: commandName });
      const commandSpecAndFn = await loadCommandFn();
      return commandSpecAndFn.commandFn(...args);
    }, "run")
  };
}
__name(buildLazyCommand, "buildLazyCommand");
var subCommands = /* @__PURE__ */ new Map();
subCommands.set("init", buildLazyCommand(commandSpec, async () => await import('../init.command-TCEMX4FS.js')));
subCommands.set("load", buildLazyCommand(commandSpec$1, async () => await import('../load.command-EJ7TPIKX.js')));
subCommands.set("run", buildLazyCommand(commandSpec$2, async () => await import('../run.command-HPS7R2MO.js')));
subCommands.set("printenv", buildLazyCommand(commandSpec$3, async () => await import('../printenv.command-AS4TMQAW.js')));
subCommands.set("encrypt", buildLazyCommand(commandSpec$4, async () => await import('../encrypt.command-TPPUPNE4.js')));
subCommands.set("lock", buildLazyCommand(commandSpec$5, async () => await import('../lock.command-5DUZUC32.js')));
subCommands.set("reveal", buildLazyCommand(commandSpec$6, async () => await import('../reveal.command-54SYZKRW.js')));
subCommands.set("explain", buildLazyCommand(commandSpec$7, async () => await import('../explain.command-E4XY7DD5.js')));
subCommands.set("help", buildLazyCommand(commandSpec$8, async () => await import('../help.command-CVRNLKQH.js')));
subCommands.set("telemetry", buildLazyCommand(commandSpec$9, async () => await import('../telemetry.command-FM3EI5OR.js')));
subCommands.set("scan", buildLazyCommand(commandSpec$a, async () => await import('../scan.command-HCG5L4HP.js')));
subCommands.set("audit", buildLazyCommand(commandSpec$b, async () => await import('../audit.command-HMLV2A3R.js')));
subCommands.set("typegen", buildLazyCommand(commandSpec$c, async () => await import('../typegen.command-NN4SVF3U.js')));
subCommands.set("install-plugin", buildLazyCommand(commandSpec$d, async () => await import('../install-plugin.command-6343YAAL.js')));
subCommands.set("generate-key", buildLazyCommand(commandSpec$e, async () => await import('../generate-key.command-3YV56KDX.js')));
subCommands.set("cache", buildLazyCommand(commandSpec$f, async () => await import('../cache.command-5CBTLZ5G.js')));
(/* @__PURE__ */ __name(async function go() {
  try {
    try {
      checkBunVersion();
    } catch (e) {
      throw new CliExitError(e.message, { forceExit: true });
    }
    let args = process.argv.slice(2);
    if (args[0] === "help") args = ["--help"];
    const isCompletionInvoke = args[0] === "complete";
    if (false) ;
    if (args[0] === "--version") {
      await trackCommand("version");
    }
    if (false) ;
    await cli(args, {
      // main command - triggered if you just run `varlock` with no args
      run: /* @__PURE__ */ __name(() => {
        console.log("Please run one of the sub-commands. Run `varlock --help` for more info.");
      }, "run")
    }, {
      name: "varlock",
      description: "Encrypt and protect your env vars",
      version: versionId,
      subCommands,
      plugins: [completion()],
      renderHeader: /* @__PURE__ */ __name(async (ctx) => {
        if (ctx.name) return "";
        return VARLOCK_BANNER_COLOR;
      }, "renderHeader")
    });
    if (process.platform === "win32") {
      await new Promise((resolve) => {
        setTimeout(resolve, 100);
      });
    }
    gracefulExit();
  } catch (error) {
    if (error instanceof Error && error.message.startsWith("Command not found: ")) {
      const badCommandName = error.message.split(": ")[1];
      const badCommandErr = new CliExitError(`Invalid subcommand: ${badCommandName}`, {
        suggestion: `Run \`${fmt.command("varlock --help", { jsPackageManager: true })}\` for more info.`
      });
      console.error(badCommandErr.getFormattedOutput());
    } else if (error instanceof CliExitError || error instanceof InvalidEnvError) {
      console.error(error.getFormattedOutput());
    } else {
      throw error;
    }
    if (process.platform === "win32") {
      await new Promise((resolve) => {
        setTimeout(resolve, 100);
      });
    }
    gracefulExit(1);
  }
}, "go"))();
//! this ouput is used by homebrew formula to check installed version is correct
/*! Bundled license information:

@gunshi/plugin/lib/index.js:
  (**
  * @author kazuya kawaguchi (a.k.a. kazupon)
  * @license MIT
  *)

@gunshi/plugin-completion/lib/index.js:
  (*! license ISC 
  * @author Bombshell team and Bombshell contributors
  * Bombshell related codes are forked from @bombsh/tab
  *)
  (**
  * @author kazuya kawaguchi (a.k.a. kazupon)
  * @license MIT
  *)
*/
//# sourceMappingURL=cli-executable.js.map
//# sourceMappingURL=cli-executable.js.map