import fetch from 'cross-fetch';

const VERSIONS_BASE_URL = "https://versions.backstage.io";
const GITHUB_RAW_BASE_URL = "https://raw.githubusercontent.com/backstage/versions/main";
function wait(waitMs, signal) {
  return new Promise((resolve, reject) => {
    const timeout = setTimeout(() => {
      if (!signal.aborted) {
        resolve();
      }
    }, waitMs);
    signal.addEventListener("abort", () => {
      clearTimeout(timeout);
      reject(new Error("Aborted"));
    });
  });
}
async function withFallback(fn1, fn2, fallbackDelayMs) {
  const c1 = new AbortController();
  const c2 = new AbortController();
  const promise1 = fn1(c1.signal).then((res) => {
    c2.abort();
    return res;
  });
  const promise2 = wait(fallbackDelayMs, c2.signal).then(() => fn2(c2.signal)).then((res) => {
    c1.abort();
    return res;
  });
  return Promise.any([promise1, promise2]).catch(() => promise1);
}
async function getManifestByVersion(options) {
  const versionEnc = encodeURIComponent(options.version);
  const res = await withFallback(
    (signal) => fetch(`${VERSIONS_BASE_URL}/v1/releases/${versionEnc}/manifest.json`, {
      signal
    }),
    (signal) => fetch(`${GITHUB_RAW_BASE_URL}/v1/releases/${versionEnc}/manifest.json`, {
      signal
    }),
    500
  );
  if (res.status === 404) {
    throw new Error(`No release found for ${options.version} version`);
  }
  if (res.status !== 200) {
    throw new Error(
      `Unexpected response status ${res.status} when fetching release from ${res.url}.`
    );
  }
  return res.json();
}
async function getManifestByReleaseLine(options) {
  const releaseEnc = encodeURIComponent(options.releaseLine);
  const res = await withFallback(
    (signal) => fetch(`${VERSIONS_BASE_URL}/v1/tags/${releaseEnc}/manifest.json`, {
      signal
    }),
    async (signal) => {
      const baseUrl = `${GITHUB_RAW_BASE_URL}/v1/tags/${releaseEnc}`;
      const linkRes = await fetch(baseUrl, { signal });
      if (!linkRes.ok) {
        return linkRes;
      }
      const link = (await linkRes.text()).trim();
      return fetch(new URL(`${link}/manifest.json`, baseUrl), { signal });
    },
    1e3
  );
  if (res.status === 404) {
    throw new Error(`No '${options.releaseLine}' release line found`);
  }
  if (res.status !== 200) {
    throw new Error(
      `Unexpected response status ${res.status} when fetching release from ${res.url}.`
    );
  }
  return res.json();
}

export { getManifestByReleaseLine, getManifestByVersion };
//# sourceMappingURL=index.esm.js.map
