const h = (d) => (u) => {
  try {
    const s = d(u);
    return s instanceof Promise ? s : {
      then(n) {
        return h(n)(s);
      },
      catch(n) {
        return this;
      }
    };
  } catch (s) {
    return {
      then(n) {
        return this;
      },
      catch(n) {
        return h(n)(s);
      }
    };
  }
}, I = (d, u) => (s, n, l) => {
  let r = {
    getStorage: () => localStorage,
    serialize: JSON.stringify,
    deserialize: JSON.parse,
    partialize: (e) => e,
    version: 0,
    merge: (e, o) => ({
      ...o,
      ...e
    }),
    ...u
  }, v = !1;
  const m = /* @__PURE__ */ new Set(), f = /* @__PURE__ */ new Set();
  let a;
  try {
    a = r.getStorage();
  } catch {
  }
  if (!a)
    return d(
      (...e) => {
        console.warn(
          `[zustand persist middleware] Unable to update item '${r.name}', the given storage is currently unavailable.`
        ), s(...e);
      },
      n,
      l
    );
  const p = h(r.serialize), y = () => {
    const e = r.partialize({ ...n() });
    let o;
    const t = p({ state: e, version: r.version }).then(
      (i) => a.setItem(r.name, i)
    ).catch((i) => {
      o = i;
    });
    if (o)
      throw o;
    return t;
  }, b = l.setState;
  l.setState = (e, o) => {
    b(e, o), y();
  };
  const g = d(
    (...e) => {
      s(...e), y();
    },
    n,
    l
  );
  let c;
  const S = () => {
    var e;
    if (!a)
      return;
    v = !1, m.forEach((t) => t(n()));
    const o = ((e = r.onRehydrateStorage) == null ? void 0 : e.call(r, n())) || void 0;
    return h(a.getItem.bind(a))(r.name).then((t) => {
      if (t)
        return r.deserialize(t);
    }).then((t) => {
      if (t)
        if (typeof t.version == "number" && t.version !== r.version) {
          if (r.migrate)
            return r.migrate(
              t.state,
              t.version
            );
          console.error(
            "State loaded from storage couldn't be migrated since no migrate function was provided"
          );
        } else
          return t.state;
    }).then((t) => {
      var i;
      return c = r.merge(
        t,
        (i = n()) != null ? i : g
      ), s(c, !0), y();
    }).then(() => {
      o == null || o(c, void 0), v = !0, f.forEach((t) => t(c));
    }).catch((t) => {
      o == null || o(void 0, t);
    });
  };
  return l.persist = {
    setOptions: (e) => {
      r = {
        ...r,
        ...e
      }, e.getStorage && (a = e.getStorage());
    },
    clearStorage: () => {
      a == null || a.removeItem(r.name);
    },
    getOptions: () => r,
    rehydrate: () => S(),
    hasHydrated: () => v,
    onHydrate: (e) => (m.add(e), () => {
      m.delete(e);
    }),
    onFinishHydration: (e) => (f.add(e), () => {
      f.delete(e);
    })
  }, S(), c || g;
}, H = I;
export {
  H as persist
};
//# sourceMappingURL=middleware.es.js.map
