import { ExitProcessError } from './chunk-SMOOGNGG.js';
import './chunk-Y45LX2LV.js';
import { init_esm_shims } from './chunk-LC652GLE.js';
import { promises } from 'fs';
import { consola } from 'consola';
import { execa } from 'execa';
import { findUp } from 'find-up';

// src/commands/branch/install/installCommand.mts
init_esm_shims();

// src/commands/branch/utils/getGitBranch.ts
init_esm_shims();
async function getGitBranch() {
  try {
    const {
      stdout
    } = await execa("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
    return stdout.trim();
  } catch {
    return void 0;
  }
}

// src/commands/branch/utils/resolveBranchedPackages.mts
init_esm_shims();

// src/commands/branch/utils/inferSdkCandidates.ts
init_esm_shims();
var SDK_NAME_RE = /^@[a-z0-9-]+\/sdk$/u;
function inferSdkCandidates(packageJson) {
  const allDeps = {
    ...packageJson.dependencies,
    ...packageJson.devDependencies,
    ...packageJson.optionalDependencies,
    ...packageJson.peerDependencies
  };
  return Object.keys(allDeps).filter((name) => SDK_NAME_RE.test(name));
}

// src/commands/branch/utils/resolveBranch.ts
init_esm_shims();
var NON_BRANCH = /* @__PURE__ */ new Set(["main", "master", "HEAD"]);
function resolveBranch(argBranch, gitBranch) {
  if (argBranch != null && argBranch.trim() !== "") {
    return argBranch.trim();
  }
  const branch = gitBranch?.trim();
  if (branch == null || branch === "" || NON_BRANCH.has(branch)) {
    return void 0;
  }
  return branch;
}

// src/commands/branch/utils/selectDistTag.ts
init_esm_shims();
function selectDistTag({
  branch,
  availableTags
}) {
  const exact = `${branch}-latest`;
  return availableTags.includes(exact) ? exact : void 0;
}

// src/commands/branch/utils/resolveBranchedPackages.mts
async function resolveFoundryBranch(args, deps) {
  const gitBranch = args.branchName == null ? await deps.getGitBranch() : void 0;
  return resolveBranch(args.branchName, gitBranch);
}
async function resolveBranchedPackages(branch, args, deps) {
  const packageJson = await readPackageJson(deps);
  const candidates = args.packageName != null ? [args.packageName] : inferSdkCandidates(packageJson);
  if (candidates.length === 0) {
    throw new ExitProcessError(1, "No Foundry SDK dependency (@<scope>/sdk) found in package.json.", "Pass --packageName <name> if your SDK uses a different name.");
  }
  const packages = [];
  for (const candidate of candidates) {
    const branched = await probeBranchedPackage(candidate, branch, packageJson, deps);
    if (branched != null) packages.push(branched);
  }
  return packages;
}
async function probeBranchedPackage(candidate, branch, packageJson, deps) {
  let tags;
  try {
    tags = await deps.npmDistTags(candidate);
  } catch (e) {
    if (isNotFound(e)) return void 0;
    throw mapNpmViewError(e, candidate);
  }
  const tagName = selectDistTag({
    branch,
    availableTags: Object.keys(tags)
  });
  if (tagName == null) return void 0;
  const version = tags[tagName];
  if (version == null) return void 0;
  return {
    pkg: candidate,
    version,
    current: readDeclaredVersion(packageJson, candidate)
  };
}
async function readPackageJson(deps) {
  const packageJsonPath = await findUp("package.json", {
    cwd: deps.cwd
  });
  if (packageJsonPath == null) {
    throw new ExitProcessError(1, "Could not find a package.json in the current directory or any parent.", "Run `osdk unstable branch` from within your project.");
  }
  try {
    return JSON.parse(await deps.readFile(packageJsonPath));
  } catch (e) {
    throw new ExitProcessError(1, `Could not read ${packageJsonPath}.`, "Ensure it is valid JSON.", e instanceof Error ? e : void 0);
  }
}
function readDeclaredVersion(pkgJson, name) {
  return pkgJson.dependencies?.[name] ?? pkgJson.devDependencies?.[name] ?? pkgJson.optionalDependencies?.[name] ?? pkgJson.peerDependencies?.[name];
}
function isNotFound(e) {
  const detail = e instanceof Error ? e.message : String(e);
  return /E404|404 Not Found/iu.test(detail);
}
function mapNpmViewError(e, pkg) {
  const detail = e instanceof Error ? e.message : String(e);
  if (/E401|Unauthorized/iu.test(detail)) {
    return new ExitProcessError(1, `Not authorized to read ${pkg}.`, "Ensure FOUNDRY_TOKEN is set and your .npmrc registry is correct.", e instanceof Error ? e : void 0);
  }
  return new ExitProcessError(1, `Failed to read dist tags for ${pkg}.`);
}

// src/commands/branch/utils/runNpm.ts
init_esm_shims();
async function npmDistTags(pkg) {
  const {
    stdout
  } = await execa("npm", ["view", pkg, "dist-tags", "--json"]);
  const trimmed = stdout.trim();
  return trimmed === "" ? {} : JSON.parse(trimmed);
}
async function npmInstall(specs) {
  if (specs.length === 0) return;
  await execa("npm", ["install", ...specs.map((s) => `${s.pkg}@${s.version}`), "--save-exact"]);
}

// src/commands/branch/install/installCommand.mts
async function installCommand(args, overrides = {}) {
  const deps = {
    getGitBranch,
    npmDistTags,
    npmInstall,
    readFile: (p) => promises.readFile(p, "utf-8"),
    cwd: process.cwd(),
    ...overrides
  };
  const branch = await resolveFoundryBranch(args, deps);
  if (branch == null) {
    consola.info("On main or no determinable branch \u2014 nothing to sync. Use --branchName to force.");
    return;
  }
  const packages = await resolveBranchedPackages(branch, args, deps);
  if (packages.length === 0) {
    consola.info(`No branched release for "${branch}" yet \u2014 nothing to sync.`);
    return;
  }
  const toInstall = packages.filter((p) => p.current !== p.version);
  const alreadyInSync = packages.length - toInstall.length;
  if (toInstall.length === 0) {
    consola.info(`All ${packages.length} branched SDK(s) already in sync for "${branch}".`);
    return;
  }
  if (args.dryRun) {
    for (const p of toInstall) {
      consola.info(`Would install ${p.pkg}@${p.version} (currently ${p.current ?? "unset"}).`);
    }
    return;
  }
  try {
    await deps.npmInstall(toInstall.map((p) => ({
      pkg: p.pkg,
      version: p.version
    })));
  } catch (e) {
    const detail = e instanceof Error ? e.stderr ?? e.message : String(e);
    throw new ExitProcessError(1, `Failed to install ${toInstall.length} branched SDK(s).`, `Check your network and .npmrc registry auth (FOUNDRY_TOKEN), then re-run.
${detail}`, e instanceof Error ? e : void 0);
  }
  for (const p of toInstall) {
    consola.success(`${p.pkg}: ${p.current ?? "unset"} \u2192 ${p.version}`);
  }
  consola.success(`Synced ${toInstall.length} branched SDK(s)${alreadyInSync > 0 ? ` (${alreadyInSync} already in sync)` : ""}`);
}

export { installCommand as default };
//# sourceMappingURL=installCommand-HFVJK5V6.js.map
//# sourceMappingURL=installCommand-HFVJK5V6.js.map