import { BroadcastChannel as bc } from "../../shared/src/broadcast-channel.js";
import { getClientGroup } from "./persist/client-groups.js";
import { withRead } from "./with-transactions.js";
function makeChannelNameV0(replicacheName) {
  return `replicache-new-client-group:${replicacheName}`;
}
function makeChannelNameV1(replicacheName) {
  return `replicache-new-client-group-v1:${replicacheName}`;
}
function isNewClientChannelMessageV1(message) {
  return typeof message === "object" && typeof message.clientGroupID === "string" && typeof message.idbName === "string";
}
function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, isNewClientGroup, onUpdateNeeded, perdag) {
  if (signal.aborted) {
    return;
  }
  const channelV1 = new bc(makeChannelNameV1(replicacheName));
  if (isNewClientGroup) {
    channelV1.postMessage({ clientGroupID, idbName });
    const channelV0 = new bc(makeChannelNameV0(replicacheName));
    channelV0.postMessage([clientGroupID]);
    channelV0.close();
  }
  channelV1.onmessage = async (e) => {
    const { data } = e;
    if (isNewClientChannelMessageV1(data)) {
      const { clientGroupID: newClientGroupID, idbName: newClientIDBName } = data;
      if (newClientGroupID !== clientGroupID) {
        if (newClientIDBName === idbName) {
          const updateNeeded = await withRead(
            perdag,
            async (perdagRead) => await getClientGroup(newClientGroupID, perdagRead) !== void 0
          );
          if (updateNeeded) {
            onUpdateNeeded();
          }
        } else {
          onUpdateNeeded();
          return;
        }
      }
    }
  };
  signal.addEventListener("abort", () => channelV1.close(), { once: true });
}
export {
  initNewClientChannel,
  makeChannelNameV0 as makeChannelNameV0ForTesting,
  makeChannelNameV1 as makeChannelNameV1ForTesting
};
//# sourceMappingURL=new-client-channel.js.map
