import { createContext, batch, useContext, createMemo, splitProps, untrack, onCleanup, createEffect } from "solid-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 createZero(options) {
  const opts = {
    ...options,
    batchViewUpdates: batch
  };
  return new Zero(opts);
}
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(props) {
  const zero = createMemo(() => {
    if ("zero" in props) {
      return props.zero;
    }
    const [, options] = splitProps(props, ["children", "auth"]);
    const authValue = untrack(() => props.auth);
    const createdZero = new Zero({
      ...options,
      ...authValue !== void 0 ? { auth: authValue } : {},
      batchViewUpdates: batch
    });
    options.init?.(createdZero);
    onCleanup(() => createdZero.close());
    return createdZero;
  });
  const auth = createMemo(() => "auth" in props ? props.auth : NO_AUTH_SET);
  let prevAuth = NO_AUTH_SET;
  createEffect(() => {
    const currentZero = zero();
    if (!currentZero || "zero" in props) {
      return;
    }
    const currentAuth = auth();
    if (prevAuth === NO_AUTH_SET) {
      prevAuth = currentAuth;
      return;
    }
    if (currentAuth !== prevAuth) {
      prevAuth = currentAuth;
      void currentZero.connection.connect({
        auth: currentAuth === NO_AUTH_SET ? void 0 : currentAuth
      });
    }
  });
  return ZeroContext.Provider({
    value: zero,
    get children() {
      return props.children;
    }
  });
}
export {
  ZeroProvider,
  createUseZero,
  createZero,
  useZero
};
//# sourceMappingURL=use-zero.js.map
