"use strict";
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const events = require("./fetch-virtual-server-J6SUa9HS.cjs");
const INFISICAL_CONFIG_DIR = "/home/user/.infisical";
const INFISICAL_CONFIG_PATH = `${INFISICAL_CONFIG_DIR}/infisical-config.json`;
const INFISICAL_AUTH_PATH = `${INFISICAL_CONFIG_DIR}/auth.json`;
const INFISICAL_WORKSPACE_FILE_NAME = ".infisical.json";
const DEFAULT_INFISICAL_DOMAIN = "https://app.infisical.com";
const INFISICAL_STORAGE_VERSION = 2;
const INFISICAL_EXPIRY_BUFFER_MS = 3e4;
function isRecord(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function ensureParentDir(vfs, filePath) {
  const parent = events.dirname(filePath);
  if (!vfs.existsSync(parent)) {
    vfs.mkdirSync(parent, { recursive: true });
  }
}
function readJsonFile(vfs, filePath) {
  if (!vfs.existsSync(filePath)) {
    return null;
  }
  try {
    const raw = vfs.readFileSync(filePath, "utf8");
    const parsed = JSON.parse(raw);
    return isRecord(parsed) ? parsed : {};
  } catch {
    return null;
  }
}
function writeJsonFile(vfs, filePath, value) {
  ensureParentDir(vfs, filePath);
  vfs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}
`);
}
function coerceString$1(value) {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}
function coerceStringRecord(value) {
  if (!isRecord(value)) {
    return null;
  }
  const next = {};
  for (const [key, entry] of Object.entries(value)) {
    const normalizedKey = key.trim();
    const normalizedValue = coerceString$1(entry);
    if (!normalizedKey || !normalizedValue) {
      continue;
    }
    next[normalizedKey] = normalizedValue;
  }
  return Object.keys(next).length > 0 ? next : null;
}
function normalizeVaultBackend(value) {
  return value === "file" ? "file" : "auto";
}
function normalizeIsoTimestamp(value) {
  if (typeof value !== "string" || !value.trim()) {
    return null;
  }
  const timestamp = Date.parse(value);
  if (!Number.isFinite(timestamp)) {
    return null;
  }
  return new Date(timestamp).toISOString();
}
function parseJwtTimestamp(token, claim) {
  if (!token) {
    return null;
  }
  const parts = token.split(".");
  if (parts.length < 2 || !parts[1]) {
    return null;
  }
  try {
    const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(parts[1].length / 4) * 4, "=");
    const decoded = typeof Buffer !== "undefined" ? Buffer.from(base64, "base64").toString("utf8") : atob(base64);
    const parsed = JSON.parse(decoded);
    const value = parsed[claim];
    if (typeof value !== "number" || !Number.isFinite(value)) {
      return null;
    }
    return new Date(value * 1e3).toISOString();
  } catch {
    return null;
  }
}
function normalizeInfisicalDomain(value) {
  const raw = typeof value === "string" && value.trim() ? value.trim() : DEFAULT_INFISICAL_DOMAIN;
  const withoutTrailingSlash = raw.replace(/\/+$/g, "");
  const withoutApiSuffix = withoutTrailingSlash.replace(/\/api$/i, "");
  let parsed;
  try {
    parsed = new URL(withoutApiSuffix);
  } catch {
    return DEFAULT_INFISICAL_DOMAIN;
  }
  if (!/^https?:$/.test(parsed.protocol)) {
    return DEFAULT_INFISICAL_DOMAIN;
  }
  parsed.pathname = parsed.pathname.replace(/\/+$/g, "") || "";
  parsed.search = "";
  parsed.hash = "";
  return parsed.toString().replace(/\/+$/g, "");
}
function normalizeDomains(raw, domain) {
  const values = Array.isArray(raw) ? raw.map((entry) => normalizeInfisicalDomain(entry)).filter(Boolean) : [];
  if (!values.includes(domain)) {
    values.push(domain);
  }
  return Array.from(new Set(values));
}
function normalizeMachineIdentity(value) {
  if (!isRecord(value)) {
    return null;
  }
  const method = value.method === "universal-auth" ? "universal-auth" : "universal-auth";
  const clientId = coerceString$1(value.clientId);
  const clientSecret = coerceString$1(value.clientSecret);
  const organizationSlug = coerceString$1(value.organizationSlug);
  if (!clientId && !clientSecret && !organizationSlug) {
    return null;
  }
  return {
    method,
    clientId,
    clientSecret,
    organizationSlug
  };
}
function readInfisicalConfig(vfs) {
  const raw = readJsonFile(vfs, INFISICAL_CONFIG_PATH) ?? {};
  const domain = normalizeInfisicalDomain(raw.domain);
  return {
    version: INFISICAL_STORAGE_VERSION,
    domain,
    domains: normalizeDomains(raw.domains, domain),
    loggedInUserEmail: coerceString$1(raw.loggedInUserEmail),
    machineIdentity: normalizeMachineIdentity(raw.machineIdentity),
    path: INFISICAL_CONFIG_PATH,
    raw,
    vaultBackendType: normalizeVaultBackend(raw.vaultBackendType)
  };
}
function writeInfisicalConfig(vfs, config) {
  var _a, _b, _c;
  const domain = normalizeInfisicalDomain(config.domain);
  const raw = isRecord(config.raw) ? { ...config.raw } : {};
  raw.version = INFISICAL_STORAGE_VERSION;
  raw.domain = domain;
  raw.domains = normalizeDomains(config.domains, domain);
  raw.vaultBackendType = normalizeVaultBackend(config.vaultBackendType);
  if (config.loggedInUserEmail) {
    raw.loggedInUserEmail = config.loggedInUserEmail;
    raw.LoggedInUserDomain = domain;
    raw.loggedInUsers = [{
      email: config.loggedInUserEmail,
      domain
    }];
  } else {
    delete raw.loggedInUserEmail;
    delete raw.LoggedInUserDomain;
    delete raw.loggedInUsers;
  }
  if (((_a = config.machineIdentity) == null ? void 0 : _a.clientId) || ((_b = config.machineIdentity) == null ? void 0 : _b.clientSecret) || ((_c = config.machineIdentity) == null ? void 0 : _c.organizationSlug)) {
    raw.machineIdentity = {
      method: "universal-auth",
      clientId: config.machineIdentity.clientId || "",
      clientSecret: config.machineIdentity.clientSecret || "",
      organizationSlug: config.machineIdentity.organizationSlug || void 0
    };
  } else {
    delete raw.machineIdentity;
  }
  writeJsonFile(vfs, INFISICAL_CONFIG_PATH, raw);
}
function readInfisicalAuth(vfs) {
  const raw = readJsonFile(vfs, INFISICAL_AUTH_PATH) ?? {};
  const accessToken = coerceString$1(raw.accessToken);
  const refreshToken = coerceString$1(raw.refreshToken) || coerceString$1(raw.RefreshToken);
  const privateKey = coerceString$1(raw.privateKey);
  const email = coerceString$1(raw.email);
  const method = raw.method === "universal-auth" ? "universal-auth" : raw.method === "user" ? "user" : email || privateKey || refreshToken ? "user" : null;
  return {
    version: INFISICAL_STORAGE_VERSION,
    accessToken,
    email,
    refreshToken,
    privateKey,
    tokenType: coerceString$1(raw.tokenType),
    expiresAt: normalizeIsoTimestamp(raw.expiresAt) || parseJwtTimestamp(accessToken, "exp"),
    issuedAt: normalizeIsoTimestamp(raw.issuedAt) || parseJwtTimestamp(accessToken, "iat"),
    domain: normalizeInfisicalDomain(raw.domain),
    method,
    clientId: coerceString$1(raw.clientId),
    organizationSlug: coerceString$1(raw.organizationSlug)
  };
}
function writeInfisicalAuth(vfs, auth) {
  const expiresAt = normalizeIsoTimestamp(auth.expiresAt) || parseJwtTimestamp(auth.accessToken, "exp");
  const issuedAt = normalizeIsoTimestamp(auth.issuedAt) || parseJwtTimestamp(auth.accessToken, "iat") || (/* @__PURE__ */ new Date()).toISOString();
  const payload = {
    version: INFISICAL_STORAGE_VERSION,
    accessToken: auth.accessToken || "",
    email: auth.email || "",
    refreshToken: auth.refreshToken || "",
    privateKey: auth.privateKey || "",
    tokenType: auth.tokenType || "Bearer",
    expiresAt,
    issuedAt,
    domain: normalizeInfisicalDomain(auth.domain),
    method: auth.method || "user",
    clientId: auth.clientId || ""
  };
  if (auth.organizationSlug) {
    payload.organizationSlug = auth.organizationSlug;
  }
  writeJsonFile(vfs, INFISICAL_AUTH_PATH, payload);
}
function deleteInfisicalAuth(vfs) {
  if (!vfs.existsSync(INFISICAL_AUTH_PATH)) {
    return false;
  }
  try {
    vfs.unlinkSync(INFISICAL_AUTH_PATH);
  } catch {
  }
  return true;
}
function isInfisicalAccessTokenValid(auth, now = Date.now()) {
  if (!auth.accessToken) {
    return false;
  }
  const expiresAt = Date.parse(auth.expiresAt || parseJwtTimestamp(auth.accessToken, "exp") || "");
  if (!Number.isFinite(expiresAt)) {
    return false;
  }
  return expiresAt > now + INFISICAL_EXPIRY_BUFFER_MS;
}
function findWorkspaceConfigPath(vfs, cwd) {
  let current = events.resolve(cwd);
  while (true) {
    const candidate = events.join(current, INFISICAL_WORKSPACE_FILE_NAME);
    if (vfs.existsSync(candidate)) {
      return candidate;
    }
    if (current === "/") {
      return null;
    }
    current = events.dirname(current);
  }
}
function readInfisicalWorkspaceConfig(vfs, cwd) {
  const filePath = findWorkspaceConfigPath(vfs, cwd);
  if (!filePath) {
    return null;
  }
  const raw = readJsonFile(vfs, filePath) ?? {};
  return {
    defaultEnvironment: coerceString$1(raw.defaultEnvironment),
    gitBranchToEnvironmentMapping: coerceStringRecord(raw.gitBranchToEnvironmentMapping),
    path: filePath,
    raw,
    workspaceId: coerceString$1(raw.workspaceId)
  };
}
function writeInfisicalWorkspaceConfig(vfs, cwd, config) {
  var _a;
  const filePath = events.join(events.resolve(cwd), INFISICAL_WORKSPACE_FILE_NAME);
  const payload = {
    workspaceId: config.workspaceId.trim()
  };
  if ((_a = config.defaultEnvironment) == null ? void 0 : _a.trim()) {
    payload.defaultEnvironment = config.defaultEnvironment.trim();
  }
  if (config.gitBranchToEnvironmentMapping && Object.keys(config.gitBranchToEnvironmentMapping).length > 0) {
    payload.gitBranchToEnvironmentMapping = config.gitBranchToEnvironmentMapping;
  }
  writeJsonFile(vfs, filePath, payload);
  return filePath;
}
const ANSI_CURSOR_HIDE = "\x1B[?25l";
const ANSI_CURSOR_SHOW = "\x1B[?25h";
const ANSI_CLEAR_LINE = "\x1B[2K";
const ANSI_LINE_UP = "\x1B[A";
const ANSI_BOLD$1 = "\x1B[1m";
const ANSI_CYAN = "\x1B[36m";
const ANSI_DIM = "\x1B[2m";
const ANSI_RESET$1 = "\x1B[0m";
class PromptAbortError extends Error {
  constructor() {
    super("prompt aborted");
    this.name = "PromptAbortError";
  }
}
function writeErr(ctx, data) {
  ctx.writeStderr(data);
}
function isAborted(ctx) {
  var _a;
  return ((_a = ctx.signal) == null ? void 0 : _a.aborted) === true;
}
function renderSelect(ctx, label, items, activeIndex, isFirstRender) {
  if (!isFirstRender) {
    let erase = "";
    for (let i = 0; i < items.length + 1; i += 1) {
      erase += `${ANSI_CLEAR_LINE}\r${i === items.length ? "" : ANSI_LINE_UP}`;
    }
    writeErr(ctx, erase);
  }
  writeErr(ctx, `${ANSI_BOLD$1}? ${label}:${ANSI_RESET$1} ${ANSI_DIM}[Use arrows to move, enter to select]${ANSI_RESET$1}\r
`);
  items.forEach((item, index) => {
    const isActive = index === activeIndex;
    const marker = isActive ? `${ANSI_CYAN}▸${ANSI_RESET$1}` : " ";
    const text = isActive ? `${ANSI_CYAN}${item.label}${ANSI_RESET$1}` : item.label;
    const suffix = index === items.length - 1 ? "" : "\r\n";
    writeErr(ctx, `${marker} ${text}${suffix}`);
  });
}
async function selectPrompt(opts) {
  const { ctx, label, items } = opts;
  if (items.length === 0) {
    throw new Error("selectPrompt: items must not be empty");
  }
  if (!ctx.onKeypress) {
    throw new Error("selectPrompt: shell context does not provide keypress input");
  }
  let activeIndex = Math.min(
    Math.max(opts.defaultIndex ?? 0, 0),
    items.length - 1
  );
  writeErr(ctx, ANSI_CURSOR_HIDE);
  renderSelect(ctx, label, items, activeIndex, true);
  return new Promise((resolve, reject) => {
    let unsubscribe = null;
    let abortHandler = null;
    const cleanup = () => {
      unsubscribe == null ? void 0 : unsubscribe();
      unsubscribe = null;
      if (abortHandler && ctx.signal) {
        ctx.signal.removeEventListener("abort", abortHandler);
        abortHandler = null;
      }
      writeErr(ctx, ANSI_CURSOR_SHOW);
    };
    const finish = (value) => {
      var _a;
      cleanup();
      let erase = "";
      for (let i = 0; i < items.length + 1; i += 1) {
        erase += `${ANSI_CLEAR_LINE}\r${i === items.length ? "" : ANSI_LINE_UP}`;
      }
      writeErr(ctx, erase);
      const chosen = ((_a = items.find((item) => item.value === value)) == null ? void 0 : _a.label) ?? "";
      writeErr(ctx, `${ANSI_BOLD$1}? ${label}:${ANSI_RESET$1} ${ANSI_CYAN}${chosen}${ANSI_RESET$1}\r
`);
      resolve(value);
    };
    const abort = () => {
      cleanup();
      reject(new PromptAbortError());
    };
    if (isAborted(ctx)) {
      abort();
      return;
    }
    if (ctx.signal) {
      abortHandler = abort;
      ctx.signal.addEventListener("abort", abortHandler, { once: true });
    }
    unsubscribe = ctx.onKeypress((ch, key) => {
      if (key.ctrl && (key.name === "c" || ch === "")) {
        abort();
        return;
      }
      if (key.name === "up" || key.name === "k") {
        activeIndex = (activeIndex - 1 + items.length) % items.length;
        renderSelect(ctx, label, items, activeIndex, false);
        return;
      }
      if (key.name === "down" || key.name === "j") {
        activeIndex = (activeIndex + 1) % items.length;
        renderSelect(ctx, label, items, activeIndex, false);
        return;
      }
      if (key.name === "return" || key.name === "enter" || ch === "\r" || ch === "\n") {
        finish(items[activeIndex].value);
      }
    });
  });
}
async function textPrompt(opts) {
  const { ctx, label, defaultValue } = opts;
  if (!ctx.onKeypress) {
    throw new Error("textPrompt: shell context does not provide keypress input");
  }
  const hint = defaultValue ? ` ${ANSI_DIM}(${defaultValue})${ANSI_RESET$1}` : "";
  writeErr(ctx, `${ANSI_BOLD$1}? ${label}:${ANSI_RESET$1}${hint} `);
  return new Promise((resolve, reject) => {
    let unsubscribe = null;
    let abortHandler = null;
    let buffer = "";
    const cleanup = () => {
      unsubscribe == null ? void 0 : unsubscribe();
      unsubscribe = null;
      if (abortHandler && ctx.signal) {
        ctx.signal.removeEventListener("abort", abortHandler);
        abortHandler = null;
      }
    };
    const finish = () => {
      cleanup();
      writeErr(ctx, "\r\n");
      resolve(buffer || defaultValue || "");
    };
    const abort = () => {
      cleanup();
      writeErr(ctx, "\r\n");
      reject(new PromptAbortError());
    };
    if (isAborted(ctx)) {
      abort();
      return;
    }
    if (ctx.signal) {
      abortHandler = abort;
      ctx.signal.addEventListener("abort", abortHandler, { once: true });
    }
    unsubscribe = ctx.onKeypress((ch, key) => {
      if (key.ctrl && (key.name === "c" || ch === "")) {
        abort();
        return;
      }
      if (key.name === "return" || key.name === "enter" || ch === "\r" || ch === "\n") {
        finish();
        return;
      }
      if (key.name === "backspace" || ch === "" || ch === "\b") {
        if (buffer.length > 0) {
          buffer = buffer.slice(0, -1);
          writeErr(ctx, "\b \b");
        }
        return;
      }
      if (ch && ch >= " ") {
        buffer += ch;
        writeErr(ctx, ch);
      }
    });
  });
}
async function hiddenPrompt(opts) {
  const { ctx, label, mask } = opts;
  if (!ctx.onKeypress) {
    throw new Error("hiddenPrompt: shell context does not provide keypress input");
  }
  writeErr(ctx, label);
  return new Promise((resolve, reject) => {
    let unsubscribe = null;
    let abortHandler = null;
    let buffer = "";
    const cleanup = () => {
      unsubscribe == null ? void 0 : unsubscribe();
      unsubscribe = null;
      if (abortHandler && ctx.signal) {
        ctx.signal.removeEventListener("abort", abortHandler);
        abortHandler = null;
      }
    };
    const finish = () => {
      cleanup();
      writeErr(ctx, "\r\n");
      resolve(buffer);
    };
    const abort = () => {
      cleanup();
      writeErr(ctx, "\r\n");
      reject(new PromptAbortError());
    };
    if (isAborted(ctx)) {
      abort();
      return;
    }
    if (ctx.signal) {
      abortHandler = abort;
      ctx.signal.addEventListener("abort", abortHandler, { once: true });
    }
    unsubscribe = ctx.onKeypress((ch, key) => {
      if (key.ctrl && (key.name === "c" || ch === "")) {
        abort();
        return;
      }
      if (key.name === "return" || key.name === "enter" || ch === "\r" || ch === "\n") {
        finish();
        return;
      }
      if (key.name === "backspace" || ch === "" || ch === "\b") {
        if (buffer.length > 0) {
          buffer = buffer.slice(0, -1);
          if (mask) {
            writeErr(ctx, "\b \b");
          }
        }
        return;
      }
      if (ch && ch >= " ") {
        buffer += ch;
        if (mask) {
          writeErr(ctx, "*");
        }
      }
    });
  });
}
const ttyPrompt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  PromptAbortError,
  hiddenPrompt,
  selectPrompt,
  textPrompt
}, Symbol.toStringTag, { value: "Module" }));
const INFISICAL_INIT_DEFAULT_ENV = "dev";
const INFISICAL_DESKTOP_AUTH_TIMEOUT_MS = 18e4;
const DESKTOP_OAUTH_LOOPBACK_BRIDGE_KEY = Symbol.for(
  "almostnode.desktopOAuthLoopback"
);
const DESKTOP_INFISICAL_SUCCESS_HTML = `<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Infisical authentication complete</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      body {
        margin: 0;
        min-height: 100vh;
        display: grid;
        place-items: center;
        background: #0f172a;
        color: #e2e8f0;
        font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      }
      main {
        max-width: 32rem;
        padding: 2rem;
        text-align: center;
      }
      h1 {
        margin: 0 0 0.75rem;
        font-size: 1.5rem;
      }
      p {
        margin: 0;
        color: #cbd5e1;
      }
    </style>
  </head>
  <body>
    <main>
      <h1>Infisical authentication complete</h1>
      <p>You can close this window and return to almostnode.</p>
    </main>
  </body>
</html>`;
class InfisicalApiError extends Error {
  constructor(status, message) {
    super(message);
    __publicField(this, "status");
    this.name = "InfisicalApiError";
    this.status = status;
  }
}
function ok(stdout) {
  return { stdout, stderr: "", exitCode: 0 };
}
function err(stderr, exitCode = 1) {
  return { stdout: "", stderr, exitCode };
}
function envToRecord(env) {
  if (!env) {
    return {};
  }
  if (env instanceof Map) {
    return Object.fromEntries(env);
  }
  return env;
}
function formatErrorMessage(error) {
  return error instanceof Error ? error.message : String(error);
}
function formatDateTime(value) {
  if (!value) {
    return null;
  }
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return null;
  }
  return parsed.toLocaleString();
}
function maskIdentifier(value) {
  if (!value) {
    return null;
  }
  if (value.length <= 8) {
    return value;
  }
  return `${value.slice(0, 4)}…${value.slice(-4)}`;
}
function coerceString(value) {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}
function signalAborted(signal) {
  return (signal == null ? void 0 : signal.aborted) === true;
}
function abortResult() {
  return err("infisical: command aborted\n", 130);
}
function normalizeSecretPath(value) {
  const trimmed = (value == null ? void 0 : value.trim()) || "/";
  const normalized = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
  const collapsed = normalized.replace(/\/+/g, "/");
  if (collapsed === "/") {
    return "/";
  }
  return collapsed.replace(/\/+$/g, "") || "/";
}
function parseBooleanFlagValue(value) {
  const normalized = value.trim().toLowerCase();
  if (normalized === "true" || normalized === "1" || normalized === "yes") {
    return true;
  }
  if (normalized === "false" || normalized === "0" || normalized === "no") {
    return false;
  }
  return null;
}
function getDesktopOAuthLoopbackBridge() {
  const candidate = globalThis[DESKTOP_OAUTH_LOOPBACK_BRIDGE_KEY];
  if (!candidate) {
    return null;
  }
  if (typeof candidate.createSession !== "function" || typeof candidate.openExternal !== "function" || typeof candidate.waitForCallback !== "function") {
    return null;
  }
  return candidate;
}
async function persistKeychainState(keychain) {
  await (keychain == null ? void 0 : keychain.persistCurrentState().catch(() => {
  }));
}
function buildHelpText() {
  return "infisical - Infisical browser auth and secrets integration for almostnode\n\nCommands:\n  login                        Start Infisical browser login (default user flow)\n  logout                       Remove the saved Infisical session\n  status                       Show current Infisical authentication status\n  whoami                       Print the current Infisical identity when available\n  init                         Link the current workspace to an Infisical project\n  secrets                      List secrets for the linked project or --projectId\n  secrets get <name...>        Read one or more secrets\n  secrets set <KEY=value...>   Create or update one or more secrets\n  secrets delete <name...>     Delete one or more secrets\n  auth token                   Print the current access token\n  auth status                  Alias for `infisical status`\n  auth whoami                  Alias for `infisical whoami`\n  vault                        Show the configured local vault mode\n  vault set <auto|file>        Update the local vault preference\n\nNotes:\n  `infisical login` follows Infisical's browser-based user flow. When the\n  desktop runtime is available, a localhost listener captures the credentials\n  automatically. Otherwise the browser will show a token that can be pasted\n  into the terminal at the prompt.\n\n  Universal Auth is still supported for automation with:\n    infisical login --method=universal-auth --client-id <id> --client-secret <secret>\n";
}
async function runtimeFetch(input, init) {
  const controller = events.getDefaultNetworkController();
  if (controller) {
    return events.networkFetch(input, init, controller);
  }
  return fetch(input, init);
}
function extractApiErrorMessage(status, statusText, parsed, bodyText) {
  if (parsed && typeof parsed === "object") {
    const record = parsed;
    if (typeof record.message === "string" && record.message.trim()) {
      return record.message.trim();
    }
    if (typeof record.error === "string" && record.error.trim()) {
      return record.error.trim();
    }
    if (Array.isArray(record.errors) && record.errors.length > 0) {
      const first = record.errors[0];
      if (typeof first === "string" && first.trim()) {
        return first.trim();
      }
      if (first && typeof first === "object" && typeof first.message === "string") {
        return first.message.trim();
      }
    }
  }
  return bodyText.trim() || `${status} ${statusText}`;
}
async function infisicalApiRequest(url, init = {}) {
  const headers = new Headers(init.headers);
  if (init.body !== void 0 && !headers.has("content-type")) {
    headers.set("content-type", "application/json");
  }
  if (!headers.has("accept")) {
    headers.set("accept", "application/json");
  }
  const response = await runtimeFetch(url, {
    ...init,
    headers
  });
  const text = await response.text().catch(() => "");
  let parsed = null;
  if (text) {
    try {
      parsed = JSON.parse(text);
    } catch {
      parsed = null;
    }
  }
  if (!response.ok) {
    throw new InfisicalApiError(
      response.status,
      extractApiErrorMessage(response.status, response.statusText, parsed, text)
    );
  }
  if (parsed === null) {
    return {};
  }
  return parsed;
}
async function loginWithUniversalAuth(options) {
  const body = {
    clientId: options.clientId,
    clientSecret: options.clientSecret
  };
  if (options.organizationSlug) {
    body.organizationSlug = options.organizationSlug;
  }
  return infisicalApiRequest(
    `${options.domain}/api/v1/auth/universal-auth/login`,
    {
      method: "POST",
      body: JSON.stringify(body)
    }
  );
}
function parseLoginFlags(args) {
  const options = {
    domain: "",
    interactive: false,
    plain: false,
    silent: false
  };
  let index = 0;
  while (index < args.length) {
    const arg = args[index];
    if (!arg) {
      index += 1;
      continue;
    }
    if (arg === "--plain") {
      options.plain = true;
      index += 1;
      continue;
    }
    if (arg === "--silent") {
      options.silent = true;
      index += 1;
      continue;
    }
    if (arg === "--interactive" || arg === "-i") {
      options.interactive = true;
      index += 1;
      continue;
    }
    if (arg === "--method") {
      const value = args[index + 1];
      if (!value) {
        return { options, error: "missing value for --method" };
      }
      options.method = value;
      index += 2;
      continue;
    }
    if (arg.startsWith("--method=")) {
      options.method = arg.slice("--method=".length);
      index += 1;
      continue;
    }
    if (arg === "--client-id") {
      const value = args[index + 1];
      if (!value) {
        return { options, error: "missing value for --client-id" };
      }
      options.clientId = value;
      index += 2;
      continue;
    }
    if (arg.startsWith("--client-id=")) {
      options.clientId = arg.slice("--client-id=".length);
      index += 1;
      continue;
    }
    if (arg === "--client-secret") {
      const value = args[index + 1];
      if (!value) {
        return { options, error: "missing value for --client-secret" };
      }
      options.clientSecret = value;
      index += 2;
      continue;
    }
    if (arg.startsWith("--client-secret=")) {
      options.clientSecret = arg.slice("--client-secret=".length);
      index += 1;
      continue;
    }
    if (arg === "--organization-slug") {
      const value = args[index + 1];
      if (!value) {
        return { options, error: "missing value for --organization-slug" };
      }
      options.organizationSlug = value;
      index += 2;
      continue;
    }
    if (arg.startsWith("--organization-slug=")) {
      options.organizationSlug = arg.slice("--organization-slug=".length);
      index += 1;
      continue;
    }
    if (arg === "--domain") {
      const value = args[index + 1];
      if (!value) {
        return { options, error: "missing value for --domain" };
      }
      options.domain = normalizeInfisicalDomain(value);
      index += 2;
      continue;
    }
    if (arg.startsWith("--domain=")) {
      options.domain = normalizeInfisicalDomain(arg.slice("--domain=".length));
      index += 1;
      continue;
    }
    if (arg === "--email") {
      const value = args[index + 1];
      if (!value) {
        return { options, error: "missing value for --email" };
      }
      options.email = value;
      index += 2;
      continue;
    }
    if (arg.startsWith("--email=")) {
      options.email = arg.slice("--email=".length);
      index += 1;
      continue;
    }
    if (arg === "--password") {
      const value = args[index + 1];
      if (!value) {
        return { options, error: "missing value for --password" };
      }
      options.password = value;
      index += 2;
      continue;
    }
    if (arg.startsWith("--password=")) {
      options.password = arg.slice("--password=".length);
      index += 1;
      continue;
    }
    if (arg === "--organization-id") {
      const value = args[index + 1];
      if (!value) {
        return { options, error: "missing value for --organization-id" };
      }
      options.organizationId = value;
      index += 2;
      continue;
    }
    if (arg.startsWith("--organization-id=")) {
      options.organizationId = arg.slice("--organization-id=".length);
      index += 1;
      continue;
    }
    return { options, error: `unknown argument '${arg}'` };
  }
  return { options };
}
function parseSecretsFlags(args) {
  const options = {
    domain: null,
    environment: null,
    expandSecretReferences: true,
    includeImports: true,
    plain: false,
    projectId: null,
    recursive: false,
    secretPath: "/",
    silent: false,
    type: "shared"
  };
  const positionals = [];
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const next = args[index + 1];
    if (arg === "--plain") {
      options.plain = true;
      continue;
    }
    if (arg === "--silent") {
      options.silent = true;
      continue;
    }
    if (arg === "--recursive") {
      options.recursive = true;
      continue;
    }
    if (arg.startsWith("--recursive=")) {
      const value = parseBooleanFlagValue(arg.slice("--recursive=".length));
      if (value === null) {
        return { options, positionals, error: `invalid value for --recursive: ${arg.slice("--recursive=".length)}` };
      }
      options.recursive = value;
      continue;
    }
    if (arg === "--expand") {
      if (next && !next.startsWith("-")) {
        const value = parseBooleanFlagValue(next);
        if (value !== null) {
          options.expandSecretReferences = value;
          index += 1;
          continue;
        }
      }
      options.expandSecretReferences = true;
      continue;
    }
    if (arg.startsWith("--expand=")) {
      const value = parseBooleanFlagValue(arg.slice("--expand=".length));
      if (value === null) {
        return { options, positionals, error: `invalid value for --expand: ${arg.slice("--expand=".length)}` };
      }
      options.expandSecretReferences = value;
      continue;
    }
    if (arg === "--no-expand") {
      options.expandSecretReferences = false;
      continue;
    }
    if (arg === "--include-imports") {
      if (next && !next.startsWith("-")) {
        const value = parseBooleanFlagValue(next);
        if (value !== null) {
          options.includeImports = value;
          index += 1;
          continue;
        }
      }
      options.includeImports = true;
      continue;
    }
    if (arg.startsWith("--include-imports=")) {
      const value = parseBooleanFlagValue(arg.slice("--include-imports=".length));
      if (value === null) {
        return { options, positionals, error: `invalid value for --include-imports: ${arg.slice("--include-imports=".length)}` };
      }
      options.includeImports = value;
      continue;
    }
    if (arg === "--env" || arg === "--environment") {
      if (!next) {
        return { options, positionals, error: `missing value for ${arg}` };
      }
      options.environment = next.trim();
      index += 1;
      continue;
    }
    if (arg.startsWith("--env=")) {
      options.environment = arg.slice("--env=".length).trim();
      continue;
    }
    if (arg.startsWith("--environment=")) {
      options.environment = arg.slice("--environment=".length).trim();
      continue;
    }
    if (arg === "--projectId" || arg === "--project-id") {
      if (!next) {
        return { options, positionals, error: `missing value for ${arg}` };
      }
      options.projectId = next.trim();
      index += 1;
      continue;
    }
    if (arg.startsWith("--projectId=")) {
      options.projectId = arg.slice("--projectId=".length).trim();
      continue;
    }
    if (arg.startsWith("--project-id=")) {
      options.projectId = arg.slice("--project-id=".length).trim();
      continue;
    }
    if (arg === "--path") {
      if (!next) {
        return { options, positionals, error: "missing value for --path" };
      }
      options.secretPath = normalizeSecretPath(next);
      index += 1;
      continue;
    }
    if (arg.startsWith("--path=")) {
      options.secretPath = normalizeSecretPath(arg.slice("--path=".length));
      continue;
    }
    if (arg === "--type") {
      if (!next) {
        return { options, positionals, error: "missing value for --type" };
      }
      if (next !== "shared" && next !== "personal") {
        return { options, positionals, error: `unsupported secret type '${next}'` };
      }
      options.type = next;
      index += 1;
      continue;
    }
    if (arg.startsWith("--type=")) {
      const type = arg.slice("--type=".length);
      if (type !== "shared" && type !== "personal") {
        return { options, positionals, error: `unsupported secret type '${type}'` };
      }
      options.type = type;
      continue;
    }
    if (arg === "--domain") {
      if (!next) {
        return { options, positionals, error: "missing value for --domain" };
      }
      options.domain = normalizeInfisicalDomain(next);
      index += 1;
      continue;
    }
    if (arg.startsWith("--domain=")) {
      options.domain = normalizeInfisicalDomain(arg.slice("--domain=".length));
      continue;
    }
    positionals.push(arg);
  }
  return { options, positionals };
}
function parseInitFlags(args) {
  const options = {
    domain: null,
    environment: null,
    projectId: null
  };
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const next = args[index + 1];
    if (arg === "--projectId" || arg === "--project-id") {
      if (!next) {
        return { options, error: `missing value for ${arg}` };
      }
      options.projectId = next.trim();
      index += 1;
      continue;
    }
    if (arg.startsWith("--projectId=")) {
      options.projectId = arg.slice("--projectId=".length).trim();
      continue;
    }
    if (arg.startsWith("--project-id=")) {
      options.projectId = arg.slice("--project-id=".length).trim();
      continue;
    }
    if (arg === "--env" || arg === "--environment") {
      if (!next) {
        return { options, error: `missing value for ${arg}` };
      }
      options.environment = next.trim();
      index += 1;
      continue;
    }
    if (arg.startsWith("--env=")) {
      options.environment = arg.slice("--env=".length).trim();
      continue;
    }
    if (arg.startsWith("--environment=")) {
      options.environment = arg.slice("--environment=".length).trim();
      continue;
    }
    if (arg === "--domain") {
      if (!next) {
        return { options, error: "missing value for --domain" };
      }
      options.domain = normalizeInfisicalDomain(next);
      index += 1;
      continue;
    }
    if (arg.startsWith("--domain=")) {
      options.domain = normalizeInfisicalDomain(arg.slice("--domain=".length));
      continue;
    }
    return { options, error: `unknown argument '${arg}'` };
  }
  return { options };
}
function buildUserLoginUrl(domain, callbackPort) {
  const loginUrl = new URL(`${domain}/login`);
  loginUrl.searchParams.set("callback_port", callbackPort);
  return loginUrl.toString();
}
function normalizeBrowserLoginPayload(rawBody) {
  let parsed;
  try {
    parsed = JSON.parse(rawBody);
  } catch {
    throw new Error("Infisical browser login returned malformed JSON.");
  }
  if (!parsed || typeof parsed !== "object") {
    throw new Error("Infisical browser login did not return a credential payload.");
  }
  const record = parsed;
  const accessToken = coerceString(record.JTWToken) || coerceString(record.token) || coerceString(record.accessToken);
  if (!accessToken) {
    throw new Error("Infisical browser login did not return an access token.");
  }
  return {
    accessToken,
    email: coerceString(record.email),
    privateKey: coerceString(record.privateKey),
    refreshToken: coerceString(record.RefreshToken) || coerceString(record.refreshToken)
  };
}
function resolveCommandDomain(vfs, ctx, explicitDomain) {
  const env = envToRecord(ctx.env);
  const config = readInfisicalConfig(vfs);
  const auth = readInfisicalAuth(vfs);
  return normalizeInfisicalDomain(
    explicitDomain || env.INFISICAL_API_URL || auth.domain || config.domain || DEFAULT_INFISICAL_DOMAIN
  );
}
function resolveStoredOrEnvToken(vfs, ctx) {
  var _a;
  const env = envToRecord(ctx.env);
  const envToken = (_a = env.INFISICAL_TOKEN) == null ? void 0 : _a.trim();
  if (envToken) {
    return { source: "env", token: envToken };
  }
  const stored = readInfisicalAuth(vfs);
  if (isInfisicalAccessTokenValid(stored)) {
    return { source: "stored", token: stored.accessToken };
  }
  return { source: "none", token: null };
}
function formatLoggedOutStatus(config, auth) {
  var _a, _b;
  const lastExpiry = formatDateTime(auth.expiresAt);
  const lastEmail = auth.email || config.loggedInUserEmail;
  const hasMachineIdentity = Boolean(
    ((_a = config.machineIdentity) == null ? void 0 : _a.clientId) && ((_b = config.machineIdentity) == null ? void 0 : _b.clientSecret)
  );
  const lines = [
    "Infisical status: not authenticated",
    `Domain: ${config.domain}`,
    lastEmail ? `Previous user: ${lastEmail}` : null,
    lastExpiry ? `Previous token expired: ${lastExpiry}` : null,
    hasMachineIdentity ? "Run `infisical login` for browser auth or `infisical login --method=universal-auth` to use the saved machine identity." : "Run `infisical login` to start the browser login flow."
  ].filter(Boolean);
  return `${lines.join("\n")}
`;
}
const INFISICAL_US_URL = "https://app.infisical.com";
const INFISICAL_EU_URL = "https://eu.infisical.com";
const INFISICAL_PASTE_PROMPT_DELAY_MS = 5e3;
const INFISICAL_WELCOME_DELAY_MS = 1e3;
const ANSI_BOLD_GREEN = "\x1B[1;32m";
const ANSI_BOLD = "\x1B[1m";
const ANSI_RESET = "\x1B[0m";
function decodePastedBase64Token(raw) {
  const trimmed = raw.trim();
  if (!trimmed) {
    throw new Error("Pasted token is empty.");
  }
  let decoded;
  try {
    decoded = atob(trimmed);
  } catch {
    throw new Error("Pasted token is not valid base64.");
  }
  let parsed;
  try {
    parsed = JSON.parse(decoded);
  } catch {
    throw new Error("Pasted token did not decode to JSON.");
  }
  if (!parsed || typeof parsed !== "object") {
    throw new Error("Pasted token did not contain a credential payload.");
  }
  const record = parsed;
  const accessToken = coerceString(record.JTWToken) || coerceString(record.token) || coerceString(record.accessToken);
  if (!accessToken) {
    throw new Error("Pasted token did not include an access token.");
  }
  return {
    accessToken,
    email: coerceString(record.email),
    privateKey: coerceString(record.privateKey),
    refreshToken: coerceString(record.RefreshToken) || coerceString(record.refreshToken)
  };
}
async function promptHostingOption(ctx, fallbackDomain) {
  var _a;
  if (!ctx.onKeypress) {
    return fallbackDomain;
  }
  try {
    const choice = await selectPrompt({
      ctx,
      label: "Select your hosting option",
      defaultIndex: fallbackDomain === INFISICAL_EU_URL ? 1 : 0,
      items: [
        { label: "Infisical Cloud (US Region)", value: "us" },
        { label: "Infisical Cloud (EU Region)", value: "eu" },
        { label: "Self-Hosting or Dedicated Instance", value: "self" }
      ]
    });
    if (choice === "us") return INFISICAL_US_URL;
    if (choice === "eu") return INFISICAL_EU_URL;
    const { textPrompt: textPrompt2 } = await Promise.resolve().then(() => ttyPrompt);
    const raw = await textPrompt2({
      ctx,
      label: "Domain",
      defaultValue: "Example - https://my-self-hosted-instance.com"
    });
    const normalized = normalizeInfisicalDomain(raw.trim());
    if (!normalized || normalized === "Example - https://my-self-hosted-instance.com") {
      (_a = ctx.writeStderr) == null ? void 0 : _a.call(ctx, "infisical login: no domain entered.\n");
      return null;
    }
    return normalized;
  } catch (error) {
    if (error instanceof PromptAbortError) {
      return null;
    }
    throw error;
  }
}
async function waitForPastedToken(ctx, abort) {
  var _a, _b;
  if (!ctx.onKeypress) {
    return new Promise((resolve) => {
      abort.signal.addEventListener("abort", () => resolve(null), { once: true });
    });
  }
  await new Promise((resolve) => {
    const timer = setTimeout(resolve, INFISICAL_PASTE_PROMPT_DELAY_MS);
    abort.signal.addEventListener("abort", () => {
      clearTimeout(timer);
      resolve();
    }, { once: true });
  });
  if (abort.signal.aborted) return null;
  (_a = ctx.writeStderr) == null ? void 0 : _a.call(
    ctx,
    "\n\nOnce login is completed via browser, the CLI should be authenticated automatically.\nHowever, if browser fails to communicate with the CLI, please paste the token from the browser below.\n\n"
  );
  const scopedCtx = { ...ctx, signal: abort.signal };
  while (!abort.signal.aborted) {
    let pasted;
    try {
      pasted = await hiddenPrompt({
        ctx: scopedCtx,
        label: "Paste your browser token here: "
      });
    } catch (error) {
      if (error instanceof PromptAbortError) return null;
      throw error;
    }
    if (!pasted.trim()) {
      continue;
    }
    try {
      return decodePastedBase64Token(pasted);
    } catch (error) {
      (_b = ctx.writeStderr) == null ? void 0 : _b.call(ctx, `${formatErrorMessage(error)} Please try again.
`);
    }
  }
  return null;
}
async function waitForLoopbackCredentials(bridge, sessionId, abort) {
  try {
    const callback = await bridge.waitForCallback({
      sessionId,
      successHtml: DESKTOP_INFISICAL_SUCCESS_HTML,
      timeoutMs: INFISICAL_DESKTOP_AUTH_TIMEOUT_MS
    });
    if (abort.signal.aborted) return null;
    return normalizeBrowserLoginPayload(callback.requestBody || "");
  } catch (error) {
    if (abort.signal.aborted) return null;
    throw error;
  }
}
async function delay(ms, signal) {
  await new Promise((resolve) => {
    const timer = setTimeout(resolve, ms);
    signal == null ? void 0 : signal.addEventListener("abort", () => {
      clearTimeout(timer);
      resolve();
    }, { once: true });
  });
}
async function runUserLogin(options, ctx, vfs, keychain) {
  var _a, _b, _c;
  if (signalAborted(ctx.signal)) {
    return abortResult();
  }
  if (options.interactive || options.email || options.password || options.organizationId) {
    return err(
      "infisical login: direct user credential entry is not implemented in almostnode.\nUse the default browser login flow instead.\n"
    );
  }
  const currentConfig = readInfisicalConfig(vfs);
  const currentAuth = readInfisicalAuth(vfs);
  let domain;
  if (options.domain) {
    domain = options.domain;
  } else if (ctx.onKeypress && !options.silent && !options.plain) {
    const selected = await promptHostingOption(
      ctx,
      resolveCommandDomain(vfs, ctx, null)
    );
    if (!selected) {
      return abortResult();
    }
    domain = selected;
  } else {
    domain = resolveCommandDomain(vfs, ctx, null);
  }
  if (currentAuth.method === "user" && currentAuth.domain === domain && isInfisicalAccessTokenValid(currentAuth)) {
    if (options.plain) return ok(`${currentAuth.accessToken}
`);
    if (options.silent) return ok("");
    return ok(
      [
        "Already authenticated with Infisical.",
        currentAuth.email ? `Email: ${currentAuth.email}` : null,
        `Domain: ${domain}`,
        currentAuth.expiresAt ? `Token expires: ${formatDateTime(currentAuth.expiresAt)}` : null
      ].filter(Boolean).join("\n") + "\n"
    );
  }
  if (typeof window === "undefined") {
    return err("Infisical browser login requires a browser environment.\n");
  }
  const bridge = getDesktopOAuthLoopbackBridge();
  let session = null;
  let callbackPort = "55118";
  if (bridge) {
    try {
      session = await bridge.createSession({
        allowedOrigins: [domain],
        callbackPath: "/",
        captureBody: true,
        matchAnyPath: true
      });
      const bridgePort = new URL(session.redirectUri).port;
      if (bridgePort) callbackPort = bridgePort;
    } catch (error) {
      (_a = ctx.writeStderr) == null ? void 0 : _a.call(
        ctx,
        `Desktop loopback listener failed (${formatErrorMessage(error)}); falling back to token paste.
`
      );
      session = null;
    }
  }
  const authUrl = buildUserLoginUrl(domain, callbackPort);
  let openedViaBridge = false;
  if (bridge && session) {
    try {
      await bridge.openExternal({ sessionId: session.sessionId, url: authUrl });
      openedViaBridge = true;
    } catch {
      openedViaBridge = false;
    }
  }
  if (!openedViaBridge) {
    try {
      window.open(authUrl, "_blank");
    } catch {
    }
  }
  (_b = ctx.writeStderr) == null ? void 0 : _b.call(
    ctx,
    `

Please proceed to your browser to complete the login process.
If the browser doesn't open automatically, please open this address in your browser: ${authUrl} 
`
  );
  const raceAbort = new AbortController();
  if (ctx.signal) {
    ctx.signal.addEventListener("abort", () => raceAbort.abort(), { once: true });
  }
  const loopbackPromise = bridge && session ? waitForLoopbackCredentials(bridge, session.sessionId, raceAbort) : new Promise((resolve) => {
    raceAbort.signal.addEventListener("abort", () => resolve(null), { once: true });
  });
  const pastePromise = waitForPastedToken(ctx, raceAbort);
  let payload = null;
  try {
    payload = await Promise.race([loopbackPromise, pastePromise]);
  } catch (error) {
    raceAbort.abort();
    if (signalAborted(ctx.signal)) return abortResult();
    return err(`infisical login: ${formatErrorMessage(error)}
`);
  }
  raceAbort.abort();
  if (!payload) {
    if (signalAborted(ctx.signal)) return abortResult();
    return err("infisical login: authentication was cancelled.\n");
  }
  writeInfisicalConfig(vfs, {
    ...currentConfig,
    domain,
    domains: Array.from(/* @__PURE__ */ new Set([...currentConfig.domains || [], domain])),
    loggedInUserEmail: payload.email
  });
  writeInfisicalAuth(vfs, {
    accessToken: payload.accessToken,
    email: payload.email,
    refreshToken: payload.refreshToken,
    privateKey: payload.privateKey,
    tokenType: "Bearer",
    expiresAt: null,
    issuedAt: null,
    domain,
    method: "user",
    clientId: null,
    organizationSlug: null
  });
  await persistKeychainState(keychain);
  const savedAuth = readInfisicalAuth(vfs);
  if (options.plain) return ok(`${savedAuth.accessToken}
`);
  if (options.silent) return ok("");
  (_c = ctx.writeStderr) == null ? void 0 : _c.call(ctx, "\n\nBrowser login successful\n");
  await delay(INFISICAL_WELCOME_DELAY_MS, ctx.signal);
  const emailLabel = payload.email || "your account";
  const successLines = [
    `${ANSI_BOLD_GREEN}>>>> Welcome to Infisical! You are now logged in as ${emailLabel} <<<< ${ANSI_RESET}`,
    "",
    `${ANSI_BOLD}Quick links${ANSI_RESET}`,
    "- Learn to inject secrets into your application at https://infisical.com/docs/cli/usage",
    "- Stuck? Join our slack for quick support https://infisical.com/slack",
    ""
  ];
  if (ctx.writeStdout) {
    ctx.writeStdout(`${successLines.join("\n")}
`);
    return ok("");
  }
  return ok(`${successLines.join("\n")}
`);
}
async function runUniversalAuthLogin(options, ctx, vfs, keychain) {
  var _a, _b, _c, _d, _e;
  const env = envToRecord(ctx.env);
  const currentConfig = readInfisicalConfig(vfs);
  const method = (_a = options.method || env.INFISICAL_AUTH_METHOD || (options.clientId || options.clientSecret ? "universal-auth" : void 0)) == null ? void 0 : _a.trim().toLowerCase();
  if (method !== "universal-auth") {
    return err(`infisical login: unsupported authentication method '${method || ""}'
`);
  }
  const clientId = (options.clientId || env.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID || ((_b = currentConfig.machineIdentity) == null ? void 0 : _b.clientId) || "").trim();
  const clientSecret = (options.clientSecret || env.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET || ((_c = currentConfig.machineIdentity) == null ? void 0 : _c.clientSecret) || "").trim();
  const organizationSlug = (options.organizationSlug || env.INFISICAL_AUTH_ORGANIZATION_SLUG || ((_d = currentConfig.machineIdentity) == null ? void 0 : _d.organizationSlug) || "").trim() || null;
  const domain = resolveCommandDomain(vfs, ctx, options.domain);
  if (!clientId || !clientSecret) {
    return err(
      "infisical login: Universal Auth requires both --client-id and --client-secret.\n"
    );
  }
  const existingAuth = readInfisicalAuth(vfs);
  if (existingAuth.method === "universal-auth" && isInfisicalAccessTokenValid(existingAuth) && existingAuth.domain === domain && existingAuth.clientId === clientId && existingAuth.organizationSlug === organizationSlug) {
    if (options.plain) {
      return ok(`${existingAuth.accessToken}
`);
    }
    if (options.silent) {
      return ok("");
    }
    return ok(
      [
        "Already authenticated with Infisical Universal Auth.",
        `Domain: ${domain}`,
        `Client ID: ${maskIdentifier(clientId)}`,
        organizationSlug ? `Organization slug: ${organizationSlug}` : null,
        existingAuth.expiresAt ? `Token expires: ${formatDateTime(existingAuth.expiresAt)}` : null
      ].filter(Boolean).join("\n") + "\n"
    );
  }
  try {
    const payload = await loginWithUniversalAuth({
      clientId,
      clientSecret,
      domain,
      organizationSlug
    });
    const accessToken = (_e = payload.accessToken) == null ? void 0 : _e.trim();
    if (!accessToken) {
      return err("infisical login: Infisical did not return an access token.\n");
    }
    writeInfisicalConfig(vfs, {
      ...currentConfig,
      domain,
      domains: Array.from(/* @__PURE__ */ new Set([...currentConfig.domains || [], domain])),
      machineIdentity: {
        method: "universal-auth",
        clientId,
        clientSecret,
        organizationSlug
      }
    });
    writeInfisicalAuth(vfs, {
      version: 2,
      accessToken,
      email: null,
      refreshToken: null,
      privateKey: null,
      tokenType: payload.tokenType || "Bearer",
      expiresAt: typeof payload.expiresIn === "number" && Number.isFinite(payload.expiresIn) ? new Date(Date.now() + payload.expiresIn * 1e3).toISOString() : null,
      issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
      domain,
      method: "universal-auth",
      clientId,
      organizationSlug
    });
    await persistKeychainState(keychain);
    if (options.plain) {
      return ok(`${accessToken}
`);
    }
    if (options.silent) {
      return ok("");
    }
    return ok(
      [
        "Authenticated with Infisical Universal Auth.",
        `Domain: ${domain}`,
        `Client ID: ${maskIdentifier(clientId)}`,
        organizationSlug ? `Organization slug: ${organizationSlug}` : null,
        "Run `infisical auth token` if you need the raw access token."
      ].filter(Boolean).join("\n") + "\n"
    );
  } catch (error) {
    return err(`infisical login: ${formatErrorMessage(error)}
`);
  }
}
async function runLoginCommand(args, ctx, vfs, keychain) {
  const parsed = parseLoginFlags(args);
  if (parsed.error) {
    return err(`infisical login: ${parsed.error}
`);
  }
  const env = envToRecord(ctx.env);
  const method = (parsed.options.method || env.INFISICAL_AUTH_METHOD || (parsed.options.clientId || parsed.options.clientSecret ? "universal-auth" : "user")).trim().toLowerCase();
  if (method === "universal-auth") {
    return runUniversalAuthLogin(parsed.options, ctx, vfs, keychain);
  }
  if (method === "user") {
    return runUserLogin(parsed.options, ctx, vfs, keychain);
  }
  return err(`infisical login: unsupported authentication method '${method}'
`);
}
async function runLogoutCommand(vfs, keychain) {
  const auth = readInfisicalAuth(vfs);
  const config = readInfisicalConfig(vfs);
  const removed = deleteInfisicalAuth(vfs);
  if (removed && auth.method === "user" && config.loggedInUserEmail) {
    writeInfisicalConfig(vfs, {
      ...config,
      loggedInUserEmail: null
    });
  }
  if (removed) {
    await persistKeychainState(keychain);
  }
  return ok(
    removed ? "Logged out of Infisical.\n" : "No stored Infisical session was found.\n"
  );
}
function runStatusCommand(ctx, vfs) {
  var _a, _b, _c, _d;
  const resolvedToken = resolveStoredOrEnvToken(vfs, ctx);
  if (resolvedToken.source === "env") {
    return ok(
      "Infisical status: authenticated via INFISICAL_TOKEN\nThe access token is being supplied by the current command environment.\n"
    );
  }
  const auth = readInfisicalAuth(vfs);
  const config = readInfisicalConfig(vfs);
  if (!isInfisicalAccessTokenValid(auth)) {
    return ok(formatLoggedOutStatus(config, auth));
  }
  return ok(
    [
      "Infisical status: authenticated",
      `Domain: ${auth.domain || config.domain}`,
      auth.method === "user" ? "Method: browser login" : `Method: ${auth.method || "universal-auth"}`,
      auth.email || config.loggedInUserEmail ? `Email: ${auth.email || config.loggedInUserEmail}` : null,
      auth.clientId || ((_a = config.machineIdentity) == null ? void 0 : _a.clientId) ? `Client ID: ${maskIdentifier(auth.clientId || ((_b = config.machineIdentity) == null ? void 0 : _b.clientId))}` : null,
      auth.organizationSlug || ((_c = config.machineIdentity) == null ? void 0 : _c.organizationSlug) ? `Organization slug: ${auth.organizationSlug || ((_d = config.machineIdentity) == null ? void 0 : _d.organizationSlug)}` : null,
      auth.expiresAt ? `Token expires: ${formatDateTime(auth.expiresAt)}` : null
    ].filter(Boolean).join("\n") + "\n"
  );
}
function runAuthTokenCommand(ctx, vfs) {
  const resolved = resolveStoredOrEnvToken(vfs, ctx);
  if (resolved.token) {
    return ok(`${resolved.token}
`);
  }
  return err(
    "infisical auth token: no valid access token is available.\nRun `infisical login` first or set `INFISICAL_TOKEN`.\n"
  );
}
function runWhoamiCommand(ctx, vfs) {
  const resolved = resolveStoredOrEnvToken(vfs, ctx);
  if (resolved.source === "env") {
    return ok("Authenticated via INFISICAL_TOKEN\n");
  }
  const auth = readInfisicalAuth(vfs);
  const email = auth.email || readInfisicalConfig(vfs).loggedInUserEmail;
  if (!resolved.token) {
    return err("infisical whoami: not authenticated\n");
  }
  if (!email) {
    return ok("Authenticated with Infisical\n");
  }
  return ok(`${email}
`);
}
function runVaultCommand(args, vfs) {
  const config = readInfisicalConfig(vfs);
  if (args.length === 0) {
    return ok(
      `Vaults are used to securely store your login details locally. Available vaults:
- auto (automatically select native vault on system)
- file (encrypted file vault)

You are currently using [${config.vaultBackendType}] vault to store your login credentials
`
    );
  }
  if (args[0] !== "set") {
    return err(`infisical vault: unknown subcommand '${args[0]}'
`);
  }
  const nextVault = args[1];
  if (!nextVault) {
    return err("infisical vault set: missing vault name\n");
  }
  if (nextVault !== "auto" && nextVault !== "file") {
    return err(`infisical vault set: unsupported vault '${nextVault}'
`);
  }
  if (args.length > 2) {
    return err(`infisical vault set: unknown argument '${args[2]}'
`);
  }
  writeInfisicalConfig(vfs, {
    ...config,
    vaultBackendType: nextVault
  });
  return ok(
    `Switched Infisical vault preference to [${nextVault}]. Existing credentials stay in place until the next login.
`
  );
}
function resolveSecretsContext(parsed, ctx, vfs) {
  const workspace = readInfisicalWorkspaceConfig(vfs, ctx.cwd || "/");
  const token = resolveStoredOrEnvToken(vfs, ctx).token;
  if (!token) {
    return {
      error: "Not authenticated. Run `infisical login` first or set `INFISICAL_TOKEN`."
    };
  }
  const projectId = parsed.options.projectId || (workspace == null ? void 0 : workspace.workspaceId) || null;
  if (!projectId) {
    return {
      error: "No Infisical project is linked. Run `infisical init` or pass `--projectId <id>`."
    };
  }
  return {
    domain: resolveCommandDomain(vfs, ctx, parsed.options.domain),
    environment: parsed.options.environment || (workspace == null ? void 0 : workspace.defaultEnvironment) || INFISICAL_INIT_DEFAULT_ENV,
    projectId,
    secretPath: normalizeSecretPath(parsed.options.secretPath),
    token,
    type: parsed.options.type
  };
}
function formatListedSecrets(secrets, plain) {
  if (secrets.length === 0) {
    return "No secrets found.\n";
  }
  if (plain) {
    return `${secrets.map((secret) => secret.secretValue || "").join("\n")}
`;
  }
  return `${secrets.map((secret) => `${secret.secretKey || ""}=${secret.secretValue || ""}`).join("\n")}
`;
}
function formatResolvedSecrets(secrets, plain) {
  if (plain) {
    return `${secrets.map((secret) => secret.secretValue || "").join("\n")}
`;
  }
  return `${secrets.map((secret) => `${secret.secretKey || ""}=${secret.secretValue || ""}`).join("\n")}
`;
}
function formatSetResults(results) {
  return `${results.map((result) => `${result.action.toUpperCase()} ${result.key}`).join("\n")}
`;
}
function formatDeleteResults(keys) {
  return `${keys.map((key) => `DELETED ${key}`).join("\n")}
`;
}
async function listSecrets(context, options) {
  const url = new URL(`${context.domain}/api/v4/secrets`);
  url.searchParams.set("projectId", context.projectId);
  url.searchParams.set("environment", context.environment);
  url.searchParams.set("secretPath", context.secretPath);
  url.searchParams.set("expandSecretReferences", String(options.expandSecretReferences));
  url.searchParams.set("includeImports", String(options.includeImports));
  url.searchParams.set("recursive", String(options.recursive));
  url.searchParams.set("viewSecretValue", "true");
  if (context.type === "personal") {
    url.searchParams.set("includePersonalOverrides", "true");
  }
  const response = await infisicalApiRequest(
    url.toString(),
    {
      headers: {
        authorization: `Bearer ${context.token}`
      }
    }
  );
  return Array.isArray(response.secrets) ? response.secrets : [];
}
async function getSecret(context, name, options) {
  const url = new URL(`${context.domain}/api/v4/secrets/${encodeURIComponent(name)}`);
  url.searchParams.set("projectId", context.projectId);
  url.searchParams.set("environment", context.environment);
  url.searchParams.set("secretPath", context.secretPath);
  url.searchParams.set("type", context.type);
  url.searchParams.set("expandSecretReferences", String(options.expandSecretReferences));
  url.searchParams.set("includeImports", String(options.includeImports));
  url.searchParams.set("viewSecretValue", "true");
  const response = await infisicalApiRequest(
    url.toString(),
    {
      headers: {
        authorization: `Bearer ${context.token}`
      }
    }
  );
  if (!response.secret) {
    throw new Error(`Infisical did not return secret ${name}.`);
  }
  return response.secret;
}
function parseSecretAssignments(args, ctx, vfs) {
  return args.map((entry) => {
    const equalsIndex = entry.indexOf("=");
    if (equalsIndex <= 0) {
      throw new Error(`invalid secret assignment '${entry}'. Expected KEY=value.`);
    }
    const key = entry.slice(0, equalsIndex).trim();
    let value = entry.slice(equalsIndex + 1);
    if (!key) {
      throw new Error(`invalid secret assignment '${entry}'. Expected KEY=value.`);
    }
    if (value.startsWith("\\@")) {
      value = value.slice(1);
    } else if (value.startsWith("@")) {
      const filePath = events.resolve(ctx.cwd || "/", value.slice(1));
      if (!vfs.existsSync(filePath)) {
        throw new Error(`secret source file not found: ${filePath}`);
      }
      value = String(vfs.readFileSync(filePath, "utf8"));
    }
    return { key, value };
  });
}
async function upsertSecret(context, assignment) {
  const url = `${context.domain}/api/v4/secrets/${encodeURIComponent(assignment.key)}`;
  const body = {
    environment: context.environment,
    projectId: context.projectId,
    secretPath: context.secretPath,
    secretValue: assignment.value,
    type: context.type
  };
  try {
    await infisicalApiRequest(url, {
      method: "PATCH",
      headers: {
        authorization: `Bearer ${context.token}`
      },
      body: JSON.stringify(body)
    });
    return "updated";
  } catch (error) {
    if (!(error instanceof InfisicalApiError) || error.status !== 404) {
      throw error;
    }
  }
  await infisicalApiRequest(url, {
    method: "POST",
    headers: {
      authorization: `Bearer ${context.token}`
    },
    body: JSON.stringify(body)
  });
  return "created";
}
async function deleteSecret(context, key) {
  await infisicalApiRequest(
    `${context.domain}/api/v4/secrets/${encodeURIComponent(key)}`,
    {
      method: "DELETE",
      headers: {
        authorization: `Bearer ${context.token}`
      },
      body: JSON.stringify({
        environment: context.environment,
        projectId: context.projectId,
        secretPath: context.secretPath,
        type: context.type
      })
    }
  );
}
async function runSecretsCommand(args, ctx, vfs) {
  const [subcommand, ...rest] = args;
  switch (subcommand) {
    case void 0:
    case "list": {
      const parsed = parseSecretsFlags(rest);
      if (parsed.error) {
        return err(`infisical secrets: ${parsed.error}
`);
      }
      const context = resolveSecretsContext(parsed, ctx, vfs);
      if ("error" in context) {
        return err(`infisical secrets: ${context.error}
`);
      }
      try {
        const secrets = await listSecrets(context, parsed.options);
        return ok(formatListedSecrets(secrets, parsed.options.plain));
      } catch (error) {
        return err(`infisical secrets: ${formatErrorMessage(error)}
`);
      }
    }
    case "get": {
      const parsed = parseSecretsFlags(rest);
      if (parsed.error) {
        return err(`infisical secrets get: ${parsed.error}
`);
      }
      if (parsed.positionals.length === 0) {
        return err("infisical secrets get: at least one secret name is required\n");
      }
      const context = resolveSecretsContext(parsed, ctx, vfs);
      if ("error" in context) {
        return err(`infisical secrets get: ${context.error}
`);
      }
      try {
        const secrets = await Promise.all(
          parsed.positionals.map((name) => getSecret(context, name, parsed.options))
        );
        return ok(formatResolvedSecrets(secrets, parsed.options.plain));
      } catch (error) {
        return err(`infisical secrets get: ${formatErrorMessage(error)}
`);
      }
    }
    case "set": {
      const parsed = parseSecretsFlags(rest);
      if (parsed.error) {
        return err(`infisical secrets set: ${parsed.error}
`);
      }
      if (parsed.positionals.length === 0) {
        return err("infisical secrets set: at least one KEY=value assignment is required\n");
      }
      const context = resolveSecretsContext(parsed, ctx, vfs);
      if ("error" in context) {
        return err(`infisical secrets set: ${context.error}
`);
      }
      try {
        const assignments = parseSecretAssignments(parsed.positionals, ctx, vfs);
        const results = [];
        for (const assignment of assignments) {
          const action = await upsertSecret(context, assignment);
          results.push({ action, key: assignment.key });
        }
        return ok(formatSetResults(results));
      } catch (error) {
        return err(`infisical secrets set: ${formatErrorMessage(error)}
`);
      }
    }
    case "delete":
    case "rm": {
      const parsed = parseSecretsFlags(rest);
      if (parsed.error) {
        return err(`infisical secrets delete: ${parsed.error}
`);
      }
      if (parsed.positionals.length === 0) {
        return err("infisical secrets delete: at least one secret name is required\n");
      }
      const context = resolveSecretsContext(parsed, ctx, vfs);
      if ("error" in context) {
        return err(`infisical secrets delete: ${context.error}
`);
      }
      try {
        for (const key of parsed.positionals) {
          await deleteSecret(context, key);
        }
        return ok(formatDeleteResults(parsed.positionals));
      } catch (error) {
        return err(`infisical secrets delete: ${formatErrorMessage(error)}
`);
      }
    }
    default:
      return err(`infisical secrets: unknown subcommand '${subcommand}'
`, 2);
  }
}
async function chooseProjectInteractively(domain, token) {
  var _a, _b, _c, _d, _e;
  if (typeof window === "undefined" || typeof window.prompt !== "function") {
    throw new Error(
      "No project is linked. Re-run `infisical init --projectId <id>` from a browser runtime, or provide --projectId explicitly."
    );
  }
  const response = await infisicalApiRequest(
    `${domain}/api/v1/projects?type=secret-manager`,
    {
      headers: {
        authorization: `Bearer ${token}`
      }
    }
  );
  const projects = Array.isArray(response.projects) ? response.projects.filter((project2) => Boolean(project2.id && project2.name)) : [];
  if (projects.length === 0) {
    throw new Error("No accessible Infisical secret-manager projects were returned for this account.");
  }
  const promptBody = projects.map((project2, index) => {
    const environments = Array.isArray(project2.environments) ? project2.environments.map((entry) => entry.slug || entry.name).filter(Boolean).join(", ") : "";
    return `${index + 1}. ${project2.name} (${project2.slug || project2.id})${environments ? ` [${environments}]` : ""}`;
  }).join("\n");
  const rawSelection = window.prompt(
    `Choose an Infisical project by number:

${promptBody}`,
    "1"
  );
  if (!(rawSelection == null ? void 0 : rawSelection.trim())) {
    throw new Error("No project was selected.");
  }
  const selectedIndex = Number(rawSelection.trim());
  if (!Number.isInteger(selectedIndex) || selectedIndex < 1 || selectedIndex > projects.length) {
    throw new Error(`Project selection must be a number between 1 and ${projects.length}.`);
  }
  const project = projects[selectedIndex - 1];
  const defaultEnvironment = Array.isArray(project.environments) && project.environments.length > 0 ? ((_a = project.environments[0]) == null ? void 0 : _a.slug) || ((_b = project.environments[0]) == null ? void 0 : _b.name) || INFISICAL_INIT_DEFAULT_ENV : INFISICAL_INIT_DEFAULT_ENV;
  const environmentPrompt = window.prompt(
    `Environment slug for ${project.name}:`,
    defaultEnvironment
  );
  const environment = (environmentPrompt == null ? void 0 : environmentPrompt.trim()) || defaultEnvironment;
  return {
    environment,
    projectId: ((_c = project.id) == null ? void 0 : _c.trim()) || "",
    projectLabel: ((_d = project.name) == null ? void 0 : _d.trim()) || ((_e = project.id) == null ? void 0 : _e.trim()) || "selected project"
  };
}
async function runInitCommand(args, ctx, vfs) {
  var _a;
  const parsed = parseInitFlags(args);
  if (parsed.error) {
    return err(`infisical init: ${parsed.error}
`);
  }
  const domain = resolveCommandDomain(vfs, ctx, parsed.options.domain);
  let projectId = parsed.options.projectId;
  let environment = ((_a = parsed.options.environment) == null ? void 0 : _a.trim()) || "";
  let projectLabel = projectId || "selected project";
  if (!projectId) {
    const token = resolveStoredOrEnvToken(vfs, ctx).token;
    if (!token) {
      return err("infisical init: authenticate first with `infisical login`\n");
    }
    try {
      const selected = await chooseProjectInteractively(domain, token);
      projectId = selected.projectId;
      environment = environment || selected.environment;
      projectLabel = selected.projectLabel;
    } catch (error) {
      return err(`infisical init: ${formatErrorMessage(error)}
`);
    }
  }
  if (!projectId) {
    return err("infisical init: missing project id\n");
  }
  const filePath = writeInfisicalWorkspaceConfig(vfs, ctx.cwd || "/", {
    defaultEnvironment: environment || INFISICAL_INIT_DEFAULT_ENV,
    workspaceId: projectId
  });
  return ok(
    [
      `Linked this workspace to Infisical project ${projectLabel}.`,
      `Project ID: ${projectId}`,
      `Default environment: ${environment || INFISICAL_INIT_DEFAULT_ENV}`,
      `Config file: ${filePath}`
    ].join("\n") + "\n"
  );
}
async function runInfisicalCommand(args, ctx, vfs, keychain) {
  const [subcommand = "status", ...rest] = args;
  if (subcommand === "--help" || subcommand === "help") {
    return ok(buildHelpText());
  }
  if (signalAborted(ctx.signal)) {
    return abortResult();
  }
  switch (subcommand) {
    case "login":
      return runLoginCommand(rest, ctx, vfs, keychain);
    case "logout":
      return runLogoutCommand(vfs, keychain);
    case "status":
      return runStatusCommand(ctx, vfs);
    case "whoami":
    case "me":
      return runWhoamiCommand(ctx, vfs);
    case "init":
      return runInitCommand(rest, ctx, vfs);
    case "secrets":
      return runSecretsCommand(rest, ctx, vfs);
    case "auth": {
      const [authCommand = "status", ...authRest] = rest;
      switch (authCommand) {
        case "login":
          return runLoginCommand(authRest, ctx, vfs, keychain);
        case "logout":
          if (authRest.length > 0) {
            return err(`infisical auth logout: unknown argument '${authRest[0]}'
`);
          }
          return runLogoutCommand(vfs, keychain);
        case "status":
          if (authRest.length > 0) {
            return err(`infisical auth status: unknown argument '${authRest[0]}'
`);
          }
          return runStatusCommand(ctx, vfs);
        case "token":
          if (authRest.length > 0) {
            return err(`infisical auth token: unknown argument '${authRest[0]}'
`);
          }
          return runAuthTokenCommand(ctx, vfs);
        case "whoami":
          if (authRest.length > 0) {
            return err(`infisical auth whoami: unknown argument '${authRest[0]}'
`);
          }
          return runWhoamiCommand(ctx, vfs);
        default:
          return err(`infisical auth: unknown subcommand '${authCommand}'
`);
      }
    }
    case "vault":
      return runVaultCommand(rest, vfs);
    default:
      return err(
        `infisical: unsupported command '${subcommand}'.
Run \`infisical --help\` for the supported auth, init, and secrets commands.
`
      );
  }
}
exports.DEFAULT_INFISICAL_DOMAIN = DEFAULT_INFISICAL_DOMAIN;
exports.INFISICAL_AUTH_PATH = INFISICAL_AUTH_PATH;
exports.INFISICAL_CONFIG_PATH = INFISICAL_CONFIG_PATH;
exports.runInfisicalCommand = runInfisicalCommand;
//# sourceMappingURL=infisical-command-C4m3JWUO.cjs.map
