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

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