import { focusManager as D } from "./focusManager.js";
import { onlineManager as C } from "./onlineManager.js";
import { pendingThenable as O } from "./thenable.js";
import { isServer as S, sleep as k } from "./utils.js";
function x(e) {
  return Math.min(1e3 * 2 ** e, 3e4);
}
function T(e) {
  return (e ?? "online") === "online" ? C.isOnline() : !0;
}
var P = class extends Error {
  constructor(e) {
    super("CancelledError"), this.revert = e == null ? void 0 : e.revert, this.silent = e == null ? void 0 : e.silent;
  }
};
function B(e) {
  return e instanceof P;
}
function G(e) {
  let m = !1, n = 0, l = !1, s;
  const u = O(), p = (r) => {
    var t;
    l || (d(new P(r)), (t = e.abort) == null || t.call(e));
  }, w = () => {
    m = !0;
  }, E = () => {
    m = !1;
  }, c = () => D.isFocused() && (e.networkMode === "always" || C.isOnline()) && e.canRun(), i = () => T(e.networkMode) && e.canRun(), M = (r) => {
    var t;
    l || (l = !0, (t = e.onSuccess) == null || t.call(e, r), s == null || s(), u.resolve(r));
  }, d = (r) => {
    var t;
    l || (l = !0, (t = e.onError) == null || t.call(e, r), s == null || s(), u.reject(r));
  }, v = () => new Promise((r) => {
    var t;
    s = (a) => {
      (l || c()) && r(a);
    }, (t = e.onPause) == null || t.call(e);
  }).then(() => {
    var r;
    s = void 0, l || (r = e.onContinue) == null || r.call(e);
  }), h = () => {
    if (l)
      return;
    let r;
    const t = n === 0 ? e.initialPromise : void 0;
    try {
      r = t ?? e.fn();
    } catch (a) {
      r = Promise.reject(a);
    }
    Promise.resolve(r).then(M).catch((a) => {
      var R;
      if (l)
        return;
      const y = e.retry ?? (S ? 0 : 3), o = e.retryDelay ?? x, b = typeof o == "function" ? o(n, a) : o, j = y === !0 || typeof y == "number" && n < y || typeof y == "function" && y(n, a);
      if (m || !j) {
        d(a);
        return;
      }
      n++, (R = e.onFail) == null || R.call(e, n, a), k(b).then(() => c() ? void 0 : v()).then(() => {
        m ? d(a) : h();
      });
    });
  };
  return {
    promise: u,
    cancel: p,
    continue: () => (s == null || s(), u),
    cancelRetry: w,
    continueRetry: E,
    canStart: i,
    start: () => (i() ? h() : v().then(h), u)
  };
}
export {
  P as CancelledError,
  T as canFetch,
  G as createRetryer,
  B as isCancelledError
};
//# sourceMappingURL=retryer.js.map
