UNPKG

@visitorquery/react

Version:

Use this package to prevent fraud and abuse by visitors hiding behind proxies and VPNs. With a simple call to `useVisitorQuery` your website or app will be making a request to our servers which will store a value indicating wether the current user is beh

86 lines (85 loc) 2.31 kB
import * as l from "react"; import f, { createContext as v, useState as y, useEffect as E, useMemo as S, useContext as w } from "react"; function V(t, a = {}) { const [i, r] = l.useState("loading"), d = l.useRef(a); return l.useEffect(() => { let e = document.querySelector(`script[src="${t}"]`); const n = e == null ? void 0 : e.getAttribute("data-status"); if (n) { r(n); return; } if (e === null) { e = document.createElement("script"), e.src = t, e.async = !0, e.setAttribute("data-status", "loading"), document.body.appendChild(e); const s = () => { e == null || e.setAttribute("data-status", "ready"), r("ready"), u(); }, o = () => { e == null || e.setAttribute("data-status", "error"), r("error"), u(); }, u = () => { e == null || e.removeEventListener("load", s), e == null || e.removeEventListener("error", o); }; e.addEventListener("load", s), e.addEventListener("error", o); const c = d.current.removeOnUnmount; return () => { c === !0 && (e == null || e.remove(), u()); }; } else r("unknown"); }, [t]), i; } const m = v(null); function L({ apiKey: t, sessionId: a, endpoint: i, children: r, trigger: d }) { const e = "main.check.visitorquery.com", n = V("https://cdn.visitorquery.com/visitorquery.js", { removeOnUnmount: !1 }), [s, o] = y({ started: !1, ended: !1 }); E(() => { typeof window.VisitorQuery < "u" && window.VisitorQuery.run({ ApiKey: t, Endpoint: i || e, SessionId: a, onOpen: () => { o({ started: !0, ended: !1 }); }, onClose: () => { o({ started: !0, ended: !0 }); }, onError: (c) => { o({ started: !0, ended: !0, errored: !0 }), console.error(c); } }); }, [t, i, a, n, d]); const u = S(() => ({ ...s, isLoading: n === "loading" }), [s, n]); return /* @__PURE__ */ f.createElement(m.Provider, { value: u }, r); } function Q() { const t = w(m); if (!t) throw new Error("useVisitorQuery must be used within a VisitorQueryProvider"); return t; } export { L as VisitorQueryProvider, Q as useVisitorQuery };