text: "use strict";
  var __importDefault = (this && this.__importDefault) || function (mod) {
      return (mod && mod.__esModule) ? mod : { "default": mod };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.getLatestTag = void 0;
  const node_fetch_1 = __importDefault(require("node-fetch"));
  const getProxyAgent_1 = require("./getProxyAgent");
  const util_1 = require("./util");
  const get_platform_1 = require("@prisma/get-platform");
  const p_queue_1 = __importDefault(require("p-queue"));
  const execa_1 = __importDefault(require("execa"));
  async function getLatestTag() {
      if (process.env.RELEASE_PROMOTE_DEV) {
          const versions = await getVersionHashes(process.env.RELEASE_PROMOTE_DEV);
          console.log(`getLatestTag: taking ${versions.engines} as RELEASE_PROMOTE_DEV has been provided`);
          return versions.engines;
      }
      let branch = await getBranch();
      if (branch !== 'master' && !isPatchBranch(branch)) {
          console.log(`Overwriting branch "${branch}" with "master" as it's not a branch we have binaries for`);
          branch = 'master';
      }
      const url = `https://api.github.com/repos/prisma/prisma-engines/commits?sha=${branch}`;
      const result = await node_fetch_1.default(url, {
          agent: getProxyAgent_1.getProxyAgent(url),
      }).then((res) => res.json());
      const commits = result.map((r) => r.sha);
      const commit = await getFirstExistingCommit(commits);
      const queue = new p_queue_1.default({ concurrency: 30 });
      const promises = [];
      const excludedPlatforms = [
          'freebsd',
          'arm',
          'linux-nixos',
          'openbsd',
          'netbsd',
      ];
      const relevantPlatforms = get_platform_1.platforms.filter((p) => !excludedPlatforms.includes(p));
      for (const platform of relevantPlatforms) {
          for (const engine of [
              'query-engine',
              'introspection-engine',
              'migration-engine',
              'prisma-fmt',
          ]) {
              for (const extension of [
                  '.gz',
                  '.gz.sha256',
                  '.gz.sig',
                  '.sig',
                  '.sha256',
              ]) {
                  const downloadUrl = util_1.getDownloadUrl('all_commits', commit, platform, engine, extension);
                  promises.push(queue.add(async () => ({
                      downloadUrl,
                      exists: await urlExists(downloadUrl),
                  })));
              }
          }
      }
      // wait for all queue items to finish
      const exist = await Promise.all(promises);
      const missing = exist.filter((e) => !e.exists);
      if (missing.length > 0) {
          throw new Error(`Could not get new tag, as some assets don't exist: ${missing
              .map((m) => m.downloadUrl)
              .join(', ')}`);
      }
      return commit;
  }
  exports.getLatestTag = getLatestTag;
  async function getFirstExistingCommit(commits) {
      for (const commit of commits) {
          const exists = await urlExists(util_1.getDownloadUrl('all_commits', commit, 'darwin', 'query-engine'));
          if (exists) {
              return commit;
          }
      }
  }
  async function urlExists(url) {
      try {
          const res = await node_fetch_1.default(url, {
              method: 'HEAD',
              agent: getProxyAgent_1.getProxyAgent(url),
          });
          const headers = fromEntries(res.headers.entries());
          if (res.status > 200) {
              console.error(res, headers);
          }
          if (parseInt(headers['content-length']) > 0) {
              return res.status < 300;
          }
      }
      catch (e) {
          //
          console.error(e);
      }
      return false;
  }
  function fromEntries(entries) {
      const result = {};
      for (const [key, value] of entries) {
          result[key] = value;
      }
      return result;
  }
  async function getBranch() {
      if (process.env.PATCH_BRANCH) {
          return process.env.PATCH_BRANCH;
      }
      if (process.env.BUILDKITE_BRANCH) {
          return process.env.BUILDKITE_BRANCH;
      }
      const result = await execa_1.default.command('git rev-parse --abbrev-ref HEAD', {
          shell: true,
          stdio: 'pipe',
      });
      return result.stdout;
  }
  // TODO: Adjust this for stable release
  function isPatchBranch(version) {
      return /2\.(\d+)\.x/.test(version);
  }
  async function getVersionHashes(npmVersion) {
      return node_fetch_1.default(`https://unpkg.com/@prisma/cli@${npmVersion}/package.json`, {
          headers: {
              accept: 'application/json',
          },
      })
          .then((res) => res.json())
          .then((pkg) => ({
          engines: pkg.prisma.version,
          prisma: pkg.prisma.prismaCommit,
      }));
  }
  //# sourceMappingURL=getLatestTag.js.map