import { ensureQueryFn as T, addToStart as j, addToEnd as E } from "./utils.js";
function B(r) {
  return {
    onFetch: (e, s) => {
      var y, h, p, F, v;
      const n = e.options, f = (p = (h = (y = e.fetchOptions) == null ? void 0 : y.meta) == null ? void 0 : h.fetchMore) == null ? void 0 : p.direction, P = ((F = e.state.data) == null ? void 0 : F.pages) || [], d = ((v = e.state.data) == null ? void 0 : v.pageParams) || [];
      let o = { pages: [], pageParams: [] }, u = 0;
      const m = async () => {
        let i = !1;
        const g = (a) => {
          Object.defineProperty(a, "signal", {
            enumerable: !0,
            get: () => (e.signal.aborted ? i = !0 : e.signal.addEventListener("abort", () => {
              i = !0;
            }), e.signal)
          });
        }, k = T(e.options, e.fetchOptions), b = async (a, t, l) => {
          if (i)
            return Promise.reject();
          if (t == null && a.pages.length)
            return Promise.resolve(a);
          const N = (() => {
            const K = {
              client: e.client,
              queryKey: e.queryKey,
              pageParam: t,
              direction: l ? "backward" : "forward",
              meta: e.options.meta
            };
            return g(K), K;
          })(), O = await k(N), { maxPages: w } = e.options, C = l ? j : E;
          return {
            pages: C(a.pages, O, w),
            pageParams: C(a.pageParams, t, w)
          };
        };
        if (f && P.length) {
          const a = f === "backward", t = a ? Q : c, l = {
            pages: P,
            pageParams: d
          }, q = t(n, l);
          o = await b(l, q, a);
        } else {
          const a = r ?? P.length;
          do {
            const t = u === 0 ? d[0] ?? n.initialPageParam : c(n, o);
            if (u > 0 && t == null)
              break;
            o = await b(o, t), u++;
          } while (u < a);
        }
        return o;
      };
      e.options.persister ? e.fetchFn = () => {
        var i, g;
        return (g = (i = e.options).persister) == null ? void 0 : g.call(
          i,
          m,
          {
            client: e.client,
            queryKey: e.queryKey,
            meta: e.options.meta,
            signal: e.signal
          },
          s
        );
      } : e.fetchFn = m;
    }
  };
}
function c(r, { pages: e, pageParams: s }) {
  const n = e.length - 1;
  return e.length > 0 ? r.getNextPageParam(
    e[n],
    e,
    s[n],
    s
  ) : void 0;
}
function Q(r, { pages: e, pageParams: s }) {
  var n;
  return e.length > 0 ? (n = r.getPreviousPageParam) == null ? void 0 : n.call(r, e[0], e, s[0], s) : void 0;
}
function D(r, e) {
  return e ? c(r, e) != null : !1;
}
function I(r, e) {
  return !e || !r.getPreviousPageParam ? !1 : Q(r, e) != null;
}
export {
  D as hasNextPage,
  I as hasPreviousPage,
  B as infiniteQueryBehavior
};
//# sourceMappingURL=infiniteQueryBehavior.js.map
