import {
  addNPMDependencies,
  checkForNewVersion,
  findUpAndReadPackageJson,
  getPackageManager,
  usesWorkspaces
} from "./chunk-HJBER2P6.js";
import {
  AbortError,
  exec,
  findPathUp,
  glob,
  outputContent,
  outputInfo,
  outputSuccess,
  outputToken,
  outputWarn
} from "./chunk-LA4HX5WI.js";
import {
  dirname,
  joinPath,
  moduleDirectory
} from "./chunk-T2GATXSP.js";
import {
  init_cjs_shims
} from "./chunk-POZ5MGPT.js";

// src/cli/services/upgrade.ts
init_cjs_shims();
var globalPlugins = ["@shopify/theme"];
async function upgrade(directory, currentVersion, { env } = { env: process.env }) {
  let newestVersion, projectDir = await getProjectDir(directory);
  if (projectDir)
    newestVersion = await upgradeLocalShopify(projectDir, currentVersion);
  else {
    if (usingPackageManager({ env }))
      throw new AbortError(
        outputContent`Couldn't find an app toml file at ${outputToken.path(
          directory
        )}, is this a Shopify project directory?`
      );
    newestVersion = await upgradeGlobalShopify(currentVersion, { env });
  }
  newestVersion && outputSuccess(`Upgraded Shopify CLI to version ${newestVersion}`);
}
async function getProjectDir(directory) {
  let configFiles = ["shopify.app{,.*}.toml", "hydrogen.config.js", "hydrogen.config.ts"], configFile = await findPathUp(async (directory2) => {
    let configPaths = await glob(configFiles.map((file) => joinPath(directory2, file)));
    return configPaths.length > 0 ? configPaths[0] : void 0;
  }, {
    cwd: directory,
    type: "file"
  });
  if (configFile)
    return dirname(configFile);
}
async function upgradeLocalShopify(projectDir, currentVersion) {
  let packageJson = (await findUpAndReadPackageJson(projectDir)).content, packageJsonDependencies = packageJson.dependencies || {}, packageJsonDevDependencies = packageJson.devDependencies || {}, allDependencies = { ...packageJsonDependencies, ...packageJsonDevDependencies }, resolvedCLIVersion = allDependencies[await cliDependency()], resolvedAppVersion = allDependencies["@shopify/app"]?.replace(/[\^~]/, "");
  resolvedCLIVersion.slice(0, 1).match(/[\^~]/) && (resolvedCLIVersion = currentVersion);
  let newestCLIVersion = await checkForNewVersion(await cliDependency(), resolvedCLIVersion), newestAppVersion = resolvedAppVersion ? await checkForNewVersion("@shopify/app", resolvedAppVersion) : void 0;
  if (newestCLIVersion)
    outputUpgradeMessage(resolvedCLIVersion, newestCLIVersion);
  else if (resolvedAppVersion && newestAppVersion)
    outputUpgradeMessage(resolvedAppVersion, newestAppVersion);
  else {
    outputWontInstallMessage(resolvedCLIVersion);
    return;
  }
  return await installJsonDependencies("prod", packageJsonDependencies, projectDir), await installJsonDependencies("dev", packageJsonDevDependencies, projectDir), newestCLIVersion ?? newestAppVersion;
}
async function upgradeGlobalShopify(currentVersion, { env } = { env: process.env }) {
  let newestVersion = await checkForNewVersion(await cliDependency(), currentVersion);
  if (!newestVersion) {
    outputWontInstallMessage(currentVersion);
    return;
  }
  outputUpgradeMessage(currentVersion, newestVersion);
  let homebrewPackage = env.SHOPIFY_HOMEBREW_FORMULA;
  try {
    if (homebrewPackage)
      throw new AbortError(
        outputContent`Upgrade only works for packages managed by a Node package manager (e.g. npm). Run ${outputToken.genericShellCommand(
          "brew upgrade && brew update"
        )} instead`
      );
    await upgradeGlobalViaNpm();
  } catch (err) {
    throw outputWarn("Upgrade failed!"), err;
  }
  return newestVersion;
}
async function upgradeGlobalViaNpm() {
  let command = "npm", args = [
    "install",
    "-g",
    `${await cliDependency()}@latest`,
    ...globalPlugins.map((plugin) => `${plugin}@latest`)
  ];
  outputInfo(
    outputContent`Attempting to upgrade via ${outputToken.genericShellCommand([command, ...args].join(" "))}...`
  ), await exec(command, args, { stdio: "inherit" });
}
function outputWontInstallMessage(currentVersion) {
  outputInfo(outputContent`You're on the latest version, ${outputToken.yellow(currentVersion)}, no need to upgrade!`);
}
function outputUpgradeMessage(currentVersion, newestVersion) {
  outputInfo(
    outputContent`Upgrading CLI from ${outputToken.yellow(currentVersion)} to ${outputToken.yellow(newestVersion)}...`
  );
}
async function installJsonDependencies(depsEnv, deps, directory) {
  let packagesToUpdate = [await cliDependency(), ...await oclifPlugins()].filter((pkg) => !!deps[pkg]).map((pkg) => ({ name: pkg, version: "latest" })), appUsesWorkspaces = await usesWorkspaces(directory);
  packagesToUpdate.length > 0 && await addNPMDependencies(packagesToUpdate, {
    packageManager: await getPackageManager(directory),
    type: depsEnv,
    directory,
    stdout: process.stdout,
    stderr: process.stderr,
    addToRootDirectory: appUsesWorkspaces
  });
}
async function cliDependency() {
  return (await packageJsonContents()).name;
}
async function oclifPlugins() {
  return (await packageJsonContents())?.oclif?.plugins || [];
}
var _packageJsonContents;
async function packageJsonContents() {
  if (!_packageJsonContents) {
    let packageJson = await findUpAndReadPackageJson(moduleDirectory(import.meta.url));
    _packageJsonContents = _packageJsonContents || packageJson.content;
  }
  return _packageJsonContents;
}
function usingPackageManager({ env } = { env: process.env }) {
  return !!env.npm_config_user_agent;
}

export {
  upgrade
};
//# sourceMappingURL=chunk-6XVKAPA7.js.map
