import { r as readGhToken, a as runGitCommand, d as deleteGhToken, h as hasGhToken, w as writeGhToken } from "./git-command-BrC1AO_p.js";
import { ak as join, p as networkFetch, h as getDefaultNetworkController, aE as isAbsolute, aD as normalize, az as resolve, ay as dirname } from "./fetch-virtual-server-BZi6n2Qk.js";
const GH_CLIENT_ID = "Ov23li3di39s0mmKf6HE";
const GH_SCOPES = "repo,read:org,gist";
function ok(stdout) {
  return { stdout, stderr: "", exitCode: 0 };
}
function err(stderr, exitCode = 1) {
  return { stdout: "", stderr, exitCode };
}
function normalizePath(input) {
  if (!input) return "/";
  const normalized = input.replace(/\\/g, "/").replace(/\/+/g, "/");
  return normalized.startsWith("/") ? normalized : `/${normalized}`;
}
function resolvePath(cwd, maybePath) {
  return normalizePath(isAbsolute(maybePath) ? normalize(maybePath) : resolve(cwd || "/", maybePath));
}
async function fetchViaProxy(url, options = {}) {
  return networkFetch(url, options, getDefaultNetworkController());
}
async function requestDeviceCode() {
  const res = await fetchViaProxy("https://github.com/login/device/code", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json"
    },
    body: JSON.stringify({
      client_id: GH_CLIENT_ID,
      scope: GH_SCOPES
    })
  });
  if (!res.ok) {
    throw new Error(`GitHub device code request failed: ${res.status} ${res.statusText}`);
  }
  return res.json();
}
async function pollForToken(deviceCode, interval, expiresIn, onTick) {
  const deadline = Date.now() + expiresIn * 1e3;
  let pollInterval = interval * 1e3;
  while (Date.now() < deadline) {
    await new Promise((r) => setTimeout(r, pollInterval));
    const res = await fetchViaProxy("https://github.com/login/oauth/access_token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify({
        client_id: GH_CLIENT_ID,
        device_code: deviceCode,
        grant_type: "urn:ietf:params:oauth:grant-type:device_code"
      })
    });
    if (!res.ok) {
      throw new Error(`Token poll failed: ${res.status}`);
    }
    const data = await res.json();
    if (data.access_token) {
      return data.access_token;
    }
    if (data.error === "slow_down") {
      pollInterval += 5e3;
      continue;
    }
    if (data.error === "authorization_pending") {
      continue;
    }
    if (data.error === "expired_token") {
      throw new Error("Device code expired. Please try again.");
    }
    if (data.error === "access_denied") {
      throw new Error("Authorization was denied by the user.");
    }
    if (data.error) {
      throw new Error(`OAuth error: ${data.error}`);
    }
  }
  throw new Error("Device code expired (timeout). Please try again.");
}
async function fetchGitHubUser(token) {
  const res = await fetchViaProxy("https://api.github.com/user", {
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json"
    }
  });
  if (!res.ok) {
    throw new Error(`Failed to fetch GitHub user: ${res.status}`);
  }
  return res.json();
}
async function authLogin(_args, _ctx, vfs, keychain) {
  const host = "github.com";
  if (hasGhToken(vfs, host)) {
    const existing = readGhToken(vfs, host);
    return ok(
      `✓ Already logged in to ${host} as ${existing.user}
  To re-authenticate, run: gh auth logout && gh auth login
`
    );
  }
  let deviceData;
  try {
    deviceData = await requestDeviceCode();
  } catch (e) {
    return err(`Failed to initiate device flow: ${e instanceof Error ? e.message : String(e)}
`);
  }
  try {
    await navigator.clipboard.writeText(deviceData.user_code);
  } catch {
  }
  try {
    if (typeof window !== "undefined" && typeof window.alert === "function") {
      window.alert(
        `Your one-time code is: ${deviceData.user_code}

(It has been copied to your clipboard)

Click OK to open GitHub in your browser.`
      );
    }
  } catch {
  }
  const output = `! First copy your one-time code: ${deviceData.user_code}
- Waiting for authentication...
`;
  try {
    window.open(deviceData.verification_uri, "_blank");
  } catch {
  }
  let token;
  try {
    token = await pollForToken(deviceData.device_code, deviceData.interval, deviceData.expires_in);
  } catch (e) {
    return err(
      output + `✗ ${e instanceof Error ? e.message : String(e)}
`
    );
  }
  let username;
  try {
    const user = await fetchGitHubUser(token);
    username = user.login;
  } catch (e) {
    return err(
      output + `✗ Authentication succeeded but failed to fetch user info: ${e instanceof Error ? e.message : String(e)}
`
    );
  }
  writeGhToken(vfs, {
    oauth_token: token,
    user: username,
    git_protocol: "https"
  }, host);
  await (keychain == null ? void 0 : keychain.persistCurrentState().catch(() => {
  }));
  return ok(
    output + `✓ Authentication complete.
✓ Logged in as ${username}
`
  );
}
async function authStatus(_args, _ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err(
      `${host}
  ✗ Not logged in to any GitHub hosts. Run gh auth login to authenticate.
`
    );
  }
  let username = config.user;
  try {
    const user = await fetchGitHubUser(config.oauth_token);
    username = user.login;
  } catch {
    return err(
      `${host}
  ✗ Token for ${config.user} is no longer valid. Run gh auth login to re-authenticate.
`
    );
  }
  return ok(
    `${host}
  ✓ Logged in to ${host} account ${username} (oauth_token)
  - Active account: true
  - Git operations protocol: ${config.git_protocol}
  - Token scopes: ${GH_SCOPES}
`
  );
}
async function authLogout(_args, _ctx, vfs, keychain) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config) {
    return err(`✗ Not logged in to ${host}
`);
  }
  const username = config.user;
  deleteGhToken(vfs, host);
  await (keychain == null ? void 0 : keychain.persistCurrentState().catch(() => {
  }));
  return ok(`✓ Logged out of ${host} account ${username}
`);
}
async function authToken(_args, _ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err(`no oauth token
`);
  }
  return ok(config.oauth_token + "\n");
}
async function runAuth(args, ctx, vfs, keychain) {
  const sub = args[0];
  switch (sub) {
    case "login":
      return authLogin(args.slice(1), ctx, vfs, keychain);
    case "status":
      return authStatus(args.slice(1), ctx, vfs);
    case "logout":
      return authLogout(args.slice(1), ctx, vfs, keychain);
    case "token":
      return authToken(args.slice(1), ctx, vfs);
    default:
      return err(
        `Usage: gh auth <command>

Available commands:
  login       Authenticate with a GitHub host
  logout      Log out of a GitHub host
  status      View authentication status
  token       Print the auth token
`
      );
  }
}
async function runApi(args, _ctx, vfs) {
  if (args.length === 0) {
    return err("Usage: gh api <endpoint> [--method METHOD] [-f field=value ...]\n");
  }
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let endpoint = args[0];
  let method = "GET";
  const fields = {};
  const headers = {
    Accept: "application/vnd.github+json",
    Authorization: `Bearer ${config.oauth_token}`
  };
  for (let i = 1; i < args.length; i++) {
    const arg = args[i];
    if ((arg === "--method" || arg === "-X") && i + 1 < args.length) {
      method = args[++i].toUpperCase();
    } else if ((arg === "-f" || arg === "--field") && i + 1 < args.length) {
      const kv = args[++i];
      const eqIdx = kv.indexOf("=");
      if (eqIdx > 0) {
        fields[kv.slice(0, eqIdx)] = kv.slice(eqIdx + 1);
      }
    } else if ((arg === "-H" || arg === "--header") && i + 1 < args.length) {
      const h = args[++i];
      const colonIdx = h.indexOf(":");
      if (colonIdx > 0) {
        headers[h.slice(0, colonIdx).trim()] = h.slice(colonIdx + 1).trim();
      }
    }
  }
  if (endpoint.startsWith("/")) {
    endpoint = `https://api.github.com${endpoint}`;
  } else if (!endpoint.startsWith("http")) {
    endpoint = `https://api.github.com/${endpoint}`;
  }
  const fetchOptions = {
    method,
    headers
  };
  if (method !== "GET" && method !== "HEAD" && Object.keys(fields).length > 0) {
    fetchOptions.body = JSON.stringify(fields);
    fetchOptions.headers["Content-Type"] = "application/json";
  }
  try {
    const res = await fetchViaProxy(endpoint, fetchOptions);
    const text = await res.text();
    if (!res.ok) {
      return err(`gh: API error (${res.status}): ${text}
`);
    }
    try {
      const json = JSON.parse(text);
      return ok(JSON.stringify(json, null, 2) + "\n");
    } catch {
      return ok(text + "\n");
    }
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
function timeAgo(date) {
  const seconds = Math.floor((Date.now() - date.getTime()) / 1e3);
  if (seconds < 60) return "just now";
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `about ${minutes} minute${minutes === 1 ? "" : "s"} ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `about ${hours} hour${hours === 1 ? "" : "s"} ago`;
  const days = Math.floor(hours / 24);
  if (days < 30) return `about ${days} day${days === 1 ? "" : "s"} ago`;
  const months = Math.floor(days / 30);
  if (months < 12) return `about ${months} month${months === 1 ? "" : "s"} ago`;
  const years = Math.floor(months / 12);
  return `about ${years} year${years === 1 ? "" : "s"} ago`;
}
async function repoList(args, _ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let owner = null;
  let limit = 30;
  let visibility = null;
  let language = null;
  let showForks = null;
  let showArchived = null;
  let jsonFields = null;
  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if ((arg === "-L" || arg === "--limit") && i + 1 < args.length) {
      limit = parseInt(args[++i], 10) || 30;
    } else if (arg === "--visibility" && i + 1 < args.length) {
      visibility = args[++i];
    } else if ((arg === "-l" || arg === "--language") && i + 1 < args.length) {
      language = args[++i];
    } else if (arg === "--fork") {
      showForks = true;
    } else if (arg === "--source") {
      showForks = false;
    } else if (arg === "--archived") {
      showArchived = true;
    } else if (arg === "--no-archived") {
      showArchived = false;
    } else if (arg === "--json" && i + 1 < args.length) {
      jsonFields = args[++i].split(",");
    } else if (!arg.startsWith("-")) {
      owner = arg;
    }
  }
  let apiUrl;
  if (owner) {
    apiUrl = `https://api.github.com/users/${encodeURIComponent(owner)}/repos`;
  } else {
    apiUrl = "https://api.github.com/user/repos";
  }
  const perPage = Math.min(Math.max(limit, 30), 100);
  apiUrl += `?per_page=${perPage}&sort=pushed&direction=desc`;
  if (visibility && !owner) {
    apiUrl += `&visibility=${visibility}`;
  }
  try {
    const res = await fetchViaProxy(apiUrl, {
      headers: {
        Authorization: `Bearer ${config.oauth_token}`,
        Accept: "application/vnd.github+json"
      }
    });
    if (!res.ok) {
      const text = await res.text();
      return err(`gh: API error (${res.status}): ${text}
`);
    }
    let repos = await res.json();
    if (showForks === true) repos = repos.filter((r) => r.fork);
    if (showForks === false) repos = repos.filter((r) => !r.fork);
    if (showArchived === true) repos = repos.filter((r) => r.archived);
    if (showArchived === false) repos = repos.filter((r) => !r.archived);
    if (language) {
      const lang = language.toLowerCase();
      repos = repos.filter((r) => {
        var _a;
        return ((_a = r.language) == null ? void 0 : _a.toLowerCase()) === lang;
      });
    }
    if (visibility && owner) {
      repos = repos.filter((r) => {
        if (visibility === "public") return !r.private;
        if (visibility === "private") return r.private;
        return true;
      });
    }
    repos = repos.slice(0, limit);
    if (jsonFields) {
      const fieldMap = {
        name: (r) => r.name,
        nameWithOwner: (r) => r.full_name,
        description: (r) => r.description || "",
        visibility: (r) => r.private ? "PRIVATE" : "PUBLIC",
        isPrivate: (r) => r.private,
        isFork: (r) => r.fork,
        isArchived: (r) => r.archived,
        primaryLanguage: (r) => r.language ? { name: r.language } : null,
        stargazerCount: (r) => r.stargazers_count,
        forkCount: (r) => r.forks_count,
        url: (r) => r.html_url,
        sshUrl: (r) => r.ssh_url,
        createdAt: (r) => r.created_at,
        updatedAt: (r) => r.updated_at,
        pushedAt: (r) => r.pushed_at,
        owner: (r) => {
          var _a;
          return { login: (_a = r.owner) == null ? void 0 : _a.login };
        }
      };
      const output = repos.map((r) => {
        const obj = {};
        for (const field of jsonFields) {
          obj[field] = fieldMap[field] ? fieldMap[field](r) : r[field] ?? null;
        }
        return obj;
      });
      return ok(JSON.stringify(output, null, 2) + "\n");
    }
    if (repos.length === 0) {
      return ok("No repositories match your search\n");
    }
    const lines = repos.map((r) => {
      const name = r.full_name;
      const desc = r.description || "";
      const vis = r.private ? "private" : "public";
      const lang = r.language || "";
      const updated = timeAgo(new Date(r.pushed_at));
      const truncDesc = desc.length > 50 ? desc.slice(0, 47) + "..." : desc;
      return `${name}	${truncDesc}	${vis}	${lang}	${updated}`;
    });
    return ok(lines.join("\n") + "\n");
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
const GH_DEFAULT_REPO_PATH = "/home/user/.config/gh/default-repo";
function readFlagValue(args, index, flag) {
  const arg = args[index];
  if (arg === flag && index + 1 < args.length) {
    return { value: args[index + 1], nextIndex: index + 1 };
  }
  if (arg.startsWith(`${flag}=`)) {
    return { value: arg.slice(flag.length + 1), nextIndex: index };
  }
  return { nextIndex: index };
}
function readAlternateFlagValue(args, index, flags) {
  for (const flag of flags) {
    const match = readFlagValue(args, index, flag);
    if (match.value !== void 0) {
      return match;
    }
  }
  return { nextIndex: index };
}
function readBooleanFlagValue(arg, flag) {
  if (arg === flag || arg === `${flag}=true`) {
    return true;
  }
  if (arg === `${flag}=false`) {
    return false;
  }
  return void 0;
}
function parseRepoCoordinates(input, defaultOwner) {
  let candidate = input.trim();
  if (!candidate) {
    return null;
  }
  candidate = candidate.replace(/^https?:\/\/github\.com\//i, "").replace(/^git@github\.com:/i, "").replace(/\.git$/i, "").replace(/^\/+/, "").replace(/\/+$/, "");
  const segments = candidate.split("/").filter(Boolean);
  if (segments.length === 1 && defaultOwner) {
    return {
      owner: defaultOwner,
      repoName: segments[0]
    };
  }
  if (segments.length !== 2) {
    return null;
  }
  return {
    owner: segments[0],
    repoName: segments[1]
  };
}
function ensureGhConfigDir(vfs) {
  const dir = dirname(GH_DEFAULT_REPO_PATH);
  if (!vfs.existsSync(dir)) {
    vfs.mkdirSync(dir, { recursive: true });
  }
}
function readDefaultRepoCoordinates(vfs) {
  if (!vfs.existsSync(GH_DEFAULT_REPO_PATH)) {
    return null;
  }
  try {
    const raw = vfs.readFileSync(GH_DEFAULT_REPO_PATH, "utf8").trim();
    return parseRepoCoordinates(raw);
  } catch {
    return null;
  }
}
function writeDefaultRepoCoordinates(vfs, coordinates) {
  ensureGhConfigDir(vfs);
  vfs.writeFileSync(GH_DEFAULT_REPO_PATH, `${coordinates.owner}/${coordinates.repoName}
`);
}
function clearDefaultRepoCoordinates(vfs) {
  if (!vfs.existsSync(GH_DEFAULT_REPO_PATH)) {
    return false;
  }
  try {
    vfs.unlinkSync(GH_DEFAULT_REPO_PATH);
  } catch {
    return false;
  }
  return true;
}
async function inferRepoCoordinatesFromOrigin(ctx, vfs) {
  let result;
  try {
    result = await runGitCommand(["remote", "get-url", "origin"], ctx, vfs);
  } catch {
    return null;
  }
  if (result.exitCode !== 0) {
    return null;
  }
  return parseRepoCoordinates(result.stdout.trim());
}
async function resolveRepoCoordinates(repoInput, ctx, vfs, defaultOwner) {
  if (repoInput) {
    const parsed = parseRepoCoordinates(repoInput, defaultOwner);
    if (!parsed) {
      return err(`gh repo: invalid repository '${repoInput}'
`, 2);
    }
    return parsed;
  }
  const inferred = await inferRepoCoordinatesFromOrigin(ctx, vfs);
  if (inferred) {
    return inferred;
  }
  const defaultRepo = readDefaultRepoCoordinates(vfs);
  if (defaultRepo) {
    return defaultRepo;
  }
  return err("gh repo: could not determine repository from the current directory. Specify OWNER/REPO.\n", 2);
}
function parseRepoCreateArgs(args) {
  let repoInput;
  let visibility = "private";
  let description;
  let homepage;
  let source;
  let remote = "origin";
  let push = false;
  let hasIssues = true;
  let hasWiki = true;
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    if (arg === "--public") {
      visibility = "public";
      continue;
    }
    if (arg === "--private") {
      visibility = "private";
      continue;
    }
    if (arg === "--push") {
      push = true;
      continue;
    }
    if (arg === "--disable-issues") {
      hasIssues = false;
      continue;
    }
    if (arg === "--disable-wiki") {
      hasWiki = false;
      continue;
    }
    if (arg === "--confirm" || arg === "-y") {
      continue;
    }
    if (arg === "--internal") {
      return err("gh repo create: unsupported option '--internal'\n", 2);
    }
    const sourceValue = readFlagValue(args, index, "--source");
    if (sourceValue.value !== void 0) {
      source = sourceValue.value;
      index = sourceValue.nextIndex;
      continue;
    }
    const remoteValue = readFlagValue(args, index, "--remote");
    if (remoteValue.value !== void 0) {
      remote = remoteValue.value;
      index = remoteValue.nextIndex;
      continue;
    }
    const descriptionValue = readFlagValue(args, index, "--description");
    if (descriptionValue.value !== void 0) {
      description = descriptionValue.value;
      index = descriptionValue.nextIndex;
      continue;
    }
    const homepageValue = readFlagValue(args, index, "--homepage");
    if (homepageValue.value !== void 0) {
      homepage = homepageValue.value;
      index = homepageValue.nextIndex;
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh repo create: unsupported option '${arg}'
`, 2);
    }
    if (repoInput) {
      return err("gh repo create: too many arguments\n", 2);
    }
    repoInput = arg;
  }
  if (!repoInput) {
    return err("Usage: gh repo create <name> [--public|--private] [--source <path>] [--push]\n", 2);
  }
  if (push && !source) {
    return err("gh repo create: --push requires --source\n", 2);
  }
  const segments = repoInput.split("/").filter(Boolean);
  if (segments.length === 0 || segments.length > 2) {
    return err(`gh repo create: invalid repository name '${repoInput}'
`, 2);
  }
  return {
    owner: segments.length === 2 ? segments[0] : void 0,
    repoName: segments[segments.length - 1],
    visibility,
    description,
    homepage,
    hasIssues,
    hasWiki,
    source,
    remote,
    push
  };
}
async function syncRepoRemote(sourceDir, remoteName, remoteUrl, ctx, vfs) {
  const remoteCtx = { ...ctx, cwd: sourceDir };
  const current = await runGitCommand(["remote", "get-url", remoteName], remoteCtx, vfs);
  if (current.exitCode === 0) {
    if (current.stdout.trim() === remoteUrl) {
      return ok("");
    }
    return runGitCommand(["remote", "set-url", remoteName, remoteUrl], remoteCtx, vfs);
  }
  return runGitCommand(["remote", "add", remoteName, remoteUrl], remoteCtx, vfs);
}
function repoCoordinatesEqual(left, right) {
  return left.owner === right.owner && left.repoName === right.repoName;
}
async function resolveExplicitRepoOption(repoOption, ctx, vfs, defaultOwner) {
  if (!repoOption) {
    return void 0;
  }
  const parsed = parseRepoCoordinates(repoOption, defaultOwner);
  if (parsed) {
    return parsed;
  }
  const remoteResult = await runGitCommand(["remote", "get-url", repoOption], ctx, vfs);
  if (remoteResult.exitCode === 0) {
    const remoteRepo = parseRepoCoordinates(remoteResult.stdout.trim(), defaultOwner);
    if (remoteRepo) {
      return remoteRepo;
    }
  }
  return err(`gh repo: invalid repository '${repoOption}'
`, 2);
}
async function resolveRepoTarget(repoInput, repoOption, ctx, vfs, defaultOwner) {
  if (repoInput && repoOption) {
    return err("gh repo: specify only one repository\n", 2);
  }
  const explicitRepo = await resolveExplicitRepoOption(repoOption, ctx, vfs, defaultOwner);
  if (explicitRepo && "exitCode" in explicitRepo) {
    return explicitRepo;
  }
  if (explicitRepo) {
    return explicitRepo;
  }
  return resolveRepoCoordinates(repoInput, ctx, vfs, defaultOwner);
}
async function repoCreate(args, ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  const parsed = parseRepoCreateArgs(args);
  if ("exitCode" in parsed) {
    return parsed;
  }
  const apiUrl = parsed.owner ? `https://api.github.com/orgs/${encodeURIComponent(parsed.owner)}/repos` : "https://api.github.com/user/repos";
  const body = {
    name: parsed.repoName,
    private: parsed.visibility !== "public",
    has_issues: parsed.hasIssues,
    has_wiki: parsed.hasWiki
  };
  if (parsed.description) {
    body.description = parsed.description;
  }
  if (parsed.homepage) {
    body.homepage = parsed.homepage;
  }
  let repository;
  try {
    const response = await fetchViaProxy(apiUrl, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${config.oauth_token}`,
        Accept: "application/vnd.github+json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    });
    const text = await response.text();
    if (!response.ok) {
      return err(`gh: API error (${response.status}): ${text}
`);
    }
    repository = text ? JSON.parse(text) : {};
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
  const htmlUrl = typeof repository.html_url === "string" ? repository.html_url : `https://github.com/${parsed.owner ? `${parsed.owner}/` : ""}${parsed.repoName}`;
  const fullName = typeof repository.full_name === "string" ? repository.full_name : htmlUrl.replace("https://github.com/", "");
  const remoteUrl = typeof repository.clone_url === "string" ? repository.clone_url : `${htmlUrl}.git`;
  const output = [
    `Created repository ${fullName}
`,
    `${htmlUrl}
`
  ];
  if (!parsed.source) {
    return ok(output.join(""));
  }
  const sourceDir = resolvePath(ctx.cwd, parsed.source);
  const gitDir = normalizePath(join(sourceDir, ".git"));
  if (!vfs.existsSync(sourceDir)) {
    return err(`gh repo create: source path '${parsed.source}' does not exist
`, 2);
  }
  if (!vfs.existsSync(gitDir)) {
    return err(
      `Created repository ${fullName}
${htmlUrl}
gh repo create: source path '${parsed.source}' is not a git repository
`,
      2
    );
  }
  const remoteResult = await syncRepoRemote(sourceDir, parsed.remote, remoteUrl, ctx, vfs);
  if (remoteResult.exitCode !== 0) {
    return err(
      `Created repository ${fullName}
${htmlUrl}
` + (remoteResult.stderr || remoteResult.stdout || `Failed to configure remote '${parsed.remote}'
`),
      remoteResult.exitCode
    );
  }
  output.push(`Configured remote '${parsed.remote}'
`);
  if (!parsed.push) {
    return ok(output.join(""));
  }
  const pushResult = await runGitCommand(["push", "-u", parsed.remote], { ...ctx, cwd: sourceDir }, vfs);
  if (pushResult.exitCode !== 0) {
    return err(
      `${output.join("")}` + (pushResult.stderr || pushResult.stdout || `Failed to push to '${parsed.remote}'
`),
      pushResult.exitCode
    );
  }
  output.push(`Pushed local commits to ${parsed.remote}
`);
  return ok(output.join(""));
}
async function repoView(args, ctx, vfs) {
  var _a;
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let repoInput;
  let repoOption;
  let jsonFields = null;
  let openInBrowser = false;
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const repoValue = readAlternateFlagValue(args, index, ["--repo", "-R"]);
    if (repoValue.value !== void 0) {
      repoOption = repoValue.value;
      index = repoValue.nextIndex;
      continue;
    }
    if (arg === "--json" && index + 1 < args.length) {
      jsonFields = args[++index].split(",");
      continue;
    }
    if (arg === "--web") {
      openInBrowser = true;
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh repo view: unsupported option '${arg}'
`, 2);
    }
    if (repoInput) {
      return err("gh repo view: too many arguments\n", 2);
    }
    repoInput = arg;
  }
  const targetCoordinates = await resolveRepoTarget(repoInput, repoOption, ctx, vfs, config.user);
  if ("exitCode" in targetCoordinates) {
    return err(`gh repo view: ${targetCoordinates.stderr.replace(/^gh repo:\s*/, "")}`, targetCoordinates.exitCode);
  }
  try {
    const response = await fetchViaProxy(
      `https://api.github.com/repos/${encodeURIComponent(targetCoordinates.owner)}/${encodeURIComponent(targetCoordinates.repoName)}`,
      {
        headers: {
          Authorization: `Bearer ${config.oauth_token}`,
          Accept: "application/vnd.github+json"
        }
      }
    );
    const text = await response.text();
    if (!response.ok) {
      return err(`gh: API error (${response.status}): ${text}
`);
    }
    const repository = text ? JSON.parse(text) : {};
    const htmlUrl = repository.html_url ?? `https://github.com/${targetCoordinates.owner}/${targetCoordinates.repoName}`;
    if (openInBrowser) {
      try {
        if (typeof window !== "undefined" && typeof window.open === "function") {
          window.open(htmlUrl, "_blank");
        }
      } catch {
      }
      return ok(`${htmlUrl}
`);
    }
    if (jsonFields) {
      const output = {};
      for (const field of jsonFields) {
        switch (field) {
          case "name":
            output[field] = repository.name ?? null;
            break;
          case "nameWithOwner":
            output[field] = repository.full_name ?? null;
            break;
          case "description":
            output[field] = repository.description || "";
            break;
          case "url":
            output[field] = repository.html_url ?? null;
            break;
          case "sshUrl":
            output[field] = repository.ssh_url ?? null;
            break;
          case "visibility":
            output[field] = repository.private ? "PRIVATE" : "PUBLIC";
            break;
          case "isPrivate":
            output[field] = Boolean(repository.private);
            break;
          case "isFork":
            output[field] = Boolean(repository.fork);
            break;
          case "isArchived":
            output[field] = Boolean(repository.archived);
            break;
          case "defaultBranchRef":
            output[field] = repository.default_branch ? { name: repository.default_branch } : null;
            break;
          case "owner":
            output[field] = { login: (_a = repository.owner) == null ? void 0 : _a.login };
            break;
          default:
            output[field] = repository[field] ?? null;
            break;
        }
      }
      return ok(`${JSON.stringify(output, null, 2)}
`);
    }
    const description = repository.description ? `${repository.description}
` : "";
    const language = repository.language ? `  - language: ${repository.language}
` : "";
    return ok(
      `${repository.full_name ?? `${targetCoordinates.owner}/${targetCoordinates.repoName}`}
` + description + `${htmlUrl}
  - visibility: ${repository.private ? "private" : "public"}
  - default branch: ${repository.default_branch ?? "main"}
  - stars: ${repository.stargazers_count ?? 0}
  - forks: ${repository.forks_count ?? 0}
` + language
    );
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
async function repoClone(args, ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  const positionals = [];
  for (const arg of args) {
    if (arg.startsWith("-")) {
      return err(`gh repo clone: unsupported option '${arg}'
`, 2);
    }
    positionals.push(arg);
  }
  if (positionals.length === 0 || positionals.length > 2) {
    return err("Usage: gh repo clone <repository> [directory]\n", 2);
  }
  const coordinates = await resolveRepoCoordinates(positionals[0], ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return coordinates;
  }
  const cloneArgs = ["clone", `https://github.com/${coordinates.owner}/${coordinates.repoName}.git`];
  if (positionals[1]) {
    cloneArgs.push(positionals[1]);
  }
  return runGitCommand(cloneArgs, ctx, vfs);
}
async function repoDelete(args, ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let repoInput;
  let confirmed = false;
  for (const arg of args) {
    if (arg === "--yes" || arg === "-y") {
      confirmed = true;
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh repo delete: unsupported option '${arg}'
`, 2);
    }
    if (repoInput) {
      return err("gh repo delete: too many arguments\n", 2);
    }
    repoInput = arg;
  }
  if (!confirmed) {
    return err("gh repo delete: pass --yes to confirm deletion\n", 2);
  }
  const coordinates = await resolveRepoCoordinates(repoInput, ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return coordinates;
  }
  try {
    const response = await fetchViaProxy(
      `https://api.github.com/repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.repoName)}`,
      {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${config.oauth_token}`,
          Accept: "application/vnd.github+json"
        }
      }
    );
    if (!response.ok) {
      const text = await response.text();
      return err(`gh: API error (${response.status}): ${text}
`);
    }
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
  return ok(`Deleted repository ${coordinates.owner}/${coordinates.repoName}
`);
}
async function repoSetDefault(args, ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let repoInput;
  let unset = false;
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const repoValue = readAlternateFlagValue(args, index, ["--repo", "-R"]);
    if (repoValue.value !== void 0) {
      repoInput = repoValue.value;
      index = repoValue.nextIndex;
      continue;
    }
    if (arg === "--unset" || arg === "-u") {
      unset = true;
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh repo set-default: unsupported option '${arg}'
`, 2);
    }
    if (repoInput) {
      return err("gh repo set-default: too many arguments\n", 2);
    }
    repoInput = arg;
  }
  if (unset) {
    clearDefaultRepoCoordinates(vfs);
    return ok("Cleared default repository\n");
  }
  const coordinates = await resolveRepoTarget(repoInput, void 0, ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return err(`gh repo set-default: ${coordinates.stderr.replace(/^gh repo:\s*/, "")}`, coordinates.exitCode);
  }
  writeDefaultRepoCoordinates(vfs, coordinates);
  return ok(`Default repository set to ${coordinates.owner}/${coordinates.repoName}
`);
}
async function repoRename(args, ctx, vfs) {
  var _a;
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let repoOption;
  let newName;
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const repoValue = readAlternateFlagValue(args, index, ["--repo", "-R"]);
    if (repoValue.value !== void 0) {
      repoOption = repoValue.value;
      index = repoValue.nextIndex;
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh repo rename: unsupported option '${arg}'
`, 2);
    }
    if (newName) {
      return err("gh repo rename: too many arguments\n", 2);
    }
    newName = arg;
  }
  if (!newName) {
    return err("Usage: gh repo rename <new-name> [-R OWNER/REPO]\n", 2);
  }
  const coordinates = await resolveRepoTarget(void 0, repoOption, ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return err(`gh repo rename: ${coordinates.stderr.replace(/^gh repo:\s*/, "")}`, coordinates.exitCode);
  }
  let repository;
  try {
    const response = await fetchViaProxy(
      `https://api.github.com/repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.repoName)}`,
      {
        method: "PATCH",
        headers: {
          Authorization: `Bearer ${config.oauth_token}`,
          Accept: "application/vnd.github+json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ name: newName })
      }
    );
    const text = await response.text();
    if (!response.ok) {
      return err(`gh: API error (${response.status}): ${text}
`);
    }
    repository = text ? JSON.parse(text) : {};
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
  const nextCoordinates = {
    owner: typeof ((_a = repository.owner) == null ? void 0 : _a.login) === "string" ? repository.owner.login : coordinates.owner,
    repoName: typeof repository.name === "string" ? repository.name : newName
  };
  const remoteUrl = typeof repository.clone_url === "string" ? repository.clone_url : `https://github.com/${nextCoordinates.owner}/${nextCoordinates.repoName}.git`;
  const htmlUrl = typeof repository.html_url === "string" ? repository.html_url : `https://github.com/${nextCoordinates.owner}/${nextCoordinates.repoName}`;
  const output = [
    `Renamed repository ${coordinates.owner}/${coordinates.repoName} to ${nextCoordinates.owner}/${nextCoordinates.repoName}
`,
    `${htmlUrl}
`
  ];
  const currentDefault = readDefaultRepoCoordinates(vfs);
  if (currentDefault && repoCoordinatesEqual(currentDefault, coordinates)) {
    writeDefaultRepoCoordinates(vfs, nextCoordinates);
    output.push("Updated default repository\n");
  }
  const currentOrigin = await inferRepoCoordinatesFromOrigin(ctx, vfs);
  if (currentOrigin && repoCoordinatesEqual(currentOrigin, coordinates)) {
    const remoteResult = await syncRepoRemote(ctx.cwd, "origin", remoteUrl, ctx, vfs);
    if (remoteResult.exitCode === 0) {
      output.push("Updated remote 'origin'\n");
    }
  }
  return ok(output.join(""));
}
async function repoEdit(args, ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let repoInput;
  let repoOption;
  let acceptVisibilityChangeConsequences = false;
  const body = {};
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const repoValue = readAlternateFlagValue(args, index, ["--repo", "-R"]);
    if (repoValue.value !== void 0) {
      repoOption = repoValue.value;
      index = repoValue.nextIndex;
      continue;
    }
    if (arg === "--accept-visibility-change-consequences") {
      acceptVisibilityChangeConsequences = true;
      continue;
    }
    const descriptionValue = readAlternateFlagValue(args, index, ["--description", "-d"]);
    if (descriptionValue.value !== void 0) {
      body.description = descriptionValue.value;
      index = descriptionValue.nextIndex;
      continue;
    }
    const homepageValue = readAlternateFlagValue(args, index, ["--homepage", "-h"]);
    if (homepageValue.value !== void 0) {
      body.homepage = homepageValue.value;
      index = homepageValue.nextIndex;
      continue;
    }
    const defaultBranchValue = readFlagValue(args, index, "--default-branch");
    if (defaultBranchValue.value !== void 0) {
      body.default_branch = defaultBranchValue.value;
      index = defaultBranchValue.nextIndex;
      continue;
    }
    const visibilityValue = readFlagValue(args, index, "--visibility");
    if (visibilityValue.value !== void 0) {
      const visibility = visibilityValue.value.toLowerCase();
      if (!["public", "private"].includes(visibility)) {
        return err(`gh repo edit: unsupported visibility '${visibilityValue.value}'
`, 2);
      }
      body.visibility = visibility;
      index = visibilityValue.nextIndex;
      continue;
    }
    const booleanFields = [
      ["--enable-issues", "has_issues"],
      ["--enable-wiki", "has_wiki"],
      ["--enable-projects", "has_projects"],
      ["--enable-discussions", "has_discussions"],
      ["--template", "is_template"],
      ["--allow-forking", "allow_forking"],
      ["--delete-branch-on-merge", "delete_branch_on_merge"],
      ["--allow-update-branch", "allow_update_branch"],
      ["--enable-merge-commit", "allow_merge_commit"],
      ["--enable-rebase-merge", "allow_rebase_merge"],
      ["--enable-squash-merge", "allow_squash_merge"],
      ["--enable-auto-merge", "allow_auto_merge"]
    ];
    let matchedBoolean = false;
    for (const [flag, field] of booleanFields) {
      const flagValue = readBooleanFlagValue(arg, flag);
      if (flagValue !== void 0) {
        body[field] = flagValue;
        matchedBoolean = true;
        break;
      }
    }
    if (matchedBoolean) {
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh repo edit: unsupported option '${arg}'
`, 2);
    }
    if (repoInput) {
      return err("gh repo edit: too many arguments\n", 2);
    }
    repoInput = arg;
  }
  if ("visibility" in body && !acceptVisibilityChangeConsequences) {
    return err(
      "gh repo edit: changing repository visibility requires --accept-visibility-change-consequences\n",
      2
    );
  }
  if (Object.keys(body).length === 0) {
    return err("gh repo edit: no updates specified\n", 2);
  }
  const coordinates = await resolveRepoTarget(repoInput, repoOption, ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return err(`gh repo edit: ${coordinates.stderr.replace(/^gh repo:\s*/, "")}`, coordinates.exitCode);
  }
  let repository;
  try {
    const response = await fetchViaProxy(
      `https://api.github.com/repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.repoName)}`,
      {
        method: "PATCH",
        headers: {
          Authorization: `Bearer ${config.oauth_token}`,
          Accept: "application/vnd.github+json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(body)
      }
    );
    const text = await response.text();
    if (!response.ok) {
      return err(`gh: API error (${response.status}): ${text}
`);
    }
    repository = text ? JSON.parse(text) : {};
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
  return ok(
    `Updated repository ${repository.full_name ?? `${coordinates.owner}/${coordinates.repoName}`}
${repository.html_url ?? `https://github.com/${coordinates.owner}/${coordinates.repoName}`}
`
  );
}
async function runRepo(args, ctx, vfs) {
  const sub = args[0];
  switch (sub) {
    case "list":
    case "ls":
      return repoList(args.slice(1), ctx, vfs);
    case "view":
      return repoView(args.slice(1), ctx, vfs);
    case "clone":
      return repoClone(args.slice(1), ctx, vfs);
    case "create":
      return repoCreate(args.slice(1), ctx, vfs);
    case "edit":
      return repoEdit(args.slice(1), ctx, vfs);
    case "delete":
      return repoDelete(args.slice(1), ctx, vfs);
    case "rename":
      return repoRename(args.slice(1), ctx, vfs);
    case "set-default":
      return repoSetDefault(args.slice(1), ctx, vfs);
    default:
      return err(
        `Usage: gh repo <command>

Available commands:
  list, ls    List repositories owned by user or organization
  view        View a repository
  clone       Clone a repository locally
  create      Create a repository on GitHub and optionally wire a local remote
  edit        Edit repository settings on GitHub
  rename      Rename a repository on GitHub
  delete      Delete a repository on GitHub
  set-default Set the default repository for future gh commands
`
      );
  }
}
async function githubApiJson(token, url, init = {}) {
  const headers = {
    Authorization: `Bearer ${token}`,
    Accept: "application/vnd.github+json",
    ...init.headers
  };
  const response = await fetchViaProxy(url, { ...init, headers });
  const text = await response.text();
  let body = null;
  try {
    body = text ? JSON.parse(text) : null;
  } catch {
  }
  return { status: response.status, ok: response.ok, body, text };
}
function prState(pr) {
  if (pr.merged_at) return "MERGED";
  return typeof pr.state === "string" ? pr.state.toUpperCase() : "OPEN";
}
function prStateDisplay(pr) {
  if (pr.merged_at) return "Merged";
  if (pr.state === "closed") return "Closed";
  if (pr.draft) return "Draft";
  return "Open";
}
const PR_JSON_FIELDS = {
  number: (pr) => pr.number,
  title: (pr) => pr.title,
  state: (pr) => prState(pr),
  url: (pr) => pr.html_url,
  baseRefName: (pr) => {
    var _a;
    return ((_a = pr.base) == null ? void 0 : _a.ref) ?? null;
  },
  headRefName: (pr) => {
    var _a;
    return ((_a = pr.head) == null ? void 0 : _a.ref) ?? null;
  },
  isDraft: (pr) => Boolean(pr.draft)
};
function formatPrJson(pr, fields) {
  const obj = {};
  for (const field of fields) {
    obj[field] = PR_JSON_FIELDS[field] ? PR_JSON_FIELDS[field](pr) : pr[field] ?? null;
  }
  return obj;
}
async function currentGitBranch(ctx, vfs) {
  try {
    const result = await runGitCommand(["rev-parse", "--abbrev-ref", "HEAD"], ctx, vfs);
    if (result.exitCode !== 0) return null;
    const branch = result.stdout.trim();
    return branch && branch !== "HEAD" ? branch : null;
  } catch {
    return null;
  }
}
async function latestCommitMessage(ctx, vfs) {
  let result;
  try {
    result = await runGitCommand(["log", "-n", "1"], ctx, vfs);
  } catch {
    return null;
  }
  if (result.exitCode !== 0 || !result.stdout.trim()) {
    return null;
  }
  const messageLines = [];
  let inMessage = false;
  for (const line of result.stdout.split("\n")) {
    if (!inMessage) {
      if (line === "") inMessage = true;
      continue;
    }
    if (line.startsWith("    ")) {
      messageLines.push(line.slice(4));
    } else if (line === "") {
      messageLines.push("");
    }
  }
  while (messageLines.length > 0 && messageLines[messageLines.length - 1] === "") {
    messageLines.pop();
  }
  if (messageLines.length === 0) {
    return null;
  }
  return {
    title: messageLines[0],
    body: messageLines.slice(1).join("\n").trim()
  };
}
async function findOpenPrForBranch(token, coordinates, branch) {
  const url = `https://api.github.com/repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.repoName)}/pulls?head=${encodeURIComponent(coordinates.owner)}:${encodeURIComponent(branch)}&state=open`;
  const result = await githubApiJson(token, url);
  if (!result.ok) {
    return { error: err(`gh: API error (${result.status}): ${result.text}
`) };
  }
  const pulls = Array.isArray(result.body) ? result.body : [];
  return { pr: pulls.length > 0 ? pulls[0] : null };
}
async function prCreate(args, ctx, vfs) {
  var _a, _b, _c, _d;
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let title;
  let bodyText;
  let base;
  let head;
  let repoOption;
  let draft = false;
  let fill = false;
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    if (arg === "--draft" || arg === "-d") {
      draft = true;
      continue;
    }
    if (arg === "--fill" || arg === "-f") {
      fill = true;
      continue;
    }
    const titleValue = readAlternateFlagValue(args, index, ["--title", "-t"]);
    if (titleValue.value !== void 0) {
      title = titleValue.value;
      index = titleValue.nextIndex;
      continue;
    }
    const bodyValue = readAlternateFlagValue(args, index, ["--body", "-b"]);
    if (bodyValue.value !== void 0) {
      bodyText = bodyValue.value;
      index = bodyValue.nextIndex;
      continue;
    }
    const baseValue = readAlternateFlagValue(args, index, ["--base", "-B"]);
    if (baseValue.value !== void 0) {
      base = baseValue.value;
      index = baseValue.nextIndex;
      continue;
    }
    const headValue = readAlternateFlagValue(args, index, ["--head", "-H"]);
    if (headValue.value !== void 0) {
      head = headValue.value;
      index = headValue.nextIndex;
      continue;
    }
    const repoValue = readAlternateFlagValue(args, index, ["--repo", "-R"]);
    if (repoValue.value !== void 0) {
      repoOption = repoValue.value;
      index = repoValue.nextIndex;
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh pr create: unsupported option '${arg}'
`, 2);
    }
    return err("gh pr create: too many arguments\n", 2);
  }
  const coordinates = await resolveRepoTarget(void 0, repoOption, ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return err(`gh pr create: ${coordinates.stderr.replace(/^gh repo:\s*/, "")}`, coordinates.exitCode);
  }
  if (!head) {
    const branch = await currentGitBranch(ctx, vfs);
    if (!branch) {
      return err("gh pr create: could not determine the current branch. Specify one with --head.\n", 2);
    }
    head = branch;
  }
  if (fill && (title === void 0 || bodyText === void 0)) {
    const commit = await latestCommitMessage(ctx, vfs);
    if (!commit) {
      return err("gh pr create: --fill requires at least one commit on the current branch\n", 2);
    }
    title ?? (title = commit.title);
    bodyText ?? (bodyText = commit.body);
  }
  if (!title) {
    return err("gh pr create: --title or --fill is required\n", 2);
  }
  const repoApiUrl = `https://api.github.com/repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.repoName)}`;
  try {
    if (!base) {
      const repoInfo = await githubApiJson(config.oauth_token, repoApiUrl);
      if (!repoInfo.ok) {
        return err(`gh: API error (${repoInfo.status}): ${repoInfo.text}
`);
      }
      base = typeof ((_a = repoInfo.body) == null ? void 0 : _a.default_branch) === "string" ? repoInfo.body.default_branch : "main";
    }
    const result = await githubApiJson(config.oauth_token, `${repoApiUrl}/pulls`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        title,
        head,
        base,
        body: bodyText ?? "",
        draft
      })
    });
    if (!result.ok) {
      const headInvalid = result.status === 422 && Array.isArray((_b = result.body) == null ? void 0 : _b.errors) && result.body.errors.some((e) => (e == null ? void 0 : e.field) === "head");
      if (headInvalid) {
        return err(
          `gh pr create: the head branch '${head}' does not exist on ${coordinates.owner}/${coordinates.repoName}.
Push it first with: git push -u origin ${head}
`
        );
      }
      return err(`gh: API error (${result.status}): ${result.text}
`);
    }
    const htmlUrl = typeof ((_c = result.body) == null ? void 0 : _c.html_url) === "string" ? result.body.html_url : `https://github.com/${coordinates.owner}/${coordinates.repoName}/pull/${((_d = result.body) == null ? void 0 : _d.number) ?? ""}`;
    return ok(`${htmlUrl}
`);
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
async function prView(args, ctx, vfs) {
  var _a, _b, _c;
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let numberInput;
  let repoOption;
  let jsonFields = null;
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const repoValue = readAlternateFlagValue(args, index, ["--repo", "-R"]);
    if (repoValue.value !== void 0) {
      repoOption = repoValue.value;
      index = repoValue.nextIndex;
      continue;
    }
    if (arg === "--json" && index + 1 < args.length) {
      jsonFields = args[++index].split(",");
      continue;
    }
    if (arg.startsWith("--json=")) {
      jsonFields = arg.slice("--json=".length).split(",");
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh pr view: unsupported option '${arg}'
`, 2);
    }
    if (numberInput) {
      return err("gh pr view: too many arguments\n", 2);
    }
    numberInput = arg;
  }
  const coordinates = await resolveRepoTarget(void 0, repoOption, ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return err(`gh pr view: ${coordinates.stderr.replace(/^gh repo:\s*/, "")}`, coordinates.exitCode);
  }
  try {
    let pr;
    if (numberInput) {
      const number = parseInt(numberInput.replace(/^#/, ""), 10);
      if (!Number.isFinite(number)) {
        return err(`gh pr view: invalid pull request number '${numberInput}'
`, 2);
      }
      const result = await githubApiJson(
        config.oauth_token,
        `https://api.github.com/repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.repoName)}/pulls/${number}`
      );
      if (!result.ok) {
        return err(`gh: API error (${result.status}): ${result.text}
`);
      }
      pr = result.body ?? {};
    } else {
      const branch = await currentGitBranch(ctx, vfs);
      if (!branch) {
        return err("gh pr view: could not determine the current branch. Specify a pull request number.\n", 2);
      }
      const found = await findOpenPrForBranch(config.oauth_token, coordinates, branch);
      if ("error" in found) {
        return found.error;
      }
      if (!found.pr) {
        return err(`no pull requests found for branch "${branch}"
`);
      }
      pr = found.pr;
    }
    if (jsonFields) {
      return ok(`${JSON.stringify(formatPrJson(pr, jsonFields), null, 2)}
`);
    }
    const lines = [
      `${pr.title} #${pr.number}`,
      `${prStateDisplay(pr)} • ${((_a = pr.user) == null ? void 0 : _a.login) ?? "unknown"} wants to merge into ${((_b = pr.base) == null ? void 0 : _b.ref) ?? "?"} from ${((_c = pr.head) == null ? void 0 : _c.ref) ?? "?"}`
    ];
    if (pr.body) {
      lines.push("", String(pr.body).trimEnd());
    }
    lines.push("", `View this pull request on GitHub: ${pr.html_url}`);
    return ok(`${lines.join("\n")}
`);
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
async function prList(args, ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let state = "open";
  let limit = 30;
  let repoOption;
  let jsonFields = null;
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const stateValue = readAlternateFlagValue(args, index, ["--state", "-s"]);
    if (stateValue.value !== void 0) {
      state = stateValue.value.toLowerCase();
      index = stateValue.nextIndex;
      continue;
    }
    const limitValue = readAlternateFlagValue(args, index, ["--limit", "-L"]);
    if (limitValue.value !== void 0) {
      limit = parseInt(limitValue.value, 10) || 30;
      index = limitValue.nextIndex;
      continue;
    }
    const repoValue = readAlternateFlagValue(args, index, ["--repo", "-R"]);
    if (repoValue.value !== void 0) {
      repoOption = repoValue.value;
      index = repoValue.nextIndex;
      continue;
    }
    if (arg === "--json" && index + 1 < args.length) {
      jsonFields = args[++index].split(",");
      continue;
    }
    if (arg.startsWith("--json=")) {
      jsonFields = arg.slice("--json=".length).split(",");
      continue;
    }
    if (arg.startsWith("-")) {
      return err(`gh pr list: unsupported option '${arg}'
`, 2);
    }
    return err("gh pr list: too many arguments\n", 2);
  }
  if (!["open", "closed", "merged", "all"].includes(state)) {
    return err(`gh pr list: invalid state '${state}'
`, 2);
  }
  const coordinates = await resolveRepoTarget(void 0, repoOption, ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return err(`gh pr list: ${coordinates.stderr.replace(/^gh repo:\s*/, "")}`, coordinates.exitCode);
  }
  const apiState = state === "merged" ? "closed" : state;
  const perPage = Math.min(Math.max(limit, 30), 100);
  try {
    const result = await githubApiJson(
      config.oauth_token,
      `https://api.github.com/repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.repoName)}/pulls?state=${apiState}&per_page=${perPage}`
    );
    if (!result.ok) {
      return err(`gh: API error (${result.status}): ${result.text}
`);
    }
    let pulls = Array.isArray(result.body) ? result.body : [];
    if (state === "merged") {
      pulls = pulls.filter((pr) => pr.merged_at);
    }
    pulls = pulls.slice(0, limit);
    if (jsonFields) {
      return ok(`${JSON.stringify(pulls.map((pr) => formatPrJson(pr, jsonFields)), null, 2)}
`);
    }
    if (pulls.length === 0) {
      return ok(`no pull requests match your search in ${coordinates.owner}/${coordinates.repoName}
`);
    }
    const lines = pulls.map(
      (pr) => {
        var _a;
        return `#${pr.number}	${pr.title}	${((_a = pr.head) == null ? void 0 : _a.ref) ?? ""}	${prState(pr)}`;
      }
    );
    return ok(`${lines.join("\n")}
`);
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
async function prStatus(args, ctx, vfs) {
  const host = "github.com";
  const config = readGhToken(vfs, host);
  if (!config || !config.oauth_token) {
    return err("gh: not logged in. Run `gh auth login` first.\n");
  }
  let repoOption;
  for (let index = 0; index < args.length; index += 1) {
    const repoValue = readAlternateFlagValue(args, index, ["--repo", "-R"]);
    if (repoValue.value !== void 0) {
      repoOption = repoValue.value;
      index = repoValue.nextIndex;
      continue;
    }
    return err(`gh pr status: unsupported option '${args[index]}'
`, 2);
  }
  const coordinates = await resolveRepoTarget(void 0, repoOption, ctx, vfs, config.user);
  if ("exitCode" in coordinates) {
    return err(`gh pr status: ${coordinates.stderr.replace(/^gh repo:\s*/, "")}`, coordinates.exitCode);
  }
  const branch = await currentGitBranch(ctx, vfs);
  try {
    const result = await githubApiJson(
      config.oauth_token,
      `https://api.github.com/repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.repoName)}/pulls?state=open&per_page=100`
    );
    if (!result.ok) {
      return err(`gh: API error (${result.status}): ${result.text}
`);
    }
    const pulls = Array.isArray(result.body) ? result.body : [];
    const currentPrs = branch ? pulls.filter((pr) => {
      var _a;
      return ((_a = pr.head) == null ? void 0 : _a.ref) === branch;
    }) : [];
    const minePrs = pulls.filter((pr) => {
      var _a;
      return ((_a = pr.user) == null ? void 0 : _a.login) === config.user;
    });
    const formatLine = (pr) => {
      var _a;
      return `  #${pr.number}  ${pr.title} [${((_a = pr.head) == null ? void 0 : _a.ref) ?? ""}]${pr.draft ? " • Draft" : ""}`;
    };
    const lines = [`Relevant pull requests in ${coordinates.owner}/${coordinates.repoName}`, ""];
    lines.push("Current branch");
    if (!branch) {
      lines.push("  There is no current branch");
    } else if (currentPrs.length === 0) {
      lines.push(`  There is no pull request associated with [${branch}]`);
    } else {
      lines.push(...currentPrs.map(formatLine));
    }
    lines.push("", "Created by you");
    if (minePrs.length === 0) {
      lines.push("  You have no open pull requests");
    } else {
      lines.push(...minePrs.map(formatLine));
    }
    return ok(`${lines.join("\n")}
`);
  } catch (e) {
    return err(`gh: ${e instanceof Error ? e.message : String(e)}
`);
  }
}
async function runPr(args, ctx, vfs) {
  const sub = args[0];
  switch (sub) {
    case "create":
      return prCreate(args.slice(1), ctx, vfs);
    case "view":
      return prView(args.slice(1), ctx, vfs);
    case "list":
    case "ls":
      return prList(args.slice(1), ctx, vfs);
    case "status":
      return prStatus(args.slice(1), ctx, vfs);
    default:
      return err(
        `Usage: gh pr <command>

Available commands:
  create      Create a pull request
  view        View a pull request
  list, ls    List pull requests in a repository
  status      Show status of relevant pull requests
`
      );
  }
}
async function runGhCommand(args, ctx, vfs, keychain) {
  const sub = args[0];
  if (!sub || sub === "help" || sub === "--help") {
    return ok(
      `Usage: gh <command> <subcommand> [flags]

Available commands:
  auth        Authenticate gh and git with GitHub
  api         Make an authenticated GitHub API request
  repo        Manage repositories
  pr          Manage pull requests

Run 'gh <command> --help' for more information about a command.
`
    );
  }
  if (sub === "--version" || sub === "version") {
    return ok("gh version 2.62.0 (almostnode)\n");
  }
  switch (sub) {
    case "auth":
      return runAuth(args.slice(1), ctx, vfs, keychain);
    case "api":
      return runApi(args.slice(1), ctx, vfs);
    case "repo":
      return runRepo(args.slice(1), ctx, vfs);
    case "pr":
      return runPr(args.slice(1), ctx, vfs);
    default:
      return err(`gh: '${sub}' is not a gh command. See 'gh --help'.
`);
  }
}
export {
  runGhCommand
};
//# sourceMappingURL=gh-command-B_e8T3FD.js.map
