import { buildManifestUrl as z, isMFManifest as H, shouldUseLocalDevEntryFallback as K, buildLocalDevEntryUrl as N, isAbortLikeError as Q, getFailureDetail as k } from "../mfRuntimeUtils/mfRuntimeUtils.js";
import { emitFrontendTelemetry as W } from "../emitFrontendTelemetry/emitFrontendTelemetry.js";
function C(c, q, U, T, r) {
  let u, f = !1, y = "progress", m, S = 0, n;
  const p = [];
  function v(e) {
    r && W(e);
  }
  function g(e) {
    r && (u = {
      attempt: e,
      loadSource: r.loadSource,
      loadStartedAt: performance.now()
    }, v({
      type: "module_load_started",
      context: r.context,
      loadSource: r.loadSource,
      attempt: e
    }));
  }
  function L(e, t, a, s) {
    u = void 0, n = void 0, m = {
      failureReason: a,
      ...s ? { failureDetail: s } : {}
    }, r && v({
      type: "module_load_failed",
      context: r.context,
      loadSource: r.loadSource,
      attempt: e,
      totalDurationMs: t,
      failureReason: a,
      ...s ? { failureDetail: s } : {}
    });
  }
  function E(e, t, a, s, w) {
    u = void 0, r && (n = {
      attempt: e,
      loadDurationMs: w,
      loadReadyAt: a,
      loadSource: r.loadSource,
      loadStartedAt: t,
      resolveDurationMs: s
    });
  }
  function P() {
    const e = n;
    return n = void 0, e;
  }
  function j() {
    const e = n ? {
      attempt: n.attempt,
      loadSource: n.loadSource,
      loadStartedAt: n.loadStartedAt
    } : u;
    return n = void 0, u = void 0, e;
  }
  function D() {
    const e = m;
    return m = void 0, e;
  }
  function x() {
    y === "error" && !f && setTimeout(h, 100);
  }
  function i(e, t) {
    y = e, e !== "progress" && (f = !1), p.forEach((a) => {
      a(e, t);
    });
  }
  function O(e) {
    p.push(e), y === "error" && x();
  }
  function B(e) {
    const t = p.indexOf(e);
    t !== -1 && p.splice(t, 1);
  }
  async function h() {
    if (f)
      return;
    f = !0, S += 1;
    const e = S, t = performance.now();
    m = void 0;
    let a = 0;
    const s = 15e3;
    let w = 0;
    const M = !T;
    let b = -1;
    g(e), i("progress", b);
    const F = new AbortController(), R = window.setTimeout(() => {
      F.abort();
    }, s), G = performance.now(), _ = z(c);
    let l;
    try {
      const o = await fetch(
        _,
        {
          signal: F.signal
        }
      );
      if (!o.ok)
        throw new Error(`Manifest request failed with status ${o.status}`);
      const d = await o.json();
      if (!H(d))
        throw new Error("Manifest is missing the required src/index.tsx entry");
      l = M ? `${c}/${d["src/index.tsx"].file}?rnd=${Math.random()}` : `${c}/${d["src/index.tsx"].file}`;
    } catch (o) {
      if (!T && K(o))
        l = N(c, M), console.warn(
          `MFLoader manifest request fell back to the Vite dev entry for ${c}`,
          o
        );
      else {
        const d = Q(o) ? "manifest_fetch_timeout" : "manifest_fetch_error";
        L(
          e,
          performance.now() - t,
          d,
          k(o, _)
        ), console.error(
          `MFLoader manifest request failed for ${c}/manifest.json`,
          o
        ), i("error", 0);
      }
    } finally {
      w = performance.now() - G, window.clearTimeout(R);
    }
    if (!l)
      return;
    const A = new AbortController(), J = window.setTimeout(() => {
      A.abort();
    }, s), V = performance.now();
    if (await U({
      method: "GET",
      endPoint: l,
      isRemote: T,
      headers: { "Content-Type": "application/json" },
      /**
       * Track bundle download progress using the network client callback.
       * Sigue el progreso de descarga del bundle usando el callback del cliente de red.
       */
      onDownloadProgress: (o) => {
        const d = typeof o.loaded == "number" ? o.loaded : 0, $ = typeof o.total == "number" ? o.total : 0;
        o.lengthComputable && $ > 0 ? b = 10 + Math.round(d * 90 / $) : b = -1, i("progress", b);
      },
      isExternalUrl: !0,
      responseType: "text",
      signal: A.signal
    }).then(() => "ok").catch((o) => (L(
      e,
      performance.now() - t,
      "bundle_resolve_error",
      k(o, l)
    ), console.error(`MFLoader bundle request failed for ${l}`, o), i("error", 0), "error")).finally(() => {
      a = performance.now() - V, window.clearTimeout(J);
    }) === "ok") {
      const o = document.createElement("script");
      o.id = q, o.crossOrigin = "", o.type = "module", o.src = l, o.onload = () => {
        E(
          e,
          t,
          performance.now(),
          w,
          a
        ), i("complete", 100);
      }, o.onerror = () => {
        L(
          e,
          performance.now() - t,
          "script_load_error",
          l
        ), i("error", 0);
      }, document.head.appendChild(o);
    }
  }
  const I = {
    consumeLastFailureTelemetry: D,
    consumePendingLoadTelemetry: j,
    consumeResolvedLoadTelemetry: P,
    notify: i,
    start: h,
    subscribe: O,
    tryAgain: x,
    unsubscribe: B
  };
  return setTimeout(h, 100), I;
}
export {
  C as createObservableLoaderMF
};
