import { debounce } from "@scalar/helpers/general/debounce";
import { clientStorage, authStorage } from "../helpers/storage.js";
const persistencePlugin = ({
  debounceDelay = 500,
  maxWait = 1e4,
  prefix = "",
  persistAuth = false
}) => {
  const { execute } = debounce({ delay: debounceDelay, maxWait });
  const authPersistence = authStorage();
  const clientPersistence = clientStorage();
  const getPrefix = () => {
    if (typeof prefix === "string") {
      return prefix;
    }
    return prefix();
  };
  const getPersistAuth = () => {
    if (typeof persistAuth === "function") {
      return persistAuth();
    }
    return persistAuth;
  };
  return {
    hooks: {
      /**
       * Handles all workspace state change events.
       * Each write is debounced by a key to prevent frequent writes for the same entity.
       */
      onWorkspaceStateChanges(event) {
        if (event.type === "meta") {
          const defaultClient = event.value["x-scalar-default-client"];
          if (defaultClient !== void 0) {
            execute("x-scalar-default-client", () => clientPersistence.set(defaultClient));
          }
          return;
        }
        if (getPersistAuth() && event.type === "auth") {
          execute("auth", () => authPersistence.setAuth(getPrefix(), event.value));
        }
        return;
      }
    }
  };
};
export {
  persistencePlugin
};
