import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  npmDependenciesLockFileResponseSchema,
  resolveNpmDependenciesSchema
} from "./chunk-KB3GWH37.js";
import {
  httpRequest
} from "./chunk-RW55Y77T.js";
import {
  VELO_DEPENDENCIES_CONFIG_PATH,
  getVeloDependenciesConfigPath,
  veloDependenciesConfigSchema
} from "./chunk-4BLGYECY.js";
import {
  getResolveNpmDependenciesResult,
  resolveNpmDependencies
} from "./chunk-KDZXPOOF.js";
import {
  NPM,
  Yarn,
  createPackageManager,
  getRepoType
} from "./chunk-KUSCYV4K.js";
import {
  isHttpError,
  pWaitFor
} from "./chunk-YHFCDWGT.js";
import {
  DEPENDENCIES_METADATA_FILENAME,
  WIX_LOCK_FILENAME
} from "./chunk-YT5BPQDJ.js";
import {
  outputFile,
  pathExists,
  readJson,
  writeJson
} from "./chunk-AYCGCYN3.js";
import {
  CliError,
  CliErrorCode
} from "./chunk-WGV2XQSB.js";
import {
  init_esm_shims
} from "./chunk-EXLZF52D.js";

// ../cli-site-old/src/velo-npm/any-npm-migration.ts
init_esm_shims();
import { unlink } from "node:fs/promises";

// ../cli-site-old/src/files/package-json.ts
init_esm_shims();
import { join } from "node:path";
async function getDependencies(projectFolder) {
  const packageJsonPath = join(projectFolder, "package.json");
  const packageJson = await readJson(packageJsonPath);
  return Object.entries(packageJson.dependencies ?? {}).map(
    ([name, version]) => ({ name, version })
  );
}
async function addDependenciesToPackageJson(projectFolder, dependenciesConfig) {
  const packageJsonPath = join(projectFolder, "package.json");
  const packageJson = await readJson(packageJsonPath);
  if (packageJson.dependencies && Object.keys(packageJson.dependencies).length > 0) {
    throw new CliError({
      code: CliErrorCode.FailedMigrationToAnyNpm(),
      cause: null
    });
  }
  packageJson.dependencies = {};
  for (const dependencyPackageName of Object.keys(
    dependenciesConfig.dependencies
  )) {
    if (packageJson.devDependencies?.[dependencyPackageName]) {
      delete packageJson.devDependencies[dependencyPackageName];
    }
    packageJson.dependencies[dependencyPackageName] = dependenciesConfig.dependencies[dependencyPackageName];
  }
  await writeJson(packageJsonPath, packageJson);
}

// ../cli-site-old/src/files/velo.dependencies.ts
init_esm_shims();
async function loadDependenciesConfig(projectFolder) {
  const configFile = await readJson(
    getVeloDependenciesConfigPath(projectFolder)
  );
  try {
    return veloDependenciesConfigSchema.parse(configFile);
  } catch (e) {
    throw new CliError({
      code: CliErrorCode.InvalidVeloConfigJson({
        configFilename: VELO_DEPENDENCIES_CONFIG_PATH
      }),
      cause: e
    });
  }
}

// ../cli-site-old/src/velo-npm/any-npm-migration.ts
var migrateToAnyNpmIfNeeded = async (root, logger) => {
  const oldDependenciesFilePath = getVeloDependenciesConfigPath(root);
  if (await pathExists(oldDependenciesFilePath)) {
    try {
      logger.logMigratingToAnyNpm();
      const oldVeloDeps = await loadDependenciesConfig(root);
      await addDependenciesToPackageJson(root, oldVeloDeps);
      await unlink(oldDependenciesFilePath);
      logger.logMigrationToAnyNpmCompletedSuccessfully();
    } catch (ex) {
      logger.logMigrationToAnyNpmFailed();
      throw ex;
    }
  }
};

// ../cli-site-old/src/velo-npm/client.ts
init_esm_shims();

// ../cli-site-old/src/files/wix.lock.ts
init_esm_shims();
import { join as join2 } from "node:path";
async function saveWixLock(projectFolder, lockFileContent) {
  const wixLockPath = join2(projectFolder, WIX_LOCK_FILENAME);
  try {
    await outputFile(wixLockPath, lockFileContent);
  } catch (e) {
    throw new CliError({
      code: CliErrorCode.FailedToWriteWixLock(),
      cause: e
    });
  }
}

// ../cli-site-old/src/files/dependencies-metadata.ts
init_esm_shims();
import { join as join3 } from "node:path";
async function saveDependenciesMetadata(projectFolder, metadataContent) {
  const metadataPath = join3(projectFolder, DEPENDENCIES_METADATA_FILENAME);
  try {
    await writeJson(metadataPath, metadataContent);
  } catch (e) {
    throw new CliError({
      code: CliErrorCode.FailedToWriteDependenciesMetadata(),
      cause: e
    });
  }
}

// ../cli-site-old/src/velo-npm/client.ts
var waitForInstallationCompleted = async (jobId, { authState }) => {
  try {
    return await pWaitFor(
      async () => {
        try {
          const { data } = await httpRequest(
            { type: "editor", authState },
            getResolveNpmDependenciesResult({ jobId })
          );
          const npmDependenciesLockFileResponse = npmDependenciesLockFileResponseSchema.parse(data);
          const { npmDependenciesLockFile, dependenciesMetadataUrl } = npmDependenciesLockFileResponse.result;
          return pWaitFor.resolveWith({
            wixLockFileUrl: npmDependenciesLockFile,
            dependenciesMetadataUrl
          });
        } catch (e) {
          if (isHttpError(e) && e.response?.status === 428) {
            return false;
          }
          throw e;
        }
      },
      {
        // Poll each 3 seconds
        interval: 3 * 1e3,
        // Fail if 5 minutes passed
        timeout: 5 * 60 * 1e3
      }
    );
  } catch (e) {
    throw new CliError({
      code: CliErrorCode.FailedToGetResolveNpmDependenciesResult(),
      cause: e,
      info: { jobId }
    });
  }
};
var fetchAndSaveWixLock = async (url, root) => {
  const wixLockContent = await httpRequest(
    { type: "standalone" },
    { url }
  );
  return saveWixLock(root, wixLockContent.data);
};
var fetchDependenciesMetadata = async (url) => {
  const metadataResponse = await httpRequest(
    { type: "standalone" },
    { url }
  );
  return metadataResponse.data;
};
var fetchAndSaveDependenciesMetadata = async (url, root) => {
  const metadata = await fetchDependenciesMetadata(url);
  return saveDependenciesMetadata(root, metadata);
};
var resolveNpmDependencies2 = async (root, { authState }) => {
  try {
    const npmPackageInfos = await getDependencies(root);
    const { data: resolveNpmDependenciesResponse } = await httpRequest(
      { type: "editor", authState },
      resolveNpmDependencies({ npmPackageInfos })
    );
    const { jobId } = resolveNpmDependenciesSchema.parse(
      resolveNpmDependenciesResponse
    );
    const { wixLockFileUrl, dependenciesMetadataUrl } = await waitForInstallationCompleted(jobId, {
      authState
    });
    await Promise.all([
      fetchAndSaveWixLock(wixLockFileUrl, root),
      ...dependenciesMetadataUrl ? [fetchAndSaveDependenciesMetadata(dependenciesMetadataUrl, root)] : []
    ]);
  } catch (e) {
    throw new CliError({
      code: CliErrorCode.FailedToResolveNpmDependencies(),
      cause: e
    });
  }
};

// ../cli-site-old/src/velo-npm/package-manager.ts
init_esm_shims();
async function resolvePackageManager(projectFolder, options) {
  const repoType = await getRepoType(projectFolder);
  if (options.yarn) {
    return new Yarn(repoType, "yarn");
  }
  if (options.npm) {
    return new NPM(repoType);
  }
  return createPackageManager(repoType);
}

// ../cli-site-old/src/velo-npm/index.ts
init_esm_shims();

export {
  migrateToAnyNpmIfNeeded,
  resolveNpmDependencies2 as resolveNpmDependencies,
  resolvePackageManager
};
//# sourceMappingURL=chunk-QTFCBXGW.js.map