var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};

// src/methods/requests/requests.ts
import axios from "axios";

// src/constants/endpoints.ts
var endpoints = {
  API: "https://client.memberstack.com"
};

// src/utils/cookies.ts
import Cookie from "js-cookie";
var memberAuthTokenName = "_ms-mid";
function isLocalStorageAvailable() {
  try {
    localStorage.setItem("test", "test");
    localStorage.removeItem("test");
    return true;
  } catch (e) {
    return false;
  }
}
var localStorageAvailable = isLocalStorageAvailable();
var useCookies = false;
var setCookieOnRootDomain = false;
var apiDomain;
var extractDomainFromHostname = (hostname) => {
  const hostnameParts = hostname.split(".");
  const isCountryCodeTLD = hostnameParts.length >= 3 && hostnameParts[hostnameParts.length - 2].length <= 3;
  if (isCountryCodeTLD) {
    return hostnameParts.slice(-3).join(".");
  } else {
    return hostnameParts.slice(-2).join(".");
  }
};
var useCookiesValid = () => {
  if (!useCookies)
    return false;
  if (setCookieOnRootDomain) {
    const apiDomainHost = extractDomainFromHostname(apiDomain);
    const currentHost = extractDomainFromHostname(window.location.hostname);
    return apiDomainHost === currentHost;
  }
  return true;
};
var setMemberToken = (token, expires) => {
  if (localStorageAvailable && useCookiesValid() === false) {
    localStorage.setItem(memberAuthTokenName, token);
  } else {
    const domain = extractDomainFromHostname(window.location.hostname);
    Cookie.set(memberAuthTokenName, token, __spreadValues({
      expires: expires && Number(expires) || 14,
      sameSite: "strict"
    }, setCookieOnRootDomain && { domain }));
  }
};
var removeMemberToken = () => {
  if (localStorageAvailable) {
    localStorage.removeItem(memberAuthTokenName);
  }
  const domain = extractDomainFromHostname(window.location.hostname);
  Cookie.set(memberAuthTokenName, "", __spreadValues({
    expires: -1,
    sameSite: "strict"
  }, setCookieOnRootDomain && { domain }));
  Cookie.set(memberAuthTokenName, "", {
    expires: -1,
    sameSite: "strict"
  });
};
var getMemberToken = () => {
  if (localStorageAvailable) {
    const memAuthToken = localStorage.getItem(memberAuthTokenName);
    if (memAuthToken)
      return memAuthToken;
  }
  return Cookie.get(memberAuthTokenName);
};
var getSessionId = () => {
  if (typeof window === "undefined")
    return null;
  const sessionId = window.localStorage.getItem("ms_session_id");
  if (!sessionId || sessionId.length > 26) {
    window.localStorage.removeItem("ms_session_id");
    return null;
  }
  return sessionId;
};
var setSessionId = (sessionId) => {
  if (typeof window !== "undefined") {
    window.localStorage.setItem("ms_session_id", sessionId);
  } else {
    console.warn("setSessionId: window is not defined");
  }
};
var removeSessionId = () => {
  if (typeof window !== "undefined") {
    window.localStorage.removeItem("ms_session_id");
  } else {
    console.warn("removeSessionId: window is not defined");
  }
};

// src/methods/requests/requests.ts
var createRequestHandler = ({
  publicKey,
  appId,
  token,
  customEndpoint
}) => {
  return {
    sendRequest: (data, options) => __async(void 0, null, function* () {
      var _a, _b, _c, _d, _e, _f, _g, _h;
      try {
        const { url } = data;
        const memberToken = getMemberToken();
        const sessionToken = getSessionId();
        const authHeader = [
          (_b = (_a = data.headers) == null ? void 0 : _a["Authorization"]) == null ? void 0 : _b.replace("Bearer ", ""),
          memberToken,
          options == null ? void 0 : options.token
        ].find((x) => x);
        const formattedUrl = `${customEndpoint || endpoints.API}${url}`;
        const res = yield axios({
          method: data.method,
          data: data.data,
          url: formattedUrl,
          headers: __spreadProps(__spreadValues(__spreadValues(__spreadProps(__spreadValues(__spreadValues(__spreadValues({}, authHeader && { authorization: `Bearer ${authHeader}` }), publicKey && { ["X-API-Key" /* API_KEY */]: publicKey }), appId && { ["X-APP-ID" /* APP_ID */]: appId }), {
            ["X-User-Agent" /* USER_AGENT */]: "@memberstack/client@1.2.0"
          }), data.contentType && { "Content-Type": data.contentType }), sessionToken && {
            ["X-Session-ID" /* SESSION_ID */]: sessionToken
          }), {
            "referring-path": window.location.pathname
          }),
          withCredentials: true
        });
        if ((_c = res == null ? void 0 : res.headers) == null ? void 0 : _c["ms-mid"]) {
          token = res.headers["ms-mid"];
        }
        if ((_d = res == null ? void 0 : res.data) == null ? void 0 : _d.error) {
          if (res.data.error.name === "JsonWebTokenError") {
            throw {
              code: "client/invalid-token",
              message: "An invalid token has been provided. Please make sure the token is valid."
            };
          }
          throw (_e = res.data) == null ? void 0 : _e.error;
        }
        return res == null ? void 0 : res.data;
      } catch (e) {
        if (!e.response)
          throw e;
        throw ((_g = (_f = e.response) == null ? void 0 : _f.data) == null ? void 0 : _g.error) || ((_h = e.response) == null ? void 0 : _h.data);
      }
    }),
    sendRequestWithFetch: (data, options) => __async(void 0, null, function* () {
      var _a, _b;
      try {
        const { url, method, data: bodyData, headers, contentType } = data;
        const memberToken = getMemberToken();
        const authHeader = [
          (_a = headers == null ? void 0 : headers["Authorization"]) == null ? void 0 : _a.replace("Bearer ", ""),
          memberToken,
          options == null ? void 0 : options.token
        ].find((x) => x);
        const formattedUrl = `${customEndpoint || endpoints.API}${url}`;
        const fetchHeaders = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, authHeader && { Authorization: `Bearer ${authHeader}` }), publicKey && { ["X-API-Key" /* API_KEY */]: publicKey }), appId && { ["X-APP-ID" /* APP_ID */]: appId }), {
          ["X-User-Agent" /* USER_AGENT */]: "@memberstack/client@1.2.0",
          "Content-Type": "application/json",
          Referer: window.location.href
        });
        const response = yield fetch(formattedUrl, {
          method,
          headers: fetchHeaders,
          body: bodyData ? JSON.stringify(bodyData) : void 0,
          credentials: "include",
          keepalive: true
          // Keeps the connection open for further requests
        });
        const contentTypeHeader = response.headers.get("content-type");
        let result;
        if (contentTypeHeader == null ? void 0 : contentTypeHeader.includes("application/json")) {
          result = yield response.json();
        } else if (contentTypeHeader == null ? void 0 : contentTypeHeader.includes("text")) {
          result = yield response.text();
        } else if (response.status === 204) {
          result = null;
        } else {
          result = yield response.text();
        }
        if (response.headers.get("ms-mid")) {
          token = response.headers.get("ms-mid");
        }
        if (!response.ok) {
          if (((_b = result == null ? void 0 : result.error) == null ? void 0 : _b.name) === "JsonWebTokenError") {
            throw {
              code: "client/invalid-token",
              message: "An invalid token has been provided. Please make sure the token is valid."
            };
          }
          throw (result == null ? void 0 : result.error) || result;
        }
        return result;
      } catch (e) {
        console.error("Error in sendRequestWithFetch:", e);
        throw e;
      }
    })
  };
};

// src/auth/index.ts
var createObservable = () => {
  const observer = /* @__PURE__ */ new Map();
  return {
    subscribe: (key, fn) => {
      if (typeof fn !== "function")
        return;
      return observer.set(key, fn);
    },
    unsubscribe: (key) => {
      return observer.delete(key);
    },
    notify: (data) => {
      return [...observer.values()].forEach((fn) => fn(data));
    }
  };
};
var observable = createObservable();
var getPersistedMember = () => {
  return JSON.parse(localStorage == null ? void 0 : localStorage.getItem("_ms-mem"));
};
var setPersistedMember = (member) => {
  if (member) {
    const data = JSON.stringify(member);
    if (data)
      localStorage == null ? void 0 : localStorage.setItem("_ms-mem", data);
    observable.notify(member);
  }
};
var updatePersistedMember = (member) => {
  if (member) {
    const data = JSON.stringify(member);
    if (data)
      localStorage == null ? void 0 : localStorage.setItem("_ms-mem", data);
  } else {
    localStorage == null ? void 0 : localStorage.removeItem("_ms-mem");
    removeMemberToken();
  }
};
var unsetPersistedMember = () => {
  localStorage == null ? void 0 : localStorage.removeItem("_ms-mem");
  removeMemberToken();
  removeSessionId();
  observable.notify(null);
};

// src/methods/requests/index.ts
function getSessionDurationDays(unixTimestampMillis) {
  const now = Date.now();
  const differenceMillis = unixTimestampMillis - now;
  return Math.ceil(differenceMillis / (24 * 60 * 60 * 1e3));
}
var addHeaders = (options) => __spreadValues({}, (options == null ? void 0 : options.token) && {
  Authorization: `Bearer ${options.token}`
});
var promiseResolve;
var promiseReject;
var receiveMessage = (event) => {
  var _a;
  const { data, origin } = event;
  if (API_ENDPOINT !== origin)
    return;
  if ((_a = data == null ? void 0 : data.data) == null ? void 0 : _a.member) {
    const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
    setPersistedMember(data.data.member);
    setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
  }
  if (data == null ? void 0 : data.error) {
    promiseReject(data.error);
  }
  promiseResolve(data);
};
var windowObjectReference = null;
var previousUrl = null;
var openSignInWindow = (url, name) => __async(void 0, null, function* () {
  window.removeEventListener("message", receiveMessage);
  const dualScreenLeft = window.screenLeft !== void 0 ? window.screenLeft : window.screenX;
  const dualScreenTop = window.screenTop !== void 0 ? window.screenTop : window.screenY;
  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
  const systemZoom = width / window.screen.availWidth;
  const left = (width - 600) / 2 / systemZoom + dualScreenLeft;
  const top = (height - 700) / 2 / systemZoom + dualScreenTop;
  const strWindowFeatures = `toolbar=no, menubar=no, width=${600 / systemZoom}, height=${700 / systemZoom}, top=${top}, left=${left}`;
  if (windowObjectReference === null || windowObjectReference.closed) {
    windowObjectReference = window.open(url, name, strWindowFeatures);
  } else if (previousUrl !== url) {
    windowObjectReference = window.open(url, name, strWindowFeatures);
    windowObjectReference.focus();
  } else {
    windowObjectReference.focus();
  }
  window.addEventListener("message", (event) => receiveMessage(event), false);
  previousUrl = url;
  window.addEventListener("beforeunload", () => {
    windowObjectReference == null ? void 0 : windowObjectReference.close();
  });
  return new Promise((resolve, reject) => {
    promiseResolve = resolve;
    promiseReject = reject;
  });
});
function getBrowser() {
  const userAgent = navigator.userAgent;
  if (/Edg/i.test(userAgent))
    return "EDGE";
  if (/Trident/i.test(userAgent) || /MSIE/i.test(userAgent))
    return "INTERNET_EXPLORER";
  if (/Safari/i.test(userAgent) && !/Chrome/i.test(userAgent))
    return "SAFARI";
  if (/Firefox/i.test(userAgent))
    return "FIREFOX";
  if (/Chrome/i.test(userAgent) && !/Edg/i.test(userAgent))
    return "CHROME";
  if (/OPR/i.test(userAgent) || /Opera/i.test(userAgent))
    return "OPERA";
  return "OTHER";
}
function getOS() {
  const userAgent = navigator.userAgent;
  if (/Windows/i.test(userAgent))
    return "WINDOWS";
  if (/Macintosh|Mac OS X/i.test(userAgent))
    return "MACOS";
  if (/Android/i.test(userAgent))
    return "ANDROID";
  if (/iPhone|iPad|iPod/i.test(userAgent))
    return "IOS";
  if (/Linux/i.test(userAgent))
    return "LINUX";
  return "OTHER";
}
function getScreenSize() {
  const width = window.innerWidth;
  if (width <= 768)
    return "PHONE";
  if (width <= 1024)
    return "TABLET";
  return "DESKTOP";
}
function getUTMParams() {
  const params = new URLSearchParams(window.location.search);
  const utmParams = {};
  const utmKeys = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
  utmKeys.forEach((key) => {
    if (params.has(key)) {
      utmParams[key] = params.get(key);
    }
  });
  return utmParams;
}
function getConversionData() {
  return {
    browser: getBrowser(),
    os: getOS(),
    screenSize: getScreenSize(),
    sessionId: getSessionId(),
    utmParams: getUTMParams()
  };
}
var API_ENDPOINT;
var initRequest = ({
  publicKey,
  appId,
  token,
  domain
  //sessionDurationDays
}) => {
  const { sendRequest, sendRequestWithFetch } = createRequestHandler({
    publicKey,
    token,
    customEndpoint: domain,
    appId
  });
  API_ENDPOINT = domain;
  return {
    _Event(params) {
      return __async(this, null, function* () {
        const payload = __spreadValues(__spreadValues({}, params.data), getConversionData());
        return sendRequestWithFetch({
          method: "POST" /* POST */,
          url: `/event`,
          data: payload
        });
      });
    },
    deleteMember() {
      return __async(this, null, function* () {
        const data = yield sendRequest({
          method: "DELETE" /* DELETE */,
          url: `/member`
        });
        unsetPersistedMember();
        return data;
      });
    },
    postIsTyping(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/comments/posts/typing`,
          data: {
            channelKey: params.channelKey
          }
        });
      });
    },
    getChannelInfo(params) {
      return __async(this, null, function* () {
        const queryParams = new URLSearchParams({
          channelKey: params.channelKey
        });
        return sendRequest({
          method: "GET" /* GET */,
          url: `/comments/channels/info?${queryParams}`
        });
      });
    },
    subscribeToChannel(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/comments/channels/manage-subscription`,
          data: {
            channelKey: params.channelKey,
            action: params.action
          }
        });
      });
    },
    getPosts(params) {
      return __async(this, null, function* () {
        const queryParams = new URLSearchParams(__spreadValues(__spreadValues(__spreadValues({
          channelKey: params.channelKey
        }, params.after && {
          after: params.after
        }), params.order && {
          order: params.order
        }), params.limit && {
          limit: params.limit.toString()
        }));
        return sendRequest({
          method: "GET" /* GET */,
          url: `/comments/posts?${queryParams}`
        });
      });
    },
    getThreads(params) {
      return __async(this, null, function* () {
        const queryParams = new URLSearchParams(__spreadValues(__spreadValues(__spreadValues({
          postId: params.postId
        }, params.after && {
          after: params.after
        }), params.order && {
          order: params.order
        }), params.limit && {
          limit: params.limit.toString()
        }));
        return sendRequest({
          method: "GET" /* GET */,
          url: `/comments/threads?${queryParams}`
        });
      });
    },
    createPost(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/comments/posts`,
          data: {
            channelKey: params.channelKey,
            content: params.content,
            _url: window.location.origin + window.location.pathname
          }
        });
      });
    },
    updatePost(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "PATCH" /* PATCH */,
          url: `/comments/posts/${params.postId}/update`,
          data: {
            content: params.content
          }
        });
      });
    },
    postVote(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/comments/posts/${params.postId}/vote`,
          data: {
            vote: params.vote
          }
        });
      });
    },
    deletePost(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "DELETE" /* DELETE */,
          url: `/comments/posts/${params.postId}`
        });
      });
    },
    createThread(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/comments/threads`,
          data: {
            postId: params.postId,
            content: params.content
          }
        });
      });
    },
    updateThread(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "PATCH" /* PATCH */,
          url: `/comments/threads/${params.threadId}/update`,
          data: {
            content: params.content
          }
        });
      });
    },
    // vote thread
    threadVote(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/comments/threads/${params.threadId}/vote`,
          data: {
            vote: params.vote
          }
        });
      });
    },
    deleteThread(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "DELETE" /* DELETE */,
          url: `/comments/threads/${params.threadId}`
        });
      });
    },
    getSecureContent(params) {
      return __async(this, null, function* () {
        const data = yield sendRequest({
          method: "POST" /* POST */,
          url: "/secure-content",
          data: {
            contentId: params.contentId
          }
        });
        return data;
      });
    },
    signupWithProvider(params) {
      return __async(this, null, function* () {
        const customFields = encodeURIComponent(params.customFields ? JSON.stringify(params.customFields) : "{}");
        const plans = encodeURIComponent(params.plans ? JSON.stringify(params.plans) : "[]");
        const conversionData = getConversionData();
        const queryParams = new URLSearchParams(__spreadProps(__spreadValues({
          provider: params.provider,
          customFields,
          plans,
          appId
        }, publicKey && {
          publicKey
        }), {
          url: window.location.pathname,
          origin: window.location.hostname,
          sessionId: conversionData.sessionId,
          browser: conversionData.browser,
          os: conversionData.os,
          screenSize: conversionData.screenSize
        }));
        return openSignInWindow(`${domain}/auth-provider/signup?${queryParams}`, "signup");
      });
    },
    loginWithProvider(params) {
      return __async(this, null, function* () {
        const allowSignup = encodeURIComponent(params.allowSignup === true ? true : false);
        const queryParams = new URLSearchParams(__spreadProps(__spreadValues({
          provider: params.provider,
          appId
        }, publicKey && {
          publicKey
        }), {
          origin: window.location.hostname,
          allowSignup
        }));
        return openSignInWindow(`${domain}/auth-provider/login?${queryParams}`, "login");
      });
    },
    connectProvider(params) {
      return __async(this, null, function* () {
        const queryParams = new URLSearchParams(__spreadProps(__spreadValues({
          provider: params.provider,
          appId
        }, publicKey && {
          publicKey
        }), {
          member: getMemberToken(),
          origin: window.location.hostname
        }));
        return openSignInWindow(`${domain}/auth-provider/connect?${queryParams}`, "connect");
      });
    },
    disconnectProvider(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: "/member/disconnect-provider",
          data: {
            provider: params.provider
          }
        });
      });
    },
    getAppAndMember(params) {
      return __async(this, null, function* () {
        var _a2, _b;
        const data = yield sendRequest({
          method: "POST" /* POST */,
          url: `/app-member`,
          data: {
            email: params.email,
            password: params.password,
            data: {
              // @ts-ignore
              includeSSOText: window == null ? void 0 : window.ssoUI,
              trackPageView: params == null ? void 0 : params.trackPageView,
              sessionData: __spreadValues({}, getConversionData())
            }
          }
        });
        try {
          const backendSessionId = (_b = (_a2 = data.data) == null ? void 0 : _a2.sessionData) == null ? void 0 : _b.sessionId;
          const storedSessionId = getSessionId();
          if (storedSessionId !== backendSessionId)
            setSessionId(backendSessionId);
        } catch (e) {
        }
        return data;
      });
    },
    getApp() {
      return __async(this, null, function* () {
        const queryParams = new URLSearchParams({
          // @ts-ignore
          includeSSOText: window == null ? void 0 : window.ssoUI
        });
        return sendRequest({
          method: "GET" /* GET */,
          url: `/app?${queryParams}`
        });
      });
    },
    loginMemberEmailPassword(params, options) {
      return __async(this, null, function* () {
        const data = yield sendRequest({
          method: "POST" /* POST */,
          url: `/auth/login`,
          data: {
            email: params.email,
            password: params.password,
            options
          }
        });
        const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
        setPersistedMember(data.data.member);
        setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
        return data;
      });
    },
    sendMemberLoginPasswordlessEmail(params, options) {
      return __async(this, null, function* () {
        return yield sendRequest({
          method: "POST" /* POST */,
          url: `/auth/passwordless/login/send`,
          data: {
            email: params.email
          }
        });
      });
    },
    sendMemberSignupPasswordlessEmail(params, options) {
      return __async(this, null, function* () {
        return yield sendRequest({
          method: "POST" /* POST */,
          url: `/auth/passwordless/signup/send`,
          data: {
            email: params.email
          }
        });
      });
    },
    loginMemberPasswordless(params, options) {
      return __async(this, null, function* () {
        const data = yield sendRequest({
          method: "POST" /* POST */,
          url: `/auth/passwordless/login`,
          data: {
            passwordlessToken: params.passwordlessToken,
            email: params.email,
            options
          }
        });
        const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
        setPersistedMember(data.data.member);
        setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
        return data;
      });
    },
    getPlan(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "GET" /* GET */,
          url: `/app/plans/${params.planId}`
        });
      });
    },
    getPlans() {
      return __async(this, null, function* () {
        const { data } = yield sendRequest({
          method: "GET" /* GET */,
          url: `/app`
        });
        return {
          data: data.plans
        };
      });
    },
    getRestrictedUrlGroups() {
      return __async(this, null, function* () {
        const { data } = yield sendRequest({
          method: "GET" /* GET */,
          url: `/app`
        });
        return {
          data: data.contentGroups
        };
      });
    },
    getCurrentMember(options) {
      return __async(this, null, function* () {
        const memberToken = getMemberToken();
        if (!memberToken)
          return { data: null };
        const getMemberRequest = sendRequest({
          method: "GET" /* GET */,
          url: `/member`,
          headers: addHeaders(options)
        });
        function setMember() {
          return __async(this, null, function* () {
            const data = yield getMemberRequest;
            updatePersistedMember(data.data);
          });
        }
        setMember();
        if ((options == null ? void 0 : options.useCache) === true) {
          const member = getPersistedMember();
          return { data: member };
        } else {
          return getMemberRequest;
        }
      });
    },
    getMemberJSON(options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "GET" /* GET */,
          url: `/member/json`,
          headers: addHeaders(options)
        });
      });
    },
    updateMemberJSON(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member/json`,
          data: {
            json: params.json
          },
          headers: addHeaders(options)
        });
      });
    },
    addPlan(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member/plans/add`,
          data: {
            planId: params.planId
          },
          headers: addHeaders(options)
        });
      });
    },
    purchasePlansWithCheckout(params, options) {
      return __async(this, null, function* () {
        function getRedirectURL(URL) {
          let redirectUrl = window.location.href;
          const urlParam = URL;
          if (urlParam) {
            if (urlParam.indexOf("http://") === 0 || urlParam.indexOf("https://") === 0) {
              redirectUrl = urlParam;
            } else {
              redirectUrl = window.location.origin + urlParam;
            }
          }
          return redirectUrl;
        }
        const success_url = params.successUrl ? getRedirectURL(params.successUrl) : void 0;
        const cancel_url = getRedirectURL(params.cancelUrl);
        const request = yield sendRequest({
          method: "POST" /* POST */,
          url: `/member/plans/create-checkout-session`,
          data: {
            priceId: params.priceId,
            couponId: params.couponId,
            metadataForCheckout: params.metadataForCheckout,
            //window.location requires dom
            success_url,
            cancel_url,
            origin_url: window.location.href,
            conversionData: __spreadValues({
              url: window.location.pathname
            }, getConversionData())
          },
          headers: addHeaders(options)
        });
        if (params.autoRedirect === false) {
          return request;
        }
        window.location.href = request.data.url;
      });
    },
    // used for plan updates
    launchStripeCustomerPortal(params, options) {
      return __async(this, null, function* () {
        function getRedirectURL(URL) {
          let redirectUrl = window.location.href;
          const urlParam = URL;
          if (urlParam) {
            if (urlParam.indexOf("http://") === 0 || urlParam.indexOf("https://") === 0) {
              redirectUrl = urlParam;
            } else {
              redirectUrl = window.location.origin + urlParam;
            }
          }
          return redirectUrl;
        }
        const returnUrl = (params == null ? void 0 : params.returnUrl) ? getRedirectURL(params.returnUrl) : void 0;
        const request = yield sendRequest({
          method: "POST" /* POST */,
          url: `/member/create-billing-portal-session`,
          data: __spreadValues({
            //window.location requires dom
            return_url: returnUrl,
            origin_url: window.location.href
          }, params && {
            priceIds: params.priceIds,
            configuration: params.configuration
          }),
          headers: addHeaders(options)
        });
        if ((params == null ? void 0 : params.autoRedirect) === false) {
          return request;
        }
        window.location.href = request.data.url;
      });
    },
    removePlan(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member/plans/remove`,
          data: {
            planId: params.planId
          },
          headers: addHeaders(options)
        });
      });
    },
    updateMember(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member`,
          data: __spreadValues({}, params.customFields && { customFields: params.customFields }),
          headers: addHeaders(options)
        });
      });
    },
    updateMemberAuth(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member-auth`,
          data: __spreadValues(__spreadValues(__spreadValues({}, params.email && { email: params.email }), params.oldPassword && { oldPassword: params.oldPassword }), params.newPassword && { newPassword: params.newPassword }),
          headers: addHeaders(options)
        });
      });
    },
    setPassword(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member/set-password`,
          data: {
            password: params.password
          },
          headers: addHeaders(options)
        });
      });
    },
    signupMemberPasswordless(params, options) {
      return __async(this, null, function* () {
        var _a2, _b, _c;
        const data = yield sendRequest({
          method: "POST" /* POST */,
          url: `/auth/signup?isPasswordless=true`,
          data: __spreadValues(__spreadProps(__spreadValues({
            email: params.email,
            customFields: params.customFields,
            passwordlessToken: params.passwordlessToken,
            metaData: params.metaData
          }, params.plans && { plans: params.plans }), {
            //internal use only
            origin_domain: window.location.origin,
            conversionData: __spreadValues(__spreadProps(__spreadValues({}, (_a2 = params == null ? void 0 : params.conversionData) != null ? _a2 : {}), {
              url: window.location.pathname
            }), getConversionData()),
            options
          }), ((_b = window.Rewardful) == null ? void 0 : _b.referral) && {
            rewardfulData: {
              // @ts-ignore
              referral: window.Rewardful.referral,
              // @ts-ignore
              coupon: (_c = window.Rewardful.coupon) == null ? void 0 : _c.id
            }
          })
        });
        const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
        setPersistedMember(data.data.member);
        setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
        return data;
      });
    },
    signupMemberEmailPassword(params, options) {
      return __async(this, null, function* () {
        var _a2, _b, _c;
        const data = yield sendRequest({
          method: "POST" /* POST */,
          url: `/auth/signup`,
          data: __spreadValues(__spreadProps(__spreadValues({
            email: params.email,
            password: params.password,
            customFields: params.customFields,
            metaData: params.metaData,
            captchaToken: params.captchaToken,
            inviteToken: params.inviteToken
          }, params.plans && { plans: params.plans }), {
            //internal use only
            origin_domain: window.location.origin,
            conversionData: __spreadValues(__spreadProps(__spreadValues({}, (_a2 = params == null ? void 0 : params.conversionData) != null ? _a2 : {}), {
              url: window.location.pathname
            }), getConversionData()),
            options
          }), ((_b = window.Rewardful) == null ? void 0 : _b.referral) && {
            rewardfulData: {
              // @ts-ignore
              referral: window.Rewardful.referral,
              // @ts-ignore
              coupon: (_c = window.Rewardful.coupon) == null ? void 0 : _c.id
            }
          })
        });
        const sessionDurationDays = getSessionDurationDays(data.data.tokens.expires);
        setPersistedMember(data.data.member);
        setMemberToken(data.data.tokens.accessToken, sessionDurationDays);
        return data;
      });
    },
    joinTeam(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member/team/join`,
          data: {
            inviteToken: params.inviteToken
          },
          headers: addHeaders(options)
        });
      });
    },
    getTeam(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "GET" /* GET */,
          url: `/member/team/${params.teamId}`,
          headers: addHeaders(options)
        });
      });
    },
    removeMemberFromTeam(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member/team/remove-member`,
          data: {
            teamId: params.teamId,
            memberId: params.memberId
          },
          headers: addHeaders(options)
        });
      });
    },
    generateInviteToken(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/member/team/generate-invite-link`,
          data: {
            teamId: params.teamId
          },
          headers: addHeaders(options)
        });
      });
    },
    updateMemberProfileImage(params) {
      return __async(this, null, function* () {
        if (params.profileImage) {
          const formData = new FormData();
          formData.append("profileImage", params.profileImage);
          return sendRequest({
            method: "POST" /* POST */,
            url: `/member/profile-image`,
            data: formData,
            contentType: "multipart/form-data"
          });
        }
      });
    },
    sendMemberVerificationEmail() {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/auth/send-email-verification`,
          data: {
            //internal use only
            origin_domain: window.location.origin
          }
        });
      });
    },
    sendMemberResetPasswordEmail(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/auth/send-reset-password-email`,
          data: {
            email: params.email
          }
        });
      });
    },
    resetMemberPassword(params) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/auth/reset-password`,
          data: {
            token: params.token,
            newPassword: params.newPassword
          }
        });
      });
    },
    logout(options) {
      return __async(this, null, function* () {
        const data = yield sendRequest({
          method: "POST" /* POST */,
          url: `/member/logout`,
          headers: addHeaders(options)
        });
        unsetPersistedMember();
        return data;
      });
    },
    // Data Tables Methods
    getDataTables(options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "GET" /* GET */,
          url: `/v1/data-tables`,
          headers: addHeaders(options)
        });
      });
    },
    getDataTable(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "GET" /* GET */,
          url: `/v1/data-tables/${params.tableKey}`,
          headers: addHeaders(options)
        });
      });
    },
    getDataRecords(params, options) {
      return __async(this, null, function* () {
        var _a2;
        const query = {};
        if (params.createdAfter || params.createdBefore) {
          query.where = {
            createdAt: __spreadValues(__spreadValues({}, params.createdAfter && { gte: params.createdAfter }), params.createdBefore && { lte: params.createdBefore })
          };
        }
        if (params.sortBy) {
          query.orderBy = {
            [params.sortBy]: params.sortDirection || "asc"
          };
        }
        if (params.limit) {
          query.take = params.limit;
        }
        if (params.after) {
          query.after = params.after;
        }
        const res = yield sendRequest({
          method: "POST" /* POST */,
          url: `/v1/data-records/query`,
          data: {
            table: params.tableKey,
            query: {
              findMany: query
            }
          },
          headers: addHeaders(options)
        });
        if ((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.records) {
          return {
            data: __spreadValues({
              records: res.data.records
            }, res.data.pagination && { pagination: res.data.pagination })
          };
        }
        return res;
      });
    },
    createDataRecord(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/v1/data-records`,
          data: __spreadValues({
            table: params.table,
            data: params.data
          }, params.memberId && { memberId: params.memberId }),
          headers: addHeaders(options)
        });
      });
    },
    getDataRecord(params, options) {
      return __async(this, null, function* () {
        var _a2;
        const res = yield sendRequest({
          method: "POST" /* POST */,
          url: `/v1/data-records/query`,
          data: {
            table: params.table,
            query: {
              findUnique: {
                where: { id: params.recordId }
              }
            }
          },
          headers: addHeaders(options)
        });
        if ((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.record) {
          return { data: res.data.record };
        }
        return res;
      });
    },
    updateDataRecord(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "PUT" /* PUT */,
          url: `/v1/data-records/${params.recordId}`,
          data: {
            data: params.data
          },
          headers: addHeaders(options)
        });
      });
    },
    deleteDataRecord(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "DELETE" /* DELETE */,
          url: `/v1/data-records/${params.recordId}`,
          headers: addHeaders(options)
        });
      });
    },
    queryDataRecords(params, options) {
      return __async(this, null, function* () {
        return sendRequest({
          method: "POST" /* POST */,
          url: `/v1/data-records/query`,
          data: {
            table: params.table,
            query: {
              findMany: params.query
            }
          },
          headers: addHeaders(options)
        });
      });
    }
  };
};
export {
  getSessionDurationDays,
  initRequest
};
