"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const events = require("./fetch-virtual-server-J6SUa9HS.cjs");
const DEFAULT_NETLIFY_API_BASE_URL = "https://api.netlify.com/api/v1";
const DEFAULT_NETLIFY_WEB_UI_URL = "https://app.netlify.com";
const NETLIFY_CONFIG_PATH = "/home/user/.config/netlify/config.json";
const NETLIFY_LEGACY_CONFIG_PATH = "/home/user/.netlify/config.json";
const NETLIFY_CLI_CLIENT_ID = "d6f37de6614df7ae58664cfca524744d73807a377f5ee71f1a254f78412e3750";
let preparedNetlifyAuthPopup = null;
function withDefaultController() {
  return events.getDefaultNetworkController();
}
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, "	"));
}
function coerceString(value) {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}
function mapStoredUser(raw, fallbackId) {
  const user = isRecord(raw) ? raw : {};
  const auth = isRecord(user.auth) ? user.auth : {};
  return {
    id: coerceString(user.id) || fallbackId,
    name: coerceString(user.name),
    email: coerceString(user.email),
    accessToken: coerceString(auth.token)
  };
}
function mapNetlifyTicket(raw) {
  const ticket = isRecord(raw) ? raw : {};
  return {
    id: coerceString(ticket.id) || "",
    clientId: coerceString(ticket.client_id),
    authorized: ticket.authorized === true,
    createdAt: coerceString(ticket.created_at)
  };
}
function mapNetlifyTicketExchange(raw) {
  const exchange = isRecord(raw) ? raw : {};
  return {
    id: coerceString(exchange.id) || "",
    accessToken: coerceString(exchange.access_token),
    userId: coerceString(exchange.user_id),
    userEmail: coerceString(exchange.user_email),
    createdAt: coerceString(exchange.created_at)
  };
}
function getConfigCandidatePaths() {
  return [NETLIFY_CONFIG_PATH, NETLIFY_LEGACY_CONFIG_PATH];
}
function buildEmptyNetlifyConfig() {
  return {
    accessToken: null,
    currentUser: null,
    path: null,
    raw: {},
    userId: null,
    users: {}
  };
}
function mapNetlifyConfig(raw, filePath) {
  const usersRaw = isRecord(raw.users) ? raw.users : {};
  const users = {};
  for (const [userId2, userValue] of Object.entries(usersRaw)) {
    users[userId2] = mapStoredUser(userValue, userId2);
  }
  const userId = coerceString(raw.userId);
  const currentUser = userId ? users[userId] ?? null : null;
  return {
    accessToken: (currentUser == null ? void 0 : currentUser.accessToken) ?? null,
    currentUser,
    path: filePath,
    raw,
    userId,
    users
  };
}
function readPreferredNetlifyConfigData(vfs) {
  const primary = readJsonFile(vfs, NETLIFY_CONFIG_PATH);
  const legacy = readJsonFile(vfs, NETLIFY_LEGACY_CONFIG_PATH);
  return {
    data: primary ?? legacy ?? {},
    path: primary ? NETLIFY_CONFIG_PATH : legacy ? NETLIFY_LEGACY_CONFIG_PATH : NETLIFY_CONFIG_PATH,
    legacyExists: vfs.existsSync(NETLIFY_LEGACY_CONFIG_PATH)
  };
}
function mergeUserRecord(existingRaw, updates) {
  const existing = isRecord(existingRaw) ? existingRaw : {};
  const existingAuth = isRecord(existing.auth) ? existing.auth : {};
  const nextAuth = { ...existingAuth };
  if (updates.accessToken === null) {
    delete nextAuth.token;
  } else if (typeof updates.accessToken === "string" && updates.accessToken.trim()) {
    nextAuth.token = updates.accessToken.trim();
  }
  const next = {
    ...existing,
    id: updates.id,
    auth: nextAuth
  };
  if (typeof updates.name === "string" && updates.name.trim()) {
    next.name = updates.name.trim();
  }
  if (typeof updates.email === "string" && updates.email.trim()) {
    next.email = updates.email.trim();
  }
  return next;
}
function writeNetlifyConfigData(vfs, data, options) {
  writeJsonFile(vfs, NETLIFY_CONFIG_PATH, data);
  if ((options == null ? void 0 : options.syncLegacyIfPresent) && vfs.existsSync(NETLIFY_LEGACY_CONFIG_PATH)) {
    writeJsonFile(vfs, NETLIFY_LEGACY_CONFIG_PATH, data);
  }
}
async function netlifyFetch(apiBaseUrl, pathname, init = {}) {
  return events.networkFetch(
    `${normalizeNetlifyApiBaseUrl(apiBaseUrl)}${pathname.startsWith("/") ? pathname : `/${pathname}`}`,
    init,
    withDefaultController()
  );
}
async function readErrorMessage(response, fallbackPrefix) {
  try {
    const contentType = response.headers.get("content-type") ?? "";
    if (contentType.includes("application/json")) {
      const payload = await response.json();
      if (isRecord(payload) && typeof payload.message === "string" && payload.message.trim()) {
        return `${fallbackPrefix}: ${payload.message.trim()}`;
      }
    } else {
      const text = (await response.text()).trim();
      if (text) {
        return `${fallbackPrefix}: ${text}`;
      }
    }
  } catch {
  }
  return `${fallbackPrefix}: ${response.status} ${response.statusText}`;
}
function delay(ms, signal) {
  if (ms <= 0) {
    return Promise.resolve();
  }
  return new Promise((resolve, reject) => {
    const handle = setTimeout(() => {
      signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
      resolve();
    }, ms);
    const onAbort = () => {
      clearTimeout(handle);
      signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
      reject(new DOMException("Aborted", "AbortError"));
    };
    if (signal == null ? void 0 : signal.aborted) {
      onAbort();
      return;
    }
    signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
  });
}
function normalizeNetlifyApiBaseUrl(value) {
  const trimmed = value == null ? void 0 : value.trim();
  if (!trimmed) {
    return DEFAULT_NETLIFY_API_BASE_URL;
  }
  return trimmed.replace(/\/+$/, "") || DEFAULT_NETLIFY_API_BASE_URL;
}
function normalizeNetlifyWebUiUrl(value) {
  const trimmed = value == null ? void 0 : value.trim();
  if (!trimmed) {
    return DEFAULT_NETLIFY_WEB_UI_URL;
  }
  return trimmed.replace(/\/+$/, "") || DEFAULT_NETLIFY_WEB_UI_URL;
}
function buildNetlifyAuthorizeUrl(webUiUrl, ticketId) {
  const baseUrl = normalizeNetlifyWebUiUrl(webUiUrl);
  return `${baseUrl}/authorize?response_type=ticket&ticket=${encodeURIComponent(ticketId)}`;
}
function readNetlifyConfig(vfs) {
  for (const filePath of getConfigCandidatePaths()) {
    const raw = readJsonFile(vfs, filePath);
    if (raw) {
      return mapNetlifyConfig(raw, filePath);
    }
  }
  return buildEmptyNetlifyConfig();
}
function readNetlifyAccessToken(vfs) {
  return readNetlifyConfig(vfs).accessToken;
}
function writeNetlifyAccessToken(vfs, session) {
  var _a;
  const token = session.accessToken.trim();
  if (!token) {
    return;
  }
  const { data, legacyExists } = readPreferredNetlifyConfigData(vfs);
  const users = isRecord(data.users) ? { ...data.users } : {};
  const userId = ((_a = session.userId) == null ? void 0 : _a.trim()) || coerceString(data.userId) || "current";
  users[userId] = mergeUserRecord(users[userId], {
    id: userId,
    accessToken: token,
    email: session.email ?? null,
    name: session.name ?? null
  });
  writeNetlifyConfigData(
    vfs,
    {
      ...data,
      userId,
      users
    },
    { syncLegacyIfPresent: legacyExists }
  );
}
function deleteNetlifyAccessToken(vfs) {
  let changed = false;
  for (const filePath of getConfigCandidatePaths()) {
    const raw = readJsonFile(vfs, filePath);
    if (!raw) {
      continue;
    }
    const userId = coerceString(raw.userId);
    const users = isRecord(raw.users) ? { ...raw.users } : {};
    let fileChanged = false;
    if (userId) {
      const existingUser = users[userId];
      if (isRecord(existingUser)) {
        const existingAuth = isRecord(existingUser.auth) ? { ...existingUser.auth } : {};
        if ("token" in existingAuth) {
          delete existingAuth.token;
          users[userId] = {
            ...existingUser,
            auth: existingAuth
          };
          fileChanged = true;
        }
      }
    }
    if (raw.userId !== null) {
      fileChanged = true;
    }
    if (!fileChanged) {
      continue;
    }
    writeJsonFile(vfs, filePath, {
      ...raw,
      userId: null,
      users
    });
    changed = true;
  }
  return changed;
}
function cancelPreparedNetlifyAuthPopup() {
  if (!preparedNetlifyAuthPopup) {
    return;
  }
  try {
    preparedNetlifyAuthPopup.close();
  } catch {
  }
  preparedNetlifyAuthPopup = null;
}
function openNetlifyAuthWindow(url) {
  var _a, _b;
  const popup = preparedNetlifyAuthPopup;
  preparedNetlifyAuthPopup = null;
  if (popup && !popup.closed) {
    try {
      popup.location.href = url;
      (_a = popup.focus) == null ? void 0 : _a.call(popup);
      return;
    } catch {
      try {
        popup.close();
      } catch {
      }
    }
  }
  try {
    (_b = window.open) == null ? void 0 : _b.call(window, url, "_blank");
  } catch {
  }
}
async function createNetlifyTicket(apiBaseUrl, options) {
  var _a;
  const clientId = ((_a = options == null ? void 0 : options.clientId) == null ? void 0 : _a.trim()) || NETLIFY_CLI_CLIENT_ID;
  const body = typeof (options == null ? void 0 : options.message) === "string" && options.message.trim() ? JSON.stringify({ message: options.message.trim() }) : void 0;
  const response = await netlifyFetch(
    apiBaseUrl,
    `/oauth/tickets?client_id=${encodeURIComponent(clientId)}`,
    {
      method: "POST",
      headers: body ? {
        "Content-Type": "application/json"
      } : void 0,
      body
    }
  );
  if (response.status !== 201) {
    throw new Error(await readErrorMessage(response, "Netlify ticket request failed"));
  }
  return mapNetlifyTicket(await response.json());
}
async function getNetlifyTicket(apiBaseUrl, ticketId) {
  const response = await netlifyFetch(apiBaseUrl, `/oauth/tickets/${encodeURIComponent(ticketId)}`);
  if (response.status === 401 || response.status === 404) {
    throw new Error("Authorization was denied or the login session expired.");
  }
  if (!response.ok) {
    throw new Error(await readErrorMessage(response, "Netlify ticket poll failed"));
  }
  return mapNetlifyTicket(await response.json());
}
async function exchangeNetlifyTicket(apiBaseUrl, ticketId) {
  const response = await netlifyFetch(
    apiBaseUrl,
    `/oauth/tickets/${encodeURIComponent(ticketId)}/exchange`,
    {
      method: "POST"
    }
  );
  if (response.status !== 201) {
    throw new Error(await readErrorMessage(response, "Netlify token exchange failed"));
  }
  return mapNetlifyTicketExchange(await response.json());
}
async function waitForNetlifyTicketAccessToken(apiBaseUrl, ticketId, options) {
  var _a;
  const startedAt = Date.now();
  const timeoutMs = (options == null ? void 0 : options.timeoutMs) ?? 15 * 60 * 1e3;
  const pollIntervalMs = (options == null ? void 0 : options.pollIntervalMs) ?? 1e3;
  while (Date.now() - startedAt < timeoutMs) {
    if ((_a = options == null ? void 0 : options.signal) == null ? void 0 : _a.aborted) {
      throw new DOMException("Aborted", "AbortError");
    }
    const ticket = await getNetlifyTicket(apiBaseUrl, ticketId);
    if (ticket.authorized) {
      return exchangeNetlifyTicket(apiBaseUrl, ticketId);
    }
    await delay(pollIntervalMs, options == null ? void 0 : options.signal);
  }
  throw new Error("Login expired, please try again");
}
async function fetchNetlifyCurrentUser(apiBaseUrl, token) {
  const response = await netlifyFetch(
    apiBaseUrl,
    "/user",
    {
      headers: {
        Authorization: `Bearer ${token.trim()}`
      }
    }
  );
  if (!response.ok) {
    throw new Error(await readErrorMessage(response, "Failed to load Netlify user"));
  }
  const payload = await response.json();
  const user = isRecord(payload) ? payload : {};
  return {
    id: coerceString(user.id),
    email: coerceString(user.email),
    name: coerceString(user.full_name)
  };
}
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 signalAborted(signal) {
  return (signal == null ? void 0 : signal.aborted) === true;
}
function abortResult() {
  return err("netlify: command aborted\n", 130);
}
function isAbortError(error) {
  return error instanceof DOMException && error.name === "AbortError";
}
function formatErrorMessage(error) {
  return error instanceof Error ? error.message : String(error);
}
function resolveStoredToken(vfs, ctx) {
  var _a;
  const env = envToRecord(ctx.env);
  const envToken = (_a = env.NETLIFY_AUTH_TOKEN) == null ? void 0 : _a.trim();
  if (envToken) {
    return envToken;
  }
  return readNetlifyAccessToken(vfs);
}
function buildHelpText() {
  return "netlify - Netlify auth integration for almostnode\n\nCommands:\n  login                        Start the browser-based Netlify login flow\n  login --request <message>    Create an approval ticket for another human to authorize\n  login --check <ticket>       Check a pending approval ticket and save the token if approved\n  logout                       Remove the saved Netlify access token\n  status                       Show current Netlify authentication status\n  auth token                   Print the saved Netlify access token\n  auth whoami                  Print the current Netlify account email\n  auth status                  Show current Netlify authentication status\n\nCommon flags:\n      --api-url <url>          Override the Netlify API base URL\n      --web-ui <url>           Override the Netlify app URL used for authorization\n";
}
function parseCommonFlags(args) {
  const options = {};
  let index = 0;
  while (index < args.length) {
    const arg = args[index];
    if (arg === "--api-url") {
      const value = args[index + 1];
      if (!value) {
        return { options, rest: [], error: "missing value for --api-url" };
      }
      options.apiUrl = value;
      index += 2;
      continue;
    }
    if (arg == null ? void 0 : arg.startsWith("--api-url=")) {
      options.apiUrl = arg.slice("--api-url=".length);
      index += 1;
      continue;
    }
    if (arg === "--web-ui") {
      const value = args[index + 1];
      if (!value) {
        return { options, rest: [], error: "missing value for --web-ui" };
      }
      options.webUiUrl = value;
      index += 2;
      continue;
    }
    if (arg == null ? void 0 : arg.startsWith("--web-ui=")) {
      options.webUiUrl = arg.slice("--web-ui=".length);
      index += 1;
      continue;
    }
    break;
  }
  return { options, rest: args.slice(index) };
}
function resolveCommonFlags(args, ctx) {
  const parsed = parseCommonFlags(args);
  if (parsed.error) {
    return {
      apiUrl: normalizeNetlifyApiBaseUrl(),
      webUiUrl: normalizeNetlifyWebUiUrl(DEFAULT_NETLIFY_WEB_UI_URL),
      rest: [],
      error: parsed.error
    };
  }
  const env = envToRecord(ctx.env);
  return {
    apiUrl: normalizeNetlifyApiBaseUrl(parsed.options.apiUrl || env.NETLIFY_API_BASE_URL),
    webUiUrl: normalizeNetlifyWebUiUrl(parsed.options.webUiUrl || env.NETLIFY_WEB_UI_URL),
    rest: parsed.rest
  };
}
function parseLoginFlags(args, ctx) {
  const common = resolveCommonFlags(args, ctx);
  if (common.error) {
    return { options: { apiUrl: common.apiUrl, webUiUrl: common.webUiUrl }, error: common.error };
  }
  let request;
  let check;
  let index = 0;
  const rest = common.rest;
  while (index < rest.length) {
    const arg = rest[index];
    if (arg === "--request") {
      const value = rest[index + 1];
      if (!value) {
        return {
          options: { apiUrl: common.apiUrl, webUiUrl: common.webUiUrl },
          error: "missing value for --request"
        };
      }
      request = value;
      index += 2;
      continue;
    }
    if (arg == null ? void 0 : arg.startsWith("--request=")) {
      request = arg.slice("--request=".length);
      index += 1;
      continue;
    }
    if (arg === "--check") {
      const value = rest[index + 1];
      if (!value) {
        return {
          options: { apiUrl: common.apiUrl, webUiUrl: common.webUiUrl },
          error: "missing value for --check"
        };
      }
      check = value;
      index += 2;
      continue;
    }
    if (arg == null ? void 0 : arg.startsWith("--check=")) {
      check = arg.slice("--check=".length);
      index += 1;
      continue;
    }
    return {
      options: { apiUrl: common.apiUrl, webUiUrl: common.webUiUrl, check, request },
      error: `unknown argument '${arg}'`
    };
  }
  if (request && check) {
    return {
      options: { apiUrl: common.apiUrl, webUiUrl: common.webUiUrl, check, request },
      error: "`--request` and `--check` are mutually exclusive"
    };
  }
  return {
    options: {
      apiUrl: common.apiUrl,
      webUiUrl: common.webUiUrl,
      check,
      request
    }
  };
}
async function persistAuthorizedToken(vfs, apiUrl, accessToken, fallback, keychain) {
  let currentUser;
  try {
    currentUser = await fetchNetlifyCurrentUser(apiUrl, accessToken);
  } catch {
    currentUser = {
      id: (fallback == null ? void 0 : fallback.userId) ?? null,
      email: (fallback == null ? void 0 : fallback.email) ?? null,
      name: null
    };
  }
  writeNetlifyAccessToken(vfs, {
    accessToken,
    userId: currentUser.id,
    email: currentUser.email,
    name: currentUser.name
  });
  await (keychain == null ? void 0 : keychain.persistCurrentState().catch(() => {
  }));
  return {
    email: currentUser.email,
    name: currentUser.name,
    userId: currentUser.id
  };
}
async function runLoginRequestCommand(args, ctx) {
  var _a;
  const resolved = resolveCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`netlify login: ${resolved.error}
`);
  }
  const rest = resolved.rest;
  let message;
  if (rest[0] === "--request") {
    message = rest[1];
    if (!message) {
      return err("netlify login: missing value for --request\n");
    }
  } else if ((_a = rest[0]) == null ? void 0 : _a.startsWith("--request=")) {
    message = rest[0].slice("--request=".length);
  } else {
    return err("netlify login: missing value for --request\n");
  }
  try {
    const ticket = await createNetlifyTicket(resolved.apiUrl, { message });
    const authUrl = buildNetlifyAuthorizeUrl(resolved.webUiUrl, ticket.id);
    return ok(
      `Ticket ID: ${ticket.id}
Authorize URL: ${authUrl}

After authorizing, run: netlify login --check ${ticket.id}
After approval, the login will be complete.
`
    );
  } catch (error) {
    return err(`Failed to start Netlify login: ${formatErrorMessage(error)}
`);
  }
}
async function runLoginCheckCommand(args, ctx, vfs, keychain) {
  var _a, _b;
  const resolved = resolveCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`netlify login: ${resolved.error}
`);
  }
  const rest = resolved.rest;
  let ticketId;
  if (rest[0] === "--check") {
    ticketId = rest[1];
  } else if ((_a = rest[0]) == null ? void 0 : _a.startsWith("--check=")) {
    ticketId = rest[0].slice("--check=".length);
  }
  if (!ticketId) {
    return err("netlify login: missing value for --check\n");
  }
  try {
    const ticket = await getNetlifyTicket(resolved.apiUrl, ticketId);
    if (!ticket.authorized) {
      return ok("Status: pending\n");
    }
    const exchange = await exchangeNetlifyTicket(resolved.apiUrl, ticketId);
    const token = (_b = exchange.accessToken) == null ? void 0 : _b.trim();
    if (!token) {
      return err("Could not retrieve Netlify access token.\n");
    }
    const user = await persistAuthorizedToken(
      vfs,
      resolved.apiUrl,
      token,
      {
        email: exchange.userEmail,
        userId: exchange.userId
      },
      keychain
    );
    return ok(
      `Status: authorized
Name: ${user.name ?? ""}
Email: ${user.email ?? ""}
`
    );
  } catch (error) {
    const message = formatErrorMessage(error);
    if (message === "Authorization was denied or the login session expired.") {
      return ok("Status: denied\n");
    }
    return err(`netlify login: ${message}
`);
  }
}
async function runLoginCommand(args, ctx, vfs, keychain) {
  var _a;
  const loginFlags = parseLoginFlags(args, ctx);
  if (loginFlags.error) {
    cancelPreparedNetlifyAuthPopup();
    return err(`netlify login: ${loginFlags.error}
`);
  }
  if (loginFlags.options.request) {
    return runLoginRequestCommand(
      [
        "--api-url",
        loginFlags.options.apiUrl,
        "--web-ui",
        loginFlags.options.webUiUrl,
        "--request",
        loginFlags.options.request
      ],
      ctx
    );
  }
  if (loginFlags.options.check) {
    return runLoginCheckCommand(
      [
        "--api-url",
        loginFlags.options.apiUrl,
        "--web-ui",
        loginFlags.options.webUiUrl,
        "--check",
        loginFlags.options.check
      ],
      ctx,
      vfs,
      keychain
    );
  }
  let ticket;
  try {
    ticket = await createNetlifyTicket(loginFlags.options.apiUrl);
  } catch (error) {
    cancelPreparedNetlifyAuthPopup();
    return err(`Failed to start Netlify login: ${formatErrorMessage(error)}
`);
  }
  const authUrl = buildNetlifyAuthorizeUrl(loginFlags.options.webUiUrl, ticket.id);
  openNetlifyAuthWindow(authUrl);
  const outputPrefix = `Opening ${authUrl} ...
If a browser tab did not open, paste that URL into a browser manually.

Waiting for Netlify authentication...
`;
  let exchange;
  try {
    exchange = await waitForNetlifyTicketAccessToken(
      loginFlags.options.apiUrl,
      ticket.id,
      {
        signal: ctx.signal
      }
    );
  } catch (error) {
    if (isAbortError(error) || signalAborted(ctx.signal)) {
      return abortResult();
    }
    return err(`${outputPrefix}${formatErrorMessage(error)}
`);
  }
  const token = (_a = exchange.accessToken) == null ? void 0 : _a.trim();
  if (!token) {
    return err(`${outputPrefix}Netlify did not return an access token.
`);
  }
  const user = await persistAuthorizedToken(
    vfs,
    loginFlags.options.apiUrl,
    token,
    {
      email: exchange.userEmail,
      userId: exchange.userId
    },
    keychain
  );
  if (user.email) {
    return ok(`${outputPrefix}Successfully logged in as ${user.email}
`);
  }
  return ok(`${outputPrefix}Successfully logged in to Netlify.
`);
}
async function runLogoutCommand(args, ctx, vfs, keychain) {
  var _a;
  const resolved = resolveCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`netlify logout: ${resolved.error}
`);
  }
  const env = envToRecord(ctx.env);
  const removed = deleteNetlifyAccessToken(vfs);
  if (removed) {
    await (keychain == null ? void 0 : keychain.persistCurrentState().catch(() => {
    }));
  }
  if ((_a = env.NETLIFY_AUTH_TOKEN) == null ? void 0 : _a.trim()) {
    return ok(
      removed ? "Removed saved Netlify login state. NETLIFY_AUTH_TOKEN is still set in the environment.\n" : "NETLIFY_AUTH_TOKEN is still set in the environment. Unset it to log out completely.\n"
    );
  }
  if (removed) {
    return ok("Removed Netlify login state.\n");
  }
  return ok("Netlify is already logged out.\n");
}
async function runStatusCommand(args, ctx, vfs) {
  const resolved = resolveCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`netlify status: ${resolved.error}
`);
  }
  const token = resolveStoredToken(vfs, ctx);
  if (!token) {
    return ok("Not logged in to Netlify. Run `netlify login` to authenticate.\n");
  }
  try {
    const user = await fetchNetlifyCurrentUser(resolved.apiUrl, token);
    if (user.email) {
      return ok(`Logged in to Netlify as ${user.email}
`);
    }
    return ok("Logged in to Netlify\n");
  } catch (error) {
    return err(`Saved Netlify token is no longer valid: ${formatErrorMessage(error)}
`);
  }
}
async function runTokenCommand(args, ctx, vfs) {
  const resolved = resolveCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`netlify auth token: ${resolved.error}
`);
  }
  const token = resolveStoredToken(vfs, ctx);
  if (!token) {
    return err("Not authenticated. Run `netlify login` first.\n");
  }
  return ok(`${token}
`);
}
async function runWhoamiCommand(args, ctx, vfs) {
  const resolved = resolveCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`netlify auth whoami: ${resolved.error}
`);
  }
  const token = resolveStoredToken(vfs, ctx);
  if (!token) {
    return err("Not authenticated. Run `netlify login` first.\n");
  }
  try {
    const user = await fetchNetlifyCurrentUser(resolved.apiUrl, token);
    if (user.email) {
      return ok(`${user.email}
`);
    }
    return err("Authenticated but Netlify did not return an account email.\n");
  } catch (error) {
    return err(`netlify auth whoami: ${formatErrorMessage(error)}
`);
  }
}
async function runAuthCommand(args, ctx, vfs) {
  const [subcommand = "status", ...rest] = args;
  switch (subcommand) {
    case "status":
      return runStatusCommand(rest, ctx, vfs);
    case "token":
      return runTokenCommand(rest, ctx, vfs);
    case "whoami":
      return runWhoamiCommand(rest, ctx, vfs);
    default:
      return err(`netlify auth: unknown command '${subcommand}'
`, 2);
  }
}
async function runNetlifyCommand(args, ctx, vfs, keychain) {
  if (signalAborted(ctx.signal)) {
    return abortResult();
  }
  try {
    const [subcommand, ...rest] = args;
    switch (subcommand) {
      case void 0:
      case "help":
      case "--help":
        return ok(buildHelpText());
      case "login":
        return runLoginCommand(rest, ctx, vfs, keychain);
      case "logout":
        return runLogoutCommand(rest, ctx, vfs, keychain);
      case "status":
        return runStatusCommand(rest, ctx, vfs);
      case "auth":
        return runAuthCommand(rest, ctx, vfs);
      case "version":
      case "--version":
        return ok("netlify v0.0.0-almostnode\n");
      default:
        return err(
          `netlify: unsupported command '${subcommand}'. Use \`netlify login\`, \`netlify status\`, or \`npx netlify <command>\` for the full CLI.
`,
          2
        );
    }
  } catch (error) {
    if (isAbortError(error) || signalAborted(ctx.signal)) {
      return abortResult();
    }
    return err(`netlify: ${formatErrorMessage(error)}
`);
  }
}
exports.runNetlifyCommand = runNetlifyCommand;
//# sourceMappingURL=netlify-command-DrVU4FqY.cjs.map
