import { detectJsPackageManager } from './chunk-LUQOMV7K.js';
import { asyncExitHook } from './chunk-XQSWW35O.js';
import { define } from './chunk-WAUK6TES.js';
import { getTelemetryUsageContextPayload } from './chunk-XEN5SRUR.js';
import { formatDuration, formatTimeAgo } from './chunk-RZCYQIYU.js';
import { ansis_default, confirm, select } from './chunk-3RZQ5CCT.js';
import { q } from './chunk-7OJKCWSO.js';
import { getCacheEnvKey, createEnvKeyCacheStore } from './chunk-223S32SW.js';
import { groupKeyPrefix, CacheStore } from './chunk-Y2ROUSC3.js';
import { getUserVarlockDir, keyExists } from './chunk-JE2IMKMO.js';
import { createDebug } from './chunk-QGM3LRUO.js';
import { __commonJS, __name, __toESM } from './chunk-IBAHCH6O.js';
import fs5, { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
import path, { join, dirname } from 'path';
import os2 from 'os';
import crypto, { createHash } from 'crypto';
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");
  }
});
var import_ci_info = __toESM(require_ci_info(), 1);
var isDockerCached;
function hasDockerEnv() {
  try {
    fs5.statSync("/.dockerenv");
    return true;
  } catch {
    return false;
  }
}
__name(hasDockerEnv, "hasDockerEnv");
function hasDockerCGroup() {
  try {
    return fs5.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
  } catch {
    return false;
  }
}
__name(hasDockerCGroup, "hasDockerCGroup");
function hasDockerMountInfo() {
  try {
    return fs5.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 {
    fs5.statSync("/.dockerenv");
    return true;
  } catch {
    return false;
  }
}
__name(hasDockerEnv2, "hasDockerEnv");
function hasDockerCGroup2() {
  try {
    return fs5.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 {
    fs5.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 (fs5.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) {
      return !isInsideContainer();
    }
  } catch {
  }
  if (fs5.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs5.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.8.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",
    prepack: "bun run scripts/sync-skill.ts",
    "sync-skill": "bun run scripts/sync-skill.ts",
    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",
    "/skills"
  ],
  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.35.1",
    "@gunshi/plugin-i18n": "^0.35.1",
    "@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.35.1",
    "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_API_URL: 'http://localhost:8888',
  VARLOCK_API_URL: "https://api.varlock.dev",
  GITHUB_APP_CLIENT_ID: "Iv23li50gB8bMxLauiJQ",
  // 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");
function buildProjectSlug(rawHost, rawPath) {
  const host = rawHost.trim().replace(/:\d+$/, "").toLowerCase();
  if (!host) return void 0;
  const path2 = rawPath.trim().replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/, "").toLowerCase();
  if (!path2) return void 0;
  return `${host}/${path2}`;
}
__name(buildProjectSlug, "buildProjectSlug");
function normalizeGitRemoteUrl(rawUrl) {
  const url = rawUrl.trim();
  if (!url) return void 0;
  let host;
  let path2;
  const schemeMatch = url.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(.*)$/);
  if (schemeMatch) {
    let rest = schemeMatch[1];
    const atIdx = rest.indexOf("@");
    const slashIdx = rest.indexOf("/");
    if (atIdx !== -1 && (slashIdx === -1 || atIdx < slashIdx)) {
      rest = rest.slice(atIdx + 1);
    }
    const firstSlash = rest.indexOf("/");
    if (firstSlash === -1) return void 0;
    host = rest.slice(0, firstSlash);
    path2 = rest.slice(firstSlash + 1);
  } else {
    const scpMatch = url.match(/^(?:[^@/]+@)?([^/]+?):(.+)$/);
    if (!scpMatch) return void 0;
    host = scpMatch[1];
    path2 = scpMatch[2];
  }
  return buildProjectSlug(host, path2);
}
__name(normalizeGitRemoteUrl, "normalizeGitRemoteUrl");
function getProjectSlugFromCi(env = process.env) {
  if (env.GITHUB_REPOSITORY) {
    const host = (env.GITHUB_SERVER_URL || "https://github.com").replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
    return buildProjectSlug(host, env.GITHUB_REPOSITORY);
  }
  if (env.CI_PROJECT_PATH && env.CI_SERVER_HOST) {
    return buildProjectSlug(env.CI_SERVER_HOST, env.CI_PROJECT_PATH);
  }
  if (env.BITBUCKET_REPO_FULL_NAME) {
    return buildProjectSlug("bitbucket.org", env.BITBUCKET_REPO_FULL_NAME);
  }
  return void 0;
}
__name(getProjectSlugFromCi, "getProjectSlugFromCi");
var _cachedProjectSlug;
function getNormalizedProjectSlug() {
  if (_cachedProjectSlug !== void 0) return _cachedProjectSlug;
  const ciSlug = getProjectSlugFromCi();
  if (ciSlug) {
    _cachedProjectSlug = ciSlug;
    return _cachedProjectSlug;
  }
  const gitRemoteUrl = getProjectGitRemoteUrl();
  _cachedProjectSlug = gitRemoteUrl && normalizeGitRemoteUrl(gitRemoteUrl) || null;
  return _cachedProjectSlug;
}
__name(getNormalizedProjectSlug, "getNormalizedProjectSlug");
function getAnonymousProjectIdV2() {
  const slug = getNormalizedProjectSlug();
  if (!slug) return null;
  return anonymizeValue(slug);
}
__name(getAnonymousProjectIdV2, "getAnonymousProjectIdV2");
function getAnonymousOrgId() {
  const slug = getNormalizedProjectSlug();
  if (!slug) return null;
  const segments = slug.split("/");
  if (segments.length < 3) return null;
  return anonymizeValue(`${segments[0]}/${segments[1]}`);
}
__name(getAnonymousOrgId, "getAnonymousOrgId");
var KNOWN_PUBLIC_GIT_HOSTS = /* @__PURE__ */ new Set([
  "github.com",
  "gitlab.com",
  "bitbucket.org",
  "dev.azure.com",
  "ssh.dev.azure.com",
  "codeberg.org",
  "gitea.com",
  "git.sr.ht",
  "sourceforge.net"
]);
function bucketGitHost(host) {
  if (!host) return null;
  return KNOWN_PUBLIC_GIT_HOSTS.has(host) ? host : "self-hosted";
}
__name(bucketGitHost, "bucketGitHost");
function getGitHost() {
  const slug = getNormalizedProjectSlug();
  return bucketGitHost(slug ? slug.split("/")[0] : null);
}
__name(getGitHost, "getGitHost");
function getJsPackageManagerForTelemetry() {
  return detectJsPackageManager()?.name ?? null;
}
__name(getJsPackageManagerForTelemetry, "getJsPackageManagerForTelemetry");
var cachedTelemetryMetadata;
function getTelemetryMeta() {
  if (cachedTelemetryMetadata) return cachedTelemetryMetadata;
  const cpus = os2.cpus() || [];
  let versionIdentifier = package_default.version;
  cachedTelemetryMetadata = {
    anonymous_project_id: getAnonymousProjectId(),
    anonymous_project_id_v2: getAnonymousProjectIdV2(),
    anonymous_org_id: getAnonymousOrgId(),
    git_host: getGitHost(),
    node_version: process.version.replace(/^v?/, ""),
    varlock_version: versionIdentifier,
    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,
    js_package_manager: getJsPackageManagerForTelemetry()
  };
  return cachedTelemetryMetadata;
}
__name(getTelemetryMeta, "getTelemetryMeta");
var isOptedOut = checkIsOptedOut();
var lastTelemetryReq;
async function posthogCapture(event, properties) {
  try {
    const telemetryMeta = getTelemetryMeta();
    const usageContext = getTelemetryUsageContextPayload();
    const payload = {
      api_key: CONFIG.POSTHOG_API_KEY,
      event,
      properties: {
        $process_person_profile: false,
        ...telemetryMeta,
        ...usageContext,
        ...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();
    });
  } catch (err) {
    debug("telemetry capture error:", err);
  }
}
__name(posthogCapture, "posthogCapture");
async function trackCommand(command, properties) {
  await posthogCapture("cli_command_executed", {
    command,
    ...properties
  });
}
__name(trackCommand, "trackCommand");

// src/cli/commands/cache.command.ts
function formatResolverSourcePath(sourcePath) {
  const homeDir = process.env.HOME;
  if (homeDir && sourcePath.startsWith(`${homeDir}/`)) {
    return `~/${sourcePath.slice(homeDir.length + 1)}`;
  }
  const relToCwd = path.relative(process.cwd(), sourcePath);
  if (relToCwd && !relToCwd.startsWith("..") && !path.isAbsolute(relToCwd)) {
    return `./${relToCwd}`;
  }
  return sourcePath;
}
__name(formatResolverSourcePath, "formatResolverSourcePath");
function getGroupLabel(prefix) {
  if (prefix.startsWith("plugin:")) {
    return `${ansis_default.magenta(`[${prefix.replace("plugin:", "")}]`)} plugin cache`;
  }
  if (prefix === "resolver:custom") {
    return `${ansis_default.cyan("[resolver:custom]")} explicit keys`;
  }
  if (prefix.startsWith("resolver:")) {
    const sourcePath = prefix.slice("resolver:".length);
    return `${ansis_default.cyan("[resolver]")} ${ansis_default.gray(formatResolverSourcePath(sourcePath))}`;
  }
  return prefix;
}
__name(getGroupLabel, "getGroupLabel");
function formatEntryLabel(entry) {
  const ttlMs = entry.expiresAt - entry.cachedAt;
  const isForever = ttlMs > 50 * 365.25 * 864e5;
  const ttlStr = isForever ? "forever" : formatDuration(ttlMs);
  const agoStr = formatTimeAgo(entry.cachedAt);
  const parts = entry.key.split(":");
  let line1;
  const line2 = ansis_default.gray(`  ttl: ${ttlStr} \xB7 cached ${agoStr}`);
  if (parts[0] === "plugin") {
    const pluginName = parts[1];
    const rest = parts.slice(2).join(":");
    line1 = `${ansis_default.magenta(`[${pluginName}]`)} ${rest}`;
  } else if (parts[0] === "resolver" && parts[1] === "custom") {
    line1 = `${ansis_default.cyan("[custom]")} ${parts.slice(2).join(":")}`;
  } else if (parts[0] === "resolver") {
    const itemKey = parts[2];
    const resolverText = parts.slice(3).join(":");
    line1 = `${ansis_default.cyan(itemKey)} ${ansis_default.gray("=")} ${resolverText}`;
  } else {
    line1 = entry.key;
  }
  return `${line1}
     ${line2}`;
}
__name(formatEntryLabel, "formatEntryLabel");
function groupEntries(entries) {
  const groups = {};
  for (const entry of entries) {
    const prefix = groupKeyPrefix(entry.key);
    groups[prefix] ??= [];
    groups[prefix].push(entry);
  }
  return groups;
}
__name(groupEntries, "groupEntries");
function printStatus(store) {
  const stats = store.getStats();
  const filePath = store.getFilePath();
  const fileSize = fs5.existsSync(filePath) ? fs5.statSync(filePath).size : 0;
  const sizeStr = fileSize < 1024 ? `${fileSize} B` : `${(fileSize / 1024).toFixed(1)} KB`;
  console.log(`
  ${ansis_default.bold("Varlock cache")}`);
  console.log(`  Location:     ${ansis_default.gray(filePath)}`);
  console.log(`  File size:    ${sizeStr}`);
  console.log(`  Total entries: ${stats.total}${stats.expired ? ansis_default.gray(` (${stats.expired} expired)`) : ""}`);
  if (Object.keys(stats.byPrefix).length > 0) {
    console.log("  By group:");
    for (const [prefix, count] of Object.entries(stats.byPrefix)) {
      console.log(`    ${prefix.padEnd(30)} ${count}`);
    }
  }
  console.log("");
}
__name(printStatus, "printStatus");
var isInteractive = /* @__PURE__ */ __name(() => process.stdout.isTTY && process.stdin.isTTY, "isInteractive");
function resolveStore() {
  const envKey = getCacheEnvKey();
  if (envKey) {
    try {
      return createEnvKeyCacheStore(envKey);
    } catch (err) {
      console.error(ansis_default.red(`_VARLOCK_CACHE_KEY is set but invalid: ${err instanceof Error ? err.message : err}`));
      process.exitCode = 1;
      return null;
    }
  }
  if (!keyExists()) {
    console.log(ansis_default.gray("  No encryption key found \u2014 cache is not active."));
    return null;
  }
  return new CacheStore();
}
__name(resolveStore, "resolveStore");
var statusCommand = define({
  name: "status",
  description: "Print a cache status summary (non-interactive)",
  run: /* @__PURE__ */ __name(async () => {
    await trackCommand("cache status", { command: "cache status" });
    const store = resolveStore();
    if (!store) return;
    printStatus(store);
  }, "run")
});
var clearCommand = define({
  name: "clear",
  description: "Clear cache entries",
  args: {
    plugin: {
      type: "string",
      description: "Clear cache for a specific plugin only"
    },
    yes: {
      type: "boolean",
      short: "y",
      description: "Skip confirmation prompts (required when non-interactive)"
    }
  },
  examples: `
  varlock cache clear --yes                       # Clear all entries (no prompt)
  varlock cache clear --plugin 1password --yes    # Clear cache for a specific plugin
`.trim(),
  run: /* @__PURE__ */ __name(async (ctx) => {
    await trackCommand("cache clear", { command: "cache clear" });
    const store = resolveStore();
    if (!store) return;
    const pluginName = ctx.values.plugin;
    const skipConfirm = ctx.values.yes;
    const target = pluginName ? `cache entries for plugin "${pluginName}"` : "cache entries";
    if (!skipConfirm) {
      if (!isInteractive()) {
        console.error(ansis_default.red(`Refusing to clear ${target} without confirmation.`));
        console.error("  Re-run with --yes to confirm, or run interactively.");
        process.exitCode = 1;
        return;
      }
      const confirmed = await confirm({
        message: `Clear all ${target}? This cannot be undone.`,
        initialValue: false
      });
      if (q(confirmed) || !confirmed) {
        console.log(ansis_default.gray("  Aborted."));
        return;
      }
    }
    try {
      const count = pluginName ? await store.clearByPrefix(`plugin:${pluginName}:`) : await store.clearAll();
      console.log(`  Cleared ${count} ${target}`);
    } catch (err) {
      console.error(ansis_default.red(`Failed to clear ${target}: ${err instanceof Error ? err.message : err}`));
      process.exitCode = 1;
    }
  }, "run")
});
var commandSpec = define({
  name: "cache",
  description: "Manage the varlock cache",
  subCommands: {
    status: statusCommand,
    clear: clearCommand
  },
  examples: `
Manage the encrypted value cache used by cache() and plugin authors.

Examples:
  varlock cache                                   # Interactive cache browser (or status summary if non-TTY)
  varlock cache status                            # Print cache status summary (non-interactive)
  varlock cache clear --yes                       # Clear all entries (no prompt)
  varlock cache clear --plugin 1password --yes    # Clear cache for a specific plugin
`.trim()
});
var commandFn = /* @__PURE__ */ __name(async () => {
  const store = resolveStore();
  if (!store) return;
  if (!isInteractive()) {
    printStatus(store);
    return;
  }
  while (true) {
    const entries = store.listEntries();
    if (entries.length === 0) {
      console.log(ansis_default.gray("\n  Cache is empty.\n"));
      return;
    }
    const groups = groupEntries(entries);
    const filePath = store.getFilePath();
    const fileSize = fs5.existsSync(filePath) ? fs5.statSync(filePath).size : 0;
    const sizeStr = fileSize < 1024 ? `${fileSize}B` : `${(fileSize / 1024).toFixed(1)}KB`;
    console.log(`
  ${ansis_default.bold(`${entries.length} cached entries`)} ${ansis_default.gray(`(${sizeStr})`)}`);
    const options = [];
    for (const [prefix, items] of Object.entries(groups)) {
      const label = getGroupLabel(prefix);
      options.push({
        value: `group:${prefix}`,
        label: `${label} ${ansis_default.gray(`(${items.length} entries)`)}`
      });
    }
    options.push({ value: "__clear_all__", label: ansis_default.red(`Clear all ${entries.length} entries`) });
    options.push({ value: "__exit__", label: ansis_default.gray("Exit") });
    const selected = await select({
      message: "Select a group to browse or an action:",
      options
    });
    if (q(selected) || selected === "__exit__") return;
    if (selected === "__clear_all__") {
      const confirmed = await confirm({
        message: `Clear all ${entries.length} cache entries?`,
        initialValue: false
      });
      if (q(confirmed) || !confirmed) continue;
      const count = await store.clearAll();
      console.log(`  Cleared ${count} entries`);
      return;
    }
    if (typeof selected === "string" && selected.startsWith("group:")) {
      const prefix = selected.replace("group:", "");
      const groupLabel = getGroupLabel(prefix);
      while (true) {
        const current = store.listEntries().filter((e) => groupKeyPrefix(e.key) === prefix);
        if (current.length === 0) {
          console.log(ansis_default.gray("  No entries remaining in this group."));
          break;
        }
        const entryOptions = [
          ...current.map((entry) => ({
            value: entry.key,
            label: formatEntryLabel(entry)
          })),
          { value: "__clear_group__", label: ansis_default.red(`Clear all ${current.length} entries`) },
          { value: "__back__", label: ansis_default.gray("\u2190 Back") }
        ];
        const entrySelected = await select({
          message: `${groupLabel} \u2014 ${current.length} entries:`,
          options: entryOptions
        });
        if (q(entrySelected) || entrySelected === "__back__") break;
        if (entrySelected === "__clear_group__") {
          const confirmed2 = await confirm({
            message: `Clear all ${current.length} entries in "${prefix}"?`,
            initialValue: false
          });
          if (q(confirmed2) || !confirmed2) continue;
          await store.clearByPrefix(`${prefix}:`);
          console.log(ansis_default.gray(`  Cleared ${current.length} entries`));
          break;
        }
        const confirmed = await confirm({
          message: `Delete "${entrySelected}"?`,
          initialValue: true
        });
        if (q(confirmed) || !confirmed) continue;
        await store.delete(entrySelected);
        console.log(ansis_default.gray("  Deleted"));
      }
    }
  }
}, "commandFn");

export { commandFn, commandSpec, package_default, trackCommand };
//# sourceMappingURL=chunk-M4UHPNUC.js.map
//# sourceMappingURL=chunk-M4UHPNUC.js.map