import { gracefulExit } from './chunk-XQSWW35O.js';
import { define } from './chunk-WIL4LMMA.js';
import { checkForSchemaErrors, checkForNoEnvFiles } from './chunk-4MCNC4YY.js';
import { loadVarlockEnvGraph } from './chunk-5SI4EGRL.js';
import { CliExitError } from './chunk-7M6WZ65V.js';
import { ansis_default, select } from './chunk-LTYLEVHC.js';
import { q } from './chunk-7OJKCWSO.js';
import { redactString } from './chunk-UWUBFNLX.js';
import { __name } from './chunk-IBAHCH6O.js';

// src/cli/commands/reveal.command.ts
var commandSpec = define({
  name: "reveal",
  description: "Securely view decrypted values of sensitive environment variables",
  args: {
    copy: {
      type: "boolean",
      description: "Copy the value to clipboard instead of displaying (auto-clears after 10s)"
    },
    path: {
      type: "string",
      short: "p",
      multiple: true,
      description: "Path to a specific .env file or directory to use as the entry point (can be specified multiple times)"
    },
    env: {
      type: "string",
      description: "Set the environment (e.g., production, development, etc)"
    }
  },
  examples: `
Securely view the plaintext value of sensitive environment variables.
Values are shown in an alternate screen buffer so they don't persist in
terminal scrollback history.

Examples:
  varlock reveal                  # Interactive picker to select and reveal values
  varlock reveal MY_SECRET        # Reveal a specific variable
  varlock reveal MY_SECRET --copy # Copy value to clipboard (auto-clears after 10s)
`.trim()
});
var CLIPBOARD_CLEAR_DELAY_MS = 1e4;
async function copyToClipboard(text) {
  const { execSync } = await import('child_process');
  const platform = process.platform;
  if (platform === "darwin") {
    execSync("pbcopy", { input: text });
  } else if (platform === "linux") {
    try {
      execSync("xclip -selection clipboard", { input: text });
    } catch {
      execSync("xsel --clipboard --input", { input: text });
    }
  } else if (platform === "win32") {
    execSync("clip", { input: text });
  } else {
    throw new CliExitError("Clipboard not supported on this platform");
  }
}
__name(copyToClipboard, "copyToClipboard");
async function clearClipboard() {
  const { execSync } = await import('child_process');
  const platform = process.platform;
  try {
    if (platform === "darwin") {
      execSync("pbcopy", { input: "" });
    } else if (platform === "linux") {
      try {
        execSync("xclip -selection clipboard", { input: "" });
      } catch {
        execSync("xsel --clipboard --input", { input: "" });
      }
    } else if (platform === "win32") {
      execSync("echo. | clip", { shell: "cmd.exe" });
    }
  } catch {
  }
}
__name(clearClipboard, "clearClipboard");
function enterAltScreen() {
  process.stdout.write("\x1B[?1049h");
  process.stdout.write("\x1B[H");
}
__name(enterAltScreen, "enterAltScreen");
function exitAltScreen() {
  process.stdout.write("\x1B[?1049l");
}
__name(exitAltScreen, "exitAltScreen");
async function waitForKeypress() {
  return new Promise((resolve) => {
    const wasRaw = process.stdin.isRaw;
    if (process.stdin.isTTY) process.stdin.setRawMode(true);
    process.stdin.resume();
    process.stdin.once("data", (data) => {
      if (process.stdin.isTTY) process.stdin.setRawMode(wasRaw);
      process.stdin.pause();
      resolve(data.toString());
    });
  });
}
__name(waitForKeypress, "waitForKeypress");
function displayRevealedValue(item) {
  enterAltScreen();
  const value = item.resolvedValue;
  const valStr = value === void 0 || value === null ? ansis_default.gray("(empty)") : String(value);
  console.log("");
  console.log(ansis_default.bold.cyan(`  ${item.key}`));
  if (item.description) {
    console.log(ansis_default.gray(`  ${item.description}`));
  }
  console.log("");
  console.log(`  ${valStr}`);
  console.log("");
  console.log(ansis_default.gray("  Press any key to hide..."));
}
__name(displayRevealedValue, "displayRevealedValue");
var commandFn = /* @__PURE__ */ __name(async (ctx) => {
  const { copy: copyMode } = ctx.values;
  const envGraph = await loadVarlockEnvGraph({
    currentEnvFallback: ctx.values.env,
    entryFilePaths: ctx.values.path
  });
  checkForSchemaErrors(envGraph);
  checkForNoEnvFiles(envGraph);
  await envGraph.resolveEnvValues();
  const sensitiveItems = [];
  for (const itemKey of envGraph.sortedConfigKeys) {
    const item = envGraph.configSchema[itemKey];
    if (item.isSensitive && item.resolvedValue !== void 0) {
      sensitiveItems.push(item);
    }
  }
  if (sensitiveItems.length === 0) {
    console.log("No sensitive values found to reveal.");
    return;
  }
  const positionals = (ctx.positionals ?? []).slice(ctx.commandPath?.length ?? 0);
  const requestedVar = positionals[0];
  if (requestedVar) {
    const item = sensitiveItems.find((i) => i.key === requestedVar);
    if (!item) {
      if (requestedVar in envGraph.configSchema) {
        throw new CliExitError(`"${requestedVar}" is not marked as sensitive`, {
          suggestion: "Use `varlock printenv` for non-sensitive values."
        });
      }
      throw new CliExitError(`Variable "${requestedVar}" not found in schema`);
    }
    if (copyMode) {
      await copyToClipboard(String(item.resolvedValue ?? ""));
      console.log(`
  Copied ${ansis_default.cyan(item.key)} to clipboard.`);
      console.log(ansis_default.gray(`  Clipboard will be cleared in ${CLIPBOARD_CLEAR_DELAY_MS / 1e3}s.
`));
      setTimeout(async () => {
        await clearClipboard();
        console.log(ansis_default.gray("  Clipboard cleared."));
        gracefulExit();
      }, CLIPBOARD_CLEAR_DELAY_MS);
      return;
    }
    displayRevealedValue(item);
    await waitForKeypress();
    exitAltScreen();
    return;
  }
  while (true) {
    const selected = await select({
      message: `Select a variable to reveal ${ansis_default.gray("(use arrows, enter to select)")}`,
      options: sensitiveItems.map((item2) => ({
        value: item2.key,
        label: item2.key,
        hint: redactString(String(item2.resolvedValue ?? "")) ?? void 0
      }))
    });
    if (q(selected)) return gracefulExit();
    const item = sensitiveItems.find((i) => i.key === selected);
    if (copyMode) {
      await copyToClipboard(String(item.resolvedValue ?? ""));
      console.log(`
  Copied ${ansis_default.cyan(item.key)} to clipboard.`);
      console.log(ansis_default.gray(`  Clipboard will be cleared in ${CLIPBOARD_CLEAR_DELAY_MS / 1e3}s.
`));
      setTimeout(async () => {
        await clearClipboard();
        console.log(ansis_default.gray("  Clipboard cleared."));
        gracefulExit();
      }, CLIPBOARD_CLEAR_DELAY_MS);
      return;
    }
    displayRevealedValue(item);
    await waitForKeypress();
    exitAltScreen();
  }
}, "commandFn");

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