var E = (i) => {
  throw TypeError(i);
};
var D = (i, t, e) => t.has(i) || E("Cannot " + e);
var r = (i, t, e) => (D(i, t, "read from private field"), e ? e.call(i) : t.get(i)), d = (i, t, e) => t.has(i) ? E("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(i) : t.set(i, e), l = (i, t, e, s) => (D(i, t, "write to private field"), s ? s.call(i, e) : t.set(i, e), e), f = (i, t, e) => (D(i, t, "access private method"), e);
import { replaceData as M, noop as O, resolveEnabled as P, skipToken as Q, resolveStaleTime as G, timeUntilStale as T, ensureQueryFn as H } from "./utils.js";
import { notifyManager as N } from "./notifyManager.js";
import { canFetch as V, createRetryer as _, isCancelledError as U } from "./retryer.js";
import { Removable as $ } from "./removable.js";
var F, S, o, b, n, q, C, h, y, k, Z = (k = class extends $ {
  constructor(t) {
    super();
    d(this, h);
    d(this, F);
    d(this, S);
    d(this, o);
    d(this, b);
    d(this, n);
    d(this, q);
    d(this, C);
    l(this, C, !1), l(this, q, t.defaultOptions), this.setOptions(t.options), this.observers = [], l(this, b, t.client), l(this, o, r(this, b).getQueryCache()), this.queryKey = t.queryKey, this.queryHash = t.queryHash, l(this, F, B(this.options)), this.state = t.state ?? r(this, F), this.scheduleGc();
  }
  get meta() {
    return this.options.meta;
  }
  get promise() {
    var t;
    return (t = r(this, n)) == null ? void 0 : t.promise;
  }
  setOptions(t) {
    this.options = { ...r(this, q), ...t }, this.updateGcTime(this.options.gcTime);
  }
  optionalRemove() {
    !this.observers.length && this.state.fetchStatus === "idle" && r(this, o).remove(this);
  }
  setData(t, e) {
    const s = M(this.state.data, t, this.options);
    return f(this, h, y).call(this, {
      data: s,
      type: "success",
      dataUpdatedAt: e == null ? void 0 : e.updatedAt,
      manual: e == null ? void 0 : e.manual
    }), s;
  }
  setState(t, e) {
    f(this, h, y).call(this, { type: "setState", state: t, setStateOptions: e });
  }
  cancel(t) {
    var s, u;
    const e = (s = r(this, n)) == null ? void 0 : s.promise;
    return (u = r(this, n)) == null || u.cancel(t), e ? e.then(O).catch(O) : Promise.resolve();
  }
  destroy() {
    super.destroy(), this.cancel({ silent: !0 });
  }
  reset() {
    this.destroy(), this.setState(r(this, F));
  }
  isActive() {
    return this.observers.some(
      (t) => P(t.options.enabled, this) !== !1
    );
  }
  isDisabled() {
    return this.getObserversCount() > 0 ? !this.isActive() : this.options.queryFn === Q || this.state.dataUpdateCount + this.state.errorUpdateCount === 0;
  }
  isStatic() {
    return this.getObserversCount() > 0 ? this.observers.some(
      (t) => G(t.options.staleTime, this) === "static"
    ) : !1;
  }
  isStale() {
    return this.getObserversCount() > 0 ? this.observers.some(
      (t) => t.getCurrentResult().isStale
    ) : this.state.data === void 0 || this.state.isInvalidated;
  }
  isStaleByTime(t = 0) {
    return this.state.data === void 0 ? !0 : t === "static" ? !1 : this.state.isInvalidated ? !0 : !T(this.state.dataUpdatedAt, t);
  }
  onFocus() {
    var e;
    const t = this.observers.find((s) => s.shouldFetchOnWindowFocus());
    t == null || t.refetch({ cancelRefetch: !1 }), (e = r(this, n)) == null || e.continue();
  }
  onOnline() {
    var e;
    const t = this.observers.find((s) => s.shouldFetchOnReconnect());
    t == null || t.refetch({ cancelRefetch: !1 }), (e = r(this, n)) == null || e.continue();
  }
  addObserver(t) {
    this.observers.includes(t) || (this.observers.push(t), this.clearGcTimeout(), r(this, o).notify({ type: "observerAdded", query: this, observer: t }));
  }
  removeObserver(t) {
    this.observers.includes(t) && (this.observers = this.observers.filter((e) => e !== t), this.observers.length || (r(this, n) && (r(this, C) ? r(this, n).cancel({ revert: !0 }) : r(this, n).cancelRetry()), this.scheduleGc()), r(this, o).notify({ type: "observerRemoved", query: this, observer: t }));
  }
  getObserversCount() {
    return this.observers.length;
  }
  invalidate() {
    this.state.isInvalidated || f(this, h, y).call(this, { type: "invalidate" });
  }
  fetch(t, e) {
    var R, w, x;
    if (this.state.fetchStatus !== "idle") {
      if (this.state.data !== void 0 && (e != null && e.cancelRefetch))
        this.cancel({ silent: !0 });
      else if (r(this, n))
        return r(this, n).continueRetry(), r(this, n).promise;
    }
    if (t && this.setOptions(t), !this.options.queryFn) {
      const a = this.observers.find((c) => c.options.queryFn);
      a && this.setOptions(a.options);
    }
    process.env.NODE_ENV !== "production" && (Array.isArray(this.options.queryKey) || console.error(
      "As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"
    ));
    const s = new AbortController(), u = (a) => {
      Object.defineProperty(a, "signal", {
        enumerable: !0,
        get: () => (l(this, C, !0), s.signal)
      });
    }, K = () => {
      const a = H(this.options, e), p = (() => {
        const v = {
          client: r(this, b),
          queryKey: this.queryKey,
          meta: this.meta
        };
        return u(v), v;
      })();
      return l(this, C, !1), this.options.persister ? this.options.persister(
        a,
        p,
        this
      ) : a(p);
    }, m = (() => {
      const a = {
        fetchOptions: e,
        options: this.options,
        queryKey: this.queryKey,
        client: r(this, b),
        state: this.state,
        fetchFn: K
      };
      return u(a), a;
    })();
    (R = this.options.behavior) == null || R.onFetch(m, this), l(this, S, this.state), (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((w = m.fetchOptions) == null ? void 0 : w.meta)) && f(this, h, y).call(this, { type: "fetch", meta: (x = m.fetchOptions) == null ? void 0 : x.meta });
    const A = (a) => {
      var c, p, v, g;
      U(a) && a.silent || f(this, h, y).call(this, {
        type: "error",
        error: a
      }), U(a) || ((p = (c = r(this, o).config).onError) == null || p.call(
        c,
        a,
        this
      ), (g = (v = r(this, o).config).onSettled) == null || g.call(
        v,
        this.state.data,
        a,
        this
      )), this.scheduleGc();
    };
    return l(this, n, _({
      initialPromise: e == null ? void 0 : e.initialPromise,
      fn: m.fetchFn,
      abort: s.abort.bind(s),
      onSuccess: (a) => {
        var c, p, v, g;
        if (a === void 0) {
          process.env.NODE_ENV !== "production" && console.error(
            `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`
          ), A(new Error(`${this.queryHash} data is undefined`));
          return;
        }
        try {
          this.setData(a);
        } catch (I) {
          A(I);
          return;
        }
        (p = (c = r(this, o).config).onSuccess) == null || p.call(c, a, this), (g = (v = r(this, o).config).onSettled) == null || g.call(
          v,
          a,
          this.state.error,
          this
        ), this.scheduleGc();
      },
      onError: A,
      onFail: (a, c) => {
        f(this, h, y).call(this, { type: "failed", failureCount: a, error: c });
      },
      onPause: () => {
        f(this, h, y).call(this, { type: "pause" });
      },
      onContinue: () => {
        f(this, h, y).call(this, { type: "continue" });
      },
      retry: m.options.retry,
      retryDelay: m.options.retryDelay,
      networkMode: m.options.networkMode,
      canRun: () => !0
    })), r(this, n).start();
  }
}, F = new WeakMap(), S = new WeakMap(), o = new WeakMap(), b = new WeakMap(), n = new WeakMap(), q = new WeakMap(), C = new WeakMap(), h = new WeakSet(), y = function(t) {
  const e = (s) => {
    switch (t.type) {
      case "failed":
        return {
          ...s,
          fetchFailureCount: t.failureCount,
          fetchFailureReason: t.error
        };
      case "pause":
        return {
          ...s,
          fetchStatus: "paused"
        };
      case "continue":
        return {
          ...s,
          fetchStatus: "fetching"
        };
      case "fetch":
        return {
          ...s,
          ...j(s.data, this.options),
          fetchMeta: t.meta ?? null
        };
      case "success":
        return {
          ...s,
          data: t.data,
          dataUpdateCount: s.dataUpdateCount + 1,
          dataUpdatedAt: t.dataUpdatedAt ?? Date.now(),
          error: null,
          isInvalidated: !1,
          status: "success",
          ...!t.manual && {
            fetchStatus: "idle",
            fetchFailureCount: 0,
            fetchFailureReason: null
          }
        };
      case "error":
        const u = t.error;
        return U(u) && u.revert && r(this, S) ? { ...r(this, S), fetchStatus: "idle" } : {
          ...s,
          error: u,
          errorUpdateCount: s.errorUpdateCount + 1,
          errorUpdatedAt: Date.now(),
          fetchFailureCount: s.fetchFailureCount + 1,
          fetchFailureReason: u,
          fetchStatus: "idle",
          status: "error"
        };
      case "invalidate":
        return {
          ...s,
          isInvalidated: !0
        };
      case "setState":
        return {
          ...s,
          ...t.state
        };
    }
  };
  this.state = e(this.state), N.batch(() => {
    this.observers.forEach((s) => {
      s.onQueryUpdate();
    }), r(this, o).notify({ query: this, type: "updated", action: t });
  });
}, k);
function j(i, t) {
  return {
    fetchFailureCount: 0,
    fetchFailureReason: null,
    fetchStatus: V(t.networkMode) ? "fetching" : "paused",
    ...i === void 0 && {
      error: null,
      status: "pending"
    }
  };
}
function B(i) {
  const t = typeof i.initialData == "function" ? i.initialData() : i.initialData, e = t !== void 0, s = e ? typeof i.initialDataUpdatedAt == "function" ? i.initialDataUpdatedAt() : i.initialDataUpdatedAt : 0;
  return {
    data: t,
    dataUpdateCount: 0,
    dataUpdatedAt: e ? s ?? Date.now() : 0,
    error: null,
    errorUpdateCount: 0,
    errorUpdatedAt: 0,
    fetchFailureCount: 0,
    fetchFailureReason: null,
    fetchMeta: null,
    isInvalidated: !1,
    status: e ? "success" : "pending",
    fetchStatus: "idle"
  };
}
export {
  Z as Query,
  j as fetchState
};
//# sourceMappingURL=query.js.map
