import { jsx } from "react/jsx-runtime";
import { createContext, useContext, useState, useRef, useMemo, useEffect } from "react";
import { stringCompare } from "../../shared/src/string-compare.js";
import "../../shared/src/config.js";
import "@rocicorp/resolver";
import "../../shared/src/resolved-promises.js";
import "../../shared/src/sleep.js";
import "../../replicache/src/hash.js";
import "../../replicache/src/deleted-clients.js";
import "@rocicorp/lock";
import "@rocicorp/logger";
import "../../replicache/src/persist/client-groups.js";
import "../../replicache/src/persist/clients.js";
import "../../shared/src/json-schema.js";
import "../../zero-protocol/src/custom-queries.js";
import "js-xxhash";
import "../../zero-protocol/src/client-schema.js";
import "../../zero-schema/src/permissions.js";
import "../../zero-protocol/src/ast.js";
import { Zero } from "../../zero-client/src/client/zero.js";
const ZeroContext = createContext(
  void 0
);
function useZero() {
  const zero = useContext(ZeroContext);
  if (zero === void 0) {
    throw new Error("useZero must be used within a ZeroProvider");
  }
  return zero;
}
function createUseZero() {
  return () => useZero();
}
const NO_AUTH_SET = Symbol();
function ZeroProvider({ children, init, ...props }) {
  const isExternalZero = "zero" in props;
  const [zero, setZero] = useState(
    isExternalZero ? props.zero : void 0
  );
  const auth = "auth" in props ? props.auth : NO_AUTH_SET;
  const prevAuthRef = useRef(auth);
  const keysWithoutAuth = useMemo(
    () => Object.entries(props).filter(([key]) => key !== "auth").sort(([a], [b]) => stringCompare(a, b)).map(([_, value]) => value),
    [props]
  );
  useEffect(() => {
    if (isExternalZero) {
      setZero(props.zero);
      return;
    }
    const z = new Zero(props);
    init?.(z);
    setZero(z);
    return () => {
      void z.close();
      setZero(void 0);
    };
  }, [init, ...keysWithoutAuth]);
  useEffect(() => {
    if (!zero || isExternalZero) return;
    const authChanged = auth !== prevAuthRef.current;
    if (authChanged) {
      prevAuthRef.current = auth;
      void zero.connection.connect({
        auth: auth === NO_AUTH_SET ? void 0 : auth
      });
    }
  }, [auth, zero]);
  return zero && /* @__PURE__ */ jsx(ZeroContext.Provider, { value: zero, children });
}
export {
  ZeroContext,
  ZeroProvider,
  createUseZero,
  useZero
};
//# sourceMappingURL=zero-provider.js.map
