import { l as E, S as w } from "./logger.mjs";
import "@seamless/logger";
import { L as R } from "./initializeLogger.mjs";
import "@seamless/store";
import { a as Y, w as oe, c as se, b as $, d as H } from "./with-usage-tracking.mjs";
import "@b2x/std/helpers.mjs";
import "@owc/aem-component-data-util";
function y(t, r, n) {
  const e = n?.events?.[t];
  if (typeof e == "function")
    try {
      e(r);
    } catch (a) {
      try {
        n?.events?.onError?.({ error: a, context: { type: t, message: "Error in event hook", ...r } });
      } catch (o) {
        E("Error in onError event hook", {
          args: [o],
          group: w.STORE,
          level: R.ERROR
        });
      }
    }
}
function ae({
  options: t,
  prevBaseState: r,
  nextBaseState: n,
  action: e,
  args: a,
  meta: o,
  skipMiddleware: l
}) {
  if (!t?.middleware || l)
    return n;
  const s = Array.isArray(t.middleware) ? t.middleware : [t.middleware];
  let i = n;
  for (const f of s)
    try {
      const S = f({ prevState: r, nextState: i, action: e, args: a, meta: o });
      if (S instanceof Promise)
        throw new Error("Async (Promise-returning) middleware is not supported. Middleware must be synchronous.");
      if (S === !1)
        return !1;
      S && typeof S == "object" && (i = S);
    } catch (S) {
      return y("onError", { error: S, action: e, args: a, meta: o }, t), !1;
    }
  return i;
}
function B({ channel: t, baseState: r, shallow: n, sourceId: e }) {
  t?.postMessage({
    type: "setState",
    sourceId: e,
    payload: r,
    shallow: n
  });
}
function F({
  baseState: t,
  derivedFunctions: r
}) {
  const n = {}, e = {};
  for (const [a, o] of Object.entries(r)) {
    const l = /* @__PURE__ */ new Set(), s = new Proxy(t, {
      get(i, f) {
        if (typeof f == "string") {
          if (f in r)
            throw new Error(
              `Derived function "${String(a)}" attempted to access another derived key "${f}". This is not allowed.`
            );
          if (f in i)
            return l.add(f), i[f];
        }
      }
    });
    try {
      n[a] = o(s), e[a] = l;
    } catch (i) {
      E(`Error computing derived key "${String(a)}":`, {
        args: [i],
        group: w.STORE,
        level: R.ERROR
      });
    }
  }
  return { derivedState: n, derivedDependencies: e };
}
function ce(t, r) {
  const n = {};
  for (const e of Reflect.ownKeys(t)) {
    if (Object.hasOwn(r, e)) {
      E(
        `Attempted to set derived key "${String(e)}" via setState. Derived values are read-only and cannot be set directly.`,
        {
          group: w.STORE,
          level: R.WARN
        }
      );
      continue;
    }
    n[e] = t[e];
  }
  return n;
}
function ie({
  baseState: t,
  derivedFunctions: r,
  update: n,
  shallow: e
}) {
  const a = typeof n == "function" ? n(t) : n, o = ce(a, r);
  return e ? { ...t, ...o } : Y(t, o);
}
const ue = Object.freeze([
  "getState",
  "setState",
  "subscribe",
  "subscribeTo",
  "resetState",
  "batch",
  "destroy",
  "unsubscribeAll"
]);
function le(t = {}) {
  return Object.fromEntries(
    Object.entries(t).filter(([r]) => {
      const n = ue.includes(r);
      return n && E(`User-defined API method "${r}" conflicts with core store method and was ignored.`, {
        args: [r],
        group: w.STORE,
        level: R.WARN
      }), !n;
    })
  );
}
function de(t, r) {
  const n = /* @__PURE__ */ new Set(), e = /* @__PURE__ */ new Set([...Reflect.ownKeys(t), ...Reflect.ownKeys(r)]);
  for (const a of e)
    r[a] !== t[a] && n.add(a);
  return n;
}
function j(t, r) {
  return { ...t, ...r };
}
function Q({
  baseState: t,
  derivedFunctions: r,
  changedKeys: n,
  prevDerivedState: e,
  prevDerivedDependencies: a
}) {
  const o = { ...e }, l = { ...a };
  for (const [s, i] of Object.entries(r)) {
    const f = a[s];
    if (f && [...f].some((S) => n.has(S))) {
      const { derivedState: S, derivedDependencies: b } = F({
        baseState: t,
        derivedFunctions: { [s]: i }
      }), O = S[s], g = e[s];
      if (Object.is(O, g))
        continue;
      o[s] = S[s], l[s] = b[s];
    }
  }
  return { derivedState: o, derivedDependencies: l };
}
function fe(t, r) {
  try {
    if (typeof r == "object" && r.enable && r.key)
      return new BroadcastChannel(r.key);
    if (r === !0 && t)
      return new BroadcastChannel(`store-sync:${t}`);
    r === !0 && E(
      'Tab sync requires an "owner" to be defined when no custom key is provided. Set the "owner" option or provide a custom tabSync.key.',
      {
        group: w.STORE,
        level: R.WARN
      }
    );
  } catch (n) {
    E("BroadcastChannel not available or failed to initialize:", {
      args: [n],
      group: w.STORE,
      level: R.WARN
    });
  }
  return null;
}
function Se(t, r) {
  const n = {};
  for (const e in r) {
    const a = r[e];
    typeof a == "function" && (n[e] = ((...o) => {
      const l = t.setState, i = { ...t, setState: (f, S = {}) => l.call(t, f, { ...S, action: e, args: o }), ...n };
      return a(i, ...o);
    }));
  }
  return n;
}
function ve({
  owner: t,
  enableUsageTracking: r = !1,
  stateCoreMethods: n,
  userDefinedApi: e,
  subscriptionMethods: a,
  untrackedMethods: o = {}
}) {
  const l = new Set(Object.keys(o)), s = Se(n, e);
  if (!t)
    return r && E('Tracking requires an "owner" to be defined. Set the "owner" option to use this feature.', {
      group: w.STORE,
      level: R.WARN
    }), {
      ...n,
      ...a,
      ...s,
      ...o
    };
  const i = Object.fromEntries(
    Object.entries(n).filter(([b]) => !l.has(b))
  ), f = Object.fromEntries(
    Object.entries(a).filter(([b]) => !l.has(b))
  );
  return {
    ...oe(t, {
      ...i,
      ...f,
      ...s
    }),
    ...o
  };
}
function be({
  channel: t,
  sourceId: r,
  setState: n,
  getBaseState: e,
  tabCounterKey: a,
  isStateBroadcasted: o
}) {
  Number(localStorage.getItem(a)) <= 1 && ye(a), t.addEventListener("message", (s) => {
    const { type: i, payload: f, sourceId: S, shallow: b } = s.data || {};
    if (S === r)
      return;
    if (i === "requestState") {
      t.postMessage({ type: "setState", payload: e(), sourceId: r, shallow: !1 });
      return;
    }
    const O = se(f, e());
    if (!(!f || i !== "setState" || O)) {
      o.value = !0;
      try {
        n(() => Y(e(), f), { shallow: b, skipMiddleware: !0 });
      } finally {
        o.value = !1;
      }
    }
  });
}
function ye(t) {
  const r = Number(localStorage.getItem(t) ?? "0") + 1;
  return localStorage.setItem(t, String(r)), r;
}
function he(t) {
  const r = Math.max(0, Number(localStorage.getItem(t) ?? "1") - 1);
  return localStorage.setItem(t, String(r)), r;
}
function ge(t, r, n) {
  for (const e of Reflect.ownKeys(n)) {
    const a = n[e];
    if (!a || a.size === 0)
      continue;
    const o = t[e], l = r[e];
    o !== l && Array.from(a).forEach((s) => {
      try {
        s(o, { prevValue: l, state: t });
      } catch (i) {
        E(`Error in subscriber for key "${String(e)}":`, {
          args: [i],
          group: w.STORE,
          level: R.ERROR
        });
      }
    });
  }
}
function P({
  nextState: t,
  prevState: r,
  subscriptions: n,
  keySubscriptions: e,
  isReady: a
}) {
  a.value && (n.forEach((o) => {
    try {
      o(t);
    } catch (l) {
      E("Error in global subscription:", {
        args: [l],
        group: w.STORE,
        level: R.ERROR
      });
    }
  }), ge(t, r, e));
}
function me(t, r, n) {
  let e = $(t);
  if (n?.persistence) {
    const { key: a, storage: o = localStorage, deserialize: l = JSON.parse } = n.persistence;
    try {
      const s = o.getItem(a);
      s && (e = l(s), r.value = !0);
    } catch (s) {
      y("onError", { error: s, context: { type: "hydrate", state: t } }, n);
    }
  }
  return e;
}
function V(t, r) {
  if (!r?.persistence)
    return;
  const { key: n, storage: e = localStorage, serialize: a = JSON.stringify } = r.persistence;
  try {
    const o = a(t);
    e.getItem(n) !== o && e.setItem(n, o);
  } catch (o) {
    y("onError", { error: o, context: { type: "persist", state: t } }, r);
  }
}
function pe({ channel: t, sourceId: r, isHydrated: n, tabCounterKey: e }) {
  return Number(localStorage.getItem(e)) <= 1 || n.value ? (n.value = !0, Promise.resolve()) : (t.postMessage({ type: "requestState", sourceId: r }), new Promise((o) => {
    const l = (s) => {
      const { type: i } = s.data || {};
      i === "setState" && (n.value = !0, t.removeEventListener("message", l), o());
    };
    t.addEventListener("message", l), setTimeout(() => {
      t.removeEventListener("message", l), n.value = !0, o();
    }, 1e3);
  }));
}
function X({
  nextBaseState: t,
  changedKeys: r,
  batchDepth: n,
  batchScheduled: e,
  pendingBaseState: a,
  pendingChangedKeys: o
}) {
  return n.value > 0 ? (a.value = t, o.value ? r.forEach((l) => o.value?.add(l)) : o.value = new Set(r), e.value = !0, !0) : !1;
}
function xe({ owner: t, initialState: r, derived: n = {}, options: e, api: a }) {
  const o = { value: !e?.controlledReady }, l = { value: !1 };
  let s = me(r, l, e), { derivedState: i, derivedDependencies: f } = F({ baseState: s, derivedFunctions: n });
  const S = le(a), b = /* @__PURE__ */ new Set(), O = /* @__PURE__ */ new Set(), g = {}, D = {}, I = { value: 0 }, K = { value: !1 }, C = { value: null }, N = { value: null }, x = crypto.randomUUID(), T = fe(t, e?.tabSync), W = { value: !1 }, U = `${T?.name}_tabCounter`;
  function _(c, {
    shallow: u = e?.defaultShallow ?? !1,
    action: d = "setState",
    args: h = [],
    meta: m,
    skipMiddleware: z = !1
  } = {}) {
    const p = j(s, i), A = { action: d, args: h, meta: m, options: e };
    try {
      let v = ie({
        baseState: I.value > 0 && C.value ? C.value : s,
        derivedFunctions: n,
        update: c,
        shallow: u
      });
      const M = de(s, v);
      if (M.size === 0 || (v = ae({
        prevBaseState: s,
        nextBaseState: H(v),
        skipMiddleware: z,
        ...A
      }), v === !1) || X({ batchDepth: I, batchScheduled: K, pendingBaseState: C, pendingChangedKeys: N, changedKeys: M, nextBaseState: v }))
        return;
      s = v, { derivedState: i, derivedDependencies: f } = Q({
        baseState: s,
        derivedFunctions: n,
        changedKeys: M,
        prevDerivedState: i,
        prevDerivedDependencies: f
      });
      const k = j(s, i);
      y("onAction", { action: d, args: h, prevState: p, nextState: k, meta: m }, e), y("onState", { prevState: p, nextState: k, action: d, meta: m }, e), V(v, e), P({ keySubscriptions: g, subscriptions: b, nextState: k, prevState: p, isReady: o }), W.value || B({ channel: T, baseState: v, shallow: u, sourceId: x });
    } catch (v) {
      y("onError", { error: v, context: { type: "setState", action: d, args: h, prevState: p, meta: m } }, e);
    }
  }
  function L() {
    let c = j(s, i);
    return e?.cloneState !== !1 && (c = $(c)), e?.freezeState !== !1 && (c = H(c)), c;
  }
  function Z() {
    if (X({
      batchDepth: I,
      batchScheduled: K,
      pendingBaseState: C,
      pendingChangedKeys: N,
      changedKeys: new Set(Object.keys(r)),
      nextBaseState: $(r)
    }))
      return;
    const c = j(s, i);
    s = $(r), { derivedState: i, derivedDependencies: f } = F({ baseState: s, derivedFunctions: n });
    const u = j(s, i);
    P({ nextState: u, subscriptions: b, prevState: c, keySubscriptions: g, isReady: o }), B({ channel: T, baseState: s, shallow: !0, sourceId: x }), y("onAction", { action: "resetState", args: [], prevState: c, nextState: u }, e), y("onState", { prevState: c, nextState: u, action: "resetState" }, e), V(s, e);
  }
  function ee(c, u) {
    let d = c;
    if (u?.once && (d = (h) => {
      c(h), b.delete(d);
    }), b.add(d), u?.emitImmediately !== !1 && o.value)
      try {
        d(L());
      } catch (h) {
        y(
          "onError",
          {
            error: h,
            context: {
              type: "subscribe",
              message: "Error in initial subscriber callback"
            }
          },
          e
        );
      }
    else u?.emitImmediately !== !1 && !o.value && O.add(d);
    return () => {
      b.delete(d), O.delete(d);
    };
  }
  function te(c, u, d) {
    const h = d?.emitImmediately !== !1, m = h && !o.value;
    function z() {
      return m ? (D[c] ??= /* @__PURE__ */ new Set(), D[c]) : (g[c] ??= /* @__PURE__ */ new Set(), g[c]);
    }
    const p = z();
    if (p.has(u))
      return E(`Duplicate subscription to key "${String(c)}"`, {
        group: w.STORE,
        level: R.WARN
      }), () => {
        p.delete(u), D[c]?.delete(u), g[c]?.delete(u);
      };
    let A = u;
    if (d?.once && (A = (v, M) => {
      u(v, M), D[c]?.delete(A), g[c]?.delete(A);
    }), p.add(A), h && !m && o.value)
      try {
        const v = L();
        A(v[c], { prevValue: void 0, state: v });
      } catch (v) {
        y(
          "onError",
          {
            error: v,
            context: {
              type: "subscribeTo",
              key: c,
              message: `Error in immediate subscription callback for "${String(c)}"`
            }
          },
          e
        );
      }
    return () => {
      D[c]?.delete(A), g[c]?.delete(A);
    };
  }
  function q() {
    b.clear(), O.clear(), Object.entries(g).forEach(([c, u]) => {
      u.clear(), delete g[c];
    }), Object.entries(D).forEach(([c, u]) => {
      u.clear(), delete D[c];
    });
  }
  async function re() {
    T && (be({
      getBaseState: () => s,
      setState: _,
      channel: T,
      sourceId: x,
      tabCounterKey: U,
      isStateBroadcasted: W
    }), await pe({ channel: T, sourceId: x, isHydrated: l, tabCounterKey: U }), window?.addEventListener?.("pagehide", J, { once: !0 }));
  }
  function G(c) {
    if (c.constructor.name === "AsyncFunction")
      throw new Error("Async batch functions are not supported.");
    const u = j(s, i);
    I.value++;
    try {
      c();
    } finally {
      if (I.value--, I.value === 0 && K.value) {
        C.value && (s = C.value, { derivedState: i, derivedDependencies: f } = Q({
          baseState: s,
          derivedFunctions: n,
          changedKeys: N.value,
          prevDerivedState: i,
          prevDerivedDependencies: f
        }), C.value = null, N.value = null);
        const d = j(s, i);
        y("onAction", { action: "resetState", args: [], prevState: u, nextState: d }, e), y("onState", { prevState: u, nextState: d, action: "resetState" }, e), V(s, e), P({ nextState: d, subscriptions: b, prevState: u, keySubscriptions: g, isReady: o }), B({ channel: T, baseState: s, shallow: !1, sourceId: x }), K.value = !1;
      }
    }
  }
  function J() {
    q(), T?.close(), T && he(U);
  }
  function ne() {
    o.value = !0;
    const c = L();
    O.forEach((u) => {
      try {
        u(c);
      } catch (d) {
        y(
          "onError",
          {
            error: d,
            context: {
              type: "subscribe",
              message: "Error in deferred subscriber callback"
            }
          },
          e
        );
      }
    }), O.clear(), Object.entries(D).forEach(([u, d]) => {
      d.forEach(
        (h) => {
          try {
            h(c[u], { prevValue: void 0, state: c });
          } catch (m) {
            y(
              "onError",
              {
                error: m,
                context: {
                  type: "subscribeTo",
                  key: u,
                  message: `Error in deferred subscription callback for "${String(u)}"`
                }
              },
              e
            );
          }
        }
      ), d.clear();
    });
  }
  return ve({
    owner: t,
    stateCoreMethods: {
      getState: L,
      setState: _,
      batch: G,
      resetState: Z
    },
    userDefinedApi: S,
    subscriptionMethods: {
      subscribe: ee,
      subscribeTo: te,
      unsubscribeAll: q
    },
    untrackedMethods: {
      batch: G,
      destroy: J,
      setupTabSync: re,
      setReady: ne
    },
    enableUsageTracking: e?.enableUsageTracking
  });
}
export {
  xe as c
};
//# sourceMappingURL=create-store.mjs.map
